{"text":"<commit_before>package consensus\n\nimport (\n\t\"bytes\"\n\t\"crypto\/rand\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\/\/ \"sync\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/tendermint\/tendermint\/consensus\/types\"\n\t\"github.com\/tendermint\/tendermint\/libs\/autofile\"\n\t\"github.com\/tendermint\/tendermint\/libs\/log\"\n\ttmtypes \"github.com\/tendermint\/tendermint\/types\"\n\ttmtime \"github.com\/tendermint\/tendermint\/types\/time\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"github.com\/stretchr\/testify\/require\"\n)\n\nconst (\n\twalTestFlushInterval = time.Duration(100) * time.Millisecond\n)\n\nfunc TestWALTruncate(t *testing.T) {\n\twalDir, err := ioutil.TempDir(\"\", \"wal\")\n\trequire.NoError(t, err)\n\tdefer os.RemoveAll(walDir)\n\n\twalFile := filepath.Join(walDir, \"wal\")\n\n\t\/\/this magic number 4K can truncate the content when RotateFile. defaultHeadSizeLimit(10M) is hard to simulate.\n\t\/\/this magic number 1 * time.Millisecond make RotateFile check frequently. defaultGroupCheckDuration(5s) is hard to simulate.\n\twal, err := NewWAL(walFile,\n\t\tautofile.GroupHeadSizeLimit(4096),\n\t\tautofile.GroupCheckDuration(1*time.Millisecond),\n\t)\n\trequire.NoError(t, err)\n\twal.SetLogger(log.TestingLogger())\n\terr = wal.Start()\n\trequire.NoError(t, err)\n\tdefer func() {\n\t\twal.Stop()\n\t\t\/\/ wait for the wal to finish shutting down so we\n\t\t\/\/ can safely remove the directory\n\t\twal.Wait()\n\t}()\n\n\t\/\/60 block's size nearly 70K, greater than group's headBuf size(4096 * 10), when headBuf is full, truncate content will Flush to the file.\n\t\/\/at this time, RotateFile is called, truncate content exist in each file.\n\terr = WALGenerateNBlocks(t, wal.Group(), 60)\n\trequire.NoError(t, err)\n\n\ttime.Sleep(1 * time.Millisecond) \/\/wait groupCheckDuration, make sure RotateFile run\n\n\twal.Group().Flush()\n\n\th := int64(50)\n\tgr, found, err := wal.SearchForEndHeight(h, &WALSearchOptions{})\n\tassert.NoError(t, err, \"expected not to err on height %d\", h)\n\tassert.True(t, found, \"expected to find end height for %d\", h)\n\tassert.NotNil(t, gr)\n\tdefer gr.Close()\n\n\tdec := NewWALDecoder(gr)\n\tmsg, err := dec.Decode()\n\tassert.NoError(t, err, \"expected to decode a message\")\n\trs, ok := msg.Msg.(tmtypes.EventDataRoundState)\n\tassert.True(t, ok, \"expected message of type EventDataRoundState\")\n\tassert.Equal(t, rs.Height, h+1, \"wrong height\")\n}\n\nfunc TestWALEncoderDecoder(t *testing.T) {\n\tnow := tmtime.Now()\n\tmsgs := []TimedWALMessage{\n\t\t{Time: now, Msg: EndHeightMessage{0}},\n\t\t{Time: now, Msg: timeoutInfo{Duration: time.Second, Height: 1, Round: 1, Step: types.RoundStepPropose}},\n\t}\n\n\tb := new(bytes.Buffer)\n\n\tfor _, msg := range msgs {\n\t\tb.Reset()\n\n\t\tenc := NewWALEncoder(b)\n\t\terr := enc.Encode(&msg)\n\t\trequire.NoError(t, err)\n\n\t\tdec := NewWALDecoder(b)\n\t\tdecoded, err := dec.Decode()\n\t\trequire.NoError(t, err)\n\n\t\tassert.Equal(t, msg.Time.UTC(), decoded.Time)\n\t\tassert.Equal(t, msg.Msg, decoded.Msg)\n\t}\n}\n\nfunc TestWALWritePanicsIfMsgIsTooBig(t *testing.T) {\n\twalDir, err := ioutil.TempDir(\"\", \"wal\")\n\trequire.NoError(t, err)\n\tdefer os.RemoveAll(walDir)\n\twalFile := filepath.Join(walDir, \"wal\")\n\n\twal, err := NewWAL(walFile)\n\trequire.NoError(t, err)\n\terr = wal.Start()\n\trequire.NoError(t, err)\n\tdefer func() {\n\t\twal.Stop()\n\t\t\/\/ wait for the wal to finish shutting down so we\n\t\t\/\/ can safely remove the directory\n\t\twal.Wait()\n\t}()\n\n\tassert.Panics(t, func() { wal.Write(make([]byte, maxMsgSizeBytes+1)) })\n}\n\nfunc TestWALSearchForEndHeight(t *testing.T) {\n\twalBody, err := WALWithNBlocks(t, 6)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\twalFile := tempWALWithData(walBody)\n\n\twal, err := NewWAL(walFile)\n\trequire.NoError(t, err)\n\twal.SetLogger(log.TestingLogger())\n\n\th := int64(3)\n\tgr, found, err := wal.SearchForEndHeight(h, &WALSearchOptions{})\n\tassert.NoError(t, err, \"expected not to err on height %d\", h)\n\tassert.True(t, found, \"expected to find end height for %d\", h)\n\tassert.NotNil(t, gr)\n\tdefer gr.Close()\n\n\tdec := NewWALDecoder(gr)\n\tmsg, err := dec.Decode()\n\tassert.NoError(t, err, \"expected to decode a message\")\n\trs, ok := msg.Msg.(tmtypes.EventDataRoundState)\n\tassert.True(t, ok, \"expected message of type EventDataRoundState\")\n\tassert.Equal(t, rs.Height, h+1, \"wrong height\")\n}\n\nfunc TestWALPeriodicSync(t *testing.T) {\n\twalDir, err := ioutil.TempDir(\"\", \"wal\")\n\trequire.NoError(t, err)\n\tdefer os.RemoveAll(walDir)\n\n\twalFile := filepath.Join(walDir, \"wal\")\n\twal, err := NewWAL(walFile, autofile.GroupCheckDuration(1*time.Millisecond))\n\trequire.NoError(t, err)\n\n\twal.SetFlushInterval(walTestFlushInterval)\n\twal.SetLogger(log.TestingLogger())\n\n\trequire.NoError(t, wal.Start())\n\tdefer func() {\n\t\twal.Stop()\n\t\twal.Wait()\n\t}()\n\n\terr = WALGenerateNBlocks(t, wal.Group(), 5)\n\trequire.NoError(t, err)\n\n\t\/\/ We should have data in the buffer now\n\tassert.NotZero(t, wal.Group().Buffered())\n\n\ttime.Sleep(walTestFlushInterval + (10 * time.Millisecond))\n\n\t\/\/ The data should have been flushed by the periodic sync\n\tassert.Zero(t, wal.Group().Buffered())\n\n\th := int64(4)\n\tgr, found, err := wal.SearchForEndHeight(h, &WALSearchOptions{})\n\tassert.NoError(t, err, \"expected not to err on height %d\", h)\n\tassert.True(t, found, \"expected to find end height for %d\", h)\n\tassert.NotNil(t, gr)\n\tif gr != nil {\n\t\tgr.Close()\n\t}\n}\n\n\/*\nvar initOnce sync.Once\n\nfunc registerInterfacesOnce() {\n\tinitOnce.Do(func() {\n\t\tvar _ = wire.RegisterInterface(\n\t\t\tstruct{ WALMessage }{},\n\t\t\twire.ConcreteType{[]byte{}, 0x10},\n\t\t)\n\t})\n}\n*\/\n\nfunc nBytes(n int) []byte {\n\tbuf := make([]byte, n)\n\tn, _ = rand.Read(buf)\n\treturn buf[:n]\n}\n\nfunc benchmarkWalDecode(b *testing.B, n int) {\n\t\/\/ registerInterfacesOnce()\n\n\tbuf := new(bytes.Buffer)\n\tenc := NewWALEncoder(buf)\n\n\tdata := nBytes(n)\n\tenc.Encode(&TimedWALMessage{Msg: data, Time: time.Now().Round(time.Second).UTC()})\n\n\tencoded := buf.Bytes()\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tbuf.Reset()\n\t\tbuf.Write(encoded)\n\t\tdec := NewWALDecoder(buf)\n\t\tif _, err := dec.Decode(); err != nil {\n\t\t\tb.Fatal(err)\n\t\t}\n\t}\n\tb.ReportAllocs()\n}\n\nfunc BenchmarkWalDecode512B(b *testing.B) {\n\tbenchmarkWalDecode(b, 512)\n}\n\nfunc BenchmarkWalDecode10KB(b *testing.B) {\n\tbenchmarkWalDecode(b, 10*1024)\n}\nfunc BenchmarkWalDecode100KB(b *testing.B) {\n\tbenchmarkWalDecode(b, 100*1024)\n}\nfunc BenchmarkWalDecode1MB(b *testing.B) {\n\tbenchmarkWalDecode(b, 1024*1024)\n}\nfunc BenchmarkWalDecode10MB(b *testing.B) {\n\tbenchmarkWalDecode(b, 10*1024*1024)\n}\nfunc BenchmarkWalDecode100MB(b *testing.B) {\n\tbenchmarkWalDecode(b, 100*1024*1024)\n}\nfunc BenchmarkWalDecode1GB(b *testing.B) {\n\tbenchmarkWalDecode(b, 1024*1024*1024)\n}\n<commit_msg>fix TestWALPeriodicSync (#3342)<commit_after>package consensus\n\nimport (\n\t\"bytes\"\n\t\"crypto\/rand\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\/\/ \"sync\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/tendermint\/tendermint\/consensus\/types\"\n\t\"github.com\/tendermint\/tendermint\/libs\/autofile\"\n\t\"github.com\/tendermint\/tendermint\/libs\/log\"\n\ttmtypes \"github.com\/tendermint\/tendermint\/types\"\n\ttmtime \"github.com\/tendermint\/tendermint\/types\/time\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"github.com\/stretchr\/testify\/require\"\n)\n\nconst (\n\twalTestFlushInterval = time.Duration(100) * time.Millisecond\n)\n\nfunc TestWALTruncate(t *testing.T) {\n\twalDir, err := ioutil.TempDir(\"\", \"wal\")\n\trequire.NoError(t, err)\n\tdefer os.RemoveAll(walDir)\n\n\twalFile := filepath.Join(walDir, \"wal\")\n\n\t\/\/this magic number 4K can truncate the content when RotateFile. defaultHeadSizeLimit(10M) is hard to simulate.\n\t\/\/this magic number 1 * time.Millisecond make RotateFile check frequently. defaultGroupCheckDuration(5s) is hard to simulate.\n\twal, err := NewWAL(walFile,\n\t\tautofile.GroupHeadSizeLimit(4096),\n\t\tautofile.GroupCheckDuration(1*time.Millisecond),\n\t)\n\trequire.NoError(t, err)\n\twal.SetLogger(log.TestingLogger())\n\terr = wal.Start()\n\trequire.NoError(t, err)\n\tdefer func() {\n\t\twal.Stop()\n\t\t\/\/ wait for the wal to finish shutting down so we\n\t\t\/\/ can safely remove the directory\n\t\twal.Wait()\n\t}()\n\n\t\/\/60 block's size nearly 70K, greater than group's headBuf size(4096 * 10), when headBuf is full, truncate content will Flush to the file.\n\t\/\/at this time, RotateFile is called, truncate content exist in each file.\n\terr = WALGenerateNBlocks(t, wal.Group(), 60)\n\trequire.NoError(t, err)\n\n\ttime.Sleep(1 * time.Millisecond) \/\/wait groupCheckDuration, make sure RotateFile run\n\n\twal.Group().Flush()\n\n\th := int64(50)\n\tgr, found, err := wal.SearchForEndHeight(h, &WALSearchOptions{})\n\tassert.NoError(t, err, \"expected not to err on height %d\", h)\n\tassert.True(t, found, \"expected to find end height for %d\", h)\n\tassert.NotNil(t, gr)\n\tdefer gr.Close()\n\n\tdec := NewWALDecoder(gr)\n\tmsg, err := dec.Decode()\n\tassert.NoError(t, err, \"expected to decode a message\")\n\trs, ok := msg.Msg.(tmtypes.EventDataRoundState)\n\tassert.True(t, ok, \"expected message of type EventDataRoundState\")\n\tassert.Equal(t, rs.Height, h+1, \"wrong height\")\n}\n\nfunc TestWALEncoderDecoder(t *testing.T) {\n\tnow := tmtime.Now()\n\tmsgs := []TimedWALMessage{\n\t\t{Time: now, Msg: EndHeightMessage{0}},\n\t\t{Time: now, Msg: timeoutInfo{Duration: time.Second, Height: 1, Round: 1, Step: types.RoundStepPropose}},\n\t}\n\n\tb := new(bytes.Buffer)\n\n\tfor _, msg := range msgs {\n\t\tb.Reset()\n\n\t\tenc := NewWALEncoder(b)\n\t\terr := enc.Encode(&msg)\n\t\trequire.NoError(t, err)\n\n\t\tdec := NewWALDecoder(b)\n\t\tdecoded, err := dec.Decode()\n\t\trequire.NoError(t, err)\n\n\t\tassert.Equal(t, msg.Time.UTC(), decoded.Time)\n\t\tassert.Equal(t, msg.Msg, decoded.Msg)\n\t}\n}\n\nfunc TestWALWritePanicsIfMsgIsTooBig(t *testing.T) {\n\twalDir, err := ioutil.TempDir(\"\", \"wal\")\n\trequire.NoError(t, err)\n\tdefer os.RemoveAll(walDir)\n\twalFile := filepath.Join(walDir, \"wal\")\n\n\twal, err := NewWAL(walFile)\n\trequire.NoError(t, err)\n\terr = wal.Start()\n\trequire.NoError(t, err)\n\tdefer func() {\n\t\twal.Stop()\n\t\t\/\/ wait for the wal to finish shutting down so we\n\t\t\/\/ can safely remove the directory\n\t\twal.Wait()\n\t}()\n\n\tassert.Panics(t, func() { wal.Write(make([]byte, maxMsgSizeBytes+1)) })\n}\n\nfunc TestWALSearchForEndHeight(t *testing.T) {\n\twalBody, err := WALWithNBlocks(t, 6)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\twalFile := tempWALWithData(walBody)\n\n\twal, err := NewWAL(walFile)\n\trequire.NoError(t, err)\n\twal.SetLogger(log.TestingLogger())\n\n\th := int64(3)\n\tgr, found, err := wal.SearchForEndHeight(h, &WALSearchOptions{})\n\tassert.NoError(t, err, \"expected not to err on height %d\", h)\n\tassert.True(t, found, \"expected to find end height for %d\", h)\n\tassert.NotNil(t, gr)\n\tdefer gr.Close()\n\n\tdec := NewWALDecoder(gr)\n\tmsg, err := dec.Decode()\n\tassert.NoError(t, err, \"expected to decode a message\")\n\trs, ok := msg.Msg.(tmtypes.EventDataRoundState)\n\tassert.True(t, ok, \"expected message of type EventDataRoundState\")\n\tassert.Equal(t, rs.Height, h+1, \"wrong height\")\n}\n\nfunc TestWALPeriodicSync(t *testing.T) {\n\twalDir, err := ioutil.TempDir(\"\", \"wal\")\n\trequire.NoError(t, err)\n\tdefer os.RemoveAll(walDir)\n\n\twalFile := filepath.Join(walDir, \"wal\")\n\twal, err := NewWAL(walFile, autofile.GroupCheckDuration(1*time.Millisecond))\n\trequire.NoError(t, err)\n\n\twal.SetFlushInterval(walTestFlushInterval)\n\twal.SetLogger(log.TestingLogger())\n\n\t\/\/ Generate some data\n\terr = WALGenerateNBlocks(t, wal.Group(), 5)\n\trequire.NoError(t, err)\n\n\t\/\/ We should have data in the buffer now\n\tassert.NotZero(t, wal.Group().Buffered())\n\n\trequire.NoError(t, wal.Start())\n\tdefer func() {\n\t\twal.Stop()\n\t\twal.Wait()\n\t}()\n\n\ttime.Sleep(walTestFlushInterval + (10 * time.Millisecond))\n\n\t\/\/ The data should have been flushed by the periodic sync\n\tassert.Zero(t, wal.Group().Buffered())\n\n\th := int64(4)\n\tgr, found, err := wal.SearchForEndHeight(h, &WALSearchOptions{})\n\tassert.NoError(t, err, \"expected not to err on height %d\", h)\n\tassert.True(t, found, \"expected to find end height for %d\", h)\n\tassert.NotNil(t, gr)\n\tif gr != nil {\n\t\tgr.Close()\n\t}\n}\n\n\/*\nvar initOnce sync.Once\n\nfunc registerInterfacesOnce() {\n\tinitOnce.Do(func() {\n\t\tvar _ = wire.RegisterInterface(\n\t\t\tstruct{ WALMessage }{},\n\t\t\twire.ConcreteType{[]byte{}, 0x10},\n\t\t)\n\t})\n}\n*\/\n\nfunc nBytes(n int) []byte {\n\tbuf := make([]byte, n)\n\tn, _ = rand.Read(buf)\n\treturn buf[:n]\n}\n\nfunc benchmarkWalDecode(b *testing.B, n int) {\n\t\/\/ registerInterfacesOnce()\n\n\tbuf := new(bytes.Buffer)\n\tenc := NewWALEncoder(buf)\n\n\tdata := nBytes(n)\n\tenc.Encode(&TimedWALMessage{Msg: data, Time: time.Now().Round(time.Second).UTC()})\n\n\tencoded := buf.Bytes()\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tbuf.Reset()\n\t\tbuf.Write(encoded)\n\t\tdec := NewWALDecoder(buf)\n\t\tif _, err := dec.Decode(); err != nil {\n\t\t\tb.Fatal(err)\n\t\t}\n\t}\n\tb.ReportAllocs()\n}\n\nfunc BenchmarkWalDecode512B(b *testing.B) {\n\tbenchmarkWalDecode(b, 512)\n}\n\nfunc BenchmarkWalDecode10KB(b *testing.B) {\n\tbenchmarkWalDecode(b, 10*1024)\n}\nfunc BenchmarkWalDecode100KB(b *testing.B) {\n\tbenchmarkWalDecode(b, 100*1024)\n}\nfunc BenchmarkWalDecode1MB(b *testing.B) {\n\tbenchmarkWalDecode(b, 1024*1024)\n}\nfunc BenchmarkWalDecode10MB(b *testing.B) {\n\tbenchmarkWalDecode(b, 10*1024*1024)\n}\nfunc BenchmarkWalDecode100MB(b *testing.B) {\n\tbenchmarkWalDecode(b, 100*1024*1024)\n}\nfunc BenchmarkWalDecode1GB(b *testing.B) {\n\tbenchmarkWalDecode(b, 1024*1024*1024)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build autopilotrpc\n\npackage main\n\nimport (\n\t\"context\"\n\n\t\"github.com\/lightningnetwork\/lnd\/lnrpc\/autopilotrpc\"\n\t\"github.com\/urfave\/cli\"\n)\n\nfunc getAutopilotClient(ctx *cli.Context) (autopilotrpc.AutopilotClient, func()) {\n\tconn := getClientConn(ctx, false)\n\n\tcleanUp := func() {\n\t\tconn.Close()\n\t}\n\n\treturn autopilotrpc.NewAutopilotClient(conn), cleanUp\n}\n\nvar getStatusCommand = cli.Command{\n\tName:        \"status\",\n\tUsage:       \"Get the active status of autopilot.\",\n\tDescription: \"\",\n\tAction:      actionDecorator(getStatus),\n}\n\nfunc getStatus(ctx *cli.Context) error {\n\tctxb := context.Background()\n\tclient, cleanUp := getAutopilotClient(ctx)\n\tdefer cleanUp()\n\n\treq := &autopilotrpc.StatusRequest{}\n\n\tresp, err := client.Status(ctxb, req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tprintRespJSON(resp)\n\treturn nil\n}\n\nvar enableCommand = cli.Command{\n\tName:        \"enable\",\n\tUsage:       \"Enable the autopilot.\",\n\tDescription: \"\",\n\tAction:      actionDecorator(enable),\n}\n\nvar disableCommand = cli.Command{\n\tName:        \"disable\",\n\tUsage:       \"Disable the active autopilot.\",\n\tDescription: \"\",\n\tAction:      actionDecorator(disable),\n}\n\nfunc enable(ctx *cli.Context) error {\n\tctxb := context.Background()\n\tclient, cleanUp := getAutopilotClient(ctx)\n\tdefer cleanUp()\n\n\t\/\/ We will enable the autopilot.\n\treq := &autopilotrpc.ModifyStatusRequest{\n\t\tEnable: true,\n\t}\n\n\tresp, err := client.ModifyStatus(ctxb, req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tprintRespJSON(resp)\n\treturn nil\n}\n\nfunc disable(ctx *cli.Context) error {\n\tctxb := context.Background()\n\tclient, cleanUp := getAutopilotClient(ctx)\n\tdefer cleanUp()\n\n\t\/\/ We will disable the autopilot.\n\treq := &autopilotrpc.ModifyStatusRequest{\n\t\tEnable: false,\n\t}\n\n\tresp, err := client.ModifyStatus(ctxb, req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tprintRespJSON(resp)\n\treturn nil\n}\n\nvar queryScoresCommand = cli.Command{\n\tName:        \"query\",\n\tUsage:       \"Query the autopilot heuristcs for nodes' scores.\",\n\tArgsUsage:   \"<pubkey> <pubkey> <pubkey> ...\",\n\tDescription: \"\",\n\tAction:      actionDecorator(queryScores),\n}\n\nfunc queryScores(ctx *cli.Context) error {\n\tctxb := context.Background()\n\tclient, cleanUp := getAutopilotClient(ctx)\n\tdefer cleanUp()\n\n\targs := ctx.Args()\n\tvar pubs []string\n\n\t\/\/ Keep reading pubkeys as long as there are arguments.\nloop:\n\tfor {\n\t\tswitch {\n\t\tcase args.Present():\n\t\t\tpubs = append(pubs, args.First())\n\t\t\targs = args.Tail()\n\t\tdefault:\n\t\t\tbreak loop\n\t\t}\n\t}\n\n\treq := &autopilotrpc.QueryScoresRequest{\n\t\tPubkeys: pubs,\n\t}\n\n\tresp, err := client.QueryScores(ctxb, req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tprintRespJSON(resp)\n\treturn nil\n}\n\n\/\/ autopilotCommands will return the set of commands to enable for autopilotrpc\n\/\/ builds.\nfunc autopilotCommands() []cli.Command {\n\treturn []cli.Command{\n\t\t{\n\t\t\tName:        \"autopilot\",\n\t\t\tCategory:    \"Autopilot\",\n\t\t\tUsage:       \"Interact with a running autopilot.\",\n\t\t\tDescription: \"\",\n\t\t\tSubcommands: []cli.Command{\n\t\t\t\tgetStatusCommand,\n\t\t\t\tenableCommand,\n\t\t\t\tdisableCommand,\n\t\t\t\tqueryScoresCommand,\n\t\t\t},\n\t\t},\n\t}\n}\n<commit_msg>lncli\/autopilot: add -ignorelocal state flag to query<commit_after>\/\/ +build autopilotrpc\n\npackage main\n\nimport (\n\t\"context\"\n\n\t\"github.com\/lightningnetwork\/lnd\/lnrpc\/autopilotrpc\"\n\t\"github.com\/urfave\/cli\"\n)\n\nfunc getAutopilotClient(ctx *cli.Context) (autopilotrpc.AutopilotClient, func()) {\n\tconn := getClientConn(ctx, false)\n\n\tcleanUp := func() {\n\t\tconn.Close()\n\t}\n\n\treturn autopilotrpc.NewAutopilotClient(conn), cleanUp\n}\n\nvar getStatusCommand = cli.Command{\n\tName:        \"status\",\n\tUsage:       \"Get the active status of autopilot.\",\n\tDescription: \"\",\n\tAction:      actionDecorator(getStatus),\n}\n\nfunc getStatus(ctx *cli.Context) error {\n\tctxb := context.Background()\n\tclient, cleanUp := getAutopilotClient(ctx)\n\tdefer cleanUp()\n\n\treq := &autopilotrpc.StatusRequest{}\n\n\tresp, err := client.Status(ctxb, req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tprintRespJSON(resp)\n\treturn nil\n}\n\nvar enableCommand = cli.Command{\n\tName:        \"enable\",\n\tUsage:       \"Enable the autopilot.\",\n\tDescription: \"\",\n\tAction:      actionDecorator(enable),\n}\n\nvar disableCommand = cli.Command{\n\tName:        \"disable\",\n\tUsage:       \"Disable the active autopilot.\",\n\tDescription: \"\",\n\tAction:      actionDecorator(disable),\n}\n\nfunc enable(ctx *cli.Context) error {\n\tctxb := context.Background()\n\tclient, cleanUp := getAutopilotClient(ctx)\n\tdefer cleanUp()\n\n\t\/\/ We will enable the autopilot.\n\treq := &autopilotrpc.ModifyStatusRequest{\n\t\tEnable: true,\n\t}\n\n\tresp, err := client.ModifyStatus(ctxb, req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tprintRespJSON(resp)\n\treturn nil\n}\n\nfunc disable(ctx *cli.Context) error {\n\tctxb := context.Background()\n\tclient, cleanUp := getAutopilotClient(ctx)\n\tdefer cleanUp()\n\n\t\/\/ We will disable the autopilot.\n\treq := &autopilotrpc.ModifyStatusRequest{\n\t\tEnable: false,\n\t}\n\n\tresp, err := client.ModifyStatus(ctxb, req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tprintRespJSON(resp)\n\treturn nil\n}\n\nvar queryScoresCommand = cli.Command{\n\tName:        \"query\",\n\tUsage:       \"Query the autopilot heuristcs for nodes' scores.\",\n\tArgsUsage:   \"[flags] <pubkey> <pubkey> <pubkey> ...\",\n\tDescription: \"\",\n\tAction:      actionDecorator(queryScores),\n\tFlags: []cli.Flag{\n\t\tcli.BoolFlag{\n\t\t\tName: \"ignorelocalstate, i\",\n\t\t\tUsage: \"Ignore local channel state when calculating \" +\n\t\t\t\t\"scores.\",\n\t\t},\n\t},\n}\n\nfunc queryScores(ctx *cli.Context) error {\n\tctxb := context.Background()\n\tclient, cleanUp := getAutopilotClient(ctx)\n\tdefer cleanUp()\n\n\targs := ctx.Args()\n\tvar pubs []string\n\n\t\/\/ Keep reading pubkeys as long as there are arguments.\nloop:\n\tfor {\n\t\tswitch {\n\t\tcase args.Present():\n\t\t\tpubs = append(pubs, args.First())\n\t\t\targs = args.Tail()\n\t\tdefault:\n\t\t\tbreak loop\n\t\t}\n\t}\n\n\treq := &autopilotrpc.QueryScoresRequest{\n\t\tPubkeys:          pubs,\n\t\tIgnoreLocalState: ctx.Bool(\"ignorelocalstate\"),\n\t}\n\n\tresp, err := client.QueryScores(ctxb, req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tprintRespJSON(resp)\n\treturn nil\n}\n\n\/\/ autopilotCommands will return the set of commands to enable for autopilotrpc\n\/\/ builds.\nfunc autopilotCommands() []cli.Command {\n\treturn []cli.Command{\n\t\t{\n\t\t\tName:        \"autopilot\",\n\t\t\tCategory:    \"Autopilot\",\n\t\t\tUsage:       \"Interact with a running autopilot.\",\n\t\t\tDescription: \"\",\n\t\t\tSubcommands: []cli.Command{\n\t\t\t\tgetStatusCommand,\n\t\t\t\tenableCommand,\n\t\t\t\tdisableCommand,\n\t\t\t\tqueryScoresCommand,\n\t\t\t},\n\t\t},\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package gitmediaclient\n\nimport (\n\t\"bytes\"\n\t\"encoding\/base64\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n)\n\nfunc Put(filename string) error {\n\toid := filepath.Base(filename)\n\tstat, err := os.Stat(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfile, err := os.Open(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq, err := clientRequest(\"PUT\", oid)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Body = file\n\treq.ContentLength = stat.Size()\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer res.Body.Close()\n\n\tif res.StatusCode > 299 {\n\t\tapierr := &Error{}\n\t\tdec := json.NewDecoder(res.Body)\n\t\tif err = dec.Decode(apierr); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn apierr\n\t}\n\n\tfmt.Printf(\"Sending %s from %s: %d\\n\", oid, filename, res.StatusCode)\n\treturn nil\n}\n\nfunc Get(filename string) (io.ReadCloser, error) {\n\toid := filepath.Base(filename)\n\tif stat, err := os.Stat(filename); err != nil || stat == nil {\n\t\treq, err := clientRequest(\"GET\", oid)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treq.Header.Set(\"Accept\", \"application\/vnd.git-media\")\n\t\tres, err := http.DefaultClient.Do(req)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn res.Body, nil\n\t}\n\n\treturn os.Open(filename)\n}\n\nfunc clientRequest(method, oid string) (*http.Request, error) {\n\tu := objectUrl(oid)\n\treq, err := http.NewRequest(method, u.String(), nil)\n\tif err == nil {\n\t\tcreds, err := credentials(u)\n\t\tif err != nil {\n\t\t\treturn req, err\n\t\t}\n\n\t\ttoken := fmt.Sprintf(\"%s:%s\", creds[\"username\"], creds[\"password\"])\n\t\tauth := \"Basic \" + base64.URLEncoding.EncodeToString([]byte(token))\n\t\treq.Header.Set(\"Authorization\", auth)\n\t}\n\n\treturn req, err\n}\n\nfunc objectUrl(oid string) *url.URL {\n\tu, _ := url.Parse(\"http:\/\/localhost:8080\")\n\tu.Path = \"\/objects\/\" + oid\n\treturn u\n}\n\nfunc credentials(u *url.URL) (map[string]string, error) {\n\tcredInput := fmt.Sprintf(\"protocol=%s\\nhost=%s\\n\", u.Scheme, u.Host)\n\tcmd, err := execCreds(credInput, \"fill\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn cmd.Credentials(), nil\n}\n\nfunc execCreds(input, subCommand string) (*CredentialCmd, error) {\n\tcmd := NewCommand(input, subCommand)\n\terr := cmd.Start()\n\tif err != nil {\n\t\treturn cmd, err\n\t}\n\n\terr = cmd.Wait()\n\treturn cmd, err\n}\n\ntype CredentialCmd struct {\n\tbufOut *bytes.Buffer\n\tbufErr *bytes.Buffer\n\t*exec.Cmd\n}\n\nfunc NewCommand(input, subCommand string) *CredentialCmd {\n\tbuf1 := new(bytes.Buffer)\n\tbuf2 := new(bytes.Buffer)\n\tcmd := exec.Command(\"git\", \"credential\", subCommand)\n\tcmd.Stdin = bytes.NewBufferString(input)\n\tcmd.Stdout = buf1\n\tcmd.Stderr = buf2\n\treturn &CredentialCmd{buf1, buf2, cmd}\n}\n\nfunc (c *CredentialCmd) StderrString() string {\n\treturn c.bufErr.String()\n}\n\nfunc (c *CredentialCmd) StdoutString() string {\n\treturn c.bufOut.String()\n}\n\nfunc (c *CredentialCmd) Credentials() map[string]string {\n\tcreds := make(map[string]string)\n\n\tfor _, line := range strings.Split(c.StdoutString(), \"\\n\") {\n\t\tpieces := strings.SplitN(line, \"=\", 2)\n\t\tif len(pieces) < 2 {\n\t\t\tcontinue\n\t\t}\n\t\tcreds[pieces[0]] = pieces[1]\n\t}\n\n\treturn creds\n}\n\ntype Error struct {\n\tMessage   string `json:\"message\"`\n\tRequestId string `json:\"request_id,omitempty\"`\n}\n\nfunc (e *Error) Error() string {\n\treturn e.Message\n}\n<commit_msg>ンンー ンンンン ンーンン<commit_after>package gitmediaclient\n\nimport (\n\t\"bytes\"\n\t\"encoding\/base64\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n)\n\nfunc Put(filename string) error {\n\toid := filepath.Base(filename)\n\tstat, err := os.Stat(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfile, err := os.Open(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq, _, err := clientRequest(\"PUT\", oid)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Body = file\n\treq.ContentLength = stat.Size()\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer res.Body.Close()\n\n\tif res.StatusCode > 299 {\n\t\tapierr := &Error{}\n\t\tdec := json.NewDecoder(res.Body)\n\t\tif err = dec.Decode(apierr); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn apierr\n\t}\n\n\tfmt.Printf(\"Sending %s from %s: %d\\n\", oid, filename, res.StatusCode)\n\treturn nil\n}\n\nfunc Get(filename string) (io.ReadCloser, error) {\n\toid := filepath.Base(filename)\n\tif stat, err := os.Stat(filename); err != nil || stat == nil {\n\t\treq, _, err := clientRequest(\"GET\", oid)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treq.Header.Set(\"Accept\", \"application\/vnd.git-media\")\n\t\tres, err := http.DefaultClient.Do(req)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn res.Body, nil\n\t}\n\n\treturn os.Open(filename)\n}\n\nfunc clientRequest(method, oid string) (*http.Request, map[string]string, error) {\n\tu := objectUrl(oid)\n\treq, err := http.NewRequest(method, u.String(), nil)\n\tif err == nil {\n\t\tcreds, err := credentials(u)\n\t\tif err != nil {\n\t\t\treturn req, nil, err\n\t\t}\n\n\t\ttoken := fmt.Sprintf(\"%s:%s\", creds[\"username\"], creds[\"password\"])\n\t\tauth := \"Basic \" + base64.URLEncoding.EncodeToString([]byte(token))\n\t\treq.Header.Set(\"Authorization\", auth)\n\t\treturn req, creds, nil\n\t}\n\n\treturn req, nil, err\n}\n\nfunc objectUrl(oid string) *url.URL {\n\tu, _ := url.Parse(\"http:\/\/localhost:8080\")\n\tu.Path = \"\/objects\/\" + oid\n\treturn u\n}\n\nfunc credentials(u *url.URL) (map[string]string, error) {\n\tcredInput := fmt.Sprintf(\"protocol=%s\\nhost=%s\\n\", u.Scheme, u.Host)\n\tcmd, err := execCreds(credInput, \"fill\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn cmd.Credentials(), nil\n}\n\nfunc execCreds(input, subCommand string) (*CredentialCmd, error) {\n\tcmd := NewCommand(input, subCommand)\n\terr := cmd.Start()\n\tif err != nil {\n\t\treturn cmd, err\n\t}\n\n\terr = cmd.Wait()\n\treturn cmd, err\n}\n\ntype CredentialCmd struct {\n\tbufOut *bytes.Buffer\n\tbufErr *bytes.Buffer\n\t*exec.Cmd\n}\n\nfunc NewCommand(input, subCommand string) *CredentialCmd {\n\tbuf1 := new(bytes.Buffer)\n\tbuf2 := new(bytes.Buffer)\n\tcmd := exec.Command(\"git\", \"credential\", subCommand)\n\tcmd.Stdin = bytes.NewBufferString(input)\n\tcmd.Stdout = buf1\n\tcmd.Stderr = buf2\n\treturn &CredentialCmd{buf1, buf2, cmd}\n}\n\nfunc (c *CredentialCmd) StderrString() string {\n\treturn c.bufErr.String()\n}\n\nfunc (c *CredentialCmd) StdoutString() string {\n\treturn c.bufOut.String()\n}\n\nfunc (c *CredentialCmd) Credentials() map[string]string {\n\tcreds := make(map[string]string)\n\n\tfor _, line := range strings.Split(c.StdoutString(), \"\\n\") {\n\t\tpieces := strings.SplitN(line, \"=\", 2)\n\t\tif len(pieces) < 2 {\n\t\t\tcontinue\n\t\t}\n\t\tcreds[pieces[0]] = pieces[1]\n\t}\n\n\treturn creds\n}\n\ntype Error struct {\n\tMessage   string `json:\"message\"`\n\tRequestId string `json:\"request_id,omitempty\"`\n}\n\nfunc (e *Error) Error() string {\n\treturn e.Message\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2017 Intel Corporation\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"regexp\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\ntype testData struct {\n\tpath          string\n\texpectFailure bool\n}\n\nfunc init() {\n\t\/\/ Ensure all log levels are logged\n\tccLog.Level = logrus.DebugLevel\n\n\t\/\/ Discard \"normal\" log output: this test only cares about the\n\t\/\/ (additional) global log output\n\tccLog.Out = ioutil.Discard\n}\n\nfunc grep(pattern, file string) error {\n\tif file == \"\" {\n\t\treturn errors.New(\"need file\")\n\t}\n\n\tbytes, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tre := regexp.MustCompile(pattern)\n\tmatches := re.FindAllStringSubmatch(string(bytes), -1)\n\n\tif matches == nil {\n\t\treturn fmt.Errorf(\"pattern %q not found in file %q\", pattern, file)\n\t}\n\n\treturn nil\n}\n\nfunc TestNewGlobalLogHook(t *testing.T) {\n\ttmpdir, err := ioutil.TempDir(\"\", \"\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.RemoveAll(tmpdir)\n\n\ttmpfile := path.Join(tmpdir, \"global.log\")\n\n\tdata := []testData{\n\t\t{\"\", true},\n\t\t{tmpfile, false},\n\t}\n\n\tfor _, d := range data {\n\t\thook, err := newGlobalLogHook(d.path)\n\t\tif d.expectFailure {\n\t\t\tif err == nil {\n\t\t\t\tt.Fatal(fmt.Sprintf(\"unexpected succes from newGlobalLogHook(path=%v)\", d.path))\n\t\t\t}\n\t\t} else {\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(fmt.Sprintf(\"unexpected failure from newGlobalLogHook(path=%q): %v\", d.path, err))\n\t\t\t}\n\t\t\tif hook.path != d.path {\n\t\t\t\tt.Fatal(fmt.Sprintf(\"expected hook to contain path %q, found %q\", d.path, hook.path))\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestHandleGlobalLog(t *testing.T) {\n\ttmpdir, err := ioutil.TempDir(\"\", \"\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.RemoveAll(tmpdir)\n\n\tsubDir := path.Join(tmpdir, \"a\/b\/global.log\")\n\terr = os.MkdirAll(subDir, testDirMode)\n\tassert.NoError(t, err)\n\n\texistingFile := path.Join(tmpdir, \"c\")\n\terr = createEmptyFile(existingFile)\n\tassert.NoError(t, err)\n\n\ttmpfile := path.Join(tmpdir, \"global.log\")\n\n\tdata := []testData{\n\t\t{\"\", false},\n\n\t\t\/\/ path must be absolute, so these should fail\n\t\t{\"foo\/bar\/global.log\", true},\n\t\t{\"..\/foo\/bar\/global.log\", true},\n\t\t{\".\/foo\/bar\/global.log\", true},\n\t\t{subDir, true},\n\t\t{path.Join(existingFile, \"global.log\"), true},\n\n\t\t{tmpfile, false},\n\t}\n\n\tfor _, d := range data {\n\t\terr := handleGlobalLog(d.path)\n\t\tif d.expectFailure {\n\t\t\tif err == nil {\n\t\t\t\tt.Fatal(fmt.Sprintf(\"unexpected success from handleGlobalLog(path=%q)\", d.path))\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif err != nil {\n\t\t\tt.Fatal(fmt.Sprintf(\"unexpected failure from handleGlobalLog(path=%q): %v\", d.path, err))\n\t\t}\n\n\t\t\/\/ It's valid to pass a blank path to handleGlobalLog(),\n\t\t\/\/ but no point in checking for log entries in that\n\t\t\/\/ case!\n\t\tif d.path == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Add a log entry\n\t\tstr := \"hello. foo bar baz!\"\n\t\tccLog.Debug(str)\n\n\t\t\/\/ Check that the string was logged\n\t\terr = grep(fmt.Sprintf(\"debug:.*%s\", str), d.path)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\t\/\/ Check expected perms\n\t\tst, err := os.Stat(d.path)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\texpectedPerms := \"-rw-r-----\"\n\t\tactualPerms := st.Mode().String()\n\t\tif expectedPerms != actualPerms {\n\t\t\tt.Fatal(fmt.Sprintf(\"logfile %v should have perms %v, but found %v\",\n\t\t\t\td.path, expectedPerms, actualPerms))\n\t\t}\n\t}\n}\n\nfunc TestHandleGlobalLogEnvVar(t *testing.T) {\n\tenvvar := \"CC_RUNTIME_GLOBAL_LOG\"\n\ttmpdir, err := ioutil.TempDir(\"\", \"\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.RemoveAll(tmpdir)\n\n\ttmpfile := path.Join(tmpdir, \"global.log\")\n\ttmpfile2 := path.Join(tmpdir, \"global-envvar.log\")\n\n\tos.Setenv(envvar, tmpfile2)\n\tdefer os.Unsetenv(envvar)\n\n\terr = handleGlobalLog(tmpfile)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tstr := \"foo or moo?\"\n\tccLog.Debug(str)\n\ttmpfileExists := fileExists(tmpfile)\n\ttmpfile2Exists := fileExists(tmpfile2)\n\n\tif tmpfileExists == true {\n\t\tt.Fatal(fmt.Sprintf(\"tmpfile %q exists unexpectedly\", tmpfile))\n\t}\n\n\tif tmpfile2Exists == false {\n\t\tt.Fatal(fmt.Sprintf(\"tmpfile2 %q does not exist unexpectedly\", tmpfile2))\n\t}\n\n\t\/\/ Check that the string was logged\n\terr = grep(fmt.Sprintf(\"debug:.*%s\", str), tmpfile2)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestLoggerFire(t *testing.T) {\n\ttmpdir, err := ioutil.TempDir(\"\", \"\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tccLog = logrus.New()\n\n\tlogFile := path.Join(tmpdir, \"a\/b\/global.log\")\n\terr = handleGlobalLog(logFile)\n\tassert.NoError(t, err)\n\n\t\/\/ccLog.Debug(\"foo\")\n\n\tentry := &logrus.Entry{\n\t\tLogger:  ccLog,\n\t\tTime:    time.Now().UTC(),\n\t\tLevel:   logrus.DebugLevel,\n\t\tMessage: \"foo\",\n\t}\n\n\terr = ccLog.Hooks.Fire(logrus.DebugLevel, entry)\n\tassert.NoError(t, err)\n\n\tassert.Equal(t, len(ccLog.Hooks[logrus.DebugLevel]), 1)\n\thook, ok := ccLog.Hooks[logrus.DebugLevel][0].(*GlobalLogHook)\n\tassert.True(t, ok)\n\n\terr = hook.file.Close()\n\tassert.NoError(t, err)\n\n\terr = os.RemoveAll(tmpdir)\n\tassert.NoError(t, err)\n\n\terr = ccLog.Hooks.Fire(logrus.DebugLevel, entry)\n\tassert.Error(t, err)\n}\n<commit_msg>tests: Remove comment.<commit_after>\/\/ Copyright (c) 2017 Intel Corporation\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"regexp\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\ntype testData struct {\n\tpath          string\n\texpectFailure bool\n}\n\nfunc init() {\n\t\/\/ Ensure all log levels are logged\n\tccLog.Level = logrus.DebugLevel\n\n\t\/\/ Discard \"normal\" log output: this test only cares about the\n\t\/\/ (additional) global log output\n\tccLog.Out = ioutil.Discard\n}\n\nfunc grep(pattern, file string) error {\n\tif file == \"\" {\n\t\treturn errors.New(\"need file\")\n\t}\n\n\tbytes, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tre := regexp.MustCompile(pattern)\n\tmatches := re.FindAllStringSubmatch(string(bytes), -1)\n\n\tif matches == nil {\n\t\treturn fmt.Errorf(\"pattern %q not found in file %q\", pattern, file)\n\t}\n\n\treturn nil\n}\n\nfunc TestNewGlobalLogHook(t *testing.T) {\n\ttmpdir, err := ioutil.TempDir(\"\", \"\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.RemoveAll(tmpdir)\n\n\ttmpfile := path.Join(tmpdir, \"global.log\")\n\n\tdata := []testData{\n\t\t{\"\", true},\n\t\t{tmpfile, false},\n\t}\n\n\tfor _, d := range data {\n\t\thook, err := newGlobalLogHook(d.path)\n\t\tif d.expectFailure {\n\t\t\tif err == nil {\n\t\t\t\tt.Fatal(fmt.Sprintf(\"unexpected succes from newGlobalLogHook(path=%v)\", d.path))\n\t\t\t}\n\t\t} else {\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(fmt.Sprintf(\"unexpected failure from newGlobalLogHook(path=%q): %v\", d.path, err))\n\t\t\t}\n\t\t\tif hook.path != d.path {\n\t\t\t\tt.Fatal(fmt.Sprintf(\"expected hook to contain path %q, found %q\", d.path, hook.path))\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestHandleGlobalLog(t *testing.T) {\n\ttmpdir, err := ioutil.TempDir(\"\", \"\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.RemoveAll(tmpdir)\n\n\tsubDir := path.Join(tmpdir, \"a\/b\/global.log\")\n\terr = os.MkdirAll(subDir, testDirMode)\n\tassert.NoError(t, err)\n\n\texistingFile := path.Join(tmpdir, \"c\")\n\terr = createEmptyFile(existingFile)\n\tassert.NoError(t, err)\n\n\ttmpfile := path.Join(tmpdir, \"global.log\")\n\n\tdata := []testData{\n\t\t{\"\", false},\n\n\t\t\/\/ path must be absolute, so these should fail\n\t\t{\"foo\/bar\/global.log\", true},\n\t\t{\"..\/foo\/bar\/global.log\", true},\n\t\t{\".\/foo\/bar\/global.log\", true},\n\t\t{subDir, true},\n\t\t{path.Join(existingFile, \"global.log\"), true},\n\n\t\t{tmpfile, false},\n\t}\n\n\tfor _, d := range data {\n\t\terr := handleGlobalLog(d.path)\n\t\tif d.expectFailure {\n\t\t\tif err == nil {\n\t\t\t\tt.Fatal(fmt.Sprintf(\"unexpected success from handleGlobalLog(path=%q)\", d.path))\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif err != nil {\n\t\t\tt.Fatal(fmt.Sprintf(\"unexpected failure from handleGlobalLog(path=%q): %v\", d.path, err))\n\t\t}\n\n\t\t\/\/ It's valid to pass a blank path to handleGlobalLog(),\n\t\t\/\/ but no point in checking for log entries in that\n\t\t\/\/ case!\n\t\tif d.path == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Add a log entry\n\t\tstr := \"hello. foo bar baz!\"\n\t\tccLog.Debug(str)\n\n\t\t\/\/ Check that the string was logged\n\t\terr = grep(fmt.Sprintf(\"debug:.*%s\", str), d.path)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\t\/\/ Check expected perms\n\t\tst, err := os.Stat(d.path)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\texpectedPerms := \"-rw-r-----\"\n\t\tactualPerms := st.Mode().String()\n\t\tif expectedPerms != actualPerms {\n\t\t\tt.Fatal(fmt.Sprintf(\"logfile %v should have perms %v, but found %v\",\n\t\t\t\td.path, expectedPerms, actualPerms))\n\t\t}\n\t}\n}\n\nfunc TestHandleGlobalLogEnvVar(t *testing.T) {\n\tenvvar := \"CC_RUNTIME_GLOBAL_LOG\"\n\ttmpdir, err := ioutil.TempDir(\"\", \"\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.RemoveAll(tmpdir)\n\n\ttmpfile := path.Join(tmpdir, \"global.log\")\n\ttmpfile2 := path.Join(tmpdir, \"global-envvar.log\")\n\n\tos.Setenv(envvar, tmpfile2)\n\tdefer os.Unsetenv(envvar)\n\n\terr = handleGlobalLog(tmpfile)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tstr := \"foo or moo?\"\n\tccLog.Debug(str)\n\ttmpfileExists := fileExists(tmpfile)\n\ttmpfile2Exists := fileExists(tmpfile2)\n\n\tif tmpfileExists == true {\n\t\tt.Fatal(fmt.Sprintf(\"tmpfile %q exists unexpectedly\", tmpfile))\n\t}\n\n\tif tmpfile2Exists == false {\n\t\tt.Fatal(fmt.Sprintf(\"tmpfile2 %q does not exist unexpectedly\", tmpfile2))\n\t}\n\n\t\/\/ Check that the string was logged\n\terr = grep(fmt.Sprintf(\"debug:.*%s\", str), tmpfile2)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestLoggerFire(t *testing.T) {\n\ttmpdir, err := ioutil.TempDir(\"\", \"\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tccLog = logrus.New()\n\n\tlogFile := path.Join(tmpdir, \"a\/b\/global.log\")\n\terr = handleGlobalLog(logFile)\n\tassert.NoError(t, err)\n\n\tentry := &logrus.Entry{\n\t\tLogger:  ccLog,\n\t\tTime:    time.Now().UTC(),\n\t\tLevel:   logrus.DebugLevel,\n\t\tMessage: \"foo\",\n\t}\n\n\terr = ccLog.Hooks.Fire(logrus.DebugLevel, entry)\n\tassert.NoError(t, err)\n\n\tassert.Equal(t, len(ccLog.Hooks[logrus.DebugLevel]), 1)\n\thook, ok := ccLog.Hooks[logrus.DebugLevel][0].(*GlobalLogHook)\n\tassert.True(t, ok)\n\n\terr = hook.file.Close()\n\tassert.NoError(t, err)\n\n\terr = os.RemoveAll(tmpdir)\n\tassert.NoError(t, err)\n\n\terr = ccLog.Hooks.Fire(logrus.DebugLevel, entry)\n\tassert.Error(t, err)\n}\n<|endoftext|>"}
{"text":"<commit_before>package admin\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/jinzhu\/gorm\"\n\t\"github.com\/jinzhu\/now\"\n\t\"github.com\/qor\/qor\"\n\t\"github.com\/qor\/qor\/resource\"\n\t\"github.com\/qor\/qor\/roles\"\n\t\"github.com\/qor\/qor\/utils\"\n)\n\ntype Resource struct {\n\tresource.Resource\n\tadmin         *Admin\n\tConfig        *Config\n\tMetas         []*Meta\n\tactions       []*Action\n\tscopes        []*Scope\n\tfilters       map[string]*Filter\n\tsearchAttrs   []string\n\tindexAttrs    []string\n\tnewAttrs      []string\n\teditAttrs     []string\n\tshowAttrs     []string\n\tcachedMetas   *map[string][]*Meta\n\tSearchHandler func(keyword string, context *qor.Context) *gorm.DB\n}\n\nfunc (res *Resource) Meta(meta *Meta) {\n\tif res.GetMeta(meta.Name) != nil {\n\t\tutils.ExitWithMsg(\"Duplicated meta %v defined for resource %v\", meta.Name, res.Name)\n\t}\n\n\tmeta.base = res\n\tmeta.updateMeta()\n\tres.Metas = append(res.Metas, meta)\n}\n\nfunc (res Resource) GetAdmin() *Admin {\n\treturn res.admin\n}\n\nfunc (res Resource) ToParam() string {\n\treturn utils.ToParamString(res.Name)\n}\n\nfunc (res Resource) UseTheme(theme string) []string {\n\tif res.Config != nil {\n\t\tres.Config.Themes = append(res.Config.Themes, theme)\n\t\treturn res.Config.Themes\n\t}\n\treturn []string{}\n}\n\nfunc (res *Resource) convertObjectToMap(context *Context, value interface{}, kind string) interface{} {\n\treflectValue := reflect.Indirect(reflect.ValueOf(value))\n\tswitch reflectValue.Kind() {\n\tcase reflect.Slice:\n\t\tvalues := []interface{}{}\n\t\tfor i := 0; i < reflectValue.Len(); i++ {\n\t\t\tvalues = append(values, res.convertObjectToMap(context, reflectValue.Index(i).Interface(), kind))\n\t\t}\n\t\treturn values\n\tcase reflect.Struct:\n\t\tvar metas []*Meta\n\t\tif kind == \"index\" {\n\t\t\tmetas = res.indexMetas()\n\t\t} else if kind == \"show\" {\n\t\t\tmetas = res.showMetas()\n\t\t}\n\n\t\tvalues := map[string]interface{}{}\n\t\tfor _, meta := range metas {\n\t\t\tif meta.HasPermission(roles.Read, context.Context) {\n\t\t\t\tvalue := meta.GetValuer()(value, context.Context)\n\t\t\t\tif meta.Resource != nil {\n\t\t\t\t\tvalue = meta.Resource.(*Resource).convertObjectToMap(context, value, kind)\n\t\t\t\t}\n\t\t\t\tvalues[meta.GetName()] = value\n\t\t\t}\n\t\t}\n\t\treturn values\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"Can't convert %v (%v) to map\", reflectValue, reflectValue.Kind()))\n\t}\n}\n\nfunc (res *Resource) Decode(context *qor.Context, value interface{}) (errs []error) {\n\treturn resource.Decode(context, value, res)\n}\n\nfunc (res *Resource) IndexAttrs(columns ...string) []string {\n\tif len(columns) > 0 {\n\t\tres.indexAttrs = columns\n\t}\n\treturn res.indexAttrs\n}\n\nfunc (res *Resource) NewAttrs(columns ...string) []string {\n\tif len(columns) > 0 {\n\t\tres.newAttrs = columns\n\t}\n\treturn res.newAttrs\n}\n\nfunc (res *Resource) EditAttrs(columns ...string) []string {\n\tif len(columns) > 0 {\n\t\tres.editAttrs = columns\n\t}\n\treturn res.editAttrs\n}\n\nfunc (res *Resource) ShowAttrs(columns ...string) []string {\n\tif len(columns) > 0 {\n\t\tres.showAttrs = columns\n\t}\n\treturn res.showAttrs\n}\n\nfunc (res *Resource) SearchAttrs(columns ...string) []string {\n\tif len(columns) > 0 {\n\t\tres.searchAttrs = columns\n\t\tres.SearchHandler = func(keyword string, context *qor.Context) *gorm.DB {\n\t\t\tdb := context.GetDB()\n\t\t\tvar conditions []string\n\t\t\tvar keywords []interface{}\n\t\t\tscope := db.NewScope(res.Value)\n\n\t\t\tfor _, column := range columns {\n\t\t\t\tif field, ok := scope.FieldByName(column); ok {\n\t\t\t\t\tswitch field.Field.Kind() {\n\t\t\t\t\tcase reflect.String:\n\t\t\t\t\t\tconditions = append(conditions, fmt.Sprintf(\"upper(%v) like upper(?)\", scope.Quote(field.DBName)))\n\t\t\t\t\t\tkeywords = append(keywords, \"%\"+keyword+\"%\")\n\t\t\t\t\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\t\t\t\t\tif _, err := strconv.Atoi(keyword); err == nil {\n\t\t\t\t\t\t\tconditions = append(conditions, fmt.Sprintf(\"%v = ?\", scope.Quote(field.DBName)))\n\t\t\t\t\t\t\tkeywords = append(keywords, keyword)\n\t\t\t\t\t\t}\n\t\t\t\t\tcase reflect.Float32, reflect.Float64:\n\t\t\t\t\t\tif _, err := strconv.ParseFloat(keyword, 64); err == nil {\n\t\t\t\t\t\t\tconditions = append(conditions, fmt.Sprintf(\"%v = ?\", scope.Quote(field.DBName)))\n\t\t\t\t\t\t\tkeywords = append(keywords, keyword)\n\t\t\t\t\t\t}\n\t\t\t\t\tcase reflect.Struct:\n\t\t\t\t\t\t\/\/ time ?\n\t\t\t\t\t\tif _, ok := field.Field.Interface().(time.Time); ok {\n\t\t\t\t\t\t\tif parsedTime, err := now.Parse(keyword); err == nil {\n\t\t\t\t\t\t\t\tconditions = append(conditions, fmt.Sprintf(\"%v = ?\", scope.Quote(field.DBName)))\n\t\t\t\t\t\t\t\tkeywords = append(keywords, parsedTime)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\tcase reflect.Ptr:\n\t\t\t\t\t\t\/\/ time ?\n\t\t\t\t\t\tif _, ok := field.Field.Interface().(*time.Time); ok {\n\t\t\t\t\t\t\tif parsedTime, err := now.Parse(keyword); err == nil {\n\t\t\t\t\t\t\t\tconditions = append(conditions, fmt.Sprintf(\"%v = ?\", scope.Quote(field.DBName)))\n\t\t\t\t\t\t\t\tkeywords = append(keywords, parsedTime)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tconditions = append(conditions, fmt.Sprintf(\"%v = ?\", scope.Quote(field.DBName)))\n\t\t\t\t\t\tkeywords = append(keywords, keyword)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif len(conditions) > 0 {\n\t\t\t\treturn context.GetDB().Where(strings.Join(conditions, \" OR \"), keywords...)\n\t\t\t} else {\n\t\t\t\treturn context.GetDB()\n\t\t\t}\n\t\t}\n\t}\n\treturn res.searchAttrs\n}\n\nfunc (res *Resource) getCachedMetas(cacheKey string, fc func() []resource.Metaor) []*Meta {\n\tif res.cachedMetas == nil {\n\t\tres.cachedMetas = &map[string][]*Meta{}\n\t}\n\n\tif values, ok := (*res.cachedMetas)[cacheKey]; ok {\n\t\treturn values\n\t} else {\n\t\tvalues := fc()\n\t\tvar metas []*Meta\n\t\tfor _, value := range values {\n\t\t\tmetas = append(metas, value.(*Meta))\n\t\t}\n\t\t(*res.cachedMetas)[cacheKey] = metas\n\t\treturn metas\n\t}\n}\n\nfunc (res *Resource) GetMetas(_attrs ...[]string) []resource.Metaor {\n\tvar attrs, ignoredAttrs []string\n\tfor _, value := range _attrs {\n\t\tif value != nil {\n\t\t\tfor _, v := range value {\n\t\t\t\tif strings.HasPrefix(v, \"-\") {\n\t\t\t\t\tignoredAttrs = append(ignoredAttrs, strings.TrimLeft(v, \"-\"))\n\t\t\t\t} else {\n\t\t\t\t\tattrs = append(attrs, v)\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif attrs == nil {\n\t\tscope := &gorm.Scope{Value: res.Value}\n\t\tstructFields := scope.GetModelStruct().StructFields\n\t\tattrs = []string{}\n\n\tFields:\n\t\tfor _, field := range structFields {\n\t\t\tfor _, attr := range ignoredAttrs {\n\t\t\t\tif attr == field.Name {\n\t\t\t\t\tcontinue Fields\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor _, meta := range res.Metas {\n\t\t\t\tif field.Name == meta.Alias {\n\t\t\t\t\tattrs = append(attrs, meta.Name)\n\t\t\t\t\tcontinue Fields\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif field.IsForeignKey {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfor _, value := range []string{\"CreatedAt\", \"UpdatedAt\", \"DeletedAt\"} {\n\t\t\t\tif value == field.Name {\n\t\t\t\t\tcontinue Fields\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tattrs = append(attrs, field.Name)\n\t\t}\n\n\tMetaIncluded:\n\t\tfor _, meta := range res.Metas {\n\t\t\tfor _, attr := range ignoredAttrs {\n\t\t\t\tif attr == meta.Name || attr == meta.Alias {\n\t\t\t\t\tcontinue MetaIncluded\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor _, attr := range attrs {\n\t\t\t\tif attr == meta.Alias || attr == meta.Name {\n\t\t\t\t\tcontinue MetaIncluded\n\t\t\t\t}\n\t\t\t}\n\t\t\tattrs = append(attrs, meta.Name)\n\t\t}\n\t}\n\n\tprimaryKey := res.PrimaryFieldName()\n\n\tmetas := []resource.Metaor{}\n\tfor _, attr := range attrs {\n\t\tvar meta *Meta\n\t\tfor _, m := range res.Metas {\n\t\t\tif m.GetName() == attr {\n\t\t\t\tmeta = m\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif meta == nil {\n\t\t\tmeta = &Meta{}\n\t\t\tmeta.Name = attr\n\t\t\tmeta.base = res\n\t\t\tif attr == primaryKey {\n\t\t\t\tmeta.Type = \"hidden\"\n\t\t\t}\n\t\t\tmeta.updateMeta()\n\t\t}\n\n\t\tmetas = append(metas, meta)\n\t}\n\n\treturn metas\n}\n\nfunc (res *Resource) GetMeta(name string) *Meta {\n\tfor _, meta := range res.Metas {\n\t\tif meta.Name == name || meta.GetFieldName() == name {\n\t\t\treturn meta\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (res *Resource) indexMetas() []*Meta {\n\treturn res.getCachedMetas(\"index_metas\", func() []resource.Metaor {\n\t\treturn res.GetMetas(res.indexAttrs, res.showAttrs)\n\t})\n}\n\nfunc (res *Resource) newMetas() []*Meta {\n\treturn res.getCachedMetas(\"new_metas\", func() []resource.Metaor {\n\t\treturn res.GetMetas(res.newAttrs, res.editAttrs)\n\t})\n}\n\nfunc (res *Resource) editMetas() []*Meta {\n\treturn res.getCachedMetas(\"edit_metas\", func() []resource.Metaor {\n\t\treturn res.GetMetas(res.editAttrs)\n\t})\n}\n\nfunc (res *Resource) showMetas() []*Meta {\n\treturn res.getCachedMetas(\"show_metas\", func() []resource.Metaor {\n\t\treturn res.GetMetas(res.showAttrs, res.editAttrs)\n\t})\n}\n\nfunc (res *Resource) allMetas() []*Meta {\n\treturn res.getCachedMetas(\"all_metas\", func() []resource.Metaor {\n\t\treturn res.GetMetas()\n\t})\n}\n\nfunc (res *Resource) allowedMetas(attrs []*Meta, context *Context, roles ...roles.PermissionMode) []*Meta {\n\tvar metas = []*Meta{}\n\tfor _, meta := range attrs {\n\t\tfor _, role := range roles {\n\t\t\tif meta.HasPermission(role, context.Context) {\n\t\t\t\tmetas = append(metas, meta)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn metas\n}\n\nfunc (res *Resource) HasPermission(mode roles.PermissionMode, context *qor.Context) bool {\n\tif res.Config == nil || res.Config.Permission == nil {\n\t\treturn true\n\t}\n\treturn res.Config.Permission.HasPermission(mode, context.Roles...)\n}\n<commit_msg>Refactor get metas<commit_after>package admin\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/jinzhu\/gorm\"\n\t\"github.com\/jinzhu\/now\"\n\t\"github.com\/qor\/qor\"\n\t\"github.com\/qor\/qor\/resource\"\n\t\"github.com\/qor\/qor\/roles\"\n\t\"github.com\/qor\/qor\/utils\"\n)\n\ntype Resource struct {\n\tresource.Resource\n\tadmin         *Admin\n\tConfig        *Config\n\tMetas         []*Meta\n\tactions       []*Action\n\tscopes        []*Scope\n\tfilters       map[string]*Filter\n\tsearchAttrs   []string\n\tindexAttrs    []string\n\tnewAttrs      []string\n\teditAttrs     []string\n\tshowAttrs     []string\n\tcachedMetas   *map[string][]*Meta\n\tSearchHandler func(keyword string, context *qor.Context) *gorm.DB\n}\n\nfunc (res *Resource) Meta(meta *Meta) {\n\tif res.GetMeta(meta.Name) != nil {\n\t\tutils.ExitWithMsg(\"Duplicated meta %v defined for resource %v\", meta.Name, res.Name)\n\t}\n\n\tmeta.base = res\n\tmeta.updateMeta()\n\tres.Metas = append(res.Metas, meta)\n}\n\nfunc (res Resource) GetAdmin() *Admin {\n\treturn res.admin\n}\n\nfunc (res Resource) ToParam() string {\n\treturn utils.ToParamString(res.Name)\n}\n\nfunc (res Resource) UseTheme(theme string) []string {\n\tif res.Config != nil {\n\t\tres.Config.Themes = append(res.Config.Themes, theme)\n\t\treturn res.Config.Themes\n\t}\n\treturn []string{}\n}\n\nfunc (res *Resource) convertObjectToMap(context *Context, value interface{}, kind string) interface{} {\n\treflectValue := reflect.Indirect(reflect.ValueOf(value))\n\tswitch reflectValue.Kind() {\n\tcase reflect.Slice:\n\t\tvalues := []interface{}{}\n\t\tfor i := 0; i < reflectValue.Len(); i++ {\n\t\t\tvalues = append(values, res.convertObjectToMap(context, reflectValue.Index(i).Interface(), kind))\n\t\t}\n\t\treturn values\n\tcase reflect.Struct:\n\t\tvar metas []*Meta\n\t\tif kind == \"index\" {\n\t\t\tmetas = res.indexMetas()\n\t\t} else if kind == \"show\" {\n\t\t\tmetas = res.showMetas()\n\t\t}\n\n\t\tvalues := map[string]interface{}{}\n\t\tfor _, meta := range metas {\n\t\t\tif meta.HasPermission(roles.Read, context.Context) {\n\t\t\t\tvalue := meta.GetValuer()(value, context.Context)\n\t\t\t\tif meta.Resource != nil {\n\t\t\t\t\tvalue = meta.Resource.(*Resource).convertObjectToMap(context, value, kind)\n\t\t\t\t}\n\t\t\t\tvalues[meta.GetName()] = value\n\t\t\t}\n\t\t}\n\t\treturn values\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"Can't convert %v (%v) to map\", reflectValue, reflectValue.Kind()))\n\t}\n}\n\nfunc (res *Resource) Decode(context *qor.Context, value interface{}) (errs []error) {\n\treturn resource.Decode(context, value, res)\n}\n\nfunc (res *Resource) IndexAttrs(columns ...string) []string {\n\tif len(columns) > 0 {\n\t\tres.indexAttrs = columns\n\t}\n\treturn res.indexAttrs\n}\n\nfunc (res *Resource) NewAttrs(columns ...string) []string {\n\tif len(columns) > 0 {\n\t\tres.newAttrs = columns\n\t}\n\treturn res.newAttrs\n}\n\nfunc (res *Resource) EditAttrs(columns ...string) []string {\n\tif len(columns) > 0 {\n\t\tres.editAttrs = columns\n\t}\n\treturn res.editAttrs\n}\n\nfunc (res *Resource) ShowAttrs(columns ...string) []string {\n\tif len(columns) > 0 {\n\t\tres.showAttrs = columns\n\t}\n\treturn res.showAttrs\n}\n\nfunc (res *Resource) SearchAttrs(columns ...string) []string {\n\tif len(columns) > 0 {\n\t\tres.searchAttrs = columns\n\t\tres.SearchHandler = func(keyword string, context *qor.Context) *gorm.DB {\n\t\t\tdb := context.GetDB()\n\t\t\tvar conditions []string\n\t\t\tvar keywords []interface{}\n\t\t\tscope := db.NewScope(res.Value)\n\n\t\t\tfor _, column := range columns {\n\t\t\t\tif field, ok := scope.FieldByName(column); ok {\n\t\t\t\t\tswitch field.Field.Kind() {\n\t\t\t\t\tcase reflect.String:\n\t\t\t\t\t\tconditions = append(conditions, fmt.Sprintf(\"upper(%v) like upper(?)\", scope.Quote(field.DBName)))\n\t\t\t\t\t\tkeywords = append(keywords, \"%\"+keyword+\"%\")\n\t\t\t\t\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\t\t\t\t\tif _, err := strconv.Atoi(keyword); err == nil {\n\t\t\t\t\t\t\tconditions = append(conditions, fmt.Sprintf(\"%v = ?\", scope.Quote(field.DBName)))\n\t\t\t\t\t\t\tkeywords = append(keywords, keyword)\n\t\t\t\t\t\t}\n\t\t\t\t\tcase reflect.Float32, reflect.Float64:\n\t\t\t\t\t\tif _, err := strconv.ParseFloat(keyword, 64); err == nil {\n\t\t\t\t\t\t\tconditions = append(conditions, fmt.Sprintf(\"%v = ?\", scope.Quote(field.DBName)))\n\t\t\t\t\t\t\tkeywords = append(keywords, keyword)\n\t\t\t\t\t\t}\n\t\t\t\t\tcase reflect.Struct:\n\t\t\t\t\t\t\/\/ time ?\n\t\t\t\t\t\tif _, ok := field.Field.Interface().(time.Time); ok {\n\t\t\t\t\t\t\tif parsedTime, err := now.Parse(keyword); err == nil {\n\t\t\t\t\t\t\t\tconditions = append(conditions, fmt.Sprintf(\"%v = ?\", scope.Quote(field.DBName)))\n\t\t\t\t\t\t\t\tkeywords = append(keywords, parsedTime)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\tcase reflect.Ptr:\n\t\t\t\t\t\t\/\/ time ?\n\t\t\t\t\t\tif _, ok := field.Field.Interface().(*time.Time); ok {\n\t\t\t\t\t\t\tif parsedTime, err := now.Parse(keyword); err == nil {\n\t\t\t\t\t\t\t\tconditions = append(conditions, fmt.Sprintf(\"%v = ?\", scope.Quote(field.DBName)))\n\t\t\t\t\t\t\t\tkeywords = append(keywords, parsedTime)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tconditions = append(conditions, fmt.Sprintf(\"%v = ?\", scope.Quote(field.DBName)))\n\t\t\t\t\t\tkeywords = append(keywords, keyword)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif len(conditions) > 0 {\n\t\t\t\treturn context.GetDB().Where(strings.Join(conditions, \" OR \"), keywords...)\n\t\t\t} else {\n\t\t\t\treturn context.GetDB()\n\t\t\t}\n\t\t}\n\t}\n\treturn res.searchAttrs\n}\n\nfunc (res *Resource) getCachedMetas(cacheKey string, fc func() []resource.Metaor) []*Meta {\n\tif res.cachedMetas == nil {\n\t\tres.cachedMetas = &map[string][]*Meta{}\n\t}\n\n\tif values, ok := (*res.cachedMetas)[cacheKey]; ok {\n\t\treturn values\n\t} else {\n\t\tvalues := fc()\n\t\tvar metas []*Meta\n\t\tfor _, value := range values {\n\t\t\tmetas = append(metas, value.(*Meta))\n\t\t}\n\t\t(*res.cachedMetas)[cacheKey] = metas\n\t\treturn metas\n\t}\n}\n\nfunc (res *Resource) GetMetas(_attrs ...[]string) []resource.Metaor {\n\tvar attrs, ignoredAttrs []string\n\tfor _, value := range _attrs {\n\t\tif len(value) != 0 {\n\t\t\tattrs, ignoredAttrs = []string{}, []string{}\n\t\t\tfor _, v := range value {\n\t\t\t\tif strings.HasPrefix(v, \"-\") {\n\t\t\t\t\tignoredAttrs = append(ignoredAttrs, strings.TrimLeft(v, \"-\"))\n\t\t\t\t} else {\n\t\t\t\t\tattrs = append(attrs, v)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif len(attrs) > 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(attrs) == 0 {\n\t\tscope := &gorm.Scope{Value: res.Value}\n\t\tstructFields := scope.GetModelStruct().StructFields\n\n\tFields:\n\t\tfor _, field := range structFields {\n\t\t\tfor _, meta := range res.Metas {\n\t\t\t\tif field.Name == meta.Alias {\n\t\t\t\t\tattrs = append(attrs, meta.Name)\n\t\t\t\t\tcontinue Fields\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif field.IsForeignKey {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfor _, value := range []string{\"CreatedAt\", \"UpdatedAt\", \"DeletedAt\"} {\n\t\t\t\tif value == field.Name {\n\t\t\t\t\tcontinue Fields\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tattrs = append(attrs, field.Name)\n\t\t}\n\n\tMetaIncluded:\n\t\tfor _, meta := range res.Metas {\n\t\t\tfor _, attr := range attrs {\n\t\t\t\tif attr == meta.Alias || attr == meta.Name {\n\t\t\t\t\tcontinue MetaIncluded\n\t\t\t\t}\n\t\t\t}\n\t\t\tattrs = append(attrs, meta.Name)\n\t\t}\n\t}\n\n\tprimaryKey := res.PrimaryFieldName()\n\n\tmetas := []resource.Metaor{}\nAttrs:\n\tfor _, attr := range attrs {\n\t\tfor _, a := range ignoredAttrs {\n\t\t\tif attr == a {\n\t\t\t\tcontinue Attrs\n\t\t\t}\n\t\t}\n\n\t\tvar meta *Meta\n\t\tfor _, m := range res.Metas {\n\t\t\tif m.GetName() == attr {\n\t\t\t\tmeta = m\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif meta == nil {\n\t\t\tmeta = &Meta{}\n\t\t\tmeta.Name = attr\n\t\t\tmeta.base = res\n\t\t\tif attr == primaryKey {\n\t\t\t\tmeta.Type = \"hidden\"\n\t\t\t}\n\t\t\tmeta.updateMeta()\n\t\t}\n\n\t\tmetas = append(metas, meta)\n\t}\n\n\treturn metas\n}\n\nfunc (res *Resource) GetMeta(name string) *Meta {\n\tfor _, meta := range res.Metas {\n\t\tif meta.Name == name || meta.GetFieldName() == name {\n\t\t\treturn meta\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (res *Resource) indexMetas() []*Meta {\n\treturn res.getCachedMetas(\"index_metas\", func() []resource.Metaor {\n\t\treturn res.GetMetas(res.indexAttrs, res.showAttrs)\n\t})\n}\n\nfunc (res *Resource) newMetas() []*Meta {\n\treturn res.getCachedMetas(\"new_metas\", func() []resource.Metaor {\n\t\treturn res.GetMetas(res.newAttrs, res.editAttrs)\n\t})\n}\n\nfunc (res *Resource) editMetas() []*Meta {\n\treturn res.getCachedMetas(\"edit_metas\", func() []resource.Metaor {\n\t\treturn res.GetMetas(res.editAttrs)\n\t})\n}\n\nfunc (res *Resource) showMetas() []*Meta {\n\treturn res.getCachedMetas(\"show_metas\", func() []resource.Metaor {\n\t\treturn res.GetMetas(res.showAttrs, res.editAttrs)\n\t})\n}\n\nfunc (res *Resource) allMetas() []*Meta {\n\treturn res.getCachedMetas(\"all_metas\", func() []resource.Metaor {\n\t\treturn res.GetMetas()\n\t})\n}\n\nfunc (res *Resource) allowedMetas(attrs []*Meta, context *Context, roles ...roles.PermissionMode) []*Meta {\n\tvar metas = []*Meta{}\n\tfor _, meta := range attrs {\n\t\tfor _, role := range roles {\n\t\t\tif meta.HasPermission(role, context.Context) {\n\t\t\t\tmetas = append(metas, meta)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn metas\n}\n\nfunc (res *Resource) HasPermission(mode roles.PermissionMode, context *qor.Context) bool {\n\tif res.Config == nil || res.Config.Permission == nil {\n\t\treturn true\n\t}\n\treturn res.Config.Permission.HasPermission(mode, context.Roles...)\n}\n<|endoftext|>"}
{"text":"<commit_before>package core\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"math\/big\"\n\t\"sync\"\n\n\t\"github.com\/ethereum\/go-ethereum\/core\/types\"\n\t\"github.com\/ethereum\/go-ethereum\/ethutil\"\n\t\"github.com\/ethereum\/go-ethereum\/event\"\n\t\"github.com\/ethereum\/go-ethereum\/logger\"\n\t\"github.com\/ethereum\/go-ethereum\/rlp\"\n\t\"github.com\/ethereum\/go-ethereum\/state\"\n)\n\nvar chainlogger = logger.NewLogger(\"CHAIN\")\n\ntype StateQuery interface {\n\tGetAccount(addr []byte) *state.StateObject\n}\n\nfunc CalcDifficulty(block, parent *types.Block) *big.Int {\n\tdiff := new(big.Int)\n\n\tbh, ph := block.Header(), parent.Header()\n\tadjust := new(big.Int).Rsh(ph.Difficulty, 10)\n\tif bh.Time >= ph.Time+13 {\n\t\tdiff.Sub(ph.Difficulty, adjust)\n\t} else {\n\t\tdiff.Add(ph.Difficulty, adjust)\n\t}\n\n\treturn diff\n}\n\nfunc CalcGasLimit(parent, block *types.Block) *big.Int {\n\tif block.Number().Cmp(big.NewInt(0)) == 0 {\n\t\treturn ethutil.BigPow(10, 6)\n\t}\n\n\t\/\/ ((1024-1) * parent.gasLimit + (gasUsed * 6 \/ 5)) \/ 1024\n\n\tprevious := new(big.Int).Mul(big.NewInt(1024-1), parent.GasLimit())\n\tcurrent := new(big.Rat).Mul(new(big.Rat).SetInt(parent.GasUsed()), big.NewRat(6, 5))\n\tcurInt := new(big.Int).Div(current.Num(), current.Denom())\n\n\tresult := new(big.Int).Add(previous, curInt)\n\tresult.Div(result, big.NewInt(1024))\n\n\tmin := big.NewInt(125000)\n\n\treturn ethutil.BigMax(min, result)\n}\n\ntype ChainManager struct {\n\t\/\/eth          EthManager\n\tdb           ethutil.Database\n\tprocessor    types.BlockProcessor\n\teventMux     *event.TypeMux\n\tgenesisBlock *types.Block\n\t\/\/ Last known total difficulty\n\tmu              sync.RWMutex\n\ttd              *big.Int\n\tlastBlockNumber uint64\n\tcurrentBlock    *types.Block\n\tlastBlockHash   []byte\n\n\ttransState *state.StateDB\n}\n\nfunc (self *ChainManager) Td() *big.Int {\n\tself.mu.RLock()\n\tdefer self.mu.RUnlock()\n\n\treturn self.td\n}\n\nfunc (self *ChainManager) LastBlockNumber() uint64 {\n\tself.mu.RLock()\n\tdefer self.mu.RUnlock()\n\n\treturn self.lastBlockNumber\n}\n\nfunc (self *ChainManager) LastBlockHash() []byte {\n\tself.mu.RLock()\n\tdefer self.mu.RUnlock()\n\n\treturn self.lastBlockHash\n}\n\nfunc (self *ChainManager) CurrentBlock() *types.Block {\n\tself.mu.RLock()\n\tdefer self.mu.RUnlock()\n\n\treturn self.currentBlock\n}\n\nfunc NewChainManager(db ethutil.Database, mux *event.TypeMux) *ChainManager {\n\tbc := &ChainManager{db: db, genesisBlock: GenesisBlock(db), eventMux: mux}\n\tbc.setLastBlock()\n\tbc.transState = bc.State().Copy()\n\n\treturn bc\n}\n\nfunc (self *ChainManager) Status() (td *big.Int, currentBlock []byte, genesisBlock []byte) {\n\tself.mu.RLock()\n\tdefer self.mu.RUnlock()\n\n\treturn self.td, self.currentBlock.Hash(), self.Genesis().Hash()\n}\n\nfunc (self *ChainManager) SetProcessor(proc types.BlockProcessor) {\n\tself.processor = proc\n}\n\nfunc (self *ChainManager) State() *state.StateDB {\n\treturn state.New(self.CurrentBlock().Root(), self.db)\n}\n\nfunc (self *ChainManager) TransState() *state.StateDB {\n\treturn self.transState\n}\n\nfunc (bc *ChainManager) setLastBlock() {\n\tdata, _ := bc.db.Get([]byte(\"LastBlock\"))\n\tif len(data) != 0 {\n\t\tvar block types.Block\n\t\trlp.Decode(bytes.NewReader(data), &block)\n\t\tbc.currentBlock = &block\n\t\tbc.lastBlockHash = block.Hash()\n\t\tbc.lastBlockNumber = block.Header().Number.Uint64()\n\n\t\t\/\/ Set the last know difficulty (might be 0x0 as initial value, Genesis)\n\t\tbc.td = ethutil.BigD(bc.db.LastKnownTD())\n\t} else {\n\t\tbc.Reset()\n\t}\n\n\tchainlogger.Infof(\"Last block (#%d) %x\\n\", bc.lastBlockNumber, bc.currentBlock.Hash())\n}\n\n\/\/ Block creation & chain handling\nfunc (bc *ChainManager) NewBlock(coinbase []byte) *types.Block {\n\tbc.mu.RLock()\n\tdefer bc.mu.RUnlock()\n\n\tvar root []byte\n\tparentHash := ZeroHash256\n\n\tif bc.CurrentBlock != nil {\n\t\troot = bc.currentBlock.Header().Root\n\t\tparentHash = bc.lastBlockHash\n\t}\n\n\tblock := types.NewBlock(\n\t\tparentHash,\n\t\tcoinbase,\n\t\troot,\n\t\tethutil.BigPow(2, 32),\n\t\tnil,\n\t\t\"\")\n\n\tparent := bc.currentBlock\n\tif parent != nil {\n\t\theader := block.Header()\n\t\theader.Difficulty = CalcDifficulty(block, parent)\n\t\theader.Number = new(big.Int).Add(parent.Header().Number, ethutil.Big1)\n\t\theader.GasLimit = CalcGasLimit(parent, block)\n\n\t}\n\n\treturn block\n}\n\nfunc (bc *ChainManager) Reset() {\n\tbc.mu.Lock()\n\tdefer bc.mu.Unlock()\n\n\tfor block := bc.currentBlock; block != nil; block = bc.GetBlock(block.Header().ParentHash) {\n\t\tbc.db.Delete(block.Hash())\n\t}\n\n\t\/\/ Prepare the genesis block\n\tbc.write(bc.genesisBlock)\n\tbc.insert(bc.genesisBlock)\n\tbc.currentBlock = bc.genesisBlock\n\n\tbc.setTotalDifficulty(ethutil.Big(\"0\"))\n}\n\nfunc (self *ChainManager) Export() []byte {\n\tself.mu.RLock()\n\tdefer self.mu.RUnlock()\n\n\tchainlogger.Infof(\"exporting %v blocks...\\n\", self.currentBlock.Header().Number)\n\n\tblocks := make([]*types.Block, int(self.currentBlock.NumberU64())+1)\n\tfor block := self.currentBlock; block != nil; block = self.GetBlock(block.Header().ParentHash) {\n\t\tblocks[block.NumberU64()] = block\n\t}\n\n\treturn ethutil.Encode(blocks)\n}\n\nfunc (bc *ChainManager) insert(block *types.Block) {\n\tencodedBlock := ethutil.Encode(block)\n\tbc.db.Put([]byte(\"LastBlock\"), encodedBlock)\n\tbc.currentBlock = block\n\tbc.lastBlockHash = block.Hash()\n}\n\nfunc (bc *ChainManager) write(block *types.Block) {\n\tbc.writeBlockInfo(block)\n\n\tencodedBlock := ethutil.Encode(block)\n\tbc.db.Put(block.Hash(), encodedBlock)\n}\n\n\/\/ Accessors\nfunc (bc *ChainManager) Genesis() *types.Block {\n\treturn bc.genesisBlock\n}\n\n\/\/ Block fetching methods\nfunc (bc *ChainManager) HasBlock(hash []byte) bool {\n\tdata, _ := bc.db.Get(hash)\n\treturn len(data) != 0\n}\n\nfunc (self *ChainManager) GetBlockHashesFromHash(hash []byte, max uint64) (chain [][]byte) {\n\tblock := self.GetBlock(hash)\n\tif block == nil {\n\t\treturn\n\t}\n\n\t\/\/ XXX Could be optimised by using a different database which only holds hashes (i.e., linked list)\n\tfor i := uint64(0); i < max; i++ {\n\t\tchain = append(chain, block.Hash())\n\n\t\tif block.Header().Number.Cmp(ethutil.Big0) <= 0 {\n\t\t\tbreak\n\t\t}\n\n\t\tblock = self.GetBlock(block.Header().ParentHash)\n\t}\n\n\treturn\n}\n\nfunc (self *ChainManager) GetBlock(hash []byte) *types.Block {\n\tdata, _ := self.db.Get(hash)\n\tif len(data) == 0 {\n\t\treturn nil\n\t}\n\tvar block types.Block\n\tif err := rlp.Decode(bytes.NewReader(data), &block); err != nil {\n\t\tfmt.Println(err)\n\t\treturn nil\n\t}\n\n\treturn &block\n}\n\nfunc (self *ChainManager) GetBlockByNumber(num uint64) *types.Block {\n\tself.mu.RLock()\n\tdefer self.mu.RUnlock()\n\n\tvar block *types.Block\n\n\tif num <= self.currentBlock.Number().Uint64() {\n\t\tblock = self.currentBlock\n\t\tfor ; block != nil; block = self.GetBlock(block.Header().ParentHash) {\n\t\t\tif block.Header().Number.Uint64() == num {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn block\n}\n\nfunc (bc *ChainManager) setTotalDifficulty(td *big.Int) {\n\tbc.db.Put([]byte(\"LTD\"), td.Bytes())\n\tbc.td = td\n}\n\nfunc (self *ChainManager) CalcTotalDiff(block *types.Block) (*big.Int, error) {\n\tparent := self.GetBlock(block.Header().ParentHash)\n\tif parent == nil {\n\t\treturn nil, fmt.Errorf(\"Unable to calculate total diff without known parent %x\", block.Header().ParentHash)\n\t}\n\n\tparentTd := parent.Td\n\n\tuncleDiff := new(big.Int)\n\tfor _, uncle := range block.Uncles() {\n\t\tuncleDiff = uncleDiff.Add(uncleDiff, uncle.Difficulty)\n\t}\n\n\ttd := new(big.Int)\n\ttd = td.Add(parentTd, uncleDiff)\n\ttd = td.Add(td, block.Header().Difficulty)\n\n\treturn td, nil\n}\n\n\/\/ Unexported method for writing extra non-essential block info to the db\nfunc (bc *ChainManager) writeBlockInfo(block *types.Block) {\n\tbc.lastBlockNumber++\n}\n\nfunc (bc *ChainManager) Stop() {\n\tif bc.CurrentBlock != nil {\n\t\tchainlogger.Infoln(\"Stopped\")\n\t}\n}\n\nfunc (self *ChainManager) InsertChain(chain types.Blocks) error {\n\tfor _, block := range chain {\n\t\ttd, messages, err := self.processor.Process(block)\n\t\tif err != nil {\n\t\t\tif IsKnownBlockErr(err) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\th := block.Header()\n\t\t\tchainlogger.Infof(\"block #%v process failed (%x)\\n\", h.Number, h.Hash()[:4])\n\t\t\tchainlogger.Infoln(block)\n\t\t\tchainlogger.Infoln(err)\n\t\t\treturn err\n\t\t}\n\t\tblock.Td = td\n\n\t\tself.mu.Lock()\n\t\t{\n\t\t\tself.write(block)\n\t\t\tcblock := self.currentBlock\n\t\t\tif td.Cmp(self.td) > 0 {\n\t\t\t\tif block.Header().Number.Cmp(new(big.Int).Add(cblock.Header().Number, ethutil.Big1)) < 0 {\n\t\t\t\t\tchainlogger.Infof(\"Split detected. New head #%v (%x), was #%v (%x)\\n\", block.Header().Number, block.Hash()[:4], cblock.Header().Number, cblock.Hash()[:4])\n\t\t\t\t}\n\n\t\t\t\tself.setTotalDifficulty(td)\n\t\t\t\tself.insert(block)\n\t\t\t\tself.transState = state.New(cblock.Root(), self.db) \/\/state.New(cblock.Trie().Copy())\n\t\t\t}\n\n\t\t}\n\t\tself.mu.Unlock()\n\n\t\tself.eventMux.Post(NewBlockEvent{block})\n\t\tself.eventMux.Post(messages)\n\t}\n\n\treturn nil\n}\n\n\/\/ Satisfy state query interface\nfunc (self *ChainManager) GetAccount(addr []byte) *state.StateObject {\n\treturn self.State().GetAccount(addr)\n}\n<commit_msg>GetBlockHashesFromHash(hash, max) gives back max hashes starting from PARENT of hash<commit_after>package core\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"math\/big\"\n\t\"sync\"\n\n\t\"github.com\/ethereum\/go-ethereum\/core\/types\"\n\t\"github.com\/ethereum\/go-ethereum\/ethutil\"\n\t\"github.com\/ethereum\/go-ethereum\/event\"\n\t\"github.com\/ethereum\/go-ethereum\/logger\"\n\t\"github.com\/ethereum\/go-ethereum\/rlp\"\n\t\"github.com\/ethereum\/go-ethereum\/state\"\n)\n\nvar chainlogger = logger.NewLogger(\"CHAIN\")\n\ntype StateQuery interface {\n\tGetAccount(addr []byte) *state.StateObject\n}\n\nfunc CalcDifficulty(block, parent *types.Block) *big.Int {\n\tdiff := new(big.Int)\n\n\tbh, ph := block.Header(), parent.Header()\n\tadjust := new(big.Int).Rsh(ph.Difficulty, 10)\n\tif bh.Time >= ph.Time+13 {\n\t\tdiff.Sub(ph.Difficulty, adjust)\n\t} else {\n\t\tdiff.Add(ph.Difficulty, adjust)\n\t}\n\n\treturn diff\n}\n\nfunc CalcGasLimit(parent, block *types.Block) *big.Int {\n\tif block.Number().Cmp(big.NewInt(0)) == 0 {\n\t\treturn ethutil.BigPow(10, 6)\n\t}\n\n\t\/\/ ((1024-1) * parent.gasLimit + (gasUsed * 6 \/ 5)) \/ 1024\n\n\tprevious := new(big.Int).Mul(big.NewInt(1024-1), parent.GasLimit())\n\tcurrent := new(big.Rat).Mul(new(big.Rat).SetInt(parent.GasUsed()), big.NewRat(6, 5))\n\tcurInt := new(big.Int).Div(current.Num(), current.Denom())\n\n\tresult := new(big.Int).Add(previous, curInt)\n\tresult.Div(result, big.NewInt(1024))\n\n\tmin := big.NewInt(125000)\n\n\treturn ethutil.BigMax(min, result)\n}\n\ntype ChainManager struct {\n\t\/\/eth          EthManager\n\tdb           ethutil.Database\n\tprocessor    types.BlockProcessor\n\teventMux     *event.TypeMux\n\tgenesisBlock *types.Block\n\t\/\/ Last known total difficulty\n\tmu              sync.RWMutex\n\ttd              *big.Int\n\tlastBlockNumber uint64\n\tcurrentBlock    *types.Block\n\tlastBlockHash   []byte\n\n\ttransState *state.StateDB\n}\n\nfunc (self *ChainManager) Td() *big.Int {\n\tself.mu.RLock()\n\tdefer self.mu.RUnlock()\n\n\treturn self.td\n}\n\nfunc (self *ChainManager) LastBlockNumber() uint64 {\n\tself.mu.RLock()\n\tdefer self.mu.RUnlock()\n\n\treturn self.lastBlockNumber\n}\n\nfunc (self *ChainManager) LastBlockHash() []byte {\n\tself.mu.RLock()\n\tdefer self.mu.RUnlock()\n\n\treturn self.lastBlockHash\n}\n\nfunc (self *ChainManager) CurrentBlock() *types.Block {\n\tself.mu.RLock()\n\tdefer self.mu.RUnlock()\n\n\treturn self.currentBlock\n}\n\nfunc NewChainManager(db ethutil.Database, mux *event.TypeMux) *ChainManager {\n\tbc := &ChainManager{db: db, genesisBlock: GenesisBlock(db), eventMux: mux}\n\tbc.setLastBlock()\n\tbc.transState = bc.State().Copy()\n\n\treturn bc\n}\n\nfunc (self *ChainManager) Status() (td *big.Int, currentBlock []byte, genesisBlock []byte) {\n\tself.mu.RLock()\n\tdefer self.mu.RUnlock()\n\n\treturn self.td, self.currentBlock.Hash(), self.Genesis().Hash()\n}\n\nfunc (self *ChainManager) SetProcessor(proc types.BlockProcessor) {\n\tself.processor = proc\n}\n\nfunc (self *ChainManager) State() *state.StateDB {\n\treturn state.New(self.CurrentBlock().Root(), self.db)\n}\n\nfunc (self *ChainManager) TransState() *state.StateDB {\n\treturn self.transState\n}\n\nfunc (bc *ChainManager) setLastBlock() {\n\tdata, _ := bc.db.Get([]byte(\"LastBlock\"))\n\tif len(data) != 0 {\n\t\tvar block types.Block\n\t\trlp.Decode(bytes.NewReader(data), &block)\n\t\tbc.currentBlock = &block\n\t\tbc.lastBlockHash = block.Hash()\n\t\tbc.lastBlockNumber = block.Header().Number.Uint64()\n\n\t\t\/\/ Set the last know difficulty (might be 0x0 as initial value, Genesis)\n\t\tbc.td = ethutil.BigD(bc.db.LastKnownTD())\n\t} else {\n\t\tbc.Reset()\n\t}\n\n\tchainlogger.Infof(\"Last block (#%d) %x\\n\", bc.lastBlockNumber, bc.currentBlock.Hash())\n}\n\n\/\/ Block creation & chain handling\nfunc (bc *ChainManager) NewBlock(coinbase []byte) *types.Block {\n\tbc.mu.RLock()\n\tdefer bc.mu.RUnlock()\n\n\tvar root []byte\n\tparentHash := ZeroHash256\n\n\tif bc.CurrentBlock != nil {\n\t\troot = bc.currentBlock.Header().Root\n\t\tparentHash = bc.lastBlockHash\n\t}\n\n\tblock := types.NewBlock(\n\t\tparentHash,\n\t\tcoinbase,\n\t\troot,\n\t\tethutil.BigPow(2, 32),\n\t\tnil,\n\t\t\"\")\n\n\tparent := bc.currentBlock\n\tif parent != nil {\n\t\theader := block.Header()\n\t\theader.Difficulty = CalcDifficulty(block, parent)\n\t\theader.Number = new(big.Int).Add(parent.Header().Number, ethutil.Big1)\n\t\theader.GasLimit = CalcGasLimit(parent, block)\n\n\t}\n\n\treturn block\n}\n\nfunc (bc *ChainManager) Reset() {\n\tbc.mu.Lock()\n\tdefer bc.mu.Unlock()\n\n\tfor block := bc.currentBlock; block != nil; block = bc.GetBlock(block.Header().ParentHash) {\n\t\tbc.db.Delete(block.Hash())\n\t}\n\n\t\/\/ Prepare the genesis block\n\tbc.write(bc.genesisBlock)\n\tbc.insert(bc.genesisBlock)\n\tbc.currentBlock = bc.genesisBlock\n\n\tbc.setTotalDifficulty(ethutil.Big(\"0\"))\n}\n\nfunc (self *ChainManager) Export() []byte {\n\tself.mu.RLock()\n\tdefer self.mu.RUnlock()\n\n\tchainlogger.Infof(\"exporting %v blocks...\\n\", self.currentBlock.Header().Number)\n\n\tblocks := make([]*types.Block, int(self.currentBlock.NumberU64())+1)\n\tfor block := self.currentBlock; block != nil; block = self.GetBlock(block.Header().ParentHash) {\n\t\tblocks[block.NumberU64()] = block\n\t}\n\n\treturn ethutil.Encode(blocks)\n}\n\nfunc (bc *ChainManager) insert(block *types.Block) {\n\tencodedBlock := ethutil.Encode(block)\n\tbc.db.Put([]byte(\"LastBlock\"), encodedBlock)\n\tbc.currentBlock = block\n\tbc.lastBlockHash = block.Hash()\n}\n\nfunc (bc *ChainManager) write(block *types.Block) {\n\tbc.writeBlockInfo(block)\n\n\tencodedBlock := ethutil.Encode(block)\n\tbc.db.Put(block.Hash(), encodedBlock)\n}\n\n\/\/ Accessors\nfunc (bc *ChainManager) Genesis() *types.Block {\n\treturn bc.genesisBlock\n}\n\n\/\/ Block fetching methods\nfunc (bc *ChainManager) HasBlock(hash []byte) bool {\n\tdata, _ := bc.db.Get(hash)\n\treturn len(data) != 0\n}\n\nfunc (self *ChainManager) GetBlockHashesFromHash(hash []byte, max uint64) (chain [][]byte) {\n\tblock := self.GetBlock(hash)\n\tif block == nil {\n\t\treturn\n\t}\n\n\t\/\/ XXX Could be optimised by using a different database which only holds hashes (i.e., linked list)\n\tfor i := uint64(0); i < max; i++ {\n\t\tblock = self.GetBlock(block.Header().ParentHash)\n\t\tchain = append(chain, block.Hash())\n\t\tif block.Header().Number.Cmp(ethutil.Big0) <= 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc (self *ChainManager) GetBlock(hash []byte) *types.Block {\n\tdata, _ := self.db.Get(hash)\n\tif len(data) == 0 {\n\t\treturn nil\n\t}\n\tvar block types.Block\n\tif err := rlp.Decode(bytes.NewReader(data), &block); err != nil {\n\t\tfmt.Println(err)\n\t\treturn nil\n\t}\n\n\treturn &block\n}\n\nfunc (self *ChainManager) GetBlockByNumber(num uint64) *types.Block {\n\tself.mu.RLock()\n\tdefer self.mu.RUnlock()\n\n\tvar block *types.Block\n\n\tif num <= self.currentBlock.Number().Uint64() {\n\t\tblock = self.currentBlock\n\t\tfor ; block != nil; block = self.GetBlock(block.Header().ParentHash) {\n\t\t\tif block.Header().Number.Uint64() == num {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn block\n}\n\nfunc (bc *ChainManager) setTotalDifficulty(td *big.Int) {\n\tbc.db.Put([]byte(\"LTD\"), td.Bytes())\n\tbc.td = td\n}\n\nfunc (self *ChainManager) CalcTotalDiff(block *types.Block) (*big.Int, error) {\n\tparent := self.GetBlock(block.Header().ParentHash)\n\tif parent == nil {\n\t\treturn nil, fmt.Errorf(\"Unable to calculate total diff without known parent %x\", block.Header().ParentHash)\n\t}\n\n\tparentTd := parent.Td\n\n\tuncleDiff := new(big.Int)\n\tfor _, uncle := range block.Uncles() {\n\t\tuncleDiff = uncleDiff.Add(uncleDiff, uncle.Difficulty)\n\t}\n\n\ttd := new(big.Int)\n\ttd = td.Add(parentTd, uncleDiff)\n\ttd = td.Add(td, block.Header().Difficulty)\n\n\treturn td, nil\n}\n\n\/\/ Unexported method for writing extra non-essential block info to the db\nfunc (bc *ChainManager) writeBlockInfo(block *types.Block) {\n\tbc.lastBlockNumber++\n}\n\nfunc (bc *ChainManager) Stop() {\n\tif bc.CurrentBlock != nil {\n\t\tchainlogger.Infoln(\"Stopped\")\n\t}\n}\n\nfunc (self *ChainManager) InsertChain(chain types.Blocks) error {\n\tfor _, block := range chain {\n\t\ttd, messages, err := self.processor.Process(block)\n\t\tif err != nil {\n\t\t\tif IsKnownBlockErr(err) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\th := block.Header()\n\t\t\tchainlogger.Infof(\"block #%v process failed (%x)\\n\", h.Number, h.Hash()[:4])\n\t\t\tchainlogger.Infoln(block)\n\t\t\tchainlogger.Infoln(err)\n\t\t\treturn err\n\t\t}\n\t\tblock.Td = td\n\n\t\tself.mu.Lock()\n\t\t{\n\t\t\tself.write(block)\n\t\t\tcblock := self.currentBlock\n\t\t\tif td.Cmp(self.td) > 0 {\n\t\t\t\tif block.Header().Number.Cmp(new(big.Int).Add(cblock.Header().Number, ethutil.Big1)) < 0 {\n\t\t\t\t\tchainlogger.Infof(\"Split detected. New head #%v (%x), was #%v (%x)\\n\", block.Header().Number, block.Hash()[:4], cblock.Header().Number, cblock.Hash()[:4])\n\t\t\t\t}\n\n\t\t\t\tself.setTotalDifficulty(td)\n\t\t\t\tself.insert(block)\n\t\t\t\tself.transState = state.New(cblock.Root(), self.db) \/\/state.New(cblock.Trie().Copy())\n\t\t\t}\n\n\t\t}\n\t\tself.mu.Unlock()\n\n\t\tself.eventMux.Post(NewBlockEvent{block})\n\t\tself.eventMux.Post(messages)\n\t}\n\n\treturn nil\n}\n\n\/\/ Satisfy state query interface\nfunc (self *ChainManager) GetAccount(addr []byte) *state.StateObject {\n\treturn self.State().GetAccount(addr)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2012 Google, Inc. All rights reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license\n\/\/ that can be found in the LICENSE file in the root of the source\n\/\/ tree.\n\n\/\/ +build darwin dragonfly freebsd netbsd openbsd\n\npackage bsdbpf\n\nimport (\n\t\"github.com\/google\/gopacket\"\n\t\"golang.org\/x\/sys\/unix\"\n\n\t\"fmt\"\n\t\"syscall\"\n\t\"time\"\n\t\"unsafe\"\n)\n\nconst wordSize = int(unsafe.Sizeof(uintptr(0)))\n\nfunc bpfWordAlign(x int) int {\n\treturn (((x) + (wordSize - 1)) &^ (wordSize - 1))\n}\n\n\/\/ Options is used to configure various properties of the BPF sniffer.\n\/\/ Default values are used when a nil Options pointer is passed to NewBPFSniffer.\ntype Options struct {\n\t\/\/ BPFDeviceName is name of the bpf device to use for sniffing\n\t\/\/ the network device. The default value of BPFDeviceName is empty string\n\t\/\/ which causes the first available BPF device file \/dev\/bpfX to be used.\n\tBPFDeviceName string\n\t\/\/ ReadBufLen specifies the size of the buffer used to read packets\n\t\/\/ off the wire such that multiple packets are buffered with each read syscall.\n\t\/\/ Note that an individual packet larger than the buffer size is necessarily truncated.\n\t\/\/ A larger buffer should increase performance because fewer read syscalls would be made.\n\t\/\/ If zero is used, the system's default buffer length will be used which depending on the\n\t\/\/ system may default to 4096 bytes which is not big enough to accomodate some link layers\n\t\/\/ such as WLAN (802.11).\n\t\/\/ ReadBufLen defaults to 32767... however typical BSD manual pages for BPF indicate that\n\t\/\/ if the requested buffer size cannot be accommodated, the closest allowable size will be\n\t\/\/ set and returned... hence our GetReadBufLen method.\n\tReadBufLen int\n\t\/\/ Timeout is the length of time to wait before timing out on a read request.\n\t\/\/ Timeout defaults to nil which means no timeout is used.\n\tTimeout *syscall.Timeval\n\t\/\/ Promisc is set to true for promiscuous mode ethernet sniffing.\n\t\/\/ Promisc defaults to true.\n\tPromisc bool\n\t\/\/ Immediate is set to true to make our read requests return as soon as a packet becomes available.\n\t\/\/ Otherwise, a read will block until either the kernel buffer becomes full or a timeout occurs.\n\t\/\/ The default is true.\n\tImmediate bool\n\t\/\/ PreserveLinkAddr is set to false if the link level source address should be filled in automatically\n\t\/\/ by the interface output routine. Set to true if the link level source address will be written,\n\t\/\/ as provided, to the wire.\n\t\/\/ The default is true.\n\tPreserveLinkAddr bool\n}\n\nvar defaultOptions = Options{\n\tBPFDeviceName:    \"\",\n\tReadBufLen:       32767,\n\tTimeout:          nil,\n\tPromisc:          true,\n\tImmediate:        true,\n\tPreserveLinkAddr: true,\n}\n\n\/\/ BPFSniffer is a struct used to track state of a BSD BPF ethernet sniffer\n\/\/ such that gopacket's PacketDataSource interface is implemented.\ntype BPFSniffer struct {\n\toptions           *Options\n\tsniffDeviceName   string\n\tfd                int\n\treadBuffer        []byte\n\tlastReadLen       int\n\treadBytesConsumed int\n}\n\n\/\/ NewBPFSniffer is used to create BSD-only BPF ethernet sniffer\n\/\/ iface is the network interface device name that you wish to sniff\n\/\/ options can set to nil in order to utilize default values for everything.\n\/\/ Each field of Options also have a default setting if left unspecified by\n\/\/ the user's custome Options struct.\nfunc NewBPFSniffer(iface string, options *Options) *BPFSniffer {\n\tsniffer := BPFSniffer{\n\t\tsniffDeviceName: iface,\n\t}\n\tif options == nil {\n\t\tsniffer.options = &defaultOptions\n\t} else {\n\t\tsniffer.options = options\n\t}\n\treturn &sniffer\n}\n\n\/\/ Close is used to close the file-descriptor of the BPF device file.\nfunc (b *BPFSniffer) Close() error {\n\treturn syscall.Close(b.fd)\n}\n\nfunc (b *BPFSniffer) pickBpfDevice() {\n\tvar err error\n\tfor i := 0; i < 99; i++ {\n\t\tb.options.BPFDeviceName = fmt.Sprintf(\"\/dev\/bpf%d\", i)\n\t\tb.fd, err = syscall.Open(b.options.BPFDeviceName, syscall.O_RDWR, 0)\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\t}\n}\n\n\/\/ Init is used to initialize a BPF device for promiscuous sniffing.\n\/\/ It also starts a goroutine to continuously read frames.\nfunc (b *BPFSniffer) Init() error {\n\tvar err error\n\tenable := 1\n\n\tif b.options.BPFDeviceName == \"\" {\n\t\tb.pickBpfDevice()\n\t}\n\n\t\/\/ setup our read buffer\n\tif b.options.ReadBufLen == 0 {\n\t\tb.options.ReadBufLen, err = syscall.BpfBuflen(b.fd)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t} else {\n\t\tb.options.ReadBufLen, err = syscall.SetBpfBuflen(b.fd, b.options.ReadBufLen)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\tb.readBuffer = make([]byte, b.options.ReadBufLen)\n\n\terr = syscall.SetBpfInterface(b.fd, b.sniffDeviceName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif b.options.Immediate {\n\t\t\/\/ turn immediate mode on. This makes the snffer non-blocking.\n\t\terr = syscall.SetBpfImmediate(b.fd, enable)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ the above call to syscall.SetBpfImmediate needs to be made\n\t\/\/ before setting a timer otherwise the reads will block for the\n\t\/\/ entire timer duration even if there are packets to return.\n\tif b.options.Timeout != nil {\n\t\terr = syscall.SetBpfTimeout(b.fd, b.options.Timeout)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tif b.options.PreserveLinkAddr {\n\t\t\/\/ preserves the link level source address...\n\t\t\/\/ higher level protocol analyzers will not need this\n\t\terr = syscall.SetBpfHeadercmpl(b.fd, enable)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif b.options.Promisc {\n\t\t\/\/ forces the interface into promiscuous mode\n\t\terr = syscall.SetBpfPromisc(b.fd, enable)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (b *BPFSniffer) ReadPacketData() ([]byte, gopacket.CaptureInfo, error) {\n\tvar err error\n\tif b.readBytesConsumed >= b.lastReadLen {\n\t\tb.readBytesConsumed = 0\n\t\tb.readBuffer = make([]byte, b.options.ReadBufLen)\n\t\tb.lastReadLen, err = syscall.Read(b.fd, b.readBuffer)\n\t\tif err != nil {\n\t\t\tb.lastReadLen = 0\n\t\t\treturn nil, gopacket.CaptureInfo{}, err\n\t\t}\n\t}\n\thdr := (*unix.BpfHdr)(unsafe.Pointer(&b.readBuffer[b.readBytesConsumed]))\n\tframeStart := b.readBytesConsumed + int(hdr.Hdrlen)\n\tb.readBytesConsumed += bpfWordAlign(int(hdr.Hdrlen) + int(hdr.Caplen))\n\trawFrame := b.readBuffer[frameStart : frameStart+int(hdr.Caplen)]\n\tcaptureInfo := gopacket.CaptureInfo{\n\t\tTimestamp:     time.Unix(int64(hdr.Tstamp.Sec), int64(hdr.Tstamp.Usec)*1000),\n\t\tCaptureLength: len(rawFrame),\n\t\tLength:        len(rawFrame),\n\t}\n\treturn rawFrame, captureInfo, nil\n}\n\n\/\/ GetReadBufLen returns the BPF read buffer length\nfunc (b *BPFSniffer) GetReadBufLen() int {\n\treturn b.options.ReadBufLen\n}\n<commit_msg>Move initialization logic into NewBPFSniffer<commit_after>\/\/ Copyright 2012 Google, Inc. All rights reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license\n\/\/ that can be found in the LICENSE file in the root of the source\n\/\/ tree.\n\n\/\/ +build darwin dragonfly freebsd netbsd openbsd\n\npackage bsdbpf\n\nimport (\n\t\"github.com\/google\/gopacket\"\n\t\"golang.org\/x\/sys\/unix\"\n\n\t\"fmt\"\n\t\"syscall\"\n\t\"time\"\n\t\"unsafe\"\n)\n\nconst wordSize = int(unsafe.Sizeof(uintptr(0)))\n\nfunc bpfWordAlign(x int) int {\n\treturn (((x) + (wordSize - 1)) &^ (wordSize - 1))\n}\n\n\/\/ Options is used to configure various properties of the BPF sniffer.\n\/\/ Default values are used when a nil Options pointer is passed to NewBPFSniffer.\ntype Options struct {\n\t\/\/ BPFDeviceName is name of the bpf device to use for sniffing\n\t\/\/ the network device. The default value of BPFDeviceName is empty string\n\t\/\/ which causes the first available BPF device file \/dev\/bpfX to be used.\n\tBPFDeviceName string\n\t\/\/ ReadBufLen specifies the size of the buffer used to read packets\n\t\/\/ off the wire such that multiple packets are buffered with each read syscall.\n\t\/\/ Note that an individual packet larger than the buffer size is necessarily truncated.\n\t\/\/ A larger buffer should increase performance because fewer read syscalls would be made.\n\t\/\/ If zero is used, the system's default buffer length will be used which depending on the\n\t\/\/ system may default to 4096 bytes which is not big enough to accomodate some link layers\n\t\/\/ such as WLAN (802.11).\n\t\/\/ ReadBufLen defaults to 32767... however typical BSD manual pages for BPF indicate that\n\t\/\/ if the requested buffer size cannot be accommodated, the closest allowable size will be\n\t\/\/ set and returned... hence our GetReadBufLen method.\n\tReadBufLen int\n\t\/\/ Timeout is the length of time to wait before timing out on a read request.\n\t\/\/ Timeout defaults to nil which means no timeout is used.\n\tTimeout *syscall.Timeval\n\t\/\/ Promisc is set to true for promiscuous mode ethernet sniffing.\n\t\/\/ Promisc defaults to true.\n\tPromisc bool\n\t\/\/ Immediate is set to true to make our read requests return as soon as a packet becomes available.\n\t\/\/ Otherwise, a read will block until either the kernel buffer becomes full or a timeout occurs.\n\t\/\/ The default is true.\n\tImmediate bool\n\t\/\/ PreserveLinkAddr is set to false if the link level source address should be filled in automatically\n\t\/\/ by the interface output routine. Set to true if the link level source address will be written,\n\t\/\/ as provided, to the wire.\n\t\/\/ The default is true.\n\tPreserveLinkAddr bool\n}\n\nvar defaultOptions = Options{\n\tBPFDeviceName:    \"\",\n\tReadBufLen:       32767,\n\tTimeout:          nil,\n\tPromisc:          true,\n\tImmediate:        true,\n\tPreserveLinkAddr: true,\n}\n\n\/\/ BPFSniffer is a struct used to track state of a BSD BPF ethernet sniffer\n\/\/ such that gopacket's PacketDataSource interface is implemented.\ntype BPFSniffer struct {\n\toptions           *Options\n\tsniffDeviceName   string\n\tfd                int\n\treadBuffer        []byte\n\tlastReadLen       int\n\treadBytesConsumed int\n}\n\n\/\/ NewBPFSniffer is used to create BSD-only BPF ethernet sniffer\n\/\/ iface is the network interface device name that you wish to sniff\n\/\/ options can set to nil in order to utilize default values for everything.\n\/\/ Each field of Options also have a default setting if left unspecified by\n\/\/ the user's custome Options struct.\nfunc NewBPFSniffer(iface string, options *Options) (*BPFSniffer, error) {\n\tvar err error\n\tenable := 1\n\tsniffer := BPFSniffer{\n\t\tsniffDeviceName: iface,\n\t}\n\tif options == nil {\n\t\tsniffer.options = &defaultOptions\n\t} else {\n\t\tsniffer.options = options\n\t}\n\n\tif sniffer.options.BPFDeviceName == \"\" {\n\t\tsniffer.pickBpfDevice()\n\t}\n\n\t\/\/ setup our read buffer\n\tif sniffer.options.ReadBufLen == 0 {\n\t\tsniffer.options.ReadBufLen, err = syscall.BpfBuflen(sniffer.fd)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tsniffer.options.ReadBufLen, err = syscall.SetBpfBuflen(sniffer.fd, sniffer.options.ReadBufLen)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tsniffer.readBuffer = make([]byte, sniffer.options.ReadBufLen)\n\n\terr = syscall.SetBpfInterface(sniffer.fd, sniffer.sniffDeviceName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif sniffer.options.Immediate {\n\t\t\/\/ turn immediate mode on. This makes the snffer non-blocking.\n\t\terr = syscall.SetBpfImmediate(sniffer.fd, enable)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t\/\/ the above call to syscall.SetBpfImmediate needs to be made\n\t\/\/ before setting a timer otherwise the reads will block for the\n\t\/\/ entire timer duration even if there are packets to return.\n\tif sniffer.options.Timeout != nil {\n\t\terr = syscall.SetBpfTimeout(sniffer.fd, sniffer.options.Timeout)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif sniffer.options.PreserveLinkAddr {\n\t\t\/\/ preserves the link level source address...\n\t\t\/\/ higher level protocol analyzers will not need this\n\t\terr = syscall.SetBpfHeadercmpl(sniffer.fd, enable)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif sniffer.options.Promisc {\n\t\t\/\/ forces the interface into promiscuous mode\n\t\terr = syscall.SetBpfPromisc(sniffer.fd, enable)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &sniffer, nil\n}\n\n\/\/ Close is used to close the file-descriptor of the BPF device file.\nfunc (b *BPFSniffer) Close() error {\n\treturn syscall.Close(b.fd)\n}\n\nfunc (b *BPFSniffer) pickBpfDevice() {\n\tvar err error\n\tfor i := 0; i < 99; i++ {\n\t\tb.options.BPFDeviceName = fmt.Sprintf(\"\/dev\/bpf%d\", i)\n\t\tb.fd, err = syscall.Open(b.options.BPFDeviceName, syscall.O_RDWR, 0)\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc (b *BPFSniffer) ReadPacketData() ([]byte, gopacket.CaptureInfo, error) {\n\tvar err error\n\tif b.readBytesConsumed >= b.lastReadLen {\n\t\tb.readBytesConsumed = 0\n\t\tb.readBuffer = make([]byte, b.options.ReadBufLen)\n\t\tb.lastReadLen, err = syscall.Read(b.fd, b.readBuffer)\n\t\tif err != nil {\n\t\t\tb.lastReadLen = 0\n\t\t\treturn nil, gopacket.CaptureInfo{}, err\n\t\t}\n\t}\n\thdr := (*unix.BpfHdr)(unsafe.Pointer(&b.readBuffer[b.readBytesConsumed]))\n\tframeStart := b.readBytesConsumed + int(hdr.Hdrlen)\n\tb.readBytesConsumed += bpfWordAlign(int(hdr.Hdrlen) + int(hdr.Caplen))\n\trawFrame := b.readBuffer[frameStart : frameStart+int(hdr.Caplen)]\n\tcaptureInfo := gopacket.CaptureInfo{\n\t\tTimestamp:     time.Unix(int64(hdr.Tstamp.Sec), int64(hdr.Tstamp.Usec)*1000),\n\t\tCaptureLength: len(rawFrame),\n\t\tLength:        len(rawFrame),\n\t}\n\treturn rawFrame, captureInfo, nil\n}\n\n\/\/ GetReadBufLen returns the BPF read buffer length\nfunc (b *BPFSniffer) GetReadBufLen() int {\n\treturn b.options.ReadBufLen\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2017 Istio Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage platform\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"reflect\"\n\t\"testing\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/ec2metadata\"\n\t\"github.com\/aws\/aws-sdk-go\/awstesting\/unit\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"google.golang.org\/grpc\"\n\t\"google.golang.org\/grpc\/credentials\"\n)\n\nconst (\n\tdoc = `{\n  \"devpayProductCodes\" : null,\n  \"privateIp\" : \"10.16.17.248\",\n  \"availabilityZone\" : \"us-west-2b\",\n  \"version\" : \"2010-08-31\",\n  \"instanceId\" : \"i-0646c9efe2e62dc63\",\n  \"billingProducts\" : null,\n  \"instanceType\" : \"c3.large\",\n  \"accountId\" : \"977777657611\",\n  \"architecture\" : \"x86_64\",\n  \"kernelId\" : null,\n  \"ramdiskId\" : null,\n  \"imageId\" : \"ami-fabf5c82\",\n  \"pendingTime\" : \"2017-08-27T17:18:20Z\",\n  \"region\" : \"us-west-2\"\n}`\n)\n\nfunc initTestServer(resp map[string][]byte) *httptest.Server {\n\treturn httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif _, ok := resp[r.RequestURI]; !ok {\n\t\t\thttp.Error(w, \"not found\", http.StatusNotFound)\n\t\t\treturn\n\t\t}\n\n\t\t_, _ = w.Write(resp[r.RequestURI])\n\t}))\n}\n\nfunc TestIsProperPlatform(t *testing.T) {\n\tserver := initTestServer(\n\t\tmap[string][]byte{\n\t\t\t\"\/latest\/meta-data\/instance-id\": []byte(\"instance-id\"),\n\t\t},\n\t)\n\n\tc := ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + \"\/latest\")})\n\tna := &AwsClientImpl{client: c}\n\tif !na.IsProperPlatform() {\n\t\tt.Errorf(\"On Proper Platform: expected true\")\n\t}\n\n\tserver.Close()\n\tif na.IsProperPlatform() {\n\t\tt.Errorf(\"On Proper Platform: expected false\")\n\t}\n}\n\nfunc TestNewAwsClientImpl(t *testing.T) {\n\tclient := NewAwsClientImpl(\"\")\n\tif client == nil {\n\t\tt.Errorf(\"NewAwsClientImpl should not return nil\")\n\t}\n}\n\nfunc TestAwsGetInstanceIdentityDocument(t *testing.T) {\n\tt.Skip(\"https:\/\/github.com\/istio\/istio\/issues\/3177\")\n\ttestCases := map[string]struct {\n\t\tsigFile              string\n\t\tdoc                  string\n\t\texpectedErr          string\n\t\texpectedInstanceType string\n\t\texpectedRegion       string\n\t\texpectedCredential   string\n\t}{\n\t\t\"Good Identity\": {\n\t\t\tsigFile:              \"testdata\/sig.pem\",\n\t\t\tdoc:                  doc,\n\t\t\texpectedErr:          \"\",\n\t\t\texpectedInstanceType: \"c3.large\",\n\t\t\texpectedRegion:       \"us-west-2\",\n\t\t\texpectedCredential: \"\\\"ewogICJkZXZwYXlQcm9kdWN0Q29kZXMiIDogbnVsbCwKICAicHJpdmF0ZUlwIiA6ICIx\" +\n\t\t\t\t\"MC4xNi4xNy4yNDgiLAogICJhdmFpbGFiaWxpdHlab25lIiA6ICJ1cy13ZXN0LTJiIiwKICAidmVyc2lvbiIgOi\" +\n\t\t\t\t\"AiMjAxMC0wOC0zMSIsCiAgImluc3RhbmNlSWQiIDogImktMDY0NmM5ZWZlMmU2MmRjNjMiLAogICJiaWxsaW5n\" +\n\t\t\t\t\"UHJvZHVjdHMiIDogbnVsbCwKICAiaW5zdGFuY2VUeXBlIiA6ICJjMy5sYXJnZSIsCiAgImFjY291bnRJZCIgOi\" +\n\t\t\t\t\"AiOTc3Nzc3NjU3NjExIiwKICAiYXJjaGl0ZWN0dXJlIiA6ICJ4ODZfNjQiLAogICJrZXJuZWxJZCIgOiBudWxs\" +\n\t\t\t\t\"LAogICJyYW1kaXNrSWQiIDogbnVsbCwKICAiaW1hZ2VJZCIgOiAiYW1pLWZhYmY1YzgyIiwKICAicGVuZGluZ1\" +\n\t\t\t\t\"RpbWUiIDogIjIwMTctMDgtMjdUMTc6MTg6MjBaIiwKICAicmVnaW9uIiA6ICJ1cy13ZXN0LTIiCn0=\\\"\",\n\t\t},\n\t}\n\n\tfor id, c := range testCases {\n\t\tsigBytes, err := ioutil.ReadFile(c.sigFile)\n\t\tassert.Equal(t, err, nil, fmt.Sprintf(\"%v: Unable to read file %s\", id, c.sigFile))\n\n\t\tserver := initTestServer(map[string][]byte{\n\t\t\t\"\/latest\/dynamic\/instance-identity\/document\":  []byte(c.doc),\n\t\t\t\"\/latest\/dynamic\/instance-identity\/signature\": sigBytes,\n\t\t})\n\t\tdefer server.Close()\n\n\t\tawsc := &AwsClientImpl{\n\t\t\tclient: ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + \"\/latest\")}),\n\t\t}\n\n\t\tdocBytes, err := awsc.getInstanceIdentityDocument()\n\t\tif len(c.expectedErr) > 0 {\n\t\t\tif err == nil {\n\t\t\t\tt.Errorf(\"%s: Succeeded. Error expected: %v\", id, err)\n\t\t\t} else if err.Error() != c.expectedErr {\n\t\t\t\tt.Errorf(\"%s: incorrect error message: %s VS %s\",\n\t\t\t\t\tid, err.Error(), c.expectedErr)\n\t\t\t}\n\t\t\tcontinue\n\t\t} else if err != nil {\n\t\t\tt.Fatalf(\"%s: Unexpected Error: %v\", id, err)\n\t\t}\n\n\t\tdoc := ec2metadata.EC2InstanceIdentityDocument{}\n\t\tdecode := json.NewDecoder(bytes.NewReader(docBytes)).Decode(&doc)\n\t\tif decode != nil {\n\t\t\tt.Fatalf(\"%s: Unexpected Error: %v\", id, err)\n\t\t}\n\n\t\tif doc.InstanceType != c.expectedInstanceType {\n\t\t\tt.Errorf(\"%s: Wrong Instance Type. Expected %s, Actual %s\", id, c.expectedInstanceType, doc.InstanceType)\n\t\t}\n\n\t\tif doc.Region != c.expectedRegion {\n\t\t\tt.Errorf(\"%s: Wrong Region. Expected %s, Actual %s\", id, c.expectedRegion, doc.Region)\n\t\t}\n\t}\n}\n\nfunc TestAwsGetServiceIdentity(t *testing.T) {\n\ttestCases := map[string]struct {\n\t\tsigFile                 string\n\t\tdoc                     string\n\t\trequestPath             string\n\t\texpectedErr             string\n\t\texpectedServiceIdentity string\n\t}{\n\t\t\"Good CredentialTypes\": {\n\t\t\tsigFile:                 \"testdata\/sig.pem\",\n\t\t\tdoc:                     doc,\n\t\t\trequestPath:             \"\/latest\/dynamic\/instance-identity\/pkcs7\",\n\t\t\texpectedErr:             \"\",\n\t\t\texpectedServiceIdentity: \"\",\n\t\t},\n\t}\n\n\tfor id, c := range testCases {\n\t\tsigBytes, err := ioutil.ReadFile(c.sigFile)\n\t\tassert.Equal(t, err, nil, fmt.Sprintf(\"%v: Unable to read file %s\", id, c.sigFile))\n\n\t\tserver := initTestServer(map[string][]byte{\n\t\t\t\"\/latest\/dynamic\/instance-identity\/document\":  []byte(c.doc),\n\t\t\t\"\/latest\/dynamic\/instance-identity\/signature\": sigBytes,\n\t\t})\n\t\tdefer server.Close()\n\n\t\tawsc := &AwsClientImpl{\n\t\t\tclient: ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + \"\/latest\")}),\n\t\t}\n\n\t\tserviceIdentity, err := awsc.GetServiceIdentity()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"%s: Unexpected Error: %v\", id, err)\n\t\t} else if serviceIdentity != c.expectedServiceIdentity {\n\t\t\tt.Errorf(\"%s: Wrong Service Identity. Expected %v, Actual %v\", id,\n\t\t\t\tstring(c.expectedServiceIdentity), string(serviceIdentity))\n\t\t}\n\t}\n}\n\nfunc TestGetGetAgentCredential(t *testing.T) {\n\tt.Skip(\"https:\/\/github.com\/istio\/istio\/issues\/3177\")\n\ttestCases := map[string]struct {\n\t\tsigFile            string\n\t\tdoc                string\n\t\trequestPath        string\n\t\texpectedErr        string\n\t\texpectedCredential string\n\t}{\n\t\t\"Good Identity\": {\n\t\t\tsigFile:     \"testdata\/sig.pem\",\n\t\t\tdoc:         doc,\n\t\t\trequestPath: \"\/latest\/dynamic\/instance-identity\/pkcs7\",\n\t\t\texpectedErr: \"\",\n\t\t\texpectedCredential: \"\\\"ewogICJkZXZwYXlQcm9kdWN0Q29kZXMiIDogbnVsbCwKICAicHJpdmF0ZUlwIiA6ICIx\" +\n\t\t\t\t\"MC4xNi4xNy4yNDgiLAogICJhdmFpbGFiaWxpdHlab25lIiA6ICJ1cy13ZXN0LTJiIiwKICAidmVyc2lvbiIgOi\" +\n\t\t\t\t\"AiMjAxMC0wOC0zMSIsCiAgImluc3RhbmNlSWQiIDogImktMDY0NmM5ZWZlMmU2MmRjNjMiLAogICJiaWxsaW5n\" +\n\t\t\t\t\"UHJvZHVjdHMiIDogbnVsbCwKICAiaW5zdGFuY2VUeXBlIiA6ICJjMy5sYXJnZSIsCiAgImFjY291bnRJZCIgOi\" +\n\t\t\t\t\"AiOTc3Nzc3NjU3NjExIiwKICAiYXJjaGl0ZWN0dXJlIiA6ICJ4ODZfNjQiLAogICJrZXJuZWxJZCIgOiBudWxs\" +\n\t\t\t\t\"LAogICJyYW1kaXNrSWQiIDogbnVsbCwKICAiaW1hZ2VJZCIgOiAiYW1pLWZhYmY1YzgyIiwKICAicGVuZGluZ1\" +\n\t\t\t\t\"RpbWUiIDogIjIwMTctMDgtMjdUMTc6MTg6MjBaIiwKICAicmVnaW9uIiA6ICJ1cy13ZXN0LTIiCn0=\\\"\",\n\t\t},\n\t}\n\n\tfor id, c := range testCases {\n\t\tsigBytes, err := ioutil.ReadFile(c.sigFile)\n\t\tassert.Equal(t, err, nil, fmt.Sprintf(\"%v: Unable to read file %s\", id, c.sigFile))\n\n\t\tserver := initTestServer(map[string][]byte{\n\t\t\t\"\/latest\/dynamic\/instance-identity\/document\":  []byte(c.doc),\n\t\t\t\"\/latest\/dynamic\/instance-identity\/signature\": sigBytes,\n\t\t})\n\t\tdefer server.Close()\n\n\t\tawsc := &AwsClientImpl{\n\t\t\tclient: ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + \"\/latest\")}),\n\t\t}\n\n\t\tcredential, err := awsc.GetAgentCredential()\n\t\tif len(c.expectedErr) > 0 {\n\t\t\tif err == nil {\n\t\t\t\tt.Errorf(\"%s: Succeeded. Error expected: %v\", id, err)\n\t\t\t} else if err.Error() != c.expectedErr {\n\t\t\t\tt.Errorf(\"%s: incorrect error message: %s VS %s\",\n\t\t\t\t\tid, err.Error(), c.expectedErr)\n\t\t\t}\n\t\t\tcontinue\n\t\t} else if err != nil {\n\t\t\tt.Fatalf(\"%s: Unexpected Error: %v\", id, err)\n\t\t}\n\n\t\tif string(credential) != c.expectedCredential {\n\t\t\tt.Errorf(\"%s: Wrong Credential. Expected %s, Actual %s\", id, c.expectedCredential, string(credential))\n\t\t}\n\t}\n}\n\nfunc TestAwsGetDialOptions(t *testing.T) {\n\tcreds, err := credentials.NewClientTLSFromFile(\"testdata\/cert-chain-good.pem\", \"\")\n\tif err != nil {\n\t\tt.Fatal(\"Unable to get credential for testdata\/cert-chain-good.pem\")\n\t}\n\n\ttestCases := map[string]struct {\n\t\texpectedErr     string\n\t\trootCertFile    string\n\t\texpectedOptions []grpc.DialOption\n\t}{\n\t\t\"Good DialOptions\": {\n\t\t\texpectedErr:  \"\",\n\t\t\trootCertFile: \"testdata\/cert-chain-good.pem\",\n\t\t\texpectedOptions: []grpc.DialOption{\n\t\t\t\tgrpc.WithTransportCredentials(creds),\n\t\t\t},\n\t\t},\n\t\t\"Bad DialOptions\": {\n\t\t\texpectedErr:  \"open testdata\/cert-chain-good_not_exist.pem: no such file or directory\",\n\t\t\trootCertFile: \"testdata\/cert-chain-good_not_exist.pem\",\n\t\t\texpectedOptions: []grpc.DialOption{\n\t\t\t\tgrpc.WithTransportCredentials(creds),\n\t\t\t},\n\t\t},\n\t}\n\n\tfor id, c := range testCases {\n\t\tawsc := &AwsClientImpl{\n\t\t\trootCertFile: c.rootCertFile,\n\t\t\tclient:       ec2metadata.New(unit.Session, &aws.Config{}),\n\t\t}\n\n\t\toptions, err := awsc.GetDialOptions()\n\t\tif len(c.expectedErr) > 0 {\n\t\t\tif err == nil {\n\t\t\t\tt.Errorf(\"%s: Succeeded. Error expected: %v\", id, err)\n\t\t\t} else if err.Error() != c.expectedErr {\n\t\t\t\tt.Errorf(\"%s: Incorrect error message: %s VS %s\", id, err.Error(), c.expectedErr)\n\t\t\t}\n\t\t\tcontinue\n\t\t} else if err != nil {\n\t\t\tt.Fatalf(\"%s: Unexpected Error: %v\", id, err)\n\t\t}\n\n\t\tif len(options) != len(c.expectedOptions) {\n\t\t\tt.Fatalf(\"%s: Wrong dial options size. Expected %v, Actual %v\",\n\t\t\t\tid, len(c.expectedOptions), len(options))\n\t\t}\n\n\t\tfor index, option := range c.expectedOptions {\n\t\t\tif reflect.ValueOf(options[index]).Pointer() != reflect.ValueOf(option).Pointer() {\n\t\t\t\tt.Errorf(\"%s: Wrong option found\", id)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestAwsGetCredentialTypes(t *testing.T) {\n\ttestCases := map[string]struct {\n\t\texpectedType string\n\t}{\n\t\t\"Good CredentialTypes\": {\n\t\t\texpectedType: \"aws\",\n\t\t},\n\t}\n\n\tfor id, c := range testCases {\n\t\tawsc := &AwsClientImpl{\n\t\t\tclient: ec2metadata.New(unit.Session, &aws.Config{}),\n\t\t}\n\n\t\tcredentialType := awsc.GetCredentialType()\n\t\tif credentialType != c.expectedType {\n\t\t\tt.Errorf(\"%s: Wrong Credential Type. Expected %v, Actual %v\", id,\n\t\t\t\tstring(c.expectedType), string(credentialType))\n\t\t}\n\t}\n}\n<commit_msg>Add back tests (#4905)<commit_after>\/\/ Copyright 2017 Istio Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage platform\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"reflect\"\n\t\"testing\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/ec2metadata\"\n\t\"github.com\/aws\/aws-sdk-go\/awstesting\/unit\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"google.golang.org\/grpc\"\n\t\"google.golang.org\/grpc\/credentials\"\n)\n\nconst (\n\tdoc = `{\n  \"devpayProductCodes\" : null,\n  \"privateIp\" : \"10.16.17.248\",\n  \"availabilityZone\" : \"us-west-2b\",\n  \"version\" : \"2010-08-31\",\n  \"instanceId\" : \"i-0646c9efe2e62dc63\",\n  \"billingProducts\" : null,\n  \"instanceType\" : \"c3.large\",\n  \"accountId\" : \"977777657611\",\n  \"architecture\" : \"x86_64\",\n  \"kernelId\" : null,\n  \"ramdiskId\" : null,\n  \"imageId\" : \"ami-fabf5c82\",\n  \"pendingTime\" : \"2017-08-27T17:18:20Z\",\n  \"region\" : \"us-west-2\"\n}`\n)\n\nfunc initTestServer(resp map[string][]byte) *httptest.Server {\n\treturn httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif _, ok := resp[r.RequestURI]; !ok {\n\t\t\thttp.Error(w, \"not found\", http.StatusNotFound)\n\t\t\treturn\n\t\t}\n\n\t\t_, _ = w.Write(resp[r.RequestURI])\n\t}))\n}\n\nfunc TestIsProperPlatform(t *testing.T) {\n\tserver := initTestServer(\n\t\tmap[string][]byte{\n\t\t\t\"\/latest\/meta-data\/instance-id\": []byte(\"instance-id\"),\n\t\t},\n\t)\n\n\tc := ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + \"\/latest\")})\n\tna := &AwsClientImpl{client: c}\n\tif !na.IsProperPlatform() {\n\t\tt.Errorf(\"On Proper Platform: expected true\")\n\t}\n\n\tserver.Close()\n\tif na.IsProperPlatform() {\n\t\tt.Errorf(\"On Proper Platform: expected false\")\n\t}\n}\n\nfunc TestNewAwsClientImpl(t *testing.T) {\n\tclient := NewAwsClientImpl(\"\")\n\tif client == nil {\n\t\tt.Errorf(\"NewAwsClientImpl should not return nil\")\n\t}\n}\n\nfunc TestAwsGetInstanceIdentityDocument(t *testing.T) {\n\ttestCases := map[string]struct {\n\t\tsigFile              string\n\t\tdoc                  string\n\t\texpectedErr          string\n\t\texpectedInstanceType string\n\t\texpectedRegion       string\n\t\texpectedCredential   string\n\t}{\n\t\t\"Good Identity\": {\n\t\t\tsigFile:              \"testdata\/sig.pem\",\n\t\t\tdoc:                  doc,\n\t\t\texpectedErr:          \"\",\n\t\t\texpectedInstanceType: \"c3.large\",\n\t\t\texpectedRegion:       \"us-west-2\",\n\t\t\texpectedCredential: \"\\\"ewogICJkZXZwYXlQcm9kdWN0Q29kZXMiIDogbnVsbCwKICAicHJpdmF0ZUlwIiA6ICIx\" +\n\t\t\t\t\"MC4xNi4xNy4yNDgiLAogICJhdmFpbGFiaWxpdHlab25lIiA6ICJ1cy13ZXN0LTJiIiwKICAidmVyc2lvbiIgOi\" +\n\t\t\t\t\"AiMjAxMC0wOC0zMSIsCiAgImluc3RhbmNlSWQiIDogImktMDY0NmM5ZWZlMmU2MmRjNjMiLAogICJiaWxsaW5n\" +\n\t\t\t\t\"UHJvZHVjdHMiIDogbnVsbCwKICAiaW5zdGFuY2VUeXBlIiA6ICJjMy5sYXJnZSIsCiAgImFjY291bnRJZCIgOi\" +\n\t\t\t\t\"AiOTc3Nzc3NjU3NjExIiwKICAiYXJjaGl0ZWN0dXJlIiA6ICJ4ODZfNjQiLAogICJrZXJuZWxJZCIgOiBudWxs\" +\n\t\t\t\t\"LAogICJyYW1kaXNrSWQiIDogbnVsbCwKICAiaW1hZ2VJZCIgOiAiYW1pLWZhYmY1YzgyIiwKICAicGVuZGluZ1\" +\n\t\t\t\t\"RpbWUiIDogIjIwMTctMDgtMjdUMTc6MTg6MjBaIiwKICAicmVnaW9uIiA6ICJ1cy13ZXN0LTIiCn0=\\\"\",\n\t\t},\n\t}\n\n\tfor id, c := range testCases {\n\t\tsigBytes, err := ioutil.ReadFile(c.sigFile)\n\t\tassert.Equal(t, err, nil, fmt.Sprintf(\"%v: Unable to read file %s\", id, c.sigFile))\n\n\t\tserver := initTestServer(map[string][]byte{\n\t\t\t\"\/latest\/dynamic\/instance-identity\/document\":  []byte(c.doc),\n\t\t\t\"\/latest\/dynamic\/instance-identity\/signature\": sigBytes,\n\t\t})\n\t\tdefer server.Close()\n\n\t\tawsc := &AwsClientImpl{\n\t\t\tclient: ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + \"\/latest\")}),\n\t\t}\n\n\t\tdocBytes, err := awsc.getInstanceIdentityDocument()\n\t\tif len(c.expectedErr) > 0 {\n\t\t\tif err == nil {\n\t\t\t\tt.Errorf(\"%s: Succeeded. Error expected: %v\", id, err)\n\t\t\t} else if err.Error() != c.expectedErr {\n\t\t\t\tt.Errorf(\"%s: incorrect error message: %s VS %s\",\n\t\t\t\t\tid, err.Error(), c.expectedErr)\n\t\t\t}\n\t\t\tcontinue\n\t\t} else if err != nil {\n\t\t\tt.Fatalf(\"%s: Unexpected Error: %v\", id, err)\n\t\t}\n\n\t\tdoc := ec2metadata.EC2InstanceIdentityDocument{}\n\t\tdecode := json.NewDecoder(bytes.NewReader(docBytes)).Decode(&doc)\n\t\tif decode != nil {\n\t\t\tt.Fatalf(\"%s: Unexpected Error: %v\", id, err)\n\t\t}\n\n\t\tif doc.InstanceType != c.expectedInstanceType {\n\t\t\tt.Errorf(\"%s: Wrong Instance Type. Expected %s, Actual %s\", id, c.expectedInstanceType, doc.InstanceType)\n\t\t}\n\n\t\tif doc.Region != c.expectedRegion {\n\t\t\tt.Errorf(\"%s: Wrong Region. Expected %s, Actual %s\", id, c.expectedRegion, doc.Region)\n\t\t}\n\t}\n}\n\nfunc TestAwsGetServiceIdentity(t *testing.T) {\n\ttestCases := map[string]struct {\n\t\tsigFile                 string\n\t\tdoc                     string\n\t\trequestPath             string\n\t\texpectedErr             string\n\t\texpectedServiceIdentity string\n\t}{\n\t\t\"Good CredentialTypes\": {\n\t\t\tsigFile:                 \"testdata\/sig.pem\",\n\t\t\tdoc:                     doc,\n\t\t\trequestPath:             \"\/latest\/dynamic\/instance-identity\/pkcs7\",\n\t\t\texpectedErr:             \"\",\n\t\t\texpectedServiceIdentity: \"\",\n\t\t},\n\t}\n\n\tfor id, c := range testCases {\n\t\tsigBytes, err := ioutil.ReadFile(c.sigFile)\n\t\tassert.Equal(t, err, nil, fmt.Sprintf(\"%v: Unable to read file %s\", id, c.sigFile))\n\n\t\tserver := initTestServer(map[string][]byte{\n\t\t\t\"\/latest\/dynamic\/instance-identity\/document\":  []byte(c.doc),\n\t\t\t\"\/latest\/dynamic\/instance-identity\/signature\": sigBytes,\n\t\t})\n\t\tdefer server.Close()\n\n\t\tawsc := &AwsClientImpl{\n\t\t\tclient: ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + \"\/latest\")}),\n\t\t}\n\n\t\tserviceIdentity, err := awsc.GetServiceIdentity()\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"%s: Unexpected Error: %v\", id, err)\n\t\t} else if serviceIdentity != c.expectedServiceIdentity {\n\t\t\tt.Errorf(\"%s: Wrong Service Identity. Expected %v, Actual %v\", id,\n\t\t\t\tstring(c.expectedServiceIdentity), string(serviceIdentity))\n\t\t}\n\t}\n}\n\nfunc TestGetGetAgentCredential(t *testing.T) {\n\ttestCases := map[string]struct {\n\t\tsigFile            string\n\t\tdoc                string\n\t\trequestPath        string\n\t\texpectedErr        string\n\t\texpectedCredential string\n\t}{\n\t\t\"Good Identity\": {\n\t\t\tsigFile:     \"testdata\/sig.pem\",\n\t\t\tdoc:         doc,\n\t\t\trequestPath: \"\/latest\/dynamic\/instance-identity\/pkcs7\",\n\t\t\texpectedErr: \"\",\n\t\t\texpectedCredential: \"\\\"ewogICJkZXZwYXlQcm9kdWN0Q29kZXMiIDogbnVsbCwKICAicHJpdmF0ZUlwIiA6ICIx\" +\n\t\t\t\t\"MC4xNi4xNy4yNDgiLAogICJhdmFpbGFiaWxpdHlab25lIiA6ICJ1cy13ZXN0LTJiIiwKICAidmVyc2lvbiIgOi\" +\n\t\t\t\t\"AiMjAxMC0wOC0zMSIsCiAgImluc3RhbmNlSWQiIDogImktMDY0NmM5ZWZlMmU2MmRjNjMiLAogICJiaWxsaW5n\" +\n\t\t\t\t\"UHJvZHVjdHMiIDogbnVsbCwKICAiaW5zdGFuY2VUeXBlIiA6ICJjMy5sYXJnZSIsCiAgImFjY291bnRJZCIgOi\" +\n\t\t\t\t\"AiOTc3Nzc3NjU3NjExIiwKICAiYXJjaGl0ZWN0dXJlIiA6ICJ4ODZfNjQiLAogICJrZXJuZWxJZCIgOiBudWxs\" +\n\t\t\t\t\"LAogICJyYW1kaXNrSWQiIDogbnVsbCwKICAiaW1hZ2VJZCIgOiAiYW1pLWZhYmY1YzgyIiwKICAicGVuZGluZ1\" +\n\t\t\t\t\"RpbWUiIDogIjIwMTctMDgtMjdUMTc6MTg6MjBaIiwKICAicmVnaW9uIiA6ICJ1cy13ZXN0LTIiCn0=\\\"\",\n\t\t},\n\t}\n\n\tfor id, c := range testCases {\n\t\tsigBytes, err := ioutil.ReadFile(c.sigFile)\n\t\tassert.Equal(t, err, nil, fmt.Sprintf(\"%v: Unable to read file %s\", id, c.sigFile))\n\n\t\tserver := initTestServer(map[string][]byte{\n\t\t\t\"\/latest\/dynamic\/instance-identity\/document\":  []byte(c.doc),\n\t\t\t\"\/latest\/dynamic\/instance-identity\/signature\": sigBytes,\n\t\t})\n\t\tdefer server.Close()\n\n\t\tawsc := &AwsClientImpl{\n\t\t\tclient: ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(server.URL + \"\/latest\")}),\n\t\t}\n\n\t\tcredential, err := awsc.GetAgentCredential()\n\t\tif len(c.expectedErr) > 0 {\n\t\t\tif err == nil {\n\t\t\t\tt.Errorf(\"%s: Succeeded. Error expected: %v\", id, err)\n\t\t\t} else if err.Error() != c.expectedErr {\n\t\t\t\tt.Errorf(\"%s: incorrect error message: %s VS %s\",\n\t\t\t\t\tid, err.Error(), c.expectedErr)\n\t\t\t}\n\t\t\tcontinue\n\t\t} else if err != nil {\n\t\t\tt.Fatalf(\"%s: Unexpected Error: %v\", id, err)\n\t\t}\n\n\t\tif string(credential) != c.expectedCredential {\n\t\t\tt.Errorf(\"%s: Wrong Credential. Expected %s, Actual %s\", id, c.expectedCredential, string(credential))\n\t\t}\n\t}\n}\n\nfunc TestAwsGetDialOptions(t *testing.T) {\n\tcreds, err := credentials.NewClientTLSFromFile(\"testdata\/cert-chain-good.pem\", \"\")\n\tif err != nil {\n\t\tt.Fatal(\"Unable to get credential for testdata\/cert-chain-good.pem\")\n\t}\n\n\ttestCases := map[string]struct {\n\t\texpectedErr     string\n\t\trootCertFile    string\n\t\texpectedOptions []grpc.DialOption\n\t}{\n\t\t\"Good DialOptions\": {\n\t\t\texpectedErr:  \"\",\n\t\t\trootCertFile: \"testdata\/cert-chain-good.pem\",\n\t\t\texpectedOptions: []grpc.DialOption{\n\t\t\t\tgrpc.WithTransportCredentials(creds),\n\t\t\t},\n\t\t},\n\t\t\"Bad DialOptions\": {\n\t\t\texpectedErr:  \"open testdata\/cert-chain-good_not_exist.pem: no such file or directory\",\n\t\t\trootCertFile: \"testdata\/cert-chain-good_not_exist.pem\",\n\t\t\texpectedOptions: []grpc.DialOption{\n\t\t\t\tgrpc.WithTransportCredentials(creds),\n\t\t\t},\n\t\t},\n\t}\n\n\tfor id, c := range testCases {\n\t\tawsc := &AwsClientImpl{\n\t\t\trootCertFile: c.rootCertFile,\n\t\t\tclient:       ec2metadata.New(unit.Session, &aws.Config{}),\n\t\t}\n\n\t\toptions, err := awsc.GetDialOptions()\n\t\tif len(c.expectedErr) > 0 {\n\t\t\tif err == nil {\n\t\t\t\tt.Errorf(\"%s: Succeeded. Error expected: %v\", id, err)\n\t\t\t} else if err.Error() != c.expectedErr {\n\t\t\t\tt.Errorf(\"%s: Incorrect error message: %s VS %s\", id, err.Error(), c.expectedErr)\n\t\t\t}\n\t\t\tcontinue\n\t\t} else if err != nil {\n\t\t\tt.Fatalf(\"%s: Unexpected Error: %v\", id, err)\n\t\t}\n\n\t\tif len(options) != len(c.expectedOptions) {\n\t\t\tt.Fatalf(\"%s: Wrong dial options size. Expected %v, Actual %v\",\n\t\t\t\tid, len(c.expectedOptions), len(options))\n\t\t}\n\n\t\tfor index, option := range c.expectedOptions {\n\t\t\tif reflect.ValueOf(options[index]).Pointer() != reflect.ValueOf(option).Pointer() {\n\t\t\t\tt.Errorf(\"%s: Wrong option found\", id)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestAwsGetCredentialTypes(t *testing.T) {\n\ttestCases := map[string]struct {\n\t\texpectedType string\n\t}{\n\t\t\"Good CredentialTypes\": {\n\t\t\texpectedType: \"aws\",\n\t\t},\n\t}\n\n\tfor id, c := range testCases {\n\t\tawsc := &AwsClientImpl{\n\t\t\tclient: ec2metadata.New(unit.Session, &aws.Config{}),\n\t\t}\n\n\t\tcredentialType := awsc.GetCredentialType()\n\t\tif credentialType != c.expectedType {\n\t\t\tt.Errorf(\"%s: Wrong Credential Type. Expected %v, Actual %v\", id,\n\t\t\t\tstring(c.expectedType), string(credentialType))\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package discordgo\n\nimport (\n\t\"os\"\n\t\"runtime\"\n\t\"sync\/atomic\"\n\t\"testing\"\n\t\"time\"\n)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ VARS NEEDED FOR TESTING\nvar (\n\tdg *Session \/\/ Stores global discordgo session\n\n\tenvToken    = os.Getenv(\"DG_TOKEN\")    \/\/ Token to use when authenticating\n\tenvEmail    = os.Getenv(\"DG_EMAIL\")    \/\/ Email to use when authenticating\n\tenvPassword = os.Getenv(\"DG_PASSWORD\") \/\/ Password to use when authenticating\n\tenvGuild    = os.Getenv(\"DG_GUILD\")    \/\/ Guild ID to use for tests\n\tenvChannel  = os.Getenv(\"DG_CHANNEL\")  \/\/ Channel ID to use for tests\n\t\/\/\tenvUser     = os.Getenv(\"DG_USER\")     \/\/ User ID to use for tests\n\tenvAdmin = os.Getenv(\"DG_ADMIN\") \/\/ User ID of admin user to use for tests\n)\n\nfunc init() {\n\tif envEmail == \"\" || envPassword == \"\" || envToken == \"\" {\n\t\treturn\n\t}\n\n\tif d, err := New(envEmail, envPassword, envToken); err == nil {\n\t\tdg = d\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ START OF TESTS\n\n\/\/ TestNew tests the New() function without any arguments.  This should return\n\/\/ a valid Session{} struct and no errors.\nfunc TestNew(t *testing.T) {\n\n\t_, err := New()\n\tif err != nil {\n\t\tt.Errorf(\"New() returned error: %+v\", err)\n\t}\n}\n\n\/\/ TestInvalidToken tests the New() function with an invalid token\nfunc TestInvalidToken(t *testing.T) {\n\td, err := New(\"asjkldhflkjasdh\")\n\tif err != nil {\n\t\tt.Fatalf(\"New(InvalidToken) returned error: %+v\", err)\n\t}\n\n\t\/\/ New with just a token does not do any communication, so attempt an api call.\n\t_, err = d.UserSettings()\n\tif err == nil {\n\t\tt.Errorf(\"New(InvalidToken), d.UserSettings returned nil error.\")\n\t}\n}\n\n\/\/ TestInvalidUserPass tests the New() function with an invalid Email and Pass\nfunc TestInvalidEmailPass(t *testing.T) {\n\n\t_, err := New(\"invalidemail\", \"invalidpassword\")\n\tif err == nil {\n\t\tt.Errorf(\"New(InvalidEmail, InvalidPass) returned nil error.\")\n\t}\n\n}\n\n\/\/ TestInvalidPass tests the New() function with an invalid Password\nfunc TestInvalidPass(t *testing.T) {\n\n\tif envEmail == \"\" {\n\t\tt.Skip(\"Skipping New(username,InvalidPass), DG_EMAIL not set\")\n\t\treturn\n\t}\n\t_, err := New(envEmail, \"invalidpassword\")\n\tif err == nil {\n\t\tt.Errorf(\"New(Email, InvalidPass) returned nil error.\")\n\t}\n}\n\n\/\/ TestNewUserPass tests the New() function with a username and password.\n\/\/ This should return a valid Session{}, a valid Session.Token.\nfunc TestNewUserPass(t *testing.T) {\n\n\tif envEmail == \"\" || envPassword == \"\" {\n\t\tt.Skip(\"Skipping New(username,password), DG_EMAIL or DG_PASSWORD not set\")\n\t\treturn\n\t}\n\n\td, err := New(envEmail, envPassword)\n\tif err != nil {\n\t\tt.Fatalf(\"New(user,pass) returned error: %+v\", err)\n\t}\n\n\tif d == nil {\n\t\tt.Fatal(\"New(user,pass), d is nil, should be Session{}\")\n\t}\n\n\tif d.Token == \"\" {\n\t\tt.Fatal(\"New(user,pass), d.Token is empty, should be a valid Token.\")\n\t}\n}\n\n\/\/ TestNewToken tests the New() function with a Token.  This should return\n\/\/ the same as the TestNewUserPass function.\nfunc TestNewToken(t *testing.T) {\n\n\tif envToken == \"\" {\n\t\tt.Skip(\"Skipping New(token), DG_TOKEN not set\")\n\t}\n\n\td, err := New(envToken)\n\tif err != nil {\n\t\tt.Fatalf(\"New(envToken) returned error: %+v\", err)\n\t}\n\n\tif d == nil {\n\t\tt.Fatal(\"New(envToken), d is nil, should be Session{}\")\n\t}\n\n\tif d.Token == \"\" {\n\t\tt.Fatal(\"New(envToken), d.Token is empty, should be a valid Token.\")\n\t}\n}\n\n\/\/ TestNewUserPassToken tests the New() function with a username, password and token.\n\/\/ This should return the same as the TestNewUserPass function.\nfunc TestNewUserPassToken(t *testing.T) {\n\n\tif envEmail == \"\" || envPassword == \"\" || envToken == \"\" {\n\t\tt.Skip(\"Skipping New(username,password,token), DG_EMAIL, DG_PASSWORD or DG_TOKEN not set\")\n\t\treturn\n\t}\n\n\td, err := New(envEmail, envPassword, envToken)\n\tif err != nil {\n\t\tt.Fatalf(\"New(user,pass,token) returned error: %+v\", err)\n\t}\n\n\tif d == nil {\n\t\tt.Fatal(\"New(user,pass,token), d is nil, should be Session{}\")\n\t}\n\n\tif d.Token == \"\" {\n\t\tt.Fatal(\"New(user,pass,token), d.Token is empty, should be a valid Token.\")\n\t}\n}\n\nfunc TestOpenClose(t *testing.T) {\n\tif envToken == \"\" {\n\t\tt.Skip(\"Skipping TestClose, DG_TOKEN not set\")\n\t}\n\n\td, err := New(envToken)\n\tif err != nil {\n\t\tt.Fatalf(\"TestClose, New(envToken) returned error: %+v\", err)\n\t}\n\n\tif err = d.Open(); err != nil {\n\t\tt.Fatalf(\"TestClose, d.Open failed: %+v\", err)\n\t}\n\n\t\/\/ We need a better way to know the session is ready for use,\n\t\/\/ this is totally gross.\n\tstart := time.Now()\n\tfor {\n\t\td.RLock()\n\t\tif d.DataReady {\n\t\t\td.RUnlock()\n\t\t\tbreak\n\t\t}\n\t\td.RUnlock()\n\n\t\tif time.Since(start) > 10*time.Second {\n\t\t\tt.Fatal(\"DataReady never became true.yy\")\n\t\t}\n\t\truntime.Gosched()\n\t}\n\n\t\/\/ TODO find a better way\n\t\/\/ Add a small sleep here to make sure heartbeat and other events\n\t\/\/ have enough time to get fired.  Need a way to actually check\n\t\/\/ those events.\n\ttime.Sleep(2 * time.Second)\n\n\t\/\/ UpdateStatus - maybe we move this into wsapi_test.go but the websocket\n\t\/\/ created here is needed.  This helps tests that the websocket was setup\n\t\/\/ and it is working.\n\tif err = d.UpdateStatus(0, time.Now().String()); err != nil {\n\t\tt.Errorf(\"UpdateStatus error: %+v\", err)\n\t}\n\n\tif err = d.Close(); err != nil {\n\t\tt.Fatalf(\"TestClose, d.Close failed: %+v\", err)\n\t}\n}\n\nfunc TestAddHandler(t *testing.T) {\n\n\ttestHandlerCalled := int32(0)\n\ttestHandler := func(s *Session, m *MessageCreate) {\n\t\tatomic.AddInt32(&testHandlerCalled, 1)\n\t}\n\n\tinterfaceHandlerCalled := int32(0)\n\tinterfaceHandler := func(s *Session, i interface{}) {\n\t\tatomic.AddInt32(&interfaceHandlerCalled, 1)\n\t}\n\n\tbogusHandlerCalled := int32(0)\n\tbogusHandler := func(s *Session, se *Session) {\n\t\tatomic.AddInt32(&bogusHandlerCalled, 1)\n\t}\n\n\td := Session{}\n\td.AddHandler(testHandler)\n\td.AddHandler(testHandler)\n\n\td.AddHandler(interfaceHandler)\n\td.AddHandler(bogusHandler)\n\n\td.handleEvent(messageCreateEventType, &MessageCreate{})\n\td.handleEvent(messageDeleteEventType, &MessageDelete{})\n\n\t<-time.After(500 * time.Millisecond)\n\n\t\/\/ testHandler will be called twice because it was added twice.\n\tif atomic.LoadInt32(&testHandlerCalled) != 2 {\n\t\tt.Fatalf(\"testHandler was not called twice.\")\n\t}\n\n\t\/\/ interfaceHandler will be called twice, once for each event.\n\tif atomic.LoadInt32(&interfaceHandlerCalled) != 2 {\n\t\tt.Fatalf(\"interfaceHandler was not called twice.\")\n\t}\n\n\tif atomic.LoadInt32(&bogusHandlerCalled) != 0 {\n\t\tt.Fatalf(\"bogusHandler was called.\")\n\t}\n}\n\nfunc TestRemoveHandler(t *testing.T) {\n\n\ttestHandlerCalled := int32(0)\n\ttestHandler := func(s *Session, m *MessageCreate) {\n\t\tatomic.AddInt32(&testHandlerCalled, 1)\n\t}\n\n\td := Session{}\n\tr := d.AddHandler(testHandler)\n\n\td.handleEvent(messageCreateEventType, &MessageCreate{})\n\n\tr()\n\n\td.handleEvent(messageCreateEventType, &MessageCreate{})\n\n\t<-time.After(500 * time.Millisecond)\n\n\t\/\/ testHandler will be called once, as it was removed in between calls.\n\tif atomic.LoadInt32(&testHandlerCalled) != 1 {\n\t\tt.Fatalf(\"testHandler was not called once.\")\n\t}\n}\n<commit_msg>Add bot account to testing<commit_after>package discordgo\n\nimport (\n\t\"os\"\n\t\"runtime\"\n\t\"sync\/atomic\"\n\t\"testing\"\n\t\"time\"\n)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ VARS NEEDED FOR TESTING\nvar (\n\tdg    *Session \/\/ Stores a global discordgo user session\n\tdgBot *Session \/\/ Stores a global discordgo bot session\n\n\tenvToken    = os.Getenv(\"DG_TOKEN\")    \/\/ Token to use when authenticating the user account\n\tenvBotToken = os.Getenv(\"DGB_TOKEN\")   \/\/ Token to use when authenticating the bot account\n\tenvEmail    = os.Getenv(\"DG_EMAIL\")    \/\/ Email to use when authenticating\n\tenvPassword = os.Getenv(\"DG_PASSWORD\") \/\/ Password to use when authenticating\n\tenvGuild    = os.Getenv(\"DG_GUILD\")    \/\/ Guild ID to use for tests\n\tenvChannel  = os.Getenv(\"DG_CHANNEL\")  \/\/ Channel ID to use for tests\n\t\/\/\tenvUser     = os.Getenv(\"DG_USER\")     \/\/ User ID to use for tests\n\tenvAdmin = os.Getenv(\"DG_ADMIN\") \/\/ User ID of admin user to use for tests\n)\n\nfunc init() {\n\tif envBotToken != \"\" {\n\t\tif d, err := New(envBotToken); err == nil {\n\t\t\tdgBot = d\n\t\t}\n\t}\n\n\tif envEmail == \"\" || envPassword == \"\" || envToken == \"\" {\n\t\treturn\n\t}\n\n\tif d, err := New(envEmail, envPassword, envToken); err == nil {\n\t\tdg = d\n\t}\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ START OF TESTS\n\n\/\/ TestNew tests the New() function without any arguments.  This should return\n\/\/ a valid Session{} struct and no errors.\nfunc TestNew(t *testing.T) {\n\n\t_, err := New()\n\tif err != nil {\n\t\tt.Errorf(\"New() returned error: %+v\", err)\n\t}\n}\n\n\/\/ TestInvalidToken tests the New() function with an invalid token\nfunc TestInvalidToken(t *testing.T) {\n\td, err := New(\"asjkldhflkjasdh\")\n\tif err != nil {\n\t\tt.Fatalf(\"New(InvalidToken) returned error: %+v\", err)\n\t}\n\n\t\/\/ New with just a token does not do any communication, so attempt an api call.\n\t_, err = d.UserSettings()\n\tif err == nil {\n\t\tt.Errorf(\"New(InvalidToken), d.UserSettings returned nil error.\")\n\t}\n}\n\n\/\/ TestInvalidUserPass tests the New() function with an invalid Email and Pass\nfunc TestInvalidEmailPass(t *testing.T) {\n\n\t_, err := New(\"invalidemail\", \"invalidpassword\")\n\tif err == nil {\n\t\tt.Errorf(\"New(InvalidEmail, InvalidPass) returned nil error.\")\n\t}\n\n}\n\n\/\/ TestInvalidPass tests the New() function with an invalid Password\nfunc TestInvalidPass(t *testing.T) {\n\n\tif envEmail == \"\" {\n\t\tt.Skip(\"Skipping New(username,InvalidPass), DG_EMAIL not set\")\n\t\treturn\n\t}\n\t_, err := New(envEmail, \"invalidpassword\")\n\tif err == nil {\n\t\tt.Errorf(\"New(Email, InvalidPass) returned nil error.\")\n\t}\n}\n\n\/\/ TestNewUserPass tests the New() function with a username and password.\n\/\/ This should return a valid Session{}, a valid Session.Token.\nfunc TestNewUserPass(t *testing.T) {\n\n\tif envEmail == \"\" || envPassword == \"\" {\n\t\tt.Skip(\"Skipping New(username,password), DG_EMAIL or DG_PASSWORD not set\")\n\t\treturn\n\t}\n\n\td, err := New(envEmail, envPassword)\n\tif err != nil {\n\t\tt.Fatalf(\"New(user,pass) returned error: %+v\", err)\n\t}\n\n\tif d == nil {\n\t\tt.Fatal(\"New(user,pass), d is nil, should be Session{}\")\n\t}\n\n\tif d.Token == \"\" {\n\t\tt.Fatal(\"New(user,pass), d.Token is empty, should be a valid Token.\")\n\t}\n}\n\n\/\/ TestNewToken tests the New() function with a Token.  This should return\n\/\/ the same as the TestNewUserPass function.\nfunc TestNewToken(t *testing.T) {\n\n\tif envToken == \"\" {\n\t\tt.Skip(\"Skipping New(token), DG_TOKEN not set\")\n\t}\n\n\td, err := New(envToken)\n\tif err != nil {\n\t\tt.Fatalf(\"New(envToken) returned error: %+v\", err)\n\t}\n\n\tif d == nil {\n\t\tt.Fatal(\"New(envToken), d is nil, should be Session{}\")\n\t}\n\n\tif d.Token == \"\" {\n\t\tt.Fatal(\"New(envToken), d.Token is empty, should be a valid Token.\")\n\t}\n}\n\n\/\/ TestNewUserPassToken tests the New() function with a username, password and token.\n\/\/ This should return the same as the TestNewUserPass function.\nfunc TestNewUserPassToken(t *testing.T) {\n\n\tif envEmail == \"\" || envPassword == \"\" || envToken == \"\" {\n\t\tt.Skip(\"Skipping New(username,password,token), DG_EMAIL, DG_PASSWORD or DG_TOKEN not set\")\n\t\treturn\n\t}\n\n\td, err := New(envEmail, envPassword, envToken)\n\tif err != nil {\n\t\tt.Fatalf(\"New(user,pass,token) returned error: %+v\", err)\n\t}\n\n\tif d == nil {\n\t\tt.Fatal(\"New(user,pass,token), d is nil, should be Session{}\")\n\t}\n\n\tif d.Token == \"\" {\n\t\tt.Fatal(\"New(user,pass,token), d.Token is empty, should be a valid Token.\")\n\t}\n}\n\nfunc TestOpenClose(t *testing.T) {\n\tif envToken == \"\" {\n\t\tt.Skip(\"Skipping TestClose, DG_TOKEN not set\")\n\t}\n\n\td, err := New(envToken)\n\tif err != nil {\n\t\tt.Fatalf(\"TestClose, New(envToken) returned error: %+v\", err)\n\t}\n\n\tif err = d.Open(); err != nil {\n\t\tt.Fatalf(\"TestClose, d.Open failed: %+v\", err)\n\t}\n\n\t\/\/ We need a better way to know the session is ready for use,\n\t\/\/ this is totally gross.\n\tstart := time.Now()\n\tfor {\n\t\td.RLock()\n\t\tif d.DataReady {\n\t\t\td.RUnlock()\n\t\t\tbreak\n\t\t}\n\t\td.RUnlock()\n\n\t\tif time.Since(start) > 10*time.Second {\n\t\t\tt.Fatal(\"DataReady never became true.yy\")\n\t\t}\n\t\truntime.Gosched()\n\t}\n\n\t\/\/ TODO find a better way\n\t\/\/ Add a small sleep here to make sure heartbeat and other events\n\t\/\/ have enough time to get fired.  Need a way to actually check\n\t\/\/ those events.\n\ttime.Sleep(2 * time.Second)\n\n\t\/\/ UpdateStatus - maybe we move this into wsapi_test.go but the websocket\n\t\/\/ created here is needed.  This helps tests that the websocket was setup\n\t\/\/ and it is working.\n\tif err = d.UpdateStatus(0, time.Now().String()); err != nil {\n\t\tt.Errorf(\"UpdateStatus error: %+v\", err)\n\t}\n\n\tif err = d.Close(); err != nil {\n\t\tt.Fatalf(\"TestClose, d.Close failed: %+v\", err)\n\t}\n}\n\nfunc TestAddHandler(t *testing.T) {\n\n\ttestHandlerCalled := int32(0)\n\ttestHandler := func(s *Session, m *MessageCreate) {\n\t\tatomic.AddInt32(&testHandlerCalled, 1)\n\t}\n\n\tinterfaceHandlerCalled := int32(0)\n\tinterfaceHandler := func(s *Session, i interface{}) {\n\t\tatomic.AddInt32(&interfaceHandlerCalled, 1)\n\t}\n\n\tbogusHandlerCalled := int32(0)\n\tbogusHandler := func(s *Session, se *Session) {\n\t\tatomic.AddInt32(&bogusHandlerCalled, 1)\n\t}\n\n\td := Session{}\n\td.AddHandler(testHandler)\n\td.AddHandler(testHandler)\n\n\td.AddHandler(interfaceHandler)\n\td.AddHandler(bogusHandler)\n\n\td.handleEvent(messageCreateEventType, &MessageCreate{})\n\td.handleEvent(messageDeleteEventType, &MessageDelete{})\n\n\t<-time.After(500 * time.Millisecond)\n\n\t\/\/ testHandler will be called twice because it was added twice.\n\tif atomic.LoadInt32(&testHandlerCalled) != 2 {\n\t\tt.Fatalf(\"testHandler was not called twice.\")\n\t}\n\n\t\/\/ interfaceHandler will be called twice, once for each event.\n\tif atomic.LoadInt32(&interfaceHandlerCalled) != 2 {\n\t\tt.Fatalf(\"interfaceHandler was not called twice.\")\n\t}\n\n\tif atomic.LoadInt32(&bogusHandlerCalled) != 0 {\n\t\tt.Fatalf(\"bogusHandler was called.\")\n\t}\n}\n\nfunc TestRemoveHandler(t *testing.T) {\n\n\ttestHandlerCalled := int32(0)\n\ttestHandler := func(s *Session, m *MessageCreate) {\n\t\tatomic.AddInt32(&testHandlerCalled, 1)\n\t}\n\n\td := Session{}\n\tr := d.AddHandler(testHandler)\n\n\td.handleEvent(messageCreateEventType, &MessageCreate{})\n\n\tr()\n\n\td.handleEvent(messageCreateEventType, &MessageCreate{})\n\n\t<-time.After(500 * time.Millisecond)\n\n\t\/\/ testHandler will be called once, as it was removed in between calls.\n\tif atomic.LoadInt32(&testHandlerCalled) != 1 {\n\t\tt.Fatalf(\"testHandler was not called once.\")\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"strings\"\n\t\"syscall\"\n\n\tex \"github.com\/Lafeng\/deblocus\/exception\"\n\tlog \"github.com\/Lafeng\/deblocus\/glog\"\n\t. \"github.com\/Lafeng\/deblocus\/tunnel\"\n\t\"github.com\/codegangsta\/cli\"\n)\n\nvar (\n\tcontext = &bootContext{}\n\tsigChan = make(chan os.Signal)\n)\n\ntype Component interface {\n\tStats() string\n\tClose()\n}\n\ntype bootContext struct {\n\tconfigFile string\n\tlogdir     string\n\tdebug      bool\n\tshowVer    bool\n\tvSpecified bool\n\tvFlag      int\n\tcman       *ConfigMan\n\tcomponents []Component\n\tcloseable  []io.Closer\n}\n\n\/\/ global before handler\nfunc (ctx *bootContext) initialize(c *cli.Context) (err error) {\n\t\/\/ inject parameters into package.tunnel\n\tVER_STRING = versionString()\n\tVERSION = version\n\tDEBUG = ctx.debug\n\t\/\/ inject parameters into package.exception\n\tex.DEBUG = ctx.debug\n\t\/\/ glog\n\tctx.vSpecified = c.IsSet(\"v\")\n\tlog.SetLogOutput(ctx.logdir)\n\tlog.SetLogVerbose(ctx.vFlag)\n\treturn nil\n}\n\nfunc (ctx *bootContext) initConfig(r ServerRole) (role ServerRole) {\n\tvar err error\n\t\/\/ load config file\n\tctx.cman, err = DetectConfig(ctx.configFile)\n\tfatalError(err)\n\t\/\/ parse config file\n\trole, err = ctx.cman.InitConfigByRole(r)\n\tif role == 0 {\n\t\terr = fmt.Errorf(\"No server role defined in config\")\n\t}\n\tfatalError(err)\n\tif !ctx.vSpecified { \/\/ no -v\n\t\t\/\/ set logV with config.v\n\t\tif v := ctx.cman.LogV(role); v > 0 {\n\t\t\tlog.SetLogVerbose(v)\n\t\t}\n\t}\n\treturn role\n}\n\n\/\/ .\/deblocus -csc [algo]\nfunc (ctx *bootContext) cscCommandHandler(c *cli.Context) {\n\tkeyType := c.String(\"type\")\n\toutput := getOutputArg(c)\n\terr := CreateServerConfigTemplate(output, keyType)\n\tfatalError(err)\n}\n\n\/\/ .\/deblocus -ccc SERV_ADDR:PORT USER\nfunc (ctx *bootContext) cccCommandHandler(c *cli.Context) {\n\t\/\/ need server config\n\tctx.initConfig(SR_SERVER)\n\tif args := c.Args(); len(args) == 1 {\n\t\tuser := args.Get(0)\n\t\tpubAddr := c.String(\"addr\")\n\t\toutput := getOutputArg(c)\n\t\terr := ctx.cman.CreateClientConfig(output, user, pubAddr)\n\t\tfatalError(err)\n\t} else {\n\t\tfatalAndCommandHelp(c)\n\t}\n}\n\nfunc (ctx *bootContext) keyInfoCommandHandler(c *cli.Context) {\n\t\/\/ need config\n\trole := ctx.initConfig(SR_AUTO)\n\tfmt.Fprintln(os.Stderr, ctx.cman.KeyInfo(role))\n}\n\nfunc (ctx *bootContext) startCommandHandler(c *cli.Context) {\n\tif len(c.Args()) > 0 {\n\t\tfatalAndCommandHelp(c)\n\t}\n\t\/\/ option as pseudo-command: help, version\n\tif ctx.showVer {\n\t\tfmt.Fprintln(os.Stderr, versionString())\n\t\treturn\n\t}\n\n\trole := ctx.initConfig(SR_AUTO)\n\tif role&SR_SERVER != 0 {\n\t\tgo ctx.startServer()\n\t}\n\tif role&SR_CLIENT != 0 {\n\t\tgo ctx.startClient()\n\t}\n\twaitSignal()\n}\n\nfunc (ctx *bootContext) startClient() {\n\tdefer func() {\n\t\tsigChan <- Bye\n\t}()\n\tvar (\n\t\tconn *net.TCPConn\n\t\tln   *net.TCPListener\n\t\terr  error\n\t)\n\n\tclient := NewClient(ctx.cman)\n\taddr := ctx.cman.ListenAddr(SR_CLIENT)\n\n\tln, err = net.ListenTCP(\"tcp\", addr)\n\tfatalError(err)\n\tdefer ln.Close()\n\n\tctx.register(client, ln)\n\tlog.Infoln(versionString())\n\tlog.Infoln(\"Proxy(SOCKS5\/HTTP) is listening on\", addr)\n\n\t\/\/ connect to server\n\tgo client.StartTun(true)\n\n\tfor {\n\t\tconn, err = ln.AcceptTCP()\n\t\tif err == nil {\n\t\t\tgo client.ClientServe(conn)\n\t\t} else {\n\t\t\tSafeClose(conn)\n\t\t}\n\t}\n}\n\nfunc (ctx *bootContext) startServer() {\n\tdefer func() {\n\t\tsigChan <- Bye\n\t}()\n\tvar (\n\t\tconn *net.TCPConn\n\t\tln   *net.TCPListener\n\t\terr  error\n\t)\n\n\tserver := NewServer(ctx.cman)\n\taddr := ctx.cman.ListenAddr(SR_SERVER)\n\n\tln, err = net.ListenTCP(\"tcp\", addr)\n\tfatalError(err)\n\tdefer ln.Close()\n\n\tctx.register(server, ln)\n\tlog.Infoln(versionString())\n\tlog.Infoln(\"Server is listening on\", addr)\n\n\tfor {\n\t\tconn, err = ln.AcceptTCP()\n\t\tif err == nil {\n\t\t\tgo server.TunnelServe(conn)\n\t\t} else {\n\t\t\tSafeClose(conn)\n\t\t}\n\t}\n}\n\nfunc (ctx *bootContext) register(cmp Component, cz io.Closer) {\n\tctx.components = append(ctx.components, cmp)\n\tctx.closeable = append(ctx.closeable, cz)\n}\n\nfunc (ctx *bootContext) doStats() {\n\tif ctx.components != nil {\n\t\tfor _, t := range ctx.components {\n\t\t\tfmt.Fprintln(os.Stderr, t.Stats())\n\t\t}\n\t}\n}\n\nfunc (ctx *bootContext) doClose() {\n\tfor _, t := range ctx.closeable {\n\t\tt.Close()\n\t}\n\tfor _, t := range ctx.components {\n\t\tt.Close()\n\t}\n}\n\nfunc (ctx *bootContext) setLogVerbose(verbose int) {\n\t\/\/ prefer command line v option\n\tif ctx.vFlag >= 0 {\n\t\tlog.SetLogVerbose(ctx.vFlag)\n\t} else {\n\t\tlog.SetLogVerbose(verbose)\n\t}\n}\n\nfunc getOutputArg(c *cli.Context) string {\n\toutput := c.String(\"output\")\n\tif output != NULL && !strings.Contains(output, \".\") {\n\t\toutput += \".ini\"\n\t}\n\treturn output\n}\n\nfunc waitSignal() {\n\tUSR2 := syscall.Signal(12) \/\/ fake signal-USR2 for windows\n\tsignal.Notify(sigChan, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM, USR2)\n\tfor sig := range sigChan {\n\t\tswitch sig {\n\t\tcase Bye:\n\t\t\tcontext.doClose()\n\t\t\tlog.Exitln(\"Exiting.\")\n\t\t\treturn\n\t\tcase syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM:\n\t\t\tcontext.doClose()\n\t\t\tlog.Exitln(\"Terminated by\", sig)\n\t\t\treturn\n\t\tcase USR2:\n\t\t\tcontext.doStats()\n\t\tdefault:\n\t\t\tlog.Infoln(\"Ingore signal\", sig)\n\t\t}\n\t}\n}\n\nfunc fatalError(err error, args ...interface{}) {\n\tif err != nil {\n\t\tmsg := err.Error()\n\t\tif len(args) > 0 {\n\t\t\tmsg += fmt.Sprint(args...)\n\t\t}\n\t\tfmt.Fprintln(os.Stderr, msg)\n\t\tcontext.doClose()\n\t\tos.Exit(1)\n\t}\n}\n\nfunc fatalAndCommandHelp(c *cli.Context) {\n\t\/\/ app root\n\tif c.Parent() == nil {\n\t\tcli.HelpPrinter(os.Stderr, cli.AppHelpTemplate, c.App)\n\t} else { \/\/ command\n\t\tcli.HelpPrinter(os.Stderr, cli.CommandHelpTemplate, c.Command)\n\t}\n\tcontext.doClose()\n\tos.Exit(1)\n}\n<commit_msg>amend log<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"strings\"\n\t\"syscall\"\n\n\tex \"github.com\/Lafeng\/deblocus\/exception\"\n\tlog \"github.com\/Lafeng\/deblocus\/glog\"\n\t. \"github.com\/Lafeng\/deblocus\/tunnel\"\n\t\"github.com\/codegangsta\/cli\"\n)\n\nvar (\n\tcontext = &bootContext{}\n\tsigChan = make(chan os.Signal)\n)\n\ntype Component interface {\n\tStats() string\n\tClose()\n}\n\ntype bootContext struct {\n\tconfigFile string\n\tlogdir     string\n\tdebug      bool\n\tshowVer    bool\n\tvSpecified bool\n\tvFlag      int\n\tcman       *ConfigMan\n\tcomponents []Component\n\tcloseable  []io.Closer\n}\n\n\/\/ global before handler\nfunc (ctx *bootContext) initialize(c *cli.Context) (err error) {\n\t\/\/ inject parameters into package.tunnel\n\tVER_STRING = versionString()\n\tVERSION = version\n\tDEBUG = ctx.debug\n\t\/\/ inject parameters into package.exception\n\tex.DEBUG = ctx.debug\n\t\/\/ glog\n\tctx.vSpecified = c.IsSet(\"v\")\n\tlog.SetLogOutput(ctx.logdir)\n\tlog.SetLogVerbose(ctx.vFlag)\n\treturn nil\n}\n\nfunc (ctx *bootContext) initConfig(r ServerRole) (role ServerRole) {\n\tvar err error\n\t\/\/ load config file\n\tctx.cman, err = DetectConfig(ctx.configFile)\n\tfatalError(err)\n\t\/\/ parse config file\n\trole, err = ctx.cman.InitConfigByRole(r)\n\tif role == 0 {\n\t\terr = fmt.Errorf(\"No server role defined in config\")\n\t}\n\tfatalError(err)\n\tif !ctx.vSpecified { \/\/ no -v\n\t\t\/\/ set logV with config.v\n\t\tif v := ctx.cman.LogV(role); v > 0 {\n\t\t\tlog.SetLogVerbose(v)\n\t\t}\n\t}\n\treturn role\n}\n\n\/\/ .\/deblocus csc [-type algo]\nfunc (ctx *bootContext) cscCommandHandler(c *cli.Context) {\n\tkeyType := c.String(\"type\")\n\toutput := getOutputArg(c)\n\terr := CreateServerConfigTemplate(output, keyType)\n\tfatalError(err)\n}\n\n\/\/ .\/deblocus ccc [-addr SERV_ADDR:PORT] USER\nfunc (ctx *bootContext) cccCommandHandler(c *cli.Context) {\n\t\/\/ need server config\n\tctx.initConfig(SR_SERVER)\n\tif args := c.Args(); len(args) == 1 {\n\t\tuser := args.Get(0)\n\t\tpubAddr := c.String(\"addr\")\n\t\toutput := getOutputArg(c)\n\t\terr := ctx.cman.CreateClientConfig(output, user, pubAddr)\n\t\tfatalError(err)\n\t} else {\n\t\tfatalAndCommandHelp(c)\n\t}\n}\n\nfunc (ctx *bootContext) keyInfoCommandHandler(c *cli.Context) {\n\t\/\/ need config\n\trole := ctx.initConfig(SR_AUTO)\n\tfmt.Fprintln(os.Stderr, ctx.cman.KeyInfo(role))\n}\n\nfunc (ctx *bootContext) startCommandHandler(c *cli.Context) {\n\tif len(c.Args()) > 0 {\n\t\tfatalAndCommandHelp(c)\n\t}\n\t\/\/ option as pseudo-command: help, version\n\tif ctx.showVer {\n\t\tfmt.Println(versionString())\n\t\treturn\n\t}\n\n\trole := ctx.initConfig(SR_AUTO)\n\tif role&SR_SERVER != 0 {\n\t\tgo ctx.startServer()\n\t}\n\tif role&SR_CLIENT != 0 {\n\t\tgo ctx.startClient()\n\t}\n\twaitSignal()\n}\n\nfunc (ctx *bootContext) startClient() {\n\tdefer func() {\n\t\tsigChan <- Bye\n\t}()\n\tvar (\n\t\tconn *net.TCPConn\n\t\tln   *net.TCPListener\n\t\terr  error\n\t)\n\n\tclient := NewClient(ctx.cman)\n\taddr := ctx.cman.ListenAddr(SR_CLIENT)\n\n\tln, err = net.ListenTCP(\"tcp\", addr)\n\tfatalError(err)\n\tdefer ln.Close()\n\n\tctx.register(client, ln)\n\tlog.Infoln(versionString())\n\tlog.Infoln(\"Proxy(SOCKS5\/HTTP) is listening on\", addr)\n\n\t\/\/ connect to server\n\tgo client.StartTun(true)\n\n\tfor {\n\t\tconn, err = ln.AcceptTCP()\n\t\tif err == nil {\n\t\t\tgo client.ClientServe(conn)\n\t\t} else {\n\t\t\tSafeClose(conn)\n\t\t}\n\t}\n}\n\nfunc (ctx *bootContext) startServer() {\n\tdefer func() {\n\t\tsigChan <- Bye\n\t}()\n\tvar (\n\t\tconn *net.TCPConn\n\t\tln   *net.TCPListener\n\t\terr  error\n\t)\n\n\tserver := NewServer(ctx.cman)\n\taddr := ctx.cman.ListenAddr(SR_SERVER)\n\n\tln, err = net.ListenTCP(\"tcp\", addr)\n\tfatalError(err)\n\tdefer ln.Close()\n\n\tctx.register(server, ln)\n\tlog.Infoln(versionString())\n\tlog.Infoln(\"Server is listening on\", addr)\n\n\tfor {\n\t\tconn, err = ln.AcceptTCP()\n\t\tif err == nil {\n\t\t\tgo server.TunnelServe(conn)\n\t\t} else {\n\t\t\tSafeClose(conn)\n\t\t}\n\t}\n}\n\nfunc (ctx *bootContext) register(cmp Component, cz io.Closer) {\n\tctx.components = append(ctx.components, cmp)\n\tctx.closeable = append(ctx.closeable, cz)\n}\n\nfunc (ctx *bootContext) doStats() {\n\tif ctx.components != nil {\n\t\tfor _, t := range ctx.components {\n\t\t\tfmt.Fprintln(os.Stderr, t.Stats())\n\t\t}\n\t}\n}\n\nfunc (ctx *bootContext) doClose() {\n\tfor _, t := range ctx.closeable {\n\t\tt.Close()\n\t}\n\tfor _, t := range ctx.components {\n\t\tt.Close()\n\t}\n}\n\nfunc (ctx *bootContext) setLogVerbose(verbose int) {\n\t\/\/ prefer command line v option\n\tif ctx.vFlag >= 0 {\n\t\tlog.SetLogVerbose(ctx.vFlag)\n\t} else {\n\t\tlog.SetLogVerbose(verbose)\n\t}\n}\n\nfunc getOutputArg(c *cli.Context) string {\n\toutput := c.String(\"output\")\n\tif output != NULL && !strings.Contains(output, \".\") {\n\t\toutput += \".ini\"\n\t}\n\treturn output\n}\n\nfunc waitSignal() {\n\tUSR2 := syscall.Signal(12) \/\/ fake signal-USR2 for windows\n\tsignal.Notify(sigChan, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM, USR2)\n\tfor sig := range sigChan {\n\t\tswitch sig {\n\t\tcase Bye:\n\t\t\tlog.Exitln(\"Exiting.\")\n\t\t\tcontext.doClose()\n\t\t\treturn\n\t\tcase syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM:\n\t\t\tlog.Exitln(\"Terminated by\", sig)\n\t\t\tcontext.doClose()\n\t\t\treturn\n\t\tcase USR2:\n\t\t\tcontext.doStats()\n\t\tdefault:\n\t\t\tlog.Infoln(\"Ingore signal\", sig)\n\t\t}\n\t}\n}\n\nfunc fatalError(err error, args ...interface{}) {\n\tif err != nil {\n\t\tmsg := err.Error()\n\t\tif len(args) > 0 {\n\t\t\tmsg += fmt.Sprint(args...)\n\t\t}\n\t\tfmt.Fprintln(os.Stderr, msg)\n\t\tcontext.doClose()\n\t\tos.Exit(1)\n\t}\n}\n\nfunc fatalAndCommandHelp(c *cli.Context) {\n\t\/\/ app root\n\tif c.Parent() == nil {\n\t\tcli.HelpPrinter(os.Stderr, cli.AppHelpTemplate, c.App)\n\t} else { \/\/ command\n\t\tcli.HelpPrinter(os.Stderr, cli.CommandHelpTemplate, c.Command)\n\t}\n\tcontext.doClose()\n\tos.Exit(1)\n}\n<|endoftext|>"}
{"text":"<commit_before>package sncf\n\nimport (\n\t\"testing\"\n\n\t. \"github.com\/smartystreets\/goconvey\/convey\"\n)\n\nfunc TestGetTrainTimesDeparture(t *testing.T) {\n\tConvey(\"Testing GetTrainTimesDeparture\", t, func() {\n\t\tresult, err := GetTrainTimesDeparture(\"RRD\")\n\t\tSo(err, ShouldBeNil)\n\t\ttrains := result.Trains\n\t\tSo(len(trains), ShouldEqual, 20)\n\t\tfirstTrain := trains[0]\n\t\tSo(firstTrain.OrigDest, ShouldNotBeEmpty)\n\t\tSo(firstTrain.Num, ShouldNotBeEmpty)\n\t\tSo(firstTrain.Heure, ShouldNotBeEmpty)\n\t})\n}\n<commit_msg>Skip network tests<commit_after>package sncf\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t. \"github.com\/smartystreets\/goconvey\/convey\"\n)\n\nfunc TestGetTrainTimesDeparture(t *testing.T) {\n\tConvey(\"Testing GetTrainTimesDeparture\", t, func() {\n\t\tif os.Getenv(\"SKIP_NETWORK_TESTS\") == \"1\" {\n\t\t\tt.Skip()\n\t\t}\n\t\tresult, err := GetTrainTimesDeparture(\"RRD\")\n\t\tSo(err, ShouldBeNil)\n\t\ttrains := result.Trains\n\t\tSo(len(trains), ShouldEqual, 20)\n\t\tfirstTrain := trains[0]\n\t\tSo(firstTrain.OrigDest, ShouldNotBeEmpty)\n\t\tSo(firstTrain.Num, ShouldNotBeEmpty)\n\t\tSo(firstTrain.Heure, ShouldNotBeEmpty)\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build !js\n\npackage model\n\nimport (\n\t\"context\"\n\n\t\"github.com\/flimzy\/kivik\"\n\t_ \"github.com\/flimzy\/kivik\/driver\/memory\" \/\/ Memory driver\n)\n\nfunc localConnection() (kivikClient, error) {\n\tc, err := kivik.New(context.Background(), \"memory\", \"local\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn wrapClient(c), nil\n}\n\nfunc remoteConnection(_ string) (kivikClient, error) {\n\tc, err := kivik.New(context.Background(), \"memory\", \"remote\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn wrapClient(c), nil\n}\n<commit_msg>Switch to new memory driver location<commit_after>\/\/ +build !js\n\npackage model\n\nimport (\n\t\"context\"\n\n\t\"github.com\/flimzy\/kivik\"\n\t_ \"github.com\/go-kivik\/memorydb\" \/\/ Kivik Memory driver\n)\n\nfunc localConnection() (kivikClient, error) {\n\tc, err := kivik.New(context.Background(), \"memory\", \"local\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn wrapClient(c), nil\n}\n\nfunc remoteConnection(_ string) (kivikClient, error) {\n\tc, err := kivik.New(context.Background(), \"memory\", \"remote\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn wrapClient(c), nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage runtime_test\n\nimport (\n\t\"runtime\"\n\t\"strings\"\n\t\"testing\"\n\t\"unsafe\"\n)\n\nfunc TestCaller(t *testing.T) {\n\tprocs := runtime.GOMAXPROCS(-1)\n\tc := make(chan bool, procs)\n\tfor p := 0; p < procs; p++ {\n\t\tgo func() {\n\t\t\tfor i := 0; i < 1000; i++ {\n\t\t\t\ttestCallerFoo(t)\n\t\t\t}\n\t\t\tc <- true\n\t\t}()\n\t\tdefer func() {\n\t\t\t<-c\n\t\t}()\n\t}\n}\n\n\/\/ These are marked noinline so that we can use FuncForPC\n\/\/ in testCallerBar.\n\/\/go:noinline\nfunc testCallerFoo(t *testing.T) {\n\ttestCallerBar(t)\n}\n\n\/\/go:noinline\nfunc testCallerBar(t *testing.T) {\n\tfor i := 0; i < 2; i++ {\n\t\tpc, file, line, ok := runtime.Caller(i)\n\t\tf := runtime.FuncForPC(pc)\n\t\tif !ok ||\n\t\t\t!strings.HasSuffix(file, \"symtab_test.go\") ||\n\t\t\t(i == 0 && !strings.HasSuffix(f.Name(), \"testCallerBar\")) ||\n\t\t\t(i == 1 && !strings.HasSuffix(f.Name(), \"testCallerFoo\")) ||\n\t\t\tline < 5 || line > 1000 ||\n\t\t\tf.Entry() >= pc {\n\t\t\tt.Errorf(\"incorrect symbol info %d: %t %d %d %s %s %d\",\n\t\t\t\ti, ok, f.Entry(), pc, f.Name(), file, line)\n\t\t}\n\t}\n}\n\nfunc lineNumber() int {\n\t_, _, line, _ := runtime.Caller(1)\n\treturn line \/\/ return 0 for error\n}\n\n\/\/ Do not add\/remove lines in this block without updating the line numbers.\nvar firstLine = lineNumber() \/\/ 0\nvar (                        \/\/ 1\n\tlineVar1             = lineNumber()               \/\/ 2\n\tlineVar2a, lineVar2b = lineNumber(), lineNumber() \/\/ 3\n)                        \/\/ 4\nvar compLit = []struct { \/\/ 5\n\tlineA, lineB int \/\/ 6\n}{ \/\/ 7\n\t{ \/\/ 8\n\t\tlineNumber(), lineNumber(), \/\/ 9\n\t}, \/\/ 10\n\t{ \/\/ 11\n\t\tlineNumber(), \/\/ 12\n\t\tlineNumber(), \/\/ 13\n\t}, \/\/ 14\n\t{ \/\/ 15\n\t\tlineB: lineNumber(), \/\/ 16\n\t\tlineA: lineNumber(), \/\/ 17\n\t}, \/\/ 18\n}                                     \/\/ 19\nvar arrayLit = [...]int{lineNumber(), \/\/ 20\n\tlineNumber(), lineNumber(), \/\/ 21\n\tlineNumber(), \/\/ 22\n}                                  \/\/ 23\nvar sliceLit = []int{lineNumber(), \/\/ 24\n\tlineNumber(), lineNumber(), \/\/ 25\n\tlineNumber(), \/\/ 26\n}                         \/\/ 27\nvar mapLit = map[int]int{ \/\/ 28\n\t29:           lineNumber(), \/\/ 29\n\t30:           lineNumber(), \/\/ 30\n\tlineNumber(): 31,           \/\/ 31\n\tlineNumber(): 32,           \/\/ 32\n}                           \/\/ 33\nvar intLit = lineNumber() + \/\/ 34\n\tlineNumber() + \/\/ 35\n\tlineNumber() \/\/ 36\nfunc trythis() { \/\/ 37\n\trecordLines(lineNumber(), \/\/ 38\n\t\tlineNumber(), \/\/ 39\n\t\tlineNumber()) \/\/ 40\n}\n\n\/\/ Modifications below this line are okay.\n\nvar l38, l39, l40 int\n\nfunc recordLines(a, b, c int) {\n\tl38 = a\n\tl39 = b\n\tl40 = c\n}\n\nfunc TestLineNumber(t *testing.T) {\n\ttrythis()\n\tfor _, test := range []struct {\n\t\tname string\n\t\tval  int\n\t\twant int\n\t}{\n\t\t{\"firstLine\", firstLine, 0},\n\t\t{\"lineVar1\", lineVar1, 2},\n\t\t{\"lineVar2a\", lineVar2a, 3},\n\t\t{\"lineVar2b\", lineVar2b, 3},\n\t\t{\"compLit[0].lineA\", compLit[0].lineA, 9},\n\t\t{\"compLit[0].lineB\", compLit[0].lineB, 9},\n\t\t{\"compLit[1].lineA\", compLit[1].lineA, 12},\n\t\t{\"compLit[1].lineB\", compLit[1].lineB, 13},\n\t\t{\"compLit[2].lineA\", compLit[2].lineA, 17},\n\t\t{\"compLit[2].lineB\", compLit[2].lineB, 16},\n\n\t\t{\"arrayLit[0]\", arrayLit[0], 20},\n\t\t{\"arrayLit[1]\", arrayLit[1], 21},\n\t\t{\"arrayLit[2]\", arrayLit[2], 21},\n\t\t{\"arrayLit[3]\", arrayLit[3], 22},\n\n\t\t{\"sliceLit[0]\", sliceLit[0], 24},\n\t\t{\"sliceLit[1]\", sliceLit[1], 25},\n\t\t{\"sliceLit[2]\", sliceLit[2], 25},\n\t\t{\"sliceLit[3]\", sliceLit[3], 26},\n\n\t\t{\"mapLit[29]\", mapLit[29], 29},\n\t\t{\"mapLit[30]\", mapLit[30], 30},\n\t\t{\"mapLit[31]\", mapLit[31+firstLine] + firstLine, 31}, \/\/ nb it's the key not the value\n\t\t{\"mapLit[32]\", mapLit[32+firstLine] + firstLine, 32}, \/\/ nb it's the key not the value\n\n\t\t{\"intLit\", intLit - 2*firstLine, 34 + 35 + 36},\n\n\t\t{\"l38\", l38, 38},\n\t\t{\"l39\", l39, 39},\n\t\t{\"l40\", l40, 40},\n\t} {\n\t\tif got := test.val - firstLine; got != test.want {\n\t\t\tt.Errorf(\"%s on firstLine+%d want firstLine+%d (firstLine=%d, val=%d)\",\n\t\t\t\ttest.name, got, test.want, firstLine, test.val)\n\t\t}\n\t}\n}\n\nfunc TestNilName(t *testing.T) {\n\tdefer func() {\n\t\tif ex := recover(); ex != nil {\n\t\t\tt.Fatalf(\"expected no nil panic, got=%v\", ex)\n\t\t}\n\t}()\n\tif got := (*runtime.Func)(nil).Name(); got != \"\" {\n\t\tt.Errorf(\"Name() = %q, want %q\", got, \"\")\n\t}\n}\n\nvar dummy int\n\nfunc inlined() {\n\t\/\/ Side effect to prevent elimination of this entire function.\n\tdummy = 42\n}\n\n\/\/ A function with an InlTree. Returns a PC within the function body.\n\/\/\n\/\/ No inline to ensure this complete function appears in output.\n\/\/\n\/\/go:noinline\nfunc tracebackFunc(t *testing.T) uintptr {\n\t\/\/ This body must be more complex than a single call to inlined to get\n\t\/\/ an inline tree.\n\tinlined()\n\tinlined()\n\n\t\/\/ Acquire a PC in this function.\n\tpc, _, _, ok := runtime.Caller(0)\n\tif !ok {\n\t\tt.Fatalf(\"Caller(0) got ok false, want true\")\n\t}\n\n\treturn pc\n}\n\n\/\/ Test that CallersFrames handles PCs in the alignment region between\n\/\/ functions (int 3 on amd64) without crashing.\n\/\/\n\/\/ Go will never generate a stack trace containing such an address, as it is\n\/\/ not a valid call site. However, the cgo traceback function passed to\n\/\/ runtime.SetCgoTraceback may not be completely accurate and may incorrect\n\/\/ provide PCs in Go code or the alignement region between functions.\n\/\/\n\/\/ Go obviously doesn't easily expose the problematic PCs to running programs,\n\/\/ so this test is a bit fragile. Some details:\n\/\/\n\/\/ * tracebackFunc is our target function. We want to get a PC in the\n\/\/   alignment region following this function. This function also has other\n\/\/   functions inlined into it to ensure it has an InlTree (this was the source\n\/\/   of the bug in issue 44971).\n\/\/\n\/\/ * We acquire a PC in tracebackFunc, walking forwards until FuncForPC says\n\/\/   we're in a new function. The last PC of the function according to FuncForPC\n\/\/   should be in the alignment region (assuming the function isn't already\n\/\/   perfectly aligned).\n\/\/\n\/\/ This is a regression test for issue 44971.\nfunc TestFunctionAlignmentTraceback(t *testing.T) {\n\tpc := tracebackFunc(t)\n\n\t\/\/ Double-check we got the right PC.\n\tf := runtime.FuncForPC(pc)\n\tif !strings.HasSuffix(f.Name(), \"tracebackFunc\") {\n\t\tt.Fatalf(\"Caller(0) = %+v, want tracebackFunc\", f)\n\t}\n\n\t\/\/ Iterate forward until we find a different function. Back up one\n\t\/\/ instruction is (hopefully) an alignment instruction.\n\tfor runtime.FuncForPC(pc) == f {\n\t\tpc++\n\t}\n\tpc--\n\n\t\/\/ Is this an alignment region filler instruction? We only check this\n\t\/\/ on amd64 for simplicity. If this function has no filler, then we may\n\t\/\/ get a false negative, but will never get a false positive.\n\tif runtime.GOARCH == \"amd64\" {\n\t\tcode := *(*uint8)(unsafe.Pointer(pc))\n\t\tif code != 0xcc { \/\/ INT $3\n\t\t\tt.Errorf(\"PC %v code got %#x want 0xcc\", pc, code)\n\t\t}\n\t}\n\n\t\/\/ Finally ensure that Frames.Next doesn't crash when processing this\n\t\/\/ PC.\n\tframes := runtime.CallersFrames([]uintptr{pc})\n\tframe, _ := frames.Next()\n\tif frame.Func != f {\n\t\tt.Errorf(\"frames.Next() got %+v want %+v\", frame.Func, f)\n\t}\n}\n<commit_msg>runtime: add Func method benchmarks<commit_after>\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage runtime_test\n\nimport (\n\t\"runtime\"\n\t\"strings\"\n\t\"testing\"\n\t\"unsafe\"\n)\n\nfunc TestCaller(t *testing.T) {\n\tprocs := runtime.GOMAXPROCS(-1)\n\tc := make(chan bool, procs)\n\tfor p := 0; p < procs; p++ {\n\t\tgo func() {\n\t\t\tfor i := 0; i < 1000; i++ {\n\t\t\t\ttestCallerFoo(t)\n\t\t\t}\n\t\t\tc <- true\n\t\t}()\n\t\tdefer func() {\n\t\t\t<-c\n\t\t}()\n\t}\n}\n\n\/\/ These are marked noinline so that we can use FuncForPC\n\/\/ in testCallerBar.\n\/\/go:noinline\nfunc testCallerFoo(t *testing.T) {\n\ttestCallerBar(t)\n}\n\n\/\/go:noinline\nfunc testCallerBar(t *testing.T) {\n\tfor i := 0; i < 2; i++ {\n\t\tpc, file, line, ok := runtime.Caller(i)\n\t\tf := runtime.FuncForPC(pc)\n\t\tif !ok ||\n\t\t\t!strings.HasSuffix(file, \"symtab_test.go\") ||\n\t\t\t(i == 0 && !strings.HasSuffix(f.Name(), \"testCallerBar\")) ||\n\t\t\t(i == 1 && !strings.HasSuffix(f.Name(), \"testCallerFoo\")) ||\n\t\t\tline < 5 || line > 1000 ||\n\t\t\tf.Entry() >= pc {\n\t\t\tt.Errorf(\"incorrect symbol info %d: %t %d %d %s %s %d\",\n\t\t\t\ti, ok, f.Entry(), pc, f.Name(), file, line)\n\t\t}\n\t}\n}\n\nfunc lineNumber() int {\n\t_, _, line, _ := runtime.Caller(1)\n\treturn line \/\/ return 0 for error\n}\n\n\/\/ Do not add\/remove lines in this block without updating the line numbers.\nvar firstLine = lineNumber() \/\/ 0\nvar (                        \/\/ 1\n\tlineVar1             = lineNumber()               \/\/ 2\n\tlineVar2a, lineVar2b = lineNumber(), lineNumber() \/\/ 3\n)                        \/\/ 4\nvar compLit = []struct { \/\/ 5\n\tlineA, lineB int \/\/ 6\n}{ \/\/ 7\n\t{ \/\/ 8\n\t\tlineNumber(), lineNumber(), \/\/ 9\n\t}, \/\/ 10\n\t{ \/\/ 11\n\t\tlineNumber(), \/\/ 12\n\t\tlineNumber(), \/\/ 13\n\t}, \/\/ 14\n\t{ \/\/ 15\n\t\tlineB: lineNumber(), \/\/ 16\n\t\tlineA: lineNumber(), \/\/ 17\n\t}, \/\/ 18\n}                                     \/\/ 19\nvar arrayLit = [...]int{lineNumber(), \/\/ 20\n\tlineNumber(), lineNumber(), \/\/ 21\n\tlineNumber(), \/\/ 22\n}                                  \/\/ 23\nvar sliceLit = []int{lineNumber(), \/\/ 24\n\tlineNumber(), lineNumber(), \/\/ 25\n\tlineNumber(), \/\/ 26\n}                         \/\/ 27\nvar mapLit = map[int]int{ \/\/ 28\n\t29:           lineNumber(), \/\/ 29\n\t30:           lineNumber(), \/\/ 30\n\tlineNumber(): 31,           \/\/ 31\n\tlineNumber(): 32,           \/\/ 32\n}                           \/\/ 33\nvar intLit = lineNumber() + \/\/ 34\n\tlineNumber() + \/\/ 35\n\tlineNumber() \/\/ 36\nfunc trythis() { \/\/ 37\n\trecordLines(lineNumber(), \/\/ 38\n\t\tlineNumber(), \/\/ 39\n\t\tlineNumber()) \/\/ 40\n}\n\n\/\/ Modifications below this line are okay.\n\nvar l38, l39, l40 int\n\nfunc recordLines(a, b, c int) {\n\tl38 = a\n\tl39 = b\n\tl40 = c\n}\n\nfunc TestLineNumber(t *testing.T) {\n\ttrythis()\n\tfor _, test := range []struct {\n\t\tname string\n\t\tval  int\n\t\twant int\n\t}{\n\t\t{\"firstLine\", firstLine, 0},\n\t\t{\"lineVar1\", lineVar1, 2},\n\t\t{\"lineVar2a\", lineVar2a, 3},\n\t\t{\"lineVar2b\", lineVar2b, 3},\n\t\t{\"compLit[0].lineA\", compLit[0].lineA, 9},\n\t\t{\"compLit[0].lineB\", compLit[0].lineB, 9},\n\t\t{\"compLit[1].lineA\", compLit[1].lineA, 12},\n\t\t{\"compLit[1].lineB\", compLit[1].lineB, 13},\n\t\t{\"compLit[2].lineA\", compLit[2].lineA, 17},\n\t\t{\"compLit[2].lineB\", compLit[2].lineB, 16},\n\n\t\t{\"arrayLit[0]\", arrayLit[0], 20},\n\t\t{\"arrayLit[1]\", arrayLit[1], 21},\n\t\t{\"arrayLit[2]\", arrayLit[2], 21},\n\t\t{\"arrayLit[3]\", arrayLit[3], 22},\n\n\t\t{\"sliceLit[0]\", sliceLit[0], 24},\n\t\t{\"sliceLit[1]\", sliceLit[1], 25},\n\t\t{\"sliceLit[2]\", sliceLit[2], 25},\n\t\t{\"sliceLit[3]\", sliceLit[3], 26},\n\n\t\t{\"mapLit[29]\", mapLit[29], 29},\n\t\t{\"mapLit[30]\", mapLit[30], 30},\n\t\t{\"mapLit[31]\", mapLit[31+firstLine] + firstLine, 31}, \/\/ nb it's the key not the value\n\t\t{\"mapLit[32]\", mapLit[32+firstLine] + firstLine, 32}, \/\/ nb it's the key not the value\n\n\t\t{\"intLit\", intLit - 2*firstLine, 34 + 35 + 36},\n\n\t\t{\"l38\", l38, 38},\n\t\t{\"l39\", l39, 39},\n\t\t{\"l40\", l40, 40},\n\t} {\n\t\tif got := test.val - firstLine; got != test.want {\n\t\t\tt.Errorf(\"%s on firstLine+%d want firstLine+%d (firstLine=%d, val=%d)\",\n\t\t\t\ttest.name, got, test.want, firstLine, test.val)\n\t\t}\n\t}\n}\n\nfunc TestNilName(t *testing.T) {\n\tdefer func() {\n\t\tif ex := recover(); ex != nil {\n\t\t\tt.Fatalf(\"expected no nil panic, got=%v\", ex)\n\t\t}\n\t}()\n\tif got := (*runtime.Func)(nil).Name(); got != \"\" {\n\t\tt.Errorf(\"Name() = %q, want %q\", got, \"\")\n\t}\n}\n\nvar dummy int\n\nfunc inlined() {\n\t\/\/ Side effect to prevent elimination of this entire function.\n\tdummy = 42\n}\n\n\/\/ A function with an InlTree. Returns a PC within the function body.\n\/\/\n\/\/ No inline to ensure this complete function appears in output.\n\/\/\n\/\/go:noinline\nfunc tracebackFunc(t *testing.T) uintptr {\n\t\/\/ This body must be more complex than a single call to inlined to get\n\t\/\/ an inline tree.\n\tinlined()\n\tinlined()\n\n\t\/\/ Acquire a PC in this function.\n\tpc, _, _, ok := runtime.Caller(0)\n\tif !ok {\n\t\tt.Fatalf(\"Caller(0) got ok false, want true\")\n\t}\n\n\treturn pc\n}\n\n\/\/ Test that CallersFrames handles PCs in the alignment region between\n\/\/ functions (int 3 on amd64) without crashing.\n\/\/\n\/\/ Go will never generate a stack trace containing such an address, as it is\n\/\/ not a valid call site. However, the cgo traceback function passed to\n\/\/ runtime.SetCgoTraceback may not be completely accurate and may incorrect\n\/\/ provide PCs in Go code or the alignement region between functions.\n\/\/\n\/\/ Go obviously doesn't easily expose the problematic PCs to running programs,\n\/\/ so this test is a bit fragile. Some details:\n\/\/\n\/\/ * tracebackFunc is our target function. We want to get a PC in the\n\/\/   alignment region following this function. This function also has other\n\/\/   functions inlined into it to ensure it has an InlTree (this was the source\n\/\/   of the bug in issue 44971).\n\/\/\n\/\/ * We acquire a PC in tracebackFunc, walking forwards until FuncForPC says\n\/\/   we're in a new function. The last PC of the function according to FuncForPC\n\/\/   should be in the alignment region (assuming the function isn't already\n\/\/   perfectly aligned).\n\/\/\n\/\/ This is a regression test for issue 44971.\nfunc TestFunctionAlignmentTraceback(t *testing.T) {\n\tpc := tracebackFunc(t)\n\n\t\/\/ Double-check we got the right PC.\n\tf := runtime.FuncForPC(pc)\n\tif !strings.HasSuffix(f.Name(), \"tracebackFunc\") {\n\t\tt.Fatalf(\"Caller(0) = %+v, want tracebackFunc\", f)\n\t}\n\n\t\/\/ Iterate forward until we find a different function. Back up one\n\t\/\/ instruction is (hopefully) an alignment instruction.\n\tfor runtime.FuncForPC(pc) == f {\n\t\tpc++\n\t}\n\tpc--\n\n\t\/\/ Is this an alignment region filler instruction? We only check this\n\t\/\/ on amd64 for simplicity. If this function has no filler, then we may\n\t\/\/ get a false negative, but will never get a false positive.\n\tif runtime.GOARCH == \"amd64\" {\n\t\tcode := *(*uint8)(unsafe.Pointer(pc))\n\t\tif code != 0xcc { \/\/ INT $3\n\t\t\tt.Errorf(\"PC %v code got %#x want 0xcc\", pc, code)\n\t\t}\n\t}\n\n\t\/\/ Finally ensure that Frames.Next doesn't crash when processing this\n\t\/\/ PC.\n\tframes := runtime.CallersFrames([]uintptr{pc})\n\tframe, _ := frames.Next()\n\tif frame.Func != f {\n\t\tt.Errorf(\"frames.Next() got %+v want %+v\", frame.Func, f)\n\t}\n}\n\nfunc BenchmarkFunc(b *testing.B) {\n\tpc, _, _, ok := runtime.Caller(0)\n\tif !ok {\n\t\tb.Fatal(\"failed to look up PC\")\n\t}\n\tf := runtime.FuncForPC(pc)\n\tb.Run(\"Name\", func(b *testing.B) {\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\tname := f.Name()\n\t\t\tif name != \"runtime_test.BenchmarkFunc\" {\n\t\t\t\tb.Fatalf(\"unexpected name %q\", name)\n\t\t\t}\n\t\t}\n\t})\n\tb.Run(\"Entry\", func(b *testing.B) {\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\tpc := f.Entry()\n\t\t\tif pc == 0 {\n\t\t\t\tb.Fatal(\"zero PC\")\n\t\t\t}\n\t\t}\n\t})\n\tb.Run(\"FileLine\", func(b *testing.B) {\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\tfile, line := f.FileLine(pc)\n\t\t\tif !strings.HasSuffix(file, \"symtab_test.go\") || line == 0 {\n\t\t\t\tb.Fatalf(\"unexpected file\/line %q:%d\", file, line)\n\t\t\t}\n\t\t}\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2010 The Go Authors.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"bytes\"\n\t\"flag\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"text\/template\"\n)\n\nvar (\n\thttpListen = flag.String(\"http\", \"127.0.0.1:3999\", \"host:port to listen on\")\n\thtmlOutput = flag.Bool(\"html\", false, \"render program output as HTML\")\n)\n\nvar (\n\t\/\/ a source of numbers, for naming temporary files\n\tuniq = make(chan int)\n)\n\nfunc main() {\n\tflag.Parse()\n\n\t\/\/ source of unique numbers\n\tgo func() {\n\t\tfor i := 0; ; i++ {\n\t\t\tuniq <- i\n\t\t}\n\t}()\n\n\thttp.HandleFunc(\"\/\", FrontPage)\n\thttp.HandleFunc(\"\/compile\", Compile)\n\tlog.Fatal(http.ListenAndServe(*httpListen, nil))\n}\n\n\/\/ FrontPage is an HTTP handler that renders the goplay interface.\n\/\/ If a filename is supplied in the path component of the URI,\n\/\/ its contents will be put in the interface's text area.\n\/\/ Otherwise, the default \"hello, world\" program is displayed.\nfunc FrontPage(w http.ResponseWriter, req *http.Request) {\n\tdata, err := ioutil.ReadFile(req.URL.Path[1:])\n\tif err != nil {\n\t\tdata = helloWorld\n\t}\n\tfrontPage.Execute(w, data)\n}\n\n\/\/ Compile is an HTTP handler that reads Go source code from the request,\n\/\/ runs the program (returning any errors),\n\/\/ and sends the program's output as the HTTP response.\nfunc Compile(w http.ResponseWriter, req *http.Request) {\n\tout, err := compile(req)\n\tif err != nil {\n\t\terror_(w, out, err)\n\t\treturn\n\t}\n\n\t\/\/ write the output of x as the http response\n\tif *htmlOutput {\n\t\tw.Write(out)\n\t} else {\n\t\toutput.Execute(w, out)\n\t}\n}\n\nvar (\n\tcommentRe = regexp.MustCompile(`(?m)^#.*\\n`)\n\ttmpdir    string\n)\n\nfunc init() {\n\t\/\/ find real temporary directory (for rewriting filename in output)\n\tvar err error\n\ttmpdir, err = filepath.EvalSymlinks(os.TempDir())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc compile(req *http.Request) (out []byte, err error) {\n\t\/\/ x is the base name for .go, .6, executable files\n\tx := filepath.Join(tmpdir, \"compile\"+strconv.Itoa(<-uniq))\n\tsrc := x + \".go\"\n\tbin := x\n\tif runtime.GOOS == \"windows\" {\n\t\tbin += \".exe\"\n\t}\n\n\t\/\/ rewrite filename in error output\n\tdefer func() {\n\t\tif err != nil {\n\t\t\t\/\/ drop messages from the go tool like '# _\/compile0'\n\t\t\tout = commentRe.ReplaceAll(out, nil)\n\t\t}\n\t\tout = bytes.Replace(out, []byte(src+\":\"), []byte(\"main.go:\"), -1)\n\t}()\n\n\t\/\/ write body to x.go\n\tbody := new(bytes.Buffer)\n\tif _, err = body.ReadFrom(req.Body); err != nil {\n\t\treturn\n\t}\n\tdefer os.Remove(src)\n\tif err = ioutil.WriteFile(src, body.Bytes(), 0666); err != nil {\n\t\treturn\n\t}\n\n\t\/\/ build x.go, creating x\n\tdir, file := filepath.Split(src)\n\tout, err = run(dir, \"go\", \"build\", \"-o\", bin, file)\n\tdefer os.Remove(bin)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ run x\n\treturn run(\"\", bin)\n}\n\n\/\/ error writes compile, link, or runtime errors to the HTTP connection.\n\/\/ The JavaScript interface uses the 404 status code to identify the error.\nfunc error_(w http.ResponseWriter, out []byte, err error) {\n\tw.WriteHeader(404)\n\tif out != nil {\n\t\toutput.Execute(w, out)\n\t} else {\n\t\toutput.Execute(w, err.Error())\n\t}\n}\n\n\/\/ run executes the specified command and returns its output and an error.\nfunc run(dir string, args ...string) ([]byte, error) {\n\tvar buf bytes.Buffer\n\tcmd := exec.Command(args[0], args[1:]...)\n\tcmd.Dir = dir\n\tcmd.Stdout = &buf\n\tcmd.Stderr = cmd.Stdout\n\terr := cmd.Run()\n\treturn buf.Bytes(), err\n}\n\nvar frontPage = template.Must(template.New(\"frontPage\").Parse(frontPageText)) \/\/ HTML template\nvar output = template.Must(template.New(\"output\").Parse(outputText))          \/\/ HTML template\n\nvar outputText = `<pre>{{printf \"%s\" . |html}}<\/pre>`\n\nvar frontPageText = `<!doctype html>\n<html>\n<head>\n<style>\npre, textarea {\n\tfont-family: Monaco, 'Courier New', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', monospace;\n\tfont-size: 100%;\n}\n.hints {\n\tfont-size: 0.8em;\n\ttext-align: right;\n}\n#edit, #output, #errors { width: 100%; text-align: left; }\n#edit { height: 500px; }\n#output { color: #00c; }\n#errors { color: #c00; }\n<\/style>\n<script>\n\nfunction insertTabs(n) {\n\t\/\/ find the selection start and end\n\tvar cont  = document.getElementById(\"edit\");\n\tvar start = cont.selectionStart;\n\tvar end   = cont.selectionEnd;\n\t\/\/ split the textarea content into two, and insert n tabs\n\tvar v = cont.value;\n\tvar u = v.substr(0, start);\n\tfor (var i=0; i<n; i++) {\n\t\tu += \"\\t\";\n\t}\n\tu += v.substr(end);\n\t\/\/ set revised content\n\tcont.value = u;\n\t\/\/ reset caret position after inserted tabs\n\tcont.selectionStart = start+n;\n\tcont.selectionEnd = start+n;\n}\n\nfunction autoindent(el) {\n\tvar curpos = el.selectionStart;\n\tvar tabs = 0;\n\twhile (curpos > 0) {\n\t\tcurpos--;\n\t\tif (el.value[curpos] == \"\\t\") {\n\t\t\ttabs++;\n\t\t} else if (tabs > 0 || el.value[curpos] == \"\\n\") {\n\t\t\tbreak;\n\t\t}\n\t}\n\tsetTimeout(function() {\n\t\tinsertTabs(tabs);\n\t}, 1);\n}\n\nfunction preventDefault(e) {\n\tif (e.preventDefault) {\n\t\te.preventDefault();\n\t} else {\n\t\te.cancelBubble = true;\n\t}\n}\n\nfunction keyHandler(event) {\n\tvar e = window.event || event;\n\tif (e.keyCode == 9) { \/\/ tab\n\t\tinsertTabs(1);\n\t\tpreventDefault(e);\n\t\treturn false;\n\t}\n\tif (e.keyCode == 13) { \/\/ enter\n\t\tif (e.shiftKey) { \/\/ +shift\n\t\t\tcompile(e.target);\n\t\t\tpreventDefault(e);\n\t\t\treturn false;\n\t\t} else {\n\t\t\tautoindent(e.target);\n\t\t}\n\t}\n\treturn true;\n}\n\nvar xmlreq;\n\nfunction autocompile() {\n\tif(!document.getElementById(\"autocompile\").checked) {\n\t\treturn;\n\t}\n\tcompile();\n}\n\nfunction compile() {\n\tvar prog = document.getElementById(\"edit\").value;\n\tvar req = new XMLHttpRequest();\n\txmlreq = req;\n\treq.onreadystatechange = compileUpdate;\n\treq.open(\"POST\", \"\/compile\", true);\n\treq.setRequestHeader(\"Content-Type\", \"text\/plain; charset=utf-8\");\n\treq.send(prog);\t\n}\n\nfunction compileUpdate() {\n\tvar req = xmlreq;\n\tif(!req || req.readyState != 4) {\n\t\treturn;\n\t}\n\tif(req.status == 200) {\n\t\tdocument.getElementById(\"output\").innerHTML = req.responseText;\n\t\tdocument.getElementById(\"errors\").innerHTML = \"\";\n\t} else {\n\t\tdocument.getElementById(\"errors\").innerHTML = req.responseText;\n\t\tdocument.getElementById(\"output\").innerHTML = \"\";\n\t}\n}\n<\/script>\n<\/head>\n<body>\n<table width=\"100%\"><tr><td width=\"60%\" valign=\"top\">\n<textarea autofocus=\"true\" id=\"edit\" spellcheck=\"false\" onkeydown=\"keyHandler(event);\" onkeyup=\"autocompile();\">{{printf \"%s\" . |html}}<\/textarea>\n<div class=\"hints\">\n(Shift-Enter to compile and run.)&nbsp;&nbsp;&nbsp;&nbsp;\n<input type=\"checkbox\" id=\"autocompile\" value=\"checked\" \/> Compile and run after each keystroke\n<\/div>\n<td width=\"3%\">\n<td width=\"27%\" align=\"right\" valign=\"top\">\n<div id=\"output\"><\/div>\n<\/table>\n<div id=\"errors\"><\/div>\n<\/body>\n<\/html>\n`\n\nvar helloWorld = []byte(`package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfmt.Println(\"hello, world\")\n}\n`)\n<commit_msg>misc\/goplay: use `go run x.go` instead of `go build x.go`<commit_after>\/\/ Copyright 2010 The Go Authors.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"bytes\"\n\t\"flag\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"text\/template\"\n)\n\nvar (\n\thttpListen = flag.String(\"http\", \"127.0.0.1:3999\", \"host:port to listen on\")\n\thtmlOutput = flag.Bool(\"html\", false, \"render program output as HTML\")\n)\n\nvar (\n\t\/\/ a source of numbers, for naming temporary files\n\tuniq = make(chan int)\n)\n\nfunc main() {\n\tflag.Parse()\n\n\t\/\/ source of unique numbers\n\tgo func() {\n\t\tfor i := 0; ; i++ {\n\t\t\tuniq <- i\n\t\t}\n\t}()\n\n\thttp.HandleFunc(\"\/\", FrontPage)\n\thttp.HandleFunc(\"\/compile\", Compile)\n\tlog.Fatal(http.ListenAndServe(*httpListen, nil))\n}\n\n\/\/ FrontPage is an HTTP handler that renders the goplay interface.\n\/\/ If a filename is supplied in the path component of the URI,\n\/\/ its contents will be put in the interface's text area.\n\/\/ Otherwise, the default \"hello, world\" program is displayed.\nfunc FrontPage(w http.ResponseWriter, req *http.Request) {\n\tdata, err := ioutil.ReadFile(req.URL.Path[1:])\n\tif err != nil {\n\t\tdata = helloWorld\n\t}\n\tfrontPage.Execute(w, data)\n}\n\n\/\/ Compile is an HTTP handler that reads Go source code from the request,\n\/\/ runs the program (returning any errors),\n\/\/ and sends the program's output as the HTTP response.\nfunc Compile(w http.ResponseWriter, req *http.Request) {\n\tout, err := compile(req)\n\tif err != nil {\n\t\terror_(w, out, err)\n\t\treturn\n\t}\n\n\t\/\/ write the output of x as the http response\n\tif *htmlOutput {\n\t\tw.Write(out)\n\t} else {\n\t\toutput.Execute(w, out)\n\t}\n}\n\nvar (\n\tcommentRe = regexp.MustCompile(`(?m)^#.*\\n`)\n\ttmpdir    string\n)\n\nfunc init() {\n\t\/\/ find real temporary directory (for rewriting filename in output)\n\tvar err error\n\ttmpdir, err = filepath.EvalSymlinks(os.TempDir())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n\nfunc compile(req *http.Request) (out []byte, err error) {\n\t\/\/ x is the base name for .go, .6, executable files\n\tx := filepath.Join(tmpdir, \"compile\"+strconv.Itoa(<-uniq))\n\tsrc := x + \".go\"\n\n\t\/\/ rewrite filename in error output\n\tdefer func() {\n\t\tif err != nil {\n\t\t\t\/\/ drop messages from the go tool like '# _\/compile0'\n\t\t\tout = commentRe.ReplaceAll(out, nil)\n\t\t}\n\t\tout = bytes.Replace(out, []byte(src+\":\"), []byte(\"main.go:\"), -1)\n\t}()\n\n\t\/\/ write body to x.go\n\tbody := new(bytes.Buffer)\n\tif _, err = body.ReadFrom(req.Body); err != nil {\n\t\treturn\n\t}\n\tdefer os.Remove(src)\n\tif err = ioutil.WriteFile(src, body.Bytes(), 0666); err != nil {\n\t\treturn\n\t}\n\n\t\/\/ go run x.go\n\tdir, file := filepath.Split(src)\n\tout, err = run(dir, \"go\", \"run\", file)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn out, nil\n}\n\n\/\/ error writes compile, link, or runtime errors to the HTTP connection.\n\/\/ The JavaScript interface uses the 404 status code to identify the error.\nfunc error_(w http.ResponseWriter, out []byte, err error) {\n\tw.WriteHeader(404)\n\tif out != nil {\n\t\toutput.Execute(w, out)\n\t} else {\n\t\toutput.Execute(w, err.Error())\n\t}\n}\n\n\/\/ run executes the specified command and returns its output and an error.\nfunc run(dir string, args ...string) ([]byte, error) {\n\tvar buf bytes.Buffer\n\tcmd := exec.Command(args[0], args[1:]...)\n\tcmd.Dir = dir\n\tcmd.Stdout = &buf\n\tcmd.Stderr = cmd.Stdout\n\terr := cmd.Run()\n\treturn buf.Bytes(), err\n}\n\nvar frontPage = template.Must(template.New(\"frontPage\").Parse(frontPageText)) \/\/ HTML template\nvar output = template.Must(template.New(\"output\").Parse(outputText))          \/\/ HTML template\n\nvar outputText = `<pre>{{printf \"%s\" . |html}}<\/pre>`\n\nvar frontPageText = `<!doctype html>\n<html>\n<head>\n<style>\npre, textarea {\n\tfont-family: Monaco, 'Courier New', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', monospace;\n\tfont-size: 100%;\n}\n.hints {\n\tfont-size: 0.8em;\n\ttext-align: right;\n}\n#edit, #output, #errors { width: 100%; text-align: left; }\n#edit { height: 500px; }\n#output { color: #00c; }\n#errors { color: #c00; }\n<\/style>\n<script>\n\nfunction insertTabs(n) {\n\t\/\/ find the selection start and end\n\tvar cont  = document.getElementById(\"edit\");\n\tvar start = cont.selectionStart;\n\tvar end   = cont.selectionEnd;\n\t\/\/ split the textarea content into two, and insert n tabs\n\tvar v = cont.value;\n\tvar u = v.substr(0, start);\n\tfor (var i=0; i<n; i++) {\n\t\tu += \"\\t\";\n\t}\n\tu += v.substr(end);\n\t\/\/ set revised content\n\tcont.value = u;\n\t\/\/ reset caret position after inserted tabs\n\tcont.selectionStart = start+n;\n\tcont.selectionEnd = start+n;\n}\n\nfunction autoindent(el) {\n\tvar curpos = el.selectionStart;\n\tvar tabs = 0;\n\twhile (curpos > 0) {\n\t\tcurpos--;\n\t\tif (el.value[curpos] == \"\\t\") {\n\t\t\ttabs++;\n\t\t} else if (tabs > 0 || el.value[curpos] == \"\\n\") {\n\t\t\tbreak;\n\t\t}\n\t}\n\tsetTimeout(function() {\n\t\tinsertTabs(tabs);\n\t}, 1);\n}\n\nfunction preventDefault(e) {\n\tif (e.preventDefault) {\n\t\te.preventDefault();\n\t} else {\n\t\te.cancelBubble = true;\n\t}\n}\n\nfunction keyHandler(event) {\n\tvar e = window.event || event;\n\tif (e.keyCode == 9) { \/\/ tab\n\t\tinsertTabs(1);\n\t\tpreventDefault(e);\n\t\treturn false;\n\t}\n\tif (e.keyCode == 13) { \/\/ enter\n\t\tif (e.shiftKey) { \/\/ +shift\n\t\t\tcompile(e.target);\n\t\t\tpreventDefault(e);\n\t\t\treturn false;\n\t\t} else {\n\t\t\tautoindent(e.target);\n\t\t}\n\t}\n\treturn true;\n}\n\nvar xmlreq;\n\nfunction autocompile() {\n\tif(!document.getElementById(\"autocompile\").checked) {\n\t\treturn;\n\t}\n\tcompile();\n}\n\nfunction compile() {\n\tvar prog = document.getElementById(\"edit\").value;\n\tvar req = new XMLHttpRequest();\n\txmlreq = req;\n\treq.onreadystatechange = compileUpdate;\n\treq.open(\"POST\", \"\/compile\", true);\n\treq.setRequestHeader(\"Content-Type\", \"text\/plain; charset=utf-8\");\n\treq.send(prog);\t\n}\n\nfunction compileUpdate() {\n\tvar req = xmlreq;\n\tif(!req || req.readyState != 4) {\n\t\treturn;\n\t}\n\tif(req.status == 200) {\n\t\tdocument.getElementById(\"output\").innerHTML = req.responseText;\n\t\tdocument.getElementById(\"errors\").innerHTML = \"\";\n\t} else {\n\t\tdocument.getElementById(\"errors\").innerHTML = req.responseText;\n\t\tdocument.getElementById(\"output\").innerHTML = \"\";\n\t}\n}\n<\/script>\n<\/head>\n<body>\n<table width=\"100%\"><tr><td width=\"60%\" valign=\"top\">\n<textarea autofocus=\"true\" id=\"edit\" spellcheck=\"false\" onkeydown=\"keyHandler(event);\" onkeyup=\"autocompile();\">{{printf \"%s\" . |html}}<\/textarea>\n<div class=\"hints\">\n(Shift-Enter to compile and run.)&nbsp;&nbsp;&nbsp;&nbsp;\n<input type=\"checkbox\" id=\"autocompile\" value=\"checked\" \/> Compile and run after each keystroke\n<\/div>\n<td width=\"3%\">\n<td width=\"27%\" align=\"right\" valign=\"top\">\n<div id=\"output\"><\/div>\n<\/table>\n<div id=\"errors\"><\/div>\n<\/body>\n<\/html>\n`\n\nvar helloWorld = []byte(`package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfmt.Println(\"hello, world\")\n}\n`)\n<|endoftext|>"}
{"text":"<commit_before>package workflow\n\nimport (\n\t\"github.com\/go-gorp\/gorp\"\n\n\t\"github.com\/ovh\/cds\/sdk\"\n)\n\n\/\/ LoadWorkfowArtifactByHash retrieves an artiface using its download hash\nfunc LoadWorkfowArtifactByHash(db gorp.SqlExecutor, hash string) (*sdk.WorkflowNodeRunArtifact, error) {\n\tvar artGorp NodeRunArtifact\n\tquery := `SELECT\n\t\t\t\tid,\n\t\t\t\tname,\n\t\t\t\ttag,\n\t\t\t\tworkflow_node_run_id,\n\t\t\t\tdownload_hash,\n\t\t\t\tsize,\n\t\t\t\tperm,\n\t\t\t\tmd5sum,\n\t\t\t\tobject_path,\n\t\t\t\tcreated,\n\t\t\t\tworkflow_run_id,\n\t\t\t\tcoalesce(sha512sum, '')\n\t\t  FROM workflow_node_run_artifacts\n\t\t  WHERE workflow_node_run_artifacts.download_hash = $1`\n\tif err := db.SelectOne(&artGorp, query, hash); err != nil {\n\t\treturn nil, err\n\t}\n\tart := sdk.WorkflowNodeRunArtifact(artGorp)\n\treturn &art, nil\n\n}\n\n\/\/ LoadArtifactByIDs Load artifact by workflow ID and artifact ID\nfunc LoadArtifactByIDs(db gorp.SqlExecutor, workflowID, artifactID int64) (*sdk.WorkflowNodeRunArtifact, error) {\n\tvar artGorp NodeRunArtifact\n\tquery := `\n\t\tSELECT\n\t\t\tid,\n\t\t\tname,\n\t\t\ttag,\n\t\t\tworkflow_node_run_id,\n\t\t\tdownload_hash,\n\t\t\tsize,\n\t\t\tperm,\n\t\t\tmd5sum,\n\t\t\tobject_path,\n\t\t\tcreated,\n\t\t\tworkflow_run_id,\n\t\t\tcoalesce(sha512sum, '')\n\t\tFROM workflow_node_run_artifacts\n\t\tJOIN workflow_run ON workflow_run.id = workflow_node_run_artifacts.workflow_run_id\n\t\tWHERE workflow_run.workflow_id = $1 AND workflow_node_run_artifacts.id = $2\n\n\t`\n\tif err := db.SelectOne(&artGorp, query, workflowID, artifactID); err != nil {\n\t\treturn nil, err\n\t}\n\tart := sdk.WorkflowNodeRunArtifact(artGorp)\n\treturn &art, nil\n}\n\nfunc loadArtifactByNodeRunID(db gorp.SqlExecutor, nodeRunID int64) ([]sdk.WorkflowNodeRunArtifact, error) {\n\tvar artifactsGorp []NodeRunArtifact\n\tif _, err := db.Select(&artifactsGorp, `SELECT\n\t\t\tid,\n\t\t\tname,\n\t\t\ttag,\n\t\t\tworkflow_node_run_id,\n\t\t\tdownload_hash,\n\t\t\tsize,\n\t\t\tperm,\n\t\t\tmd5sum,\n\t\t\tobject_path,\n\t\t\tcreated,\n\t\t\tworkflow_run_id,\n\t\t\tcoalesce(sha512sum, '')\n\t\tFROM workflow_node_run_artifacts WHERE workflow_node_run_id = $1`, nodeRunID); err != nil {\n\t\treturn nil, err\n\t}\n\n\tartifacts := make([]sdk.WorkflowNodeRunArtifact, len(artifactsGorp))\n\tfor i := range artifactsGorp {\n\t\tartifacts[i] = sdk.WorkflowNodeRunArtifact(artifactsGorp[i])\n\t}\n\treturn artifacts, nil\n}\n\n\/\/ InsertArtifact insert in table workflow_artifacts\nfunc InsertArtifact(db gorp.SqlExecutor, a *sdk.WorkflowNodeRunArtifact) error {\n\twArtifactDB := NodeRunArtifact(*a)\n\tif err := db.Insert(&wArtifactDB); err != nil {\n\t\treturn err\n\t}\n\ta.ID = wArtifactDB.ID\n\treturn nil\n}\n<commit_msg>fix (api): ambiguous column name (#2754)<commit_after>package workflow\n\nimport (\n\t\"github.com\/go-gorp\/gorp\"\n\n\t\"github.com\/ovh\/cds\/sdk\"\n)\n\n\/\/ LoadWorkfowArtifactByHash retrieves an artiface using its download hash\nfunc LoadWorkfowArtifactByHash(db gorp.SqlExecutor, hash string) (*sdk.WorkflowNodeRunArtifact, error) {\n\tvar artGorp NodeRunArtifact\n\tquery := `SELECT\n\t\t\t\tid,\n\t\t\t\tname,\n\t\t\t\ttag,\n\t\t\t\tworkflow_node_run_id,\n\t\t\t\tdownload_hash,\n\t\t\t\tsize,\n\t\t\t\tperm,\n\t\t\t\tmd5sum,\n\t\t\t\tobject_path,\n\t\t\t\tcreated,\n\t\t\t\tworkflow_run_id,\n\t\t\t\tcoalesce(sha512sum, '')\n\t\t  FROM workflow_node_run_artifacts\n\t\t  WHERE workflow_node_run_artifacts.download_hash = $1`\n\tif err := db.SelectOne(&artGorp, query, hash); err != nil {\n\t\treturn nil, err\n\t}\n\tart := sdk.WorkflowNodeRunArtifact(artGorp)\n\treturn &art, nil\n\n}\n\n\/\/ LoadArtifactByIDs Load artifact by workflow ID and artifact ID\nfunc LoadArtifactByIDs(db gorp.SqlExecutor, workflowID, artifactID int64) (*sdk.WorkflowNodeRunArtifact, error) {\n\tvar artGorp NodeRunArtifact\n\tquery := `\n\t\tSELECT\n\t\t\tworkflow_node_run_artifacts.id,\n\t\t\tworkflow_node_run_artifacts.name,\n\t\t\tworkflow_node_run_artifacts.tag,\n\t\t\tworkflow_node_run_artifacts.workflow_node_run_id,\n\t\t\tworkflow_node_run_artifacts.download_hash,\n\t\t\tworkflow_node_run_artifacts.size,\n\t\t\tworkflow_node_run_artifacts.perm,\n\t\t\tworkflow_node_run_artifacts.md5sum,\n\t\t\tworkflow_node_run_artifacts.object_path,\n\t\t\tworkflow_node_run_artifacts.created,\n\t\t\tworkflow_node_run_artifacts.workflow_run_id,\n\t\t\tworkflow_node_run_artifacts.coalesce(sha512sum, '')\n\t\tFROM workflow_node_run_artifacts\n\t\tJOIN workflow_run ON workflow_run.id = workflow_node_run_artifacts.workflow_run_id\n\t\tWHERE workflow_run.workflow_id = $1 AND workflow_node_run_artifacts.id = $2\n\n\t`\n\tif err := db.SelectOne(&artGorp, query, workflowID, artifactID); err != nil {\n\t\treturn nil, err\n\t}\n\tart := sdk.WorkflowNodeRunArtifact(artGorp)\n\treturn &art, nil\n}\n\nfunc loadArtifactByNodeRunID(db gorp.SqlExecutor, nodeRunID int64) ([]sdk.WorkflowNodeRunArtifact, error) {\n\tvar artifactsGorp []NodeRunArtifact\n\tif _, err := db.Select(&artifactsGorp, `SELECT\n\t\t\tid,\n\t\t\tname,\n\t\t\ttag,\n\t\t\tworkflow_node_run_id,\n\t\t\tdownload_hash,\n\t\t\tsize,\n\t\t\tperm,\n\t\t\tmd5sum,\n\t\t\tobject_path,\n\t\t\tcreated,\n\t\t\tworkflow_run_id,\n\t\t\tcoalesce(sha512sum, '')\n\t\tFROM workflow_node_run_artifacts WHERE workflow_node_run_id = $1`, nodeRunID); err != nil {\n\t\treturn nil, err\n\t}\n\n\tartifacts := make([]sdk.WorkflowNodeRunArtifact, len(artifactsGorp))\n\tfor i := range artifactsGorp {\n\t\tartifacts[i] = sdk.WorkflowNodeRunArtifact(artifactsGorp[i])\n\t}\n\treturn artifacts, nil\n}\n\n\/\/ InsertArtifact insert in table workflow_artifacts\nfunc InsertArtifact(db gorp.SqlExecutor, a *sdk.WorkflowNodeRunArtifact) error {\n\twArtifactDB := NodeRunArtifact(*a)\n\tif err := db.Insert(&wArtifactDB); err != nil {\n\t\treturn err\n\t}\n\ta.ID = wArtifactDB.ID\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package etree provides XML services through an Element Tree abstraction.\npackage etree\n\nimport (\n    \"bufio\"\n    \"container\/list\"\n    \"io\"\n)\n\nconst sp string = \"\\n                                                            \"\n\n\/\/ A Token is an empty interface that represents an Element,\n\/\/ Comment, CharData or ProcInst.\ntype Token interface {\n    writeTo(w *bufio.Writer)\n}\n\n\/\/ An Element represents an XML element.  The Children list contains\n\/\/ Tokens.\ntype Element struct {\n    Name     []byte\n    Attr     []Attr\n    Children *list.List\n}\n\n\/\/ A Comment represents an XML comment\ntype Comment []byte\n\n\/\/ CharData represents character data within XML.\ntype CharData []byte\n\n\/\/ An Attr represents a key-value attribute of an XML element.\ntype Attr struct {\n    Key   []byte\n    Value []byte\n}\n\n\/\/ NewElement creates a root-level XML element with the specified name.\nfunc NewElement(name string) *Element {\n    return &Element{\n        Name:     []byte(name),\n        Attr:     make([]Attr, 0),\n        Children: list.New(), \/\/ list of Tokens\n    }\n}\n\n\/\/ CreateElement creates a child element of the receiving element and\n\/\/ gives it the specified name.\nfunc (e *Element) CreateElement(name string) *Element {\n    c := NewElement(name)\n    e.addChild(c)\n    return c\n}\n\n\/\/ WriteTo serializes the element and its children as XML into\n\/\/ the writer w.\nfunc (e *Element) WriteTo(w io.Writer) error {\n    b := bufio.NewWriter(w)\n    e.writeTo(b)\n    return b.Flush()\n}\n\n\/\/ Indent modifies the element tree by inserting CharData entities\n\/\/ that introduce indentation.  The amount of indenting per depth\n\/\/ level is equal to spaces.\nfunc (e *Element) Indent(spaces int) {\n    e.indent(1, spaces)\n}\n\n\/\/ indent recursively inserts proper indentation between an\n\/\/ XML element's child tokens.\nfunc (e *Element) indent(depth, spaces int) {\n    for c := e.Children.Front(); c != nil; {\n        n := c.Next()\n        e.Children.InsertBefore(indentCharData(depth, spaces), c)\n        if ce, ok := c.Value.(*Element); ok {\n            ce.indent(depth+1, spaces)\n        }\n        c = n\n    }\n    if b := e.Children.Back(); b != nil {\n        e.Children.InsertAfter(indentCharData(depth-1, spaces), b)\n    }\n}\n\n\/\/ addChild adds a child token to the receiving element.\nfunc (e *Element) addChild(t Token) {\n    e.Children.PushBack(t)\n}\n\n\/\/ writeTo serializes the element to the writer w.\nfunc (e *Element) writeTo(w *bufio.Writer) {\n    w.WriteByte('<')\n    w.Write(e.Name)\n    for _, a := range e.Attr {\n        w.WriteByte(' ')\n        a.writeTo(w)\n    }\n    if e.Children.Len() > 0 {\n        w.WriteString(\">\")\n        for c := e.Children.Front(); c != nil; c = c.Next() {\n            c.Value.(Token).writeTo(w)\n        }\n        w.Write([]byte{'<', '\/'})\n        w.Write(e.Name)\n        w.WriteByte('>')\n    } else {\n        w.Write([]byte{'\/', '>'})\n    }\n}\n\n\/\/ CreateAttr creates an attribute and adds it to the receiving element.\nfunc (e *Element) CreateAttr(key, value string) Attr {\n    a := Attr{[]byte(key), []byte(value)}\n    e.Attr = append(e.Attr, a)\n    return a\n}\n\n\/\/ writeTo serializes the attribute to the writer.\nfunc (a *Attr) writeTo(w *bufio.Writer) {\n    w.Write(a.Key)\n    w.Write([]byte{'=', '\"'})\n    w.Write(a.Value)\n    w.WriteByte('\"')\n}\n\n\/\/ newCharData creates an XML character data entity.\nfunc newCharData(charData string) *CharData {\n    c := new(CharData)\n    *c = CharData(charData)\n    return c\n}\n\n\/\/ CreateCharData creates an XML character data entity and adds it\n\/\/ as a child of the receiving element.\nfunc (e *Element) CreateCharData(charData string) *CharData {\n    c := newCharData(charData)\n    e.addChild(c)\n    return c\n}\n\n\/\/ writeTo serializes the character data entity to the writer.\nfunc (c *CharData) writeTo(w *bufio.Writer) {\n    w.Write(escape(*c))\n}\n\n\/\/ NewComment creates an XML comment.\nfunc newComment(comment string) *Comment {\n    c := new(Comment)\n    *c = Comment(comment)\n    return c\n}\n\n\/\/ CreateComment creates an XML comment and adds it as a child of the\n\/\/ receiving element.\nfunc (e *Element) CreateComment(comment string) *Comment {\n    c := newComment(comment)\n    e.addChild(c)\n    return c\n}\n\n\/\/ writeTo serialies the comment to the writer.\nfunc (c *Comment) writeTo(w *bufio.Writer) {\n    w.Write([]byte{'<', '!', '-', '-', ' '})\n    w.Write(*c)\n    w.Write([]byte{' ', '-', '-', '>'})\n}\n\n\/\/ indentCharData returns the indentation CharData token for the given\n\/\/ depth level with the given number of spaces per level.\nfunc indentCharData(depth, spaces int) *CharData {\n    c := 1 + depth*spaces\n    if c > len(sp) {\n        return newCharData(sp)\n    } else {\n        return newCharData(sp[:c])\n    }\n}\n\nvar escapeTable = [...]byte{\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 1, 0, 0, 0, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 5, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n}\n\nvar substTable = [...][]byte{\n    {'&', 'q', 'u', 'o', 't', ';'}, \/\/ 1\n    {'&', 'a', 'm', 'p', ';'},      \/\/ 2\n    {'&', 'a', 'p', 'o', 's', ';'}, \/\/ 3\n    {'&', 'l', 't', ';'},           \/\/ 4\n    {'&', 'g', 't', ';'},           \/\/ 5\n}\n\n\/\/ escape generates an escaped XML string.\nfunc escape(b []byte) []byte {\n    buf := make([]byte, 0, len(b))\n    for _, c := range b {\n        subst := escapeTable[c]\n        if subst > 0 {\n            buf = append(buf, substTable[subst-1]...)\n        } else {\n            buf = append(buf, c)\n        }\n    }\n    return buf\n}\n<commit_msg>added Document & ProcInst types<commit_after>\/\/ Package etree provides XML services through an Element Tree abstraction.\npackage etree\n\nimport (\n    \"bufio\"\n    \"container\/list\"\n    \"io\"\n)\n\nconst sp string = \"\\n                                                            \"\n\n\/\/ A Token is an empty interface that represents an Element,\n\/\/ Comment, CharData or ProcInst.\ntype Token interface {\n    writeTo(w *bufio.Writer)\n}\n\n\/\/ A Document represents an XML document.  It is essentially\n\/\/ an element without a name or attributes, and it is never\n\/\/ serialized directly to XML; only its children are.\ntype Document struct {\n    Element\n}\n\n\/\/ An Element represents an XML element.  The Children list contains\n\/\/ Tokens.\ntype Element struct {\n    Name     []byte\n    Attr     []Attr\n    Children *list.List\n}\n\n\/\/ An Attr represents a key-value attribute of an XML element.\ntype Attr struct {\n    Key   []byte\n    Value []byte\n}\n\n\/\/ A Comment represents an XML comment\ntype Comment []byte\n\n\/\/ CharData represents character data within XML.\ntype CharData []byte\n\n\/\/ A ProcInst represents an XML processing instruction.\ntype ProcInst struct {\n    Target []byte\n    Inst   []byte\n}\n\n\/\/ NewDocument creates an empty XML document and returns it.\nfunc NewDocument() *Document {\n    d := new(Document)\n    d.Children = list.New()\n    return d\n}\n\n\/\/ WriteTo serializes an XML document into the writer w.\nfunc (d *Document) WriteTo(w io.Writer) error {\n    b := bufio.NewWriter(w)\n    for c := d.Children.Front(); c != nil; c = c.Next() {\n        c.Value.(Token).writeTo(b)\n    }\n    return b.Flush()\n}\n\n\/\/ Indent modifies the element tree by inserting CharData entities\n\/\/ that introduce indentation.  The amount of indenting per depth\n\/\/ level is equal to spaces.\nfunc (d *Document) Indent(spaces int) {\n    d.indent(0, spaces)\n}\n\n\/\/ NewElement creates a root-level XML element with the specified name.\nfunc NewElement(name string) *Element {\n    return &Element{\n        Name:     []byte(name),\n        Attr:     make([]Attr, 0),\n        Children: list.New(), \/\/ list of Tokens\n    }\n}\n\n\/\/ CreateElement creates a child element of the receiving element and\n\/\/ gives it the specified name.\nfunc (e *Element) CreateElement(name string) *Element {\n    c := NewElement(name)\n    e.addChild(c)\n    return c\n}\n\n\/\/ WriteTo serializes the element and its children as XML into\n\/\/ the writer w.\nfunc (e *Element) WriteTo(w io.Writer) error {\n    b := bufio.NewWriter(w)\n    e.writeTo(b)\n    return b.Flush()\n}\n\n\/\/ Indent modifies the element tree by inserting CharData entities\n\/\/ that introduce indentation.  The amount of indenting per depth\n\/\/ level is equal to spaces.\nfunc (e *Element) Indent(spaces int) {\n    e.indent(1, spaces)\n}\n\n\/\/ indent recursively inserts proper indentation between an\n\/\/ XML element's child tokens.\nfunc (e *Element) indent(depth, spaces int) {\n    for c := e.Children.Front(); c != nil; {\n        n := c.Next()\n        if depth > 0 || c != e.Children.Front() {\n            e.Children.InsertBefore(indentCharData(depth, spaces), c)\n        }\n        if ce, ok := c.Value.(*Element); ok {\n            ce.indent(depth+1, spaces)\n        }\n        c = n\n    }\n    if b := e.Children.Back(); depth > 0 && b != nil {\n        e.Children.InsertAfter(indentCharData(depth-1, spaces), b)\n    }\n}\n\n\/\/ addChild adds a child token to the receiving element.\nfunc (e *Element) addChild(t Token) {\n    e.Children.PushBack(t)\n}\n\n\/\/ writeTo serializes the element to the writer w.\nfunc (e *Element) writeTo(w *bufio.Writer) {\n    w.WriteByte('<')\n    w.Write(e.Name)\n    for _, a := range e.Attr {\n        w.WriteByte(' ')\n        a.writeTo(w)\n    }\n    if e.Children.Len() > 0 {\n        w.WriteString(\">\")\n        for c := e.Children.Front(); c != nil; c = c.Next() {\n            c.Value.(Token).writeTo(w)\n        }\n        w.Write([]byte{'<', '\/'})\n        w.Write(e.Name)\n        w.WriteByte('>')\n    } else {\n        w.Write([]byte{'\/', '>'})\n    }\n}\n\n\/\/ CreateAttr creates an attribute and adds it to the receiving element.\nfunc (e *Element) CreateAttr(key, value string) Attr {\n    a := Attr{[]byte(key), []byte(value)}\n    e.Attr = append(e.Attr, a)\n    return a\n}\n\n\/\/ writeTo serializes the attribute to the writer.\nfunc (a *Attr) writeTo(w *bufio.Writer) {\n    w.Write(a.Key)\n    w.Write([]byte{'=', '\"'})\n    w.Write(a.Value)\n    w.WriteByte('\"')\n}\n\n\/\/ newCharData creates an XML character data entity.\nfunc newCharData(charData string) *CharData {\n    c := new(CharData)\n    *c = CharData(charData)\n    return c\n}\n\n\/\/ CreateCharData creates an XML character data entity and adds it\n\/\/ as a child of the receiving element.\nfunc (e *Element) CreateCharData(charData string) *CharData {\n    c := newCharData(charData)\n    e.addChild(c)\n    return c\n}\n\n\/\/ writeTo serializes the character data entity to the writer.\nfunc (c *CharData) writeTo(w *bufio.Writer) {\n    w.Write(escape(*c))\n}\n\n\/\/ NewComment creates an XML comment.\nfunc newComment(comment string) *Comment {\n    c := new(Comment)\n    *c = Comment(comment)\n    return c\n}\n\n\/\/ CreateComment creates an XML comment and adds it as a child of the\n\/\/ receiving element.\nfunc (e *Element) CreateComment(comment string) *Comment {\n    c := newComment(comment)\n    e.addChild(c)\n    return c\n}\n\n\/\/ writeTo serialies the comment to the writer.\nfunc (c *Comment) writeTo(w *bufio.Writer) {\n    w.Write([]byte{'<', '!', '-', '-', ' '})\n    w.Write(*c)\n    w.Write([]byte{' ', '-', '-', '>'})\n}\n\n\/\/ newProcInst creates a new processing instruction.\nfunc newProcInst(target, inst string) *ProcInst {\n    return &ProcInst{\n        Target: []byte(target),\n        Inst:   []byte(inst),\n    }\n}\n\n\/\/ CreateProcInst creates a processing instruction and adds it as a\n\/\/ child of the receiving element\nfunc (e *Element) CreateProcInst(target, inst string) *ProcInst {\n    p := newProcInst(target, inst)\n    e.addChild(p)\n    return p\n}\n\n\/\/ writeTo serializes the processing instruction to the writer.\nfunc (p *ProcInst) writeTo(w *bufio.Writer) {\n    w.Write([]byte{'<', '?'})\n    w.Write(p.Target)\n    w.WriteByte(' ')\n    w.Write(p.Inst)\n    w.Write([]byte{'?', '>'})\n}\n\n\/\/ indentCharData returns the indentation CharData token for the given\n\/\/ depth level with the given number of spaces per level.\nfunc indentCharData(depth, spaces int) *CharData {\n    c := 1 + depth*spaces\n    if c > len(sp) {\n        return newCharData(sp)\n    } else {\n        return newCharData(sp[:c])\n    }\n}\n\nvar escapeTable = [...]byte{\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 1, 0, 0, 0, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 5, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n}\n\nvar substTable = [...][]byte{\n    {'&', 'q', 'u', 'o', 't', ';'}, \/\/ 1\n    {'&', 'a', 'm', 'p', ';'},      \/\/ 2\n    {'&', 'a', 'p', 'o', 's', ';'}, \/\/ 3\n    {'&', 'l', 't', ';'},           \/\/ 4\n    {'&', 'g', 't', ';'},           \/\/ 5\n}\n\n\/\/ escape generates an escaped XML string.\nfunc escape(b []byte) []byte {\n    buf := make([]byte, 0, len(b))\n    for _, c := range b {\n        subst := escapeTable[c]\n        if subst > 0 {\n            buf = append(buf, substTable[subst-1]...)\n        } else {\n            buf = append(buf, c)\n        }\n    }\n    return buf\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package main provides ...\npackage main\n\nimport (\n\t\"errors\"\n\t\"koding\/db\/models\"\n\t\"koding\/db\/mongodb\/modelhelper\"\n\t\"net\/http\"\n\t\"regexp\"\n\n\t\"github.com\/coreos\/etcd\/log\"\n\t\"github.com\/coreos\/etcd\/store\"\n\t\"github.com\/juju\/ratelimit\"\n)\n\nvar (\n\trestrictions = make(map[string]*models.Restriction)\n)\n\ntype Checker interface {\n\tCheck() bool\n}\n\ntype CheckIP struct {\n\tIP      string\n\tPattern string\n}\n\ntype CheckCountry struct {\n\tCountry string\n\tPattern string\n}\n\ntype CheckRequest struct {\n\tDomain string\n}\n\nfunc firewallHandler(h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\trest, err := modelhelper.GetRestrictionByDomain(r.Host)\n\t\tif err != nil {\n\t\t\t\/\/ don't block if we don't get a rule (pre-caution))\n\t\t\th.ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\n\t\tfor _, rule := range rest.RuleList {\n\t\t\tif a := ApplyRule(rule, r); a != nil {\n\t\t\t\ta.ServeHTTP(w, r)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\th.ServeHTTP(w, r)\n\t})\n}\n\n\/\/ ApplyRule checks the rule and returns an http.Handler to be executed. A nil\n\/\/ handler means there is no http.Handler to be executed. For example if the\n\/\/ user is allowed to pass the rule a \"nil\" http.Handler is returned, however\n\/\/ if the user is denied a `quotaExceeded` template handler is returned that\n\/\/ neneeds to be exectued\nfunc ApplyRule(rule models.Rule, r *http.Request) http.Handler {\n\tif !rule.Enabled {\n\t\treturn nil\n\t}\n\n\tfilter, err := modelhelper.GetFilterByField(\"name\", rule.Name)\n\tif err != nil {\n\t\treturn nil \/\/ if not found just continue with next rule\n\t}\n\n\t\/\/ country is empty for now\n\tchecker, err := GetChecker(filter, getIP(r.RemoteAddr), \"\")\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tmatched := checker.Check()\n\tswitch rule.Action {\n\tcase \"deny\":\n\t\tif matched {\n\t\t\treturn templateHandler(\"quotaExceeded.html\", r.Host, 509)\n\t\t}\n\tcase \"allow\":\n\t\tif !matched {\n\t\t\treturn templateHandler(\"quotaExceeded.html\", r.Host, 509)\n\t\t}\n\tcase \"securepage\":\n\t\tif !matched {\n\t\t\treturn nil\n\t\t}\n\n\t\tsession, _ := store.Get(r, CookieVM)\n\t\tlog.Debug(\"getting cookie for: %s\", r.Host)\n\t\tcookieValue, ok := session.Values[r.Host]\n\t\tif !ok || cookieValue != MagicCookieValue {\n\t\t\treturn securePageHandler(session)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc GetChecker(f models.Filter, ip, country string) (Checker, error) {\n\tswitch f.Type {\n\tcase \"ip\":\n\t\treturn &CheckIP{IP: ip, Pattern: f.Match}, nil\n\tcase \"country\":\n\t\treturn &CheckCountry{Country: country, Pattern: f.Match}, nil\n\t}\n\n\treturn nil, errors.New(\"no checker found\")\n}\n\nvar buckets = make(map[string]*ratelimit.Bucket)\n\nfunc (c *CheckRequest) Check() bool {\n\tvar b *ratelimit.Bucket\n\tb, ok := buckets[c.Domain]\n\tif !ok {\n\t\tb = ratelimit.NewBucketWithRate(60, 60)\n\t\tbuckets[c.Domain] = b\n\t}\n\n\t\/\/ one request\n\tavailable := b.TakeAvailable(1)\n\tif available == 0 {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\nfunc (c *CheckCountry) Check() bool {\n\tif c.Pattern == \"all\" {\n\t\treturn true\n\t}\n\n\tif c.Pattern == c.Country {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc (c *CheckIP) Check() bool {\n\tif c.Pattern == \"all\" {\n\t\t\/\/ assume allowed for all\n\t\treturn true\n\t}\n\n\tmatched, err := regexp.MatchString(c.Pattern, c.IP)\n\tif err != nil {\n\t\t\/\/ do not block if the regex fails\n\t\treturn true\n\t}\n\n\tif matched {\n\t\treturn false\n\t}\n\n\treturn true \/\/ not matched, give access\n}\n<commit_msg>kdproxy: more changes to rate limiter<commit_after>\/\/ Package main provides ...\npackage main\n\nimport (\n\t\"errors\"\n\t\"koding\/db\/models\"\n\t\"koding\/db\/mongodb\/modelhelper\"\n\t\"net\/http\"\n\t\"regexp\"\n\t\"strconv\"\n\n\t\"github.com\/juju\/ratelimit\"\n)\n\nvar (\n\trestrictions = make(map[string]*models.Restriction)\n\tbuckets      = make(map[string]*ratelimit.Bucket)\n)\n\ntype Checker interface {\n\tCheck() bool\n}\n\ntype CheckIP struct {\n\tIP      string\n\tPattern string\n}\n\ntype CheckCountry struct {\n\tCountry string\n\tPattern string\n}\n\ntype CheckRequest struct {\n\tHost string\n\tRate int\n}\n\nfunc firewallHandler(h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\trest, err := modelhelper.GetRestrictionByDomain(r.Host)\n\t\tif err != nil {\n\t\t\t\/\/ don't block if we don't get a rule (pre-caution))\n\t\t\th.ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\n\t\tfor _, rule := range rest.RuleList {\n\t\t\tif a := ApplyRule(rule, r); a != nil {\n\t\t\t\ta.ServeHTTP(w, r)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\th.ServeHTTP(w, r)\n\t})\n}\n\n\/\/ ApplyRule checks the rule and returns an http.Handler to be executed. A nil\n\/\/ handler means there is no http.Handler to be executed. For example if the\n\/\/ user is allowed to pass the rule a \"nil\" http.Handler is returned, however\n\/\/ if the user is denied a `quotaExceeded` template handler is returned that\n\/\/ neneeds to be exectued\nfunc ApplyRule(rule models.Rule, r *http.Request) http.Handler {\n\tif !rule.Enabled {\n\t\treturn nil\n\t}\n\n\tfilter, err := modelhelper.GetFilterByField(\"name\", rule.Name)\n\tif err != nil {\n\t\treturn nil \/\/ if not found just continue with next rule\n\t}\n\n\t\/\/ country is empty for now\n\tchecker, err := GetChecker(filter, getIP(r.RemoteAddr), \"\", r.Host)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tmatched := checker.Check()\n\tswitch rule.Action {\n\tcase \"deny\":\n\t\tif matched {\n\t\t\treturn templateHandler(\"quotaExceeded.html\", r.Host, 509)\n\t\t}\n\tcase \"allow\":\n\t\tif !matched {\n\t\t\treturn templateHandler(\"quotaExceeded.html\", r.Host, 509)\n\t\t}\n\tcase \"securepage\":\n\t\tif !matched {\n\t\t\treturn nil\n\t\t}\n\n\t\tsession, _ := store.Get(r, CookieVM)\n\t\tlog.Debug(\"getting cookie for: %s\", r.Host)\n\t\tcookieValue, ok := session.Values[r.Host]\n\t\tif !ok || cookieValue != MagicCookieValue {\n\t\t\treturn securePageHandler(session)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc GetChecker(f models.Filter, ip, country, host string) (Checker, error) {\n\tswitch f.Type {\n\tcase \"ip\":\n\t\treturn &CheckIP{IP: ip, Pattern: f.Match}, nil\n\tcase \"country\":\n\t\treturn &CheckCountry{Country: country, Pattern: f.Match}, nil\n\tcase \"request\":\n\t\trate, err := strconv.Atoi(f.Match)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn &CheckRequest{Host: host, Rate: rate}, nil\n\t}\n\n\treturn nil, errors.New(\"no checker found\")\n}\n\nfunc (c *CheckRequest) Check() bool {\n\tvar b *ratelimit.Bucket\n\tb, ok := buckets[c.Host]\n\tif !ok {\n\t\tb = ratelimit.NewBucketWithRate(float64(c.Rate), int64(c.Rate))\n\t\tbuckets[c.Host] = b\n\t}\n\n\t\/\/ one request\n\tavailable := b.TakeAvailable(1)\n\tif available == 0 {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\nfunc (c *CheckCountry) Check() bool {\n\tif c.Pattern == \"all\" {\n\t\treturn true\n\t}\n\n\tif c.Pattern == c.Country {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc (c *CheckIP) Check() bool {\n\tif c.Pattern == \"all\" {\n\t\t\/\/ assume allowed for all\n\t\treturn true\n\t}\n\n\tmatched, err := regexp.MatchString(c.Pattern, c.IP)\n\tif err != nil {\n\t\t\/\/ do not block if the regex fails\n\t\treturn true\n\t}\n\n\tif matched {\n\t\treturn false\n\t}\n\n\treturn true \/\/ not matched, give access\n}\n<|endoftext|>"}
{"text":"<commit_before>package mutamarkdown\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/leeola\/muta\"\n\t\"github.com\/leeola\/muta\/mutil\"\n\t\"github.com\/russross\/blackfriday\"\n)\n\nfunc Markdown() muta.Streamer {\n\treturn &MarkdownStreamer{}\n}\n\ntype MarkdownStreamer struct {\n}\n\nfunc (s *MarkdownStreamer) Next(fi muta.FileInfo, rc io.ReadCloser) (\n\tmuta.FileInfo, io.ReadCloser, error) {\n\n\t\/\/ MarkdownStreamer does not create any files, so if no files are\n\t\/\/ given to it, just return.\n\tif fi == nil {\n\t\treturn fi, rc, nil\n\t}\n\n\t\/\/ If the file isn't markdown, we don't care about it. Return it\n\t\/\/ unmodified.\n\tif filepath.Ext(fi.Name()) != \".md\" {\n\t\treturn fi, rc, nil\n\t}\n\n\t\/\/ Since the file is markdown, read it all so we can convert it to\n\t\/\/ markdown.\n\tmarkdown, err := ioutil.ReadAll(rc)\n\tdefer rc.Close()\n\tif err != nil {\n\t\treturn fi, rc, err\n\t}\n\n\t\/\/ Rename the file to HTML\n\tfi.SetName(fmt.Sprintf(\"%s.html\",\n\t\tstrings.TrimSuffix(fi.Name(), filepath.Ext(fi.Name())),\n\t))\n\n\t\/\/ Use Blackfriday to create our Markdown\n\thtml := blackfriday.MarkdownBasic(markdown)\n\n\t\/\/ ByteCloser() is a muta utility function that takes a byte array, and\n\t\/\/ returns a fake ReadCloser. This is needed to satisfy the Streamer\n\t\/\/ interface.\n\trc = mutil.ByteCloser(html)\n\n\t\/\/ Now return it all, for subsequent plugins to modify, write to file, etc.\n\treturn fi, rc, nil\n}\n<commit_msg>examples: Small docstring addition<commit_after>package mutamarkdown\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/leeola\/muta\"\n\t\"github.com\/leeola\/muta\/mutil\"\n\t\"github.com\/russross\/blackfriday\"\n)\n\nfunc Markdown() muta.Streamer {\n\treturn &MarkdownStreamer{}\n}\n\ntype MarkdownStreamer struct {\n}\n\n\/\/ The Next() method is the (only) workhorse of a Streamer. The Stream\n\/\/ will call it with a FileInfo and a ReadCloser, expecting the Next()\n\/\/ method to modify them as it sees fit.\n\/\/\n\/\/ If no FileInfo is provided, the Next() method is expected to create\n\/\/ new files and return them - or return nothing and not be called again.\n\/\/\n\/\/ Next() will always be called once more if it returns a file, unless\n\/\/ it returns an error.\nfunc (s *MarkdownStreamer) Next(fi muta.FileInfo, rc io.ReadCloser) (\n\tmuta.FileInfo, io.ReadCloser, error) {\n\n\t\/\/ MarkdownStreamer does not create any files, so if no files are\n\t\/\/ given to it, just return.\n\tif fi == nil {\n\t\treturn fi, rc, nil\n\t}\n\n\t\/\/ If the file isn't markdown, we don't care about it. Return it\n\t\/\/ unmodified.\n\tif filepath.Ext(fi.Name()) != \".md\" {\n\t\treturn fi, rc, nil\n\t}\n\n\t\/\/ Since the file is markdown, read it all so we can convert it to\n\t\/\/ markdown.\n\tmarkdown, err := ioutil.ReadAll(rc)\n\tdefer rc.Close()\n\tif err != nil {\n\t\treturn fi, rc, err\n\t}\n\n\t\/\/ Rename the file to HTML\n\tfi.SetName(fmt.Sprintf(\"%s.html\",\n\t\tstrings.TrimSuffix(fi.Name(), filepath.Ext(fi.Name())),\n\t))\n\n\t\/\/ Use Blackfriday to create our Markdown\n\thtml := blackfriday.MarkdownBasic(markdown)\n\n\t\/\/ ByteCloser() is a muta utility function that takes a byte array, and\n\t\/\/ returns a fake ReadCloser. This is needed to satisfy the Streamer\n\t\/\/ interface.\n\trc = mutil.ByteCloser(html)\n\n\t\/\/ Now return it all, for subsequent plugins to modify, write to file, etc.\n\treturn fi, rc, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"sort\"\n)\n\ntype PrintGoStructVisitor struct {\n\talreadyVisited      map[string]bool\n\tglobalTagAttributes map[string]([]*FQN)\n\tlineChannel         chan string\n\tmaxDepth            int\n\tdepth               int\n\tnameSpaceTagMap     map[string]string\n\tuseType             bool\n\tnameSpaceInJsonName bool\n}\n\nfunc (v *PrintGoStructVisitor) init(lineChannel chan string, maxDepth int, globalTagAttributes map[string]([]*FQN), nameSpaceTagMap map[string]string, useType bool, nameSpaceInJsonName bool) {\n\tv.alreadyVisited = make(map[string]bool)\n\tv.globalTagAttributes = make(map[string]([]*FQN))\n\tv.globalTagAttributes = globalTagAttributes\n\tv.lineChannel = lineChannel\n\tv.maxDepth = maxDepth\n\tv.depth = 0\n\tv.nameSpaceTagMap = nameSpaceTagMap\n\tv.useType = useType\n\tv.nameSpaceInJsonName = nameSpaceInJsonName\n}\n\nfunc (v *PrintGoStructVisitor) Visit(node *Node) bool {\n\tv.depth += 1\n\t\/\/\tif v.depth >= v.maxDepth {\n\t\/\/\t\treturn false\n\t\/\/\t}\n\n\tif v.AlreadyVisited(node) {\n\t\tv.depth += 1\n\t\treturn false\n\t}\n\tv.SetAlreadyVisited(node)\n\n\tattributes := v.globalTagAttributes[nk(node)]\n\n\tv.lineChannel <- \"type \" + node.makeType(namePrefix, nameSuffix) + \" struct {\"\n\tmakeAttributes(v.lineChannel, attributes, v.nameSpaceTagMap)\n\tv.printInternalFields(node)\n\tif node.space != \"\" {\n\t\t\/\/v.lineChannel <- \"\\tXMLName  xml.Name `xml:\"\" + node.space + \" \" + node.name + \",omitempty\\\" \" + makeJsonAnnotation(node.spaceTag, v.nameSpaceInJsonName, node.name) + \"\\\"`\"\n\t\tv.lineChannel <- \"\\tXMLName  xml.Name `\" + makeXmlAnnotation(node.space, false, node.name) + \" \" + makeJsonAnnotation(node.spaceTag, false, node.name) + \"`\"\n\t} else {\n\t\t\/\/xmlName = \"\\tXMLName  xml.Name `xml:\\\"\" + n.name + \",omitempty\\\" json:\\\",omitempty\\\"`\"\n\t}\n\tv.lineChannel <- \"}\\n\"\n\n\tfor _, child := range node.children {\n\t\tv.Visit(child)\n\t}\n\tv.depth += 1\n\treturn true\n}\n\nfunc (v *PrintGoStructVisitor) AlreadyVisited(n *Node) bool {\n\t_, ok := v.alreadyVisited[nk(n)]\n\treturn ok\n}\n\nfunc (v *PrintGoStructVisitor) SetAlreadyVisited(n *Node) {\n\tv.alreadyVisited[nk(n)] = true\n}\n\nfunc (pn *PrintGoStructVisitor) printInternalFields(n *Node) {\n\tvar fields []string\n\n\tvar field string\n\n\tfor _, v := range n.children {\n\t\tfield = \"\\t\" + v.makeType(namePrefix, nameSuffix) + \" \"\n\t\tif v.repeats {\n\t\t\tfield += \"[]*\"\n\t\t} else {\n\t\t\tfield += \"*\"\n\t\t}\n\t\tfield += v.makeType(namePrefix, nameSuffix)\n\n\t\tjsonAnnotation := makeJsonAnnotation(v.spaceTag, pn.nameSpaceInJsonName, v.name)\n\t\txmlAnnotation := makeXmlAnnotation(v.space, false, v.name)\n\n\t\tannotation := \" `\" + xmlAnnotation + \" \" + jsonAnnotation + \"`\"\n\n\t\tfield += annotation\n\t\tfields = append(fields, field)\n\t}\n\n\tif n.hasCharData {\n\t\txmlString := \" `xml:\\\",chardata\\\" \" + makeJsonAnnotation(\"\", false, \"\") + \"`\"\n\t\tcharField := \"\\t\" + \"Text\" + \" \" + findType(n.nodeTypeInfo, useType) + xmlString\n\t\tfields = append(fields, charField)\n\t}\n\tsort.Strings(fields)\n\tfor i := 0; i < len(fields); i++ {\n\t\tpn.lineChannel <- fields[i]\n\t}\n}\n\nfunc makeJsonAnnotation(spaceTag string, useSpaceTagInName bool, name string) string {\n\treturn makeAnnotation(\"json\", spaceTag, false, useSpaceTagInName, name)\n}\n\nfunc makeXmlAnnotation(spaceTag string, useSpaceTag bool, name string) string {\n\treturn makeAnnotation(\"xml\", spaceTag, true, false, name)\n}\n\nfunc makeAnnotation(annotationId string, spaceTag string, useSpaceTag bool, useSpaceTagInName bool, name string) (annotation string) {\n\tannotation = annotationId + \":\\\"\"\n\n\tif useSpaceTag {\n\t\tannotation = annotation + spaceTag\n\t\tannotation = annotation + \" \"\n\t}\n\n\tif useSpaceTagInName {\n\t\tif spaceTag != \"\" {\n\t\t\tannotation = annotation + spaceTag + \"__\"\n\t\t}\n\t}\n\n\tannotation = annotation + name + \",omitempty\\\"\"\n\n\treturn annotation\n}\n<commit_msg>Added empty dbAnnotation method to printGoStructVistor<commit_after>package main\n\nimport (\n\t\"sort\"\n)\n\ntype PrintGoStructVisitor struct {\n\talreadyVisited      map[string]bool\n\tglobalTagAttributes map[string]([]*FQN)\n\tlineChannel         chan string\n\tmaxDepth            int\n\tdepth               int\n\tnameSpaceTagMap     map[string]string\n\tuseType             bool\n\tnameSpaceInJsonName bool\n}\n\nfunc (v *PrintGoStructVisitor) init(lineChannel chan string, maxDepth int, globalTagAttributes map[string]([]*FQN), nameSpaceTagMap map[string]string, useType bool, nameSpaceInJsonName bool) {\n\tv.alreadyVisited = make(map[string]bool)\n\tv.globalTagAttributes = make(map[string]([]*FQN))\n\tv.globalTagAttributes = globalTagAttributes\n\tv.lineChannel = lineChannel\n\tv.maxDepth = maxDepth\n\tv.depth = 0\n\tv.nameSpaceTagMap = nameSpaceTagMap\n\tv.useType = useType\n\tv.nameSpaceInJsonName = nameSpaceInJsonName\n}\n\nfunc (v *PrintGoStructVisitor) Visit(node *Node) bool {\n\tv.depth += 1\n\t\/\/\tif v.depth >= v.maxDepth {\n\t\/\/\t\treturn false\n\t\/\/\t}\n\n\tif v.AlreadyVisited(node) {\n\t\tv.depth += 1\n\t\treturn false\n\t}\n\tv.SetAlreadyVisited(node)\n\n\tattributes := v.globalTagAttributes[nk(node)]\n\n\tv.lineChannel <- \"type \" + node.makeType(namePrefix, nameSuffix) + \" struct {\"\n\tmakeAttributes(v.lineChannel, attributes, v.nameSpaceTagMap)\n\tv.printInternalFields(node)\n\tif node.space != \"\" {\n\t\t\/\/v.lineChannel <- \"\\tXMLName  xml.Name `xml:\"\" + node.space + \" \" + node.name + \",omitempty\\\" \" + makeJsonAnnotation(node.spaceTag, v.nameSpaceInJsonName, node.name) + \"\\\"`\"\n\t\tv.lineChannel <- \"\\tXMLName  xml.Name `\" + makeXmlAnnotation(node.space, false, node.name) + \" \" + makeJsonAnnotation(node.spaceTag, false, node.name) + \"`\"\n\t} else {\n\t\t\/\/xmlName = \"\\tXMLName  xml.Name `xml:\\\"\" + n.name + \",omitempty\\\" json:\\\",omitempty\\\"`\"\n\t}\n\tv.lineChannel <- \"}\\n\"\n\n\tfor _, child := range node.children {\n\t\tv.Visit(child)\n\t}\n\tv.depth += 1\n\treturn true\n}\n\nfunc (v *PrintGoStructVisitor) AlreadyVisited(n *Node) bool {\n\t_, ok := v.alreadyVisited[nk(n)]\n\treturn ok\n}\n\nfunc (v *PrintGoStructVisitor) SetAlreadyVisited(n *Node) {\n\tv.alreadyVisited[nk(n)] = true\n}\n\nfunc (pn *PrintGoStructVisitor) printInternalFields(n *Node) {\n\tvar fields []string\n\n\tvar field string\n\n\tfor _, v := range n.children {\n\t\tfield = \"\\t\" + v.makeType(namePrefix, nameSuffix) + \" \"\n\t\tif v.repeats {\n\t\t\tfield += \"[]*\"\n\t\t} else {\n\t\t\tfield += \"*\"\n\t\t}\n\t\tfield += v.makeType(namePrefix, nameSuffix)\n\n\t\tjsonAnnotation := makeJsonAnnotation(v.spaceTag, pn.nameSpaceInJsonName, v.name)\n\t\txmlAnnotation := makeXmlAnnotation(v.space, false, v.name)\n\t\tdbAnnotation := \"\"\n\t\tif addDbMetadata {\n\t\t\tdbAnnotation = \" \" + makeDbAnnotation(v.space, false, v.name)\n\t\t}\n\n\t\tannotation := \" `\" + xmlAnnotation + \" \" + jsonAnnotation + dbAnnotation + \"`\"\n\n\t\tfield += annotation\n\t\tfields = append(fields, field)\n\t}\n\n\tif n.hasCharData {\n\t\txmlString := \" `xml:\\\",chardata\\\" \" + makeJsonAnnotation(\"\", false, \"\") + \"`\"\n\t\tcharField := \"\\t\" + \"Text\" + \" \" + findType(n.nodeTypeInfo, useType) + xmlString\n\t\tfields = append(fields, charField)\n\t}\n\tsort.Strings(fields)\n\tfor i := 0; i < len(fields); i++ {\n\t\tpn.lineChannel <- fields[i]\n\t}\n}\n\nfunc makeJsonAnnotation(spaceTag string, useSpaceTagInName bool, name string) string {\n\treturn makeAnnotation(\"json\", spaceTag, false, useSpaceTagInName, name)\n}\n\nfunc makeXmlAnnotation(spaceTag string, useSpaceTag bool, name string) string {\n\treturn makeAnnotation(\"xml\", spaceTag, true, false, name)\n}\n\nfunc makeDbAnnotation(spaceTag string, useSpaceTag bool, name string) string {\n\treturn makeAnnotation(\"db\", spaceTag, true, false, name)\n}\n\nfunc makeAnnotation(annotationId string, spaceTag string, useSpaceTag bool, useSpaceTagInName bool, name string) (annotation string) {\n\tannotation = annotationId + \":\\\"\"\n\n\tif useSpaceTag {\n\t\tannotation = annotation + spaceTag\n\t\tannotation = annotation + \" \"\n\t}\n\n\tif useSpaceTagInName {\n\t\tif spaceTag != \"\" {\n\t\t\tannotation = annotation + spaceTag + \"__\"\n\t\t}\n\t}\n\n\tannotation = annotation + name + \",omitempty\\\"\"\n\n\treturn annotation\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package snaker provides methods to convert CamelCase to and from snake_case.\n\/\/\n\/\/ snaker takes into takes into consideration common initialisms (ie, ID, HTTP,\n\/\/ ACL, etc) when converting to\/from CamelCase and snake_case.\npackage snaker\n\n\/\/go:generate .\/gen.sh --update\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"unicode\"\n)\n\n\/\/ CamelToSnake converts s to snake_case.\nfunc CamelToSnake(s string) string {\n\tif s == \"\" {\n\t\treturn \"\"\n\t}\n\n\trs := []rune(s)\n\n\tvar r string\n\tvar lastWasUpper, lastWasLetter, lastWasIsm, isUpper, isLetter bool\n\tfor i := 0; i < len(rs); {\n\t\tisUpper = unicode.IsUpper(rs[i])\n\t\tisLetter = unicode.IsLetter(rs[i])\n\n\t\t\/\/ append _ when last was not upper and not letter\n\t\tif (lastWasLetter && isUpper) || (lastWasIsm && isLetter) {\n\t\t\tr += \"_\"\n\t\t}\n\n\t\t\/\/ determine next to append to r\n\t\tvar next string\n\t\tif ism := peekInitialism(rs[i:]); ism != \"\" && (!lastWasUpper || lastWasIsm) {\n\t\t\tnext = ism\n\t\t} else {\n\t\t\tnext = string(rs[i])\n\t\t}\n\n\t\t\/\/ save for next iteration\n\t\tlastWasIsm = false\n\t\tif len(next) > 1 {\n\t\t\tlastWasIsm = true\n\t\t}\n\t\tlastWasUpper = isUpper\n\t\tlastWasLetter = isLetter\n\n\t\tr += next\n\t\ti += len(next)\n\t}\n\n\treturn strings.ToLower(r)\n}\n\n\/\/ CamelToSnakeIdentifier converts s to its snake_case identifier.\nfunc CamelToSnakeIdentifier(s string) string {\n\treturn toIdentifier(CamelToSnake(s))\n}\n\n\/\/ SnakeToCamel converts s to CamelCase.\nfunc SnakeToCamel(s string) string {\n\tvar r string\n\n\tfor _, w := range strings.Split(s, \"_\") {\n\t\tif w == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tu := strings.ToUpper(w)\n\t\tif ok := commonInitialisms[u]; ok {\n\t\t\tr += u\n\t\t} else {\n\t\t\tr += strings.ToUpper(w[:1]) + strings.ToLower(w[1:])\n\t\t}\n\t}\n\n\treturn r\n}\n\n\/\/ SnakeToCamelIdentifier converts s to its CamelCase identifier (first\n\/\/ letter is capitalized).\nfunc SnakeToCamelIdentifier(s string) string {\n\treturn SnakeToCamel(toIdentifier(s))\n}\n\n\/\/ AddInitialisms adds initialisms to the recognized initialisms.\nfunc AddInitialisms(initialisms ...string) error {\n\tfor _, s := range initialisms {\n\t\tif len(s) < minInitialismLen || len(s) > maxInitialismLen {\n\t\t\treturn fmt.Errorf(\"%s does not have length between %d and %d\", s, minInitialismLen, maxInitialismLen)\n\t\t}\n\t\tcommonInitialisms[s] = true\n\t}\n\n\treturn nil\n}\n\n\/\/ IsInitialism indicates whether or not an initialism is registered as an\n\/\/ identified initialism.\nfunc IsInitialism(initialism string) bool {\n\treturn commonInitialisms[strings.ToUpper(initialism)]\n}\n<commit_msg>Adding ForceCamelIdentifier and ForceLowerCamelIdentifier funcs<commit_after>\/\/ Package snaker provides methods to convert CamelCase to and from snake_case.\n\/\/\n\/\/ snaker takes into takes into consideration common initialisms (ie, ID, HTTP,\n\/\/ ACL, etc) when converting to\/from CamelCase and snake_case.\npackage snaker\n\n\/\/go:generate .\/gen.sh --update\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"unicode\"\n)\n\n\/\/ CamelToSnake converts s to snake_case.\nfunc CamelToSnake(s string) string {\n\tif s == \"\" {\n\t\treturn \"\"\n\t}\n\n\trs := []rune(s)\n\n\tvar r string\n\tvar lastWasUpper, lastWasLetter, lastWasIsm, isUpper, isLetter bool\n\tfor i := 0; i < len(rs); {\n\t\tisUpper = unicode.IsUpper(rs[i])\n\t\tisLetter = unicode.IsLetter(rs[i])\n\n\t\t\/\/ append _ when last was not upper and not letter\n\t\tif (lastWasLetter && isUpper) || (lastWasIsm && isLetter) {\n\t\t\tr += \"_\"\n\t\t}\n\n\t\t\/\/ determine next to append to r\n\t\tvar next string\n\t\tif ism := peekInitialism(rs[i:]); ism != \"\" && (!lastWasUpper || lastWasIsm) {\n\t\t\tnext = ism\n\t\t} else {\n\t\t\tnext = string(rs[i])\n\t\t}\n\n\t\t\/\/ save for next iteration\n\t\tlastWasIsm = false\n\t\tif len(next) > 1 {\n\t\t\tlastWasIsm = true\n\t\t}\n\t\tlastWasUpper = isUpper\n\t\tlastWasLetter = isLetter\n\n\t\tr += next\n\t\ti += len(next)\n\t}\n\n\treturn strings.ToLower(r)\n}\n\n\/\/ CamelToSnakeIdentifier converts s to its snake_case identifier.\nfunc CamelToSnakeIdentifier(s string) string {\n\treturn toIdentifier(CamelToSnake(s))\n}\n\n\/\/ SnakeToCamel converts s to CamelCase.\nfunc SnakeToCamel(s string) string {\n\tvar r string\n\n\tfor _, w := range strings.Split(s, \"_\") {\n\t\tif w == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tu := strings.ToUpper(w)\n\t\tif ok := commonInitialisms[u]; ok {\n\t\t\tr += u\n\t\t} else {\n\t\t\tr += strings.ToUpper(w[:1]) + strings.ToLower(w[1:])\n\t\t}\n\t}\n\n\treturn r\n}\n\n\/\/ SnakeToCamelIdentifier converts s to its CamelCase identifier (first\n\/\/ letter is capitalized).\nfunc SnakeToCamelIdentifier(s string) string {\n\treturn SnakeToCamel(toIdentifier(s))\n}\n\n\/\/ ForceCamelIdentifier forces CamelCase specific to Go.\nfunc ForceCamelIdentifier(s string) string {\n\tif s == \"\" {\n\t\treturn \"\"\n\t}\n\n\treturn SnakeToCamelIdentifier(CamelToSnake(s))\n}\n\n\/\/ ForceLowerCamelIdentifier forces the first portion of an identifier to be\n\/\/ lower case.\nfunc ForceLowerCamelIdentifier(s string) string {\n\tif s == \"\" {\n\t\treturn \"\"\n\t}\n\n\ts = CamelToSnake(s)\n\tfirst := strings.SplitN(s, \"_\", -1)[0]\n\ts = SnakeToCamelIdentifier(s)\n\n\treturn strings.ToLower(first) + s[len(first):]\n}\n\n\/\/ AddInitialisms adds initialisms to the recognized initialisms.\nfunc AddInitialisms(initialisms ...string) error {\n\tfor _, s := range initialisms {\n\t\tif len(s) < minInitialismLen || len(s) > maxInitialismLen {\n\t\t\treturn fmt.Errorf(\"%s does not have length between %d and %d\", s, minInitialismLen, maxInitialismLen)\n\t\t}\n\t\tcommonInitialisms[s] = true\n\t}\n\n\treturn nil\n}\n\n\/\/ IsInitialism indicates whether or not an initialism is registered as an\n\/\/ identified initialism.\nfunc IsInitialism(initialism string) bool {\n\treturn commonInitialisms[strings.ToUpper(initialism)]\n}\n<|endoftext|>"}
{"text":"<commit_before>package google\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com\/hashicorp\/terraform\/helper\/acctest\"\n\t\"github.com\/hashicorp\/terraform\/helper\/resource\"\n\t\"github.com\/hashicorp\/terraform\/terraform\"\n\t\"google.golang.org\/api\/compute\/v1\"\n)\n\nfunc TestAccComputeSnapshot_basic(t *testing.T) {\n\tsnapshotName := fmt.Sprintf(\"tf-test-%s\", acctest.RandString(10))\n\tvar snapshot compute.Snapshot\n\tdiskName := fmt.Sprintf(\"tf-test-%s\", acctest.RandString(10))\n\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckComputeSnapshotDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccComputeSnapshot_basic(snapshotName, diskName),\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckComputeSnapshotExists(\n\t\t\t\t\t\t\"google_compute_snapshot.foobar\", &snapshot),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc TestAccComputeSnapshot_encryption(t *testing.T) {\n\tsnapshotName := fmt.Sprintf(\"tf-test-%s\", acctest.RandString(10))\n\tvar snapshot compute.Snapshot\n\tdiskName := fmt.Sprintf(\"tf-test-%s\", acctest.RandString(10))\n\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckComputeSnapshotDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccComputeSnapshot_encryption(snapshotName, diskName),\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckComputeSnapshotExists(\n\t\t\t\t\t\t\"google_compute_snapshot.foobar\", &snapshot),\n\t\t\t\t\ttestAccCheckSnapshotEncryptionKey(\n\t\t\t\t\t\t\"google_compute_snapshot.foobar\", &snapshot),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc testAccCheckComputeSnapshotDestroy(s *terraform.State) error {\n\tconfig := testAccProvider.Meta().(*Config)\n\n\tfor _, rs := range s.RootModule().Resources {\n\t\tif rs.Type != \"google_compute_snapshot\" {\n\t\t\tcontinue\n\t\t}\n\n\t\t_, err := config.clientCompute.Snapshots.Get(\n\t\t\tconfig.Project, rs.Primary.ID).Do()\n\t\tif err == nil {\n\t\t\treturn fmt.Errorf(\"Snapshot still exists\")\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc testAccCheckComputeSnapshotExists(n string, snapshot *compute.Snapshot) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\trs, ok := s.RootModule().Resources[n]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Not found: %s\", n)\n\t\t}\n\n\t\tif rs.Primary.ID == \"\" {\n\t\t\treturn fmt.Errorf(\"No ID is set\")\n\t\t}\n\n\t\tconfig := testAccProvider.Meta().(*Config)\n\n\t\tfound, err := config.clientCompute.Snapshots.Get(\n\t\t\tconfig.Project, rs.Primary.ID).Do()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif found.Name != rs.Primary.ID {\n\t\t\treturn fmt.Errorf(\"Snapshot not found\")\n\t\t}\n\n\t\t*snapshot = *found\n\n\t\treturn nil\n\t}\n}\n\nfunc testAccCheckSnapshotEncryptionKey(n string, snapshot *compute.Snapshot) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\trs, ok := s.RootModule().Resources[n]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Not found: %s\", n)\n\t\t}\n\n\t\tattr := rs.Primary.Attributes[\"snapshot_encryption_key_sha256\"]\n\t\tif snapshot.SnapshotEncryptionKey == nil && attr != \"\" {\n\t\t\treturn fmt.Errorf(\"Snapshot %s has mismatched encryption key.\\nTF State: %+v\\nGCP State: <empty>\", n, attr)\n\t\t}\n\n\t\tif attr != snapshot.SnapshotEncryptionKey.Sha256 {\n\t\t\treturn fmt.Errorf(\"Snapshot %s has mismatched encryption key.\\nTF State: %+v.\\nGCP State: %+v\",\n\t\t\t\tn, attr, snapshot.SnapshotEncryptionKey.Sha256)\n\t\t}\n\t\treturn nil\n\t}\n}\n\nfunc testAccComputeSnapshot_basic(snapshotName string, diskName string) string {\n\treturn fmt.Sprintf(`\nresource \"google_compute_disk\" \"foobar\" {\n\tname = \"%s\"\n\timage = \"debian-8-jessie-v20160803\"\n\tsize = 50\n\ttype = \"pd-ssd\"\n\tzone = \"us-central1-a\"\n}\n\nresource \"google_compute_snapshot\" \"foobar\" {\n\tname = \"%s\"\n\tdisk = \"${google_compute_disk.foobar.name}\"\n\tzone = \"us-central1-a\"\n}`, diskName, snapshotName)\n}\n\nfunc testAccComputeSnapshot_encryption(snapshotName string, diskName string) string {\n\treturn fmt.Sprintf(`\nresource \"google_compute_disk\" \"foobar\" {\n\tname = \"%s\"\n\timage = \"debian-8-jessie-v20160803\"\n\tsize = 50\n\ttype = \"pd-ssd\"\n\tzone = \"us-central1-a\"\n}\nresource \"google_compute_snapshot\" \"foobar\" {\n\tname = \"%s\"\n\tdisk = \"%s\"\n\tzone = \"us-central1-a\"\n\tsnapshot_encryption_key_raw = \"SGVsbG8gZnJvbSBHb29nbGUgQ2xvdWQgUGxhdGZvcm0=\"\n}`, diskName, snapshotName, diskName)\n}\n<commit_msg>Use a new image type<commit_after>package google\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com\/hashicorp\/terraform\/helper\/acctest\"\n\t\"github.com\/hashicorp\/terraform\/helper\/resource\"\n\t\"github.com\/hashicorp\/terraform\/terraform\"\n\t\"google.golang.org\/api\/compute\/v1\"\n)\n\nfunc TestAccComputeSnapshot_basic(t *testing.T) {\n\tsnapshotName := fmt.Sprintf(\"tf-test-%s\", acctest.RandString(10))\n\tvar snapshot compute.Snapshot\n\tdiskName := fmt.Sprintf(\"tf-test-%s\", acctest.RandString(10))\n\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckComputeSnapshotDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccComputeSnapshot_basic(snapshotName, diskName),\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckComputeSnapshotExists(\n\t\t\t\t\t\t\"google_compute_snapshot.foobar\", &snapshot),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc TestAccComputeSnapshot_encryption(t *testing.T) {\n\tsnapshotName := fmt.Sprintf(\"tf-test-%s\", acctest.RandString(10))\n\tvar snapshot compute.Snapshot\n\tdiskName := fmt.Sprintf(\"tf-test-%s\", acctest.RandString(10))\n\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckComputeSnapshotDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccComputeSnapshot_encryption(snapshotName, diskName),\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckComputeSnapshotExists(\n\t\t\t\t\t\t\"google_compute_snapshot.foobar\", &snapshot),\n\t\t\t\t\ttestAccCheckSnapshotEncryptionKey(\n\t\t\t\t\t\t\"google_compute_snapshot.foobar\", &snapshot),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc testAccCheckComputeSnapshotDestroy(s *terraform.State) error {\n\tconfig := testAccProvider.Meta().(*Config)\n\n\tfor _, rs := range s.RootModule().Resources {\n\t\tif rs.Type != \"google_compute_snapshot\" {\n\t\t\tcontinue\n\t\t}\n\n\t\t_, err := config.clientCompute.Snapshots.Get(\n\t\t\tconfig.Project, rs.Primary.ID).Do()\n\t\tif err == nil {\n\t\t\treturn fmt.Errorf(\"Snapshot still exists\")\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc testAccCheckComputeSnapshotExists(n string, snapshot *compute.Snapshot) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\trs, ok := s.RootModule().Resources[n]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Not found: %s\", n)\n\t\t}\n\n\t\tif rs.Primary.ID == \"\" {\n\t\t\treturn fmt.Errorf(\"No ID is set\")\n\t\t}\n\n\t\tconfig := testAccProvider.Meta().(*Config)\n\n\t\tfound, err := config.clientCompute.Snapshots.Get(\n\t\t\tconfig.Project, rs.Primary.ID).Do()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif found.Name != rs.Primary.ID {\n\t\t\treturn fmt.Errorf(\"Snapshot not found\")\n\t\t}\n\n\t\t*snapshot = *found\n\n\t\treturn nil\n\t}\n}\n\nfunc testAccCheckSnapshotEncryptionKey(n string, snapshot *compute.Snapshot) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\trs, ok := s.RootModule().Resources[n]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Not found: %s\", n)\n\t\t}\n\n\t\tattr := rs.Primary.Attributes[\"snapshot_encryption_key_sha256\"]\n\t\tif snapshot.SnapshotEncryptionKey == nil && attr != \"\" {\n\t\t\treturn fmt.Errorf(\"Snapshot %s has mismatched encryption key.\\nTF State: %+v\\nGCP State: <empty>\", n, attr)\n\t\t}\n\n\t\tif attr != snapshot.SnapshotEncryptionKey.Sha256 {\n\t\t\treturn fmt.Errorf(\"Snapshot %s has mismatched encryption key.\\nTF State: %+v.\\nGCP State: %+v\",\n\t\t\t\tn, attr, snapshot.SnapshotEncryptionKey.Sha256)\n\t\t}\n\t\treturn nil\n\t}\n}\n\nfunc testAccComputeSnapshot_basic(snapshotName string, diskName string) string {\n\treturn fmt.Sprintf(`\nresource \"google_compute_disk\" \"foobar\" {\n\tname = \"%s\"\n\timage = \"debian-8-jessie-v20160921\"\n\tsize = 10\n\ttype = \"pd-ssd\"\n\tzone = \"us-central1-a\"\n}\n\nresource \"google_compute_snapshot\" \"foobar\" {\n\tname = \"%s\"\n\tdisk = \"${google_compute_disk.foobar.name}\"\n\tzone = \"us-central1-a\"\n}`, diskName, snapshotName)\n}\n\nfunc testAccComputeSnapshot_encryption(snapshotName string, diskName string) string {\n\treturn fmt.Sprintf(`\nresource \"google_compute_disk\" \"foobar\" {\n\tname = \"%s\"\n\timage = \"debian-8-jessie-v20160803\"\n\tsize = 50\n\ttype = \"pd-ssd\"\n\tzone = \"us-central1-a\"\n}\nresource \"google_compute_snapshot\" \"foobar\" {\n\tname = \"%s\"\n\tdisk = \"%s\"\n\tzone = \"us-central1-a\"\n\tsnapshot_encryption_key_raw = \"SGVsbG8gZnJvbSBHb29nbGUgQ2xvdWQgUGxhdGZvcm0=\"\n}`, diskName, snapshotName, diskName)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ reference:\n\/\/ http:\/\/stackoverflow.com\/questions\/10171941\/need-help-understanding-why-select-isnt-blocking-forever\n\npackage main\n\nimport (\n\t\"crypto\/md5\"\n\t\"fmt\"\n\t\"github.com\/smartystreets\/goconvey\/web\/server\/parser\"\n\t\"github.com\/smartystreets\/goconvey\/web\/server\/results\"\n\t\"io\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n)\n\nfunc runTests(path string) *TestPackage {\n\tif err := os.Chdir(path); err != nil {\n\t\tpanic(fmt.Sprintf(\"Could not change dir to %s\", path))\n\t}\n\n\texec.Command(\"go\", \"test\", \"-i\").Run()\n\toutput, _ := exec.Command(\"go\", \"test\", \"-v\", \"-timeout=-42s\").CombinedOutput()\n\tstringOutput := string(output)\n\n\tpackageIndex := strings.Index(path, \"\/src\/\")\n\tpackageName := path[packageIndex+len(\"\/src\/\"):]\n\tresult := parser.ParsePackageResults(packageName, stringOutput)\n\treturn &TestPackage{\n\t\tPath:   path,\n\t\tOutput: stringOutput,\n\t\tParsed: result,\n\t}\n}\n\nfunc worker(in chan string, out chan *TestPackage) {\n\tfor path := range in {\n\t\tout <- runTests(path)\n\t}\n}\n\nfunc main() {\n\tfolders := []string{\n\t\t\"\/Users\/mike\/work\/dev\/goconvey\/src\/github.com\/smartystreets\/goconvey\/assertions\",\n\t\t\"\/Users\/mike\/work\/dev\/goconvey\/src\/github.com\/smartystreets\/goconvey\/convey\",\n\t\t\"\/Users\/mike\/work\/dev\/goconvey\/src\/github.com\/smartystreets\/goconvey\/web\/server\",\n\t\t\"\/Users\/mike\/work\/dev\/goconvey\/src\/github.com\/smartystreets\/goconvey\/web\/server\/parser\",\n\t\t\"\/Users\/mike\/work\/dev\/goconvey\/src\/github.com\/smartystreets\/goconvey\/reporting\",\n\t\t\"\/Users\/mike\/work\/dev\/goconvey\/src\/github.com\/smartystreets\/goconvey\/printing\",\n\t\t\"\/Users\/mike\/work\/dev\/goconvey\/src\/github.com\/smartystreets\/goconvey\/execution\",\n\t}\n\n\tnumWorkers := len(folders)\n\n\t\/\/ spawn workers\n\tin, out := make(chan string), make(chan *TestPackage)\n\tfor i := 0; i < numWorkers; i++ {\n\t\tgo worker(in, out)\n\t}\n\n\t\/\/ schedule tasks\n\tgo func() {\n\t\tfor _, f := range folders {\n\t\t\tin <- f\n\t\t}\n\t}()\n\n\tresults := []*TestPackage{}\n\tfor _ = range folders {\n\t\tresults = append(results, <-out)\n\t}\n\n\trevision := md5.New()\n\n\tfor _, output := range results {\n\t\tio.WriteString(revision, output.Path)\n\t}\n\n\tfmt.Println(string(revision.Sum(nil)))\n}\n\ntype TestPackage struct {\n\tPath   string\n\tOutput string\n\tParsed *results.PackageResult\n}\n<commit_msg>Removed reference file.<commit_after><|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com\/nlopes\/slack\"\n)\n\nfunc main() {\n\tapi := slack.New(\"YOUR TOKEN HERE\")\n\tlogger := log.New(os.Stdout, \"slack-bot: \", log.Lshortfile|log.LstdFlags)\n\tslack.SetLogger(logger)\n\tapi.SetDebug(true)\n\n\trtm := api.NewRTM()\n\tgo rtm.ManageConnection()\n\nLoop:\n\tfor {\n\t\tselect {\n\t\tcase msg := <-rtm.IncomingEvents:\n\t\t\tfmt.Print(\"Event Received: \")\n\t\t\tswitch ev := msg.Data.(type) {\n\t\t\tcase *slack.HelloEvent:\n\t\t\t\t\/\/ Ignore hello\n\n\t\t\tcase *slack.ConnectedEvent:\n\t\t\t\tfmt.Println(\"Infos:\", ev.Info)\n\t\t\t\tfmt.Println(\"Connection counter:\", ev.ConnectionCount)\n\t\t\t\t\/\/ Replace #general with your Channel ID\n\t\t\t\trtm.SendMessage(rtm.NewOutgoingMessage(\"Hello world\", \"#general\"))\n\n\t\t\tcase *slack.MessageEvent:\n\t\t\t\tfmt.Printf(\"Message: %v\\n\", ev)\n\n\t\t\tcase *slack.PresenceChangeEvent:\n\t\t\t\tfmt.Printf(\"Presence Change: %v\\n\", ev)\n\n\t\t\tcase *slack.LatencyReport:\n\t\t\t\tfmt.Printf(\"Current latency: %v\\n\", ev.Value)\n\n\t\t\tcase *slack.RTMError:\n\t\t\t\tfmt.Printf(\"Error: %s\\n\", ev.Error())\n\n\t\t\tcase *slack.InvalidAuthEvent:\n\t\t\t\tfmt.Printf(\"Invalid credentials\")\n\t\t\t\tbreak Loop\n\n\t\t\tdefault:\n\n\t\t\t\t\/\/ Ignore other events..\n\t\t\t\t\/\/ fmt.Printf(\"Unexpected: %v\\n\", msg.Data)\n\t\t\t}\n\t\t}\n\t}\n}\n<commit_msg>simplify websocket example<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com\/nlopes\/slack\"\n)\n\nfunc main() {\n\tapi := slack.New(\"YOUR TOKEN HERE\")\n\tlogger := log.New(os.Stdout, \"slack-bot: \", log.Lshortfile|log.LstdFlags)\n\tslack.SetLogger(logger)\n\tapi.SetDebug(true)\n\n\trtm := api.NewRTM()\n\tgo rtm.ManageConnection()\n\n\tfor msg := range rtm.IncomingEvents {\n\t\tfmt.Print(\"Event Received: \")\n\t\tswitch ev := msg.Data.(type) {\n\t\tcase *slack.HelloEvent:\n\t\t\t\/\/ Ignore hello\n\n\t\tcase *slack.ConnectedEvent:\n\t\t\tfmt.Println(\"Infos:\", ev.Info)\n\t\t\tfmt.Println(\"Connection counter:\", ev.ConnectionCount)\n\t\t\t\/\/ Replace #general with your Channel ID\n\t\t\trtm.SendMessage(rtm.NewOutgoingMessage(\"Hello world\", \"#general\"))\n\n\t\tcase *slack.MessageEvent:\n\t\t\tfmt.Printf(\"Message: %v\\n\", ev)\n\n\t\tcase *slack.PresenceChangeEvent:\n\t\t\tfmt.Printf(\"Presence Change: %v\\n\", ev)\n\n\t\tcase *slack.LatencyReport:\n\t\t\tfmt.Printf(\"Current latency: %v\\n\", ev.Value)\n\n\t\tcase *slack.RTMError:\n\t\t\tfmt.Printf(\"Error: %s\\n\", ev.Error())\n\n\t\tcase *slack.InvalidAuthEvent:\n\t\t\tfmt.Printf(\"Invalid credentials\")\n\t\t\treturn\n\n\t\tdefault:\n\n\t\t\t\/\/ Ignore other events..\n\t\t\t\/\/ fmt.Printf(\"Unexpected: %v\\n\", msg.Data)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package notifiers\n\nimport (\n\t\"strconv\"\n\n\t\"github.com\/grafana\/grafana\/pkg\/bus\"\n\t\"github.com\/grafana\/grafana\/pkg\/components\/simplejson\"\n\t\"github.com\/grafana\/grafana\/pkg\/log\"\n\t\"github.com\/grafana\/grafana\/pkg\/metrics\"\n\tm \"github.com\/grafana\/grafana\/pkg\/models\"\n\t\"github.com\/grafana\/grafana\/pkg\/services\/alerting\"\n)\n\nfunc init() {\n\talerting.RegisterNotifier(&alerting.NotifierPlugin{\n\t\tType:        \"pagerduty\",\n\t\tName:        \"PagerDuty\",\n\t\tDescription: \"Sends notifications to PagerDuty\",\n\t\tFactory:     NewPagerdutyNotifier,\n\t\tOptionsTemplate: `\n      <h3 class=\"page-heading\">PagerDuty settings<\/h3>\n      <div class=\"gf-form\">\n        <span class=\"gf-form-label width-14\">Integration Key<\/span>\n        <input type=\"text\" required class=\"gf-form-input max-width-22\" ng-model=\"ctrl.model.settings.integrationKey\" placeholder=\"Pagerduty integeration Key\"><\/input>\n      <\/div>\n      <div class=\"gf-form\">\n        <gf-form-switch\n           class=\"gf-form\"\n           label=\"Auto resolve incidents\"\n           label-class=\"width-14\"\n           checked=\"ctrl.model.settings.autoResolve\"\n           tooltip=\"Resolve incidents in pagerduty once the alert goes back to ok.\">\n        <\/gf-form-switch>\n      <\/div>\n    `,\n\t})\n}\n\nvar (\n\tpagerdutyEventApiUrl string = \"https:\/\/events.pagerduty.com\/generic\/2010-04-15\/create_event.json\"\n)\n\nfunc NewPagerdutyNotifier(model *m.AlertNotification) (alerting.Notifier, error) {\n\tautoResolve := model.Settings.Get(\"autoResolve\").MustBool(true)\n\tkey := model.Settings.Get(\"integrationKey\").MustString()\n\tif key == \"\" {\n\t\treturn nil, alerting.ValidationError{Reason: \"Could not find integration key property in settings\"}\n\t}\n\n\treturn &PagerdutyNotifier{\n\t\tNotifierBase: NewNotifierBase(model.Id, model.IsDefault, model.Name, model.Type, model.Settings),\n\t\tKey:          key,\n\t\tAutoResolve:  autoResolve,\n\t\tlog:          log.New(\"alerting.notifier.pagerduty\"),\n\t}, nil\n}\n\ntype PagerdutyNotifier struct {\n\tNotifierBase\n\tKey         string\n\tAutoResolve bool\n\tlog         log.Logger\n}\n\nfunc (this *PagerdutyNotifier) Notify(evalContext *alerting.EvalContext) error {\n\tmetrics.M_Alerting_Notification_Sent_PagerDuty.Inc(1)\n\n\tif evalContext.Rule.State == m.AlertStateOK && !this.AutoResolve {\n\t\tthis.log.Info(\"Not sending a trigger to Pagerduty\", \"state\", evalContext.Rule.State, \"auto resolve\", this.AutoResolve)\n\t\treturn nil\n\t}\n\n\teventType := \"trigger\"\n\tif evalContext.Rule.State == m.AlertStateOK {\n\t\teventType = \"resolve\"\n\t}\n\n\tthis.log.Info(\"Notifying Pagerduty\", \"event_type\", eventType)\n\n\tbodyJSON := simplejson.New()\n\tbodyJSON.Set(\"service_key\", this.Key)\n\tbodyJSON.Set(\"description\", evalContext.Rule.Name+\" - \"+evalContext.Rule.Message)\n\tbodyJSON.Set(\"client\", \"Grafana\")\n\tbodyJSON.Set(\"event_type\", eventType)\n\tbodyJSON.Set(\"incident_key\", \"alertId-\"+strconv.FormatInt(evalContext.Rule.Id, 10))\n\n\truleUrl, err := evalContext.GetRuleUrl()\n\tif err != nil {\n\t\tthis.log.Error(\"Failed get rule link\", \"error\", err)\n\t\treturn err\n\t}\n\tbodyJSON.Set(\"client_url\", ruleUrl)\n\n\tif evalContext.ImagePublicUrl != \"\" {\n\t\tcontexts := make([]interface{}, 1)\n\t\timageJSON := simplejson.New()\n\t\timageJSON.Set(\"type\", \"image\")\n\t\timageJSON.Set(\"src\", evalContext.ImagePublicUrl)\n\t\tcontexts[0] = imageJSON\n\t\tbodyJSON.Set(\"contexts\", contexts)\n\t}\n\n\tbody, _ := bodyJSON.MarshalJSON()\n\n\tcmd := &m.SendWebhookSync{\n\t\tUrl:        pagerdutyEventApiUrl,\n\t\tBody:       string(body),\n\t\tHttpMethod: \"POST\",\n\t}\n\n\tif err := bus.DispatchCtx(evalContext.Ctx, cmd); err != nil {\n\t\tthis.log.Error(\"Failed to send notification to Pagerduty\", \"error\", err, \"body\", string(body))\n\t\treturn err\n\t}\n\n\treturn nil\n}\n<commit_msg>Include triggering metrics to pagerduty alerts<commit_after>package notifiers\n\nimport (\n\t\"strconv\"\n\n\t\"github.com\/grafana\/grafana\/pkg\/bus\"\n\t\"github.com\/grafana\/grafana\/pkg\/components\/simplejson\"\n\t\"github.com\/grafana\/grafana\/pkg\/log\"\n\t\"github.com\/grafana\/grafana\/pkg\/metrics\"\n\tm \"github.com\/grafana\/grafana\/pkg\/models\"\n\t\"github.com\/grafana\/grafana\/pkg\/services\/alerting\"\n)\n\nfunc init() {\n\talerting.RegisterNotifier(&alerting.NotifierPlugin{\n\t\tType:        \"pagerduty\",\n\t\tName:        \"PagerDuty\",\n\t\tDescription: \"Sends notifications to PagerDuty\",\n\t\tFactory:     NewPagerdutyNotifier,\n\t\tOptionsTemplate: `\n      <h3 class=\"page-heading\">PagerDuty settings<\/h3>\n      <div class=\"gf-form\">\n        <span class=\"gf-form-label width-14\">Integration Key<\/span>\n        <input type=\"text\" required class=\"gf-form-input max-width-22\" ng-model=\"ctrl.model.settings.integrationKey\" placeholder=\"Pagerduty integeration Key\"><\/input>\n      <\/div>\n      <div class=\"gf-form\">\n        <gf-form-switch\n           class=\"gf-form\"\n           label=\"Auto resolve incidents\"\n           label-class=\"width-14\"\n           checked=\"ctrl.model.settings.autoResolve\"\n           tooltip=\"Resolve incidents in pagerduty once the alert goes back to ok.\">\n        <\/gf-form-switch>\n      <\/div>\n    `,\n\t})\n}\n\nvar (\n\tpagerdutyEventApiUrl string = \"https:\/\/events.pagerduty.com\/generic\/2010-04-15\/create_event.json\"\n)\n\nfunc NewPagerdutyNotifier(model *m.AlertNotification) (alerting.Notifier, error) {\n\tautoResolve := model.Settings.Get(\"autoResolve\").MustBool(true)\n\tkey := model.Settings.Get(\"integrationKey\").MustString()\n\tif key == \"\" {\n\t\treturn nil, alerting.ValidationError{Reason: \"Could not find integration key property in settings\"}\n\t}\n\n\treturn &PagerdutyNotifier{\n\t\tNotifierBase: NewNotifierBase(model.Id, model.IsDefault, model.Name, model.Type, model.Settings),\n\t\tKey:          key,\n\t\tAutoResolve:  autoResolve,\n\t\tlog:          log.New(\"alerting.notifier.pagerduty\"),\n\t}, nil\n}\n\ntype PagerdutyNotifier struct {\n\tNotifierBase\n\tKey         string\n\tAutoResolve bool\n\tlog         log.Logger\n}\n\nfunc (this *PagerdutyNotifier) Notify(evalContext *alerting.EvalContext) error {\n\tmetrics.M_Alerting_Notification_Sent_PagerDuty.Inc(1)\n\n\tif evalContext.Rule.State == m.AlertStateOK && !this.AutoResolve {\n\t\tthis.log.Info(\"Not sending a trigger to Pagerduty\", \"state\", evalContext.Rule.State, \"auto resolve\", this.AutoResolve)\n\t\treturn nil\n\t}\n\n\teventType := \"trigger\"\n\tif evalContext.Rule.State == m.AlertStateOK {\n\t\teventType = \"resolve\"\n\t}\n\tcustomData := make([]map[string]interface{}, 0)\n\tfieldLimitCount := 4\n\tfor index, evt := range evalContext.EvalMatches {\n\t\tcustomData = append(customData, map[string]interface{}{\n\t\t\tevt.Metric: evt.Value,\n\t\t})\n\t\tif index > fieldLimitCount {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tthis.log.Info(\"Notifying Pagerduty\", \"event_type\", eventType)\n\n\tbodyJSON := simplejson.New()\n\tbodyJSON.Set(\"service_key\", this.Key)\n\tbodyJSON.Set(\"description\", evalContext.Rule.Name+\" - \"+evalContext.Rule.Message)\n\tbodyJSON.Set(\"client\", \"Grafana\")\n\tbodyJSON.Set(\"details\", customData)\n\tbodyJSON.Set(\"event_type\", eventType)\n\tbodyJSON.Set(\"incident_key\", \"alertId-\"+strconv.FormatInt(evalContext.Rule.Id, 10))\n\n\truleUrl, err := evalContext.GetRuleUrl()\n\tif err != nil {\n\t\tthis.log.Error(\"Failed get rule link\", \"error\", err)\n\t\treturn err\n\t}\n\tbodyJSON.Set(\"client_url\", ruleUrl)\n\n\tif evalContext.ImagePublicUrl != \"\" {\n\t\tcontexts := make([]interface{}, 1)\n\t\timageJSON := simplejson.New()\n\t\timageJSON.Set(\"type\", \"image\")\n\t\timageJSON.Set(\"src\", evalContext.ImagePublicUrl)\n\t\tcontexts[0] = imageJSON\n\t\tbodyJSON.Set(\"contexts\", contexts)\n\t}\n\n\tbody, _ := bodyJSON.MarshalJSON()\n\n\tcmd := &m.SendWebhookSync{\n\t\tUrl:        pagerdutyEventApiUrl,\n\t\tBody:       string(body),\n\t\tHttpMethod: \"POST\",\n\t}\n\n\tif err := bus.DispatchCtx(evalContext.Ctx, cmd); err != nil {\n\t\tthis.log.Error(\"Failed to send notification to Pagerduty\", \"error\", err, \"body\", string(body))\n\t\treturn err\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package error_handling\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\n\t\"github.com\/aschepis\/api_patterns\/rendering\"\n)\n\n\/\/ error type suitable for returning to\ntype APIError struct {\n\terr        error\n\tMessage    string `json:\"message\"`\n\tStatusCode int    `json:\"-\"`\n}\n\n\/\/ a function type that returns an APIError\ntype APIErrorFunc func() *APIError\n\n\/\/ wrapper to generate api error for internal errors\nfunc InternalError() *APIError {\n\treturn &APIError{\n\t\tMessage:    fmt.Sprintf(\"Internal Server Error\"),\n\t\tStatusCode: http.StatusInternalServerError,\n\t}\n}\n\n\/\/ wrapper to generate api error for Forbidden errors\nfunc ForbiddenError() *APIError {\n\treturn &APIError{\n\t\tMessage:    fmt.Sprintf(\"Forbidden\"),\n\t\tStatusCode: http.StatusForbidden,\n\t}\n}\n\n\/\/ wrapper to generate api error for Forbidden errors\nfunc NotFoundError() *APIError {\n\treturn &APIError{\n\t\tMessage:    fmt.Sprintf(\"Not Found\"),\n\t\tStatusCode: http.StatusNotFound,\n\t}\n}\n\n\/\/ helper for generating api error objects\nfunc MakeAPIError(err error, code int) *APIError {\n\treturn &APIError{\n\t\tMessage:    err.Error(),\n\t\tStatusCode: code,\n\t}\n}\n\n\/\/ Handy wrapper function to help with giving decent error responses\/codes\n\/\/ when an error occurs.\nfunc WrapError(w http.ResponseWriter, r rendering.RenderFunc, f APIErrorFunc) {\n\tif err := f(); err != nil {\n\t\tw.WriteHeader(err.StatusCode)\n\t\tr(w, err)\n\t}\n}\n<commit_msg>add details to api error output<commit_after>package error_handling\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\n\t\"github.com\/aschepis\/api_patterns\/rendering\"\n)\n\n\/\/ error type suitable for returning to\ntype APIError struct {\n\terr        error\n\tMessage    interface{} `json:\"message\"`\n\tStatusCode int         `json:\"-\"`\n}\n\n\/\/ a function type that returns an APIError\ntype APIErrorFunc func() *APIError\n\n\/\/ wrapper to generate api error for internal errors\nfunc InternalError() *APIError {\n\treturn &APIError{\n\t\tMessage:    fmt.Sprintf(\"Internal Server Error\"),\n\t\tStatusCode: http.StatusInternalServerError,\n\t}\n}\n\n\/\/ wrapper to generate api error for Forbidden errors\nfunc ForbiddenError() *APIError {\n\treturn &APIError{\n\t\tMessage:    fmt.Sprintf(\"Forbidden\"),\n\t\tStatusCode: http.StatusForbidden,\n\t}\n}\n\n\/\/ wrapper to generate api error for Forbidden errors\nfunc NotFoundError() *APIError {\n\treturn &APIError{\n\t\tMessage:    fmt.Sprintf(\"Not Found\"),\n\t\tStatusCode: http.StatusNotFound,\n\t}\n}\n\n\/\/ helper for generating api error objects\nfunc MakeAPIError(err error, code int) *APIError {\n\treturn &APIError{\n\t\tMessage:    err.Error(),\n\t\tStatusCode: code,\n\t}\n}\n\n\/\/ helper for generating api error objects\nfunc MakeDetailedAPIError(err error, code int, details interface{}) *APIError {\n\terrorMap := map[string]interface{}{\n\t\t\"error\":   err.Error(),\n\t\t\"details\": details,\n\t}\n\treturn &APIError{\n\t\tMessage:    errorMap,\n\t\tStatusCode: code,\n\t}\n}\n\n\/\/ Handy wrapper function to help with giving decent error responses\/codes\n\/\/ when an error occurs.\nfunc WrapError(w http.ResponseWriter, r rendering.RenderFunc, f APIErrorFunc) {\n\tif err := f(); err != nil {\n\t\tw.WriteHeader(err.StatusCode)\n\t\tr(w, err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package server\n\nimport (\n\t\"fmt\"\n\n\t\"go.pachyderm.com\/pachyderm\/src\/pps\/persist\"\n\t\"go.pedge.io\/google-protobuf\"\n\t\"golang.org\/x\/net\/context\"\n)\n\nfunc getPipeline(persistAPIClient persist.APIClient, name string) (*persist.Pipeline, error) {\n\tpipelines, err := persistAPIClient.GetPipelinesByName(context.Background(), &google_protobuf.StringValue{Value: name})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(pipelines.Pipeline) == 0 {\n\t\treturn nil, fmt.Errorf(\"pachyderm.pps.watch.server: no piplines for name %s\", name)\n\t}\n\treturn pipelines.Pipeline[0], nil\n}\n\nfunc getAllPipelines(persistAPIClient persist.APIClient) ([]*persist.Pipeline, error) {\n\tprotoPipelines, err := persistAPIClient.GetAllPipelines(context.Background(), emptyInstance)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpipelineMap := make(map[string]*persist.Pipeline)\n\tfor _, pipeline := range protoPipelines.Pipeline {\n\t\t\/\/ pipelines are ordered newest to oldest, so if we have already\n\t\t\/\/ seen a pipeline with the same name, it is newer\n\t\tif _, ok := pipelineMap[pipeline.Name]; !ok {\n\t\t\tpipelineMap[pipeline.Name] = pipeline\n\t\t}\n\t}\n\tpipelines := make([]*persist.Pipeline, len(pipelineMap))\n\ti := 0\n\tfor _, pipeline := range pipelineMap {\n\t\tpipelines[i] = pipeline\n\t\ti++\n\t}\n\treturn pipelines, nil\n}\n\nfunc getJobsByPipelineName(persistAPIClient persist.APIClient, name string) ([]*persist.Job, error) {\n\tpipelines, err := persistAPIClient.GetPipelinesByName(context.Background(), &google_protobuf.StringValue{Value: name})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(pipelines.Pipeline) == 0 {\n\t\treturn nil, fmt.Errorf(\"pachyderm.pps.watch.server: no piplines for name %s\", name)\n\t}\n\tvar jobs []*persist.Job\n\tfor _, pipeline := range pipelines.Pipeline {\n\t\tprotoJobs, err := persistAPIClient.GetJobsByPipelineID(context.Background(), &google_protobuf.StringValue{Value: pipeline.Id})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(protoJobs.Job) > 0 {\n\t\t\tjobs = append(jobs, protoJobs.Job...)\n\t\t}\n\t}\n\t\/\/ TODO(pedge): sort by timestamp\n\treturn jobs, nil\n}\n<commit_msg>sort jobs by created at desc for pps watch api server implementation<commit_after>package server\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n\n\t\"go.pachyderm.com\/pachyderm\/src\/pps\/persist\"\n\t\"go.pedge.io\/google-protobuf\"\n\t\"go.pedge.io\/proto\/time\"\n\t\"golang.org\/x\/net\/context\"\n)\n\nfunc getPipeline(persistAPIClient persist.APIClient, name string) (*persist.Pipeline, error) {\n\tpipelines, err := persistAPIClient.GetPipelinesByName(context.Background(), &google_protobuf.StringValue{Value: name})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(pipelines.Pipeline) == 0 {\n\t\treturn nil, fmt.Errorf(\"pachyderm.pps.watch.server: no piplines for name %s\", name)\n\t}\n\treturn pipelines.Pipeline[0], nil\n}\n\nfunc getAllPipelines(persistAPIClient persist.APIClient) ([]*persist.Pipeline, error) {\n\tprotoPipelines, err := persistAPIClient.GetAllPipelines(context.Background(), emptyInstance)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpipelineMap := make(map[string]*persist.Pipeline)\n\tfor _, pipeline := range protoPipelines.Pipeline {\n\t\t\/\/ pipelines are ordered newest to oldest, so if we have already\n\t\t\/\/ seen a pipeline with the same name, it is newer\n\t\tif _, ok := pipelineMap[pipeline.Name]; !ok {\n\t\t\tpipelineMap[pipeline.Name] = pipeline\n\t\t}\n\t}\n\tpipelines := make([]*persist.Pipeline, len(pipelineMap))\n\ti := 0\n\tfor _, pipeline := range pipelineMap {\n\t\tpipelines[i] = pipeline\n\t\ti++\n\t}\n\treturn pipelines, nil\n}\n\nfunc getJobsByPipelineName(persistAPIClient persist.APIClient, name string) ([]*persist.Job, error) {\n\tpipelines, err := persistAPIClient.GetPipelinesByName(context.Background(), &google_protobuf.StringValue{Value: name})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(pipelines.Pipeline) == 0 {\n\t\treturn nil, fmt.Errorf(\"pachyderm.pps.watch.server: no piplines for name %s\", name)\n\t}\n\tvar jobs []*persist.Job\n\tfor _, pipeline := range pipelines.Pipeline {\n\t\tprotoJobs, err := persistAPIClient.GetJobsByPipelineID(context.Background(), &google_protobuf.StringValue{Value: pipeline.Id})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif len(protoJobs.Job) > 0 {\n\t\t\tjobs = append(jobs, protoJobs.Job...)\n\t\t}\n\t}\n\tsort.Sort(jobsByCreatedAtDesc(jobs))\n\treturn jobs, nil\n}\n\ntype jobsByCreatedAtDesc []*persist.Job\n\nfunc (s jobsByCreatedAtDesc) Len() int      { return len(s) }\nfunc (s jobsByCreatedAtDesc) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\nfunc (s jobsByCreatedAtDesc) Less(i, j int) bool {\n\treturn prototime.TimestampLess(s[j].CreatedAt, s[i].CreatedAt)\n}\n<|endoftext|>"}
{"text":"<commit_before>package postgresql\n\nimport (\n\t\"errors\"\n\t\"time\"\n\n\t\"github.com\/tecsisa\/authorizr\/api\"\n)\n\n\/\/ User database\ntype User struct {\n\tID         int    `gorm:\"primary_key\"`\n\tExternalID string `gorm:\"not null;unique\"`\n\tPath       string `gorm:\"not null\"`\n\tCreateDate int64  `gorm:\"not null\"`\n\tUrn        string `gorm:\"not null;unique\"`\n}\n\n\/\/ set User's table name to be `profiles\nfunc (User) TableName() string {\n\treturn \"users\"\n}\n\nfunc (u PostgresRepo) GetUserByID(id string) (*api.User, error) {\n\tuser := &User{}\n\terr := u.Dbmap.Where(\"external_id like ?\", id).Find(user).Error\n\t\/\/ Error Handling\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif user != nil {\n\t\treturn userDBToUserAPI(user), nil\n\t}\n\treturn nil, nil\n}\n\nfunc (u PostgresRepo) AddUser(user api.User) (*api.User, error) {\n\tuserDB := &User{\n\t\tExternalID: user.ExternalID,\n\t\tPath:       user.Path,\n\t\tCreateDate: time.Now().UTC().UnixNano(),\n\t\tUrn:        user.Urn,\n\t}\n\n\terr := u.Dbmap.Create(userDB).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn userDBToUserAPI(userDB), nil\n}\n\nfunc (u PostgresRepo) GetUsersFiltered(path string) ([]api.User, error) {\n\tusers := []User{}\n\tquery := u.Dbmap\n\tif len(path) > 0 {\n\t\tquery = query.Where(\"path like ?\", path+\"%\")\n\t}\n\n\tif err := query.Where(\"name = ?\", \"jinzhu\").First(&users).Error; err != nil {\n\t\treturn nil, err\n\t}\n\n\tif users != nil {\n\t\tapiusers := make([]api.User, len(users), cap(users))\n\t\tfor i, u := range users {\n\t\t\tapiusers[i] = *userDBToUserAPI(&u)\n\t\t}\n\t\treturn apiusers, nil\n\t}\n\n\treturn nil, nil\n}\n\nfunc (u PostgresRepo) GetGroupsByUserID(id string) ([]api.Group, error) {\n\treturn nil, nil\n}\n\nfunc (u PostgresRepo) RemoveUser(id string) error {\n\tuser := &User{}\n\terr := u.Dbmap.Where(\"external_id = ?\", id).Find(user).Error\n\t\/\/ Error Handling\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif user != nil {\n\t\treturn u.Dbmap.Delete(&user).Error\n\t} else {\n\t\treturn errors.New(\"User not found\")\n\t}\n}\n\n\/\/ Transform a user retrieved from db into a user for API\nfunc userDBToUserAPI(userdb *User) *api.User {\n\treturn &api.User{\n\t\tExternalID: userdb.ExternalID,\n\t\tPath:       userdb.Path,\n\t\tDate:       time.Unix(0, userdb.CreateDate).UTC(),\n\t\tUrn:        userdb.Urn,\n\t}\n}\n<commit_msg>corrected query for users filtered<commit_after>package postgresql\n\nimport (\n\t\"errors\"\n\t\"time\"\n\n\t\"github.com\/tecsisa\/authorizr\/api\"\n)\n\n\/\/ User database\ntype User struct {\n\tID         int    `gorm:\"primary_key\"`\n\tExternalID string `gorm:\"not null;unique\"`\n\tPath       string `gorm:\"not null\"`\n\tCreateDate int64  `gorm:\"not null\"`\n\tUrn        string `gorm:\"not null;unique\"`\n}\n\n\/\/ set User's table name to be `profiles\nfunc (User) TableName() string {\n\treturn \"users\"\n}\n\nfunc (u PostgresRepo) GetUserByID(id string) (*api.User, error) {\n\tuser := &User{}\n\terr := u.Dbmap.Where(\"external_id like ?\", id).Find(user).Error\n\t\/\/ Error Handling\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif user != nil {\n\t\treturn userDBToUserAPI(user), nil\n\t}\n\treturn nil, nil\n}\n\nfunc (u PostgresRepo) AddUser(user api.User) (*api.User, error) {\n\tuserDB := &User{\n\t\tExternalID: user.ExternalID,\n\t\tPath:       user.Path,\n\t\tCreateDate: time.Now().UTC().UnixNano(),\n\t\tUrn:        user.Urn,\n\t}\n\n\terr := u.Dbmap.Create(userDB).Error\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn userDBToUserAPI(userDB), nil\n}\n\nfunc (u PostgresRepo) GetUsersFiltered(path string) ([]api.User, error) {\n\tusers := []User{}\n\tquery := u.Dbmap\n\tif len(path) > 0 {\n\t\tquery = query.Where(\"path like ?\", path+\"%\")\n\t}\n\n\tif err := query.Find(&users).Error; err != nil {\n\t\treturn nil, err\n\t}\n\n\tif users != nil {\n\t\tapiusers := make([]api.User, len(users), cap(users))\n\t\tfor i, u := range users {\n\t\t\tapiusers[i] = *userDBToUserAPI(&u)\n\t\t}\n\t\treturn apiusers, nil\n\t}\n\n\treturn nil, nil\n}\n\nfunc (u PostgresRepo) GetGroupsByUserID(id string) ([]api.Group, error) {\n\treturn nil, nil\n}\n\nfunc (u PostgresRepo) RemoveUser(id string) error {\n\tuser := &User{}\n\terr := u.Dbmap.Where(\"external_id = ?\", id).Find(user).Error\n\t\/\/ Error Handling\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif user != nil {\n\t\treturn u.Dbmap.Delete(&user).Error\n\t} else {\n\t\treturn errors.New(\"User not found\")\n\t}\n}\n\n\/\/ Transform a user retrieved from db into a user for API\nfunc userDBToUserAPI(userdb *User) *api.User {\n\treturn &api.User{\n\t\tExternalID: userdb.ExternalID,\n\t\tPath:       userdb.Path,\n\t\tDate:       time.Unix(0, userdb.CreateDate).UTC(),\n\t\tUrn:        userdb.Urn,\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package agent\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\tnet_url \"net\/url\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/resourced\/resourced\/wstrafficker\"\n)\n\nconst (\n\twebsocketPathByAccessTokenPrefix = \"\/api\/ws\/access-tokens\"\n)\n\n\/\/ setWSTrafficker construct WSTrafficker instance.\n\/\/ WSTrafficker carry its own websocket client.\nfunc (a *Agent) setWSTrafficker() error {\n\tvar masterUrl *net_url.URL\n\tvar accessToken string\n\tvar err error\n\n\tfor _, writer := range a.Configs.Writers {\n\t\tif writer.GoStruct == \"ResourcedMaster\" {\n\t\t\turlInterface := writer.GoStructFields[\"Url\"]\n\t\t\tif urlInterface == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\taccessTokenInterface := writer.GoStructFields[\"Username\"]\n\t\t\tif accessTokenInterface == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\taccessToken = accessTokenInterface.(string)\n\n\t\t\tmasterUrl, err = net_url.Parse(urlInterface.(string))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif masterUrl != nil && accessToken != \"\" {\n\t\thostname, err := os.Hostname()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\toriginScheme := \"ws\"\n\t\tif a.IsTLS() {\n\t\t\toriginScheme = \"wss\"\n\t\t}\n\n\t\toriginAddr := a.GeneralConfig.Addr\n\n\t\ttargetScheme := \"ws\"\n\t\tif masterUrl.Scheme == \"https\" {\n\t\t\ttargetScheme = \"wss\"\n\t\t}\n\n\t\toriginURL := fmt.Sprintf(\"%v:\/\/%v\", originScheme, originAddr)\n\t\ttargetURL := fmt.Sprintf(\"%v:\/\/%v%v\/%v\", targetScheme, masterUrl.Host, websocketPathByAccessTokenPrefix, accessToken)\n\n\t\twsSettings := make(map[string]interface{})\n\t\twsSettings[\"Timeout\"] = 1 * time.Second\n\n\t\ttrafficker, err := wstrafficker.NewWSTrafficker(originURL, targetURL, wsSettings)\n\t\tif err != nil {\n\t\t\tlogrus.WithFields(logrus.Fields{\n\t\t\t\t\"Error\":     err.Error(),\n\t\t\t\t\"OriginURL\": originURL,\n\t\t\t\t\"TargetURL\": targetURL,\n\t\t\t\t\"Timeout\":   wsSettings[\"Timeout\"],\n\t\t\t}).Error(\"Failed to establish websocket connection\")\n\t\t\treturn nil\n\t\t}\n\n\t\ta.WSTrafficker = trafficker\n\n\t\tpayload := make(map[string]string)\n\t\tpayload[\"Hostname\"] = hostname\n\n\t\tpayloadJson, err := json.Marshal(payload)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = a.WSTrafficker.Write(1, payloadJson)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tlogrus.WithFields(logrus.Fields{\n\t\t\t\"OriginURL\": originURL,\n\t\t\t\"TargetURL\": targetURL,\n\t\t\t\"Timeout\":   wsSettings[\"Timeout\"],\n\t\t}).Info(\"Established websocket connection\")\n\n\t\t\/\/ Ping and reconnect when neccessary\n\t\ttrafficker.PingAndReconnect()\n\t}\n\n\treturn nil\n}\n<commit_msg>There will be more than 1 ResourcedMaster writer.<commit_after>package agent\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\tnet_url \"net\/url\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/resourced\/resourced\/wstrafficker\"\n)\n\nconst (\n\twebsocketPathByAccessTokenPrefix = \"\/api\/ws\/access-tokens\"\n)\n\n\/\/ setWSTrafficker construct WSTrafficker instance.\n\/\/ WSTrafficker carry its own websocket client.\nfunc (a *Agent) setWSTrafficker() error {\n\tvar masterUrl *net_url.URL\n\tvar accessToken string\n\tvar err error\n\n\tfor _, writer := range a.Configs.Writers {\n\t\tif strings.HasPrefix(writer.GoStruct, \"ResourcedMaster\") {\n\t\t\turlInterface := writer.GoStructFields[\"Url\"]\n\t\t\tif urlInterface == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\taccessTokenInterface := writer.GoStructFields[\"Username\"]\n\t\t\tif accessTokenInterface == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\taccessToken = accessTokenInterface.(string)\n\n\t\t\tmasterUrl, err = net_url.Parse(urlInterface.(string))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif masterUrl != nil && accessToken != \"\" {\n\t\thostname, err := os.Hostname()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\toriginScheme := \"ws\"\n\t\tif a.IsTLS() {\n\t\t\toriginScheme = \"wss\"\n\t\t}\n\n\t\toriginAddr := a.GeneralConfig.Addr\n\n\t\ttargetScheme := \"ws\"\n\t\tif masterUrl.Scheme == \"https\" {\n\t\t\ttargetScheme = \"wss\"\n\t\t}\n\n\t\toriginURL := fmt.Sprintf(\"%v:\/\/%v\", originScheme, originAddr)\n\t\ttargetURL := fmt.Sprintf(\"%v:\/\/%v%v\/%v\", targetScheme, masterUrl.Host, websocketPathByAccessTokenPrefix, accessToken)\n\n\t\twsSettings := make(map[string]interface{})\n\t\twsSettings[\"Timeout\"] = 1 * time.Second\n\n\t\ttrafficker, err := wstrafficker.NewWSTrafficker(originURL, targetURL, wsSettings)\n\t\tif err != nil {\n\t\t\tlogrus.WithFields(logrus.Fields{\n\t\t\t\t\"Error\":     err.Error(),\n\t\t\t\t\"OriginURL\": originURL,\n\t\t\t\t\"TargetURL\": targetURL,\n\t\t\t\t\"Timeout\":   wsSettings[\"Timeout\"],\n\t\t\t}).Error(\"Failed to establish websocket connection\")\n\t\t\treturn nil\n\t\t}\n\n\t\ta.WSTrafficker = trafficker\n\n\t\tpayload := make(map[string]string)\n\t\tpayload[\"Hostname\"] = hostname\n\n\t\tpayloadJson, err := json.Marshal(payload)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = a.WSTrafficker.Write(1, payloadJson)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tlogrus.WithFields(logrus.Fields{\n\t\t\t\"OriginURL\": originURL,\n\t\t\t\"TargetURL\": targetURL,\n\t\t\t\"Timeout\":   wsSettings[\"Timeout\"],\n\t\t}).Info(\"Established websocket connection\")\n\n\t\t\/\/ Ping and reconnect when neccessary\n\t\ttrafficker.PingAndReconnect()\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2018 The Jetstack cert-manager contributors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage validation\n\nimport (\n\t\"k8s.io\/apimachinery\/pkg\/util\/validation\/field\"\n\n\t\"github.com\/jetstack\/cert-manager\/pkg\/apis\/certmanager\/v1alpha1\"\n)\n\n\/\/ Validation functions for cert-manager v1alpha1 Issuer types\n\nfunc ValidateIssuer(iss *v1alpha1.Issuer) field.ErrorList {\n\tallErrs := ValidateIssuerSpec(&iss.Spec, field.NewPath(\"spec\"))\n\treturn allErrs\n}\n\nfunc ValidateIssuerSpec(iss *v1alpha1.IssuerSpec, fldPath *field.Path) field.ErrorList {\n\tel := field.ErrorList{}\n\tel = ValidateIssuerConfig(&iss.IssuerConfig, fldPath)\n\treturn el\n}\n\nfunc ValidateIssuerConfig(iss *v1alpha1.IssuerConfig, fldPath *field.Path) field.ErrorList {\n\tnumConfigs := 0\n\tel := field.ErrorList{}\n\tif iss.ACME != nil {\n\t\tif numConfigs > 0 {\n\t\t\tel = append(el, field.Forbidden(fldPath.Child(\"acme\"), \"may not specify more than one issuer type\"))\n\t\t} else {\n\t\t\tnumConfigs++\n\t\t\tel = append(el, ValidateACMEIssuerConfig(iss.ACME, fldPath.Child(\"acme\"))...)\n\t\t}\n\t}\n\tif iss.CA != nil {\n\t\tif numConfigs > 0 {\n\t\t\tel = append(el, field.Forbidden(fldPath.Child(\"ca\"), \"may not specify more than one issuer type\"))\n\t\t} else {\n\t\t\tnumConfigs++\n\t\t\tel = append(el, ValidateCAIssuerConfig(iss.CA, fldPath.Child(\"ca\"))...)\n\t\t}\n\t}\n\tif iss.SelfSigned != nil {\n\t\tif numConfigs > 0 {\n\t\t\tel = append(el, field.Forbidden(fldPath.Child(\"selfSigned\"), \"may not specify more than one issuer type\"))\n\t\t} else {\n\t\t\tnumConfigs++\n\t\t\tel = append(el, ValidateSelfSignedIssuerConfig(iss.SelfSigned, fldPath.Child(\"selfSigned\"))...)\n\t\t}\n\t}\n\tif iss.Vault != nil {\n\t\tif numConfigs > 0 {\n\t\t\tel = append(el, field.Forbidden(fldPath.Child(\"vault\"), \"may not specify more than one issuer type\"))\n\t\t} else {\n\t\t\tnumConfigs++\n\t\t\tel = append(el, ValidateVaultIssuerConfig(iss.Vault, fldPath.Child(\"vault\"))...)\n\t\t}\n\t}\n\tif numConfigs == 0 {\n\t\tel = append(el, field.Required(fldPath, \"at least one issuer must be configured\"))\n\t}\n\treturn el\n}\n\nfunc ValidateACMEIssuerConfig(iss *v1alpha1.ACMEIssuer, fldPath *field.Path) field.ErrorList {\n\tel := field.ErrorList{}\n\tif len(iss.Email) == 0 {\n\t\tel = append(el, field.Required(fldPath.Child(\"email\"), \"email address is a required field\"))\n\t}\n\tif len(iss.PrivateKey.Name) == 0 {\n\t\tel = append(el, field.Required(fldPath.Child(\"privateKey\", \"name\"), \"private key secret name is a required field\"))\n\t}\n\tif len(iss.Server) == 0 {\n\t\tel = append(el, field.Required(fldPath.Child(\"server\"), \"acme server URL is a required field\"))\n\t}\n\tif iss.HTTP01 != nil {\n\t\tel = append(el, ValidateACMEIssuerHTTP01Config(iss.HTTP01, fldPath.Child(\"http01\"))...)\n\t}\n\tif iss.DNS01 != nil {\n\t\tel = append(el, ValidateACMEIssuerDNS01Config(iss.DNS01, fldPath.Child(\"dns01\"))...)\n\t}\n\treturn el\n}\n\nfunc ValidateCAIssuerConfig(iss *v1alpha1.CAIssuer, fldPath *field.Path) field.ErrorList {\n\tel := field.ErrorList{}\n\tif len(iss.SecretName) == 0 {\n\t\tel = append(el, field.Required(fldPath.Child(\"secretName\"), \"\"))\n\t}\n\treturn el\n}\n\nfunc ValidateSelfSignedIssuerConfig(iss *v1alpha1.SelfSignedIssuer, fldPath *field.Path) field.ErrorList {\n\treturn nil\n}\n\nfunc ValidateVaultIssuerConfig(iss *v1alpha1.VaultIssuer, fldPath *field.Path) field.ErrorList {\n\tel := field.ErrorList{}\n\tif len(iss.Server) == 0 {\n\t\tel = append(el, field.Required(fldPath.Child(\"server\"), \"\"))\n\t}\n\tif len(iss.Path) == 0 {\n\t\tel = append(el, field.Required(fldPath.Child(\"path\"), \"\"))\n\t}\n\treturn el\n\t\/\/ TODO: add validation for Vault authentication types\n}\n\nfunc ValidateACMEIssuerHTTP01Config(iss *v1alpha1.ACMEIssuerHTTP01Config, fldPath *field.Path) field.ErrorList {\n\treturn nil\n}\n\nfunc ValidateACMEIssuerDNS01Config(iss *v1alpha1.ACMEIssuerDNS01Config, fldPath *field.Path) field.ErrorList {\n\tel := field.ErrorList{}\n\tprovidersFldPath := fldPath.Child(\"providers\")\n\tfor i, p := range iss.Providers {\n\t\tfldPath := providersFldPath.Index(i)\n\t\tif len(p.Name) == 0 {\n\t\t\tel = append(el, field.Required(fldPath.Child(\"name\"), \"name must be specified\"))\n\t\t}\n\t\tnumProviders := 0\n\t\tif p.Akamai != nil {\n\t\t\tnumProviders++\n\t\t\tel = append(el, ValidateSecretKeySelector(&p.Akamai.AccessToken, fldPath.Child(\"akamai\", \"accessToken\"))...)\n\t\t\tel = append(el, ValidateSecretKeySelector(&p.Akamai.ClientSecret, fldPath.Child(\"akamai\", \"clientSecret\"))...)\n\t\t\tel = append(el, ValidateSecretKeySelector(&p.Akamai.ClientToken, fldPath.Child(\"akamai\", \"clientToken\"))...)\n\t\t\tif len(p.Akamai.ServiceConsumerDomain) == 0 {\n\t\t\t\tel = append(el, field.Required(fldPath.Child(\"akamai\", \"serviceConsumerDomain\"), \"\"))\n\t\t\t}\n\t\t}\n\t\tif p.AzureDNS != nil {\n\t\t\tif numProviders > 0 {\n\t\t\t\tel = append(el, field.Forbidden(fldPath.Child(\"azuredns\"), \"may not specify more than one provider type\"))\n\t\t\t} else {\n\t\t\t\tnumProviders++\n\t\t\t\tel = append(el, ValidateSecretKeySelector(&p.AzureDNS.ClientSecret, fldPath.Child(\"azuredns\", \"clientSecretSecretRef\"))...)\n\t\t\t\tif len(p.AzureDNS.ClientID) == 0 {\n\t\t\t\t\tel = append(el, field.Required(fldPath.Child(\"azuredns\", \"clientID\"), \"\"))\n\t\t\t\t}\n\t\t\t\tif len(p.AzureDNS.SubscriptionID) == 0 {\n\t\t\t\t\tel = append(el, field.Required(fldPath.Child(\"azuredns\", \"subscriptionID\"), \"\"))\n\t\t\t\t}\n\t\t\t\tif len(p.AzureDNS.TenantID) == 0 {\n\t\t\t\t\tel = append(el, field.Required(fldPath.Child(\"azuredns\", \"tenantID\"), \"\"))\n\t\t\t\t}\n\t\t\t\tif len(p.AzureDNS.ResourceGroupName) == 0 {\n\t\t\t\t\tel = append(el, field.Required(fldPath.Child(\"azuredns\", \"resourceGroupName\"), \"\"))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif p.CloudDNS != nil {\n\t\t\tif numProviders > 0 {\n\t\t\t\tel = append(el, field.Forbidden(fldPath.Child(\"clouddns\"), \"may not specify more than one provider type\"))\n\t\t\t} else {\n\t\t\t\tnumProviders++\n\t\t\t\tel = append(el, ValidateSecretKeySelector(&p.CloudDNS.ServiceAccount, fldPath.Child(\"clouddns\", \"serviceAccountSecretRef\"))...)\n\t\t\t\tif len(p.CloudDNS.Project) == 0 {\n\t\t\t\t\tel = append(el, field.Required(fldPath.Child(\"clouddns\", \"project\"), \"\"))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif p.Cloudflare != nil {\n\t\t\tif numProviders > 0 {\n\t\t\t\tel = append(el, field.Forbidden(fldPath.Child(\"cloudflare\"), \"may not specify more than one provider type\"))\n\t\t\t} else {\n\t\t\t\tnumProviders++\n\t\t\t\tel = append(el, ValidateSecretKeySelector(&p.Cloudflare.APIKey, fldPath.Child(\"cloudflare\", \"apiKeySecretRef\"))...)\n\t\t\t\tif len(p.Cloudflare.Email) == 0 {\n\t\t\t\t\tel = append(el, field.Required(fldPath.Child(\"cloudflare\", \"email\"), \"\"))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif p.Route53 != nil {\n\t\t\tif numProviders > 0 {\n\t\t\t\tel = append(el, field.Forbidden(fldPath.Child(\"route53\"), \"may not specify more than one provider type\"))\n\t\t\t} else {\n\t\t\t\tnumProviders++\n\t\t\t\t\/\/ region is the only required field for route53 as ambient credentials can be used instead\n\t\t\t\tif len(p.Route53.Region) == 0 {\n\t\t\t\t\tel = append(el, field.Required(fldPath.Child(\"route53\", \"region\"), \"\"))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif numProviders == 0 {\n\t\t\tel = append(el, field.Required(fldPath, \"at least one provider must be configured\"))\n\t\t}\n\t}\n\treturn el\n}\n\nfunc ValidateSecretKeySelector(sks *v1alpha1.SecretKeySelector, fldPath *field.Path) field.ErrorList {\n\tel := field.ErrorList{}\n\tif sks.Name == \"\" {\n\t\tel = append(el, field.Required(fldPath.Child(\"name\"), \"secret name is required\"))\n\t}\n\tif sks.Key == \"\" {\n\t\tel = append(el, field.Required(fldPath.Child(\"key\"), \"secret key is required\"))\n\t}\n\treturn el\n}\n<commit_msg>Add validation logic<commit_after>\/*\nCopyright 2018 The Jetstack cert-manager contributors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage validation\n\nimport (\n\t\"k8s.io\/apimachinery\/pkg\/util\/validation\/field\"\n\n\t\"github.com\/jetstack\/cert-manager\/pkg\/apis\/certmanager\/v1alpha1\"\n)\n\n\/\/ Validation functions for cert-manager v1alpha1 Issuer types\n\nfunc ValidateIssuer(iss *v1alpha1.Issuer) field.ErrorList {\n\tallErrs := ValidateIssuerSpec(&iss.Spec, field.NewPath(\"spec\"))\n\treturn allErrs\n}\n\nfunc ValidateIssuerSpec(iss *v1alpha1.IssuerSpec, fldPath *field.Path) field.ErrorList {\n\tel := field.ErrorList{}\n\tel = ValidateIssuerConfig(&iss.IssuerConfig, fldPath)\n\treturn el\n}\n\nfunc ValidateIssuerConfig(iss *v1alpha1.IssuerConfig, fldPath *field.Path) field.ErrorList {\n\tnumConfigs := 0\n\tel := field.ErrorList{}\n\tif iss.ACME != nil {\n\t\tif numConfigs > 0 {\n\t\t\tel = append(el, field.Forbidden(fldPath.Child(\"acme\"), \"may not specify more than one issuer type\"))\n\t\t} else {\n\t\t\tnumConfigs++\n\t\t\tel = append(el, ValidateACMEIssuerConfig(iss.ACME, fldPath.Child(\"acme\"))...)\n\t\t}\n\t}\n\tif iss.CA != nil {\n\t\tif numConfigs > 0 {\n\t\t\tel = append(el, field.Forbidden(fldPath.Child(\"ca\"), \"may not specify more than one issuer type\"))\n\t\t} else {\n\t\t\tnumConfigs++\n\t\t\tel = append(el, ValidateCAIssuerConfig(iss.CA, fldPath.Child(\"ca\"))...)\n\t\t}\n\t}\n\tif iss.SelfSigned != nil {\n\t\tif numConfigs > 0 {\n\t\t\tel = append(el, field.Forbidden(fldPath.Child(\"selfSigned\"), \"may not specify more than one issuer type\"))\n\t\t} else {\n\t\t\tnumConfigs++\n\t\t\tel = append(el, ValidateSelfSignedIssuerConfig(iss.SelfSigned, fldPath.Child(\"selfSigned\"))...)\n\t\t}\n\t}\n\tif iss.Vault != nil {\n\t\tif numConfigs > 0 {\n\t\t\tel = append(el, field.Forbidden(fldPath.Child(\"vault\"), \"may not specify more than one issuer type\"))\n\t\t} else {\n\t\t\tnumConfigs++\n\t\t\tel = append(el, ValidateVaultIssuerConfig(iss.Vault, fldPath.Child(\"vault\"))...)\n\t\t}\n\t}\n\tif numConfigs == 0 {\n\t\tel = append(el, field.Required(fldPath, \"at least one issuer must be configured\"))\n\t}\n\treturn el\n}\n\nfunc ValidateACMEIssuerConfig(iss *v1alpha1.ACMEIssuer, fldPath *field.Path) field.ErrorList {\n\tel := field.ErrorList{}\n\tif len(iss.Email) == 0 {\n\t\tel = append(el, field.Required(fldPath.Child(\"email\"), \"email address is a required field\"))\n\t}\n\tif len(iss.PrivateKey.Name) == 0 {\n\t\tel = append(el, field.Required(fldPath.Child(\"privateKey\", \"name\"), \"private key secret name is a required field\"))\n\t}\n\tif len(iss.Server) == 0 {\n\t\tel = append(el, field.Required(fldPath.Child(\"server\"), \"acme server URL is a required field\"))\n\t}\n\tif iss.HTTP01 != nil {\n\t\tel = append(el, ValidateACMEIssuerHTTP01Config(iss.HTTP01, fldPath.Child(\"http01\"))...)\n\t}\n\tif iss.DNS01 != nil {\n\t\tel = append(el, ValidateACMEIssuerDNS01Config(iss.DNS01, fldPath.Child(\"dns01\"))...)\n\t}\n\treturn el\n}\n\nfunc ValidateCAIssuerConfig(iss *v1alpha1.CAIssuer, fldPath *field.Path) field.ErrorList {\n\tel := field.ErrorList{}\n\tif len(iss.SecretName) == 0 {\n\t\tel = append(el, field.Required(fldPath.Child(\"secretName\"), \"\"))\n\t}\n\treturn el\n}\n\nfunc ValidateSelfSignedIssuerConfig(iss *v1alpha1.SelfSignedIssuer, fldPath *field.Path) field.ErrorList {\n\treturn nil\n}\n\nfunc ValidateVaultIssuerConfig(iss *v1alpha1.VaultIssuer, fldPath *field.Path) field.ErrorList {\n\tel := field.ErrorList{}\n\tif len(iss.Server) == 0 {\n\t\tel = append(el, field.Required(fldPath.Child(\"server\"), \"\"))\n\t}\n\tif len(iss.Path) == 0 {\n\t\tel = append(el, field.Required(fldPath.Child(\"path\"), \"\"))\n\t}\n\treturn el\n\t\/\/ TODO: add validation for Vault authentication types\n}\n\nfunc ValidateACMEIssuerHTTP01Config(iss *v1alpha1.ACMEIssuerHTTP01Config, fldPath *field.Path) field.ErrorList {\n\treturn nil\n}\n\nfunc ValidateACMEIssuerDNS01Config(iss *v1alpha1.ACMEIssuerDNS01Config, fldPath *field.Path) field.ErrorList {\n\tel := field.ErrorList{}\n\tprovidersFldPath := fldPath.Child(\"providers\")\n\tfor i, p := range iss.Providers {\n\t\tfldPath := providersFldPath.Index(i)\n\t\tif len(p.Name) == 0 {\n\t\t\tel = append(el, field.Required(fldPath.Child(\"name\"), \"name must be specified\"))\n\t\t}\n\t\tnumProviders := 0\n\t\tif p.Akamai != nil {\n\t\t\tnumProviders++\n\t\t\tel = append(el, ValidateSecretKeySelector(&p.Akamai.AccessToken, fldPath.Child(\"akamai\", \"accessToken\"))...)\n\t\t\tel = append(el, ValidateSecretKeySelector(&p.Akamai.ClientSecret, fldPath.Child(\"akamai\", \"clientSecret\"))...)\n\t\t\tel = append(el, ValidateSecretKeySelector(&p.Akamai.ClientToken, fldPath.Child(\"akamai\", \"clientToken\"))...)\n\t\t\tif len(p.Akamai.ServiceConsumerDomain) == 0 {\n\t\t\t\tel = append(el, field.Required(fldPath.Child(\"akamai\", \"serviceConsumerDomain\"), \"\"))\n\t\t\t}\n\t\t}\n\t\tif p.AzureDNS != nil {\n\t\t\tif numProviders > 0 {\n\t\t\t\tel = append(el, field.Forbidden(fldPath.Child(\"azuredns\"), \"may not specify more than one provider type\"))\n\t\t\t} else {\n\t\t\t\tnumProviders++\n\t\t\t\tel = append(el, ValidateSecretKeySelector(&p.AzureDNS.ClientSecret, fldPath.Child(\"azuredns\", \"clientSecretSecretRef\"))...)\n\t\t\t\tif len(p.AzureDNS.ClientID) == 0 {\n\t\t\t\t\tel = append(el, field.Required(fldPath.Child(\"azuredns\", \"clientID\"), \"\"))\n\t\t\t\t}\n\t\t\t\tif len(p.AzureDNS.SubscriptionID) == 0 {\n\t\t\t\t\tel = append(el, field.Required(fldPath.Child(\"azuredns\", \"subscriptionID\"), \"\"))\n\t\t\t\t}\n\t\t\t\tif len(p.AzureDNS.TenantID) == 0 {\n\t\t\t\t\tel = append(el, field.Required(fldPath.Child(\"azuredns\", \"tenantID\"), \"\"))\n\t\t\t\t}\n\t\t\t\tif len(p.AzureDNS.ResourceGroupName) == 0 {\n\t\t\t\t\tel = append(el, field.Required(fldPath.Child(\"azuredns\", \"resourceGroupName\"), \"\"))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif p.CloudDNS != nil {\n\t\t\tif numProviders > 0 {\n\t\t\t\tel = append(el, field.Forbidden(fldPath.Child(\"clouddns\"), \"may not specify more than one provider type\"))\n\t\t\t} else {\n\t\t\t\tnumProviders++\n\t\t\t\tel = append(el, ValidateSecretKeySelector(&p.CloudDNS.ServiceAccount, fldPath.Child(\"clouddns\", \"serviceAccountSecretRef\"))...)\n\t\t\t\tif len(p.CloudDNS.Project) == 0 {\n\t\t\t\t\tel = append(el, field.Required(fldPath.Child(\"clouddns\", \"project\"), \"\"))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif p.Cloudflare != nil {\n\t\t\tif numProviders > 0 {\n\t\t\t\tel = append(el, field.Forbidden(fldPath.Child(\"cloudflare\"), \"may not specify more than one provider type\"))\n\t\t\t} else {\n\t\t\t\tnumProviders++\n\t\t\t\tel = append(el, ValidateSecretKeySelector(&p.Cloudflare.APIKey, fldPath.Child(\"cloudflare\", \"apiKeySecretRef\"))...)\n\t\t\t\tif len(p.Cloudflare.Email) == 0 {\n\t\t\t\t\tel = append(el, field.Required(fldPath.Child(\"cloudflare\", \"email\"), \"\"))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif p.Route53 != nil {\n\t\t\tif numProviders > 0 {\n\t\t\t\tel = append(el, field.Forbidden(fldPath.Child(\"route53\"), \"may not specify more than one provider type\"))\n\t\t\t} else {\n\t\t\t\tnumProviders++\n\t\t\t\t\/\/ region is the only required field for route53 as ambient credentials can be used instead\n\t\t\t\tif len(p.Route53.Region) == 0 {\n\t\t\t\t\tel = append(el, field.Required(fldPath.Child(\"route53\", \"region\"), \"\"))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif p.AcmeDNS != nil {\n\t\t\tnumProviders++\n\t\t\tel = append(el, ValidateSecretKeySelector(&p.AcmeDNS.AccountsSecret, fldPath.Child(\"acmedns\", \"accounts\"))...)\n\t\t\tif len(p.AcmeDNS.Host) == 0 {\n\t\t\t\tel = append(el, field.Required(fldPath.Child(\"acmedns\", \"host\"), \"\"))\n\t\t\t}\n\t\t}\n\t\tif numProviders == 0 {\n\t\t\tel = append(el, field.Required(fldPath, \"at least one provider must be configured\"))\n\t\t}\n\t}\n\treturn el\n}\n\nfunc ValidateSecretKeySelector(sks *v1alpha1.SecretKeySelector, fldPath *field.Path) field.ErrorList {\n\tel := field.ErrorList{}\n\tif sks.Name == \"\" {\n\t\tel = append(el, field.Required(fldPath.Child(\"name\"), \"secret name is required\"))\n\t}\n\tif sks.Key == \"\" {\n\t\tel = append(el, field.Required(fldPath.Child(\"key\"), \"secret key is required\"))\n\t}\n\treturn el\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright © 2019 Circonus, Inc. <support@circonus.com>\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\/\/\n\npackage connection\n\nimport (\n\t\"context\"\n\tcrand \"crypto\/rand\"\n\t\"crypto\/tls\"\n\t\"fmt\"\n\t\"math\"\n\t\"math\/big\"\n\t\"math\/rand\"\n\t\"net\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/circonus-labs\/circonus-agent\/internal\/check\"\n\t\"github.com\/circonus-labs\/circonus-agent\/internal\/config\"\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/rs\/zerolog\"\n\t\"github.com\/spf13\/viper\"\n)\n\ntype Connection struct {\n\tlogger          zerolog.Logger\n\tState           string\n\tLastRequestTime *time.Time\n\tagentAddress    string\n\tcommTimeouts    int\n\tconnAttempts    int\n\tdelay           time.Duration\n\tmaxConnRetry    int\n\trevConfig       check.ReverseConfig\n\tsync.Mutex\n}\n\n\/\/ command contains details of the command received from the broker\ntype command struct {\n\terr       error\n\tignore    bool\n\tfatal     bool\n\treset     bool\n\tchannelID uint16\n\tname      string\n\trequest   []byte\n\tmetrics   *[]byte\n\tstart     time.Time\n}\n\n\/\/ noitHeader defines the header received from the noit\/broker\ntype noitHeader struct {\n\tchannelID  uint16\n\tisCommand  bool\n\tpayloadLen uint32\n}\n\n\/\/ noitFrame defines the header + the payload (described by the header) received from the noit\/broker\ntype noitFrame struct {\n\theader  *noitHeader\n\tpayload []byte\n}\n\n\/\/ connError returned from connect(), adds flag indicating whether to retry\ntype connError struct {\n\terr   error\n\tretry bool\n}\n\ntype OpError struct {\n\tErr          string\n\tFatal        bool\n\tRefreshCheck bool\n\tOrigErr      error\n}\n\nfunc (e *OpError) Error() string {\n\tif e == nil {\n\t\treturn \"<nil>\"\n\t}\n\tif e.Err == \"\" {\n\t\treturn e.OrigErr.Error()\n\t}\n\treturn e.Err\n}\n\nconst (\n\tStateConnActive = \"CONN_ACTIVE\" \/\/ connected, broker requesting metrics\n\tStateConnIdle   = \"CONN_IDLE\"   \/\/ connected, no requests\n\tStateNew        = \"NEW\"         \/\/ new, no attempt to connect yet\n\tStateError      = \"ERROR\"       \/\/ connection is erroring\n\tCommandConnect  = \"CONNECT\"     \/\/ Connect command, must be followed by a request payload\n\tCommandReset    = \"RESET\"       \/\/ Reset command, resets the connection\n\n\t\/\/ NOTE: TBD, make some of these user-configurable\n\tCommTimeoutSeconds   = 10    \/\/ seconds, when communicating with noit\n\tDialerTimeoutSeconds = 15    \/\/ seconds, establishing connection\n\tMetricTimeoutSeconds = 50    \/\/ seconds, when communicating with agent\n\tMaxDelaySeconds      = 60    \/\/ maximum amount of delay between attempts\n\tMaxRequests          = -1    \/\/ max requests from broker before resetting connection, -1 = unlimited\n\tMaxPayloadLen        = 65529 \/\/ max unsigned short - 6 (for header)\n\tMaxCommTimeouts      = 6     \/\/ multiply by commTimeout, ensure >(broker polling interval) otherwise conn reset loop\n\tMinDelayStep         = 1     \/\/ minimum seconds to add on retry\n\tMaxDelayStep         = 20    \/\/ maximum seconds to add on retry\n\tConfigRetryLimit     = 5     \/\/ if failed attempts > limit, force check reconfig (see if broker configuration changed)\n)\n\nfunc New(parentLogger zerolog.Logger, agentAddress string, cfg *check.ReverseConfig) (*Connection, error) {\n\tif agentAddress == \"\" {\n\t\treturn nil, errors.Errorf(\"invalid agent address (empty)\")\n\t}\n\tif cfg == nil {\n\t\treturn nil, errors.Errorf(\"invalid config (nil)\")\n\t}\n\n\tif n, err := crand.Int(crand.Reader, big.NewInt(math.MaxInt64)); err != nil {\n\t\trand.Seed(time.Now().UTC().UnixNano())\n\t} else {\n\t\trand.Seed(n.Int64())\n\t}\n\n\tc := Connection{\n\t\tagentAddress: agentAddress,\n\t\trevConfig:    *cfg,\n\t\tState:        StateNew,\n\t\tlogger:       parentLogger.With().Str(\"cn\", cfg.CN).Logger(),\n\t\tconnAttempts: 0,\n\t\tdelay:        1 * time.Second,\n\t\tmaxConnRetry: viper.GetInt(config.KeyReverseMaxConnRetry), \/\/ max times to retry a persistently failing connection\n\t}\n\n\treturn &c, nil\n}\n\n\/\/ Start the reverse connection to the broker\nfunc (c *Connection) Start(ctx context.Context) error {\n\n\tfor {\n\n\t\tconn, cerr := c.connect()\n\t\tif cerr != nil {\n\t\t\tif cerr.retry {\n\t\t\t\tc.logger.Warn().Err(cerr.err).Msg(\"retrying\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tc.logger.Error().Err(cerr.err).Msg(\"unable to establish reverse connection to broker\")\n\t\t\treturn &OpError{\n\t\t\t\tRefreshCheck: true,\n\t\t\t\tOrigErr:      cerr.err,\n\t\t\t}\n\n\t\t}\n\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil\n\t\tdefault:\n\t\t}\n\n\t\tcmdCtx, cmdCancel := context.WithCancel(ctx)\n\t\tdefer cmdCancel()\n\t\tcommandReader := c.newCommandReader(cmdCtx, conn)\n\t\tcommandProcessor := c.newCommandProcessor(cmdCtx, commandReader)\n\n\t\tfor result := range commandProcessor {\n\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\tconn.Close()\n\t\t\t\treturn nil\n\t\t\tdefault:\n\t\t\t}\n\n\t\t\tif result.ignore {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif result.err != nil {\n\t\t\t\tswitch {\n\t\t\t\tcase result.reset:\n\t\t\t\t\tc.logger.Warn().Err(result.err).Int(\"timeouts\", c.commTimeouts).Msg(\"resetting connection\")\n\t\t\t\t\tcmdCancel()\n\t\t\t\tcase result.fatal:\n\t\t\t\t\tc.logger.Error().Err(result.err).Interface(\"result\", result).Msg(\"fatal error, exiting\")\n\t\t\t\t\tconn.Close()\n\t\t\t\t\treturn &OpError{\n\t\t\t\t\t\tFatal:   true,\n\t\t\t\t\t\tOrigErr: result.err,\n\t\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\tc.logger.Error().Err(result.err).Interface(\"result\", result).Msg(\"unhandled error state...\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ send metrics to broker\n\t\t\tif err := c.sendMetricData(conn, result.channelID, result.metrics, result.start); err != nil {\n\t\t\t\tc.logger.Warn().Err(err).Msg(\"sending metric data, resetting connection\")\n\t\t\t\tconn.Close()\n\t\t\t\treturn &OpError{\n\t\t\t\t\tRefreshCheck: true,\n\t\t\t\t\tOrigErr:      err,\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tc.Lock()\n\t\t\tc.State = StateConnActive\n\t\t\treqTime := result.start\n\t\t\tc.LastRequestTime = &reqTime\n\t\t\tc.Unlock()\n\n\t\t\tc.logger.Debug().Uint16(\"channel_id\", result.channelID).Str(\"duration\", time.Since(result.start).String()).Msg(\"CONNECT command request processed\")\n\n\t\t\tc.resetConnectionAttempts()\n\t\t}\n\n\t\tconn.Close()\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil\n\t\tdefault:\n\t\t}\n\t}\n}\n\n\/\/ connect to broker w\/tls and send initial introduction\n\/\/ NOTE: all reverse connections require tls\nfunc (c *Connection) connect() (*tls.Conn, *connError) {\n\tc.Lock()\n\tif c.connAttempts > 0 {\n\t\tif c.maxConnRetry != -1 && c.connAttempts >= c.maxConnRetry {\n\t\t\tc.Unlock()\n\t\t\treturn nil, &connError{retry: false, err: errors.Errorf(\"max broker connection attempts reached (%d of %d)\", c.connAttempts, c.maxConnRetry)}\n\t\t}\n\n\t\tc.logger.Info().\n\t\t\tStr(\"delay\", c.delay.String()).\n\t\t\tInt(\"attempt\", c.connAttempts).\n\t\t\tMsg(\"connect retry\")\n\n\t\ttime.Sleep(c.delay)\n\t\tc.delay = c.getNextDelay(c.delay)\n\n\t\t\/\/ Under normal circumstances the configuration for reverse is\n\t\t\/\/ non-volatile. There are, however, some situations where the\n\t\t\/\/ configuration must be rebuilt. (e.g. ip of broker changed,\n\t\t\/\/ check changed to use a different broker, broker certificate\n\t\t\/\/ changes, cluster membership changes, etc.) The majority of\n\t\t\/\/ configuration based errors are fatal, no attempt is made to\n\t\t\/\/ resolve.\n\t\t\/\/\n\t\t\/\/ TBD determine what pattern(s) emerge with clustered behavior\n\t\t\/\/ given that a connection to each broker in the cluster must\n\t\t\/\/ be maintained since there is no way to identify which broker\n\t\t\/\/ in the cluster is currently responsible for a given check...\n\t\tif c.connAttempts%ConfigRetryLimit == 0 {\n\t\t\t\/\/ Check configuration refresh -- TBD on if check refresh really needed or just find owner again for clustered\n\t\t\tc.Unlock()\n\t\t\treturn nil, &connError{retry: false, err: errors.Errorf(\"max connection attempts (%d), check refresh\", c.connAttempts)}\n\t\t}\n\t}\n\tc.Unlock()\n\n\trevHost := c.revConfig.ReverseURL.Host\n\tc.logger.Debug().Str(\"host\", revHost).Msg(\"connecting\")\n\tc.Lock()\n\tc.connAttempts++\n\tc.Unlock()\n\tdialer := &net.Dialer{Timeout: DialerTimeoutSeconds * time.Second}\n\tconn, err := tls.DialWithDialer(dialer, \"tcp\", c.revConfig.BrokerAddr.String(), c.revConfig.TLSConfig)\n\tif err != nil {\n\t\tif ne, ok := err.(*net.OpError); ok {\n\t\t\tif ne.Timeout() {\n\t\t\t\treturn nil, &connError{retry: ne.Temporary(), err: errors.Wrapf(err, \"timeout connecting to %s\", revHost)}\n\t\t\t}\n\t\t}\n\t\treturn nil, &connError{retry: true, err: errors.Wrapf(err, \"connecting to %s\", revHost)}\n\t}\n\tc.logger.Info().Str(\"host\", revHost).Msg(\"connected\")\n\n\tif err := conn.SetDeadline(time.Now().Add(CommTimeoutSeconds * time.Second)); err != nil {\n\t\tc.logger.Warn().Err(err).Msg(\"setting connection deadline\")\n\t}\n\tintroReq := \"REVERSE \" + c.revConfig.ReverseURL.Path\n\tif c.revConfig.ReverseURL.Fragment != \"\" {\n\t\tintroReq += \"#\" + c.revConfig.ReverseURL.Fragment \/\/ reverse secret is placed here when reverse url is parsed\n\t}\n\tc.logger.Debug().Msg(fmt.Sprintf(\"sending intro '%s'\", introReq))\n\tif _, err := fmt.Fprintf(conn, \"%s HTTP\/1.1\\r\\n\\r\\n\", introReq); err != nil {\n\t\tc.logger.Error().Err(err).Msg(\"sending intro\")\n\t\treturn nil, &connError{retry: true, err: errors.Wrapf(err, \"unable to write intro to %s\", revHost)}\n\t}\n\n\tc.Lock()\n\tc.State = StateConnIdle\n\t\/\/ reset timeouts after successful (re)connection\n\tc.commTimeouts = 0\n\tc.Unlock()\n\n\treturn conn, nil\n}\n\n\/\/ getNextDelay for failed connection attempts\nfunc (c *Connection) getNextDelay(currDelay time.Duration) time.Duration {\n\tmaxDelay := MaxDelaySeconds * time.Second\n\n\tif currDelay == maxDelay {\n\t\treturn currDelay\n\t}\n\n\tdelay := currDelay\n\n\tif delay < maxDelay {\n\t\tdrift := rand.Intn(MaxDelayStep-MinDelayStep) + MinDelayStep\n\t\tdelay += time.Duration(drift) * time.Second\n\t}\n\n\tif delay > maxDelay {\n\t\tdelay = maxDelay\n\t}\n\n\treturn delay\n}\n\n\/\/ resetConnectionAttempts on successful send\/receive\nfunc (c *Connection) resetConnectionAttempts() {\n\tc.Lock()\n\tif c.connAttempts > 0 {\n\t\tc.delay = 1 * time.Second\n\t\tc.connAttempts = 0\n\t}\n\tc.Unlock()\n}\n\n\/\/ Error returns string representation of a connError\nfunc (e *connError) Error() string {\n\treturn e.err.Error()\n}\n<commit_msg>upd: refactor connection handling for reverse when broker closes connection due to simultaneous attempts for same check from multiple agents<commit_after>\/\/ Copyright © 2019 Circonus, Inc. <support@circonus.com>\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\/\/\n\npackage connection\n\nimport (\n\t\"context\"\n\tcrand \"crypto\/rand\"\n\t\"crypto\/tls\"\n\t\"fmt\"\n\t\"math\"\n\t\"math\/big\"\n\t\"math\/rand\"\n\t\"net\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/circonus-labs\/circonus-agent\/internal\/check\"\n\t\"github.com\/circonus-labs\/circonus-agent\/internal\/config\"\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/rs\/zerolog\"\n\t\"github.com\/spf13\/viper\"\n)\n\ntype Connection struct {\n\tlogger          zerolog.Logger\n\tState           string\n\tLastRequestTime *time.Time\n\tagentAddress    string\n\tcommTimeouts    int\n\tconnAttempts    int\n\tdelay           time.Duration\n\tmaxConnRetry    int\n\trevConfig       check.ReverseConfig\n\tsync.Mutex\n}\n\n\/\/ command contains details of the command received from the broker\ntype command struct {\n\terr       error\n\tignore    bool\n\tfatal     bool\n\treset     bool\n\tchannelID uint16\n\tname      string\n\trequest   []byte\n\tmetrics   *[]byte\n\tstart     time.Time\n}\n\n\/\/ noitHeader defines the header received from the noit\/broker\ntype noitHeader struct {\n\tchannelID  uint16\n\tisCommand  bool\n\tpayloadLen uint32\n}\n\n\/\/ noitFrame defines the header + the payload (described by the header) received from the noit\/broker\ntype noitFrame struct {\n\theader  *noitHeader\n\tpayload []byte\n}\n\n\/\/ connError returned from connect(), adds flag indicating whether to retry\ntype connError struct {\n\terr   error\n\tretry bool\n}\n\ntype OpError struct {\n\tErr          string\n\tFatal        bool\n\tRefreshCheck bool\n\tOrigErr      error\n}\n\nfunc (e *OpError) Error() string {\n\tif e == nil {\n\t\treturn \"<nil>\"\n\t}\n\tif e.Err != \"\" {\n\t\treturn e.Err + \": (\" + e.OrigErr.Error() + \")\"\n\t}\n\treturn e.OrigErr.Error()\n}\n\nconst (\n\tStateConnActive = \"CONN_ACTIVE\" \/\/ connected, broker requesting metrics\n\tStateConnIdle   = \"CONN_IDLE\"   \/\/ connected, no requests\n\tStateNew        = \"NEW\"         \/\/ new, no attempt to connect yet\n\tStateError      = \"ERROR\"       \/\/ connection is erroring\n\tCommandConnect  = \"CONNECT\"     \/\/ Connect command, must be followed by a request payload\n\tCommandReset    = \"RESET\"       \/\/ Reset command, resets the connection\n\n\t\/\/ NOTE: TBD, make some of these user-configurable\n\tCommTimeoutSeconds   = 10    \/\/ seconds, when communicating with noit\n\tDialerTimeoutSeconds = 15    \/\/ seconds, establishing connection\n\tMetricTimeoutSeconds = 50    \/\/ seconds, when communicating with agent\n\tMaxDelaySeconds      = 10    \/\/ maximum amount of delay between attempts\n\tMaxRequests          = -1    \/\/ max requests from broker before resetting connection, -1 = unlimited\n\tMaxPayloadLen        = 65529 \/\/ max unsigned short - 6 (for header)\n\tMaxCommTimeouts      = 6     \/\/ multiply by commTimeout, ensure >(broker polling interval) otherwise conn reset loop\n\tMinDelayStep         = 1     \/\/ minimum seconds to add on retry\n\tMaxDelayStep         = 7     \/\/ maximum seconds to add on retry\n\tConfigRetryLimit     = 3     \/\/ if failed attempts > limit, force check reconfig (see if broker configuration changed)\n)\n\nfunc New(parentLogger zerolog.Logger, agentAddress string, cfg *check.ReverseConfig) (*Connection, error) {\n\tif agentAddress == \"\" {\n\t\treturn nil, errors.Errorf(\"invalid agent address (empty)\")\n\t}\n\tif cfg == nil {\n\t\treturn nil, errors.Errorf(\"invalid config (nil)\")\n\t}\n\n\tif n, err := crand.Int(crand.Reader, big.NewInt(math.MaxInt64)); err != nil {\n\t\trand.Seed(time.Now().UTC().UnixNano())\n\t} else {\n\t\trand.Seed(n.Int64())\n\t}\n\n\tc := Connection{\n\t\tagentAddress: agentAddress,\n\t\trevConfig:    *cfg,\n\t\tState:        StateNew,\n\t\tlogger:       parentLogger.With().Str(\"cn\", cfg.CN).Logger(),\n\t\tconnAttempts: 0,\n\t\tdelay:        1 * time.Second,\n\t\tmaxConnRetry: viper.GetInt(config.KeyReverseMaxConnRetry), \/\/ max times to retry a persistently failing connection\n\t}\n\n\treturn &c, nil\n}\n\n\/\/ Start the reverse connection to the broker\nfunc (c *Connection) Start(ctx context.Context) error {\n\tfor {\n\t\tconn, cerr := c.connect(ctx)\n\t\tif cerr != nil {\n\t\t\tif cerr.retry {\n\t\t\t\tc.logger.Warn().Err(cerr.err).Msg(\"retrying\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t\/\/ c.logger.Error().Err(cerr.err).Msg(\"unable to establish reverse connection to broker\")\n\t\t\treturn &OpError{\n\t\t\t\tErr:          \"unable to establish reverse connection to broker\",\n\t\t\t\tRefreshCheck: true,\n\t\t\t\tOrigErr:      cerr.err,\n\t\t\t}\n\t\t}\n\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil\n\t\tdefault:\n\t\t}\n\n\t\tcmdCtx, cmdCancel := context.WithCancel(ctx)\n\t\tdefer cmdCancel()\n\t\tcommandReader := c.newCommandReader(cmdCtx, conn)\n\t\tcommandProcessor := c.newCommandProcessor(cmdCtx, commandReader)\n\n\t\tfor result := range commandProcessor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\tconn.Close()\n\t\t\t\treturn nil\n\t\t\tdefault:\n\t\t\t}\n\n\t\t\tif result.ignore {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif result.err != nil {\n\t\t\t\tswitch {\n\t\t\t\tcase result.reset:\n\t\t\t\t\tc.logger.Warn().Err(result.err).Int(\"timeouts\", c.commTimeouts).Msg(\"resetting connection\")\n\t\t\t\tcase result.fatal:\n\t\t\t\t\tc.logger.Error().Err(result.err).Interface(\"result\", result).Msg(\"fatal error, exiting\")\n\t\t\t\t\tconn.Close()\n\t\t\t\t\treturn &OpError{\n\t\t\t\t\t\tFatal:   true,\n\t\t\t\t\t\tOrigErr: result.err,\n\t\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\tc.logger.Error().Err(result.err).Interface(\"result\", result).Msg(\"unhandled error state...\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tcmdCancel()\n\t\t\t\tbreak \/\/ inner loop for check refresh\n\t\t\t}\n\n\t\t\t\/\/ send metrics to broker\n\t\t\tif err := c.sendMetricData(conn, result.channelID, result.metrics, result.start); err != nil {\n\t\t\t\tc.logger.Warn().Err(err).Msg(\"sending metric data, resetting connection\")\n\t\t\t\tconn.Close()\n\t\t\t\treturn &OpError{\n\t\t\t\t\tRefreshCheck: true,\n\t\t\t\t\tOrigErr:      err,\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tc.Lock()\n\t\t\tc.State = StateConnActive\n\t\t\treqTime := result.start\n\t\t\tc.LastRequestTime = &reqTime\n\t\t\tc.Unlock()\n\n\t\t\tc.logger.Debug().Uint16(\"channel_id\", result.channelID).Str(\"duration\", time.Since(result.start).String()).Msg(\"CONNECT command request processed\")\n\n\t\t\tc.resetConnectionAttempts()\n\t\t}\n\n\t\tconn.Close()\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil\n\t\tdefault:\n\t\t}\n\t}\n}\n\n\/\/ connect to broker w\/tls and send initial introduction\n\/\/ NOTE: all reverse connections require tls\nfunc (c *Connection) connect(ctx context.Context) (*tls.Conn, *connError) {\n\tc.Lock()\n\tif c.connAttempts > 0 {\n\t\tif c.maxConnRetry != -1 && c.connAttempts >= c.maxConnRetry {\n\t\t\tc.Unlock()\n\t\t\treturn nil, &connError{retry: false, err: errors.Errorf(\"max broker connection attempts reached (%d of %d)\", c.connAttempts, c.maxConnRetry)}\n\t\t}\n\n\t\tc.logger.Info().\n\t\t\tStr(\"delay\", c.delay.String()).\n\t\t\tInt(\"attempt\", c.connAttempts).\n\t\t\tMsg(\"connect retry\")\n\n\t\ttime.Sleep(c.delay)\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tc.Unlock()\n\t\t\treturn nil, nil\n\t\tdefault:\n\t\t}\n\t\tc.delay = c.getNextDelay(c.delay)\n\n\t\t\/\/ Under normal circumstances the configuration for reverse is\n\t\t\/\/ non-volatile. There are, however, some situations where the\n\t\t\/\/ configuration must be rebuilt. (e.g. ip of broker changed,\n\t\t\/\/ check changed to use a different broker, broker certificate\n\t\t\/\/ changes, cluster membership changes, etc.) The majority of\n\t\t\/\/ configuration based errors are fatal, no attempt is made to\n\t\t\/\/ resolve.\n\t\t\/\/\n\t\t\/\/ TBD determine what pattern(s) emerge with clustered behavior\n\t\t\/\/ given that a connection to each broker in the cluster must\n\t\t\/\/ be maintained since there is no way to identify which broker\n\t\t\/\/ in the cluster is currently responsible for a given check...\n\t\tif c.connAttempts%ConfigRetryLimit == 0 {\n\t\t\t\/\/ Check configuration refresh -- TBD on if check refresh really needed or just find owner again for clustered\n\t\t\tc.Unlock()\n\t\t\treturn nil, &connError{retry: false, err: errors.Errorf(\"max connection attempts (%d), check refresh\", c.connAttempts)}\n\t\t}\n\t}\n\tc.Unlock()\n\n\trevHost := c.revConfig.ReverseURL.Host\n\tc.logger.Debug().Str(\"host\", revHost).Msg(\"connecting\")\n\tc.Lock()\n\tc.connAttempts++\n\tc.Unlock()\n\tdialer := &net.Dialer{Timeout: DialerTimeoutSeconds * time.Second}\n\tconn, err := tls.DialWithDialer(dialer, \"tcp\", c.revConfig.BrokerAddr.String(), c.revConfig.TLSConfig)\n\tif err != nil {\n\t\tif ne, ok := err.(*net.OpError); ok {\n\t\t\tif ne.Timeout() {\n\t\t\t\treturn nil, &connError{retry: ne.Temporary(), err: errors.Wrapf(err, \"timeout connecting to %s\", revHost)}\n\t\t\t}\n\t\t}\n\t\treturn nil, &connError{retry: true, err: errors.Wrapf(err, \"connecting to %s\", revHost)}\n\t}\n\tc.logger.Info().Str(\"host\", revHost).Msg(\"connected\")\n\n\tif err := conn.SetDeadline(time.Now().Add(CommTimeoutSeconds * time.Second)); err != nil {\n\t\tc.logger.Warn().Err(err).Msg(\"setting connection deadline\")\n\t}\n\tintroReq := \"REVERSE \" + c.revConfig.ReverseURL.Path\n\tif c.revConfig.ReverseURL.Fragment != \"\" {\n\t\tintroReq += \"#\" + c.revConfig.ReverseURL.Fragment \/\/ reverse secret is placed here when reverse url is parsed\n\t}\n\tc.logger.Debug().Msg(fmt.Sprintf(\"sending intro '%s'\", introReq))\n\tif _, err := fmt.Fprintf(conn, \"%s HTTP\/1.1\\r\\n\\r\\n\", introReq); err != nil {\n\t\tc.logger.Error().Err(err).Msg(\"sending intro\")\n\t\treturn nil, &connError{retry: true, err: errors.Wrapf(err, \"unable to write intro to %s\", revHost)}\n\t}\n\n\tc.Lock()\n\tc.State = StateConnIdle\n\t\/\/ reset timeouts after successful (re)connection\n\tc.commTimeouts = 0\n\tc.Unlock()\n\n\treturn conn, nil\n}\n\n\/\/ getNextDelay for failed connection attempts\nfunc (c *Connection) getNextDelay(currDelay time.Duration) time.Duration {\n\tmaxDelay := MaxDelaySeconds * time.Second\n\n\tif currDelay == maxDelay {\n\t\treturn time.Duration(MinDelayStep) * time.Second\n\t}\n\n\tdelay := currDelay\n\n\tif delay < maxDelay {\n\t\tdrift := rand.Intn(MaxDelayStep-MinDelayStep) + MinDelayStep\n\t\tdelay += time.Duration(drift) * time.Second\n\t}\n\n\tif delay > maxDelay {\n\t\tdelay = maxDelay\n\t}\n\n\treturn delay\n}\n\n\/\/ resetConnectionAttempts on successful send\/receive\nfunc (c *Connection) resetConnectionAttempts() {\n\tc.Lock()\n\tif c.connAttempts > 0 {\n\t\tc.delay = 1 * time.Second\n\t\tc.connAttempts = 0\n\t}\n\tc.Unlock()\n}\n\n\/\/ Error returns string representation of a connError\nfunc (e *connError) Error() string {\n\treturn e.err.Error()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage gcscaching\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"sync\"\n\t\"time\"\n\n\t\"golang.org\/x\/net\/context\"\n\n\t\"github.com\/googlecloudplatform\/gcsfuse\/timeutil\"\n\t\"github.com\/jacobsa\/gcloud\/gcs\"\n)\n\n\/\/ Create a bucket that caches object records returned by the supplied wrapped\n\/\/ bucket. Records are invalidated when modifications are made through this\n\/\/ bucket, and after the supplied TTL.\nfunc NewFastStatBucket(\n\tttl time.Duration,\n\tcache StatCache,\n\tclock timeutil.Clock,\n\twrapped gcs.Bucket) (b gcs.Bucket) {\n\tfsb := &fastStatBucket{\n\t\tcache:   cache,\n\t\tclock:   clock,\n\t\twrapped: wrapped,\n\t\tttl:     ttl,\n\t}\n\n\tb = fsb\n\treturn\n}\n\ntype fastStatBucket struct {\n\tmu sync.Mutex\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Dependencies\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\/\/ GUARDED_BY(mu)\n\tcache StatCache\n\n\tclock   timeutil.Clock\n\twrapped gcs.Bucket\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Constant data\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tttl time.Duration\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Helpers\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ LOCKS_EXCLUDED(b.mu)\nfunc (b *fastStatBucket) insertMultiple(objs []*gcs.Object) {\n\tb.mu.Lock()\n\tdefer b.mu.Unlock()\n\n\texpiration := b.clock.Now().Add(b.ttl)\n\tfor _, o := range objs {\n\t\tb.cache.Insert(o, expiration)\n\t}\n}\n\n\/\/ LOCKS_EXCLUDED(b.mu)\nfunc (b *fastStatBucket) insert(o *gcs.Object) {\n\tb.insertMultiple([]*gcs.Object{o})\n}\n\n\/\/ LOCKS_EXCLUDED(b.mu)\nfunc (b *fastStatBucket) invalidate(name string) {\n\tb.mu.Lock()\n\tdefer b.mu.Unlock()\n\n\tb.cache.Erase(name)\n}\n\n\/\/ LOCKS_EXCLUDED(b.mu)\nfunc (b *fastStatBucket) lookUp(name string) (o *gcs.Object) {\n\tb.mu.Lock()\n\tdefer b.mu.Unlock()\n\n\to = b.cache.LookUp(name, b.clock.Now())\n\treturn\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Bucket interface\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nfunc (b *fastStatBucket) Name() string {\n\treturn b.wrapped.Name()\n}\n\nfunc (b *fastStatBucket) NewReader(\n\tctx context.Context,\n\treq *gcs.ReadObjectRequest) (rc io.ReadCloser, err error) {\n\trc, err = b.wrapped.NewReader(ctx, req)\n\treturn\n}\n\n\/\/ LOCKS_EXCLUDED(b.mu)\nfunc (b *fastStatBucket) CreateObject(\n\tctx context.Context,\n\treq *gcs.CreateObjectRequest) (o *gcs.Object, err error) {\n\t\/\/ Throw away any existing record for this object.\n\tb.invalidate(req.Name)\n\n\t\/\/ Create the new object.\n\to, err = b.wrapped.CreateObject(ctx, req)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Record the new object.\n\tb.insert(o)\n\n\treturn\n}\n\n\/\/ LOCKS_EXCLUDED(b.mu)\nfunc (b *fastStatBucket) StatObject(\n\tctx context.Context,\n\treq *gcs.StatObjectRequest) (o *gcs.Object, err error) {\n\t\/\/ Do we already have an entry in the cache?\n\to = b.lookUp(req.Name)\n\tif o != nil {\n\t\treturn\n\t}\n\n\t\/\/ Ask the wrapped bucket.\n\to, err = b.wrapped.StatObject(ctx, req)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Update the cache.\n\tb.insert(o)\n\n\treturn\n}\n\n\/\/ LOCKS_EXCLUDED(b.mu)\nfunc (b *fastStatBucket) ListObjects(\n\tctx context.Context,\n\treq *gcs.ListObjectsRequest) (listing *gcs.Listing, err error) {\n\t\/\/ Fetch the listing.\n\tlisting, err = b.wrapped.ListObjects(ctx, req)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Note anything we found.\n\tb.insertMultiple(listing.Objects)\n\n\treturn\n}\n\n\/\/ LOCKS_EXCLUDED(b.mu)\nfunc (b *fastStatBucket) UpdateObject(\n\tctx context.Context,\n\treq *gcs.UpdateObjectRequest) (o *gcs.Object, err error) {\n\terr = errors.New(\"TODO\")\n\treturn\n}\n\n\/\/ LOCKS_EXCLUDED(b.mu)\nfunc (b *fastStatBucket) DeleteObject(\n\tctx context.Context,\n\tname string) (err error) {\n\terr = errors.New(\"TODO\")\n\treturn\n}\n<commit_msg>fastStatBucket.UpdateObject<commit_after>\/\/ Copyright 2015 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage gcscaching\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"sync\"\n\t\"time\"\n\n\t\"golang.org\/x\/net\/context\"\n\n\t\"github.com\/googlecloudplatform\/gcsfuse\/timeutil\"\n\t\"github.com\/jacobsa\/gcloud\/gcs\"\n)\n\n\/\/ Create a bucket that caches object records returned by the supplied wrapped\n\/\/ bucket. Records are invalidated when modifications are made through this\n\/\/ bucket, and after the supplied TTL.\nfunc NewFastStatBucket(\n\tttl time.Duration,\n\tcache StatCache,\n\tclock timeutil.Clock,\n\twrapped gcs.Bucket) (b gcs.Bucket) {\n\tfsb := &fastStatBucket{\n\t\tcache:   cache,\n\t\tclock:   clock,\n\t\twrapped: wrapped,\n\t\tttl:     ttl,\n\t}\n\n\tb = fsb\n\treturn\n}\n\ntype fastStatBucket struct {\n\tmu sync.Mutex\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Dependencies\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\/\/ GUARDED_BY(mu)\n\tcache StatCache\n\n\tclock   timeutil.Clock\n\twrapped gcs.Bucket\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Constant data\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tttl time.Duration\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Helpers\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ LOCKS_EXCLUDED(b.mu)\nfunc (b *fastStatBucket) insertMultiple(objs []*gcs.Object) {\n\tb.mu.Lock()\n\tdefer b.mu.Unlock()\n\n\texpiration := b.clock.Now().Add(b.ttl)\n\tfor _, o := range objs {\n\t\tb.cache.Insert(o, expiration)\n\t}\n}\n\n\/\/ LOCKS_EXCLUDED(b.mu)\nfunc (b *fastStatBucket) insert(o *gcs.Object) {\n\tb.insertMultiple([]*gcs.Object{o})\n}\n\n\/\/ LOCKS_EXCLUDED(b.mu)\nfunc (b *fastStatBucket) invalidate(name string) {\n\tb.mu.Lock()\n\tdefer b.mu.Unlock()\n\n\tb.cache.Erase(name)\n}\n\n\/\/ LOCKS_EXCLUDED(b.mu)\nfunc (b *fastStatBucket) lookUp(name string) (o *gcs.Object) {\n\tb.mu.Lock()\n\tdefer b.mu.Unlock()\n\n\to = b.cache.LookUp(name, b.clock.Now())\n\treturn\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Bucket interface\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nfunc (b *fastStatBucket) Name() string {\n\treturn b.wrapped.Name()\n}\n\nfunc (b *fastStatBucket) NewReader(\n\tctx context.Context,\n\treq *gcs.ReadObjectRequest) (rc io.ReadCloser, err error) {\n\trc, err = b.wrapped.NewReader(ctx, req)\n\treturn\n}\n\n\/\/ LOCKS_EXCLUDED(b.mu)\nfunc (b *fastStatBucket) CreateObject(\n\tctx context.Context,\n\treq *gcs.CreateObjectRequest) (o *gcs.Object, err error) {\n\t\/\/ Throw away any existing record for this object.\n\tb.invalidate(req.Name)\n\n\t\/\/ Create the new object.\n\to, err = b.wrapped.CreateObject(ctx, req)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Record the new object.\n\tb.insert(o)\n\n\treturn\n}\n\n\/\/ LOCKS_EXCLUDED(b.mu)\nfunc (b *fastStatBucket) StatObject(\n\tctx context.Context,\n\treq *gcs.StatObjectRequest) (o *gcs.Object, err error) {\n\t\/\/ Do we already have an entry in the cache?\n\to = b.lookUp(req.Name)\n\tif o != nil {\n\t\treturn\n\t}\n\n\t\/\/ Ask the wrapped bucket.\n\to, err = b.wrapped.StatObject(ctx, req)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Update the cache.\n\tb.insert(o)\n\n\treturn\n}\n\n\/\/ LOCKS_EXCLUDED(b.mu)\nfunc (b *fastStatBucket) ListObjects(\n\tctx context.Context,\n\treq *gcs.ListObjectsRequest) (listing *gcs.Listing, err error) {\n\t\/\/ Fetch the listing.\n\tlisting, err = b.wrapped.ListObjects(ctx, req)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Note anything we found.\n\tb.insertMultiple(listing.Objects)\n\n\treturn\n}\n\n\/\/ LOCKS_EXCLUDED(b.mu)\nfunc (b *fastStatBucket) UpdateObject(\n\tctx context.Context,\n\treq *gcs.UpdateObjectRequest) (o *gcs.Object, err error) {\n\t\/\/ Throw away any existing record for this object.\n\tb.invalidate(req.Name)\n\n\t\/\/ Update the object.\n\to, err = b.wrapped.UpdateObject(ctx, req)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Record the new version.\n\tb.insert(o)\n\n\treturn\n}\n\n\/\/ LOCKS_EXCLUDED(b.mu)\nfunc (b *fastStatBucket) DeleteObject(\n\tctx context.Context,\n\tname string) (err error) {\n\terr = errors.New(\"TODO\")\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"crypto\/tls\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n\t\"github.com\/prometheus\/common\/log\"\n)\n\nconst (\n\tnamespace = \"apache\" \/\/ For Prometheus metrics.\n)\n\nvar (\n\tlisteningAddress = flag.String(\"telemetry.address\", \":9117\", \"Address on which to expose metrics.\")\n\tmetricsEndpoint  = flag.String(\"telemetry.endpoint\", \"\/metrics\", \"Path under which to expose metrics.\")\n\tscrapeURI        = flag.String(\"scrape_uri\", \"http:\/\/localhost\/server-status\/?auto\", \"URI to apache stub status page.\")\n\tinsecure         = flag.Bool(\"insecure\", false, \"Ignore server certificate if using https.\")\n)\n\ntype Exporter struct {\n\tURI    string\n\tmutex  sync.Mutex\n\tclient *http.Client\n\n\tup             *prometheus.Desc\n\tscrapeFailures prometheus.Counter\n\taccessesTotal  *prometheus.Desc\n\tkBytesTotal    *prometheus.Desc\n\tuptime         *prometheus.Desc\n\tworkers        *prometheus.GaugeVec\n\tscoreboard     *prometheus.GaugeVec\n\tconnections    *prometheus.GaugeVec\n}\n\nfunc NewExporter(uri string) *Exporter {\n\treturn &Exporter{\n\t\tURI: uri,\n\t\tup: prometheus.NewDesc(\n                        prometheus.BuildFQName(namespace, \"\", \"up\"),\n                        \"Could the apache server be reached\",\n                        nil,\n\t\t\tnil),\n                scrapeFailures: prometheus.NewCounter(prometheus.CounterOpts{\n                        Namespace: namespace,\n                        Name:      \"exporter_scrape_failures_total\",\n                        Help:      \"Number of errors while scraping apache.\",\n                }),\n                accessesTotal: prometheus.NewDesc(\n                        prometheus.BuildFQName(namespace, \"\", \"accesses_total\"),\n                        \"Current total apache accesses\",\n                        nil,\n                        nil),\n                kBytesTotal: prometheus.NewDesc(\n                        prometheus.BuildFQName(namespace, \"\", \"sent_kilobytes_total\"),\n                        \"Current total kbytes sent\",\n                        nil,\n                        nil),\n                uptime: prometheus.NewDesc(\n                        prometheus.BuildFQName(namespace, \"\", \"uptime_seconds_total\"),\n                        \"Current uptime in seconds\",\n                        nil,\n                        nil),\n\t\tworkers: prometheus.NewGaugeVec(prometheus.GaugeOpts{\n\t\t\tNamespace: namespace,\n\t\t\tName:      \"workers\",\n\t\t\tHelp:      \"Apache worker statuses\",\n\t\t},\n\t\t\t[]string{\"state\"},\n\t\t),\n\t\tscoreboard: prometheus.NewGaugeVec(prometheus.GaugeOpts{\n\t\t\tNamespace: namespace,\n\t\t\tName:      \"scoreboard\",\n\t\t\tHelp:      \"Apache scoreboard statuses\",\n\t\t},\n\t\t\t[]string{\"state\"},\n\t\t),\n\t\tconnections: prometheus.NewGaugeVec(prometheus.GaugeOpts{\n\t\t\tNamespace: namespace,\n\t\t\tName:      \"connections\",\n\t\t\tHelp:      \"Apache connection statuses\",\n\t\t},\n\t\t\t[]string{\"state\"},\n\t\t),\n\t\tclient: &http.Client{\n\t\t\tTransport: &http.Transport{\n\t\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: *insecure},\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc (e *Exporter) Describe(ch chan<- *prometheus.Desc) {\n        ch <- e.up\n        ch <- e.accessesTotal\n        ch <- e.kBytesTotal\n        ch <- e.uptime\n        e.scrapeFailures.Describe(ch)\n        e.workers.Describe(ch)\n        e.scoreboard.Describe(ch)\n        e.connections.Describe(ch)\n}\n\n\/\/ Split colon separated string into two fields\nfunc splitkv(s string) (string, string) {\n\n\tif len(s) == 0 {\n\t\treturn s, s\n\t}\n\n\tslice := strings.SplitN(s, \":\", 2)\n\n\tif len(slice) == 1 {\n\t\treturn slice[0], \"\"\n\t}\n\n\treturn strings.TrimSpace(slice[0]), strings.TrimSpace(slice[1])\n}\n\nfunc (e *Exporter) updateScoreboard(scoreboard string) {\n\te.scoreboard.Reset()\n\tfor _, worker_status := range scoreboard {\n\t\ts := string(worker_status)\n\t\tswitch {\n\t\tcase s == \"_\":\n\t\t\te.scoreboard.WithLabelValues(\"idle\").Inc()\n\t\tcase s == \"S\":\n\t\t\te.scoreboard.WithLabelValues(\"startup\").Inc()\n\t\tcase s == \"R\":\n\t\t\te.scoreboard.WithLabelValues(\"read\").Inc()\n\t\tcase s == \"W\":\n\t\t\te.scoreboard.WithLabelValues(\"reply\").Inc()\n\t\tcase s == \"K\":\n\t\t\te.scoreboard.WithLabelValues(\"keepalive\").Inc()\n\t\tcase s == \"D\":\n\t\t\te.scoreboard.WithLabelValues(\"dns\").Inc()\n\t\tcase s == \"C\":\n\t\t\te.scoreboard.WithLabelValues(\"closing\").Inc()\n\t\tcase s == \"L\":\n\t\t\te.scoreboard.WithLabelValues(\"logging\").Inc()\n\t\tcase s == \"G\":\n\t\t\te.scoreboard.WithLabelValues(\"graceful_stop\").Inc()\n\t\tcase s == \"I\":\n\t\t\te.scoreboard.WithLabelValues(\"idle_cleanup\").Inc()\n\t\tcase s == \".\":\n\t\t\te.scoreboard.WithLabelValues(\"open_slot\").Inc()\n\t\t}\n\t}\n}\n\nfunc (e *Exporter) collect(ch chan<- prometheus.Metric) error {\n\tresp, err := e.client.Get(e.URI)\n\tif err != nil {\n                ch <- prometheus.MustNewConstMetric(e.up, prometheus.GaugeValue, 0)\n\t\treturn fmt.Errorf(\"Error scraping apache: %v\", err)\n\t}\n        ch <- prometheus.MustNewConstMetric(e.up, prometheus.GaugeValue, 1)\n\n\tdata, err := ioutil.ReadAll(resp.Body)\n\tresp.Body.Close()\n\tif resp.StatusCode != 200 {\n\t\tif err != nil {\n\t\t\tdata = []byte(err.Error())\n\t\t}\n\t\treturn fmt.Errorf(\"Status %s (%d): %s\", resp.Status, resp.StatusCode, data)\n\t}\n\n\tlines := strings.Split(string(data), \"\\n\")\n\n\tconnectionInfo := false\n\n\tfor _, l := range lines {\n\t\tkey, v := splitkv(l)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch {\n\t\tcase key == \"Total Accesses\":\n\t\t\tval, err := strconv.ParseFloat(v, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n                ch <- prometheus.MustNewConstMetric(e.accessesTotal, prometheus.CounterValue, val)\n\t\tcase key == \"Total kBytes\":\n\t\t\tval, err := strconv.ParseFloat(v, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n                ch <- prometheus.MustNewConstMetric(e.kBytesTotal, prometheus.CounterValue, val)\n\t\tcase key == \"Uptime\":\n\t\t\tval, err := strconv.ParseFloat(v, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n                ch <- prometheus.MustNewConstMetric(e.uptime, prometheus.CounterValue, val)\n\t\tcase key == \"BusyWorkers\":\n\t\t\tval, err := strconv.ParseFloat(v, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\te.workers.WithLabelValues(\"busy\").Set(val)\n\t\tcase key == \"IdleWorkers\":\n\t\t\tval, err := strconv.ParseFloat(v, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\te.workers.WithLabelValues(\"idle\").Set(val)\n\t\tcase key == \"Scoreboard\":\n\t\t\te.updateScoreboard(v)\n\t\t\te.scoreboard.Collect(ch)\n\t\tcase key == \"ConnsTotal\":\n\t\t\tval, err := strconv.ParseFloat(v, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\te.connections.WithLabelValues(\"total\").Set(val)\n\t\t\tconnectionInfo = true\n\t\tcase key == \"ConnsAsyncWriting\":\n\t\t\tval, err := strconv.ParseFloat(v, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\te.connections.WithLabelValues(\"writing\").Set(val)\n\t\t\tconnectionInfo = true\n\t\tcase key == \"ConnsAsyncKeepAlive\":\n\t\t\tval, err := strconv.ParseFloat(v, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\te.connections.WithLabelValues(\"keepalive\").Set(val)\n\t\t\tconnectionInfo = true\n\t\tcase key == \"ConnsAsyncClosing\":\n\t\t\tval, err := strconv.ParseFloat(v, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\te.connections.WithLabelValues(\"closing\").Set(val)\n\t\t\tconnectionInfo = true\n\t\t}\n\n\t}\n\n\te.workers.Collect(ch)\n\tif connectionInfo {\n\t\te.connections.Collect(ch)\n\t}\n\n\treturn nil\n}\n\nfunc (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mutex.Lock() \/\/ To protect metrics from concurrent collects.\n\tdefer e.mutex.Unlock()\n\tif err := e.collect(ch); err != nil {\n\t\tlog.Errorf(\"Error scraping apache: %s\", err)\n\t\te.scrapeFailures.Inc()\n\t\te.scrapeFailures.Collect(ch)\n\t}\n\treturn\n}\n\nfunc main() {\n\tflag.Parse()\n\n\texporter := NewExporter(*scrapeURI)\n\tprometheus.MustRegister(exporter)\n\n\tlog.Infof(\"Starting Server: %s\", *listeningAddress)\n\thttp.Handle(*metricsEndpoint, prometheus.Handler())\n\tlog.Fatal(http.ListenAndServe(*listeningAddress, nil))\n}\n<commit_msg>Add version cli flag and export as a metric<commit_after>package main\n\nimport (\n\t\"crypto\/tls\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n\t\"github.com\/prometheus\/common\/log\"\n\t\"github.com\/prometheus\/common\/version\"\n)\n\nconst (\n\tnamespace = \"apache\" \/\/ For Prometheus metrics.\n)\n\nvar (\n\tlisteningAddress = flag.String(\"telemetry.address\", \":9117\", \"Address on which to expose metrics.\")\n\tmetricsEndpoint  = flag.String(\"telemetry.endpoint\", \"\/metrics\", \"Path under which to expose metrics.\")\n\tscrapeURI        = flag.String(\"scrape_uri\", \"http:\/\/localhost\/server-status\/?auto\", \"URI to apache stub status page.\")\n\tinsecure         = flag.Bool(\"insecure\", false, \"Ignore server certificate if using https.\")\n\tshowVersion      = flag.Bool(\"version\", false, \"Print version information.\")\n)\n\ntype Exporter struct {\n\tURI    string\n\tmutex  sync.Mutex\n\tclient *http.Client\n\n\tup             *prometheus.Desc\n\tscrapeFailures prometheus.Counter\n\taccessesTotal  *prometheus.Desc\n\tkBytesTotal    *prometheus.Desc\n\tuptime         *prometheus.Desc\n\tworkers        *prometheus.GaugeVec\n\tscoreboard     *prometheus.GaugeVec\n\tconnections    *prometheus.GaugeVec\n}\n\nfunc NewExporter(uri string) *Exporter {\n\treturn &Exporter{\n\t\tURI: uri,\n\t\tup: prometheus.NewDesc(\n                        prometheus.BuildFQName(namespace, \"\", \"up\"),\n                        \"Could the apache server be reached\",\n                        nil,\n\t\t\tnil),\n                scrapeFailures: prometheus.NewCounter(prometheus.CounterOpts{\n                        Namespace: namespace,\n                        Name:      \"exporter_scrape_failures_total\",\n                        Help:      \"Number of errors while scraping apache.\",\n                }),\n                accessesTotal: prometheus.NewDesc(\n                        prometheus.BuildFQName(namespace, \"\", \"accesses_total\"),\n                        \"Current total apache accesses\",\n                        nil,\n                        nil),\n                kBytesTotal: prometheus.NewDesc(\n                        prometheus.BuildFQName(namespace, \"\", \"sent_kilobytes_total\"),\n                        \"Current total kbytes sent\",\n                        nil,\n                        nil),\n                uptime: prometheus.NewDesc(\n                        prometheus.BuildFQName(namespace, \"\", \"uptime_seconds_total\"),\n                        \"Current uptime in seconds\",\n                        nil,\n                        nil),\n\t\tworkers: prometheus.NewGaugeVec(prometheus.GaugeOpts{\n\t\t\tNamespace: namespace,\n\t\t\tName:      \"workers\",\n\t\t\tHelp:      \"Apache worker statuses\",\n\t\t},\n\t\t\t[]string{\"state\"},\n\t\t),\n\t\tscoreboard: prometheus.NewGaugeVec(prometheus.GaugeOpts{\n\t\t\tNamespace: namespace,\n\t\t\tName:      \"scoreboard\",\n\t\t\tHelp:      \"Apache scoreboard statuses\",\n\t\t},\n\t\t\t[]string{\"state\"},\n\t\t),\n\t\tconnections: prometheus.NewGaugeVec(prometheus.GaugeOpts{\n\t\t\tNamespace: namespace,\n\t\t\tName:      \"connections\",\n\t\t\tHelp:      \"Apache connection statuses\",\n\t\t},\n\t\t\t[]string{\"state\"},\n\t\t),\n\t\tclient: &http.Client{\n\t\t\tTransport: &http.Transport{\n\t\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: *insecure},\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc (e *Exporter) Describe(ch chan<- *prometheus.Desc) {\n        ch <- e.up\n        ch <- e.accessesTotal\n        ch <- e.kBytesTotal\n        ch <- e.uptime\n        e.scrapeFailures.Describe(ch)\n        e.workers.Describe(ch)\n        e.scoreboard.Describe(ch)\n        e.connections.Describe(ch)\n}\n\n\/\/ Split colon separated string into two fields\nfunc splitkv(s string) (string, string) {\n\n\tif len(s) == 0 {\n\t\treturn s, s\n\t}\n\n\tslice := strings.SplitN(s, \":\", 2)\n\n\tif len(slice) == 1 {\n\t\treturn slice[0], \"\"\n\t}\n\n\treturn strings.TrimSpace(slice[0]), strings.TrimSpace(slice[1])\n}\n\nfunc (e *Exporter) updateScoreboard(scoreboard string) {\n\te.scoreboard.Reset()\n\tfor _, worker_status := range scoreboard {\n\t\ts := string(worker_status)\n\t\tswitch {\n\t\tcase s == \"_\":\n\t\t\te.scoreboard.WithLabelValues(\"idle\").Inc()\n\t\tcase s == \"S\":\n\t\t\te.scoreboard.WithLabelValues(\"startup\").Inc()\n\t\tcase s == \"R\":\n\t\t\te.scoreboard.WithLabelValues(\"read\").Inc()\n\t\tcase s == \"W\":\n\t\t\te.scoreboard.WithLabelValues(\"reply\").Inc()\n\t\tcase s == \"K\":\n\t\t\te.scoreboard.WithLabelValues(\"keepalive\").Inc()\n\t\tcase s == \"D\":\n\t\t\te.scoreboard.WithLabelValues(\"dns\").Inc()\n\t\tcase s == \"C\":\n\t\t\te.scoreboard.WithLabelValues(\"closing\").Inc()\n\t\tcase s == \"L\":\n\t\t\te.scoreboard.WithLabelValues(\"logging\").Inc()\n\t\tcase s == \"G\":\n\t\t\te.scoreboard.WithLabelValues(\"graceful_stop\").Inc()\n\t\tcase s == \"I\":\n\t\t\te.scoreboard.WithLabelValues(\"idle_cleanup\").Inc()\n\t\tcase s == \".\":\n\t\t\te.scoreboard.WithLabelValues(\"open_slot\").Inc()\n\t\t}\n\t}\n}\n\nfunc (e *Exporter) collect(ch chan<- prometheus.Metric) error {\n\tresp, err := e.client.Get(e.URI)\n\tif err != nil {\n                ch <- prometheus.MustNewConstMetric(e.up, prometheus.GaugeValue, 0)\n\t\treturn fmt.Errorf(\"Error scraping apache: %v\", err)\n\t}\n        ch <- prometheus.MustNewConstMetric(e.up, prometheus.GaugeValue, 1)\n\n\tdata, err := ioutil.ReadAll(resp.Body)\n\tresp.Body.Close()\n\tif resp.StatusCode != 200 {\n\t\tif err != nil {\n\t\t\tdata = []byte(err.Error())\n\t\t}\n\t\treturn fmt.Errorf(\"Status %s (%d): %s\", resp.Status, resp.StatusCode, data)\n\t}\n\n\tlines := strings.Split(string(data), \"\\n\")\n\n\tconnectionInfo := false\n\n\tfor _, l := range lines {\n\t\tkey, v := splitkv(l)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch {\n\t\tcase key == \"Total Accesses\":\n\t\t\tval, err := strconv.ParseFloat(v, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n                ch <- prometheus.MustNewConstMetric(e.accessesTotal, prometheus.CounterValue, val)\n\t\tcase key == \"Total kBytes\":\n\t\t\tval, err := strconv.ParseFloat(v, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n                ch <- prometheus.MustNewConstMetric(e.kBytesTotal, prometheus.CounterValue, val)\n\t\tcase key == \"Uptime\":\n\t\t\tval, err := strconv.ParseFloat(v, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n                ch <- prometheus.MustNewConstMetric(e.uptime, prometheus.CounterValue, val)\n\t\tcase key == \"BusyWorkers\":\n\t\t\tval, err := strconv.ParseFloat(v, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\te.workers.WithLabelValues(\"busy\").Set(val)\n\t\tcase key == \"IdleWorkers\":\n\t\t\tval, err := strconv.ParseFloat(v, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\te.workers.WithLabelValues(\"idle\").Set(val)\n\t\tcase key == \"Scoreboard\":\n\t\t\te.updateScoreboard(v)\n\t\t\te.scoreboard.Collect(ch)\n\t\tcase key == \"ConnsTotal\":\n\t\t\tval, err := strconv.ParseFloat(v, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\te.connections.WithLabelValues(\"total\").Set(val)\n\t\t\tconnectionInfo = true\n\t\tcase key == \"ConnsAsyncWriting\":\n\t\t\tval, err := strconv.ParseFloat(v, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\te.connections.WithLabelValues(\"writing\").Set(val)\n\t\t\tconnectionInfo = true\n\t\tcase key == \"ConnsAsyncKeepAlive\":\n\t\t\tval, err := strconv.ParseFloat(v, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\te.connections.WithLabelValues(\"keepalive\").Set(val)\n\t\t\tconnectionInfo = true\n\t\tcase key == \"ConnsAsyncClosing\":\n\t\t\tval, err := strconv.ParseFloat(v, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\te.connections.WithLabelValues(\"closing\").Set(val)\n\t\t\tconnectionInfo = true\n\t\t}\n\n\t}\n\n\te.workers.Collect(ch)\n\tif connectionInfo {\n\t\te.connections.Collect(ch)\n\t}\n\n\treturn nil\n}\n\nfunc (e *Exporter) Collect(ch chan<- prometheus.Metric) {\n\te.mutex.Lock() \/\/ To protect metrics from concurrent collects.\n\tdefer e.mutex.Unlock()\n\tif err := e.collect(ch); err != nil {\n\t\tlog.Errorf(\"Error scraping apache: %s\", err)\n\t\te.scrapeFailures.Inc()\n\t\te.scrapeFailures.Collect(ch)\n\t}\n\treturn\n}\n\nfunc main() {\n\tflag.Parse()\n\n\tif *showVersion {\n\t\tfmt.Fprintln(os.Stdout, version.Print(\"apache_exporter\"))\n\t\tos.Exit(0)\n\t}\n\texporter := NewExporter(*scrapeURI)\n\tprometheus.MustRegister(exporter)\n\tprometheus.MustRegister(version.NewCollector(\"apache_exporter\"))\n\n\tlog.Infoln(\"Starting apache_exporter\", version.Info())\n\tlog.Infoln(\"Build context\", version.BuildContext())\n\n\tlog.Infof(\"Starting Server: %s\", *listeningAddress)\n\thttp.Handle(*metricsEndpoint, prometheus.Handler())\n\tlog.Fatal(http.ListenAndServe(*listeningAddress, nil))\n}\n<|endoftext|>"}
{"text":"<commit_before>package actor\n\ntype deadLetterProcess struct{}\n\nvar (\n\tdeadLetter Process = &deadLetterProcess{}\n)\n\ntype DeadLetter struct {\n\tPID     *PID\n\tMessage interface{}\n\tSender  *PID\n}\n\nfunc (*deadLetterProcess) SendUserMessage(pid *PID, message interface{}, sender *PID) {\n\tEventStream.Publish(&DeadLetter{\n\t\tPID:     pid,\n\t\tMessage: message,\n\t\tSender:  sender,\n\t})\n}\n\nfunc (*deadLetterProcess) SendSystemMessage(pid *PID, message SystemMessage) {\n\tEventStream.Publish(&DeadLetter{\n\t\tPID:     pid,\n\t\tMessage: message,\n\t})\n}\n\nfunc (ref *deadLetterProcess) Stop(pid *PID) {\n\tref.SendSystemMessage(pid, stopMessage)\n}\n\nfunc (ref *deadLetterProcess) Watch(pid *PID) {\n\tref.SendSystemMessage(pid, &Watch{Watcher: pid})\n}\n\nfunc (ref *deadLetterProcess) Unwatch(pid *PID) {\n\tref.SendSystemMessage(pid, &Unwatch{Watcher: pid})\n}\n<commit_msg>remove watch \/ unwatch<commit_after>package actor\n\ntype deadLetterProcess struct{}\n\nvar (\n\tdeadLetter Process = &deadLetterProcess{}\n)\n\ntype DeadLetter struct {\n\tPID     *PID\n\tMessage interface{}\n\tSender  *PID\n}\n\nfunc (*deadLetterProcess) SendUserMessage(pid *PID, message interface{}, sender *PID) {\n\tEventStream.Publish(&DeadLetter{\n\t\tPID:     pid,\n\t\tMessage: message,\n\t\tSender:  sender,\n\t})\n}\n\nfunc (*deadLetterProcess) SendSystemMessage(pid *PID, message SystemMessage) {\n\tEventStream.Publish(&DeadLetter{\n\t\tPID:     pid,\n\t\tMessage: message,\n\t})\n}\n\nfunc (ref *deadLetterProcess) Stop(pid *PID) {\n\tref.SendSystemMessage(pid, stopMessage)\n}\n<|endoftext|>"}
{"text":"<commit_before>c6c0ef5a-2e55-11e5-9284-b827eb9e62be<commit_msg>c6c60666-2e55-11e5-9284-b827eb9e62be<commit_after>c6c60666-2e55-11e5-9284-b827eb9e62be<|endoftext|>"}
{"text":"<commit_before>package console\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\n\t\"strings\"\n\n\tassetfs \"github.com\/elazarl\/go-bindata-assetfs\"\n\t\"github.com\/jmartin82\/mmock\/definition\"\n\t\"github.com\/jmartin82\/mmock\/match\"\n\t\"github.com\/jmartin82\/mmock\/scenario\"\n\t\"github.com\/jmartin82\/mmock\/statistics\"\n\t\"github.com\/labstack\/echo\"\n\t\"golang.org\/x\/net\/websocket\"\n)\n\ntype ActionResponse struct {\n\tResult string `json:\"result\"`\n}\n\n\/\/Dispatcher is the http console server.\ntype Dispatcher struct {\n\tIP       string\n\tPort     int\n\tMatchSpy match.Spier\n\tScenario scenario.Director\n\tMapping  definition.Mapping\n\tMlog     chan definition.Match\n\tclients  []*websocket.Conn\n}\n\nfunc (di *Dispatcher) removeClient(i int) {\n\tcopy(di.clients[i:], di.clients[i+1:])\n\tdi.clients[len(di.clients)-1] = nil\n\tdi.clients = di.clients[:len(di.clients)-1]\n}\n\nfunc (di *Dispatcher) addClient(ws *websocket.Conn) {\n\tdi.clients = append(di.clients, ws)\n}\n\nfunc (di *Dispatcher) logFanOut() {\n\tfor match := range di.Mlog {\n\t\tfor i, c := range di.clients {\n\t\t\tif c != nil {\n\t\t\t\tif err := websocket.JSON.Send(c, match); err != nil {\n\t\t\t\t\tdi.removeClient(i)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/Start initiates the http console.\nfunc (di *Dispatcher) Start() {\n\te := echo.New()\n\t\/\/WS\n\tdi.clients = []*websocket.Conn{}\n\te.GET(\"\/echo\", di.webSocketHandler)\n\n\t\/\/HTTP\n\tstatics := http.FileServer(&assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, AssetInfo: AssetInfo, Prefix: \"tmpl\"})\n\te.GET(\"\/js\/*\", echo.WrapHandler(statics))\n\te.GET(\"\/css\/*\", echo.WrapHandler(statics))\n\te.GET(\"\/swagger.json\", di.swaggerHandler)\n\te.GET(\"\/\", di.consoleHandler)\n\n\t\/\/verification\n\te.GET(\"\/api\/request\/reset\", di.requestResetHandler)\n\te.POST(\"\/api\/request\/verify\", di.requestVerifyHandler)\n\te.GET(\"\/api\/request\/all\", di.requestAllHandler)\n\te.GET(\"\/api\/request\/matched\", di.requestMatchedHandler)\n\te.GET(\"\/api\/request\/unmatched\", di.requestUnMatchedHandler)\n\te.GET(\"\/api\/scenarios\/reset_all\", di.scenariosResetHandler)\n\te.PUT(\"\/api\/scenarios\/set\/:scenario\/:state\", di.scenariosSetHandler)\n\te.PUT(\"\/api\/scenarios\/pause\", di.scenariosPauseHandler)\n\te.PUT(\"\/api\/scenarios\/unpause\", di.scenariosUnpauseHandler)\n\n\t\/\/mapping\n\te.GET(\"\/api\/mapping\", di.mappingListHandler)\n\te.GET(\"\/api\/mapping\/*\", di.mappingGetHandler)\n\te.POST(\"\/api\/mapping\/*\", di.mappingCreateHandler)\n\te.PUT(\"\/api\/mapping\/*\", di.mappingUpdateHandler)\n\te.DELETE(\"\/api\/mapping\/*\", di.mappingDeleteHandler)\n\n\t\/\/POST api\/mapping (all)\n\n\tgo di.logFanOut()\n\n\taddr := fmt.Sprintf(\"%s:%d\", di.IP, di.Port)\n\te.Logger.Fatal(e.Start(addr))\n}\n\n\/\/CONSOLE\nfunc (di *Dispatcher) consoleHandler(c echo.Context) error {\n\tstatistics.TrackConsoleRequest()\n\ttmpl, _ := Asset(\"tmpl\/index.html\")\n\tcontent := string(tmpl)\n\treturn c.HTML(http.StatusOK, content)\n}\n\nfunc (di *Dispatcher) swaggerHandler(c echo.Context) error {\n\ttmpl, _ := Asset(\"tmpl\/swagger.json\")\n\treturn c.JSONBlob(http.StatusOK, tmpl)\n}\n\nfunc (di *Dispatcher) webSocketHandler(c echo.Context) error {\n\twebsocket.Handler(func(ws *websocket.Conn) {\n\t\tdi.addClient(ws)\n\t\tdefer ws.Close()\n\t\t\/\/block\n\t\tvar message string\n\t\twebsocket.Message.Receive(ws, &message)\n\n\t}).ServeHTTP(c.Response(), c.Request())\n\treturn nil\n}\n\nfunc (di *Dispatcher) getMappingUri(path string) string {\n\troot := \"\/api\/mapping\/\"\n\treturn strings.TrimPrefix(path, root)\n}\n\n\/\/API REQUEST\nfunc (di *Dispatcher) mappingListHandler(c echo.Context) (err error) {\n\tmocks := di.Mapping.List()\n\treturn c.JSON(http.StatusOK, mocks)\n}\n\nfunc (di *Dispatcher) mappingGetHandler(c echo.Context) (err error) {\n\n\tURI := di.getMappingUri(c.Request().URL.Path)\n\tmock := definition.Mock{}\n\tok := false\n\tif mock, ok = di.Mapping.Get(URI); !ok {\n\t\tar := &ActionResponse{\n\t\t\tResult: \"not_found\",\n\t\t}\n\t\treturn c.JSON(http.StatusNotFound, ar)\n\t}\n\n\treturn c.JSON(http.StatusOK, mock)\n\n}\n\nfunc (di *Dispatcher) mappingDeleteHandler(c echo.Context) (err error) {\n\n\tURI := di.getMappingUri(c.Request().URL.Path)\n\tok := false\n\tif _, ok = di.Mapping.Get(URI); !ok {\n\t\tar := &ActionResponse{\n\t\t\tResult: \"not_found\",\n\t\t}\n\t\treturn c.JSON(http.StatusNotFound, ar)\n\t}\n\n\tif err = di.Mapping.Delete(URI); err != nil {\n\t\treturn err\n\t}\n\tar := &ActionResponse{\n\t\tResult: \"deleted\",\n\t}\n\treturn c.JSON(http.StatusOK, ar)\n\n}\n\nfunc (di *Dispatcher) mappingCreateHandler(c echo.Context) (err error) {\n\n\tmock := &definition.Mock{}\n\tURI := di.getMappingUri(c.Request().URL.Path)\n\n\tif _, ok := di.Mapping.Get(URI); ok {\n\t\tar := &ActionResponse{\n\t\t\tResult: \"already_exists\",\n\t\t}\n\t\treturn c.JSON(http.StatusConflict, ar)\n\t}\n\n\tif err = c.Bind(mock); err != nil {\n\t\tar := &ActionResponse{\n\t\t\tResult: \"invalid_mock_definition\",\n\t\t}\n\t\treturn c.JSON(http.StatusBadRequest, ar)\n\t}\n\n\terr = di.Mapping.Set(URI, *mock)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tar := &ActionResponse{\n\t\tResult: \"created\",\n\t}\n\treturn c.JSON(http.StatusCreated, ar)\n\n}\n\nfunc (di *Dispatcher) mappingUpdateHandler(c echo.Context) (err error) {\n\n\tmock := &definition.Mock{}\n\tURI := di.getMappingUri(c.Request().URL.Path)\n\n\tif _, ok := di.Mapping.Get(URI); !ok {\n\t\tar := &ActionResponse{\n\t\t\tResult: \"not_found\",\n\t\t}\n\t\treturn c.JSON(http.StatusNotFound, ar)\n\t}\n\n\tif err = c.Bind(mock); err != nil {\n\t\tar := &ActionResponse{\n\t\t\tResult: \"invalid_mock_definition\",\n\t\t}\n\t\treturn c.JSON(http.StatusBadRequest, ar)\n\t}\n\n\terr = di.Mapping.Set(URI, *mock)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tar := &ActionResponse{\n\t\tResult: \"updated\",\n\t}\n\treturn c.JSON(http.StatusOK, ar)\n\n}\n\nfunc (di *Dispatcher) requestVerifyHandler(c echo.Context) error {\n\tstatistics.TrackVerifyRequest()\n\tdReq := definition.Request{}\n\tif err := c.Bind(&dReq); err != nil {\n\t\treturn err\n\t}\n\tresult := di.MatchSpy.Find(dReq)\n\treturn c.JSON(http.StatusOK, result)\n}\n\nfunc (di *Dispatcher) requestResetHandler(c echo.Context) error {\n\tdi.MatchSpy.Reset()\n\tar := &ActionResponse{\n\t\tResult: \"reset\",\n\t}\n\treturn c.JSON(http.StatusOK, ar)\n}\n\nfunc (di *Dispatcher) scenariosResetHandler(c echo.Context) error {\n\tdi.Scenario.ResetAll()\n\tar := &ActionResponse{\n\t\tResult: \"reset\",\n\t}\n\treturn c.JSON(http.StatusOK, ar)\n}\n\nfunc (di *Dispatcher) scenariosSetHandler(c echo.Context) error {\n\tdi.Scenario.SetState(c.Param(\"scenario\"), c.Param(\"state\"))\n\tar := &ActionResponse{\n\t\tResult: \"updated\",\n\t}\n\treturn c.JSON(http.StatusOK, ar)\n}\n\nfunc (di *Dispatcher) scenariosPauseHandler(c echo.Context) error {\n\tdi.Scenario.SetPaused(true)\n\tar := &ActionResponse{\n\t\tResult: \"updated\",\n\t}\n\treturn c.JSON(http.StatusOK, ar)\n}\n\nfunc (di *Dispatcher) scenariosUnpauseHandler(c echo.Context) error {\n\tdi.Scenario.SetPaused(false)\n\tar := &ActionResponse{\n\t\tResult: \"updated\",\n\t}\n\treturn c.JSON(http.StatusOK, ar)\n}\n\nfunc (di *Dispatcher) requestAllHandler(c echo.Context) error {\n\n\treturn c.JSON(http.StatusOK, di.MatchSpy.GetAll())\n}\n\nfunc (di *Dispatcher) requestMatchedHandler(c echo.Context) error {\n\n\treturn c.JSON(http.StatusOK, di.MatchSpy.GetMatched())\n}\n\nfunc (di *Dispatcher) requestUnMatchedHandler(c echo.Context) error {\n\n\treturn c.JSON(http.StatusOK, di.MatchSpy.GetUnMatched())\n}\n<commit_msg>Hide echo banner<commit_after>package console\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\n\t\"strings\"\n\n\tassetfs \"github.com\/elazarl\/go-bindata-assetfs\"\n\t\"github.com\/jmartin82\/mmock\/definition\"\n\t\"github.com\/jmartin82\/mmock\/match\"\n\t\"github.com\/jmartin82\/mmock\/scenario\"\n\t\"github.com\/jmartin82\/mmock\/statistics\"\n\t\"github.com\/labstack\/echo\"\n\t\"golang.org\/x\/net\/websocket\"\n)\n\ntype ActionResponse struct {\n\tResult string `json:\"result\"`\n}\n\n\/\/Dispatcher is the http console server.\ntype Dispatcher struct {\n\tIP       string\n\tPort     int\n\tMatchSpy match.Spier\n\tScenario scenario.Director\n\tMapping  definition.Mapping\n\tMlog     chan definition.Match\n\tclients  []*websocket.Conn\n}\n\nfunc (di *Dispatcher) removeClient(i int) {\n\tcopy(di.clients[i:], di.clients[i+1:])\n\tdi.clients[len(di.clients)-1] = nil\n\tdi.clients = di.clients[:len(di.clients)-1]\n}\n\nfunc (di *Dispatcher) addClient(ws *websocket.Conn) {\n\tdi.clients = append(di.clients, ws)\n}\n\nfunc (di *Dispatcher) logFanOut() {\n\tfor match := range di.Mlog {\n\t\tfor i, c := range di.clients {\n\t\t\tif c != nil {\n\t\t\t\tif err := websocket.JSON.Send(c, match); err != nil {\n\t\t\t\t\tdi.removeClient(i)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/Start initiates the http console.\nfunc (di *Dispatcher) Start() {\n\te := echo.New()\n\te.HideBanner = true\n\t\n\t\/\/WS\n\tdi.clients = []*websocket.Conn{}\n\te.GET(\"\/echo\", di.webSocketHandler)\n\n\t\/\/HTTP\n\tstatics := http.FileServer(&assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, AssetInfo: AssetInfo, Prefix: \"tmpl\"})\n\te.GET(\"\/js\/*\", echo.WrapHandler(statics))\n\te.GET(\"\/css\/*\", echo.WrapHandler(statics))\n\te.GET(\"\/swagger.json\", di.swaggerHandler)\n\te.GET(\"\/\", di.consoleHandler)\n\n\t\/\/verification\n\te.GET(\"\/api\/request\/reset\", di.requestResetHandler)\n\te.POST(\"\/api\/request\/verify\", di.requestVerifyHandler)\n\te.GET(\"\/api\/request\/all\", di.requestAllHandler)\n\te.GET(\"\/api\/request\/matched\", di.requestMatchedHandler)\n\te.GET(\"\/api\/request\/unmatched\", di.requestUnMatchedHandler)\n\te.GET(\"\/api\/scenarios\/reset_all\", di.scenariosResetHandler)\n\te.PUT(\"\/api\/scenarios\/set\/:scenario\/:state\", di.scenariosSetHandler)\n\te.PUT(\"\/api\/scenarios\/pause\", di.scenariosPauseHandler)\n\te.PUT(\"\/api\/scenarios\/unpause\", di.scenariosUnpauseHandler)\n\n\t\/\/mapping\n\te.GET(\"\/api\/mapping\", di.mappingListHandler)\n\te.GET(\"\/api\/mapping\/*\", di.mappingGetHandler)\n\te.POST(\"\/api\/mapping\/*\", di.mappingCreateHandler)\n\te.PUT(\"\/api\/mapping\/*\", di.mappingUpdateHandler)\n\te.DELETE(\"\/api\/mapping\/*\", di.mappingDeleteHandler)\n\n\t\/\/POST api\/mapping (all)\n\n\tgo di.logFanOut()\n\n\taddr := fmt.Sprintf(\"%s:%d\", di.IP, di.Port)\n\te.Logger.Fatal(e.Start(addr))\n}\n\n\/\/CONSOLE\nfunc (di *Dispatcher) consoleHandler(c echo.Context) error {\n\tstatistics.TrackConsoleRequest()\n\ttmpl, _ := Asset(\"tmpl\/index.html\")\n\tcontent := string(tmpl)\n\treturn c.HTML(http.StatusOK, content)\n}\n\nfunc (di *Dispatcher) swaggerHandler(c echo.Context) error {\n\ttmpl, _ := Asset(\"tmpl\/swagger.json\")\n\treturn c.JSONBlob(http.StatusOK, tmpl)\n}\n\nfunc (di *Dispatcher) webSocketHandler(c echo.Context) error {\n\twebsocket.Handler(func(ws *websocket.Conn) {\n\t\tdi.addClient(ws)\n\t\tdefer ws.Close()\n\t\t\/\/block\n\t\tvar message string\n\t\twebsocket.Message.Receive(ws, &message)\n\n\t}).ServeHTTP(c.Response(), c.Request())\n\treturn nil\n}\n\nfunc (di *Dispatcher) getMappingUri(path string) string {\n\troot := \"\/api\/mapping\/\"\n\treturn strings.TrimPrefix(path, root)\n}\n\n\/\/API REQUEST\nfunc (di *Dispatcher) mappingListHandler(c echo.Context) (err error) {\n\tmocks := di.Mapping.List()\n\treturn c.JSON(http.StatusOK, mocks)\n}\n\nfunc (di *Dispatcher) mappingGetHandler(c echo.Context) (err error) {\n\n\tURI := di.getMappingUri(c.Request().URL.Path)\n\tmock := definition.Mock{}\n\tok := false\n\tif mock, ok = di.Mapping.Get(URI); !ok {\n\t\tar := &ActionResponse{\n\t\t\tResult: \"not_found\",\n\t\t}\n\t\treturn c.JSON(http.StatusNotFound, ar)\n\t}\n\n\treturn c.JSON(http.StatusOK, mock)\n\n}\n\nfunc (di *Dispatcher) mappingDeleteHandler(c echo.Context) (err error) {\n\n\tURI := di.getMappingUri(c.Request().URL.Path)\n\tok := false\n\tif _, ok = di.Mapping.Get(URI); !ok {\n\t\tar := &ActionResponse{\n\t\t\tResult: \"not_found\",\n\t\t}\n\t\treturn c.JSON(http.StatusNotFound, ar)\n\t}\n\n\tif err = di.Mapping.Delete(URI); err != nil {\n\t\treturn err\n\t}\n\tar := &ActionResponse{\n\t\tResult: \"deleted\",\n\t}\n\treturn c.JSON(http.StatusOK, ar)\n\n}\n\nfunc (di *Dispatcher) mappingCreateHandler(c echo.Context) (err error) {\n\n\tmock := &definition.Mock{}\n\tURI := di.getMappingUri(c.Request().URL.Path)\n\n\tif _, ok := di.Mapping.Get(URI); ok {\n\t\tar := &ActionResponse{\n\t\t\tResult: \"already_exists\",\n\t\t}\n\t\treturn c.JSON(http.StatusConflict, ar)\n\t}\n\n\tif err = c.Bind(mock); err != nil {\n\t\tar := &ActionResponse{\n\t\t\tResult: \"invalid_mock_definition\",\n\t\t}\n\t\treturn c.JSON(http.StatusBadRequest, ar)\n\t}\n\n\terr = di.Mapping.Set(URI, *mock)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tar := &ActionResponse{\n\t\tResult: \"created\",\n\t}\n\treturn c.JSON(http.StatusCreated, ar)\n\n}\n\nfunc (di *Dispatcher) mappingUpdateHandler(c echo.Context) (err error) {\n\n\tmock := &definition.Mock{}\n\tURI := di.getMappingUri(c.Request().URL.Path)\n\n\tif _, ok := di.Mapping.Get(URI); !ok {\n\t\tar := &ActionResponse{\n\t\t\tResult: \"not_found\",\n\t\t}\n\t\treturn c.JSON(http.StatusNotFound, ar)\n\t}\n\n\tif err = c.Bind(mock); err != nil {\n\t\tar := &ActionResponse{\n\t\t\tResult: \"invalid_mock_definition\",\n\t\t}\n\t\treturn c.JSON(http.StatusBadRequest, ar)\n\t}\n\n\terr = di.Mapping.Set(URI, *mock)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tar := &ActionResponse{\n\t\tResult: \"updated\",\n\t}\n\treturn c.JSON(http.StatusOK, ar)\n\n}\n\nfunc (di *Dispatcher) requestVerifyHandler(c echo.Context) error {\n\tstatistics.TrackVerifyRequest()\n\tdReq := definition.Request{}\n\tif err := c.Bind(&dReq); err != nil {\n\t\treturn err\n\t}\n\tresult := di.MatchSpy.Find(dReq)\n\treturn c.JSON(http.StatusOK, result)\n}\n\nfunc (di *Dispatcher) requestResetHandler(c echo.Context) error {\n\tdi.MatchSpy.Reset()\n\tar := &ActionResponse{\n\t\tResult: \"reset\",\n\t}\n\treturn c.JSON(http.StatusOK, ar)\n}\n\nfunc (di *Dispatcher) scenariosResetHandler(c echo.Context) error {\n\tdi.Scenario.ResetAll()\n\tar := &ActionResponse{\n\t\tResult: \"reset\",\n\t}\n\treturn c.JSON(http.StatusOK, ar)\n}\n\nfunc (di *Dispatcher) scenariosSetHandler(c echo.Context) error {\n\tdi.Scenario.SetState(c.Param(\"scenario\"), c.Param(\"state\"))\n\tar := &ActionResponse{\n\t\tResult: \"updated\",\n\t}\n\treturn c.JSON(http.StatusOK, ar)\n}\n\nfunc (di *Dispatcher) scenariosPauseHandler(c echo.Context) error {\n\tdi.Scenario.SetPaused(true)\n\tar := &ActionResponse{\n\t\tResult: \"updated\",\n\t}\n\treturn c.JSON(http.StatusOK, ar)\n}\n\nfunc (di *Dispatcher) scenariosUnpauseHandler(c echo.Context) error {\n\tdi.Scenario.SetPaused(false)\n\tar := &ActionResponse{\n\t\tResult: \"updated\",\n\t}\n\treturn c.JSON(http.StatusOK, ar)\n}\n\nfunc (di *Dispatcher) requestAllHandler(c echo.Context) error {\n\n\treturn c.JSON(http.StatusOK, di.MatchSpy.GetAll())\n}\n\nfunc (di *Dispatcher) requestMatchedHandler(c echo.Context) error {\n\n\treturn c.JSON(http.StatusOK, di.MatchSpy.GetMatched())\n}\n\nfunc (di *Dispatcher) requestUnMatchedHandler(c echo.Context) error {\n\n\treturn c.JSON(http.StatusOK, di.MatchSpy.GetUnMatched())\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build mqdev\n\n\/*\n© Copyright IBM Corporation 2018\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\npackage main\n\nimport (\n\t\"os\"\n\t\"path\/filepath\"\n)\n\n\/\/ postInit is run after \/var\/mqm is set up\n\/\/ This version of postInit is only included as part of the MQ Advanced for Developers build\nfunc postInit(name string) error {\n\tdisable := os.Getenv(\"MQ_DISABLE_WEB_CONSOLE\")\n\tif disable != \"true\" && disable != \"1\" {\n\t\t\/\/ Configure and start the web server, in the background (if installed)\n\t\t\/\/ WARNING: No error handling or health checking available for the web server,\n\t\t\/\/ which is why it's limited to use with MQ Advanced for Developers only\n\t\tgo func() {\n\t\t\tconfigureWebServer()\n\t\t\tstartWebServer()\n\t\t}()\n\t}\n\n\tdir := \"\/etc\/mqm\/tls\"\n\tkeyFile := filepath.Join(dir, \"key.kdb\")\n\tstashFile := filepath.Join(dir, \"key.sth\")\n\n\t_, err := os.Stat(keyFile)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\n\t_, err = os.Stat(stashFile)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\n\treturn nil\n}\n<commit_msg>Remove unused code<commit_after>\/\/ +build mqdev\n\n\/*\n© Copyright IBM Corporation 2018\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\npackage main\n\nimport (\n\t\"os\"\n)\n\n\/\/ postInit is run after \/var\/mqm is set up\n\/\/ This version of postInit is only included as part of the MQ Advanced for Developers build\nfunc postInit(name string) error {\n\tdisable := os.Getenv(\"MQ_DISABLE_WEB_CONSOLE\")\n\tif disable != \"true\" && disable != \"1\" {\n\t\t\/\/ Configure and start the web server, in the background (if installed)\n\t\t\/\/ WARNING: No error handling or health checking available for the web server,\n\t\t\/\/ which is why it's limited to use with MQ Advanced for Developers only\n\t\tgo func() {\n\t\t\tconfigureWebServer()\n\t\t\tstartWebServer()\n\t\t}()\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package controller\n\nimport (\n\t\"bytes\"\n\t\"encoding\/base64\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"time\"\n\n\tct \"github.com\/flynn\/flynn-controller\/types\"\n\t\"github.com\/flynn\/flynn-controller\/utils\"\n\t\"github.com\/flynn\/go-discoverd\"\n\t\"github.com\/flynn\/go-discoverd\/dialer\"\n\t\"github.com\/flynn\/go-flynn\/pinned\"\n\t\"github.com\/flynn\/rpcplus\"\n\t\"github.com\/flynn\/strowger\/types\"\n)\n\nfunc NewClient(uri, key string) (*Client, error) {\n\tif uri == \"\" {\n\t\turi = \"discoverd+http:\/\/flynn-controller\"\n\t}\n\tu, err := url.Parse(uri)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc := &Client{\n\t\turl:  uri,\n\t\taddr: u.Host,\n\t\thttp: http.DefaultClient,\n\t\tkey:  key,\n\t}\n\tif u.Scheme == \"discoverd+http\" {\n\t\tif err := discoverd.Connect(\"\"); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdialer := dialer.New(discoverd.DefaultClient, nil)\n\t\tc.dial = dialer.Dial\n\t\tc.dialClose = dialer\n\t\tc.http = &http.Client{Transport: &http.Transport{Dial: c.dial}}\n\t\tu.Scheme = \"http\"\n\t\tc.url = u.String()\n\t}\n\treturn c, nil\n}\n\nfunc NewClientWithPin(uri, key string, pin []byte) (*Client, error) {\n\tu, err := url.Parse(uri)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc := &Client{\n\t\tdial: (&pinned.Config{Pin: pin}).Dial,\n\t\tkey:  key,\n\t}\n\tif _, port, _ := net.SplitHostPort(u.Host); port == \"\" {\n\t\tu.Host += \":443\"\n\t}\n\tc.addr = u.Host\n\tu.Scheme = \"http\"\n\tc.url = u.String()\n\tc.http = &http.Client{Transport: &http.Transport{Dial: c.dial}}\n\treturn c, nil\n}\n\ntype Client struct {\n\turl  string\n\tkey  string\n\taddr string\n\thttp *http.Client\n\n\tdial      rpcplus.DialFunc\n\tdialClose io.Closer\n}\n\nfunc (c *Client) Close() error {\n\tif c.dialClose != nil {\n\t\tc.dialClose.Close()\n\t}\n\treturn nil\n}\n\nvar ErrNotFound = errors.New(\"controller: not found\")\n\nfunc toJSON(v interface{}) (io.Reader, error) {\n\tdata, err := json.Marshal(v)\n\treturn bytes.NewBuffer(data), err\n}\n\nfunc (c *Client) rawReq(method, path string, contentType string, in, out interface{}) (*http.Response, error) {\n\tvar payload io.Reader\n\tswitch v := in.(type) {\n\tcase io.Reader:\n\t\tpayload = v\n\tcase nil:\n\tdefault:\n\t\tvar err error\n\t\tpayload, err = toJSON(in)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treq, err := http.NewRequest(method, c.url+path, payload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif contentType == \"\" {\n\t\tcontentType = \"application\/json\"\n\t}\n\treq.Header.Set(\"Content-Type\", contentType)\n\treq.SetBasicAuth(\"\", c.key)\n\tres, err := c.http.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif res.StatusCode == 404 {\n\t\tres.Body.Close()\n\t\treturn res, ErrNotFound\n\t}\n\tif res.StatusCode != 200 {\n\t\tres.Body.Close()\n\t\treturn res, &url.Error{\n\t\t\tOp:  req.Method,\n\t\t\tURL: req.URL.String(),\n\t\t\tErr: fmt.Errorf(\"controller: unexpected status %d\", res.StatusCode),\n\t\t}\n\t}\n\tif out != nil {\n\t\tdefer res.Body.Close()\n\t\treturn res, json.NewDecoder(res.Body).Decode(out)\n\t}\n\treturn res, nil\n}\n\nfunc (c *Client) send(method, path string, in, out interface{}) error {\n\t_, err := c.rawReq(method, path, \"\", in, out)\n\treturn err\n}\n\nfunc (c *Client) put(path string, in, out interface{}) error {\n\treturn c.send(\"PUT\", path, in, out)\n}\n\nfunc (c *Client) post(path string, in, out interface{}) error {\n\treturn c.send(\"POST\", path, in, out)\n}\n\nfunc (c *Client) get(path string, out interface{}) error {\n\t_, err := c.rawReq(\"GET\", path, \"\", nil, out)\n\treturn err\n}\n\nfunc (c *Client) StreamFormations(since *time.Time) (<-chan *ct.ExpandedFormation, *error) {\n\tif since == nil {\n\t\ts := time.Unix(0, 0)\n\t\tsince = &s\n\t}\n\tdial := c.dial\n\tif dial == nil {\n\t\tdial = net.Dial\n\t}\n\tch := make(chan *ct.ExpandedFormation)\n\tconn, err := dial(\"tcp\", c.addr)\n\tif err != nil {\n\t\tclose(ch)\n\t\treturn ch, &err\n\t}\n\theader := make(http.Header)\n\theader.Set(\"Authorization\", \"Basic \"+base64.StdEncoding.EncodeToString([]byte(\":\"+c.key)))\n\tclient, err := rpcplus.NewHTTPClient(conn, rpcplus.DefaultRPCPath, header)\n\tif err != nil {\n\t\tclose(ch)\n\t\treturn ch, &err\n\t}\n\treturn ch, &client.StreamGo(\"Controller.StreamFormations\", since, ch).Error\n}\n\nfunc (c *Client) CreateArtifact(artifact *ct.Artifact) error {\n\treturn c.post(\"\/artifacts\", artifact, artifact)\n}\n\nfunc (c *Client) CreateRelease(release *ct.Release) error {\n\treturn c.post(\"\/releases\", release, release)\n}\n\nfunc (c *Client) CreateApp(app *ct.App) error {\n\treturn c.post(\"\/apps\", app, app)\n}\n\nfunc (c *Client) CreateProvider(provider *ct.Provider) error {\n\treturn c.post(\"\/providers\", provider, provider)\n}\n\nfunc (c *Client) ProvisionResource(req *ct.ResourceReq) (*ct.Resource, error) {\n\tif req.ProviderID == \"\" {\n\t\treturn nil, errors.New(\"controller: missing provider id\")\n\t}\n\tres := &ct.Resource{}\n\terr := c.post(fmt.Sprintf(\"\/providers\/%s\/resources\", req.ProviderID), req, res)\n\treturn res, err\n}\n\nfunc (c *Client) PutResource(resource *ct.Resource) error {\n\tif resource.ID == \"\" || resource.ProviderID == \"\" {\n\t\treturn errors.New(\"controller: missing id and\/or provider id\")\n\t}\n\treturn c.put(fmt.Sprintf(\"\/providers\/%s\/resources\/%s\", resource.ProviderID, resource.ID), resource, resource)\n}\n\nfunc (c *Client) PutFormation(formation *ct.Formation) error {\n\tif formation.AppID == \"\" || formation.ReleaseID == \"\" {\n\t\treturn errors.New(\"controller: missing app id and\/or release id\")\n\t}\n\treturn c.put(fmt.Sprintf(\"\/apps\/%s\/formations\/%s\", formation.AppID, formation.ReleaseID), formation, formation)\n}\n\nfunc (c *Client) SetAppRelease(appID, releaseID string) error {\n\treturn c.put(fmt.Sprintf(\"\/apps\/%s\/release\", appID), &ct.Release{ID: releaseID}, nil)\n}\n\nfunc (c *Client) GetAppRelease(appID string) (*ct.Release, error) {\n\trelease := &ct.Release{}\n\treturn release, c.get(fmt.Sprintf(\"\/apps\/%s\/release\", appID), release)\n}\n\nfunc (c *Client) CreateRoute(appID string, route *strowger.Route) error {\n\treturn c.post(fmt.Sprintf(\"\/apps\/%s\/routes\", appID), route, route)\n}\n\nfunc (c *Client) GetFormation(appID, releaseID string) (*ct.Formation, error) {\n\tformation := &ct.Formation{}\n\treturn formation, c.get(fmt.Sprintf(\"\/apps\/%s\/formations\/%s\", appID, releaseID), formation)\n}\n\nfunc (c *Client) GetRelease(releaseID string) (*ct.Release, error) {\n\trelease := &ct.Release{}\n\treturn release, c.get(fmt.Sprintf(\"\/releases\/%s\", releaseID), release)\n}\n\nfunc (c *Client) GetArtifact(artifactID string) (*ct.Artifact, error) {\n\tartifact := &ct.Artifact{}\n\treturn artifact, c.get(fmt.Sprintf(\"\/artifacts\/%s\", artifactID), artifact)\n}\n\nfunc (c *Client) GetApp(appID string) (*ct.App, error) {\n\tapp := &ct.App{}\n\treturn app, c.get(fmt.Sprintf(\"\/apps\/%s\", appID), app)\n}\n\nfunc (c *Client) GetJobLog(appID, jobID string) (io.ReadCloser, error) {\n\tres, err := c.rawReq(\"GET\", fmt.Sprintf(\"\/apps\/%s\/jobs\/%s\/log\", appID, jobID), \"\", nil, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn res.Body, nil\n}\n\nfunc (c *Client) RunJobAttached(appID string, job *ct.NewJob) (utils.ReadWriteCloser, error) {\n\tdata, err := toJSON(job)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq, err := http.NewRequest(\"POST\", fmt.Sprintf(\"%s\/apps\/%s\/jobs\", c.url, appID), data)\n\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\treq.Header.Set(\"Accept\", \"application\/vnd.flynn.attach\")\n\treq.SetBasicAuth(\"\", c.key)\n\tvar dial rpcplus.DialFunc\n\tif c.dial != nil {\n\t\tdial = c.dial\n\t}\n\tres, rwc, err := utils.HijackRequest(req, dial)\n\tif err != nil {\n\t\tres.Body.Close()\n\t\treturn nil, err\n\t}\n\treturn rwc, nil\n}\n\nfunc (c *Client) RunJobDetached(appID string, req *ct.NewJob) (*ct.Job, error) {\n\tjob := &ct.Job{}\n\treturn job, c.post(fmt.Sprintf(\"\/apps\/%s\/jobs\", appID), req, job)\n}\n\nfunc (c *Client) JobList(appID string) ([]*ct.Job, error) {\n\tvar jobs []*ct.Job\n\treturn jobs, c.get(fmt.Sprintf(\"\/apps\/%s\/jobs\", appID), &jobs)\n}\n\nfunc (c *Client) KeyList() ([]*ct.Key, error) {\n\tvar keys []*ct.Key\n\treturn keys, c.get(\"\/keys\", &keys)\n}\n<commit_msg>client: Implement CreateKey and DeleteKey<commit_after>package controller\n\nimport (\n\t\"bytes\"\n\t\"encoding\/base64\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strings\"\n\t\"time\"\n\n\tct \"github.com\/flynn\/flynn-controller\/types\"\n\t\"github.com\/flynn\/flynn-controller\/utils\"\n\t\"github.com\/flynn\/go-discoverd\"\n\t\"github.com\/flynn\/go-discoverd\/dialer\"\n\t\"github.com\/flynn\/go-flynn\/pinned\"\n\t\"github.com\/flynn\/rpcplus\"\n\t\"github.com\/flynn\/strowger\/types\"\n)\n\nfunc NewClient(uri, key string) (*Client, error) {\n\tif uri == \"\" {\n\t\turi = \"discoverd+http:\/\/flynn-controller\"\n\t}\n\tu, err := url.Parse(uri)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc := &Client{\n\t\turl:  uri,\n\t\taddr: u.Host,\n\t\thttp: http.DefaultClient,\n\t\tkey:  key,\n\t}\n\tif u.Scheme == \"discoverd+http\" {\n\t\tif err := discoverd.Connect(\"\"); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdialer := dialer.New(discoverd.DefaultClient, nil)\n\t\tc.dial = dialer.Dial\n\t\tc.dialClose = dialer\n\t\tc.http = &http.Client{Transport: &http.Transport{Dial: c.dial}}\n\t\tu.Scheme = \"http\"\n\t\tc.url = u.String()\n\t}\n\treturn c, nil\n}\n\nfunc NewClientWithPin(uri, key string, pin []byte) (*Client, error) {\n\tu, err := url.Parse(uri)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc := &Client{\n\t\tdial: (&pinned.Config{Pin: pin}).Dial,\n\t\tkey:  key,\n\t}\n\tif _, port, _ := net.SplitHostPort(u.Host); port == \"\" {\n\t\tu.Host += \":443\"\n\t}\n\tc.addr = u.Host\n\tu.Scheme = \"http\"\n\tc.url = u.String()\n\tc.http = &http.Client{Transport: &http.Transport{Dial: c.dial}}\n\treturn c, nil\n}\n\ntype Client struct {\n\turl  string\n\tkey  string\n\taddr string\n\thttp *http.Client\n\n\tdial      rpcplus.DialFunc\n\tdialClose io.Closer\n}\n\nfunc (c *Client) Close() error {\n\tif c.dialClose != nil {\n\t\tc.dialClose.Close()\n\t}\n\treturn nil\n}\n\nvar ErrNotFound = errors.New(\"controller: not found\")\n\nfunc toJSON(v interface{}) (io.Reader, error) {\n\tdata, err := json.Marshal(v)\n\treturn bytes.NewBuffer(data), err\n}\n\nfunc (c *Client) rawReq(method, path string, contentType string, in, out interface{}) (*http.Response, error) {\n\tvar payload io.Reader\n\tswitch v := in.(type) {\n\tcase io.Reader:\n\t\tpayload = v\n\tcase nil:\n\tdefault:\n\t\tvar err error\n\t\tpayload, err = toJSON(in)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treq, err := http.NewRequest(method, c.url+path, payload)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif contentType == \"\" {\n\t\tcontentType = \"application\/json\"\n\t}\n\treq.Header.Set(\"Content-Type\", contentType)\n\treq.SetBasicAuth(\"\", c.key)\n\tres, err := c.http.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif res.StatusCode == 404 {\n\t\tres.Body.Close()\n\t\treturn res, ErrNotFound\n\t}\n\tif res.StatusCode != 200 {\n\t\tres.Body.Close()\n\t\treturn res, &url.Error{\n\t\t\tOp:  req.Method,\n\t\t\tURL: req.URL.String(),\n\t\t\tErr: fmt.Errorf(\"controller: unexpected status %d\", res.StatusCode),\n\t\t}\n\t}\n\tif out != nil {\n\t\tdefer res.Body.Close()\n\t\treturn res, json.NewDecoder(res.Body).Decode(out)\n\t}\n\treturn res, nil\n}\n\nfunc (c *Client) send(method, path string, in, out interface{}) error {\n\t_, err := c.rawReq(method, path, \"\", in, out)\n\treturn err\n}\n\nfunc (c *Client) put(path string, in, out interface{}) error {\n\treturn c.send(\"PUT\", path, in, out)\n}\n\nfunc (c *Client) post(path string, in, out interface{}) error {\n\treturn c.send(\"POST\", path, in, out)\n}\n\nfunc (c *Client) get(path string, out interface{}) error {\n\t_, err := c.rawReq(\"GET\", path, \"\", nil, out)\n\treturn err\n}\n\nfunc (c *Client) delete(path string) error {\n\tres, err := c.rawReq(\"DELETE\", path, \"\", nil, nil)\n\tif err == nil {\n\t\tres.Body.Close()\n\t}\n\treturn err\n}\n\nfunc (c *Client) StreamFormations(since *time.Time) (<-chan *ct.ExpandedFormation, *error) {\n\tif since == nil {\n\t\ts := time.Unix(0, 0)\n\t\tsince = &s\n\t}\n\tdial := c.dial\n\tif dial == nil {\n\t\tdial = net.Dial\n\t}\n\tch := make(chan *ct.ExpandedFormation)\n\tconn, err := dial(\"tcp\", c.addr)\n\tif err != nil {\n\t\tclose(ch)\n\t\treturn ch, &err\n\t}\n\theader := make(http.Header)\n\theader.Set(\"Authorization\", \"Basic \"+base64.StdEncoding.EncodeToString([]byte(\":\"+c.key)))\n\tclient, err := rpcplus.NewHTTPClient(conn, rpcplus.DefaultRPCPath, header)\n\tif err != nil {\n\t\tclose(ch)\n\t\treturn ch, &err\n\t}\n\treturn ch, &client.StreamGo(\"Controller.StreamFormations\", since, ch).Error\n}\n\nfunc (c *Client) CreateArtifact(artifact *ct.Artifact) error {\n\treturn c.post(\"\/artifacts\", artifact, artifact)\n}\n\nfunc (c *Client) CreateRelease(release *ct.Release) error {\n\treturn c.post(\"\/releases\", release, release)\n}\n\nfunc (c *Client) CreateApp(app *ct.App) error {\n\treturn c.post(\"\/apps\", app, app)\n}\n\nfunc (c *Client) CreateProvider(provider *ct.Provider) error {\n\treturn c.post(\"\/providers\", provider, provider)\n}\n\nfunc (c *Client) ProvisionResource(req *ct.ResourceReq) (*ct.Resource, error) {\n\tif req.ProviderID == \"\" {\n\t\treturn nil, errors.New(\"controller: missing provider id\")\n\t}\n\tres := &ct.Resource{}\n\terr := c.post(fmt.Sprintf(\"\/providers\/%s\/resources\", req.ProviderID), req, res)\n\treturn res, err\n}\n\nfunc (c *Client) PutResource(resource *ct.Resource) error {\n\tif resource.ID == \"\" || resource.ProviderID == \"\" {\n\t\treturn errors.New(\"controller: missing id and\/or provider id\")\n\t}\n\treturn c.put(fmt.Sprintf(\"\/providers\/%s\/resources\/%s\", resource.ProviderID, resource.ID), resource, resource)\n}\n\nfunc (c *Client) PutFormation(formation *ct.Formation) error {\n\tif formation.AppID == \"\" || formation.ReleaseID == \"\" {\n\t\treturn errors.New(\"controller: missing app id and\/or release id\")\n\t}\n\treturn c.put(fmt.Sprintf(\"\/apps\/%s\/formations\/%s\", formation.AppID, formation.ReleaseID), formation, formation)\n}\n\nfunc (c *Client) SetAppRelease(appID, releaseID string) error {\n\treturn c.put(fmt.Sprintf(\"\/apps\/%s\/release\", appID), &ct.Release{ID: releaseID}, nil)\n}\n\nfunc (c *Client) GetAppRelease(appID string) (*ct.Release, error) {\n\trelease := &ct.Release{}\n\treturn release, c.get(fmt.Sprintf(\"\/apps\/%s\/release\", appID), release)\n}\n\nfunc (c *Client) CreateRoute(appID string, route *strowger.Route) error {\n\treturn c.post(fmt.Sprintf(\"\/apps\/%s\/routes\", appID), route, route)\n}\n\nfunc (c *Client) GetFormation(appID, releaseID string) (*ct.Formation, error) {\n\tformation := &ct.Formation{}\n\treturn formation, c.get(fmt.Sprintf(\"\/apps\/%s\/formations\/%s\", appID, releaseID), formation)\n}\n\nfunc (c *Client) GetRelease(releaseID string) (*ct.Release, error) {\n\trelease := &ct.Release{}\n\treturn release, c.get(fmt.Sprintf(\"\/releases\/%s\", releaseID), release)\n}\n\nfunc (c *Client) GetArtifact(artifactID string) (*ct.Artifact, error) {\n\tartifact := &ct.Artifact{}\n\treturn artifact, c.get(fmt.Sprintf(\"\/artifacts\/%s\", artifactID), artifact)\n}\n\nfunc (c *Client) GetApp(appID string) (*ct.App, error) {\n\tapp := &ct.App{}\n\treturn app, c.get(fmt.Sprintf(\"\/apps\/%s\", appID), app)\n}\n\nfunc (c *Client) GetJobLog(appID, jobID string) (io.ReadCloser, error) {\n\tres, err := c.rawReq(\"GET\", fmt.Sprintf(\"\/apps\/%s\/jobs\/%s\/log\", appID, jobID), \"\", nil, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn res.Body, nil\n}\n\nfunc (c *Client) RunJobAttached(appID string, job *ct.NewJob) (utils.ReadWriteCloser, error) {\n\tdata, err := toJSON(job)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq, err := http.NewRequest(\"POST\", fmt.Sprintf(\"%s\/apps\/%s\/jobs\", c.url, appID), data)\n\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\treq.Header.Set(\"Accept\", \"application\/vnd.flynn.attach\")\n\treq.SetBasicAuth(\"\", c.key)\n\tvar dial rpcplus.DialFunc\n\tif c.dial != nil {\n\t\tdial = c.dial\n\t}\n\tres, rwc, err := utils.HijackRequest(req, dial)\n\tif err != nil {\n\t\tres.Body.Close()\n\t\treturn nil, err\n\t}\n\treturn rwc, nil\n}\n\nfunc (c *Client) RunJobDetached(appID string, req *ct.NewJob) (*ct.Job, error) {\n\tjob := &ct.Job{}\n\treturn job, c.post(fmt.Sprintf(\"\/apps\/%s\/jobs\", appID), req, job)\n}\n\nfunc (c *Client) JobList(appID string) ([]*ct.Job, error) {\n\tvar jobs []*ct.Job\n\treturn jobs, c.get(fmt.Sprintf(\"\/apps\/%s\/jobs\", appID), &jobs)\n}\n\nfunc (c *Client) KeyList() ([]*ct.Key, error) {\n\tvar keys []*ct.Key\n\treturn keys, c.get(\"\/keys\", &keys)\n}\n\nfunc (c *Client) CreateKey(pubKey string) (*ct.Key, error) {\n\tkey := &ct.Key{}\n\treturn key, c.post(\"\/keys\", &ct.Key{Key: pubKey}, key)\n}\n\nfunc (c *Client) DeleteKey(id string) error {\n\treturn c.delete(\"\/keys\/\" + strings.Replace(id, \":\", \"\", -1))\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2017 Cisco and\/or its affiliates.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at:\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage logging\n\n\/\/ LogLevel represents severity of log record\ntype LogLevel int\n\nconst (\n\t\/\/ DebugLevel - the most verbose logging\n\tDebugLevel LogLevel = iota\n\t\/\/ InfoLevel level - general operational entries about what's going on inside the application.\n\tInfoLevel\n\t\/\/ WarnLevel - non-critical entries that deserve eyes.\n\tWarnLevel\n\t\/\/ ErrorLevel level - used for errors that should definitely be noted.\n\tErrorLevel\n\t\/\/ FatalLevel - logs and then calls `os.Exit(1)`.\n\tFatalLevel\n\t\/\/ PanicLevel - highest level of severity. Logs and then calls panic with the message passed in.\n\tPanicLevel\n)\n\n\/\/ Logger provides logging capabilities\ntype Logger interface {\n\tLogWithLevel\n\t\/\/ SetLevel modifies the LogLevel\n\tSetLevel(level LogLevel)\n\t\/\/ GetLevel returns currently set logLevel\n\tGetLevel() LogLevel\n\t\/\/ WithField creates one structured field\n\tWithField(key string, value interface{}) LogWithLevel\n\t\/\/ WithFields creates multiple structured fields\n\tWithFields(fields map[string]interface{}) LogWithLevel\n}\n\n\/\/ LogWithLevel allows to log with different log levels\ntype LogWithLevel interface {\n\t\/\/ Debug logs using Debug level\n\tDebug(args ...interface{})\n\t\/\/ Info logs using Info level\n\tInfo(args ...interface{})\n\t\/\/ Warning logs using Warning level\n\tWarn(args ...interface{})\n\t\/\/ Error logs using Error level\n\tError(args ...interface{})\n\t\/\/ Errorf prints formatted log using Error level\n\tErrorf(format string, args ...interface{})\n\t\/\/ Panic logs using Panic level and panics\n\tPanic(args ...interface{})\n\t\/\/ Fatal logs using Fatal level and calls os.Exit(1)\n\tFatal(args ...interface{})\n}\n\n\/\/ Registry groups multiple Logger instances and allows to mange their log levels.\ntype Registry interface {\n\t\/\/ List Loggers returns a map (loggerName => log level)\n\tListLoggers() map[string]string\n\t\/\/ SetLevel modifies log level of selected logger in the registry\n\tSetLevel(logger, level string) error\n\t\/\/ GetLevel returns the currently set log level of the logger from registry\n\tGetLevel(logger string) (string, error)\n\t\/\/ GetLoggerByName returns a logger instance identified by name from registry\n\tGetLoggerByName(name string) (Logger, bool)\n\t\/\/ ClearRegistry removes all loggers except the default one from registry\n\tClearRegistry()\n}\n\n\/\/ String converts the Level to a string. E.g. PanicLevel becomes \"panic\".\nfunc (level LogLevel) String() string {\n\tswitch level {\n\tcase DebugLevel:\n\t\treturn \"debug\"\n\tcase InfoLevel:\n\t\treturn \"info\"\n\tcase WarnLevel:\n\t\treturn \"warning\"\n\tcase ErrorLevel:\n\t\treturn \"error\"\n\tcase FatalLevel:\n\t\treturn \"fatal\"\n\tcase PanicLevel:\n\t\treturn \"panic\"\n\t}\n\n\treturn \"unknown\"\n}\n<commit_msg>Add log API with format string<commit_after>\/\/ Copyright (c) 2017 Cisco and\/or its affiliates.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at:\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage logging\n\n\/\/ LogLevel represents severity of log record\ntype LogLevel int\n\nconst (\n\t\/\/ DebugLevel - the most verbose logging\n\tDebugLevel LogLevel = iota\n\t\/\/ InfoLevel level - general operational entries about what's going on inside the application.\n\tInfoLevel\n\t\/\/ WarnLevel - non-critical entries that deserve eyes.\n\tWarnLevel\n\t\/\/ ErrorLevel level - used for errors that should definitely be noted.\n\tErrorLevel\n\t\/\/ FatalLevel - logs and then calls `os.Exit(1)`.\n\tFatalLevel\n\t\/\/ PanicLevel - highest level of severity. Logs and then calls panic with the message passed in.\n\tPanicLevel\n)\n\n\/\/ Logger provides logging capabilities\ntype Logger interface {\n\tLogWithLevel\n\t\/\/ SetLevel modifies the LogLevel\n\tSetLevel(level LogLevel)\n\t\/\/ GetLevel returns currently set logLevel\n\tGetLevel() LogLevel\n\t\/\/ WithField creates one structured field\n\tWithField(key string, value interface{}) LogWithLevel\n\t\/\/ WithFields creates multiple structured fields\n\tWithFields(fields map[string]interface{}) LogWithLevel\n}\n\n\/\/ LogWithLevel allows to log with different log levels\ntype LogWithLevel interface {\n\t\/\/ Debug logs using Debug level\n\tDebug(args ...interface{})\n\t\/\/ Debugf prints formatted log using Debug level\n\tDebugf(format string, args ...interface{})\n\t\/\/ Info logs using Info level\n\tInfo(args ...interface{})\n\t\/\/ Infof prints formatted log using Info level\n\tInfof(format string, args ...interface{})\n\t\/\/ Warning logs using Warning level\n\tWarn(args ...interface{})\n\t\/\/ Warnf prints formatted log using Warn level\n\tWarnf(format string, args ...interface{})\n\t\/\/ Error logs using Error level\n\tError(args ...interface{})\n\t\/\/ Errorf prints formatted log using Error level\n\tErrorf(format string, args ...interface{})\n\t\/\/ Panic logs using Panic level and panics\n\tPanic(args ...interface{})\n\t\/\/ Panicf prints formatted log using Panic level and panic\n\tPanicf(format string, args ...interface{})\n\t\/\/ Fatal logs using Fatal level and calls os.Exit(1)\n\tFatal(args ...interface{})\n\t\/\/ Fatalf prints formatted log using Fatal level and calls os.Exit(1)\n\tFatalf(format string, args ...interface{})\n}\n\n\/\/ Registry groups multiple Logger instances and allows to mange their log levels.\ntype Registry interface {\n\t\/\/ List Loggers returns a map (loggerName => log level)\n\tListLoggers() map[string]string\n\t\/\/ SetLevel modifies log level of selected logger in the registry\n\tSetLevel(logger, level string) error\n\t\/\/ GetLevel returns the currently set log level of the logger from registry\n\tGetLevel(logger string) (string, error)\n\t\/\/ GetLoggerByName returns a logger instance identified by name from registry\n\tGetLoggerByName(name string) (Logger, bool)\n\t\/\/ ClearRegistry removes all loggers except the default one from registry\n\tClearRegistry()\n}\n\n\/\/ String converts the Level to a string. E.g. PanicLevel becomes \"panic\".\nfunc (level LogLevel) String() string {\n\tswitch level {\n\tcase DebugLevel:\n\t\treturn \"debug\"\n\tcase InfoLevel:\n\t\treturn \"info\"\n\tcase WarnLevel:\n\t\treturn \"warning\"\n\tcase ErrorLevel:\n\t\treturn \"error\"\n\tcase FatalLevel:\n\t\treturn \"fatal\"\n\tcase PanicLevel:\n\t\treturn \"panic\"\n\t}\n\n\treturn \"unknown\"\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2017 HenryLee. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage socket\n\nimport (\n\t\"bufio\"\n\t\"encoding\/binary\"\n\t\"errors\"\n\t\"io\"\n\t\"sync\"\n\n\t\"github.com\/henrylee2cn\/goutil\"\n\t\"github.com\/henrylee2cn\/teleport\/utils\"\n)\n\ntype (\n\t\/\/ Proto pack\/unpack protocol scheme of socket packet.\n\tProto interface {\n\t\t\/\/ Version returns the protocol's id and name.\n\t\tVersion() (byte, string)\n\t\t\/\/ Pack writes the Packet into the connection.\n\t\t\/\/ Note: Make sure to write only once or there will be package contamination!\n\t\tPack(*Packet) error\n\t\t\/\/ Unpack reads bytes from the connection to the Packet.\n\t\t\/\/ Note: Concurrent unsafe!\n\t\tUnpack(*Packet) error\n\t}\n\t\/\/ ProtoFunc function used to create a custom Proto interface.\n\tProtoFunc func(io.ReadWriter) Proto\n)\n\n\/\/ DefaultProtoFunc gets the default builder of socket communication protocol\nfunc DefaultProtoFunc() ProtoFunc {\n\treturn defaultProtoFunc\n}\n\n\/\/ SetDefaultProtoFunc sets the default builder of socket communication protocol\nfunc SetDefaultProtoFunc(protoFunc ProtoFunc) {\n\tdefaultProtoFunc = protoFunc\n}\n\ntype (\n\t\/\/ FastProto fast socket communication protocol.\n\tFastProto struct {\n\t\tid   byte\n\t\tname string\n\t\tr    io.Reader\n\t\tw    io.Writer\n\t\trMu  sync.Mutex\n\t}\n)\n\n\/\/ default builder of socket communication protocol\nvar (\n\tdefaultProtoFunc = func(rw io.ReadWriter) Proto {\n\t\treturn &FastProto{\n\t\t\tid:   'f',\n\t\t\tname: \"fast\",\n\t\t\tr:    bufio.NewReaderSize(rw, fastProtoReadBufioSize),\n\t\t\tw:    rw,\n\t\t}\n\t}\n\tlengthSize = int64(binary.Size(uint32(0)))\n)\n\n\/\/ error\nvar (\n\tErrProtoUnmatch = errors.New(\"Mismatched protocol\")\n)\n\n\/\/ Version returns the protocol's id and name.\nfunc (f *FastProto) Version() (byte, string) {\n\treturn f.id, f.name\n}\n\n\/\/ Pack writes the Packet into the connection.\n\/\/ Note: Make sure to write only once or there will be package contamination!\nfunc (f *FastProto) Pack(p *Packet) error {\n\tbb := utils.AcquireByteBuffer()\n\tdefer utils.ReleaseByteBuffer(bb)\n\n\t\/\/ fake size\n\terr := binary.Write(bb, binary.BigEndian, uint32(0))\n\n\t\/\/ protocol version\n\tbb.WriteByte(f.id)\n\n\t\/\/ transfer pipe\n\tbb.WriteByte(byte(p.XferPipe().Len()))\n\tbb.Write(p.XferPipe().Ids())\n\n\tprefixLen := bb.Len()\n\n\t\/\/ header\n\terr = f.writeHeader(bb, p)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ body\n\terr = f.writeBody(bb, p)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ do transfer pipe\n\tpayload, err := p.XferPipe().OnPack(bb.B[prefixLen:])\n\tif err != nil {\n\t\treturn err\n\t}\n\tbb.B = append(bb.B[:prefixLen], payload...)\n\n\t\/\/ set and check packet size\n\terr = p.SetSize(uint32(bb.Len()))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ reset real size\n\tbinary.BigEndian.PutUint32(bb.B, p.Size())\n\n\t\/\/ real write\n\t_, err = f.w.Write(bb.B)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn err\n}\n\nfunc (f *FastProto) writeHeader(bb *utils.ByteBuffer, p *Packet) error {\n\tbinary.Write(bb, binary.BigEndian, p.Seq())\n\n\tbb.WriteByte(p.Ptype())\n\n\turiBytes := goutil.StringToBytes(p.Uri())\n\tbinary.Write(bb, binary.BigEndian, uint32(len(uriBytes)))\n\tbb.Write(uriBytes)\n\n\tmetaBytes := p.Meta().QueryString()\n\tbinary.Write(bb, binary.BigEndian, uint32(len(metaBytes)))\n\tbb.Write(metaBytes)\n\treturn nil\n}\n\nfunc (f *FastProto) writeBody(bb *utils.ByteBuffer, p *Packet) error {\n\tbb.WriteByte(p.BodyCodec())\n\tbodyBytes, err := p.MarshalBody()\n\tif err != nil {\n\t\treturn err\n\t}\n\tbb.Write(bodyBytes)\n\treturn nil\n}\n\n\/\/ Unpack reads bytes from the connection to the Packet.\n\/\/ Note: Concurrent unsafe!\nfunc (f *FastProto) Unpack(p *Packet) error {\n\tbb := utils.AcquireByteBuffer()\n\tdefer utils.ReleaseByteBuffer(bb)\n\n\t\/\/ read packet\n\terr := f.readPacket(bb, p)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/ do transfer pipe\n\tdata, err := p.XferPipe().OnUnpack(bb.B)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/ header\n\tdata = f.readHeader(data, p)\n\t\/\/ body\n\treturn f.readBody(data, p)\n}\n\nfunc (f *FastProto) readPacket(bb *utils.ByteBuffer, p *Packet) error {\n\tf.rMu.Lock()\n\tdefer f.rMu.Unlock()\n\t\/\/ size\n\tvar size uint32\n\terr := binary.Read(f.r, binary.BigEndian, &size)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = p.SetSize(size); err != nil {\n\t\treturn err\n\t}\n\t\/\/ protocol\n\tbb.ChangeLen(1024)\n\t_, err = f.r.Read(bb.B[:1])\n\tif err != nil {\n\t\treturn err\n\t}\n\tif bb.B[0] != f.id {\n\t\treturn ErrProtoUnmatch\n\t}\n\t\/\/ transfer pipe\n\t_, err = f.r.Read(bb.B[:1])\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar xferLen = bb.B[0]\n\tif xferLen > 0 {\n\t\t_, err = f.r.Read(bb.B[:xferLen])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = p.XferPipe().Append(bb.B[:xferLen]...)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t\/\/ read last all\n\tvar lastLen = int(size) - 4 - 1 - 1 - int(xferLen)\n\tbb.ChangeLen(lastLen)\n\t_, err = io.ReadFull(f.r, bb.B)\n\treturn err\n}\n\nfunc (f *FastProto) readHeader(data []byte, p *Packet) []byte {\n\t\/\/ seq\n\tp.SetSeq(binary.BigEndian.Uint64(data))\n\tdata = data[8:]\n\t\/\/ type\n\tp.SetPtype(data[0])\n\tdata = data[1:]\n\t\/\/ uri\n\turiLen := binary.BigEndian.Uint32(data)\n\tdata = data[4:]\n\tp.SetUri(string(data[:uriLen]))\n\tdata = data[uriLen:]\n\t\/\/ meta\n\tmetaLen := binary.BigEndian.Uint32(data)\n\tdata = data[4:]\n\tp.Meta().ParseBytes(data[:metaLen])\n\tdata = data[metaLen:]\n\treturn data\n}\n\nfunc (f *FastProto) readBody(data []byte, p *Packet) error {\n\tp.SetBodyCodec(data[0])\n\treturn p.UnmarshalNewBody(data[1:])\n}\n<commit_msg>Optimize protocol.go<commit_after>\/\/ Copyright 2017 HenryLee. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage socket\n\nimport (\n\t\"bufio\"\n\t\"encoding\/binary\"\n\t\"errors\"\n\t\"io\"\n\t\"sync\"\n\n\t\"github.com\/henrylee2cn\/goutil\"\n\t\"github.com\/henrylee2cn\/teleport\/utils\"\n)\n\ntype (\n\t\/\/ Proto pack\/unpack protocol scheme of socket packet.\n\tProto interface {\n\t\t\/\/ Version returns the protocol's id and name.\n\t\tVersion() (byte, string)\n\t\t\/\/ Pack writes the Packet into the connection.\n\t\t\/\/ Note: Make sure to write only once or there will be package contamination!\n\t\tPack(*Packet) error\n\t\t\/\/ Unpack reads bytes from the connection to the Packet.\n\t\t\/\/ Note: Concurrent unsafe!\n\t\tUnpack(*Packet) error\n\t}\n\t\/\/ ProtoFunc function used to create a custom Proto interface.\n\tProtoFunc func(io.ReadWriter) Proto\n)\n\n\/\/ DefaultProtoFunc gets the default builder of socket communication protocol\nfunc DefaultProtoFunc() ProtoFunc {\n\treturn defaultProtoFunc\n}\n\n\/\/ SetDefaultProtoFunc sets the default builder of socket communication protocol\nfunc SetDefaultProtoFunc(protoFunc ProtoFunc) {\n\tdefaultProtoFunc = protoFunc\n}\n\ntype (\n\t\/\/ FastProto fast socket communication protocol.\n\tFastProto struct {\n\t\tid   byte\n\t\tname string\n\t\tr    io.Reader\n\t\tw    io.Writer\n\t\trMu  sync.Mutex\n\t}\n)\n\n\/\/ default builder of socket communication protocol\nvar defaultProtoFunc = func(rw io.ReadWriter) Proto {\n\treturn &FastProto{\n\t\tid:   'f',\n\t\tname: \"fast\",\n\t\tr:    bufio.NewReaderSize(rw, fastProtoReadBufioSize),\n\t\tw:    rw,\n\t}\n}\n\n\/\/ Version returns the protocol's id and name.\nfunc (f *FastProto) Version() (byte, string) {\n\treturn f.id, f.name\n}\n\n\/\/ Pack writes the Packet into the connection.\n\/\/ Note: Make sure to write only once or there will be package contamination!\nfunc (f *FastProto) Pack(p *Packet) error {\n\tbb := utils.AcquireByteBuffer()\n\tdefer utils.ReleaseByteBuffer(bb)\n\n\t\/\/ fake size\n\terr := binary.Write(bb, binary.BigEndian, uint32(0))\n\n\t\/\/ protocol version\n\tbb.WriteByte(f.id)\n\n\t\/\/ transfer pipe\n\tbb.WriteByte(byte(p.XferPipe().Len()))\n\tbb.Write(p.XferPipe().Ids())\n\n\tprefixLen := bb.Len()\n\n\t\/\/ header\n\terr = f.writeHeader(bb, p)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ body\n\terr = f.writeBody(bb, p)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ do transfer pipe\n\tpayload, err := p.XferPipe().OnPack(bb.B[prefixLen:])\n\tif err != nil {\n\t\treturn err\n\t}\n\tbb.B = append(bb.B[:prefixLen], payload...)\n\n\t\/\/ set and check packet size\n\terr = p.SetSize(uint32(bb.Len()))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ reset real size\n\tbinary.BigEndian.PutUint32(bb.B, p.Size())\n\n\t\/\/ real write\n\t_, err = f.w.Write(bb.B)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn err\n}\n\nfunc (f *FastProto) writeHeader(bb *utils.ByteBuffer, p *Packet) error {\n\tbinary.Write(bb, binary.BigEndian, p.Seq())\n\n\tbb.WriteByte(p.Ptype())\n\n\turiBytes := goutil.StringToBytes(p.Uri())\n\tbinary.Write(bb, binary.BigEndian, uint32(len(uriBytes)))\n\tbb.Write(uriBytes)\n\n\tmetaBytes := p.Meta().QueryString()\n\tbinary.Write(bb, binary.BigEndian, uint32(len(metaBytes)))\n\tbb.Write(metaBytes)\n\treturn nil\n}\n\nfunc (f *FastProto) writeBody(bb *utils.ByteBuffer, p *Packet) error {\n\tbb.WriteByte(p.BodyCodec())\n\tbodyBytes, err := p.MarshalBody()\n\tif err != nil {\n\t\treturn err\n\t}\n\tbb.Write(bodyBytes)\n\treturn nil\n}\n\n\/\/ Unpack reads bytes from the connection to the Packet.\n\/\/ Note: Concurrent unsafe!\nfunc (f *FastProto) Unpack(p *Packet) error {\n\tbb := utils.AcquireByteBuffer()\n\tdefer utils.ReleaseByteBuffer(bb)\n\n\t\/\/ read packet\n\terr := f.readPacket(bb, p)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/ do transfer pipe\n\tdata, err := p.XferPipe().OnUnpack(bb.B)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/ header\n\tdata = f.readHeader(data, p)\n\t\/\/ body\n\treturn f.readBody(data, p)\n}\n\nvar errProtoUnmatch = errors.New(\"Mismatched protocol\")\n\nfunc (f *FastProto) readPacket(bb *utils.ByteBuffer, p *Packet) error {\n\tf.rMu.Lock()\n\tdefer f.rMu.Unlock()\n\t\/\/ size\n\tvar size uint32\n\terr := binary.Read(f.r, binary.BigEndian, &size)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = p.SetSize(size); err != nil {\n\t\treturn err\n\t}\n\t\/\/ protocol\n\tbb.ChangeLen(1024)\n\t_, err = f.r.Read(bb.B[:1])\n\tif err != nil {\n\t\treturn err\n\t}\n\tif bb.B[0] != f.id {\n\t\treturn errProtoUnmatch\n\t}\n\t\/\/ transfer pipe\n\t_, err = f.r.Read(bb.B[:1])\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar xferLen = bb.B[0]\n\tif xferLen > 0 {\n\t\t_, err = f.r.Read(bb.B[:xferLen])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = p.XferPipe().Append(bb.B[:xferLen]...)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t\/\/ read last all\n\tvar lastLen = int(size) - 4 - 1 - 1 - int(xferLen)\n\tbb.ChangeLen(lastLen)\n\t_, err = io.ReadFull(f.r, bb.B)\n\treturn err\n}\n\nfunc (f *FastProto) readHeader(data []byte, p *Packet) []byte {\n\t\/\/ seq\n\tp.SetSeq(binary.BigEndian.Uint64(data))\n\tdata = data[8:]\n\t\/\/ type\n\tp.SetPtype(data[0])\n\tdata = data[1:]\n\t\/\/ uri\n\turiLen := binary.BigEndian.Uint32(data)\n\tdata = data[4:]\n\tp.SetUri(string(data[:uriLen]))\n\tdata = data[uriLen:]\n\t\/\/ meta\n\tmetaLen := binary.BigEndian.Uint32(data)\n\tdata = data[4:]\n\tp.Meta().ParseBytes(data[:metaLen])\n\tdata = data[metaLen:]\n\treturn data\n}\n\nfunc (f *FastProto) readBody(data []byte, p *Packet) error {\n\tp.SetBodyCodec(data[0])\n\treturn p.UnmarshalNewBody(data[1:])\n}\n<|endoftext|>"}
{"text":"<commit_before>package aiff\n\nimport (\n\t\"bytes\"\n\t\"encoding\/binary\"\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com\/mattetti\/audio\"\n\t\"github.com\/mattetti\/audio\/misc\"\n)\n\ntype Clip struct {\n\tr            io.ReadSeeker\n\tbyteSize     int\n\tchannels     int\n\tbitDepth     int\n\tsampleRate   int64\n\tsampleFrames int\n\treadFrames   int\n\n\t\/\/ decoder info\n\toffset    uint32\n\tblockSize uint32\n}\n\n\/\/ ReadPCM reads up to n frames from the clip.\n\/\/ The frwames as well as the number of frames\/items read are returned.\n\/\/ TODO(mattetti): misc.AudioFrames is a temporary solution that needs to be improved.\n\/\/ TODO(mattetti): we might want to keep track of the postion in the reader so we can easily check if\n\/\/ the reader has been reset.\nfunc (c *Clip) ReadPCM(nFrames int) (frames misc.AudioFrames, n int, err error) {\n\tif c == nil || c.sampleFrames == 0 {\n\t\treturn nil, 0, nil\n\t}\n\tif err := c.readOffsetBlockSize(); err != nil {\n\t\treturn nil, 0, err\n\t}\n\t\/\/ TODO(mattetti): respect offset and block size\n\n\tbytesPerSample := (c.bitDepth-1)\/8 + 1\n\tsampleBufData := make([]byte, bytesPerSample)\n\tframes = make(misc.AudioFrames, nFrames)\n\tfor i := 0; i < c.channels; i++ {\n\t\tframes[i] = make([]int, c.channels)\n\t}\n\noutter:\n\tfor frameIDX := 0; frameIDX < nFrames; frameIDX++ {\n\t\tif frameIDX > len(frames) {\n\t\t\tbreak\n\t\t}\n\n\t\tframe := make([]int, c.channels)\n\t\tfor j := 0; j < c.channels; j++ {\n\t\t\t_, err := c.r.Read(sampleBufData)\n\t\t\tif err != nil {\n\t\t\t\tif err == io.EOF {\n\t\t\t\t\terr = nil\n\t\t\t\t}\n\t\t\t\tbreak outter\n\t\t\t}\n\n\t\t\tsampleBuf := bytes.NewBuffer(sampleBufData)\n\t\t\tswitch c.bitDepth {\n\t\t\tcase 8:\n\t\t\t\tvar v uint8\n\t\t\t\tbinary.Read(sampleBuf, binary.BigEndian, &v)\n\t\t\t\tframe[j] = int(v)\n\t\t\tcase 16:\n\t\t\t\tvar v int16\n\t\t\t\tbinary.Read(sampleBuf, binary.BigEndian, &v)\n\t\t\t\tframe[j] = int(v)\n\t\t\tcase 24:\n\t\t\t\t\/\/ TODO: check if the conversion might not be inversed depending on\n\t\t\t\t\/\/ the encoding (BE vs LE)\n\t\t\t\tvar output int32\n\t\t\t\toutput |= int32(sampleBufData[2]) << 0\n\t\t\t\toutput |= int32(sampleBufData[1]) << 8\n\t\t\t\toutput |= int32(sampleBufData[0]) << 16\n\t\t\t\tframe[j] = int(output)\n\t\t\tcase 32:\n\t\t\t\tvar v int32\n\t\t\t\tbinary.Read(sampleBuf, binary.BigEndian, &v)\n\t\t\t\tframe[j] = int(v)\n\t\t\tdefault:\n\t\t\t\terr = fmt.Errorf(\"%v bit depth not supported\", c.bitDepth)\n\t\t\t\tbreak outter\n\t\t\t}\n\t\t}\n\t\tframes[frameIDX] = frame\n\t\tn++\n\t}\n\n\treturn frames, n, err\n}\n\n\/\/ Read reads frames into the passed buffer and returns the number of full frames\n\/\/ read.\nfunc (c *Clip) Read(buf []byte) (n int, err error) {\n\tif c == nil || c.sampleFrames == 0 {\n\t\treturn n, nil\n\t}\n\tif err := c.readOffsetBlockSize(); err != nil {\n\t\treturn n, err\n\t}\n\t\/\/ TODO(mattetti): respect offset and block size\n\n\tbytesPerSample := (c.bitDepth-1)\/8 + 1\n\tsampleBufData := make([]byte, bytesPerSample)\n\n\tframeSize := (bytesPerSample * c.channels)\n\t\/\/ TODO(mattetti): track how many frames we previously read so we don't\n\t\/\/ read past the chunk\n\tstartingAtFrame := c.readFrames\n\tif startingAtFrame >= c.sampleFrames {\n\t\treturn 0, nil\n\t}\noutter:\n\tfor i := 0; i+frameSize < len(buf); {\n\t\tfor j := 0; j < c.channels; j++ {\n\t\t\t_, err := c.r.Read(sampleBufData)\n\t\t\tif err != nil {\n\t\t\t\tif err == io.EOF {\n\t\t\t\t\terr = nil\n\t\t\t\t}\n\t\t\t\tbreak outter\n\t\t\t}\n\t\t\tfor _, b := range sampleBufData {\n\t\t\t\tbuf[i] = b\n\t\t\t\ti++\n\t\t\t}\n\t\t}\n\t\tc.readFrames++\n\t\tif c.readFrames >= c.sampleFrames {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tn = c.readFrames - startingAtFrame\n\treturn n, err\n}\n\n\/\/ Size returns the total number of frames available in this clip.\nfunc (c *Clip) Size() int64 {\n\tif c == nil {\n\t\treturn 0\n\t}\n\treturn int64(c.sampleFrames)\n}\n\n\/\/ Seek seeks into the clip\n\/\/ TODO(mattetti): Seek offset should be in frames, not bytes\nfunc (c *Clip) Seek(offset int64, whence int) (int64, error) {\n\tif c == nil {\n\t\treturn 0, nil\n\t}\n\n\treturn c.r.Seek(offset, whence)\n}\n\nfunc (c *Clip) FrameInfo() audio.FrameInfo {\n\treturn audio.FrameInfo{\n\t\tChannels:   c.channels,\n\t\tBitDepth:   c.bitDepth,\n\t\tSampleRate: c.sampleRate,\n\t}\n}\n\nfunc (c *Clip) readOffsetBlockSize() error {\n\tif c == nil || c.blockSize > 0 {\n\t\treturn nil\n\t}\n\n\t\/\/ TODO: endianness might depend on the encoding used to generate the aiff data.\n\t\/\/ check encSowt or encTwos\n\n\tif err := binary.Read(c.r, binary.BigEndian, &c.offset); err != nil {\n\t\treturn err\n\t}\n\tif err := binary.Read(c.r, binary.BigEndian, &c.blockSize); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n<commit_msg>aiff: fix the test<commit_after>package aiff\n\nimport (\n\t\"bytes\"\n\t\"encoding\/binary\"\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com\/mattetti\/audio\"\n\t\"github.com\/mattetti\/audio\/misc\"\n)\n\ntype Clip struct {\n\tr            io.ReadSeeker\n\tbyteSize     int\n\tchannels     int\n\tbitDepth     int\n\tsampleRate   int64\n\tsampleFrames int\n\treadFrames   int\n\n\t\/\/ decoder info\n\toffset     uint32\n\tblockSize  uint32\n\toffsetRead bool\n}\n\n\/\/ ReadPCM reads up to n frames from the clip.\n\/\/ The frwames as well as the number of frames\/items read are returned.\n\/\/ TODO(mattetti): misc.AudioFrames is a temporary solution that needs to be improved.\n\/\/ TODO(mattetti): we might want to keep track of the postion in the reader so we can easily check if\n\/\/ the reader has been reset.\nfunc (c *Clip) ReadPCM(nFrames int) (frames misc.AudioFrames, n int, err error) {\n\tif c == nil || c.sampleFrames == 0 {\n\t\treturn nil, 0, nil\n\t}\n\tif err := c.readOffsetBlockSize(); err != nil {\n\t\treturn nil, 0, err\n\t}\n\t\/\/ TODO(mattetti): respect offset and block size\n\n\tbytesPerSample := (c.bitDepth-1)\/8 + 1\n\tsampleBufData := make([]byte, bytesPerSample)\n\tframes = make(misc.AudioFrames, nFrames)\n\tfor i := 0; i < c.channels; i++ {\n\t\tframes[i] = make([]int, c.channels)\n\t}\n\noutter:\n\tfor frameIDX := 0; frameIDX < nFrames; frameIDX++ {\n\t\tif frameIDX > len(frames) {\n\t\t\tbreak\n\t\t}\n\n\t\tframe := make([]int, c.channels)\n\t\tfor j := 0; j < c.channels; j++ {\n\t\t\t_, err := c.r.Read(sampleBufData)\n\t\t\tif err != nil {\n\t\t\t\tif err == io.EOF {\n\t\t\t\t\terr = nil\n\t\t\t\t}\n\t\t\t\tbreak outter\n\t\t\t}\n\n\t\t\tsampleBuf := bytes.NewBuffer(sampleBufData)\n\t\t\tswitch c.bitDepth {\n\t\t\tcase 8:\n\t\t\t\tvar v uint8\n\t\t\t\tbinary.Read(sampleBuf, binary.BigEndian, &v)\n\t\t\t\tframe[j] = int(v)\n\t\t\tcase 16:\n\t\t\t\tvar v int16\n\t\t\t\tbinary.Read(sampleBuf, binary.BigEndian, &v)\n\t\t\t\tframe[j] = int(v)\n\t\t\tcase 24:\n\t\t\t\t\/\/ TODO: check if the conversion might not be inversed depending on\n\t\t\t\t\/\/ the encoding (BE vs LE)\n\t\t\t\tvar output int32\n\t\t\t\toutput |= int32(sampleBufData[2]) << 0\n\t\t\t\toutput |= int32(sampleBufData[1]) << 8\n\t\t\t\toutput |= int32(sampleBufData[0]) << 16\n\t\t\t\tframe[j] = int(output)\n\t\t\tcase 32:\n\t\t\t\tvar v int32\n\t\t\t\tbinary.Read(sampleBuf, binary.BigEndian, &v)\n\t\t\t\tframe[j] = int(v)\n\t\t\tdefault:\n\t\t\t\terr = fmt.Errorf(\"%v bit depth not supported\", c.bitDepth)\n\t\t\t\tbreak outter\n\t\t\t}\n\t\t}\n\t\tframes[frameIDX] = frame\n\t\tn++\n\t}\n\n\treturn frames, n, err\n}\n\n\/\/ Read reads frames into the passed buffer and returns the number of full frames\n\/\/ read.\nfunc (c *Clip) Read(buf []byte) (n int, err error) {\n\tif c == nil || c.sampleFrames == 0 {\n\t\treturn n, nil\n\t}\n\tif err := c.readOffsetBlockSize(); err != nil {\n\t\treturn n, err\n\t}\n\t\/\/ TODO(mattetti): respect offset and block size\n\n\tbytesPerSample := (c.bitDepth-1)\/8 + 1\n\tsampleBufData := make([]byte, bytesPerSample)\n\n\tframeSize := (bytesPerSample * c.channels)\n\t\/\/ TODO(mattetti): track how many frames we previously read so we don't\n\t\/\/ read past the chunk\n\tstartingAtFrame := c.readFrames\n\tif startingAtFrame >= c.sampleFrames {\n\t\treturn 0, nil\n\t}\noutter:\n\tfor i := 0; i+frameSize < len(buf); {\n\t\tfor j := 0; j < c.channels; j++ {\n\t\t\t_, err := c.r.Read(sampleBufData)\n\t\t\tif err != nil {\n\t\t\t\tif err == io.EOF {\n\t\t\t\t\terr = nil\n\t\t\t\t}\n\t\t\t\tbreak outter\n\t\t\t}\n\t\t\tfor _, b := range sampleBufData {\n\t\t\t\tbuf[i] = b\n\t\t\t\ti++\n\t\t\t}\n\t\t}\n\t\tc.readFrames++\n\t\tif c.readFrames >= c.sampleFrames {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tn = c.readFrames - startingAtFrame\n\treturn n, err\n}\n\n\/\/ Size returns the total number of frames available in this clip.\nfunc (c *Clip) Size() int64 {\n\tif c == nil {\n\t\treturn 0\n\t}\n\treturn int64(c.sampleFrames)\n}\n\n\/\/ Seek seeks into the clip\n\/\/ TODO(mattetti): Seek offset should be in frames, not bytes\nfunc (c *Clip) Seek(offset int64, whence int) (int64, error) {\n\tif c == nil {\n\t\treturn 0, nil\n\t}\n\n\treturn c.r.Seek(offset, whence)\n}\n\nfunc (c *Clip) FrameInfo() audio.FrameInfo {\n\treturn audio.FrameInfo{\n\t\tChannels:   c.channels,\n\t\tBitDepth:   c.bitDepth,\n\t\tSampleRate: c.sampleRate,\n\t}\n}\n\nfunc (c *Clip) readOffsetBlockSize() error {\n\t\/\/ reading the offset and blocksize should only happen once per chunk\n\tif c == nil || c.offsetRead == true {\n\t\treturn nil\n\t}\n\n\t\/\/ TODO: endianness might depend on the encoding used to generate the aiff data.\n\t\/\/ check encSowt or encTwos\n\n\tif err := binary.Read(c.r, binary.BigEndian, &c.offset); err != nil {\n\t\treturn err\n\t}\n\tif err := binary.Read(c.r, binary.BigEndian, &c.blockSize); err != nil {\n\t\treturn err\n\t}\n\n\tc.offsetRead = true\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package workflow\n\nimport (\n\t\"github.com\/go-gorp\/gorp\"\n\n\t\"github.com\/ovh\/cds\/sdk\"\n)\n\n\/\/ LoadWorkfowArtifactByHash retrieves an artiface using its download hash\nfunc LoadWorkfowArtifactByHash(db gorp.SqlExecutor, hash string) (*sdk.WorkflowNodeRunArtifact, error) {\n\tvar artGorp NodeRunArtifact\n\tquery := `SELECT workflow_node_run_artifacts.*\n\t\t  FROM workflow_node_run_artifacts\n\t\t  WHERE workflow_node_run_artifacts.download_hash = $1`\n\tif err := db.SelectOne(&artGorp, query, hash); err != nil {\n\t\treturn nil, err\n\t}\n\tart := sdk.WorkflowNodeRunArtifact(artGorp)\n\treturn &art, nil\n\n}\n\n\/\/ LoadArtifactByIDs Load artifact by workflow ID and artifact ID\nfunc LoadArtifactByIDs(db gorp.SqlExecutor, workflowID, artifactID int64) (*sdk.WorkflowNodeRunArtifact, error) {\n\tvar artGorp NodeRunArtifact\n\tquery := `\n\t\tSELECT *\n\t\tFROM workflow_node_run_artifacts\n\t\tJOIN workflow_run ON workflow_run.id = workflow_node_run_artifacts.workflow_run_id\n\t\tWHERE workflow_run.workflow_id = $1 AND workflow_node_run_artifacts.id = $2\n\n\t`\n\tif err := db.SelectOne(&artGorp, query, workflowID, artifactID); err != nil {\n\t\treturn nil, err\n\t}\n\tart := sdk.WorkflowNodeRunArtifact(artGorp)\n\treturn &art, nil\n}\n\nfunc loadArtifactByNodeRunID(db gorp.SqlExecutor, nodeRunID int64) ([]sdk.WorkflowNodeRunArtifact, error) {\n\tvar artifactsGorp []NodeRunArtifact\n\tif _, err := db.Select(&artifactsGorp, \"SELECT * FROM workflow_node_run_artifacts WHERE workflow_node_run_id = $1\", nodeRunID); err != nil {\n\t\treturn nil, err\n\t}\n\n\tartifacts := make([]sdk.WorkflowNodeRunArtifact, len(artifactsGorp))\n\tfor i := range artifactsGorp {\n\t\tartifacts[i] = sdk.WorkflowNodeRunArtifact(artifactsGorp[i])\n\t}\n\treturn artifacts, nil\n}\n\n\/\/ InsertArtifact insert in table workflow_artifacts\nfunc InsertArtifact(db gorp.SqlExecutor, a *sdk.WorkflowNodeRunArtifact) error {\n\twArtifactDB := NodeRunArtifact(*a)\n\tif err := db.Insert(&wArtifactDB); err != nil {\n\t\treturn err\n\t}\n\ta.ID = wArtifactDB.ID\n\treturn nil\n}\n<commit_msg>fix (api): load artifact sha512 on old wf (#2751)<commit_after>package workflow\n\nimport (\n\t\"github.com\/go-gorp\/gorp\"\n\n\t\"github.com\/ovh\/cds\/sdk\"\n)\n\n\/\/ LoadWorkfowArtifactByHash retrieves an artiface using its download hash\nfunc LoadWorkfowArtifactByHash(db gorp.SqlExecutor, hash string) (*sdk.WorkflowNodeRunArtifact, error) {\n\tvar artGorp NodeRunArtifact\n\tquery := `SELECT\n\t\t\t\tid,\n\t\t\t\tname,\n\t\t\t\ttag,\n\t\t\t\tworkflow_node_run_id,\n\t\t\t\tdownload_hash,\n\t\t\t\tsize,\n\t\t\t\tperm,\n\t\t\t\tmd5sum,\n\t\t\t\tobject_path,\n\t\t\t\tcreated,\n\t\t\t\tworkflow_run_id,\n\t\t\t\tcoalesce(sha512sum, '')\n\t\t  FROM workflow_node_run_artifacts\n\t\t  WHERE workflow_node_run_artifacts.download_hash = $1`\n\tif err := db.SelectOne(&artGorp, query, hash); err != nil {\n\t\treturn nil, err\n\t}\n\tart := sdk.WorkflowNodeRunArtifact(artGorp)\n\treturn &art, nil\n\n}\n\n\/\/ LoadArtifactByIDs Load artifact by workflow ID and artifact ID\nfunc LoadArtifactByIDs(db gorp.SqlExecutor, workflowID, artifactID int64) (*sdk.WorkflowNodeRunArtifact, error) {\n\tvar artGorp NodeRunArtifact\n\tquery := `\n\t\tSELECT\n\t\t\tid,\n\t\t\tname,\n\t\t\ttag,\n\t\t\tworkflow_node_run_id,\n\t\t\tdownload_hash,\n\t\t\tsize,\n\t\t\tperm,\n\t\t\tmd5sum,\n\t\t\tobject_path,\n\t\t\tcreated,\n\t\t\tworkflow_run_id,\n\t\t\tcoalesce(sha512sum, '')\n\t\tFROM workflow_node_run_artifacts\n\t\tJOIN workflow_run ON workflow_run.id = workflow_node_run_artifacts.workflow_run_id\n\t\tWHERE workflow_run.workflow_id = $1 AND workflow_node_run_artifacts.id = $2\n\n\t`\n\tif err := db.SelectOne(&artGorp, query, workflowID, artifactID); err != nil {\n\t\treturn nil, err\n\t}\n\tart := sdk.WorkflowNodeRunArtifact(artGorp)\n\treturn &art, nil\n}\n\nfunc loadArtifactByNodeRunID(db gorp.SqlExecutor, nodeRunID int64) ([]sdk.WorkflowNodeRunArtifact, error) {\n\tvar artifactsGorp []NodeRunArtifact\n\tif _, err := db.Select(&artifactsGorp, `SELECT\n\t\t\tid,\n\t\t\tname,\n\t\t\ttag,\n\t\t\tworkflow_node_run_id,\n\t\t\tdownload_hash,\n\t\t\tsize,\n\t\t\tperm,\n\t\t\tmd5sum,\n\t\t\tobject_path,\n\t\t\tcreated,\n\t\t\tworkflow_run_id,\n\t\t\tcoalesce(sha512sum, '')\n\t\tFROM workflow_node_run_artifacts WHERE workflow_node_run_id = $1`, nodeRunID); err != nil {\n\t\treturn nil, err\n\t}\n\n\tartifacts := make([]sdk.WorkflowNodeRunArtifact, len(artifactsGorp))\n\tfor i := range artifactsGorp {\n\t\tartifacts[i] = sdk.WorkflowNodeRunArtifact(artifactsGorp[i])\n\t}\n\treturn artifacts, nil\n}\n\n\/\/ InsertArtifact insert in table workflow_artifacts\nfunc InsertArtifact(db gorp.SqlExecutor, a *sdk.WorkflowNodeRunArtifact) error {\n\twArtifactDB := NodeRunArtifact(*a)\n\tif err := db.Insert(&wArtifactDB); err != nil {\n\t\treturn err\n\t}\n\ta.ID = wArtifactDB.ID\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package helper\n\nimport (\n\t\"koding\/tools\/config\"\n\t\"socialapi\/db\"\n\n\t\"github.com\/koding\/bongo\"\n\t\"github.com\/koding\/broker\"\n\t\"github.com\/koding\/rabbitmq\"\n)\n\nfunc MustInitBongo(c *config.Config) *bongo.Bongo {\n\trmqConf := &rabbitmq.Config{\n\t\tHost:     c.Mq.Host,\n\t\tPort:     c.Mq.Port,\n\t\tUsername: c.Mq.ComponentUser,\n\t\tPassword: c.Mq.Password,\n\t\tVhost:    c.Mq.Vhost,\n\t}\n\n\tbConf := &broker.Config{\n\t\tRMQConfig: rmqConf,\n\t}\n\tbroker := broker.New(bConf, log)\n\tbongo := bongo.New(broker, db.DB, log)\n\terr := Bongo.Connect()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn bongo\n}\n<commit_msg>Social: change bongo helper to accept log intance<commit_after>package helper\n\nimport (\n\t\"koding\/tools\/config\"\n\t\"socialapi\/db\"\n\t\"github.com\/koding\/logging\"\n\n\t\"github.com\/koding\/bongo\"\n\t\"github.com\/koding\/broker\"\n\t\"github.com\/koding\/rabbitmq\"\n)\n\nfunc MustInitBongo(c *config.Config, log logging.Logger) *bongo.Bongo {\n\trmqConf := &rabbitmq.Config{\n\t\tHost:     c.Mq.Host,\n\t\tPort:     c.Mq.Port,\n\t\tUsername: c.Mq.ComponentUser,\n\t\tPassword: c.Mq.Password,\n\t\tVhost:    c.Mq.Vhost,\n\t}\n\n\tbConf := &broker.Config{\n\t\tRMQConfig: rmqConf,\n\t}\n\tbroker := broker.New(bConf, log)\n\tbongo := bongo.New(broker, db.DB, log)\n\terr := bongo.Connect()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn bongo\n}\n<|endoftext|>"}
{"text":"<commit_before>package mk2if\n\nconst (\n\tLED_TEMPERATURE = 128\n\tLED_LOW_BATTERY = 64\n\tLED_OVERLOAD    = 32\n\tLED_INVERTER    = 16\n\tLED_FLOAT       = 8\n\tLED_BULK        = 4\n\tLED_ABSORPTION  = 2\n\tLED_MAIN        = 1\n)\n\nvar LedNames = map[int]string{\n\tLED_TEMPERATURE: \"Temperature\",\n\tLED_LOW_BATTERY: \"Low Battery\",\n\tLED_OVERLOAD:    \"Overload\",\n\tLED_INVERTER:    \"Inverter\",\n\tLED_FLOAT:       \"Float\",\n\tLED_BULK:        \"Bulk\",\n\tLED_ABSORPTION:  \"Absorbtion\",\n\tLED_MAIN:        \"Mains\",\n}\n\ntype Mk2Info struct {\n\tValid bool\n\n\tVersion    uint32\n\n\tBatVoltage float64\n\t\/\/ Positive current == charging\n\t\/\/ Negative current == discharging\n\tBatCurrent float64\n\n\t\/\/ Input AC parameters\n\tInVoltage   float64\n\tInCurrent   float64\n\tInFrequency float64\n\n\t\/\/ Output AC parameters\n\tOutVoltage   float64\n\tOutCurrent   float64\n\tOutFrequency float64\n\n\t\/\/ Charge state 0.0 to 1.0\n\tChargeState float64\n\n\t\/\/ List only active LEDs\n\tLedListOn    []int\n\tLedListBlink []int\n\n\tErrors []error\n}\n\ntype Mk2If interface {\n\tGetMk2Info() *Mk2Info\n\tClose()\n}\n<commit_msg>Cleanup<commit_after>package mk2if\n\nconst (\n\tLED_TEMPERATURE = 128\n\tLED_LOW_BATTERY = 64\n\tLED_OVERLOAD    = 32\n\tLED_INVERTER    = 16\n\tLED_FLOAT       = 8\n\tLED_BULK        = 4\n\tLED_ABSORPTION  = 2\n\tLED_MAIN        = 1\n)\n\nvar LedNames = map[int]string{\n\tLED_TEMPERATURE: \"Temperature\",\n\tLED_LOW_BATTERY: \"Low Battery\",\n\tLED_OVERLOAD:    \"Overload\",\n\tLED_INVERTER:    \"Inverter\",\n\tLED_FLOAT:       \"Float\",\n\tLED_BULK:        \"Bulk\",\n\tLED_ABSORPTION:  \"Absorbtion\",\n\tLED_MAIN:        \"Mains\",\n}\n\ntype Mk2Info struct {\n\t\/\/ Will be marked as false if an error is detected.\n\tValid bool\n\n\tVersion uint32\n\n\tBatVoltage float64\n\t\/\/ Positive current == charging\n\t\/\/ Negative current == discharging\n\tBatCurrent float64\n\n\t\/\/ Input AC parameters\n\tInVoltage   float64\n\tInCurrent   float64\n\tInFrequency float64\n\n\t\/\/ Output AC parameters\n\tOutVoltage   float64\n\tOutCurrent   float64\n\tOutFrequency float64\n\n\t\/\/ Charge state 0.0 to 1.0\n\tChargeState float64\n\n\t\/\/ List only active LEDs\n\tLedListOn    []int\n\tLedListBlink []int\n\n\tErrors []error\n}\n\ntype Mk2If interface {\n\tGetMk2Info() *Mk2Info\n\tClose()\n}\n<|endoftext|>"}
{"text":"<commit_before>package transport\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"logger\"\n\t\"net\"\n\t\"stash.cloudflare.com\/go-stream\/stream\"\n\t\"stash.cloudflare.com\/go-stream\/stream\/sink\"\n\t\"stash.cloudflare.com\/go-stream\/stream\/source\"\n\t\"stash.cloudflare.com\/go-stream\/util\"\n\t\"stash.cloudflare.com\/go-stream\/util\/slog\"\n\t\"sync\"\n\t\"time\"\n)\n\nconst RETRIES = 3\nconst ACK_TIMEOUT_MS = 10000\n\ntype Client struct {\n\t*stream.HardStopChannelCloser\n\t*stream.BaseIn\n\taddr string\n\t\/\/id string\n\thwm      int\n\tbuf      util.SequentialBuffer\n\tretries  int\n\trunning  bool\n\tnotifier stream.ProcessedNotifier\n}\n\nfunc DefaultClient(ip string) *Client {\n\treturn NewClient(fmt.Sprintf(\"%s:4558\", ip), DEFAULT_HWM)\n}\n\nfunc NewClient(addr string, hwm int) *Client {\n\tbuf := util.NewSequentialBufferChanImpl(hwm + 1)\n\treturn &Client{stream.NewHardStopChannelCloser(), stream.NewBaseIn(stream.CHAN_SLACK), addr, hwm, buf, 0, false, nil}\n}\n\nfunc (src *Client) SetNotifier(n stream.ProcessedNotifier) *Client {\n\tif n.Blocking() == true {\n\t\tslog.Fatalf(\"Can't use a blocking Notifier\")\n\t}\n\tsrc.notifier = n\n\treturn src\n}\n\nfunc (src *Client) processAck(seq int) (progress bool) {\n\t\/\/log.Println(\"Processing ack\", seq)\n\tcnt := src.buf.Ack(seq)\n\tif cnt > 0 {\n\t\tif src.notifier != nil {\n\t\t\tsrc.notifier.Notify(cnt)\n\t\t}\n\t\tsrc.retries = 0\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (c *Client) ReConnect() error {\n\tif c.IsRunning() {\n\t\treturn errors.New(\"Still Running\")\n\t}\n\tc.retries = 0\n\treturn c.Run()\n}\n\nfunc (src *Client) Run() error {\n\tsrc.running = true\n\tdefer func() {\n\t\tsrc.running = false\n\t}()\n\tfor src.retries < 3 {\n\t\terr := src.connect()\n\t\tif err == nil {\n\t\t\tslog.Logf(logger.Levels.Warn, \"Connection failed without error\")\n\t\t\treturn err\n\t\t} else {\n\t\t\tslog.Logf(logger.Levels.Error, \"Connection failed with error, retrying: %s\", err)\n\t\t}\n\t}\n\tslog.Logf(logger.Levels.Error, \"Connection failed retries exceeded. Leftover: %d\", src.buf.Len())\n\treturn nil \/\/>>>>>>>>>>>>>>???????????????????????\n}\n\nfunc (src Client) IsRunning() bool {\n\treturn src.running\n}\n\nfunc (src Client) Len() (int, error) {\n\tif src.IsRunning() {\n\t\treturn -1, errors.New(\"Still Running\")\n\t}\n\treturn src.buf.Len(), nil\n}\n\nfunc (src *Client) resetAckTimer() (timer <-chan time.Time) {\n\tif src.buf.Len() > 0 {\n\t\treturn time.After(ACK_TIMEOUT_MS * time.Millisecond)\n\t}\n\treturn nil\n}\n\nfunc (src *Client) connect() error {\n\tdefer func() {\n\t\tsrc.retries++\n\t}()\n\n\tconn, err := net.Dial(\"tcp\", src.addr)\n\tif err != nil {\n\t\tslog.Logf(logger.Levels.Error, \"Cannot establish a connection with %s %v\", src.addr, err)\n\t\treturn err\n\t}\n\n\twg_sub := &sync.WaitGroup{}\n\tdefer wg_sub.Wait()\n\n\trcvChData := make(chan stream.Object, 10)\n\treceiver := source.NewIOReaderSourceLengthDelim(conn)\n\treceiver.SetOut(rcvChData)\n\trcvChCloseNotifier := make(chan bool)\n\twg_sub.Add(1)\n\tgo func() {\n\t\tdefer wg_sub.Done()\n\t\tdefer close(rcvChCloseNotifier)\n\t\terr := receiver.Run()\n\t\tif err != nil {\n\t\t\tslog.Logf(logger.Levels.Error, \"Error in client reciever: %v\", err)\n\t\t}\n\t}()\n\t\/\/receiver will be closed by the sender after it is done sending. receiver closed via a hard stop.\n\n\twriteNotifier := stream.NewNonBlockingProcessedNotifier(2)\n\tsndChData := make(chan stream.Object, src.hwm)\n\tsndChCloseNotifier := make(chan bool)\n\tdefer close(sndChData)\n\tsender := sink.NewMultiPartWriterSink(conn)\n\tsender.CompletedNotifier = writeNotifier\n\tsender.SetIn(sndChData)\n\twg_sub.Add(1)\n\tgo func() {\n\t\tdefer receiver.Stop() \/\/close receiver\n\t\tdefer wg_sub.Done()\n\t\tdefer close(sndChCloseNotifier)\n\t\terr := sender.Run()\n\t\tif err != nil {\n\t\t\tslog.Logf(logger.Levels.Error, \"Error in client sender: %v\", err)\n\t\t}\n\t}()\n\t\/\/sender closed by closing the sndChData channel or by a hard stop\n\n\tif src.buf.Len() > 0 {\n\t\tleftover := src.buf.Reset()\n\t\tfor i, value := range leftover {\n\t\t\tsendData(sndChData, value, i+1)\n\t\t}\n\t}\n\n\ttimer := src.resetAckTimer()\n\n\tclosing := false\n\n\t\/\/defer log.Println(\"Exiting client loop\")\n\twritesNotCompleted := uint(0)\n\tfor {\n\t\tupstreamCh := src.In()\n\t\tif !src.buf.CanAdd() || closing {\n\t\t\t\/\/disable upstream listening\n\t\t\tupstreamCh = nil\n\t\t}\n\t\tif closing && src.buf.Len() == 0 {\n\t\t\tsendClose(sndChData, 100)\n\t\t\treturn nil\n\t\t}\n\t\tselect {\n\t\tcase msg, ok := <-upstreamCh:\n\t\t\tif !ok {\n\t\t\t\t\/\/softClose\n\t\t\t\t\/\/make sure everything was sent\n\t\t\t\tclosing = true\n\t\t\t} else {\n\t\t\t\tbytes := msg.([]byte)\n\t\t\t\tseq, err := src.buf.Add(bytes)\n\t\t\t\tif err != nil {\n\t\t\t\t\tslog.Fatalf(\"Error adding item to buffer %v\", err)\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tsendData(sndChData, bytes, seq)\n\t\t\t\twritesNotCompleted += 1\n\t\t\t}\n\t\tcase cnt := <-writeNotifier.NotificationChannel():\n\t\t\twritesNotCompleted -= cnt\n\t\t\tif timer == nil {\n\t\t\t\tslog.Logf(logger.Levels.Debug, \"Seting timer %v, %v\", time.Now(), time.Now().UnixNano())\n\t\t\t\ttimer = src.resetAckTimer()\n\t\t\t}\n\t\tcase obj, ok := <-rcvChData:\n\t\t\tslog.Logf(logger.Levels.Debug, \"in Rcv: %v\", ok)\n\t\t\tcommand, seq, _, err := parseMsg(obj.([]byte))\n\t\t\tif err != nil {\n\t\t\t\tslog.Fatalf(\"%v\", err)\n\t\t\t}\n\t\t\tif command == ACK {\n\t\t\t\tif src.processAck(seq) {\n\t\t\t\t\ttimer = src.resetAckTimer()\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tslog.Fatalf(\"Unknown Command: %v\", command)\n\t\t\t}\n\t\tcase <-rcvChCloseNotifier:\n\t\t\t\/\/connection threw an eof to the reader?\n\t\t\treturn errors.New(\"In Select: Recieve Closed\")\n\t\tcase <-sndChCloseNotifier:\n\t\t\treturn errors.New(\"Connection to Server was Broken in Send Direction\")\n\t\tcase <-timer:\n\t\t\treturn errors.New(fmt.Sprintf(\"Time Out Waiting For Ack, %d %v %v\", len(rcvChData), time.Now(), time.Now().UnixNano()))\n\t\tcase <-src.StopNotifier:\n\t\t\tsender.Stop()\n\t\t\treturn nil\n\t\t}\n\t}\n}\n<commit_msg>Armoring client transport to handle server failures gracefully<commit_after>package transport\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"logger\"\n\t\"net\"\n\t\"stash.cloudflare.com\/go-stream\/stream\"\n\t\"stash.cloudflare.com\/go-stream\/stream\/sink\"\n\t\"stash.cloudflare.com\/go-stream\/stream\/source\"\n\t\"stash.cloudflare.com\/go-stream\/util\"\n\t\"stash.cloudflare.com\/go-stream\/util\/slog\"\n\t\"sync\"\n\t\"time\"\n)\n\nconst RETRIES = 3\nconst ACK_TIMEOUT_MS = 10000\n\ntype Client struct {\n\t*stream.HardStopChannelCloser\n\t*stream.BaseIn\n\taddr string\n\t\/\/id string\n\thwm      int\n\tbuf      util.SequentialBuffer\n\tretries  int\n\trunning  bool\n\tnotifier stream.ProcessedNotifier\n}\n\nfunc DefaultClient(ip string) *Client {\n\treturn NewClient(fmt.Sprintf(\"%s:4558\", ip), DEFAULT_HWM)\n}\n\nfunc NewClient(addr string, hwm int) *Client {\n\tbuf := util.NewSequentialBufferChanImpl(hwm + 1)\n\treturn &Client{stream.NewHardStopChannelCloser(), stream.NewBaseIn(stream.CHAN_SLACK), addr, hwm, buf, 0, false, nil}\n}\n\nfunc (src *Client) SetNotifier(n stream.ProcessedNotifier) *Client {\n\tif n.Blocking() == true {\n\t\tslog.Fatalf(\"Can't use a blocking Notifier\")\n\t}\n\tsrc.notifier = n\n\treturn src\n}\n\nfunc (src *Client) processAck(seq int) (progress bool) {\n\t\/\/log.Println(\"Processing ack\", seq)\n\tcnt := src.buf.Ack(seq)\n\tif cnt > 0 {\n\t\tif src.notifier != nil {\n\t\t\tsrc.notifier.Notify(cnt)\n\t\t}\n\t\tsrc.retries = 0\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (c *Client) ReConnect() error {\n\tif c.IsRunning() {\n\t\treturn errors.New(\"Still Running\")\n\t}\n\tc.retries = 0\n\treturn c.Run()\n}\n\nfunc (src *Client) Run() error {\n\tsrc.running = true\n\tdefer func() {\n\t\tsrc.running = false\n\t}()\n\tfor src.retries < 3 {\n\t\terr := src.connect()\n\t\tif err == nil {\n\t\t\tslog.Logf(logger.Levels.Warn, \"Connection failed without error\")\n\t\t\treturn err\n\t\t} else {\n\t\t\tslog.Logf(logger.Levels.Error, \"Connection failed with error, retrying: %s\", err)\n\t\t}\n\t}\n\tslog.Logf(logger.Levels.Error, \"Connection failed retries exceeded. Leftover: %d\", src.buf.Len())\n\treturn nil \/\/>>>>>>>>>>>>>>???????????????????????\n}\n\nfunc (src Client) IsRunning() bool {\n\treturn src.running\n}\n\nfunc (src Client) Len() (int, error) {\n\tif src.IsRunning() {\n\t\treturn -1, errors.New(\"Still Running\")\n\t}\n\treturn src.buf.Len(), nil\n}\n\nfunc (src *Client) resetAckTimer() (timer <-chan time.Time) {\n\tif src.buf.Len() > 0 {\n\t\treturn time.After(ACK_TIMEOUT_MS * time.Millisecond)\n\t}\n\treturn nil\n}\n\nfunc (src *Client) connect() error {\n\tdefer func() {\n\t\tsrc.retries++\n\t}()\n\n\tconn, err := net.Dial(\"tcp\", src.addr)\n\tif err != nil {\n\t\tslog.Logf(logger.Levels.Error, \"Cannot establish a connection with %s %v\", src.addr, err)\n\t\treturn err\n\t}\n\n\twg_sub := &sync.WaitGroup{}\n\tdefer wg_sub.Wait()\n\n\trcvChData := make(chan stream.Object, 10)\n\treceiver := source.NewIOReaderSourceLengthDelim(conn)\n\treceiver.SetOut(rcvChData)\n\trcvChCloseNotifier := make(chan bool)\n\twg_sub.Add(1)\n\tgo func() {\n\t\tdefer wg_sub.Done()\n\t\tdefer close(rcvChCloseNotifier)\n\t\terr := receiver.Run()\n\t\tif err != nil {\n\t\t\tslog.Logf(logger.Levels.Error, \"Error in client reciever: %v\", err)\n\t\t}\n\t}()\n\t\/\/receiver will be closed by the sender after it is done sending. receiver closed via a hard stop.\n\n\twriteNotifier := stream.NewNonBlockingProcessedNotifier(2)\n\tsndChData := make(chan stream.Object, src.hwm)\n\tsndChCloseNotifier := make(chan bool)\n\tdefer close(sndChData)\n\tsender := sink.NewMultiPartWriterSink(conn)\n\tsender.CompletedNotifier = writeNotifier\n\tsender.SetIn(sndChData)\n\twg_sub.Add(1)\n\tgo func() {\n\t\tdefer receiver.Stop() \/\/close receiver\n\t\tdefer wg_sub.Done()\n\t\tdefer close(sndChCloseNotifier)\n\t\terr := sender.Run()\n\t\tif err != nil {\n\t\t\tslog.Logf(logger.Levels.Error, \"Error in client sender: %v\", err)\n\t\t}\n\t}()\n\t\/\/sender closed by closing the sndChData channel or by a hard stop\n\n\tif src.buf.Len() > 0 {\n\t\tleftover := src.buf.Reset()\n\t\tfor i, value := range leftover {\n\t\t\tsendData(sndChData, value, i+1)\n\t\t}\n\t}\n\n\ttimer := src.resetAckTimer()\n\n\tclosing := false\n\n\t\/\/defer log.Println(\"Exiting client loop\")\n\twritesNotCompleted := uint(0)\n\tfor {\n\t\tupstreamCh := src.In()\n\t\tif !src.buf.CanAdd() || closing {\n\t\t\t\/\/disable upstream listening\n\t\t\tupstreamCh = nil\n\t\t}\n\t\tif closing && src.buf.Len() == 0 {\n\t\t\tsendClose(sndChData, 100)\n\t\t\treturn nil\n\t\t}\n\t\tselect {\n\t\tcase msg, ok := <-upstreamCh:\n\t\t\tif !ok {\n\t\t\t\t\/\/softClose\n\t\t\t\t\/\/make sure everything was sent\n\t\t\t\tclosing = true\n\t\t\t} else {\n\t\t\t\tbytes := msg.([]byte)\n\t\t\t\tseq, err := src.buf.Add(bytes)\n\t\t\t\tif err != nil {\n\t\t\t\t\tslog.Fatalf(\"Error adding item to buffer %v\", err)\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tsendData(sndChData, bytes, seq)\n\t\t\t\twritesNotCompleted += 1\n\t\t\t}\n\t\tcase cnt := <-writeNotifier.NotificationChannel():\n\t\t\twritesNotCompleted -= cnt\n\t\t\tif timer == nil {\n\t\t\t\tslog.Logf(logger.Levels.Debug, \"Seting timer %v, %v\", time.Now(), time.Now().UnixNano())\n\t\t\t\ttimer = src.resetAckTimer()\n\t\t\t}\n\t\tcase obj, ok := <-rcvChData:\n\t\t\tslog.Logf(logger.Levels.Debug, \"in Rcv: %v\", ok)\n\t\t\tif !ok {\n\t\t\t\treturn errors.New(\"Connection to Server was Broken in Recieve Direction\")\n\t\t\t}\n\n\t\t\tcommand, seq, _, err := parseMsg(obj.([]byte))\n\t\t\tif err != nil {\n\t\t\t\tslog.Fatalf(\"%v\", err)\n\t\t\t}\n\t\t\tif command == ACK {\n\t\t\t\tif src.processAck(seq) {\n\t\t\t\t\ttimer = src.resetAckTimer()\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tslog.Fatalf(\"Unknown Command: %v\", command)\n\t\t\t}\n\t\tcase <-rcvChCloseNotifier:\n\t\t\t\/\/connection threw an eof to the reader?\n\t\t\treturn errors.New(\"In Select: Recieve Closed\")\n\t\tcase <-sndChCloseNotifier:\n\t\t\treturn errors.New(\"Connection to Server was Broken in Send Direction\")\n\t\tcase <-timer:\n\t\t\treturn errors.New(fmt.Sprintf(\"Time Out Waiting For Ack, %d %v %v\", len(rcvChData), time.Now(), time.Now().UnixNano()))\n\t\tcase <-src.StopNotifier:\n\t\t\tsender.Stop()\n\t\t\treturn nil\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package cl11\n\nimport (\n\t\"unsafe\"\n\n\tclw \"github.com\/rdwilliamson\/clw11\"\n)\n\ntype Event struct {\n\tid           clw.Event\n\tContext      *Context\n\tCommandType  CommandType\n\tCommandQueue *CommandQueue\n\n\tQueued int64\n\tSubmit int64\n\tStart  int64\n\tEnd    int64\n}\n\nfunc (c *Context) CreateUserEvent() (*Event, error) {\n\n\tevent, err := clw.CreateUserEvent(c.id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Event{id: event, Context: c, CommandType: CommandUser}, nil\n}\n\ntype CommandType int\n\nconst (\n\tCommandNDRangeKernel        = CommandType(clw.CommandNdrangeKernel)\n\tCommandTask                 = CommandType(clw.CommandTask)\n\tCommandNativeKernel         = CommandType(clw.CommandNativeKernel)\n\tCommandReadBuffer           = CommandType(clw.CommandReadBuffer)\n\tCommandWriteBuffer          = CommandType(clw.CommandWriteBuffer)\n\tCommandCopyBuffer           = CommandType(clw.CommandCopyBuffer)\n\tCommandReadImage            = CommandType(clw.CommandReadImage)\n\tCommandWriteImage           = CommandType(clw.CommandWriteImage)\n\tCommandCopyImage            = CommandType(clw.CommandCopyImage)\n\tCommandCopyImageToBuffer    = CommandType(clw.CommandCopyImageToBuffer)\n\tCommandCopyBufferToImage    = CommandType(clw.CommandCopyBufferToImage)\n\tCommandMapBuffer            = CommandType(clw.CommandMapBuffer)\n\tCommandMapImage             = CommandType(clw.CommandMapImage)\n\tCommandUnmapMemoryObject    = CommandType(clw.CommandUnmapMemoryObject)\n\tCommandMarker               = CommandType(clw.CommandMarker)\n\tCommandAcquireGlObjects     = CommandType(clw.CommandAcquireGlObjects)\n\tCommandReleaseGlObjects     = CommandType(clw.CommandReleaseGlObjects)\n\tCommandReadBufferRectangle  = CommandType(clw.CommandReadBufferRectangle)\n\tCommandWriteBufferRectangle = CommandType(clw.CommandWriteBufferRectangle)\n\tCommandCopyBufferRectangle  = CommandType(clw.CommandCopyBufferRectangle)\n\tCommandUser                 = CommandType(clw.CommandUser)\n)\n\nvar commandTypeMap = map[CommandType]string{\n\tCommandNDRangeKernel:        \"ND range kernel\",\n\tCommandTask:                 \"task\",\n\tCommandNativeKernel:         \"native kernel\",\n\tCommandReadBuffer:           \"read buffer\",\n\tCommandWriteBuffer:          \"write buffer\",\n\tCommandCopyBuffer:           \"copy buffer\",\n\tCommandReadImage:            \"read image\",\n\tCommandWriteImage:           \"write image\",\n\tCommandCopyImage:            \"copy image\",\n\tCommandCopyImageToBuffer:    \"copy image to buffer\",\n\tCommandCopyBufferToImage:    \"copy buffer to image\",\n\tCommandMapBuffer:            \"map buffer\",\n\tCommandMapImage:             \"map image\",\n\tCommandUnmapMemoryObject:    \"unmap memory object\",\n\tCommandMarker:               \"marker\",\n\tCommandAcquireGlObjects:     \"acquire GL objects\",\n\tCommandReleaseGlObjects:     \"release GL objects\",\n\tCommandReadBufferRectangle:  \"read buffer rectangle\",\n\tCommandWriteBufferRectangle: \"write buffer rectangle\",\n\tCommandCopyBufferRectangle:  \"copy buffer rectangle\",\n\tCommandUser:                 \"user\",\n}\n\nfunc (ct CommandType) String() string {\n\treturn commandTypeMap[ct]\n}\n\ntype CommandExecutionStatus int\n\nconst (\n\tComplete  = CommandExecutionStatus(clw.Complete)\n\tRunning   = CommandExecutionStatus(clw.Running)\n\tSubmitted = CommandExecutionStatus(clw.Submitted)\n\tQueued    = CommandExecutionStatus(clw.Queued)\n)\n\nfunc (ces CommandExecutionStatus) String() string {\n\tswitch ces {\n\tcase Complete:\n\t\treturn \"complete\"\n\tcase Running:\n\t\treturn \"running\"\n\tcase Submitted:\n\t\treturn \"submitted\"\n\tcase Queued:\n\t\treturn \"queued\"\n\t}\n\treturn \"\"\n}\n\n\/\/ Returns the events status, an error that caused the event to terminate, or an\n\/\/ error that occurred trying to retrieve the event status.\nfunc (e *Event) Status() (CommandExecutionStatus, error, error) {\n\n\tvar status clw.CommandExecutionStatus\n\terr := clw.GetEventInfo(e.id, clw.EventCommandExecutionStatus, clw.Size(unsafe.Sizeof(status)),\n\t\tunsafe.Pointer(&status), nil)\n\tif err != nil {\n\t\treturn 0, nil, err\n\t}\n\n\tif status < 0 {\n\t\treturn 0, clw.CodeToError(clw.Int(status)), nil\n\t}\n\n\treturn CommandExecutionStatus(status), nil, nil\n}\n\nfunc (e *Event) GetProfilingInfo() error {\n\n\tvar value clw.Ulong\n\terr := clw.GetEventProfilingInfo(e.id, clw.ProfilingCommandQueued, clw.Size(unsafe.Sizeof(value)),\n\t\tunsafe.Pointer(&value), nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\te.Queued = int64(value)\n\n\terr = clw.GetEventProfilingInfo(e.id, clw.ProfilingCommandSubmit, clw.Size(unsafe.Sizeof(value)),\n\t\tunsafe.Pointer(&value), nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\te.Submit = int64(value)\n\n\terr = clw.GetEventProfilingInfo(e.id, clw.ProfilingCommandStart, clw.Size(unsafe.Sizeof(value)),\n\t\tunsafe.Pointer(&value), nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\te.Start = int64(value)\n\n\terr = clw.GetEventProfilingInfo(e.id, clw.ProfilingCommandEnd, clw.Size(unsafe.Sizeof(value)),\n\t\tunsafe.Pointer(&value), nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\te.End = int64(value)\n\n\treturn nil\n}\n\nfunc (e *Event) SetCallback(callback func(e *Event, userData interface{}), userData interface{}) error {\n\n\treturn clw.SetEventCallback(e.id, clw.Complete,\n\t\tfunc(event clw.Event, ces clw.CommandExecutionStatus, _userData interface{}) {\n\t\t\tcallback(e, _userData)\n\t\t},\n\t\tuserData)\n}\n<commit_msg>Added wait for events.<commit_after>package cl11\n\nimport (\n\t\"unsafe\"\n\n\tclw \"github.com\/rdwilliamson\/clw11\"\n)\n\ntype Event struct {\n\tid           clw.Event\n\tContext      *Context\n\tCommandType  CommandType\n\tCommandQueue *CommandQueue\n\n\tQueued int64\n\tSubmit int64\n\tStart  int64\n\tEnd    int64\n}\n\nfunc (c *Context) CreateUserEvent() (*Event, error) {\n\n\tevent, err := clw.CreateUserEvent(c.id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Event{id: event, Context: c, CommandType: CommandUser}, nil\n}\n\ntype CommandType int\n\nconst (\n\tCommandNDRangeKernel        = CommandType(clw.CommandNdrangeKernel)\n\tCommandTask                 = CommandType(clw.CommandTask)\n\tCommandNativeKernel         = CommandType(clw.CommandNativeKernel)\n\tCommandReadBuffer           = CommandType(clw.CommandReadBuffer)\n\tCommandWriteBuffer          = CommandType(clw.CommandWriteBuffer)\n\tCommandCopyBuffer           = CommandType(clw.CommandCopyBuffer)\n\tCommandReadImage            = CommandType(clw.CommandReadImage)\n\tCommandWriteImage           = CommandType(clw.CommandWriteImage)\n\tCommandCopyImage            = CommandType(clw.CommandCopyImage)\n\tCommandCopyImageToBuffer    = CommandType(clw.CommandCopyImageToBuffer)\n\tCommandCopyBufferToImage    = CommandType(clw.CommandCopyBufferToImage)\n\tCommandMapBuffer            = CommandType(clw.CommandMapBuffer)\n\tCommandMapImage             = CommandType(clw.CommandMapImage)\n\tCommandUnmapMemoryObject    = CommandType(clw.CommandUnmapMemoryObject)\n\tCommandMarker               = CommandType(clw.CommandMarker)\n\tCommandAcquireGlObjects     = CommandType(clw.CommandAcquireGlObjects)\n\tCommandReleaseGlObjects     = CommandType(clw.CommandReleaseGlObjects)\n\tCommandReadBufferRectangle  = CommandType(clw.CommandReadBufferRectangle)\n\tCommandWriteBufferRectangle = CommandType(clw.CommandWriteBufferRectangle)\n\tCommandCopyBufferRectangle  = CommandType(clw.CommandCopyBufferRectangle)\n\tCommandUser                 = CommandType(clw.CommandUser)\n)\n\nvar commandTypeMap = map[CommandType]string{\n\tCommandNDRangeKernel:        \"ND range kernel\",\n\tCommandTask:                 \"task\",\n\tCommandNativeKernel:         \"native kernel\",\n\tCommandReadBuffer:           \"read buffer\",\n\tCommandWriteBuffer:          \"write buffer\",\n\tCommandCopyBuffer:           \"copy buffer\",\n\tCommandReadImage:            \"read image\",\n\tCommandWriteImage:           \"write image\",\n\tCommandCopyImage:            \"copy image\",\n\tCommandCopyImageToBuffer:    \"copy image to buffer\",\n\tCommandCopyBufferToImage:    \"copy buffer to image\",\n\tCommandMapBuffer:            \"map buffer\",\n\tCommandMapImage:             \"map image\",\n\tCommandUnmapMemoryObject:    \"unmap memory object\",\n\tCommandMarker:               \"marker\",\n\tCommandAcquireGlObjects:     \"acquire GL objects\",\n\tCommandReleaseGlObjects:     \"release GL objects\",\n\tCommandReadBufferRectangle:  \"read buffer rectangle\",\n\tCommandWriteBufferRectangle: \"write buffer rectangle\",\n\tCommandCopyBufferRectangle:  \"copy buffer rectangle\",\n\tCommandUser:                 \"user\",\n}\n\nfunc (ct CommandType) String() string {\n\treturn commandTypeMap[ct]\n}\n\ntype CommandExecutionStatus int\n\nconst (\n\tComplete  = CommandExecutionStatus(clw.Complete)\n\tRunning   = CommandExecutionStatus(clw.Running)\n\tSubmitted = CommandExecutionStatus(clw.Submitted)\n\tQueued    = CommandExecutionStatus(clw.Queued)\n)\n\nfunc (ces CommandExecutionStatus) String() string {\n\tswitch ces {\n\tcase Complete:\n\t\treturn \"complete\"\n\tcase Running:\n\t\treturn \"running\"\n\tcase Submitted:\n\t\treturn \"submitted\"\n\tcase Queued:\n\t\treturn \"queued\"\n\t}\n\treturn \"\"\n}\n\n\/\/ Returns the events status, an error that caused the event to terminate, or an\n\/\/ error that occurred trying to retrieve the event status.\nfunc (e *Event) Status() (CommandExecutionStatus, error, error) {\n\n\tvar status clw.CommandExecutionStatus\n\terr := clw.GetEventInfo(e.id, clw.EventCommandExecutionStatus, clw.Size(unsafe.Sizeof(status)),\n\t\tunsafe.Pointer(&status), nil)\n\tif err != nil {\n\t\treturn 0, nil, err\n\t}\n\n\tif status < 0 {\n\t\treturn 0, clw.CodeToError(clw.Int(status)), nil\n\t}\n\n\treturn CommandExecutionStatus(status), nil, nil\n}\n\nfunc (e *Event) GetProfilingInfo() error {\n\n\tvar value clw.Ulong\n\terr := clw.GetEventProfilingInfo(e.id, clw.ProfilingCommandQueued, clw.Size(unsafe.Sizeof(value)),\n\t\tunsafe.Pointer(&value), nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\te.Queued = int64(value)\n\n\terr = clw.GetEventProfilingInfo(e.id, clw.ProfilingCommandSubmit, clw.Size(unsafe.Sizeof(value)),\n\t\tunsafe.Pointer(&value), nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\te.Submit = int64(value)\n\n\terr = clw.GetEventProfilingInfo(e.id, clw.ProfilingCommandStart, clw.Size(unsafe.Sizeof(value)),\n\t\tunsafe.Pointer(&value), nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\te.Start = int64(value)\n\n\terr = clw.GetEventProfilingInfo(e.id, clw.ProfilingCommandEnd, clw.Size(unsafe.Sizeof(value)),\n\t\tunsafe.Pointer(&value), nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\te.End = int64(value)\n\n\treturn nil\n}\n\nfunc (e *Event) SetCallback(callback func(e *Event, userData interface{}), userData interface{}) error {\n\n\treturn clw.SetEventCallback(e.id, clw.Complete,\n\t\tfunc(event clw.Event, ces clw.CommandExecutionStatus, _userData interface{}) {\n\t\t\tcallback(e, _userData)\n\t\t},\n\t\tuserData)\n}\n\nfunc WaitForEvents(events ...*Event) error {\n\te := make([]clw.Event, len(events))\n\tfor i := range events {\n\t\te[i] = events[i].id\n\t}\n\treturn clw.WaitForEvents(e)\n}\n<|endoftext|>"}
{"text":"<commit_before>package agent\n\nimport (\n\t\"fmt\"\n\t\"github.com\/golang\/glog\"\n\t\"github.com\/romana\/core\/common\"\n\t\"github.com\/romana\/core\/pkg\/util\/firewall\"\n)\n\n\/\/ addPolicy is a placeholder. TODO\nfunc (a *Agent) addPolicy(input interface{}, ctx common.RestContext) (interface{}, error) {\n\t\/\/\tpolicy := input.(*common.Policy)\n\treturn nil, nil\n}\n\n\/\/ deletePolicy is a placeholder. TODO\nfunc (a *Agent) deletePolicy(input interface{}, ctx common.RestContext) (interface{}, error) {\n\t\/\/\tpolicyId := ctx.PathVariables[\"policyID\"]\n\treturn nil, nil\n}\n\n\/\/ listPolicies is a placeholder. TODO.\nfunc (a *Agent) listPolicies(input interface{}, ctx common.RestContext) (interface{}, error) {\n\treturn nil, nil\n}\n\n\/\/ Status is a structure containing statistics returned by statusHandler\ntype Status struct {\n\tRules      []firewall.IPtablesRule `json:\"rules\"`\n\tInterfaces []NetIf                 `json:\"interfaces\"`\n}\n\n\/\/ statusHandler reports operational statistics.\nfunc (a *Agent) statusHandler(input interface{}, ctx common.RestContext) (interface{}, error) {\n\tglog.V(1).Infoln(\"Agent: Entering statusHandler()\")\n\tfw, err := firewall.NewFirewall(firewall.ShellexProvider)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = fw.Init(a.Helper.Executor, a.store, a.networkConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trules, err := fw.ListRules()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tifaces, err := a.store.listNetIfs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstatus := Status{Rules: rules, Interfaces: ifaces}\n\treturn status, nil\n}\n\n\/\/ podDownHandler cleans up after pod deleted.\nfunc (a *Agent) podDownHandler(input interface{}, ctx common.RestContext) (interface{}, error) {\n\tglog.V(1).Infoln(\"Agent: Entering podDownHandler()\")\n\tnetReq := input.(*NetworkRequest)\n\tnetif := netReq.NetIf\n\n\t\/\/ We need new firewall instance here to use it's Cleanup()\n\t\/\/ to uninstall firewall rules related to the endpoint.\n\tfw, err := firewall.NewFirewall(firewall.ShellexProvider)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = fw.Init(a.Helper.Executor, a.store, a.networkConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = fw.Cleanup(netif)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Spawn new thread to process the request\n\tglog.Infof(\"Agent: Got request for pod teardown %v\\n\", netReq)\n\n\treturn \"OK\", nil\n}\n\n\/\/ podUpHandler handles HTTP requests for endpoints provisioning.\nfunc (a *Agent) podUpHandler(input interface{}, ctx common.RestContext) (interface{}, error) {\n\tglog.Infof(\"Agent: Entering podUpHandler()\")\n\tnetReq := input.(*NetworkRequest)\n\n\tglog.Infof(\"Agent: Got request for network configuration: %v\\n\", netReq)\n\t\/\/ Spawn new thread to process the request\n\n\t\/\/ TODO don't know if fork-bombs are possible in go but if they are this\n\t\/\/ need to be refactored as buffered channel with fixed pool of workers\n\tgo a.podUpHandlerAsync(*netReq)\n\n\t\/\/ TODO I wonder if this should actually return something like a\n\t\/\/ link to a status of this request which will later get updated\n\t\/\/ with success or failure -- Greg.\n\treturn \"OK\", nil\n}\n\n\/\/ vmDownHandler handles HTTP requests for endpoints teardown.\nfunc (a *Agent) vmDownHandler(input interface{}, ctx common.RestContext) (interface{}, error) {\n\tglog.Infof(\"In vmDownHandler() with %T %v\", input, input)\n\tnetif := input.(*NetIf)\n\tif netif.Name == \"\" {\n\t\t\/\/ This is a request from OpenStack Mech driver who does not have a name, let's find it.\n\t\terr := a.store.findNetIf(netif)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tglog.Infof(\"In vmDownHandler() with Name %s, IP %s Mac %s\\n\", netif.Name, netif.IP, netif.Mac)\n\n\tglog.Info(\"Agent: provisioning DHCP\")\n\tif err := a.leaseFile.provisionLease(netif, leaseRemove); err != nil {\n\t\tglog.Error(agentError(err))\n\t\treturn \"Error removing DHCP lease\", agentError(err)\n\t}\n\n\t\/\/ We need new firewall instance here to use it's Cleanup()\n\t\/\/ to uninstall firewall rules related to the endpoint.\n\tfw, err := firewall.NewFirewall(firewall.ShellexProvider)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = fw.Init(a.Helper.Executor, a.store, a.networkConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = fw.Cleanup(netif)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = a.store.deleteNetIf(netif)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \"OK\", nil\n}\n\n\/\/ vmUpHandler handles HTTP requests for endpoints provisioning.\n\/\/ Currently tested with Romana ML2 driver.\nfunc (a *Agent) vmUpHandler(input interface{}, ctx common.RestContext) (interface{}, error) {\n\t\/\/ Parse out NetIf form the request\n\tnetif := input.(*NetIf)\n\n\tglog.Infof(\"Got interface: Name %s, IP %s Mac %s\\n\", netif.Name, netif.IP, netif.Mac)\n\n\t\/\/ Spawn new thread to process the request\n\n\t\/\/ TODO don't know if fork-bombs are possible in go but if they are this\n\t\/\/ need to be refactored as buffered channel with fixed pool of workers\n\tgo a.vmUpHandlerAsync(*netif)\n\n\t\/\/ TODO I wonder if this should actually return something like a\n\t\/\/ link to a status of this request which will later get updated\n\t\/\/ with success or failure -- Greg.\n\treturn \"OK\", nil\n}\n\n\/\/ podUpHandlerAsync does a number of operations on given endpoint to ensure\n\/\/ it's connected:\n\/\/ 1. Ensures interface is ready\n\/\/ 2. Creates ip route pointing new interface\n\/\/ 3. Provisions firewall rules\nfunc (a *Agent) podUpHandlerAsync(netReq NetworkRequest) error {\n\tglog.V(1).Info(\"Agent: Entering podUpHandlerAsync()\")\n\tcurrentProvider := firewall.IPTsaveProvider\n\n\tnetif := netReq.NetIf\n\tif netif.Name == \"\" {\n\t\treturn agentErrorString(\"Agent: Interface name required\")\n\t}\n\tif !a.Helper.waitForIface(netif.Name) {\n\t\t\/\/ TODO should we resubmit failed interface in queue for later\n\t\t\/\/ retry ? ... considering openstack will give up as well after\n\t\t\/\/ timeout\n\t\tmsg := fmt.Sprintf(\"Requested interface not available in time - %s\", netif.Name)\n\t\tglog.Infoln(\"Agent: \", msg)\n\t\treturn agentErrorString(msg)\n\t}\n\tglog.Info(\"Agent: creating endpoint routes\")\n\tif err := a.Helper.ensureRouteToEndpoint(&netif); err != nil {\n\t\tglog.Error(agentError(err))\n\t\treturn agentError(err)\n\t}\n\n\tglog.Info(\"Agent: provisioning firewall\")\n\tfw, err := firewall.NewFirewall(currentProvider)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = fw.Init(a.Helper.Executor, a.store, a.networkConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err1 := fw.SetEndpoint(netif); err1 != nil {\n\t\tglog.Error(agentError(err))\n\t\treturn agentError(err)\n\t}\n\n\tvar rules RuleSet\n\tswitch currentProvider {\n\tcase firewall.ShellexProvider:\n\t\trules = KubeShellRules\n\tcase firewall.IPTsaveProvider:\n\t\trules = KubeSaveRestoreRules\n\tdefault:\n\t\terr := fmt.Errorf(\"Unkown firewall provider in podUpHandler\")\n\t\tglog.Error(agentError(err))\n\t\treturn agentError(err)\n\t}\n\n\tif err := prepareFirewallRules(fw, rules, currentProvider); err != nil {\n\t\tglog.Error(agentError(err))\n\t\treturn agentError(err)\n\t}\n\n\tif err := fw.ProvisionEndpoint(); err != nil {\n\t\tglog.Error(agentError(err))\n\t\treturn agentError(err)\n\t}\n\n\tglog.Info(\"Agent: All good\", netif)\n\treturn nil\n}\n\nfunc prepareFirewallRules(fw firewall.Firewall, rules RuleSet, firewallProvider firewall.Provider) error {\n\tvar defaultRules []firewall.FirewallRule\n\t\/\/\tvar u32filter string\n\tvar chainNames []string\n\tvar formatBody string\n\n\tswitch firewallProvider {\n\tcase firewall.ShellexProvider:\n\t\tmetadata := fw.Metadata()\n\t\tchainNames = metadata[\"chains\"].([]string)\n\t\t\/\/\t\tu32filter = metadata[\"u32filter\"].(string)\n\n\t\tfor _, rule := range rules {\n\t\t\tglog.V(2).Infof(\"In prepareFirewallRules(), with %v\", rule)\n\n\t\t\tvar currentChain string\n\t\t\tswitch rule.Direction {\n\t\t\tcase EgressLocalDirection:\n\t\t\t\tcurrentChain = chainNames[firewall.InputChainIndex]\n\t\t\tcase EgressGlobalDirection:\n\t\t\t\tcurrentChain = chainNames[firewall.ForwardOutChainIndex]\n\t\t\tcase IngressGlobalDirection:\n\t\t\t\tcurrentChain = chainNames[firewall.ForwardInChainIndex]\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"Error, unsupported rule direction type with firewall provider %s\", firewallProvider)\n\t\t\t}\n\n\t\t\tswitch rule.Format {\n\t\t\tcase FormatChain:\n\t\t\t\tformatBody = fmt.Sprintf(rule.Body, currentChain)\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"Error, unsupported rule format type with firewall provider %s\", firewallProvider)\n\t\t\t}\n\n\t\t\tr := firewall.NewFirewallRule()\n\t\t\tr.SetBody(formatBody)\n\n\t\t\tswitch rule.Position {\n\t\t\tcase DefaultPosition:\n\t\t\t\tdefaultRules = append(defaultRules, r)\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"Error, unsupported rule position with firewall provider %s\", firewallProvider)\n\t\t\t}\n\t\t}\n\tcase firewall.IPTsaveProvider:\n\t\tfor _, rule := range rules {\n\t\t\tglog.V(2).Infof(\"In prepareFirewallRules(), with %v\", rule)\n\n\t\t\tvar currentChain string\n\t\t\tswitch rule.Direction {\n\t\t\tcase EgressLocalDirection:\n\t\t\t\tcurrentChain = firewall.ChainNameEndpointToHost\n\t\t\tcase EgressGlobalDirection:\n\t\t\t\tcurrentChain = firewall.ChainNameEndpointEgress\n\t\t\tcase IngressGlobalDirection:\n\t\t\t\tcurrentChain = firewall.ChainNameEndpointIngress\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"Error, unsupported rule direction type with firewall provider %s\", firewallProvider)\n\t\t\t}\n\n\t\t\tswitch rule.Format {\n\t\t\tcase FormatChain:\n\t\t\t\tformatBody = fmt.Sprintf(rule.Body, currentChain)\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"Error, unsupported rule format type with firewall provider %s\", firewallProvider)\n\t\t\t}\n\n\t\t\tr := firewall.NewFirewallRule()\n\t\t\tr.SetBody(formatBody)\n\n\t\t\tswitch rule.Position {\n\t\t\tcase TopPosition:\n\t\t\t\tfw.EnsureRule(r, firewall.EnsureFirst)\n\t\t\tcase BottomPosition:\n\t\t\t\tfw.EnsureRule(r, firewall.EnsureLast)\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"Error, unsupported rule position with firewall provider %s\", firewallProvider)\n\t\t\t}\n\t\t}\n\tdefault:\n\t\treturn fmt.Errorf(\"Error, unsupported firewall provider type when preparing firewall rules\")\n\t}\n\n\treturn nil\n}\n\n\/\/ vmUpHandlerAsync does a number of operations on given endpoint to ensure\n\/\/ it's connected:\n\/\/ 1. Ensures interface is ready\n\/\/ 2. Checks if DHCP is running\n\/\/ 3. Creates ip route pointing new interface\n\/\/ 4. Provisions static DHCP lease for new interface\n\/\/ 5. Provisions firewall rules\nfunc (a *Agent) vmUpHandlerAsync(netif NetIf) error {\n\tglog.V(1).Info(\"Agent: Entering interfaceHandle()\")\n\tif !a.Helper.waitForIface(netif.Name) {\n\t\t\/\/ TODO should we resubmit failed interface in queue for later\n\t\t\/\/ retry ? ... considering oenstack will give up as well after\n\t\t\/\/ timeout\n\t\treturn agentErrorString(fmt.Sprintf(\"Requested interface not available in time - %s\", netif.Name))\n\t}\n\n\t\/\/ dhcpPid is only needed here for fail fast check\n\t\/\/ will try to poll the pid again in provisionLease\n\tglog.Info(\"Agent: checking if DHCP is running\")\n\t_, err := a.Helper.DhcpPid()\n\tif err != nil {\n\t\tglog.Error(agentError(err))\n\t\treturn agentError(err)\n\t}\n\terr = a.store.addNetIf(&netif)\n\tif err != nil {\n\t\treturn agentError(err)\n\t}\n\tglog.Info(\"Agent: creating endpoint routes\")\n\tif err := a.Helper.ensureRouteToEndpoint(&netif); err != nil {\n\t\tglog.Error(agentError(err))\n\t\treturn agentError(err)\n\t}\n\tglog.Info(\"Agent: provisioning DHCP\")\n\tif err := a.leaseFile.provisionLease(&netif, leaseAdd); err != nil {\n\t\tglog.Error(agentError(err))\n\t\treturn agentError(err)\n\t}\n\n\tglog.Info(\"Agent: provisioning firewall\")\n\tfw, err := firewall.NewFirewall(firewall.ShellexProvider)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = fw.Init(a.Helper.Executor, a.store, a.networkConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err1 := fw.SetEndpoint(netif); err1 != nil {\n\t\tglog.Error(agentError(err))\n\t\treturn agentError(err)\n\t}\n\n\tmetadata := fw.Metadata()\n\tchainNames := metadata[\"chains\"].([]string)\n\tu32filter := metadata[\"u32filter\"]\n\thostAddr := a.networkConfig.RomanaGW()\n\n\t\/\/ Default firewall rules for OpenStack\n\tinboundChain := chainNames[firewall.InputChainIndex]\n\tvar defaultRules []firewall.FirewallRule\n\n\tinboundRule := firewall.NewFirewallRule()\n\tinboundRule.SetBody(fmt.Sprintf(\"%s %s\", inboundChain, \"-m comment --comment DefaultDrop -j DROP\"))\n\tdefaultRules = append(defaultRules, inboundRule)\n\n\tinboundRule = firewall.NewFirewallRule()\n\tinboundRule.SetBody(fmt.Sprintf(\"%s %s\", inboundChain, \"-m state --state ESTABLISHED -j ACCEPT\"))\n\tdefaultRules = append(defaultRules, inboundRule)\n\n\tforwardOutChain := chainNames[firewall.ForwardOutChainIndex]\n\tforwardOutRule := firewall.NewFirewallRule()\n\tforwardOutRule.SetBody(fmt.Sprintf(\"%s %s\", forwardOutChain, \"-m comment --comment Outgoing -j RETURN\"))\n\tdefaultRules = append(defaultRules, forwardOutRule)\n\n\tforwardInChain := chainNames[firewall.ForwardInChainIndex]\n\tforwardInRule := firewall.NewFirewallRule()\n\tforwardInRule.SetBody(fmt.Sprintf(\"%s %s\", forwardInChain, \"-m state --state ESTABLISHED -j ACCEPT\"))\n\tdefaultRules = append(defaultRules, forwardInRule)\n\n\tforwardInRule = firewall.NewFirewallRule()\n\tforwardInRule.SetBody(fmt.Sprintf(\"%s ! -s %s -m u32 --u32 %s %s\", forwardInChain, hostAddr, u32filter, \"-j ACCEPT\"))\n\tdefaultRules = append(defaultRules, forwardInRule)\n\n\tfw.SetDefaultRules(defaultRules)\n\n\tif err := fw.ProvisionEndpoint(); err != nil {\n\t\tglog.Error(agentError(err))\n\t\treturn agentError(err)\n\t}\n\n\tglog.Info(\"All good\", netif)\n\treturn nil\n}\n<commit_msg>Allow choosing firewall provider with romana agent configuration file.<commit_after>package agent\n\nimport (\n\t\"fmt\"\n\t\"github.com\/golang\/glog\"\n\t\"github.com\/romana\/core\/common\"\n\t\"github.com\/romana\/core\/pkg\/util\/firewall\"\n)\n\n\/\/ addPolicy is a placeholder. TODO\nfunc (a *Agent) addPolicy(input interface{}, ctx common.RestContext) (interface{}, error) {\n\t\/\/\tpolicy := input.(*common.Policy)\n\treturn nil, nil\n}\n\n\/\/ deletePolicy is a placeholder. TODO\nfunc (a *Agent) deletePolicy(input interface{}, ctx common.RestContext) (interface{}, error) {\n\t\/\/\tpolicyId := ctx.PathVariables[\"policyID\"]\n\treturn nil, nil\n}\n\n\/\/ listPolicies is a placeholder. TODO.\nfunc (a *Agent) listPolicies(input interface{}, ctx common.RestContext) (interface{}, error) {\n\treturn nil, nil\n}\n\n\/\/ Status is a structure containing statistics returned by statusHandler\ntype Status struct {\n\tRules      []firewall.IPtablesRule `json:\"rules\"`\n\tInterfaces []NetIf                 `json:\"interfaces\"`\n}\n\n\/\/ statusHandler reports operational statistics.\nfunc (a *Agent) statusHandler(input interface{}, ctx common.RestContext) (interface{}, error) {\n\tglog.V(1).Infoln(\"Agent: Entering statusHandler()\")\n\tfw, err := firewall.NewFirewall(a.getFirewallType())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = fw.Init(a.Helper.Executor, a.store, a.networkConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trules, err := fw.ListRules()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tifaces, err := a.store.listNetIfs()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstatus := Status{Rules: rules, Interfaces: ifaces}\n\treturn status, nil\n}\n\n\/\/ podDownHandler cleans up after pod deleted.\nfunc (a *Agent) podDownHandler(input interface{}, ctx common.RestContext) (interface{}, error) {\n\tglog.V(1).Infoln(\"Agent: Entering podDownHandler()\")\n\tnetReq := input.(*NetworkRequest)\n\tnetif := netReq.NetIf\n\n\t\/\/ We need new firewall instance here to use it's Cleanup()\n\t\/\/ to uninstall firewall rules related to the endpoint.\n\tfw, err := firewall.NewFirewall(a.getFirewallType())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = fw.Init(a.Helper.Executor, a.store, a.networkConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = fw.Cleanup(netif)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Spawn new thread to process the request\n\tglog.Infof(\"Agent: Got request for pod teardown %v\\n\", netReq)\n\n\treturn \"OK\", nil\n}\n\n\/\/ podUpHandler handles HTTP requests for endpoints provisioning.\nfunc (a *Agent) podUpHandler(input interface{}, ctx common.RestContext) (interface{}, error) {\n\tglog.Infof(\"Agent: Entering podUpHandler()\")\n\tnetReq := input.(*NetworkRequest)\n\n\tglog.Infof(\"Agent: Got request for network configuration: %v\\n\", netReq)\n\t\/\/ Spawn new thread to process the request\n\n\t\/\/ TODO don't know if fork-bombs are possible in go but if they are this\n\t\/\/ need to be refactored as buffered channel with fixed pool of workers\n\tgo a.podUpHandlerAsync(*netReq)\n\n\t\/\/ TODO I wonder if this should actually return something like a\n\t\/\/ link to a status of this request which will later get updated\n\t\/\/ with success or failure -- Greg.\n\treturn \"OK\", nil\n}\n\n\/\/ vmDownHandler handles HTTP requests for endpoints teardown.\nfunc (a *Agent) vmDownHandler(input interface{}, ctx common.RestContext) (interface{}, error) {\n\tglog.Infof(\"In vmDownHandler() with %T %v\", input, input)\n\tnetif := input.(*NetIf)\n\tif netif.Name == \"\" {\n\t\t\/\/ This is a request from OpenStack Mech driver who does not have a name, let's find it.\n\t\terr := a.store.findNetIf(netif)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tglog.Infof(\"In vmDownHandler() with Name %s, IP %s Mac %s\\n\", netif.Name, netif.IP, netif.Mac)\n\n\tglog.Info(\"Agent: provisioning DHCP\")\n\tif err := a.leaseFile.provisionLease(netif, leaseRemove); err != nil {\n\t\tglog.Error(agentError(err))\n\t\treturn \"Error removing DHCP lease\", agentError(err)\n\t}\n\n\t\/\/ We need new firewall instance here to use it's Cleanup()\n\t\/\/ to uninstall firewall rules related to the endpoint.\n\tfw, err := firewall.NewFirewall(a.getFirewallType())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = fw.Init(a.Helper.Executor, a.store, a.networkConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = fw.Cleanup(netif)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = a.store.deleteNetIf(netif)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn \"OK\", nil\n}\n\n\/\/ vmUpHandler handles HTTP requests for endpoints provisioning.\n\/\/ Currently tested with Romana ML2 driver.\nfunc (a *Agent) vmUpHandler(input interface{}, ctx common.RestContext) (interface{}, error) {\n\t\/\/ Parse out NetIf form the request\n\tnetif := input.(*NetIf)\n\n\tglog.Infof(\"Got interface: Name %s, IP %s Mac %s\\n\", netif.Name, netif.IP, netif.Mac)\n\n\t\/\/ Spawn new thread to process the request\n\n\t\/\/ TODO don't know if fork-bombs are possible in go but if they are this\n\t\/\/ need to be refactored as buffered channel with fixed pool of workers\n\tgo a.vmUpHandlerAsync(*netif)\n\n\t\/\/ TODO I wonder if this should actually return something like a\n\t\/\/ link to a status of this request which will later get updated\n\t\/\/ with success or failure -- Greg.\n\treturn \"OK\", nil\n}\n\n\/\/ podUpHandlerAsync does a number of operations on given endpoint to ensure\n\/\/ it's connected:\n\/\/ 1. Ensures interface is ready\n\/\/ 2. Creates ip route pointing new interface\n\/\/ 3. Provisions firewall rules\nfunc (a *Agent) podUpHandlerAsync(netReq NetworkRequest) error {\n\tglog.V(1).Info(\"Agent: Entering podUpHandlerAsync()\")\n\tcurrentProvider := a.getFirewallType()\n\n\tnetif := netReq.NetIf\n\tif netif.Name == \"\" {\n\t\treturn agentErrorString(\"Agent: Interface name required\")\n\t}\n\tif !a.Helper.waitForIface(netif.Name) {\n\t\t\/\/ TODO should we resubmit failed interface in queue for later\n\t\t\/\/ retry ? ... considering openstack will give up as well after\n\t\t\/\/ timeout\n\t\tmsg := fmt.Sprintf(\"Requested interface not available in time - %s\", netif.Name)\n\t\tglog.Infoln(\"Agent: \", msg)\n\t\treturn agentErrorString(msg)\n\t}\n\tglog.Info(\"Agent: creating endpoint routes\")\n\tif err := a.Helper.ensureRouteToEndpoint(&netif); err != nil {\n\t\tglog.Error(agentError(err))\n\t\treturn agentError(err)\n\t}\n\n\tglog.Info(\"Agent: provisioning firewall\")\n\tfw, err := firewall.NewFirewall(currentProvider)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = fw.Init(a.Helper.Executor, a.store, a.networkConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err1 := fw.SetEndpoint(netif); err1 != nil {\n\t\tglog.Error(agentError(err))\n\t\treturn agentError(err)\n\t}\n\n\tvar rules RuleSet\n\tswitch currentProvider {\n\tcase firewall.ShellexProvider:\n\t\trules = KubeShellRules\n\tcase firewall.IPTsaveProvider:\n\t\trules = KubeSaveRestoreRules\n\tdefault:\n\t\terr := fmt.Errorf(\"Unkown firewall provider in podUpHandler\")\n\t\tglog.Error(agentError(err))\n\t\treturn agentError(err)\n\t}\n\n\tif err := prepareFirewallRules(fw, rules, currentProvider); err != nil {\n\t\tglog.Error(agentError(err))\n\t\treturn agentError(err)\n\t}\n\n\tif err := fw.ProvisionEndpoint(); err != nil {\n\t\tglog.Error(agentError(err))\n\t\treturn agentError(err)\n\t}\n\n\tglog.Info(\"Agent: All good\", netif)\n\treturn nil\n}\n\nfunc prepareFirewallRules(fw firewall.Firewall, rules RuleSet, firewallProvider firewall.Provider) error {\n\tvar defaultRules []firewall.FirewallRule\n\t\/\/\tvar u32filter string\n\tvar chainNames []string\n\tvar formatBody string\n\n\tswitch firewallProvider {\n\tcase firewall.ShellexProvider:\n\t\tmetadata := fw.Metadata()\n\t\tchainNames = metadata[\"chains\"].([]string)\n\t\t\/\/\t\tu32filter = metadata[\"u32filter\"].(string)\n\n\t\tfor _, rule := range rules {\n\t\t\tglog.V(2).Infof(\"In prepareFirewallRules(), with %v\", rule)\n\n\t\t\tvar currentChain string\n\t\t\tswitch rule.Direction {\n\t\t\tcase EgressLocalDirection:\n\t\t\t\tcurrentChain = chainNames[firewall.InputChainIndex]\n\t\t\tcase EgressGlobalDirection:\n\t\t\t\tcurrentChain = chainNames[firewall.ForwardOutChainIndex]\n\t\t\tcase IngressGlobalDirection:\n\t\t\t\tcurrentChain = chainNames[firewall.ForwardInChainIndex]\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"Error, unsupported rule direction type with firewall provider %s\", firewallProvider)\n\t\t\t}\n\n\t\t\tswitch rule.Format {\n\t\t\tcase FormatChain:\n\t\t\t\tformatBody = fmt.Sprintf(rule.Body, currentChain)\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"Error, unsupported rule format type with firewall provider %s\", firewallProvider)\n\t\t\t}\n\n\t\t\tr := firewall.NewFirewallRule()\n\t\t\tr.SetBody(formatBody)\n\n\t\t\tswitch rule.Position {\n\t\t\tcase DefaultPosition:\n\t\t\t\tdefaultRules = append(defaultRules, r)\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"Error, unsupported rule position with firewall provider %s\", firewallProvider)\n\t\t\t}\n\t\t}\n\tcase firewall.IPTsaveProvider:\n\t\tfor _, rule := range rules {\n\t\t\tglog.V(2).Infof(\"In prepareFirewallRules(), with %v\", rule)\n\n\t\t\tvar currentChain string\n\t\t\tswitch rule.Direction {\n\t\t\tcase EgressLocalDirection:\n\t\t\t\tcurrentChain = firewall.ChainNameEndpointToHost\n\t\t\tcase EgressGlobalDirection:\n\t\t\t\tcurrentChain = firewall.ChainNameEndpointEgress\n\t\t\tcase IngressGlobalDirection:\n\t\t\t\tcurrentChain = firewall.ChainNameEndpointIngress\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"Error, unsupported rule direction type with firewall provider %s\", firewallProvider)\n\t\t\t}\n\n\t\t\tswitch rule.Format {\n\t\t\tcase FormatChain:\n\t\t\t\tformatBody = fmt.Sprintf(rule.Body, currentChain)\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"Error, unsupported rule format type with firewall provider %s\", firewallProvider)\n\t\t\t}\n\n\t\t\tr := firewall.NewFirewallRule()\n\t\t\tr.SetBody(formatBody)\n\n\t\t\tswitch rule.Position {\n\t\t\tcase TopPosition:\n\t\t\t\tfw.EnsureRule(r, firewall.EnsureFirst)\n\t\t\tcase BottomPosition:\n\t\t\t\tfw.EnsureRule(r, firewall.EnsureLast)\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"Error, unsupported rule position with firewall provider %s\", firewallProvider)\n\t\t\t}\n\t\t}\n\tdefault:\n\t\treturn fmt.Errorf(\"Error, unsupported firewall provider type when preparing firewall rules\")\n\t}\n\n\treturn nil\n}\n\n\/\/ vmUpHandlerAsync does a number of operations on given endpoint to ensure\n\/\/ it's connected:\n\/\/ 1. Ensures interface is ready\n\/\/ 2. Checks if DHCP is running\n\/\/ 3. Creates ip route pointing new interface\n\/\/ 4. Provisions static DHCP lease for new interface\n\/\/ 5. Provisions firewall rules\nfunc (a *Agent) vmUpHandlerAsync(netif NetIf) error {\n\tglog.V(1).Info(\"Agent: Entering interfaceHandle()\")\n\tif !a.Helper.waitForIface(netif.Name) {\n\t\t\/\/ TODO should we resubmit failed interface in queue for later\n\t\t\/\/ retry ? ... considering oenstack will give up as well after\n\t\t\/\/ timeout\n\t\treturn agentErrorString(fmt.Sprintf(\"Requested interface not available in time - %s\", netif.Name))\n\t}\n\n\t\/\/ dhcpPid is only needed here for fail fast check\n\t\/\/ will try to poll the pid again in provisionLease\n\tglog.Info(\"Agent: checking if DHCP is running\")\n\t_, err := a.Helper.DhcpPid()\n\tif err != nil {\n\t\tglog.Error(agentError(err))\n\t\treturn agentError(err)\n\t}\n\terr = a.store.addNetIf(&netif)\n\tif err != nil {\n\t\treturn agentError(err)\n\t}\n\tglog.Info(\"Agent: creating endpoint routes\")\n\tif err := a.Helper.ensureRouteToEndpoint(&netif); err != nil {\n\t\tglog.Error(agentError(err))\n\t\treturn agentError(err)\n\t}\n\tglog.Info(\"Agent: provisioning DHCP\")\n\tif err := a.leaseFile.provisionLease(&netif, leaseAdd); err != nil {\n\t\tglog.Error(agentError(err))\n\t\treturn agentError(err)\n\t}\n\n\tglog.Info(\"Agent: provisioning firewall\")\n\tfw, err := firewall.NewFirewall(firewall.ShellexProvider)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = fw.Init(a.Helper.Executor, a.store, a.networkConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err1 := fw.SetEndpoint(netif); err1 != nil {\n\t\tglog.Error(agentError(err))\n\t\treturn agentError(err)\n\t}\n\n\tmetadata := fw.Metadata()\n\tchainNames := metadata[\"chains\"].([]string)\n\tu32filter := metadata[\"u32filter\"]\n\thostAddr := a.networkConfig.RomanaGW()\n\n\t\/\/ Default firewall rules for OpenStack\n\tinboundChain := chainNames[firewall.InputChainIndex]\n\tvar defaultRules []firewall.FirewallRule\n\n\tinboundRule := firewall.NewFirewallRule()\n\tinboundRule.SetBody(fmt.Sprintf(\"%s %s\", inboundChain, \"-m comment --comment DefaultDrop -j DROP\"))\n\tdefaultRules = append(defaultRules, inboundRule)\n\n\tinboundRule = firewall.NewFirewallRule()\n\tinboundRule.SetBody(fmt.Sprintf(\"%s %s\", inboundChain, \"-m state --state ESTABLISHED -j ACCEPT\"))\n\tdefaultRules = append(defaultRules, inboundRule)\n\n\tforwardOutChain := chainNames[firewall.ForwardOutChainIndex]\n\tforwardOutRule := firewall.NewFirewallRule()\n\tforwardOutRule.SetBody(fmt.Sprintf(\"%s %s\", forwardOutChain, \"-m comment --comment Outgoing -j RETURN\"))\n\tdefaultRules = append(defaultRules, forwardOutRule)\n\n\tforwardInChain := chainNames[firewall.ForwardInChainIndex]\n\tforwardInRule := firewall.NewFirewallRule()\n\tforwardInRule.SetBody(fmt.Sprintf(\"%s %s\", forwardInChain, \"-m state --state ESTABLISHED -j ACCEPT\"))\n\tdefaultRules = append(defaultRules, forwardInRule)\n\n\tforwardInRule = firewall.NewFirewallRule()\n\tforwardInRule.SetBody(fmt.Sprintf(\"%s ! -s %s -m u32 --u32 %s %s\", forwardInChain, hostAddr, u32filter, \"-j ACCEPT\"))\n\tdefaultRules = append(defaultRules, forwardInRule)\n\n\tfw.SetDefaultRules(defaultRules)\n\n\tif err := fw.ProvisionEndpoint(); err != nil {\n\t\tglog.Error(agentError(err))\n\t\treturn agentError(err)\n\t}\n\n\tglog.Info(\"All good\", netif)\n\treturn nil\n}\n\nfunc (a Agent) getFirewallType() firewall.Provider {\n\tprovider, ok := a.config.ServiceSpecific[\"firewall_provider\"].(string)\n\tif !ok {\n\t\tpanic(\"Unable to read firewall_provider from config\")\n\t}\n\n\tswitch provider {\n\tcase \"shellex\":\n\t\tglog.Infoln(\"Agent: using ShellexProvider firewall provider\")\n\t\treturn firewall.ShellexProvider\n\tcase \"save-restore\":\n\t\tglog.Infoln(\"Agent: using IPTsaveProvider firewall provider\")\n\t\treturn firewall.IPTsaveProvider\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"Unsupported firewall type value %s, supported values are 'shellex' and 'save-restore'\", provider))\n\t}\n\t\t\n}\n<|endoftext|>"}
{"text":"<commit_before>package broker\n\nimport (\n\t\"fmt\"\n\t\"github.com\/siddontang\/golib\/log\"\n\t\"github.com\/siddontang\/moonmq\/proto\"\n\t\"net\"\n\t\"runtime\"\n\t\"sync\"\n\t\"time\"\n)\n\ntype conn struct {\n\tsync.Mutex\n\n\tapp *App\n\n\tc net.Conn\n\n\tdecoder *proto.Decoder\n\n\tlastUpdate int64\n\n\thandshaked bool\n\n\troutes map[string][]string\n}\n\nfunc newConn(app *App, co net.Conn) *conn {\n\tc := new(conn)\n\n\tc.app = app\n\tc.c = co\n\n\tc.handshaked = false\n\n\tc.decoder = proto.NewDecoder(co)\n\n\tc.checkKeepAlive()\n\n\tc.routes = make(map[string][]string)\n\n\treturn c\n}\n\nfunc (c *conn) run() {\n\tc.onRead()\n}\n\nfunc (c *conn) onRead() {\n\tdefer func() {\n\t\tif err := recover(); err != nil {\n\t\t\tbuf := make([]byte, 1024)\n\t\t\tbuf = buf[:runtime.Stack(buf, false)]\n\t\t\tlog.Fatal(\"crash %v:%v\", err, buf)\n\t\t}\n\n\t\tc.c.Close()\n\n\t}()\n\n\tfor {\n\t\tp, err := c.decoder.DecodeProto()\n\t\tif err != nil {\n\t\t\tlog.Info(\"on read error %v\", err)\n\t\t\treturn\n\t\t}\n\n\t\tif p.Method == proto.Handshake {\n\t\t\terr = c.handleHandshake(p)\n\t\t} else {\n\t\t\tif !c.handshaked {\n\t\t\t\terr = fmt.Errorf(\"must handshake first\")\n\t\t\t} else {\n\t\t\t\tswitch p.Method {\n\t\t\t\tcase proto.Publish:\n\t\t\t\t\terr = c.handlePublish(p)\n\t\t\t\tcase proto.Bind:\n\t\t\t\tcase proto.Unbind:\n\t\t\t\tcase proto.Ack:\n\t\t\t\t\terr = c.handleAck(p)\n\t\t\t\tcase proto.Heartbeat:\n\t\t\t\t\tc.lastUpdate = time.Now().Unix()\n\t\t\t\tdefault:\n\t\t\t\t\tlog.Info(\"invalid proto method %d\", p.Method)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif err != nil {\n\t\t\tc.writeError(err)\n\t\t}\n\t}\n}\n\nfunc (c *conn) handleHandshake(p *proto.Proto) error {\n\t\/\/later check authorization\n\n\trp := proto.NewProto(proto.Handshake_OK, nil, nil)\n\tc.writeProto(rp)\n\n\tc.handshaked = true\n\n\treturn nil\n}\n\nfunc (c *conn) writeError(err error) {\n\tvar p *proto.Proto\n\tif pe, ok := err.(*proto.ProtoError); ok {\n\t\tp = pe.P\n\t} else {\n\t\tpe = proto.NewProtoError(500, err.Error())\n\t\tp = pe.P\n\t}\n\n\tc.writeProto(p)\n}\n\nfunc (c *conn) protoError(code int, message string) error {\n\treturn proto.NewProtoError(code, message)\n}\n\nfunc (c *conn) writeProto(p *proto.Proto) error {\n\tbuf, err := proto.Marshal(p)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar n int\n\tc.Lock()\n\tn, err = c.c.Write(buf)\n\tc.Unlock()\n\n\tif err != nil {\n\t\treturn err\n\t} else if n != len(buf) {\n\t\treturn fmt.Errorf(\"write incomplete, %d less than %d\", n, len(buf))\n\t} else {\n\t\treturn nil\n\t}\n}\n\nfunc (c *conn) checkKeepAlive() {\n\tvar f func()\n\tf = func() {\n\t\tif time.Now().Unix()-c.lastUpdate > int64(1.5*float32(c.app.cfg.KeepAlive)) {\n\t\t\tlog.Info(\"keepalive timeout\")\n\t\t\tc.c.Close()\n\t\t\treturn\n\t\t} else {\n\t\t\tc.app.wheel.AddTask(time.Duration(c.app.cfg.KeepAlive), f)\n\t\t}\n\t}\n\n\tc.app.wheel.AddTask(time.Duration(c.app.cfg.KeepAlive), f)\n}\n<commit_msg>close after write error<commit_after>package broker\n\nimport (\n\t\"fmt\"\n\t\"github.com\/siddontang\/golib\/log\"\n\t\"github.com\/siddontang\/moonmq\/proto\"\n\t\"net\"\n\t\"runtime\"\n\t\"sync\"\n\t\"time\"\n)\n\ntype conn struct {\n\tsync.Mutex\n\n\tapp *App\n\n\tc net.Conn\n\n\tdecoder *proto.Decoder\n\n\tlastUpdate int64\n\n\thandshaked bool\n\n\troutes map[string][]string\n}\n\nfunc newConn(app *App, co net.Conn) *conn {\n\tc := new(conn)\n\n\tc.app = app\n\tc.c = co\n\n\tc.handshaked = false\n\n\tc.decoder = proto.NewDecoder(co)\n\n\tc.checkKeepAlive()\n\n\tc.routes = make(map[string][]string)\n\n\treturn c\n}\n\nfunc (c *conn) run() {\n\tc.onRead()\n}\n\nfunc (c *conn) onRead() {\n\tdefer func() {\n\t\tif err := recover(); err != nil {\n\t\t\tbuf := make([]byte, 1024)\n\t\t\tbuf = buf[:runtime.Stack(buf, false)]\n\t\t\tlog.Fatal(\"crash %v:%v\", err, buf)\n\t\t}\n\n\t\tc.c.Close()\n\n\t}()\n\n\tfor {\n\t\tp, err := c.decoder.DecodeProto()\n\t\tif err != nil {\n\t\t\tlog.Info(\"on read error %v\", err)\n\t\t\treturn\n\t\t}\n\n\t\tif p.Method == proto.Handshake {\n\t\t\terr = c.handleHandshake(p)\n\t\t} else {\n\t\t\tif !c.handshaked {\n\t\t\t\terr = fmt.Errorf(\"must handshake first\")\n\t\t\t} else {\n\t\t\t\tswitch p.Method {\n\t\t\t\tcase proto.Publish:\n\t\t\t\t\terr = c.handlePublish(p)\n\t\t\t\tcase proto.Bind:\n\t\t\t\tcase proto.Unbind:\n\t\t\t\tcase proto.Ack:\n\t\t\t\t\terr = c.handleAck(p)\n\t\t\t\tcase proto.Heartbeat:\n\t\t\t\t\tc.lastUpdate = time.Now().Unix()\n\t\t\t\tdefault:\n\t\t\t\t\tlog.Info(\"invalid proto method %d\", p.Method)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif err != nil {\n\t\t\tc.writeError(err)\n\t\t}\n\t}\n}\n\nfunc (c *conn) handleHandshake(p *proto.Proto) error {\n\t\/\/later check authorization\n\n\trp := proto.NewProto(proto.Handshake_OK, nil, nil)\n\tc.writeProto(rp)\n\n\tc.handshaked = true\n\n\treturn nil\n}\n\nfunc (c *conn) writeError(err error) {\n\tvar p *proto.Proto\n\tif pe, ok := err.(*proto.ProtoError); ok {\n\t\tp = pe.P\n\t} else {\n\t\tpe = proto.NewProtoError(500, err.Error())\n\t\tp = pe.P\n\t}\n\n\tc.writeProto(p)\n}\n\nfunc (c *conn) protoError(code int, message string) error {\n\treturn proto.NewProtoError(code, message)\n}\n\nfunc (c *conn) writeProto(p *proto.Proto) error {\n\tbuf, err := proto.Marshal(p)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar n int\n\tc.Lock()\n\tn, err = c.c.Write(buf)\n\tc.Unlock()\n\n\tif err != nil {\n\t\tc.c.Close()\n\t\treturn err\n\t} else if n != len(buf) {\n\t\tc.c.Close()\n\t\treturn fmt.Errorf(\"write incomplete, %d less than %d\", n, len(buf))\n\t} else {\n\t\treturn nil\n\t}\n}\n\nfunc (c *conn) checkKeepAlive() {\n\tvar f func()\n\tf = func() {\n\t\tif time.Now().Unix()-c.lastUpdate > int64(1.5*float32(c.app.cfg.KeepAlive)) {\n\t\t\tlog.Info(\"keepalive timeout\")\n\t\t\tc.c.Close()\n\t\t\treturn\n\t\t} else {\n\t\t\tc.app.wheel.AddTask(time.Duration(c.app.cfg.KeepAlive), f)\n\t\t}\n\t}\n\n\tc.app.wheel.AddTask(time.Duration(c.app.cfg.KeepAlive), f)\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>08ddfa28-2e55-11e5-9284-b827eb9e62be<commit_after><|endoftext|>"}
{"text":"<commit_before>package lib\n\nimport (\n\t\"crypto\/tls\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strings\"\n\n\t\"github.com\/docker\/docker\/pkg\/sockets\"\n\t\"github.com\/docker\/docker\/pkg\/tlsconfig\"\n)\n\n\/\/ Client is the API client that performs all operations\n\/\/ against a docker server.\ntype Client struct {\n\t\/\/ proto holds the client protocol i.e. unix.\n\tproto string\n\t\/\/ addr holds the client address.\n\taddr string\n\t\/\/ basePath holds the path to prepend to the requests\n\tbasePath string\n\t\/\/ scheme holds the scheme of the client i.e. https.\n\tscheme string\n\t\/\/ tlsConfig holds the tls configuration to use in hijacked requests.\n\ttlsConfig *tls.Config\n\t\/\/ httpClient holds the client transport instance. Exported to keep the old code running.\n\thttpClient *http.Client\n\t\/\/ version of the server to talk to.\n\tversion string\n\t\/\/ custom http headers configured by users\n\tcustomHTTPHeaders map[string]string\n}\n\n\/\/ NewClient initializes a new API client for the given host and API version.\n\/\/ It won't send any version information if the version number is empty.\n\/\/ It uses the tlsOptions to decide whether to use a secure connection or not.\n\/\/ It also initializes the custom http headers to add to each request.\nfunc NewClient(host string, version string, tlsOptions *tlsconfig.Options, httpHeaders map[string]string) (*Client, error) {\n\tvar (\n\t\tbasePath       string\n\t\ttlsConfig      *tls.Config\n\t\tscheme         = \"http\"\n\t\tprotoAddrParts = strings.SplitN(host, \":\/\/\", 2)\n\t\tproto, addr    = protoAddrParts[0], protoAddrParts[1]\n\t)\n\n\tif proto == \"tcp\" {\n\t\tparsed, err := url.Parse(\"tcp:\/\/\" + addr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\taddr = parsed.Host\n\t\tbasePath = parsed.Path\n\t}\n\n\tif tlsOptions != nil {\n\t\tscheme = \"https\"\n\t\tvar err error\n\t\ttlsConfig, err = tlsconfig.Client(*tlsOptions)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t\/\/ The transport is created here for reuse during the client session.\n\ttransport := &http.Transport{\n\t\tTLSClientConfig: tlsConfig,\n\t}\n\tsockets.ConfigureTCPTransport(transport, proto, addr)\n\n\treturn &Client{\n\t\tproto:             proto,\n\t\taddr:              addr,\n\t\tbasePath:          basePath,\n\t\tscheme:            scheme,\n\t\ttlsConfig:         tlsConfig,\n\t\thttpClient:        &http.Client{Transport: transport},\n\t\tversion:           version,\n\t\tcustomHTTPHeaders: httpHeaders,\n\t}, nil\n}\n\n\/\/ getAPIPath returns the versioned request path to call the api.\n\/\/ It appends the query parameters to the path if they are not empty.\nfunc (cli *Client) getAPIPath(p string, query url.Values) string {\n\tvar apiPath string\n\tif cli.version != \"\" {\n\t\tv := strings.TrimPrefix(cli.version, \"v\")\n\t\tapiPath = fmt.Sprintf(\"%s\/v%s%s\", cli.basePath, v, p)\n\t} else {\n\t\tapiPath = fmt.Sprintf(\"%s%s\", cli.basePath, p)\n\t}\n\tif len(query) > 0 {\n\t\tapiPath += \"?\" + query.Encode()\n\t}\n\treturn apiPath\n}\n<commit_msg>Add a DOCKER_API_VERSION env var<commit_after>package lib\n\nimport (\n\t\"crypto\/tls\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strings\"\n\n\t\"github.com\/docker\/docker\/pkg\/sockets\"\n\t\"github.com\/docker\/docker\/pkg\/tlsconfig\"\n)\n\n\/\/ Client is the API client that performs all operations\n\/\/ against a docker server.\ntype Client struct {\n\t\/\/ proto holds the client protocol i.e. unix.\n\tproto string\n\t\/\/ addr holds the client address.\n\taddr string\n\t\/\/ basePath holds the path to prepend to the requests\n\tbasePath string\n\t\/\/ scheme holds the scheme of the client i.e. https.\n\tscheme string\n\t\/\/ tlsConfig holds the tls configuration to use in hijacked requests.\n\ttlsConfig *tls.Config\n\t\/\/ httpClient holds the client transport instance. Exported to keep the old code running.\n\thttpClient *http.Client\n\t\/\/ version of the server to talk to.\n\tversion string\n\t\/\/ custom http headers configured by users\n\tcustomHTTPHeaders map[string]string\n}\n\n\/\/ NewClient initializes a new API client for the given host and API version.\n\/\/ It won't send any version information if the version number is empty.\n\/\/ It uses the tlsOptions to decide whether to use a secure connection or not.\n\/\/ It also initializes the custom http headers to add to each request.\nfunc NewClient(host string, version string, tlsOptions *tlsconfig.Options, httpHeaders map[string]string) (*Client, error) {\n\tvar (\n\t\tbasePath       string\n\t\ttlsConfig      *tls.Config\n\t\tscheme         = \"http\"\n\t\tprotoAddrParts = strings.SplitN(host, \":\/\/\", 2)\n\t\tproto, addr    = protoAddrParts[0], protoAddrParts[1]\n\t)\n\n\tif proto == \"tcp\" {\n\t\tparsed, err := url.Parse(\"tcp:\/\/\" + addr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\taddr = parsed.Host\n\t\tbasePath = parsed.Path\n\t}\n\n\tif tlsOptions != nil {\n\t\tscheme = \"https\"\n\t\tvar err error\n\t\ttlsConfig, err = tlsconfig.Client(*tlsOptions)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t\/\/ The transport is created here for reuse during the client session.\n\ttransport := &http.Transport{\n\t\tTLSClientConfig: tlsConfig,\n\t}\n\tsockets.ConfigureTCPTransport(transport, proto, addr)\n\n\treturn &Client{\n\t\tproto:             proto,\n\t\taddr:              addr,\n\t\tbasePath:          basePath,\n\t\tscheme:            scheme,\n\t\ttlsConfig:         tlsConfig,\n\t\thttpClient:        &http.Client{Transport: transport},\n\t\tversion:           version,\n\t\tcustomHTTPHeaders: httpHeaders,\n\t}, nil\n}\n\n\/\/ getAPIPath returns the versioned request path to call the api.\n\/\/ It appends the query parameters to the path if they are not empty.\nfunc (cli *Client) getAPIPath(p string, query url.Values) string {\n\tvar apiPath string\n\tif cli.version != \"\" {\n\t\tv := strings.TrimPrefix(cli.version, \"v\")\n\t\tapiPath = fmt.Sprintf(\"%s\/v%s%s\", cli.basePath, v, p)\n\t} else {\n\t\tapiPath = fmt.Sprintf(\"%s%s\", cli.basePath, p)\n\t}\n\tif len(query) > 0 {\n\t\tapiPath += \"?\" + query.Encode()\n\t}\n\treturn apiPath\n}\n\n\/\/ ClientVersion returns the version string associated with this\n\/\/ instance of the Client. Note that this value can be changed\n\/\/ via the DOCKER_API_VERSION env var.\nfunc (cli *Client) ClientVersion() string {\n\treturn cli.version\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2017 Microsoft. All rights reserved.\n\/\/ MIT License\n\npackage dockerclient\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"os\/exec\"\n\n\t\"github.com\/Azure\/azure-container-networking\/cns\/imdsclient\"\n\t\"github.com\/Azure\/azure-container-networking\/log\"\n)\n\nconst (\n\tdefaultDockerConnectionURL = \"http:\/\/127.0.0.1:2375\"\n\tdefaultIpamPlugin          = \"azure-vnet\"\n\tnetworkMode                = \"com.microsoft.azure.network.mode\"\n\tbridgeMode                 = \"bridge\"\n)\n\n\/\/ DockerClient specifies a client to connect to docker.\ntype DockerClient struct {\n\tconnectionURL string\n\timdsClient    *imdsclient.ImdsClient\n}\n\nfunc executeShellCommand(command string) error {\n\tlog.Debugf(\"[ebtables] %s\", command)\n\tcmd := exec.Command(\"sh\", \"-c\", command)\n\terr := cmd.Start()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn cmd.Wait()\n}\n\n\/\/ NewDockerClient create a new docker client.\nfunc NewDockerClient(url string) (*DockerClient, error) {\n\treturn &DockerClient{\n\t\tconnectionURL: url,\n\t\timdsClient:    &imdsclient.ImdsClient{},\n\t}, nil\n}\n\n\/\/ NewDefaultDockerClient create a new docker client.\nfunc NewDefaultDockerClient(imdsClient *imdsclient.ImdsClient) (*DockerClient, error) {\n\treturn &DockerClient{\n\t\tconnectionURL: defaultDockerConnectionURL,\n\t\timdsClient:    imdsClient,\n\t}, nil\n}\n\n\/\/ NetworkExists tries to retrieve a network from docker (if it exists).\nfunc (dockerClient *DockerClient) NetworkExists(networkName string) error {\n\tlog.Printf(\"[Azure CNS] NetworkExists\")\n\n\tres, err := http.Get(\n\t\tdockerClient.connectionURL + inspectNetworkPath + networkName)\n\n\tif err != nil {\n\t\tlog.Printf(\"[Azure CNS] Error received from http Post for docker network inspect %v %v\", networkName, err.Error())\n\t\treturn err\n\t}\n\n\t\/\/ network exists\n\tif res.StatusCode == 200 {\n\t\tlog.Debugf(\"[Azure CNS] Network with name %v already exists. Docker return code: %v\", networkName, res.StatusCode)\n\t\treturn nil\n\t}\n\n\t\/\/ network not found\n\tif res.StatusCode == 404 {\n\t\tlog.Debugf(\"[Azure CNS] Network with name %v does not exist. Docker return code: %v\", networkName, res.StatusCode)\n\t\treturn fmt.Errorf(\"Network not found\")\n\t}\n\n\treturn fmt.Errorf(\"Unknown return code from docker inspect %d\", res.StatusCode)\n}\n\n\/\/ CreateNetwork creates a network using docker network create.\nfunc (dockerClient *DockerClient) CreateNetwork(networkName string, options map[string]interface{}) error {\n\tlog.Printf(\"[Azure CNS] CreateNetwork\")\n\n\tenableSnat := true\n\n\tprimaryNic, err := dockerClient.imdsClient.GetPrimaryInterfaceInfoFromHost()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconfig := &Config{\n\t\tSubnet: primaryNic.Subnet,\n\t}\n\n\tconfigs := make([]Config, 1)\n\tconfigs[0] = *config\n\tipamConfig := &IPAM{\n\t\tDriver: defaultIpamPlugin,\n\t\tConfig: configs,\n\t}\n\n\tnetConfig := &NetworkConfiguration{\n\t\tName:     networkName,\n\t\tDriver:   defaultNetworkPlugin,\n\t\tIPAM:     *ipamConfig,\n\t\tInternal: true,\n\t}\n\n\tif options != nil {\n\t\tif _, ok := options[OptDisableSnat]; ok {\n\t\t\tenableSnat = false\n\t\t}\n\t}\n\n\tif enableSnat {\n\t\tnetConfig.Options = make(map[string]interface{})\n\t\tnetConfig.Options[networkMode] = bridgeMode\n\t}\n\n\tlog.Printf(\"[Azure CNS] Going to create network with config: %+v\", netConfig)\n\n\tnetConfigJSON := new(bytes.Buffer)\n\terr = json.NewEncoder(netConfigJSON).Encode(netConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tres, err := http.Post(\n\t\tdockerClient.connectionURL+createNetworkPath,\n\t\t\"application\/json; charset=utf-8\",\n\t\tnetConfigJSON)\n\n\tif err != nil {\n\t\tlog.Printf(\"[Azure CNS] Error received from http Post for docker network create %v\", networkName)\n\t\treturn err\n\t}\n\tif res.StatusCode != 201 {\n\t\tvar createNetworkResponse DockerErrorResponse\n\t\terr = json.NewDecoder(res.Body).Decode(&createNetworkResponse)\n\t\tvar ermsg string\n\t\termsg = \"\"\n\t\tif err != nil {\n\t\t\termsg = err.Error()\n\t\t}\n\t\treturn fmt.Errorf(\"[Azure CNS] Create docker network failed with error code %v - %v - %v\",\n\t\t\tres.StatusCode, createNetworkResponse.message, ermsg)\n\t}\n\n\tif enableSnat {\n\t\tcmd := fmt.Sprintf(\"iptables -t nat -A POSTROUTING -m iprange ! --dst-range 168.63.129.16 -m addrtype ! --dst-type local ! -d %v -j MASQUERADE\",\n\t\t\tprimaryNic.Subnet)\n\t\terr = executeShellCommand(cmd)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"SNAT Iptable rule was not set\")\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ DeleteNetwork creates a network using docker network create.\nfunc (dockerClient *DockerClient) DeleteNetwork(networkName string) error {\n\tlog.Printf(\"[Azure CNS] DeleteNetwork\")\n\n\turl := dockerClient.connectionURL + inspectNetworkPath + networkName\n\treq, err := http.NewRequest(\"DELETE\", url, nil)\n\tif err != nil {\n\t\tlog.Printf(\"[Azure CNS] Error received while creating http DELETE request for network delete %v %v\", networkName, err.Error())\n\t\treturn err\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application\/json; charset=utf-8\")\n\tclient := &http.Client{}\n\tres, err := client.Do(req)\n\n\t\/\/ network successfully deleted.\n\tif res.StatusCode == 204 {\n\t\tprimaryNic, err := dockerClient.imdsClient.GetPrimaryInterfaceInfoFromHost()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tcmd := fmt.Sprintf(\"iptables -t nat -D POSTROUTING -m iprange ! --dst-range 168.63.129.16 -m addrtype ! --dst-type local ! -d %v -j MASQUERADE\",\n\t\t\tprimaryNic.Subnet)\n\t\texecuteShellCommand(cmd)\n\t\treturn nil\n\t}\n\n\t\/\/ network not found.\n\tif res.StatusCode == 404 {\n\t\treturn fmt.Errorf(\"[Azure CNS] Network not found %v\", networkName)\n\t}\n\n\treturn fmt.Errorf(\"[Azure CNS] Unknown return code from docker delete network %v: ret = %d\",\n\t\tnetworkName, res.StatusCode)\n}\n<commit_msg>updated log<commit_after>\/\/ Copyright 2017 Microsoft. All rights reserved.\n\/\/ MIT License\n\npackage dockerclient\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"os\/exec\"\n\n\t\"github.com\/Azure\/azure-container-networking\/cns\/imdsclient\"\n\t\"github.com\/Azure\/azure-container-networking\/log\"\n)\n\nconst (\n\tdefaultDockerConnectionURL = \"http:\/\/127.0.0.1:2375\"\n\tdefaultIpamPlugin          = \"azure-vnet\"\n\tnetworkMode                = \"com.microsoft.azure.network.mode\"\n\tbridgeMode                 = \"bridge\"\n)\n\n\/\/ DockerClient specifies a client to connect to docker.\ntype DockerClient struct {\n\tconnectionURL string\n\timdsClient    *imdsclient.ImdsClient\n}\n\nfunc executeShellCommand(command string) error {\n\tlog.Debugf(\"[Azure-CNS] %s\", command)\n\tcmd := exec.Command(\"sh\", \"-c\", command)\n\terr := cmd.Start()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn cmd.Wait()\n}\n\n\/\/ NewDockerClient create a new docker client.\nfunc NewDockerClient(url string) (*DockerClient, error) {\n\treturn &DockerClient{\n\t\tconnectionURL: url,\n\t\timdsClient:    &imdsclient.ImdsClient{},\n\t}, nil\n}\n\n\/\/ NewDefaultDockerClient create a new docker client.\nfunc NewDefaultDockerClient(imdsClient *imdsclient.ImdsClient) (*DockerClient, error) {\n\treturn &DockerClient{\n\t\tconnectionURL: defaultDockerConnectionURL,\n\t\timdsClient:    imdsClient,\n\t}, nil\n}\n\n\/\/ NetworkExists tries to retrieve a network from docker (if it exists).\nfunc (dockerClient *DockerClient) NetworkExists(networkName string) error {\n\tlog.Printf(\"[Azure CNS] NetworkExists\")\n\n\tres, err := http.Get(\n\t\tdockerClient.connectionURL + inspectNetworkPath + networkName)\n\n\tif err != nil {\n\t\tlog.Printf(\"[Azure CNS] Error received from http Post for docker network inspect %v %v\", networkName, err.Error())\n\t\treturn err\n\t}\n\n\t\/\/ network exists\n\tif res.StatusCode == 200 {\n\t\tlog.Debugf(\"[Azure CNS] Network with name %v already exists. Docker return code: %v\", networkName, res.StatusCode)\n\t\treturn nil\n\t}\n\n\t\/\/ network not found\n\tif res.StatusCode == 404 {\n\t\tlog.Debugf(\"[Azure CNS] Network with name %v does not exist. Docker return code: %v\", networkName, res.StatusCode)\n\t\treturn fmt.Errorf(\"Network not found\")\n\t}\n\n\treturn fmt.Errorf(\"Unknown return code from docker inspect %d\", res.StatusCode)\n}\n\n\/\/ CreateNetwork creates a network using docker network create.\nfunc (dockerClient *DockerClient) CreateNetwork(networkName string, options map[string]interface{}) error {\n\tlog.Printf(\"[Azure CNS] CreateNetwork\")\n\n\tenableSnat := true\n\n\tprimaryNic, err := dockerClient.imdsClient.GetPrimaryInterfaceInfoFromHost()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconfig := &Config{\n\t\tSubnet: primaryNic.Subnet,\n\t}\n\n\tconfigs := make([]Config, 1)\n\tconfigs[0] = *config\n\tipamConfig := &IPAM{\n\t\tDriver: defaultIpamPlugin,\n\t\tConfig: configs,\n\t}\n\n\tnetConfig := &NetworkConfiguration{\n\t\tName:     networkName,\n\t\tDriver:   defaultNetworkPlugin,\n\t\tIPAM:     *ipamConfig,\n\t\tInternal: true,\n\t}\n\n\tif options != nil {\n\t\tif _, ok := options[OptDisableSnat]; ok {\n\t\t\tenableSnat = false\n\t\t}\n\t}\n\n\tif enableSnat {\n\t\tnetConfig.Options = make(map[string]interface{})\n\t\tnetConfig.Options[networkMode] = bridgeMode\n\t}\n\n\tlog.Printf(\"[Azure CNS] Going to create network with config: %+v\", netConfig)\n\n\tnetConfigJSON := new(bytes.Buffer)\n\terr = json.NewEncoder(netConfigJSON).Encode(netConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tres, err := http.Post(\n\t\tdockerClient.connectionURL+createNetworkPath,\n\t\t\"application\/json; charset=utf-8\",\n\t\tnetConfigJSON)\n\n\tif err != nil {\n\t\tlog.Printf(\"[Azure CNS] Error received from http Post for docker network create %v\", networkName)\n\t\treturn err\n\t}\n\tif res.StatusCode != 201 {\n\t\tvar createNetworkResponse DockerErrorResponse\n\t\terr = json.NewDecoder(res.Body).Decode(&createNetworkResponse)\n\t\tvar ermsg string\n\t\termsg = \"\"\n\t\tif err != nil {\n\t\t\termsg = err.Error()\n\t\t}\n\t\treturn fmt.Errorf(\"[Azure CNS] Create docker network failed with error code %v - %v - %v\",\n\t\t\tres.StatusCode, createNetworkResponse.message, ermsg)\n\t}\n\n\tif enableSnat {\n\t\tcmd := fmt.Sprintf(\"iptables -t nat -A POSTROUTING -m iprange ! --dst-range 168.63.129.16 -m addrtype ! --dst-type local ! -d %v -j MASQUERADE\",\n\t\t\tprimaryNic.Subnet)\n\t\terr = executeShellCommand(cmd)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"SNAT Iptable rule was not set\")\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ DeleteNetwork creates a network using docker network create.\nfunc (dockerClient *DockerClient) DeleteNetwork(networkName string) error {\n\tlog.Printf(\"[Azure CNS] DeleteNetwork\")\n\n\turl := dockerClient.connectionURL + inspectNetworkPath + networkName\n\treq, err := http.NewRequest(\"DELETE\", url, nil)\n\tif err != nil {\n\t\tlog.Printf(\"[Azure CNS] Error received while creating http DELETE request for network delete %v %v\", networkName, err.Error())\n\t\treturn err\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application\/json; charset=utf-8\")\n\tclient := &http.Client{}\n\tres, err := client.Do(req)\n\n\t\/\/ network successfully deleted.\n\tif res.StatusCode == 204 {\n\t\tprimaryNic, err := dockerClient.imdsClient.GetPrimaryInterfaceInfoFromHost()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tcmd := fmt.Sprintf(\"iptables -t nat -D POSTROUTING -m iprange ! --dst-range 168.63.129.16 -m addrtype ! --dst-type local ! -d %v -j MASQUERADE\",\n\t\t\tprimaryNic.Subnet)\n\t\texecuteShellCommand(cmd)\n\t\treturn nil\n\t}\n\n\t\/\/ network not found.\n\tif res.StatusCode == 404 {\n\t\treturn fmt.Errorf(\"[Azure CNS] Network not found %v\", networkName)\n\t}\n\n\treturn fmt.Errorf(\"[Azure CNS] Unknown return code from docker delete network %v: ret = %d\",\n\t\tnetworkName, res.StatusCode)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright Piero de Salvia.\n\/\/ All Rights Reserved\n\n\/*\nmoved test to this package because of https:\/\/github.com\/golang\/go\/issues\/17928\n*\/\npackage dynaroutes_integration\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/pierods\/dynaroutes\"\n)\n\nvar testDataDir string\n\nfunc init() {\n\n\tgoPath := os.Getenv(\"GOPATH\")\n\ttestDataDir = goPath + \"\/src\/github.com\/pierods\/dynaroutes\/testdata\"\n}\n\nfunc TestHeaders(t *testing.T) {\n\n\tclient := http.Client{}\n\n\treq, err := http.NewRequest(\"GET\", \"http:\/\/localhost:30000\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treq.Header.Add(\"Must\", \"gothrough\")\n\treq.Header.Add(\"This\", \"too\")\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif resp.Header.Get(\"Must\") != \"gothrough\" || resp.Header.Get(\"This\") != \"too\" {\n\t\tt.Fatal(\"Should be able to carry headers through\")\n\t}\n}\n\nfunc TestBody(t *testing.T) {\n\n\tclient := http.Client{}\n\n\tbody := \"Body\"\n\treq, err := http.NewRequest(\"GET\", \"http:\/\/localhost:30000\", strings.NewReader(body))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tbuffer := new(bytes.Buffer)\n\tio.Copy(buffer, resp.Body)\n\tresponseBody := buffer.String()\n\tt.Log(body)\n\n\tif responseBody != body+\" - filtered\" {\n\t\tt.Fatal(\"Should be able to carry body through and filter it\")\n\t}\n}\n\nfunc TestTimeouts(t *testing.T) {\n\n\tclient := http.Client{}\n\n\treq, err := http.NewRequest(\"GET\", \"http:\/\/localhost:30000\/timeout\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tresp, err := client.Do(req)\n\tif resp.StatusCode == 200 {\n\t\tt.Fatal(\"Should err out on a timeout\")\n\t}\n\n\tclient = http.Client{}\n\n\treq, err = http.NewRequest(\"GET\", \"http:\/\/localhost:30000\/timeoutplugin\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tresp, err = client.Do(req)\n\tif resp.StatusCode == 200 {\n\t\tt.Fatal(\"Should err out on a timeout\")\n\t}\n\n}\n\nfunc TestMain(m *testing.M) {\n\n\tlistener, err := net.Listen(\"tcp\", \":50000\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\tserver := http.Server{\n\t\tHandler: &EchoHandler{},\n\t}\n\n\tgo func() {\n\t\tif err := server.Serve(listener); err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tos.Exit(1)\n\t\t}\n\t}()\n\n\tdefer server.Close()\n\n\trouter, err := dynaroutes.NewRouterF(\"localhost\", 30000, 5*time.Second, 5*time.Second, testDataDir, \"localhost\", 31000)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\tgo func() {\n\t\trouter.Start()\n\t}()\n\n\tdefer router.Shutdown()\n\ttime.Sleep(40 * time.Second)\n\tretCode := m.Run()\n\tos.Exit(retCode)\n\n}\n\ntype EchoHandler struct{}\n\nfunc (e *EchoHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {\n\n\tif strings.Contains(r.URL.String(), \"timeout\") {\n\t\ttime.Sleep(1000 * time.Minute)\n\t\treturn\n\t}\n\tcopyHeader(rw.Header(), r.Header)\n\trw.Header().Set(\"Request URL\", r.URL.String())\n\trw.Header().Set(\"Request method\", r.Method)\n\trw.Header().Set(\"Request Content-Length\", strconv.FormatInt(r.ContentLength, 10))\n\trw.WriteHeader(200)\n\tif r.ContentLength > 0 {\n\t\tdefer r.Body.Close()\n\t\tio.Copy(rw, r.Body)\n\t}\n}\n\nfunc copyHeader(dst, src http.Header) {\n\tfor k, vv := range src {\n\t\tfor _, v := range vv {\n\t\t\tdst.Add(k, v)\n\t\t}\n\t}\n}\n<commit_msg>removed spurious go func in tests<commit_after>\/\/ Copyright Piero de Salvia.\n\/\/ All Rights Reserved\n\n\/*\nmoved test to this package because of https:\/\/github.com\/golang\/go\/issues\/17928\n*\/\npackage dynaroutes_integration\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/pierods\/dynaroutes\"\n)\n\nvar testDataDir string\n\nfunc init() {\n\n\tgoPath := os.Getenv(\"GOPATH\")\n\ttestDataDir = goPath + \"\/src\/github.com\/pierods\/dynaroutes\/testdata\"\n}\n\nfunc TestHeaders(t *testing.T) {\n\n\tclient := http.Client{}\n\n\treq, err := http.NewRequest(\"GET\", \"http:\/\/localhost:30000\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treq.Header.Add(\"Must\", \"gothrough\")\n\treq.Header.Add(\"This\", \"too\")\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif resp.Header.Get(\"Must\") != \"gothrough\" || resp.Header.Get(\"This\") != \"too\" {\n\t\tt.Fatal(\"Should be able to carry headers through\")\n\t}\n}\n\nfunc TestBody(t *testing.T) {\n\n\tclient := http.Client{}\n\n\tbody := \"Body\"\n\treq, err := http.NewRequest(\"GET\", \"http:\/\/localhost:30000\", strings.NewReader(body))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tbuffer := new(bytes.Buffer)\n\tio.Copy(buffer, resp.Body)\n\tresponseBody := buffer.String()\n\tt.Log(body)\n\n\tif responseBody != body+\" - filtered\" {\n\t\tt.Fatal(\"Should be able to carry body through and filter it\")\n\t}\n}\n\nfunc TestTimeouts(t *testing.T) {\n\n\tclient := http.Client{}\n\n\treq, err := http.NewRequest(\"GET\", \"http:\/\/localhost:30000\/timeout\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tresp, err := client.Do(req)\n\tif resp.StatusCode == 200 {\n\t\tt.Fatal(\"Should err out on a timeout\")\n\t}\n\n\tclient = http.Client{}\n\n\treq, err = http.NewRequest(\"GET\", \"http:\/\/localhost:30000\/timeoutplugin\", nil)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tresp, err = client.Do(req)\n\tif resp.StatusCode == 200 {\n\t\tt.Fatal(\"Should err out on a timeout\")\n\t}\n\n}\n\nfunc TestMain(m *testing.M) {\n\n\tlistener, err := net.Listen(\"tcp\", \":50000\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\tserver := http.Server{\n\t\tHandler: &EchoHandler{},\n\t}\n\n\tgo func() {\n\t\tif err := server.Serve(listener); err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tos.Exit(1)\n\t\t}\n\t}()\n\n\tdefer server.Close()\n\n\trouter, err := dynaroutes.NewRouterF(\"localhost\", 30000, 5*time.Second, 5*time.Second, testDataDir, \"localhost\", 31000)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\tgo router.Start()\n\n\tdefer router.Shutdown()\n\ttime.Sleep(50 * time.Second)\n\tretCode := m.Run()\n\tos.Exit(retCode)\n\n}\n\ntype EchoHandler struct{}\n\nfunc (e *EchoHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {\n\n\tif strings.Contains(r.URL.String(), \"timeout\") {\n\t\ttime.Sleep(1000 * time.Minute)\n\t\treturn\n\t}\n\tcopyHeader(rw.Header(), r.Header)\n\trw.Header().Set(\"Request URL\", r.URL.String())\n\trw.Header().Set(\"Request method\", r.Method)\n\trw.Header().Set(\"Request Content-Length\", strconv.FormatInt(r.ContentLength, 10))\n\trw.WriteHeader(200)\n\tif r.ContentLength > 0 {\n\t\tdefer r.Body.Close()\n\t\tio.Copy(rw, r.Body)\n\t}\n}\n\nfunc copyHeader(dst, src http.Header) {\n\tfor k, vv := range src {\n\t\tfor _, v := range vv {\n\t\t\tdst.Add(k, v)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package sphere\n\nimport \"errors\"\n\nconst (\n\t\/\/ BrokerErrorOverrideOnSubscribe to warn use to override OnSubsribe function\n\tBrokerErrorOverrideOnSubscribe = \"please override OnSubscribe\"\n\t\/\/ BrokerErrorOverrideOnUnsubscribe to warn use to override OnUnsubscribe function\n\tBrokerErrorOverrideOnUnsubscribe = \"please override OnUnsubscribe\"\n\t\/\/ BrokerErrorOverrideOnPublish to warn use to override OnPublish function\n\tBrokerErrorOverrideOnPublish = \"please override OnPublish\"\n)\n\n\/\/ Broker allows you to interact directly with Websocket internal data and pub\/sub channels\ntype Broker struct {\n\t\/\/ The broker's id\n\tid string\n\t\/\/ List of channels\n\tchannels map[string]*Channel\n}\n\n\/\/ OnSubscribe when websocket subscribes to a channel\nfunc (broker *Broker) OnSubscribe() error {\n\treturn errors.New(BrokerErrorOverrideOnSubscribe)\n}\n\n\/\/ OnUnsubscribe when websocket unsubscribes from a channel\nfunc (broker *Broker) OnUnsubscribe() error {\n\treturn errors.New(BrokerErrorOverrideOnUnsubscribe)\n}\n\n\/\/ OnPublish when websocket publishes data to a particular channel from the current broker\nfunc (broker *Broker) OnPublish(channel *Channel, data interface{}) error {\n\treturn errors.New(BrokerErrorOverrideOnPublish)\n}\n<commit_msg>create new broker func<commit_after>package sphere\n\nimport \"errors\"\n\nconst (\n\t\/\/ BrokerErrorOverrideOnSubscribe to warn use to override OnSubsribe function\n\tBrokerErrorOverrideOnSubscribe = \"please override OnSubscribe\"\n\t\/\/ BrokerErrorOverrideOnUnsubscribe to warn use to override OnUnsubscribe function\n\tBrokerErrorOverrideOnUnsubscribe = \"please override OnUnsubscribe\"\n\t\/\/ BrokerErrorOverrideOnPublish to warn use to override OnPublish function\n\tBrokerErrorOverrideOnPublish = \"please override OnPublish\"\n)\n\n\/\/ Agent represents Broker instance\ntype Agent interface {\n\tOnSubscribe()   \/\/ => Broker OnSubscribe\n\tOnUnsubscribe() \/\/ => Broker OnUnsubscribe\n\tOnPublish()     \/\/ => Broker OnPublish\n}\n\n\/\/ NewBroker creates a broker instance\nfunc NewBroker() *Broker {\n\treturn &Broker{\n\t\tid:       \"\",\n\t\tchannels: make(map[string]*Channel),\n\t}\n}\n\n\/\/ Broker allows you to interact directly with Websocket internal data and pub\/sub channels\ntype Broker struct {\n\t\/\/ The broker's id\n\tid string\n\t\/\/ List of channels\n\tchannels map[string]*Channel\n}\n\n\/\/ OnSubscribe when websocket subscribes to a channel\nfunc (broker *Broker) OnSubscribe() error {\n\treturn errors.New(BrokerErrorOverrideOnSubscribe)\n}\n\n\/\/ OnUnsubscribe when websocket unsubscribes from a channel\nfunc (broker *Broker) OnUnsubscribe() error {\n\treturn errors.New(BrokerErrorOverrideOnUnsubscribe)\n}\n\n\/\/ OnPublish when websocket publishes data to a particular channel from the current broker\nfunc (broker *Broker) OnPublish(channel *Channel, data interface{}) error {\n\treturn errors.New(BrokerErrorOverrideOnPublish)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 CoreOS, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Package login1 provides integration with the systemd logind API.  See http:\/\/www.freedesktop.org\/wiki\/Software\/systemd\/logind\/\npackage login1\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strconv\"\n\n\t\"github.com\/godbus\/dbus\/v5\"\n)\n\nconst (\n\tdbusDest      = \"org.freedesktop.login1\"\n\tdbusInterface = \"org.freedesktop.login1.Manager\"\n\tdbusPath      = \"\/org\/freedesktop\/login1\"\n)\n\n\/\/ Conn is a connection to systemds dbus endpoint.\ntype Conn struct {\n\tconn   *dbus.Conn\n\tobject dbus.BusObject\n}\n\n\/\/ New establishes a connection to the system bus and authenticates.\nfunc New() (*Conn, error) {\n\tc := new(Conn)\n\n\tif err := c.initConnection(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c, nil\n}\n\n\/\/ Close closes the dbus connection\nfunc (c *Conn) Close() {\n\tif c == nil {\n\t\treturn\n\t}\n\n\tif c.conn != nil {\n\t\tc.conn.Close()\n\t}\n}\n\nfunc (c *Conn) initConnection() error {\n\tvar err error\n\tc.conn, err = dbus.SystemBusPrivate()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Only use EXTERNAL method, and hardcode the uid (not username)\n\t\/\/ to avoid a username lookup (which requires a dynamically linked\n\t\/\/ libc)\n\tmethods := []dbus.Auth{dbus.AuthExternal(strconv.Itoa(os.Getuid()))}\n\n\terr = c.conn.Auth(methods)\n\tif err != nil {\n\t\tc.conn.Close()\n\t\treturn err\n\t}\n\n\terr = c.conn.Hello()\n\tif err != nil {\n\t\tc.conn.Close()\n\t\treturn err\n\t}\n\n\tc.object = c.conn.Object(\"org.freedesktop.login1\", dbus.ObjectPath(dbusPath))\n\n\treturn nil\n}\n\n\/\/ Session object definition.\ntype Session struct {\n\tID   string\n\tUID  uint32\n\tUser string\n\tSeat string\n\tPath dbus.ObjectPath\n}\n\n\/\/ User object definition.\ntype User struct {\n\tUID  uint32\n\tName string\n\tPath dbus.ObjectPath\n}\n\nfunc (s Session) toInterface() []interface{} {\n\treturn []interface{}{s.ID, s.UID, s.User, s.Seat, s.Path}\n}\n\nfunc sessionFromInterfaces(session []interface{}) (*Session, error) {\n\tif len(session) < 5 {\n\t\treturn nil, fmt.Errorf(\"invalid number of session fields: %d\", len(session))\n\t}\n\tid, ok := session[0].(string)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"failed to typecast session field 0 to string\")\n\t}\n\tuid, ok := session[1].(uint32)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"failed to typecast session field 1 to uint32\")\n\t}\n\tuser, ok := session[2].(string)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"failed to typecast session field 2 to string\")\n\t}\n\tseat, ok := session[3].(string)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"failed to typecast session field 2 to string\")\n\t}\n\tpath, ok := session[4].(dbus.ObjectPath)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"failed to typecast session field 4 to ObjectPath\")\n\t}\n\n\tret := Session{ID: id, UID: uid, User: user, Seat: seat, Path: path}\n\treturn &ret, nil\n}\n\nfunc userFromInterfaces(user []interface{}) (*User, error) {\n\tif len(user) < 3 {\n\t\treturn nil, fmt.Errorf(\"invalid number of user fields: %d\", len(user))\n\t}\n\tuid, ok := user[0].(uint32)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"failed to typecast user field 0 to uint32\")\n\t}\n\tname, ok := user[1].(string)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"failed to typecast session field 1 to string\")\n\t}\n\tpath, ok := user[2].(dbus.ObjectPath)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"failed to typecast user field 2 to ObjectPath\")\n\t}\n\n\tret := User{UID: uid, Name: name, Path: path}\n\treturn &ret, nil\n}\n\n\/\/ GetActiveSession may be used to get the session object path for the current active session\nfunc (c *Conn) GetActiveSession() (dbus.ObjectPath, error) {\n\tvar activeSessionPath dbus.ObjectPath\n\tvar seat0Path dbus.ObjectPath\n\tif err := c.object.Call(dbusInterface+\".GetSeat\", 0, \"seat0\").Store(&seat0Path); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tseat0Obj := c.conn.Object(dbusDest, seat0Path)\n\tactiveSession, err := seat0Obj.GetProperty(dbusDest + \".Seat.ActiveSession\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tactiveSessionMap, ok := activeSession.Value().([]interface{})\n\tif !ok || len(activeSessionMap) < 2 {\n\t\treturn \"\", fmt.Errorf(\"failed to typecast active session map\")\n\t}\n\n\tactiveSessionPath, ok = activeSessionMap[1].(dbus.ObjectPath)\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"failed to typecast dbus active session Path\")\n\t}\n\treturn activeSessionPath, nil\n}\n\n\/\/ GetSessionUser may be used to get the user of specific session\nfunc (c *Conn) GetSessionUser(sessionPath dbus.ObjectPath) (*User, error) {\n\tif len(sessionPath) == 0 {\n\t\treturn nil, fmt.Errorf(\"Empty sessionPath\")\n\t}\n\n\tvar user User\n\tactiveSessionObj := c.conn.Object(dbusDest, sessionPath)\n\tsessionUserName, err := activeSessionObj.GetProperty(dbusDest + \".Session.Name\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsessionUser, err := activeSessionObj.GetProperty(dbusDest + \".Session.User\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdbusUser, ok := sessionUser.Value().([]interface{})\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"failed to typecast dbus session user\")\n\t}\n\n\tif len(dbusUser) < 2 {\n\t\treturn nil, fmt.Errorf(\"invalid number of user fields: %d\", len(dbusUser))\n\t}\n\tuid, ok := dbusUser[0].(uint32)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"failed to typecast user field 0 to uint32\")\n\t}\n\tpath, ok := dbusUser[1].(dbus.ObjectPath)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"failed to typecast user field 1 to ObjectPath\")\n\t}\n\n\tuser = User{UID: uid, Name: sessionUserName.String(), Path: path}\n\n\treturn &user, nil\n}\n\n\/\/ GetSessionDisplay may be used to get the display for specific session\nfunc (c *Conn) GetSessionDisplay(sessionPath dbus.ObjectPath) (string, error) {\n\tif len(sessionPath) == 0 {\n\t\treturn \"\", fmt.Errorf(\"Empty sessionPath\")\n\t}\n\tsessionObj := c.conn.Object(dbusDest, sessionPath)\n\tdisplay, err := sessionObj.GetProperty(dbusDest + \".Session.Display\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn display.String(), nil\n}\n\n\/\/ GetSession may be used to get the session object path for the session with the specified ID.\nfunc (c *Conn) GetSession(id string) (dbus.ObjectPath, error) {\n\tvar out interface{}\n\tif err := c.object.Call(dbusInterface+\".GetSession\", 0, id).Store(&out); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tret, ok := out.(dbus.ObjectPath)\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"failed to typecast session to ObjectPath\")\n\t}\n\n\treturn ret, nil\n}\n\n\/\/ ListSessions returns an array with all current sessions.\nfunc (c *Conn) ListSessions() ([]Session, error) {\n\tout := [][]interface{}{}\n\tif err := c.object.Call(dbusInterface+\".ListSessions\", 0).Store(&out); err != nil {\n\t\treturn nil, err\n\t}\n\n\tret := []Session{}\n\tfor _, el := range out {\n\t\tsession, err := sessionFromInterfaces(el)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tret = append(ret, *session)\n\t}\n\treturn ret, nil\n}\n\n\/\/ ListUsers returns an array with all currently logged in users.\nfunc (c *Conn) ListUsers() ([]User, error) {\n\tout := [][]interface{}{}\n\tif err := c.object.Call(dbusInterface+\".ListUsers\", 0).Store(&out); err != nil {\n\t\treturn nil, err\n\t}\n\n\tret := []User{}\n\tfor _, el := range out {\n\t\tuser, err := userFromInterfaces(el)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tret = append(ret, *user)\n\t}\n\treturn ret, nil\n}\n\n\/\/ LockSession asks the session with the specified ID to activate the screen lock.\nfunc (c *Conn) LockSession(id string) {\n\tc.object.Call(dbusInterface+\".LockSession\", 0, id)\n}\n\n\/\/ LockSessions asks all sessions to activate the screen locks. This may be used to lock any access to the machine in one action.\nfunc (c *Conn) LockSessions() {\n\tc.object.Call(dbusInterface+\".LockSessions\", 0)\n}\n\n\/\/ TerminateSession forcibly terminate one specific session.\nfunc (c *Conn) TerminateSession(id string) {\n\tc.object.Call(dbusInterface+\".TerminateSession\", 0, id)\n}\n\n\/\/ TerminateUser forcibly terminates all processes of a user.\nfunc (c *Conn) TerminateUser(uid uint32) {\n\tc.object.Call(dbusInterface+\".TerminateUser\", 0, uid)\n}\n\n\/\/ Reboot asks logind for a reboot optionally asking for auth.\nfunc (c *Conn) Reboot(askForAuth bool) {\n\tc.object.Call(dbusInterface+\".Reboot\", 0, askForAuth)\n}\n\n\/\/ Inhibit takes inhibition lock in logind.\nfunc (c *Conn) Inhibit(what, who, why, mode string) (*os.File, error) {\n\tvar fd dbus.UnixFD\n\n\terr := c.object.Call(dbusInterface+\".Inhibit\", 0, what, who, why, mode).Store(&fd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn os.NewFile(uintptr(fd), \"inhibit\"), nil\n}\n\n\/\/ Subscribe to signals on the logind dbus\nfunc (c *Conn) Subscribe(members ...string) chan *dbus.Signal {\n\tfor _, member := range members {\n\t\tc.conn.BusObject().Call(\"org.freedesktop.DBus.AddMatch\", 0,\n\t\t\tfmt.Sprintf(\"type='signal',interface='org.freedesktop.login1.Manager',member='%s'\", member))\n\t}\n\tch := make(chan *dbus.Signal, 10)\n\tc.conn.Signal(ch)\n\treturn ch\n}\n\n\/\/ PowerOff asks logind for a power off optionally asking for auth.\nfunc (c *Conn) PowerOff(askForAuth bool) {\n\tc.object.Call(dbusInterface+\".PowerOff\", 0, askForAuth)\n}\n<commit_msg>removed quotes from username and display. Made suggested fixes for PR<commit_after>\/\/ Copyright 2015 CoreOS, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Package login1 provides integration with the systemd logind API.  See http:\/\/www.freedesktop.org\/wiki\/Software\/systemd\/logind\/\npackage login1\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/godbus\/dbus\/v5\"\n)\n\nconst (\n\tdbusDest      = \"org.freedesktop.login1\"\n\tdbusInterface = \"org.freedesktop.login1.Manager\"\n\tdbusPath      = \"\/org\/freedesktop\/login1\"\n)\n\n\/\/ Conn is a connection to systemds dbus endpoint.\ntype Conn struct {\n\tconn   *dbus.Conn\n\tobject dbus.BusObject\n}\n\n\/\/ New establishes a connection to the system bus and authenticates.\nfunc New() (*Conn, error) {\n\tc := new(Conn)\n\n\tif err := c.initConnection(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c, nil\n}\n\n\/\/ Close closes the dbus connection\nfunc (c *Conn) Close() {\n\tif c == nil {\n\t\treturn\n\t}\n\n\tif c.conn != nil {\n\t\tc.conn.Close()\n\t}\n}\n\nfunc (c *Conn) initConnection() error {\n\tvar err error\n\tc.conn, err = dbus.SystemBusPrivate()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Only use EXTERNAL method, and hardcode the uid (not username)\n\t\/\/ to avoid a username lookup (which requires a dynamically linked\n\t\/\/ libc)\n\tmethods := []dbus.Auth{dbus.AuthExternal(strconv.Itoa(os.Getuid()))}\n\n\terr = c.conn.Auth(methods)\n\tif err != nil {\n\t\tc.conn.Close()\n\t\treturn err\n\t}\n\n\terr = c.conn.Hello()\n\tif err != nil {\n\t\tc.conn.Close()\n\t\treturn err\n\t}\n\n\tc.object = c.conn.Object(\"org.freedesktop.login1\", dbus.ObjectPath(dbusPath))\n\n\treturn nil\n}\n\n\/\/ Session object definition.\ntype Session struct {\n\tID   string\n\tUID  uint32\n\tUser string\n\tSeat string\n\tPath dbus.ObjectPath\n}\n\n\/\/ User object definition.\ntype User struct {\n\tUID  uint32\n\tName string\n\tPath dbus.ObjectPath\n}\n\nfunc (s Session) toInterface() []interface{} {\n\treturn []interface{}{s.ID, s.UID, s.User, s.Seat, s.Path}\n}\n\nfunc sessionFromInterfaces(session []interface{}) (*Session, error) {\n\tif len(session) < 5 {\n\t\treturn nil, fmt.Errorf(\"invalid number of session fields: %d\", len(session))\n\t}\n\tid, ok := session[0].(string)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"failed to typecast session field 0 to string\")\n\t}\n\tuid, ok := session[1].(uint32)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"failed to typecast session field 1 to uint32\")\n\t}\n\tuser, ok := session[2].(string)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"failed to typecast session field 2 to string\")\n\t}\n\tseat, ok := session[3].(string)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"failed to typecast session field 2 to string\")\n\t}\n\tpath, ok := session[4].(dbus.ObjectPath)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"failed to typecast session field 4 to ObjectPath\")\n\t}\n\n\tret := Session{ID: id, UID: uid, User: user, Seat: seat, Path: path}\n\treturn &ret, nil\n}\n\nfunc userFromInterfaces(user []interface{}) (*User, error) {\n\tif len(user) < 3 {\n\t\treturn nil, fmt.Errorf(\"invalid number of user fields: %d\", len(user))\n\t}\n\tuid, ok := user[0].(uint32)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"failed to typecast user field 0 to uint32\")\n\t}\n\tname, ok := user[1].(string)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"failed to typecast session field 1 to string\")\n\t}\n\tpath, ok := user[2].(dbus.ObjectPath)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"failed to typecast user field 2 to ObjectPath\")\n\t}\n\n\tret := User{UID: uid, Name: name, Path: path}\n\treturn &ret, nil\n}\n\n\/\/ GetActiveSession may be used to get the session object path for the current active session\nfunc (c *Conn) GetActiveSession() (dbus.ObjectPath, error) {\n\tvar seat0Path dbus.ObjectPath\n\tif err := c.object.Call(dbusInterface+\".GetSeat\", 0, \"seat0\").Store(&seat0Path); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tseat0Obj := c.conn.Object(dbusDest, seat0Path)\n\tactiveSession, err := seat0Obj.GetProperty(dbusDest + \".Seat.ActiveSession\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tactiveSessionMap, ok := activeSession.Value().([]interface{})\n\tif !ok || len(activeSessionMap) < 2 {\n\t\treturn \"\", fmt.Errorf(\"failed to typecast active session map\")\n\t}\n\n\tactiveSessionPath, ok := activeSessionMap[1].(dbus.ObjectPath)\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"failed to typecast dbus active session Path\")\n\t}\n\treturn activeSessionPath, nil\n}\n\n\/\/ GetSessionUser may be used to get the user of specific session\nfunc (c *Conn) GetSessionUser(sessionPath dbus.ObjectPath) (*User, error) {\n\tif len(sessionPath) == 0 {\n\t\treturn nil, fmt.Errorf(\"empty sessionPath\")\n\t}\n\n\tactiveSessionObj := c.conn.Object(dbusDest, sessionPath)\n\tsessionUserName, err := activeSessionObj.GetProperty(dbusDest + \".Session.Name\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsessionUser, err := activeSessionObj.GetProperty(dbusDest + \".Session.User\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdbusUser, ok := sessionUser.Value().([]interface{})\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"failed to typecast dbus session user\")\n\t}\n\n\tif len(dbusUser) < 2 {\n\t\treturn nil, fmt.Errorf(\"invalid number of user fields: %d\", len(dbusUser))\n\t}\n\tuid, ok := dbusUser[0].(uint32)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"failed to typecast user field 0 to uint32\")\n\t}\n\tpath, ok := dbusUser[1].(dbus.ObjectPath)\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"failed to typecast user field 1 to ObjectPath\")\n\t}\n\n\tuser := User{UID: uid, Name: strings.Trim(sessionUserName.String(), \"\\\"\"), Path: path}\n\n\treturn &user, nil\n}\n\n\/\/ GetSessionDisplay may be used to get the display for specific session\nfunc (c *Conn) GetSessionDisplay(sessionPath dbus.ObjectPath) (string, error) {\n\tif len(sessionPath) == 0 {\n\t\treturn \"\", fmt.Errorf(\"empty sessionPath\")\n\t}\n\tsessionObj := c.conn.Object(dbusDest, sessionPath)\n\tdisplay, err := sessionObj.GetProperty(dbusDest + \".Session.Display\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn strings.Trim(display.String(), \"\\\"\"), nil\n}\n\n\/\/ GetSession may be used to get the session object path for the session with the specified ID.\nfunc (c *Conn) GetSession(id string) (dbus.ObjectPath, error) {\n\tvar out interface{}\n\tif err := c.object.Call(dbusInterface+\".GetSession\", 0, id).Store(&out); err != nil {\n\t\treturn \"\", err\n\t}\n\n\tret, ok := out.(dbus.ObjectPath)\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"failed to typecast session to ObjectPath\")\n\t}\n\n\treturn ret, nil\n}\n\n\/\/ ListSessions returns an array with all current sessions.\nfunc (c *Conn) ListSessions() ([]Session, error) {\n\tout := [][]interface{}{}\n\tif err := c.object.Call(dbusInterface+\".ListSessions\", 0).Store(&out); err != nil {\n\t\treturn nil, err\n\t}\n\n\tret := []Session{}\n\tfor _, el := range out {\n\t\tsession, err := sessionFromInterfaces(el)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tret = append(ret, *session)\n\t}\n\treturn ret, nil\n}\n\n\/\/ ListUsers returns an array with all currently logged in users.\nfunc (c *Conn) ListUsers() ([]User, error) {\n\tout := [][]interface{}{}\n\tif err := c.object.Call(dbusInterface+\".ListUsers\", 0).Store(&out); err != nil {\n\t\treturn nil, err\n\t}\n\n\tret := []User{}\n\tfor _, el := range out {\n\t\tuser, err := userFromInterfaces(el)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tret = append(ret, *user)\n\t}\n\treturn ret, nil\n}\n\n\/\/ LockSession asks the session with the specified ID to activate the screen lock.\nfunc (c *Conn) LockSession(id string) {\n\tc.object.Call(dbusInterface+\".LockSession\", 0, id)\n}\n\n\/\/ LockSessions asks all sessions to activate the screen locks. This may be used to lock any access to the machine in one action.\nfunc (c *Conn) LockSessions() {\n\tc.object.Call(dbusInterface+\".LockSessions\", 0)\n}\n\n\/\/ TerminateSession forcibly terminate one specific session.\nfunc (c *Conn) TerminateSession(id string) {\n\tc.object.Call(dbusInterface+\".TerminateSession\", 0, id)\n}\n\n\/\/ TerminateUser forcibly terminates all processes of a user.\nfunc (c *Conn) TerminateUser(uid uint32) {\n\tc.object.Call(dbusInterface+\".TerminateUser\", 0, uid)\n}\n\n\/\/ Reboot asks logind for a reboot optionally asking for auth.\nfunc (c *Conn) Reboot(askForAuth bool) {\n\tc.object.Call(dbusInterface+\".Reboot\", 0, askForAuth)\n}\n\n\/\/ Inhibit takes inhibition lock in logind.\nfunc (c *Conn) Inhibit(what, who, why, mode string) (*os.File, error) {\n\tvar fd dbus.UnixFD\n\n\terr := c.object.Call(dbusInterface+\".Inhibit\", 0, what, who, why, mode).Store(&fd)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn os.NewFile(uintptr(fd), \"inhibit\"), nil\n}\n\n\/\/ Subscribe to signals on the logind dbus\nfunc (c *Conn) Subscribe(members ...string) chan *dbus.Signal {\n\tfor _, member := range members {\n\t\tc.conn.BusObject().Call(\"org.freedesktop.DBus.AddMatch\", 0,\n\t\t\tfmt.Sprintf(\"type='signal',interface='org.freedesktop.login1.Manager',member='%s'\", member))\n\t}\n\tch := make(chan *dbus.Signal, 10)\n\tc.conn.Signal(ch)\n\treturn ch\n}\n\n\/\/ PowerOff asks logind for a power off optionally asking for auth.\nfunc (c *Conn) PowerOff(askForAuth bool) {\n\tc.object.Call(dbusInterface+\".PowerOff\", 0, askForAuth)\n}\n<|endoftext|>"}
{"text":"<commit_before>package goridge\n\nimport (\n\t\"io\"\n\t\"sync\"\n)\n\n\/\/ SocketRelay communicates with underlying process using sockets (TPC or Unix).\ntype SocketRelay struct {\n\t\/\/ How many bytes to write\/read at once.\n\tBufferSize uint64\n\n\tmuw sync.Mutex \/\/ concurrent write\n\tmur sync.Mutex \/\/ concurrent read\n\trwc io.ReadWriteCloser\n}\n\n\/\/ NewSocketRelay creates new socket based data relay.\nfunc NewSocketRelay(rwc io.ReadWriteCloser) *SocketRelay {\n\treturn &SocketRelay{BufferSize: BufferSize, rwc: rwc}\n}\n\n\/\/ Send signed (prefixed) data to PHP process.\nfunc (rl *SocketRelay) Send(data []byte, flags byte) (err error) {\n\trl.muw.Lock()\n\tdefer rl.muw.Unlock()\n\n\tprefix := NewPrefix().WithFlags(flags).WithSize(uint64(len(data)))\n\tif _, err := rl.rwc.Write(prefix[:]); err != nil {\n\t\treturn err\n\t}\n\n\tif _, err := rl.rwc.Write(data); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ Receive data from the underlying process and returns associated prefix or error.\nfunc (rl *SocketRelay) Receive() (data []byte, p Prefix, err error) {\n\trl.mur.Lock()\n\tdefer rl.mur.Unlock()\n\n\tif _, err := rl.rwc.Read(p[:]); err != nil {\n\t\treturn nil, p, err\n\t}\n\n\tif !p.HasPayload() {\n\t\treturn nil, p, nil\n\t}\n\n\tleftBytes := p.Size()\n\tdata = make([]byte, 0, leftBytes)\n\tbuffer := make([]byte, min(leftBytes, rl.BufferSize))\n\n\tfor {\n\t\tif n, err := rl.rwc.Read(buffer); err == nil {\n\t\t\tdata = append(data, buffer[:n]...)\n\t\t\tleftBytes -= uint64(n)\n\t\t} else {\n\t\t\treturn nil, p, err\n\t\t}\n\n\t\tif leftBytes == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn\n}\n\n\/\/ Close the connection.\nfunc (rl *SocketRelay) Close() error {\n\trl.muw.Lock()\n\trl.mur.Lock()\n\tdefer rl.muw.Unlock()\n\tdefer rl.mur.Unlock()\n\n\treturn rl.rwc.Close()\n}\n<commit_msg>error handling in receive<commit_after>package goridge\n\nimport (\n\t\"io\"\n\t\"sync\"\n)\n\n\/\/ SocketRelay communicates with underlying process using sockets (TPC or Unix).\ntype SocketRelay struct {\n\t\/\/ How many bytes to write\/read at once.\n\tBufferSize uint64\n\n\tmuw sync.Mutex \/\/ concurrent write\n\tmur sync.Mutex \/\/ concurrent read\n\trwc io.ReadWriteCloser\n}\n\n\/\/ NewSocketRelay creates new socket based data relay.\nfunc NewSocketRelay(rwc io.ReadWriteCloser) *SocketRelay {\n\treturn &SocketRelay{BufferSize: BufferSize, rwc: rwc}\n}\n\n\/\/ Send signed (prefixed) data to PHP process.\nfunc (rl *SocketRelay) Send(data []byte, flags byte) (err error) {\n\trl.muw.Lock()\n\tdefer rl.muw.Unlock()\n\n\tprefix := NewPrefix().WithFlags(flags).WithSize(uint64(len(data)))\n\tif _, err := rl.rwc.Write(prefix[:]); err != nil {\n\t\treturn err\n\t}\n\n\tif _, err := rl.rwc.Write(data); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ Receive data from the underlying process and returns associated prefix or error.\nfunc (rl *SocketRelay) Receive() (data []byte, p Prefix, err error) {\n\trl.mur.Lock()\n\tdefer rl.mur.Unlock()\n\n\tdefer func() {\n\t\tif rErr, ok := recover().(error); ok {\n\t\t\terr = rErr\n\t\t}\n\t}()\n\n\tif _, err := rl.rwc.Read(p[:]); err != nil {\n\t\treturn nil, p, err\n\t}\n\n\tif !p.HasPayload() {\n\t\treturn nil, p, nil\n\t}\n\n\tleftBytes := p.Size()\n\tdata = make([]byte, 0, leftBytes)\n\tbuffer := make([]byte, min(leftBytes, rl.BufferSize))\n\n\tfor {\n\t\tif n, err := rl.rwc.Read(buffer); err == nil {\n\t\t\tdata = append(data, buffer[:n]...)\n\t\t\tleftBytes -= uint64(n)\n\t\t} else {\n\t\t\treturn nil, p, err\n\t\t}\n\n\t\tif leftBytes == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn\n}\n\n\/\/ Close the connection.\nfunc (rl *SocketRelay) Close() error {\n\trl.muw.Lock()\n\trl.mur.Lock()\n\tdefer rl.muw.Unlock()\n\tdefer rl.mur.Unlock()\n\n\treturn rl.rwc.Close()\n}\n<|endoftext|>"}
{"text":"<commit_before>package heartbeat\n\nimport (\n\t\"context\"\n\t\"sync\"\n\t\"time\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t\"github.com\/onsi\/ginkgo\/extensions\/table\"\n\t. \"github.com\/onsi\/gomega\"\n\tv1 \"k8s.io\/api\/core\/v1\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/client-go\/kubernetes\/fake\"\n\n\tvirtv1 \"kubevirt.io\/client-go\/api\/v1\"\n\t\"kubevirt.io\/kubevirt\/pkg\/testutils\"\n\tvirtconfig \"kubevirt.io\/kubevirt\/pkg\/virt-config\"\n\tdevice_manager \"kubevirt.io\/kubevirt\/pkg\/virt-handler\/device-manager\"\n)\n\nconst (\n\tcpu_manager_static_path = \"testdata\/cpu_manager_state_static\"\n\tcpu_manager_none_path   = \"testdata\/cpu_manager_state_none\"\n)\n\nvar _ = Describe(\"Heartbeat\", func() {\n\n\tvar node *v1.Node\n\tvar fakeClient *fake.Clientset\n\n\tBeforeEach(func() {\n\t\tnode = &v1.Node{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: \"mynode\",\n\t\t\t},\n\t\t}\n\t\tfakeClient = fake.NewSimpleClientset(node)\n\t})\n\n\ttable.DescribeTable(\"with cpumanager featuregate should set the node to\", func(deviceController device_manager.DeviceControllerInterface, cpuManagerPaths []string, schedulable string, cpumanager string) {\n\t\theartbeat := NewHeartBeat(fakeClient.CoreV1(), deviceController, config(virtconfig.CPUManager), \"mynode\")\n\t\theartbeat.cpuManagerPaths = cpuManagerPaths\n\t\theartbeat.do()\n\t\tnode, err := fakeClient.CoreV1().Nodes().Get(context.Background(), \"mynode\", metav1.GetOptions{})\n\t\tExpect(err).ToNot(HaveOccurred())\n\t\tExpect(node.Labels).To(HaveKeyWithValue(virtv1.NodeSchedulable, schedulable))\n\t\tExpect(node.Labels).To(HaveKeyWithValue(virtv1.CPUManager, cpumanager))\n\t},\n\t\ttable.Entry(\"not schedulable and no cpu manager with no cpu manager file and device plugins are not initialized\",\n\t\t\tdeviceController(false),\n\t\t\t[]string{\"non\/existent\/cpumanager\/statefile\"},\n\t\t\t\"false\",\n\t\t\t\"false\",\n\t\t),\n\t\ttable.Entry(\"schedulable and no cpu manager with no cpu manager file and plugins are not initialized\",\n\t\t\tdeviceController(true),\n\t\t\t[]string{\"non\/existent\/cpumanager\/statefile\"},\n\t\t\t\"true\",\n\t\t\t\"false\",\n\t\t),\n\t\ttable.Entry(\"schedulable and cpu manager with static cpu manager policy configured and device plugins are not initialized\",\n\t\t\tdeviceController(true),\n\t\t\t[]string{\"non\/existent\/cpumanager\/statefile\", cpu_manager_static_path},\n\t\t\t\"true\",\n\t\t\t\"true\",\n\t\t),\n\t\ttable.Entry(\"schedulable and no cpu manager with no cpu manager policy configured and device plugins are not initialized\",\n\t\t\tdeviceController(true),\n\t\t\t[]string{cpu_manager_none_path, \"non\/existent\/cpumanager\/statefile\"},\n\t\t\t\"true\",\n\t\t\t\"false\",\n\t\t),\n\t)\n\n\ttable.DescribeTable(\"without cpumanager featuregate should set the node to\", func(deviceController device_manager.DeviceControllerInterface, schedulable string) {\n\t\theartbeat := NewHeartBeat(fakeClient.CoreV1(), deviceController, config(), \"mynode\")\n\t\theartbeat.do()\n\t\tnode, err := fakeClient.CoreV1().Nodes().Get(context.Background(), \"mynode\", metav1.GetOptions{})\n\t\tExpect(err).ToNot(HaveOccurred())\n\t\tExpect(node.Labels).To(HaveKeyWithValue(virtv1.NodeSchedulable, schedulable))\n\t\tExpect(node.Labels).ToNot(HaveKeyWithValue(virtv1.CPUManager, false))\n\t},\n\t\ttable.Entry(\"not schedulable with no cpumanager label present\",\n\t\t\tdeviceController(false),\n\t\t\t\"false\",\n\t\t),\n\t\ttable.Entry(\"schedulable with no cpumanger label present\",\n\t\t\tdeviceController(true),\n\t\t\t\"true\",\n\t\t),\n\t)\n\n\ttable.DescribeTable(\"without deviceplugin and\", func(deviceController device_manager.DeviceControllerInterface, initiallySchedulable string, finallySchedulable string) {\n\t\theartbeat := NewHeartBeat(fakeClient.CoreV1(), deviceController, config(), \"mynode\")\n\t\theartbeat.devicePluginWaitTimeout = 1 * time.Second\n\t\theartbeat.devicePluginPollIntervall = 10 * time.Millisecond\n\t\tstopChan := make(chan struct{})\n\t\tdone := heartbeat.Run(100*time.Second, stopChan)\n\t\tdefer func() {\n\t\t\tclose(stopChan)\n\t\t\t<-done\n\t\t}()\n\t\tEventually(func() map[string]string {\n\t\t\tnode, err := fakeClient.CoreV1().Nodes().Get(context.Background(), \"mynode\", metav1.GetOptions{})\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\treturn node.Labels\n\t\t}).Should(And(\n\t\t\tHaveKeyWithValue(virtv1.NodeSchedulable, initiallySchedulable),\n\t\t))\n\t\tConsistently(func() map[string]string {\n\t\t\tnode, err := fakeClient.CoreV1().Nodes().Get(context.Background(), \"mynode\", metav1.GetOptions{})\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\treturn node.Labels\n\t\t}, 500*time.Millisecond, 10*time.Millisecond).Should(And(\n\t\t\tHaveKeyWithValue(virtv1.NodeSchedulable, initiallySchedulable),\n\t\t))\n\t\tEventually(func() map[string]string {\n\t\t\tnode, err := fakeClient.CoreV1().Nodes().Get(context.Background(), \"mynode\", metav1.GetOptions{})\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\treturn node.Labels\n\t\t}).Should(And(\n\t\t\tHaveKeyWithValue(virtv1.NodeSchedulable, finallySchedulable),\n\t\t))\n\t\tConsistently(func() map[string]string {\n\t\t\tnode, err := fakeClient.CoreV1().Nodes().Get(context.Background(), \"mynode\", metav1.GetOptions{})\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\treturn node.Labels\n\t\t}, 500*time.Millisecond, 10*time.Millisecond).Should(And(\n\t\t\tHaveKeyWithValue(virtv1.NodeSchedulable, finallySchedulable),\n\t\t))\n\t},\n\t\ttable.Entry(\"not becoming ready, node should be set to unschedulable immediately and stick to it\",\n\t\t\tnewProbeCountingDeviceController(probe{false, 1000}),\n\t\t\t\"false\",\n\t\t\t\"false\",\n\t\t),\n\t\ttable.Entry(\"becoming ready after a few probes, node should be set to unschedulable immediately and switch earlier than one minute\",\n\t\t\tnewProbeCountingDeviceController(probe{false, 100}, probe{true, 100}),\n\t\t\t\"false\",\n\t\t\t\"true\",\n\t\t),\n\t)\n})\n\ntype fakeDeviceController struct {\n\tinitialized bool\n}\n\nfunc (f *fakeDeviceController) Initialized() bool {\n\treturn f.initialized\n}\n\nfunc config(featuregates ...string) *virtconfig.ClusterConfig {\n\tcfg := &virtv1.KubeVirtConfiguration{\n\t\tDeveloperConfiguration: &virtv1.DeveloperConfiguration{\n\t\t\tFeatureGates: featuregates,\n\t\t},\n\t}\n\tclusterConfig, _, _, _ := testutils.NewFakeClusterConfigUsingKVConfig(cfg)\n\treturn clusterConfig\n}\n\nfunc deviceController(initialized bool) device_manager.DeviceControllerInterface {\n\treturn &fakeDeviceController{initialized: initialized}\n}\n\ntype probeCountingDeviceController struct {\n\tprobes []bool\n\tprobed int\n\tlock   *sync.Mutex\n}\n\nfunc (f *probeCountingDeviceController) Initialized() bool {\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\tf.probed++\n\treturn f.probes[f.probed-1]\n}\n\nfunc newProbeCountingDeviceController(probes ...probe) device_manager.DeviceControllerInterface {\n\tvar probeArray []bool\n\tfor _, p := range probes {\n\t\tfor x := 0; x < p.repetitions; x++ {\n\t\t\tprobeArray = append(probeArray, p.value)\n\t\t}\n\t}\n\treturn &probeCountingDeviceController{probes: probeArray, lock: &sync.Mutex{}}\n}\n\ntype probe struct {\n\tvalue       bool\n\trepetitions int\n}\n<commit_msg>Increase device plugin wait timeout<commit_after>package heartbeat\n\nimport (\n\t\"context\"\n\t\"sync\"\n\t\"time\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t\"github.com\/onsi\/ginkgo\/extensions\/table\"\n\t. \"github.com\/onsi\/gomega\"\n\tv1 \"k8s.io\/api\/core\/v1\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/client-go\/kubernetes\/fake\"\n\n\tvirtv1 \"kubevirt.io\/client-go\/api\/v1\"\n\t\"kubevirt.io\/kubevirt\/pkg\/testutils\"\n\tvirtconfig \"kubevirt.io\/kubevirt\/pkg\/virt-config\"\n\tdevice_manager \"kubevirt.io\/kubevirt\/pkg\/virt-handler\/device-manager\"\n)\n\nconst (\n\tcpu_manager_static_path = \"testdata\/cpu_manager_state_static\"\n\tcpu_manager_none_path   = \"testdata\/cpu_manager_state_none\"\n)\n\nvar _ = Describe(\"Heartbeat\", func() {\n\n\tvar node *v1.Node\n\tvar fakeClient *fake.Clientset\n\n\tBeforeEach(func() {\n\t\tnode = &v1.Node{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: \"mynode\",\n\t\t\t},\n\t\t}\n\t\tfakeClient = fake.NewSimpleClientset(node)\n\t})\n\n\ttable.DescribeTable(\"with cpumanager featuregate should set the node to\", func(deviceController device_manager.DeviceControllerInterface, cpuManagerPaths []string, schedulable string, cpumanager string) {\n\t\theartbeat := NewHeartBeat(fakeClient.CoreV1(), deviceController, config(virtconfig.CPUManager), \"mynode\")\n\t\theartbeat.cpuManagerPaths = cpuManagerPaths\n\t\theartbeat.do()\n\t\tnode, err := fakeClient.CoreV1().Nodes().Get(context.Background(), \"mynode\", metav1.GetOptions{})\n\t\tExpect(err).ToNot(HaveOccurred())\n\t\tExpect(node.Labels).To(HaveKeyWithValue(virtv1.NodeSchedulable, schedulable))\n\t\tExpect(node.Labels).To(HaveKeyWithValue(virtv1.CPUManager, cpumanager))\n\t},\n\t\ttable.Entry(\"not schedulable and no cpu manager with no cpu manager file and device plugins are not initialized\",\n\t\t\tdeviceController(false),\n\t\t\t[]string{\"non\/existent\/cpumanager\/statefile\"},\n\t\t\t\"false\",\n\t\t\t\"false\",\n\t\t),\n\t\ttable.Entry(\"schedulable and no cpu manager with no cpu manager file and plugins are not initialized\",\n\t\t\tdeviceController(true),\n\t\t\t[]string{\"non\/existent\/cpumanager\/statefile\"},\n\t\t\t\"true\",\n\t\t\t\"false\",\n\t\t),\n\t\ttable.Entry(\"schedulable and cpu manager with static cpu manager policy configured and device plugins are not initialized\",\n\t\t\tdeviceController(true),\n\t\t\t[]string{\"non\/existent\/cpumanager\/statefile\", cpu_manager_static_path},\n\t\t\t\"true\",\n\t\t\t\"true\",\n\t\t),\n\t\ttable.Entry(\"schedulable and no cpu manager with no cpu manager policy configured and device plugins are not initialized\",\n\t\t\tdeviceController(true),\n\t\t\t[]string{cpu_manager_none_path, \"non\/existent\/cpumanager\/statefile\"},\n\t\t\t\"true\",\n\t\t\t\"false\",\n\t\t),\n\t)\n\n\ttable.DescribeTable(\"without cpumanager featuregate should set the node to\", func(deviceController device_manager.DeviceControllerInterface, schedulable string) {\n\t\theartbeat := NewHeartBeat(fakeClient.CoreV1(), deviceController, config(), \"mynode\")\n\t\theartbeat.do()\n\t\tnode, err := fakeClient.CoreV1().Nodes().Get(context.Background(), \"mynode\", metav1.GetOptions{})\n\t\tExpect(err).ToNot(HaveOccurred())\n\t\tExpect(node.Labels).To(HaveKeyWithValue(virtv1.NodeSchedulable, schedulable))\n\t\tExpect(node.Labels).ToNot(HaveKeyWithValue(virtv1.CPUManager, false))\n\t},\n\t\ttable.Entry(\"not schedulable with no cpumanager label present\",\n\t\t\tdeviceController(false),\n\t\t\t\"false\",\n\t\t),\n\t\ttable.Entry(\"schedulable with no cpumanger label present\",\n\t\t\tdeviceController(true),\n\t\t\t\"true\",\n\t\t),\n\t)\n\n\ttable.DescribeTable(\"without deviceplugin and\", func(deviceController device_manager.DeviceControllerInterface, initiallySchedulable string, finallySchedulable string) {\n\t\theartbeat := NewHeartBeat(fakeClient.CoreV1(), deviceController, config(), \"mynode\")\n\t\theartbeat.devicePluginWaitTimeout = 2 * time.Second\n\t\theartbeat.devicePluginPollIntervall = 10 * time.Millisecond\n\t\tstopChan := make(chan struct{})\n\t\tdone := heartbeat.Run(100*time.Second, stopChan)\n\t\tdefer func() {\n\t\t\tclose(stopChan)\n\t\t\t<-done\n\t\t}()\n\t\tEventually(func() map[string]string {\n\t\t\tnode, err := fakeClient.CoreV1().Nodes().Get(context.Background(), \"mynode\", metav1.GetOptions{})\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\treturn node.Labels\n\t\t}).Should(And(\n\t\t\tHaveKeyWithValue(virtv1.NodeSchedulable, initiallySchedulable),\n\t\t))\n\t\tConsistently(func() map[string]string {\n\t\t\tnode, err := fakeClient.CoreV1().Nodes().Get(context.Background(), \"mynode\", metav1.GetOptions{})\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\treturn node.Labels\n\t\t}, 500*time.Millisecond, 10*time.Millisecond).Should(And(\n\t\t\tHaveKeyWithValue(virtv1.NodeSchedulable, initiallySchedulable),\n\t\t))\n\t\tEventually(func() map[string]string {\n\t\t\tnode, err := fakeClient.CoreV1().Nodes().Get(context.Background(), \"mynode\", metav1.GetOptions{})\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\treturn node.Labels\n\t\t}).Should(And(\n\t\t\tHaveKeyWithValue(virtv1.NodeSchedulable, finallySchedulable),\n\t\t))\n\t\tConsistently(func() map[string]string {\n\t\t\tnode, err := fakeClient.CoreV1().Nodes().Get(context.Background(), \"mynode\", metav1.GetOptions{})\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\t\t\treturn node.Labels\n\t\t}, 500*time.Millisecond, 10*time.Millisecond).Should(And(\n\t\t\tHaveKeyWithValue(virtv1.NodeSchedulable, finallySchedulable),\n\t\t))\n\t},\n\t\ttable.Entry(\"not becoming ready, node should be set to unschedulable immediately and stick to it\",\n\t\t\tnewProbeCountingDeviceController(probe{false, 1000}),\n\t\t\t\"false\",\n\t\t\t\"false\",\n\t\t),\n\t\ttable.Entry(\"becoming ready after a few probes, node should be set to unschedulable immediately and switch earlier than one minute\",\n\t\t\tnewProbeCountingDeviceController(probe{false, 100}, probe{true, 100}),\n\t\t\t\"false\",\n\t\t\t\"true\",\n\t\t),\n\t)\n})\n\ntype fakeDeviceController struct {\n\tinitialized bool\n}\n\nfunc (f *fakeDeviceController) Initialized() bool {\n\treturn f.initialized\n}\n\nfunc config(featuregates ...string) *virtconfig.ClusterConfig {\n\tcfg := &virtv1.KubeVirtConfiguration{\n\t\tDeveloperConfiguration: &virtv1.DeveloperConfiguration{\n\t\t\tFeatureGates: featuregates,\n\t\t},\n\t}\n\tclusterConfig, _, _, _ := testutils.NewFakeClusterConfigUsingKVConfig(cfg)\n\treturn clusterConfig\n}\n\nfunc deviceController(initialized bool) device_manager.DeviceControllerInterface {\n\treturn &fakeDeviceController{initialized: initialized}\n}\n\ntype probeCountingDeviceController struct {\n\tprobes []bool\n\tprobed int\n\tlock   *sync.Mutex\n}\n\nfunc (f *probeCountingDeviceController) Initialized() bool {\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\tf.probed++\n\treturn f.probes[f.probed-1]\n}\n\nfunc newProbeCountingDeviceController(probes ...probe) device_manager.DeviceControllerInterface {\n\tvar probeArray []bool\n\tfor _, p := range probes {\n\t\tfor x := 0; x < p.repetitions; x++ {\n\t\t\tprobeArray = append(probeArray, p.value)\n\t\t}\n\t}\n\treturn &probeCountingDeviceController{probes: probeArray, lock: &sync.Mutex{}}\n}\n\ntype probe struct {\n\tvalue       bool\n\trepetitions int\n}\n<|endoftext|>"}
{"text":"<commit_before>package sqldb\n\nimport (\n\t\"database\/sql\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"code.cloudfoundry.org\/auctioneer\"\n\t\"code.cloudfoundry.org\/bbs\/models\"\n\t\"code.cloudfoundry.org\/lager\"\n\t\"code.cloudfoundry.org\/runtimeschema\/metric\"\n\t\"github.com\/cloudfoundry\/gunk\/workpool\"\n)\n\nconst (\n\tconvergeLRPRunsCounter = metric.Counter(\"ConvergenceLRPRuns\")\n\tconvergeLRPDuration    = metric.Duration(\"ConvergenceLRPDuration\")\n\n\tdomainMetricPrefix = \"Domain.\"\n\n\tinstanceLRPs  = metric.Metric(\"LRPsDesired\") \/\/ this is the number of desired instances\n\tclaimedLRPs   = metric.Metric(\"LRPsClaimed\")\n\tunclaimedLRPs = metric.Metric(\"LRPsUnclaimed\")\n\trunningLRPs   = metric.Metric(\"LRPsRunning\")\n\n\tmissingLRPs = metric.Metric(\"LRPsMissing\")\n\textraLRPs   = metric.Metric(\"LRPsExtra\")\n\n\tcrashedActualLRPs   = metric.Metric(\"CrashedActualLRPs\")\n\tcrashingDesiredLRPs = metric.Metric(\"CrashingDesiredLRPs\")\n)\n\nfunc (db *SQLDB) ConvergeLRPs(logger lager.Logger, cellSet models.CellSet) ([]*auctioneer.LRPStartRequest, []*models.ActualLRPKeyWithSchedulingInfo, []*models.ActualLRPKey) {\n\tconvergeStart := db.clock.Now()\n\tconvergeLRPRunsCounter.Increment()\n\tlogger.Info(\"starting\")\n\tdefer logger.Info(\"completed\")\n\n\tdefer func() {\n\t\terr := convergeLRPDuration.Send(time.Since(convergeStart))\n\t\tif err != nil {\n\t\t\tlogger.Error(\"failed-sending-converge-lrp-duration-metric\", err)\n\t\t}\n\t}()\n\n\tnow := db.clock.Now()\n\n\tdb.pruneDomains(logger, now)\n\tdb.pruneEvacuatingActualLRPs(logger, now)\n\n\tdomainSet, err := db.domainSet(logger)\n\tif err != nil {\n\t\treturn nil, nil, nil\n\t}\n\n\tdb.emitDomainMetrics(logger, domainSet)\n\n\tconverge := newConvergence(db)\n\tconverge.staleUnclaimedActualLRPs(logger, now)\n\tconverge.actualLRPsWithMissingCells(logger, cellSet)\n\tconverge.lrpInstanceCounts(logger, domainSet)\n\tconverge.orphanedActualLRPs(logger)\n\tconverge.crashedActualLRPs(logger, now)\n\n\treturn converge.result(logger)\n}\n\ntype convergence struct {\n\t*SQLDB\n\n\tguidsToStartRequests map[string]*auctioneer.LRPStartRequest\n\tstartRequestsMutex   sync.Mutex\n\n\tkeysWithMissingCells []*models.ActualLRPKeyWithSchedulingInfo\n\n\tkeysToRetire []*models.ActualLRPKey\n\tkeysMutex    sync.Mutex\n\n\tpool   *workpool.WorkPool\n\tpoolWg sync.WaitGroup\n}\n\nfunc newConvergence(db *SQLDB) *convergence {\n\tpool, err := workpool.NewWorkPool(db.convergenceWorkersSize)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"failing to create workpool is irrecoverable %v\", err))\n\t}\n\n\treturn &convergence{\n\t\tSQLDB:                db,\n\t\tguidsToStartRequests: map[string]*auctioneer.LRPStartRequest{},\n\t\tkeysToRetire:         []*models.ActualLRPKey{},\n\t\tpool:                 pool,\n\t}\n}\n\n\/\/ Adds stale UNCLAIMED Actual LRPs to the list of start requests.\nfunc (c *convergence) staleUnclaimedActualLRPs(logger lager.Logger, now time.Time) {\n\tlogger = logger.Session(\"stale-unclaimed-actual-lrps\")\n\n\trows, err := c.selectStaleUnclaimedLRPs(logger, c.db, now)\n\tif err != nil {\n\t\tlogger.Error(\"failed-query\", err)\n\t\treturn\n\t}\n\n\tfor rows.Next() {\n\t\tvar index int\n\t\tschedulingInfo, err := c.fetchDesiredLRPSchedulingInfoAndMore(logger, rows, &index)\n\t\tif err == nil {\n\t\t\tc.addStartRequestFromSchedulingInfo(logger, schedulingInfo, index)\n\t\t}\n\t}\n\n\tif rows.Err() != nil {\n\t\tlogger.Error(\"failed-getting-next-row\", rows.Err())\n\t}\n\n\treturn\n}\n\n\/\/ Adds CRASHED Actual LRPs that can be restarted to the list of start requests\n\/\/ and transitions them to UNCLAIMED.\nfunc (c *convergence) crashedActualLRPs(logger lager.Logger, now time.Time) {\n\tlogger = logger.Session(\"crashed-actual-lrps\")\n\trestartCalculator := models.NewDefaultRestartCalculator()\n\n\trows, err := c.selectCrashedLRPs(logger, c.db)\n\tif err != nil {\n\t\tlogger.Error(\"failed-query\", err)\n\t\treturn\n\t}\n\n\tfor rows.Next() {\n\t\tvar index int\n\t\tactual := &models.ActualLRP{}\n\n\t\tschedulingInfo, err := c.fetchDesiredLRPSchedulingInfoAndMore(logger, rows, &index, &actual.Since, &actual.CrashCount)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tactual.ProcessGuid = schedulingInfo.ProcessGuid\n\t\tactual.Domain = schedulingInfo.Domain\n\t\tactual.State = models.ActualLRPStateCrashed\n\n\t\tif actual.ShouldRestartCrash(now, restartCalculator) {\n\t\t\tc.submit(func() {\n\t\t\t\t_, _, err = c.UnclaimActualLRP(logger, &actual.ActualLRPKey)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Error(\"failed-unclaiming-actual-lrp\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tc.addStartRequestFromSchedulingInfo(logger, schedulingInfo, index)\n\t\t\t})\n\t\t}\n\t}\n\n\tif rows.Err() != nil {\n\t\tlogger.Error(\"failed-getting-next-row\", rows.Err())\n\t}\n\n\treturn\n}\n\n\/\/ Adds orphaned Actual LRPs (ones with no corresponding Desired LRP) to the\n\/\/ list of keys to retire.\nfunc (c *convergence) orphanedActualLRPs(logger lager.Logger) {\n\tlogger = logger.Session(\"orphaned-actual-lrps\")\n\n\trows, err := c.selectOrphanedActualLRPs(logger, c.db)\n\tif err != nil {\n\t\tlogger.Error(\"failed-query\", err)\n\t\treturn\n\t}\n\n\tfor rows.Next() {\n\t\tactualLRPKey := &models.ActualLRPKey{}\n\n\t\terr := rows.Scan(\n\t\t\t&actualLRPKey.ProcessGuid,\n\t\t\t&actualLRPKey.Index,\n\t\t\t&actualLRPKey.Domain,\n\t\t)\n\t\tif err != nil {\n\t\t\tlogger.Error(\"failed-scanning\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tc.addKeyToRetire(logger, actualLRPKey)\n\t}\n\n\tif rows.Err() != nil {\n\t\tlogger.Error(\"failed-getting-next-row\", rows.Err())\n\t}\n}\n\n\/\/ Creates and adds missing Actual LRPs to the list of start requests.\n\/\/ Adds extra Actual LRPs  to the list of keys to retire.\nfunc (c *convergence) lrpInstanceCounts(logger lager.Logger, domainSet map[string]struct{}) {\n\tlogger = logger.Session(\"lrp-instance-counts\")\n\n\trows, err := c.selectLRPInstanceCounts(logger, c.db)\n\tif err != nil {\n\t\tlogger.Error(\"failed-query\", err)\n\t\treturn\n\t}\n\n\tmissingLRPCount := 0\n\tfor rows.Next() {\n\t\tvar existingIndicesStr sql.NullString\n\t\tvar actualInstances int\n\n\t\tschedulingInfo, err := c.fetchDesiredLRPSchedulingInfoAndMore(logger, rows, &actualInstances, &existingIndicesStr)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tindices := []int{}\n\t\texistingIndices := strings.Split(existingIndicesStr.String, \",\")\n\n\t\tfor i := 0; i < int(schedulingInfo.Instances); i++ {\n\t\t\tfound := false\n\t\t\tfor _, indexStr := range existingIndices {\n\t\t\t\tif indexStr == strconv.Itoa(i) {\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\tmissingLRPCount++\n\t\t\t\tindices = append(indices, i)\n\t\t\t\tindex := int32(i)\n\n\t\t\t\tc.submit(func() {\n\t\t\t\t\t_, err := c.CreateUnclaimedActualLRP(logger, &models.ActualLRPKey{ProcessGuid: schedulingInfo.ProcessGuid, Domain: schedulingInfo.Domain, Index: index})\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlogger.Error(\"failed-creating-missing-actual-lrp\", err)\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\tc.addStartRequestFromSchedulingInfo(logger, schedulingInfo, indices...)\n\n\t\tif actualInstances > int(schedulingInfo.Instances) {\n\t\t\tfor i := int(schedulingInfo.Instances); i < actualInstances; i++ {\n\t\t\t\tif _, ok := domainSet[schedulingInfo.Domain]; ok {\n\t\t\t\t\tc.addKeyToRetire(logger, &models.ActualLRPKey{\n\t\t\t\t\t\tProcessGuid: schedulingInfo.ProcessGuid,\n\t\t\t\t\t\tIndex:       int32(i),\n\t\t\t\t\t\tDomain:      schedulingInfo.Domain,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif rows.Err() != nil {\n\t\tlogger.Error(\"failed-getting-next-row\", rows.Err())\n\t}\n\n\tmissingLRPs.Send(missingLRPCount)\n}\n\n\/\/ Unclaim Actual LRPs that have missing cells (not in the cell set passed to\n\/\/ convergence) and add them to the list of start requests.\nfunc (c *convergence) actualLRPsWithMissingCells(logger lager.Logger, cellSet models.CellSet) {\n\t\/\/ time.Sleep(1000 * time.Second)\n\tlogger = logger.Session(\"actual-lrps-with-missing-cells\")\n\n\tkeysWithMissingCells := make([]*models.ActualLRPKeyWithSchedulingInfo, 0)\n\n\trows, err := c.selectLRPsWithMissingCells(logger, c.db, cellSet)\n\tif err != nil {\n\t\tlogger.Error(\"failed-query\", err)\n\t\treturn\n\t}\n\n\tfor rows.Next() {\n\t\tvar index int32\n\t\tschedulingInfo, err := c.fetchDesiredLRPSchedulingInfoAndMore(logger, rows, &index)\n\t\tif err == nil {\n\t\t\tkeysWithMissingCells = append(keysWithMissingCells, &models.ActualLRPKeyWithSchedulingInfo{\n\t\t\t\tKey: &models.ActualLRPKey{\n\t\t\t\t\tProcessGuid: schedulingInfo.ProcessGuid,\n\t\t\t\t\tDomain:      schedulingInfo.Domain,\n\t\t\t\t\tIndex:       index,\n\t\t\t\t},\n\t\t\t\tSchedulingInfo: schedulingInfo,\n\t\t\t})\n\t\t}\n\t}\n\n\tif rows.Err() != nil {\n\t\tlogger.Error(\"failed-getting-next-row\", rows.Err())\n\t}\n\n\tc.keysWithMissingCells = keysWithMissingCells\n}\n\nfunc (c *convergence) addStartRequestFromSchedulingInfo(logger lager.Logger, schedulingInfo *models.DesiredLRPSchedulingInfo, indices ...int) {\n\tif len(indices) == 0 {\n\t\treturn\n\t}\n\n\tc.startRequestsMutex.Lock()\n\tdefer c.startRequestsMutex.Unlock()\n\n\tif startRequest, ok := c.guidsToStartRequests[schedulingInfo.ProcessGuid]; ok {\n\t\tstartRequest.Indices = append(startRequest.Indices, indices...)\n\t\treturn\n\t}\n\n\tstartRequest := auctioneer.NewLRPStartRequestFromSchedulingInfo(schedulingInfo, indices...)\n\tc.guidsToStartRequests[schedulingInfo.ProcessGuid] = &startRequest\n}\n\nfunc (c *convergence) addKeyToRetire(logger lager.Logger, key *models.ActualLRPKey) {\n\tc.keysMutex.Lock()\n\tdefer c.keysMutex.Unlock()\n\n\tc.keysToRetire = append(c.keysToRetire, key)\n}\n\nfunc (c *convergence) submit(work func()) {\n\tc.poolWg.Add(1)\n\tc.pool.Submit(func() {\n\t\tdefer c.poolWg.Done()\n\t\twork()\n\t})\n}\n\nfunc (c *convergence) result(logger lager.Logger) ([]*auctioneer.LRPStartRequest, []*models.ActualLRPKeyWithSchedulingInfo, []*models.ActualLRPKey) {\n\tc.poolWg.Wait()\n\tc.startRequestsMutex.Lock()\n\tdefer c.startRequestsMutex.Unlock()\n\tc.keysMutex.Lock()\n\tdefer c.keysMutex.Unlock()\n\n\tstartRequests := make([]*auctioneer.LRPStartRequest, 0, len(c.guidsToStartRequests))\n\tfor _, startRequest := range c.guidsToStartRequests {\n\t\tstartRequests = append(startRequests, startRequest)\n\t}\n\n\textraLRPs.Send(len(c.keysToRetire))\n\tc.emitLRPMetrics(logger)\n\n\treturn startRequests, c.keysWithMissingCells, c.keysToRetire\n}\n\nfunc (db *SQLDB) pruneDomains(logger lager.Logger, now time.Time) {\n\tlogger = logger.Session(\"prune-domains\")\n\n\t_, err := db.delete(logger, db.db, domainsTable, \"expire_time <= ?\", now.UnixNano())\n\tif err != nil {\n\t\tlogger.Error(\"failed-query\", err)\n\t}\n}\n\nfunc (db *SQLDB) pruneEvacuatingActualLRPs(logger lager.Logger, now time.Time) {\n\tlogger = logger.Session(\"prune-evacuating-actual-lrps\")\n\n\t_, err := db.delete(logger, db.db, actualLRPsTable, \"evacuating = ? AND expire_time <= ?\", true, now.UnixNano())\n\tif err != nil {\n\t\tlogger.Error(\"failed-query\", err)\n\t}\n}\n\nfunc (db *SQLDB) domainSet(logger lager.Logger) (map[string]struct{}, error) {\n\tlogger.Debug(\"listing-domains\")\n\tdomains, err := db.Domains(logger)\n\tif err != nil {\n\t\tlogger.Error(\"failed-listing-domains\", err)\n\t\treturn nil, err\n\t}\n\tlogger.Debug(\"succeeded-listing-domains\")\n\tm := make(map[string]struct{}, len(domains))\n\tfor _, domain := range domains {\n\t\tm[domain] = struct{}{}\n\t}\n\treturn m, nil\n}\n\nfunc (db *SQLDB) emitDomainMetrics(logger lager.Logger, domainSet map[string]struct{}) {\n\tfor domain := range domainSet {\n\t\tmetric.Metric(\"Domain.\" + domain).Send(1)\n\t}\n}\n\nfunc (db *SQLDB) emitLRPMetrics(logger lager.Logger) {\n\tvar err error\n\tlogger = logger.Session(\"emit-lrp-metrics\")\n\tclaimedInstances, unclaimedInstances, runningInstances, crashedInstances, crashingDesireds := db.countActualLRPsByState(logger, db.db)\n\n\tdesiredInstances := db.countDesiredInstances(logger, db.db)\n\n\terr = unclaimedLRPs.Send(unclaimedInstances)\n\tif err != nil {\n\t\tlogger.Error(\"failed-sending-unclaimed-lrps-metric\", err)\n\t}\n\n\terr = claimedLRPs.Send(claimedInstances)\n\tif err != nil {\n\t\tlogger.Error(\"failed-sending-claimed-lrps-metric\", err)\n\t}\n\n\terr = runningLRPs.Send(runningInstances)\n\tif err != nil {\n\t\tlogger.Error(\"failed-sending-running-lrps-metric\", err)\n\t}\n\n\terr = crashedActualLRPs.Send(crashedInstances)\n\tif err != nil {\n\t\tlogger.Error(\"failed-sending-crashed-actual-lrps-metric\", err)\n\t}\n\n\terr = crashingDesiredLRPs.Send(crashingDesireds)\n\tif err != nil {\n\t\tlogger.Error(\"failed-sending-crashing-desired-lrps-metric\", err)\n\t}\n\n\terr = instanceLRPs.Send(desiredInstances)\n\tif err != nil {\n\t\tlogger.Error(\"failed-sending-desired-lrps-metric\", err)\n\t}\n}\n\nfunc (db *SQLDB) GatherAndPruneLRPs(logger lager.Logger, cellSet models.CellSet) (*models.ConvergenceInput, error) {\n\tpanic(\"not implemented\")\n}\n<commit_msg>stop convergence workpool after it is done executing<commit_after>package sqldb\n\nimport (\n\t\"database\/sql\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"code.cloudfoundry.org\/auctioneer\"\n\t\"code.cloudfoundry.org\/bbs\/models\"\n\t\"code.cloudfoundry.org\/lager\"\n\t\"code.cloudfoundry.org\/runtimeschema\/metric\"\n\t\"github.com\/cloudfoundry\/gunk\/workpool\"\n)\n\nconst (\n\tconvergeLRPRunsCounter = metric.Counter(\"ConvergenceLRPRuns\")\n\tconvergeLRPDuration    = metric.Duration(\"ConvergenceLRPDuration\")\n\n\tdomainMetricPrefix = \"Domain.\"\n\n\tinstanceLRPs  = metric.Metric(\"LRPsDesired\") \/\/ this is the number of desired instances\n\tclaimedLRPs   = metric.Metric(\"LRPsClaimed\")\n\tunclaimedLRPs = metric.Metric(\"LRPsUnclaimed\")\n\trunningLRPs   = metric.Metric(\"LRPsRunning\")\n\n\tmissingLRPs = metric.Metric(\"LRPsMissing\")\n\textraLRPs   = metric.Metric(\"LRPsExtra\")\n\n\tcrashedActualLRPs   = metric.Metric(\"CrashedActualLRPs\")\n\tcrashingDesiredLRPs = metric.Metric(\"CrashingDesiredLRPs\")\n)\n\nfunc (db *SQLDB) ConvergeLRPs(logger lager.Logger, cellSet models.CellSet) ([]*auctioneer.LRPStartRequest, []*models.ActualLRPKeyWithSchedulingInfo, []*models.ActualLRPKey) {\n\tconvergeStart := db.clock.Now()\n\tconvergeLRPRunsCounter.Increment()\n\tlogger.Info(\"starting\")\n\tdefer logger.Info(\"completed\")\n\n\tdefer func() {\n\t\terr := convergeLRPDuration.Send(time.Since(convergeStart))\n\t\tif err != nil {\n\t\t\tlogger.Error(\"failed-sending-converge-lrp-duration-metric\", err)\n\t\t}\n\t}()\n\n\tnow := db.clock.Now()\n\n\tdb.pruneDomains(logger, now)\n\tdb.pruneEvacuatingActualLRPs(logger, now)\n\n\tdomainSet, err := db.domainSet(logger)\n\tif err != nil {\n\t\treturn nil, nil, nil\n\t}\n\n\tdb.emitDomainMetrics(logger, domainSet)\n\n\tconverge := newConvergence(db)\n\tconverge.staleUnclaimedActualLRPs(logger, now)\n\tconverge.actualLRPsWithMissingCells(logger, cellSet)\n\tconverge.lrpInstanceCounts(logger, domainSet)\n\tconverge.orphanedActualLRPs(logger)\n\tconverge.crashedActualLRPs(logger, now)\n\n\treturn converge.result(logger)\n}\n\ntype convergence struct {\n\t*SQLDB\n\n\tguidsToStartRequests map[string]*auctioneer.LRPStartRequest\n\tstartRequestsMutex   sync.Mutex\n\n\tkeysWithMissingCells []*models.ActualLRPKeyWithSchedulingInfo\n\n\tkeysToRetire []*models.ActualLRPKey\n\tkeysMutex    sync.Mutex\n\n\tpool   *workpool.WorkPool\n\tpoolWg sync.WaitGroup\n}\n\nfunc newConvergence(db *SQLDB) *convergence {\n\tpool, err := workpool.NewWorkPool(db.convergenceWorkersSize)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"failing to create workpool is irrecoverable %v\", err))\n\t}\n\n\treturn &convergence{\n\t\tSQLDB:                db,\n\t\tguidsToStartRequests: map[string]*auctioneer.LRPStartRequest{},\n\t\tkeysToRetire:         []*models.ActualLRPKey{},\n\t\tpool:                 pool,\n\t}\n}\n\n\/\/ Adds stale UNCLAIMED Actual LRPs to the list of start requests.\nfunc (c *convergence) staleUnclaimedActualLRPs(logger lager.Logger, now time.Time) {\n\tlogger = logger.Session(\"stale-unclaimed-actual-lrps\")\n\n\trows, err := c.selectStaleUnclaimedLRPs(logger, c.db, now)\n\tif err != nil {\n\t\tlogger.Error(\"failed-query\", err)\n\t\treturn\n\t}\n\n\tfor rows.Next() {\n\t\tvar index int\n\t\tschedulingInfo, err := c.fetchDesiredLRPSchedulingInfoAndMore(logger, rows, &index)\n\t\tif err == nil {\n\t\t\tc.addStartRequestFromSchedulingInfo(logger, schedulingInfo, index)\n\t\t}\n\t}\n\n\tif rows.Err() != nil {\n\t\tlogger.Error(\"failed-getting-next-row\", rows.Err())\n\t}\n\n\treturn\n}\n\n\/\/ Adds CRASHED Actual LRPs that can be restarted to the list of start requests\n\/\/ and transitions them to UNCLAIMED.\nfunc (c *convergence) crashedActualLRPs(logger lager.Logger, now time.Time) {\n\tlogger = logger.Session(\"crashed-actual-lrps\")\n\trestartCalculator := models.NewDefaultRestartCalculator()\n\n\trows, err := c.selectCrashedLRPs(logger, c.db)\n\tif err != nil {\n\t\tlogger.Error(\"failed-query\", err)\n\t\treturn\n\t}\n\n\tfor rows.Next() {\n\t\tvar index int\n\t\tactual := &models.ActualLRP{}\n\n\t\tschedulingInfo, err := c.fetchDesiredLRPSchedulingInfoAndMore(logger, rows, &index, &actual.Since, &actual.CrashCount)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tactual.ProcessGuid = schedulingInfo.ProcessGuid\n\t\tactual.Domain = schedulingInfo.Domain\n\t\tactual.State = models.ActualLRPStateCrashed\n\n\t\tif actual.ShouldRestartCrash(now, restartCalculator) {\n\t\t\tc.submit(func() {\n\t\t\t\t_, _, err = c.UnclaimActualLRP(logger, &actual.ActualLRPKey)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Error(\"failed-unclaiming-actual-lrp\", err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tc.addStartRequestFromSchedulingInfo(logger, schedulingInfo, index)\n\t\t\t})\n\t\t}\n\t}\n\n\tif rows.Err() != nil {\n\t\tlogger.Error(\"failed-getting-next-row\", rows.Err())\n\t}\n\n\treturn\n}\n\n\/\/ Adds orphaned Actual LRPs (ones with no corresponding Desired LRP) to the\n\/\/ list of keys to retire.\nfunc (c *convergence) orphanedActualLRPs(logger lager.Logger) {\n\tlogger = logger.Session(\"orphaned-actual-lrps\")\n\n\trows, err := c.selectOrphanedActualLRPs(logger, c.db)\n\tif err != nil {\n\t\tlogger.Error(\"failed-query\", err)\n\t\treturn\n\t}\n\n\tfor rows.Next() {\n\t\tactualLRPKey := &models.ActualLRPKey{}\n\n\t\terr := rows.Scan(\n\t\t\t&actualLRPKey.ProcessGuid,\n\t\t\t&actualLRPKey.Index,\n\t\t\t&actualLRPKey.Domain,\n\t\t)\n\t\tif err != nil {\n\t\t\tlogger.Error(\"failed-scanning\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tc.addKeyToRetire(logger, actualLRPKey)\n\t}\n\n\tif rows.Err() != nil {\n\t\tlogger.Error(\"failed-getting-next-row\", rows.Err())\n\t}\n}\n\n\/\/ Creates and adds missing Actual LRPs to the list of start requests.\n\/\/ Adds extra Actual LRPs  to the list of keys to retire.\nfunc (c *convergence) lrpInstanceCounts(logger lager.Logger, domainSet map[string]struct{}) {\n\tlogger = logger.Session(\"lrp-instance-counts\")\n\n\trows, err := c.selectLRPInstanceCounts(logger, c.db)\n\tif err != nil {\n\t\tlogger.Error(\"failed-query\", err)\n\t\treturn\n\t}\n\n\tmissingLRPCount := 0\n\tfor rows.Next() {\n\t\tvar existingIndicesStr sql.NullString\n\t\tvar actualInstances int\n\n\t\tschedulingInfo, err := c.fetchDesiredLRPSchedulingInfoAndMore(logger, rows, &actualInstances, &existingIndicesStr)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tindices := []int{}\n\t\texistingIndices := strings.Split(existingIndicesStr.String, \",\")\n\n\t\tfor i := 0; i < int(schedulingInfo.Instances); i++ {\n\t\t\tfound := false\n\t\t\tfor _, indexStr := range existingIndices {\n\t\t\t\tif indexStr == strconv.Itoa(i) {\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\tmissingLRPCount++\n\t\t\t\tindices = append(indices, i)\n\t\t\t\tindex := int32(i)\n\n\t\t\t\tc.submit(func() {\n\t\t\t\t\t_, err := c.CreateUnclaimedActualLRP(logger, &models.ActualLRPKey{ProcessGuid: schedulingInfo.ProcessGuid, Domain: schedulingInfo.Domain, Index: index})\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlogger.Error(\"failed-creating-missing-actual-lrp\", err)\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\tc.addStartRequestFromSchedulingInfo(logger, schedulingInfo, indices...)\n\n\t\tif actualInstances > int(schedulingInfo.Instances) {\n\t\t\tfor i := int(schedulingInfo.Instances); i < actualInstances; i++ {\n\t\t\t\tif _, ok := domainSet[schedulingInfo.Domain]; ok {\n\t\t\t\t\tc.addKeyToRetire(logger, &models.ActualLRPKey{\n\t\t\t\t\t\tProcessGuid: schedulingInfo.ProcessGuid,\n\t\t\t\t\t\tIndex:       int32(i),\n\t\t\t\t\t\tDomain:      schedulingInfo.Domain,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif rows.Err() != nil {\n\t\tlogger.Error(\"failed-getting-next-row\", rows.Err())\n\t}\n\n\tmissingLRPs.Send(missingLRPCount)\n}\n\n\/\/ Unclaim Actual LRPs that have missing cells (not in the cell set passed to\n\/\/ convergence) and add them to the list of start requests.\nfunc (c *convergence) actualLRPsWithMissingCells(logger lager.Logger, cellSet models.CellSet) {\n\t\/\/ time.Sleep(1000 * time.Second)\n\tlogger = logger.Session(\"actual-lrps-with-missing-cells\")\n\n\tkeysWithMissingCells := make([]*models.ActualLRPKeyWithSchedulingInfo, 0)\n\n\trows, err := c.selectLRPsWithMissingCells(logger, c.db, cellSet)\n\tif err != nil {\n\t\tlogger.Error(\"failed-query\", err)\n\t\treturn\n\t}\n\n\tfor rows.Next() {\n\t\tvar index int32\n\t\tschedulingInfo, err := c.fetchDesiredLRPSchedulingInfoAndMore(logger, rows, &index)\n\t\tif err == nil {\n\t\t\tkeysWithMissingCells = append(keysWithMissingCells, &models.ActualLRPKeyWithSchedulingInfo{\n\t\t\t\tKey: &models.ActualLRPKey{\n\t\t\t\t\tProcessGuid: schedulingInfo.ProcessGuid,\n\t\t\t\t\tDomain:      schedulingInfo.Domain,\n\t\t\t\t\tIndex:       index,\n\t\t\t\t},\n\t\t\t\tSchedulingInfo: schedulingInfo,\n\t\t\t})\n\t\t}\n\t}\n\n\tif rows.Err() != nil {\n\t\tlogger.Error(\"failed-getting-next-row\", rows.Err())\n\t}\n\n\tc.keysWithMissingCells = keysWithMissingCells\n}\n\nfunc (c *convergence) addStartRequestFromSchedulingInfo(logger lager.Logger, schedulingInfo *models.DesiredLRPSchedulingInfo, indices ...int) {\n\tif len(indices) == 0 {\n\t\treturn\n\t}\n\n\tc.startRequestsMutex.Lock()\n\tdefer c.startRequestsMutex.Unlock()\n\n\tif startRequest, ok := c.guidsToStartRequests[schedulingInfo.ProcessGuid]; ok {\n\t\tstartRequest.Indices = append(startRequest.Indices, indices...)\n\t\treturn\n\t}\n\n\tstartRequest := auctioneer.NewLRPStartRequestFromSchedulingInfo(schedulingInfo, indices...)\n\tc.guidsToStartRequests[schedulingInfo.ProcessGuid] = &startRequest\n}\n\nfunc (c *convergence) addKeyToRetire(logger lager.Logger, key *models.ActualLRPKey) {\n\tc.keysMutex.Lock()\n\tdefer c.keysMutex.Unlock()\n\n\tc.keysToRetire = append(c.keysToRetire, key)\n}\n\nfunc (c *convergence) submit(work func()) {\n\tc.poolWg.Add(1)\n\tc.pool.Submit(func() {\n\t\tdefer c.poolWg.Done()\n\t\twork()\n\t})\n}\n\nfunc (c *convergence) result(logger lager.Logger) ([]*auctioneer.LRPStartRequest, []*models.ActualLRPKeyWithSchedulingInfo, []*models.ActualLRPKey) {\n\tc.poolWg.Wait()\n\tc.pool.Stop()\n\n\tc.startRequestsMutex.Lock()\n\tdefer c.startRequestsMutex.Unlock()\n\n\tc.keysMutex.Lock()\n\tdefer c.keysMutex.Unlock()\n\n\tstartRequests := make([]*auctioneer.LRPStartRequest, 0, len(c.guidsToStartRequests))\n\tfor _, startRequest := range c.guidsToStartRequests {\n\t\tstartRequests = append(startRequests, startRequest)\n\t}\n\n\textraLRPs.Send(len(c.keysToRetire))\n\tc.emitLRPMetrics(logger)\n\n\treturn startRequests, c.keysWithMissingCells, c.keysToRetire\n}\n\nfunc (db *SQLDB) pruneDomains(logger lager.Logger, now time.Time) {\n\tlogger = logger.Session(\"prune-domains\")\n\n\t_, err := db.delete(logger, db.db, domainsTable, \"expire_time <= ?\", now.UnixNano())\n\tif err != nil {\n\t\tlogger.Error(\"failed-query\", err)\n\t}\n}\n\nfunc (db *SQLDB) pruneEvacuatingActualLRPs(logger lager.Logger, now time.Time) {\n\tlogger = logger.Session(\"prune-evacuating-actual-lrps\")\n\n\t_, err := db.delete(logger, db.db, actualLRPsTable, \"evacuating = ? AND expire_time <= ?\", true, now.UnixNano())\n\tif err != nil {\n\t\tlogger.Error(\"failed-query\", err)\n\t}\n}\n\nfunc (db *SQLDB) domainSet(logger lager.Logger) (map[string]struct{}, error) {\n\tlogger.Debug(\"listing-domains\")\n\tdomains, err := db.Domains(logger)\n\tif err != nil {\n\t\tlogger.Error(\"failed-listing-domains\", err)\n\t\treturn nil, err\n\t}\n\tlogger.Debug(\"succeeded-listing-domains\")\n\tm := make(map[string]struct{}, len(domains))\n\tfor _, domain := range domains {\n\t\tm[domain] = struct{}{}\n\t}\n\treturn m, nil\n}\n\nfunc (db *SQLDB) emitDomainMetrics(logger lager.Logger, domainSet map[string]struct{}) {\n\tfor domain := range domainSet {\n\t\tmetric.Metric(\"Domain.\" + domain).Send(1)\n\t}\n}\n\nfunc (db *SQLDB) emitLRPMetrics(logger lager.Logger) {\n\tvar err error\n\tlogger = logger.Session(\"emit-lrp-metrics\")\n\tclaimedInstances, unclaimedInstances, runningInstances, crashedInstances, crashingDesireds := db.countActualLRPsByState(logger, db.db)\n\n\tdesiredInstances := db.countDesiredInstances(logger, db.db)\n\n\terr = unclaimedLRPs.Send(unclaimedInstances)\n\tif err != nil {\n\t\tlogger.Error(\"failed-sending-unclaimed-lrps-metric\", err)\n\t}\n\n\terr = claimedLRPs.Send(claimedInstances)\n\tif err != nil {\n\t\tlogger.Error(\"failed-sending-claimed-lrps-metric\", err)\n\t}\n\n\terr = runningLRPs.Send(runningInstances)\n\tif err != nil {\n\t\tlogger.Error(\"failed-sending-running-lrps-metric\", err)\n\t}\n\n\terr = crashedActualLRPs.Send(crashedInstances)\n\tif err != nil {\n\t\tlogger.Error(\"failed-sending-crashed-actual-lrps-metric\", err)\n\t}\n\n\terr = crashingDesiredLRPs.Send(crashingDesireds)\n\tif err != nil {\n\t\tlogger.Error(\"failed-sending-crashing-desired-lrps-metric\", err)\n\t}\n\n\terr = instanceLRPs.Send(desiredInstances)\n\tif err != nil {\n\t\tlogger.Error(\"failed-sending-desired-lrps-metric\", err)\n\t}\n}\n\nfunc (db *SQLDB) GatherAndPruneLRPs(logger lager.Logger, cellSet models.CellSet) (*models.ConvergenceInput, error) {\n\tpanic(\"not implemented\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package controller\n\nimport (\n\t\"github.com\/cuigh\/auxo\/errors\"\n\t\"github.com\/cuigh\/auxo\/net\/web\"\n\t\"github.com\/cuigh\/swirl\/biz\"\n\t\"github.com\/cuigh\/swirl\/biz\/docker\"\n\t\"github.com\/cuigh\/swirl\/model\"\n)\n\n\/\/ HomeController is a basic controller of site\ntype HomeController struct {\n\tIndex    web.HandlerFunc `path:\"\/\" name:\"index\" authorize:\"?\" desc:\"index page\"`\n\tLogin    web.HandlerFunc `path:\"\/login\" name:\"login\" authorize:\"*\" desc:\"sign in page\"`\n\tInitGet  web.HandlerFunc `path:\"\/init\" name:\"init\" authorize:\"*\" desc:\"initialize page\"`\n\tInitPost web.HandlerFunc `path:\"\/init\" method:\"post\" name:\"init\" authorize:\"*\" desc:\"initialize system\"`\n\tError403 web.HandlerFunc `path:\"\/403\" name:\"403\" authorize:\"?\" desc:\"403 page\"`\n\tError404 web.HandlerFunc `path:\"\/404\" name:\"404\" authorize:\"*\" desc:\"404 page\"`\n}\n\n\/\/ Home creates an instance of HomeController\nfunc Home() (c *HomeController) {\n\treturn &HomeController{\n\t\tIndex:    homeIndex,\n\t\tLogin:    homeLogin,\n\t\tInitGet:  homeInitGet,\n\t\tInitPost: homeInitPost,\n\t\tError403: homeError403,\n\t\tError404: homeError404,\n\t}\n}\n\nfunc homeIndex(ctx web.Context) (err error) {\n\tvar (\n\t\tcount int\n\t\tm     = newModel(ctx)\n\t)\n\n\tif count, err = docker.NodeCount(); err != nil {\n\t\treturn\n\t}\n\tm.Set(\"NodeCount\", count)\n\n\tif count, err = docker.NetworkCount(); err != nil {\n\t\treturn\n\t}\n\tm.Set(\"NetworkCount\", count)\n\n\tif count, err = docker.ServiceCount(); err != nil {\n\t\treturn\n\t}\n\tm.Set(\"ServiceCount\", count)\n\n\tif count, err = docker.StackCount(); err != nil {\n\t\treturn\n\t}\n\tm.Set(\"StackCount\", count)\n\n\treturn ctx.Render(\"index\", m)\n}\n\nfunc homeLogin(ctx web.Context) error {\n\tcount, err := biz.User.Count()\n\tif err != nil {\n\t\treturn err\n\t} else if count == 0 {\n\t\treturn ctx.Redirect(\"init\")\n\t}\n\tif ctx.User() != nil {\n\t\tu := ctx.Q(\"from\")\n\t\tif u == \"\" {\n\t\t\tu = \"\/\"\n\t\t}\n\t\treturn ctx.Redirect(u)\n\t}\n\treturn ctx.Render(\"login\", nil)\n}\n\nfunc homeInitGet(ctx web.Context) error {\n\tcount, err := biz.User.Count()\n\tif err != nil {\n\t\treturn err\n\t} else if count > 0 {\n\t\treturn ctx.Redirect(\"login\")\n\t}\n\treturn ctx.Render(\"init\", nil)\n}\n\nfunc homeInitPost(ctx web.Context) error {\n\tcount, err := biz.User.Count()\n\tif err != nil {\n\t\treturn err\n\t} else if count > 0 {\n\t\treturn errors.New(\"Swirl was already initialized\")\n\t}\n\n\tuser := &model.User{}\n\terr = ctx.Bind(user)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tuser.Admin = true\n\tuser.Type = model.UserTypeInternal\n\terr = biz.User.Create(user, nil)\n\treturn ajaxResult(ctx, err)\n}\n\nfunc homeError403(ctx web.Context) error {\n\treturn ctx.Render(\"403\", nil)\n}\n\nfunc homeError404(ctx web.Context) error {\n\treturn ctx.Render(\"404\", nil)\n}\n<commit_msg>Rename handlers<commit_after>package controller\n\nimport (\n\t\"github.com\/cuigh\/auxo\/errors\"\n\t\"github.com\/cuigh\/auxo\/net\/web\"\n\t\"github.com\/cuigh\/swirl\/biz\"\n\t\"github.com\/cuigh\/swirl\/biz\/docker\"\n\t\"github.com\/cuigh\/swirl\/model\"\n)\n\n\/\/ HomeController is a basic controller of site\ntype HomeController struct {\n\tIndex    web.HandlerFunc `path:\"\/\" name:\"index\" authorize:\"?\" desc:\"index page\"`\n\tLogin    web.HandlerFunc `path:\"\/login\" name:\"login.view\" authorize:\"*\" desc:\"sign in page\"`\n\tInitGet  web.HandlerFunc `path:\"\/init\" name:\"init.view\" authorize:\"*\" desc:\"initialize page\"`\n\tInitPost web.HandlerFunc `path:\"\/init\" name:\"init\" method:\"post\" authorize:\"*\" desc:\"initialize system\"`\n\tError403 web.HandlerFunc `path:\"\/403\" name:\"403\" authorize:\"?\" desc:\"403 page\"`\n\tError404 web.HandlerFunc `path:\"\/404\" name:\"404\" authorize:\"*\" desc:\"404 page\"`\n}\n\n\/\/ Home creates an instance of HomeController\nfunc Home() (c *HomeController) {\n\treturn &HomeController{\n\t\tIndex:    homeIndex,\n\t\tLogin:    homeLogin,\n\t\tInitGet:  homeInitGet,\n\t\tInitPost: homeInitPost,\n\t\tError403: homeError403,\n\t\tError404: homeError404,\n\t}\n}\n\nfunc homeIndex(ctx web.Context) (err error) {\n\tvar (\n\t\tcount int\n\t\tm     = newModel(ctx)\n\t)\n\n\tif count, err = docker.NodeCount(); err != nil {\n\t\treturn\n\t}\n\tm.Set(\"NodeCount\", count)\n\n\tif count, err = docker.NetworkCount(); err != nil {\n\t\treturn\n\t}\n\tm.Set(\"NetworkCount\", count)\n\n\tif count, err = docker.ServiceCount(); err != nil {\n\t\treturn\n\t}\n\tm.Set(\"ServiceCount\", count)\n\n\tif count, err = docker.StackCount(); err != nil {\n\t\treturn\n\t}\n\tm.Set(\"StackCount\", count)\n\n\treturn ctx.Render(\"index\", m)\n}\n\nfunc homeLogin(ctx web.Context) error {\n\tcount, err := biz.User.Count()\n\tif err != nil {\n\t\treturn err\n\t} else if count == 0 {\n\t\treturn ctx.Redirect(\"init\")\n\t}\n\tif ctx.User() != nil {\n\t\tu := ctx.Q(\"from\")\n\t\tif u == \"\" {\n\t\t\tu = \"\/\"\n\t\t}\n\t\treturn ctx.Redirect(u)\n\t}\n\treturn ctx.Render(\"login\", nil)\n}\n\nfunc homeInitGet(ctx web.Context) error {\n\tcount, err := biz.User.Count()\n\tif err != nil {\n\t\treturn err\n\t} else if count > 0 {\n\t\treturn ctx.Redirect(\"login\")\n\t}\n\treturn ctx.Render(\"init\", nil)\n}\n\nfunc homeInitPost(ctx web.Context) error {\n\tcount, err := biz.User.Count()\n\tif err != nil {\n\t\treturn err\n\t} else if count > 0 {\n\t\treturn errors.New(\"Swirl was already initialized\")\n\t}\n\n\tuser := &model.User{}\n\terr = ctx.Bind(user)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tuser.Admin = true\n\tuser.Type = model.UserTypeInternal\n\terr = biz.User.Create(user, nil)\n\treturn ajaxResult(ctx, err)\n}\n\nfunc homeError403(ctx web.Context) error {\n\treturn ctx.Render(\"403\", nil)\n}\n\nfunc homeError404(ctx web.Context) error {\n\treturn ctx.Render(\"404\", nil)\n}\n<|endoftext|>"}
{"text":"<commit_before>package agent\n\nimport (\n\t\"reflect\"\n\t\"sync\"\n\n\t\"github.com\/docker\/swarmkit\/api\"\n\t\"github.com\/docker\/swarmkit\/log\"\n\t\"golang.org\/x\/net\/context\"\n)\n\n\/\/ StatusReporter receives updates to task status. Method may be called\n\/\/ concurrently, so implementations should be goroutine-safe.\ntype StatusReporter interface {\n\tUpdateTaskStatus(ctx context.Context, taskID string, status *api.TaskStatus) error\n}\n\ntype statusReporterFunc func(ctx context.Context, taskID string, status *api.TaskStatus) error\n\nfunc (fn statusReporterFunc) UpdateTaskStatus(ctx context.Context, taskID string, status *api.TaskStatus) error {\n\treturn fn(ctx, taskID, status)\n}\n\n\/\/ statusReporter creates a reliable StatusReporter that will always succeed.\n\/\/ It handles several tasks at once, ensuring all statuses are reported.\n\/\/\n\/\/ The reporter will continue reporting the current status until it succeeds.\ntype statusReporter struct {\n\treporter StatusReporter\n\tstatuses map[string]*api.TaskStatus\n\tmu       sync.Mutex\n\tcond     sync.Cond\n\tclosed   bool\n}\n\nfunc newStatusReporter(ctx context.Context, upstream StatusReporter) *statusReporter {\n\tr := &statusReporter{\n\t\treporter: upstream,\n\t\tstatuses: make(map[string]*api.TaskStatus),\n\t}\n\n\tr.cond.L = &r.mu\n\n\tgo r.run(ctx)\n\treturn r\n}\n\nfunc (sr *statusReporter) UpdateTaskStatus(ctx context.Context, taskID string, status *api.TaskStatus) error {\n\tsr.mu.Lock()\n\tdefer sr.mu.Unlock()\n\n\tcurrent, ok := sr.statuses[taskID]\n\tif ok {\n\t\tif reflect.DeepEqual(current, status) {\n\t\t\treturn nil\n\t\t}\n\n\t\tif current.State > status.State {\n\t\t\treturn nil \/\/ ignore old updates\n\t\t}\n\t}\n\tsr.statuses[taskID] = status\n\tsr.cond.Signal()\n\n\treturn nil\n}\n\nfunc (sr *statusReporter) Close() error {\n\tsr.mu.Lock()\n\tdefer sr.mu.Unlock()\n\n\tsr.closed = true\n\tsr.cond.Signal()\n\n\treturn nil\n}\n\nfunc (sr *statusReporter) run(ctx context.Context) {\n\tdone := make(chan struct{})\n\tdefer close(done)\n\n\tgo func() {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tsr.Close()\n\t\tcase <-done:\n\t\t\treturn\n\t\t}\n\t}()\n\n\tsr.mu.Lock() \/\/ released during wait, below.\n\tdefer sr.mu.Unlock()\n\n\tfor {\n\t\tif len(sr.statuses) == 0 {\n\t\t\tsr.cond.Wait()\n\t\t}\n\n\t\tfor taskID, status := range sr.statuses {\n\t\t\tif sr.closed {\n\t\t\t\t\/\/ TODO(stevvooe): Add support here for waiting until all\n\t\t\t\t\/\/ statuses are flushed before shutting down.\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tdelete(sr.statuses, taskID) \/\/ delete the entry, while trying to send.\n\n\t\t\tsr.mu.Unlock()\n\t\t\terr := sr.reporter.UpdateTaskStatus(ctx, taskID, status)\n\t\t\tsr.mu.Lock()\n\n\t\t\tif err != nil {\n\t\t\t\tlog.G(ctx).WithError(err).Error(\"failed reporting status to agent\")\n\n\t\t\t\t\/\/ place it back in the map, if not there, allowing us to pick\n\t\t\t\t\/\/ the value if a new one came in when we were sending the last\n\t\t\t\t\/\/ update.\n\t\t\t\tif _, ok := sr.statuses[taskID]; !ok {\n\t\t\t\t\tsr.statuses[taskID] = status\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n<commit_msg>agent: fix leak in reporter on stop<commit_after>package agent\n\nimport (\n\t\"reflect\"\n\t\"sync\"\n\n\t\"github.com\/docker\/swarmkit\/api\"\n\t\"github.com\/docker\/swarmkit\/log\"\n\t\"golang.org\/x\/net\/context\"\n)\n\n\/\/ StatusReporter receives updates to task status. Method may be called\n\/\/ concurrently, so implementations should be goroutine-safe.\ntype StatusReporter interface {\n\tUpdateTaskStatus(ctx context.Context, taskID string, status *api.TaskStatus) error\n}\n\ntype statusReporterFunc func(ctx context.Context, taskID string, status *api.TaskStatus) error\n\nfunc (fn statusReporterFunc) UpdateTaskStatus(ctx context.Context, taskID string, status *api.TaskStatus) error {\n\treturn fn(ctx, taskID, status)\n}\n\n\/\/ statusReporter creates a reliable StatusReporter that will always succeed.\n\/\/ It handles several tasks at once, ensuring all statuses are reported.\n\/\/\n\/\/ The reporter will continue reporting the current status until it succeeds.\ntype statusReporter struct {\n\treporter StatusReporter\n\tstatuses map[string]*api.TaskStatus\n\tmu       sync.Mutex\n\tcond     sync.Cond\n\tclosed   bool\n}\n\nfunc newStatusReporter(ctx context.Context, upstream StatusReporter) *statusReporter {\n\tr := &statusReporter{\n\t\treporter: upstream,\n\t\tstatuses: make(map[string]*api.TaskStatus),\n\t}\n\n\tr.cond.L = &r.mu\n\n\tgo r.run(ctx)\n\treturn r\n}\n\nfunc (sr *statusReporter) UpdateTaskStatus(ctx context.Context, taskID string, status *api.TaskStatus) error {\n\tsr.mu.Lock()\n\tdefer sr.mu.Unlock()\n\n\tcurrent, ok := sr.statuses[taskID]\n\tif ok {\n\t\tif reflect.DeepEqual(current, status) {\n\t\t\treturn nil\n\t\t}\n\n\t\tif current.State > status.State {\n\t\t\treturn nil \/\/ ignore old updates\n\t\t}\n\t}\n\tsr.statuses[taskID] = status\n\tsr.cond.Signal()\n\n\treturn nil\n}\n\nfunc (sr *statusReporter) Close() error {\n\tsr.mu.Lock()\n\tdefer sr.mu.Unlock()\n\n\tsr.closed = true\n\tsr.cond.Signal()\n\n\treturn nil\n}\n\nfunc (sr *statusReporter) run(ctx context.Context) {\n\tdone := make(chan struct{})\n\tdefer close(done)\n\n\tsr.mu.Lock() \/\/ released during wait, below.\n\tdefer sr.mu.Unlock()\n\n\tgo func() {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tsr.Close()\n\t\tcase <-done:\n\t\t\treturn\n\t\t}\n\t}()\n\n\tfor {\n\t\tif len(sr.statuses) == 0 {\n\t\t\tsr.cond.Wait()\n\t\t}\n\n\t\tif sr.closed {\n\t\t\t\/\/ TODO(stevvooe): Add support here for waiting until all\n\t\t\t\/\/ statuses are flushed before shutting down.\n\t\t\treturn\n\t\t}\n\n\t\tfor taskID, status := range sr.statuses {\n\t\t\tdelete(sr.statuses, taskID) \/\/ delete the entry, while trying to send.\n\n\t\t\tsr.mu.Unlock()\n\t\t\terr := sr.reporter.UpdateTaskStatus(ctx, taskID, status)\n\t\t\tsr.mu.Lock()\n\n\t\t\t\/\/ reporter might be closed during UpdateTaskStatus call\n\t\t\tif sr.closed {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif err != nil {\n\t\t\t\tlog.G(ctx).WithError(err).Error(\"failed reporting status to agent\")\n\n\t\t\t\t\/\/ place it back in the map, if not there, allowing us to pick\n\t\t\t\t\/\/ the value if a new one came in when we were sending the last\n\t\t\t\t\/\/ update.\n\t\t\t\tif _, ok := sr.statuses[taskID]; !ok {\n\t\t\t\t\tsr.statuses[taskID] = status\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package iot\n\nimport (\n\t\"time\"\n\t. \"github.com\/influxdata\/influxdb-comparisons\/bulk_data_gen\/common\"\n)\n\nvar (\n\tDoorByteString      = []byte(\"door_state\")       \/\/ heap optimization\n)\n\nvar (\n\t\/\/ Field keys for 'air condition indoor' points.\n\tDoorFieldKeys = [][]byte{\n\t\t[]byte(\"state\"),\n\t\t[]byte(\"battery_voltage\"),\n\n\t}\n)\n\ntype DoorMeasurement struct {\n\tsensorId \t[]byte\n\ttimestamp     time.Time\n\tdistributions []Distribution\n}\n\nfunc NewDoorMeasurement(start time.Time, id []byte) *DoorMeasurement {\n\tdistributions := make([]Distribution, len(DoorFieldKeys))\n\t\/\/state\n\tdistributions[0] = TSD(0,1,0)\n\t\/\/battery_voltage\n\tdistributions[1] = MUDWD(ND(1,0.5), 1, 3.2, 3.2 )\n\n\treturn &DoorMeasurement{\n\t\ttimestamp:   start,\n\t\tdistributions: distributions,\n\t\tsensorId: id,\n\t}\n}\n\nfunc (m *DoorMeasurement) Tick(d time.Duration) {\n\tm.timestamp = m.timestamp.Add(d)\n\tfor i := range m.distributions {\n\t\tm.distributions[i].Advance()\n\t}\n}\n\nfunc (m *DoorMeasurement) ToPoint(p *Point) {\n\tp.SetMeasurementName(DoorByteString)\n\tp.SetTimestamp(&m.timestamp)\n\n\tfor i := range m.distributions {\n\t\tp.AppendField(DoorFieldKeys[i], m.distributions[i].Get())\n\t}\n}\n<commit_msg>Improved variables<commit_after>package iot\n\nimport (\n\t. \"github.com\/influxdata\/influxdb-comparisons\/bulk_data_gen\/common\"\n\t\"time\"\n)\n\nvar (\n\tDoorByteString = []byte(\"door_state\") \/\/ heap optimization\n\tDoorTagKey     = []byte(\"door\")\n)\n\nvar (\n\t\/\/ Field keys for 'air condition indoor' points.\n\tDoorFieldKeys = [][]byte{\n\t\t[]byte(\"state\"),\n\t\t[]byte(\"battery_voltage\"),\n\t}\n)\n\ntype DoorMeasurement struct {\n\tsensorId      []byte\n\tdoorId        []byte\n\ttimestamp     time.Time\n\tdistributions []Distribution\n}\n\nfunc NewDoorMeasurement(start time.Time, doorId []byte, sendorId []byte) *DoorMeasurement {\n\tdistributions := make([]Distribution, len(DoorFieldKeys))\n\t\/\/state\n\tdistributions[0] = TSD(0, 1, 0)\n\t\/\/battery_voltage\n\tdistributions[1] = MUDWD(ND(1, 0.5), 1, 3.2, 3.2)\n\n\treturn &DoorMeasurement{\n\t\ttimestamp:     start,\n\t\tdistributions: distributions,\n\t\tsensorId:      sendorId,\n\t\tdoorId:        doorId,\n\t}\n}\n\nfunc (m *DoorMeasurement) Tick(d time.Duration) {\n\tm.timestamp = m.timestamp.Add(d)\n\tfor i := range m.distributions {\n\t\tm.distributions[i].Advance()\n\t}\n}\n\nfunc (m *DoorMeasurement) ToPoint(p *Point) {\n\tp.SetMeasurementName(DoorByteString)\n\tp.SetTimestamp(&m.timestamp)\n\tp.AppendTag(DoorTagKey, m.doorId)\n\tfor i := range m.distributions {\n\t\tp.AppendField(DoorFieldKeys[i], m.distributions[i].Get())\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport \"github.com\/kormoc\/unit\/datarate\"\nimport \"github.com\/ncw\/directio\"\nimport \"io\"\nimport \"os\"\nimport \"sync\"\nimport \"time\"\n\nvar workerIOJobs chan job\nvar workerIOJobswg sync.WaitGroup\n\nfunc initWorkerIO() {\n\tworkerIOJobs = make(chan job, workerCountIO*2)\n\tworkerIOJobswg.Add(workerCountIO)\n\tfor i := 0; i < workerCountIO; i++ {\n\t\tgo workerIO()\n\t}\n\tgo func() {\n\t\tworkerIOJobswg.Wait()\n\t\tclose(workerEndJobs)\n\n\t}()\n}\n\nfunc workerIO() {\n\tdefer workerIOJobswg.Done()\n\tfor currentJob := range workerIOJobs {\n\t\terr := func() error {\n\t\t\ttime_start := time.Now()\n\t\t\tTrace.Printf(\"%v: IO Processing...\\n\", currentJob.path)\n\t\t\t\/\/ Try direct io. Fail back to normal IO if needed\n\t\t\tfp, err := directio.OpenFile(currentJob.path, os.O_RDONLY, 0000)\n\t\t\tif err != nil {\n\t\t\t\tfp, err = os.OpenFile(currentJob.path, os.O_RDONLY, 0000)\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\tdefer fp.Close()\n\n\t\t\tbuffer := directio.AlignedBlock(directio.BlockSize * bufferSize)\n\t\t\ttotalRead := 0\n\n\t\t\tfor {\n\t\t\t\tamountRead, err := io.ReadAtLeast(fp, buffer, 0)\n\t\t\t\ttotalRead += amountRead\n\t\t\t\tif err == io.EOF {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tfor checksumAlgo := range currentJob.hashers {\n\t\t\t\t\tcurrentJob.hashers[checksumAlgo].Write(buffer[:amountRead])\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tduration := time.Since(time_start)\n\t\t\tcurrentJob.duration += duration\n\t\t\tcurrentJob.dataRate = datarate.NewDatarateSIBytes(datarate.Datarate(totalRead)*datarate.Byte, duration)\n\t\t\tTrace.Printf(\"%v: IO Processing took %v at %v\\n\", currentJob.path, duration, currentJob.dataRate)\n\t\t\tworkerEndJobs <- currentJob\n\t\t\treturn nil\n\t\t}()\n\n\t\tif err != nil {\n\t\t\tError.Printf(\"%v: IO Processing: %v\\n\", currentJob.path, err)\n\t\t}\n\t}\n}\n<commit_msg>Break on empty read<commit_after>package main\n\nimport \"github.com\/kormoc\/unit\/datarate\"\nimport \"github.com\/ncw\/directio\"\nimport \"io\"\nimport \"os\"\nimport \"sync\"\nimport \"time\"\n\nvar workerIOJobs chan job\nvar workerIOJobswg sync.WaitGroup\n\nfunc initWorkerIO() {\n\tworkerIOJobs = make(chan job, workerCountIO*2)\n\tworkerIOJobswg.Add(workerCountIO)\n\tfor i := 0; i < workerCountIO; i++ {\n\t\tgo workerIO()\n\t}\n\tgo func() {\n\t\tworkerIOJobswg.Wait()\n\t\tclose(workerEndJobs)\n\n\t}()\n}\n\nfunc workerIO() {\n\tdefer workerIOJobswg.Done()\n\tfor currentJob := range workerIOJobs {\n\t\terr := func() error {\n\t\t\ttime_start := time.Now()\n\t\t\tTrace.Printf(\"%v: IO Processing...\\n\", currentJob.path)\n\t\t\t\/\/ Try direct io. Fail back to normal IO if needed\n\t\t\tfp, err := directio.OpenFile(currentJob.path, os.O_RDONLY, 0000)\n\t\t\tif err != nil {\n\t\t\t\tfp, err = os.OpenFile(currentJob.path, os.O_RDONLY, 0000)\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\tdefer fp.Close()\n\n\t\t\tbuffer := directio.AlignedBlock(directio.BlockSize * bufferSize)\n\t\t\ttotalRead := 0\n\n\t\t\tfor {\n\t\t\t\tamountRead, err := io.ReadAtLeast(fp, buffer, 0)\n\t\t\t\ttotalRead += amountRead\n\t\t\t\tif err == io.EOF || amountRead == 0 {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tfor checksumAlgo := range currentJob.hashers {\n\t\t\t\t\tcurrentJob.hashers[checksumAlgo].Write(buffer[:amountRead])\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tduration := time.Since(time_start)\n\t\t\tcurrentJob.duration += duration\n\t\t\tcurrentJob.dataRate = datarate.NewDatarateSIBytes(datarate.Datarate(totalRead)*datarate.Byte, duration)\n\t\t\tTrace.Printf(\"%v: IO Processing took %v at %v\\n\", currentJob.path, duration, currentJob.dataRate)\n\t\t\tworkerEndJobs <- currentJob\n\t\t\treturn nil\n\t\t}()\n\n\t\tif err != nil {\n\t\t\tError.Printf(\"%v: IO Processing: %v\\n\", currentJob.path, err)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/stefanprodan\/syros\/models\"\n\t\"gopkg.in\/mgo.v2\"\n\t\"gopkg.in\/mgo.v2\/bson\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype Repository struct {\n\tConfig  *Config\n\tSession *mgo.Session\n}\n\nfunc NewRepository(config *Config) (*Repository, error) {\n\tcluster := strings.Split(config.MongoDB, \",\")\n\tdialInfo := &mgo.DialInfo{\n\t\tAddrs:    cluster,\n\t\tDatabase: config.Database,\n\t\tTimeout:  10 * time.Second,\n\t\tFailFast: true,\n\t}\n\n\tsession, err := mgo.DialWithInfo(dialInfo)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsession.SetMode(mgo.Monotonic, true)\n\n\trepo := &Repository{\n\t\tConfig:  config,\n\t\tSession: session,\n\t}\n\n\treturn repo, nil\n}\n\nfunc (repo *Repository) Initialize() {\n\trepo.CreateIndex(\"hosts\", \"environment\")\n\trepo.CreateIndex(\"hosts\", \"collected\")\n\trepo.CreateIndex(\"containers\", \"host_id\")\n\trepo.CreateIndex(\"containers\", \"environment\")\n\trepo.CreateIndex(\"containers\", \"collected\")\n\trepo.CreateIndex(\"checks\", \"host_id\")\n\trepo.CreateIndex(\"checks\", \"environment\")\n\trepo.CreateIndex(\"checks\", \"collected\")\n\trepo.CreateIndex(\"checks_log\", \"check_id\")\n\trepo.CreateIndex(\"checks_log\", \"begin\")\n\trepo.CreateIndex(\"checks_log\", \"end\")\n\trepo.CreateIndex(\"syros_services\", \"environment\")\n\trepo.CreateIndex(\"syros_services\", \"collected\")\n\trepo.CreateIndex(\"releases\", \"ticket_id\")\n\trepo.CreateIndex(\"deployments\", \"release_id\")\n}\n\nfunc (repo *Repository) CreateIndex(col string, index string) {\n\tc := repo.Session.DB(repo.Config.Database).C(col)\n\terr := c.EnsureIndexKey(index)\n\n\tif err != nil {\n\t\tlog.Fatalf(\"MongoDB index %v init failed %v\", index, err)\n\t}\n}\n\nfunc (repo *Repository) HostUpsert(host models.DockerHost) {\n\ts := repo.Session.Copy()\n\tdefer s.Close()\n\n\tc := s.DB(repo.Config.Database).C(\"hosts\")\n\n\t_, err := c.UpsertId(host.Id, &host)\n\tif err != nil {\n\t\tlog.Errorf(\"Repository hosts upsert failed %v\", err)\n\t}\n}\n\nfunc (repo *Repository) ContainerUpsert(container models.DockerContainer) {\n\ts := repo.Session.Copy()\n\tdefer s.Close()\n\n\tc := s.DB(repo.Config.Database).C(\"containers\")\n\n\t_, err := c.UpsertId(container.Id, &container)\n\tif err != nil {\n\t\tlog.Errorf(\"Repository containers upsert failed %v\", err)\n\t}\n}\n\nfunc (repo *Repository) ContainersUpsert(containers []models.DockerContainer) {\n\ts := repo.Session.Copy()\n\tdefer s.Close()\n\n\tc := s.DB(repo.Config.Database).C(\"containers\")\n\n\tfor _, container := range containers {\n\t\t_, err := c.UpsertId(container.Id, &container)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Repository containers upsert failed %v\", err)\n\t\t}\n\t}\n}\n\nfunc (repo *Repository) ChecksUpsert(checks []models.ConsulHealthCheck) {\n\ts := repo.Session.Copy()\n\tdefer s.Close()\n\n\tc := s.DB(repo.Config.Database).C(\"checks\")\n\n\tfor _, check := range checks {\n\t\tres := models.ConsulHealthCheck{}\n\t\terr := c.FindId(check.Id).One(&res)\n\t\tif err != nil {\n\t\t\t\/\/ insert check\n\t\t\tif err.Error() == \"not found\" {\n\t\t\t\tcheck.Since = check.Collected\n\t\t\t\terr = c.Insert(&check)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errorf(\"Repository checks insert failed %v\", err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlog.Errorf(\"Repository checks find by id failed %v\", err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ if status changed insert into logs and reset since\n\t\tif res.Status != check.Status {\n\t\t\tcheckLog := models.NewConsulHealthCheckLog(res, res.Since, check.Collected)\n\t\t\tl := s.DB(repo.Config.Database).C(\"checks_log\")\n\t\t\terr = l.Insert(&checkLog)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Repository checks_log insert failed %v\", err)\n\t\t\t}\n\t\t\tcheck.Since = check.Collected\n\t\t} else {\n\t\t\tcheck.Since = res.Since\n\t\t}\n\n\t\t\/\/ update check\n\t\t_, err = c.UpsertId(check.Id, &check)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Repository checks upsert failed %v\", err)\n\t\t}\n\t}\n}\n\nfunc (repo *Repository) SyrosServiceUpsert(service models.SyrosService) {\n\ts := repo.Session.Copy()\n\tdefer s.Close()\n\n\tc := s.DB(repo.Config.Database).C(\"syros_services\")\n\n\t_, err := c.UpsertId(service.Id, &service)\n\tif err != nil {\n\t\tlog.Errorf(\"Repository syros_services upsert failed %v\", err)\n\t}\n}\n\n\/\/ Removes stale records\nfunc (repo *Repository) RunGarbageCollector(cols []string) {\n\tif repo.Config.DatabaseStale > 0 {\n\t\tlog.Infof(\"Stating repository GC interval %v minutes\", repo.Config.DatabaseStale)\n\t\tgo func(stale int) {\n\n\t\t\tfor true {\n\t\t\t\ts := repo.Session.Copy()\n\t\t\t\tfor _, col := range cols {\n\t\t\t\t\tc := s.DB(repo.Config.Database).C(col)\n\t\t\t\t\tinfo, err := c.RemoveAll(\n\t\t\t\t\t\tbson.M{\n\t\t\t\t\t\t\t\"collected\": bson.M{\n\t\t\t\t\t\t\t\t\"$lt\": time.Now().Add(-time.Duration(stale) * time.Minute).UTC(),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t})\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Errorf(\"Repository GC for col %v query failed %v\", col, err)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif info.Removed > 0 {\n\t\t\t\t\t\t\tlog.Infof(\"Repository GC removed %v from %v\", info.Removed, col)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\ts.Close()\n\t\t\t\ttime.Sleep(60 * time.Second)\n\t\t\t}\n\n\t\t}(repo.Config.DatabaseStale)\n\t}\n}\n<commit_msg>run GC with a ticker<commit_after>package main\n\nimport (\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/stefanprodan\/syros\/models\"\n\t\"gopkg.in\/mgo.v2\"\n\t\"gopkg.in\/mgo.v2\/bson\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype Repository struct {\n\tConfig  *Config\n\tSession *mgo.Session\n}\n\nfunc NewRepository(config *Config) (*Repository, error) {\n\tcluster := strings.Split(config.MongoDB, \",\")\n\tdialInfo := &mgo.DialInfo{\n\t\tAddrs:    cluster,\n\t\tDatabase: config.Database,\n\t\tTimeout:  10 * time.Second,\n\t\tFailFast: true,\n\t}\n\n\tsession, err := mgo.DialWithInfo(dialInfo)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsession.SetMode(mgo.Monotonic, true)\n\n\trepo := &Repository{\n\t\tConfig:  config,\n\t\tSession: session,\n\t}\n\n\treturn repo, nil\n}\n\nfunc (repo *Repository) Initialize() {\n\trepo.CreateIndex(\"hosts\", \"environment\")\n\trepo.CreateIndex(\"hosts\", \"collected\")\n\trepo.CreateIndex(\"containers\", \"host_id\")\n\trepo.CreateIndex(\"containers\", \"environment\")\n\trepo.CreateIndex(\"containers\", \"collected\")\n\trepo.CreateIndex(\"checks\", \"host_id\")\n\trepo.CreateIndex(\"checks\", \"environment\")\n\trepo.CreateIndex(\"checks\", \"collected\")\n\trepo.CreateIndex(\"checks_log\", \"check_id\")\n\trepo.CreateIndex(\"checks_log\", \"begin\")\n\trepo.CreateIndex(\"checks_log\", \"end\")\n\trepo.CreateIndex(\"syros_services\", \"environment\")\n\trepo.CreateIndex(\"syros_services\", \"collected\")\n\trepo.CreateIndex(\"releases\", \"ticket_id\")\n\trepo.CreateIndex(\"deployments\", \"release_id\")\n}\n\nfunc (repo *Repository) CreateIndex(col string, index string) {\n\tc := repo.Session.DB(repo.Config.Database).C(col)\n\terr := c.EnsureIndexKey(index)\n\n\tif err != nil {\n\t\tlog.Fatalf(\"MongoDB index %v init failed %v\", index, err)\n\t}\n}\n\nfunc (repo *Repository) HostUpsert(host models.DockerHost) {\n\ts := repo.Session.Copy()\n\tdefer s.Close()\n\n\tc := s.DB(repo.Config.Database).C(\"hosts\")\n\n\t_, err := c.UpsertId(host.Id, &host)\n\tif err != nil {\n\t\tlog.Errorf(\"Repository hosts upsert failed %v\", err)\n\t}\n}\n\nfunc (repo *Repository) ContainerUpsert(container models.DockerContainer) {\n\ts := repo.Session.Copy()\n\tdefer s.Close()\n\n\tc := s.DB(repo.Config.Database).C(\"containers\")\n\n\t_, err := c.UpsertId(container.Id, &container)\n\tif err != nil {\n\t\tlog.Errorf(\"Repository containers upsert failed %v\", err)\n\t}\n}\n\nfunc (repo *Repository) ContainersUpsert(containers []models.DockerContainer) {\n\ts := repo.Session.Copy()\n\tdefer s.Close()\n\n\tc := s.DB(repo.Config.Database).C(\"containers\")\n\n\tfor _, container := range containers {\n\t\t_, err := c.UpsertId(container.Id, &container)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Repository containers upsert failed %v\", err)\n\t\t}\n\t}\n}\n\nfunc (repo *Repository) ChecksUpsert(checks []models.ConsulHealthCheck) {\n\ts := repo.Session.Copy()\n\tdefer s.Close()\n\n\tc := s.DB(repo.Config.Database).C(\"checks\")\n\n\tfor _, check := range checks {\n\t\tres := models.ConsulHealthCheck{}\n\t\terr := c.FindId(check.Id).One(&res)\n\t\tif err != nil {\n\t\t\t\/\/ insert check\n\t\t\tif err.Error() == \"not found\" {\n\t\t\t\tcheck.Since = check.Collected\n\t\t\t\terr = c.Insert(&check)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errorf(\"Repository checks insert failed %v\", err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlog.Errorf(\"Repository checks find by id failed %v\", err)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ if status changed insert into logs and reset since\n\t\tif res.Status != check.Status {\n\t\t\tcheckLog := models.NewConsulHealthCheckLog(res, res.Since, check.Collected)\n\t\t\tl := s.DB(repo.Config.Database).C(\"checks_log\")\n\t\t\terr = l.Insert(&checkLog)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Repository checks_log insert failed %v\", err)\n\t\t\t}\n\t\t\tcheck.Since = check.Collected\n\t\t} else {\n\t\t\tcheck.Since = res.Since\n\t\t}\n\n\t\t\/\/ update check\n\t\t_, err = c.UpsertId(check.Id, &check)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Repository checks upsert failed %v\", err)\n\t\t}\n\t}\n}\n\nfunc (repo *Repository) SyrosServiceUpsert(service models.SyrosService) {\n\ts := repo.Session.Copy()\n\tdefer s.Close()\n\n\tc := s.DB(repo.Config.Database).C(\"syros_services\")\n\n\t_, err := c.UpsertId(service.Id, &service)\n\tif err != nil {\n\t\tlog.Errorf(\"Repository syros_services upsert failed %v\", err)\n\t}\n}\n\n\/\/ Removes stale records\nfunc (repo *Repository) RunGarbageCollector(cols []string) {\n\tif repo.Config.DatabaseStale > 0 {\n\t\tticker := time.NewTicker(60 * time.Second)\n\t\tlog.Infof(\"Stating repository GC interval %v minutes\", repo.Config.DatabaseStale)\n\t\tgo func(stale int) {\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase <-ticker.C:\n\t\t\t\t\ts := repo.Session.Copy()\n\t\t\t\t\tfor _, col := range cols {\n\t\t\t\t\t\tc := s.DB(repo.Config.Database).C(col)\n\t\t\t\t\t\tinfo, err := c.RemoveAll(\n\t\t\t\t\t\t\tbson.M{\n\t\t\t\t\t\t\t\t\"collected\": bson.M{\n\t\t\t\t\t\t\t\t\t\"$lt\": time.Now().Add(-time.Duration(stale) * time.Minute).UTC(),\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tlog.Errorf(\"Repository GC for col %v query failed %v\", col, err)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tif info.Removed > 0 {\n\t\t\t\t\t\t\t\tlog.Infof(\"Repository GC removed %v from %v\", info.Removed, col)\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\ts.Close()\n\t\t\t\t}\n\t\t\t}\n\t\t}(repo.Config.DatabaseStale)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n\/\/ not use this file except in compliance with the License. A copy of the\n\/\/ License is located at\n\/\/\n\/\/\thttp:\/\/aws.amazon.com\/apache2.0\/\n\/\/\n\/\/ or in the \"license\" file accompanying this file. This file is distributed\n\/\/ on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n\/\/ express or implied. See the License for the specific language governing\n\/\/ permissions and limitations under the License.\n\npackage api\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n)\n\n\/\/ Implements Error & Retriable\ntype APIError struct {\n\terr       error\n\tRetriable bool\n}\n\ntype jsonError struct {\n\tErrType string `json:\"__type\"`\n\tMessage string `json:\"message\"`\n}\n\nfunc NewAPIError(err error) *APIError {\n\tintermediate := &jsonError{}\n\tif err := json.Unmarshal([]byte(err.Error()), intermediate); err == nil {\n\t\tif intermediate.ErrType == \"ClientException\" {\n\t\t\treturn &APIError{errors.New(intermediate.Message), false}\n\t\t}\n\t}\n\n\treturn &APIError{err, true}\n}\n\nfunc (sce *APIError) Retry() bool {\n\treturn sce.Retriable\n}\n\nfunc (sce *APIError) Error() string {\n\treturn sce.err.Error()\n}\n<commit_msg>Rename receiver<commit_after>\/\/ Copyright 2014-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n\/\/ not use this file except in compliance with the License. A copy of the\n\/\/ License is located at\n\/\/\n\/\/\thttp:\/\/aws.amazon.com\/apache2.0\/\n\/\/\n\/\/ or in the \"license\" file accompanying this file. This file is distributed\n\/\/ on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n\/\/ express or implied. See the License for the specific language governing\n\/\/ permissions and limitations under the License.\n\npackage api\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n)\n\n\/\/ Implements Error & Retriable\ntype APIError struct {\n\terr       error\n\tRetriable bool\n}\n\ntype jsonError struct {\n\tErrType string `json:\"__type\"`\n\tMessage string `json:\"message\"`\n}\n\nfunc NewAPIError(err error) *APIError {\n\tintermediate := &jsonError{}\n\tif err := json.Unmarshal([]byte(err.Error()), intermediate); err == nil {\n\t\tif intermediate.ErrType == \"ClientException\" {\n\t\t\treturn &APIError{errors.New(intermediate.Message), false}\n\t\t}\n\t}\n\n\treturn &APIError{err, true}\n}\n\nfunc (apiErr *APIError) Retry() bool {\n\treturn apiErr.Retriable\n}\n\nfunc (apiErr *APIError) Error() string {\n\treturn apiErr.err.Error()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2018 Cisco and\/or its affiliates.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at:\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"github.com\/networkservicemesh\/networkservicemesh\/controlplane\/pkg\/apis\/local\/connection\"\n\t\"github.com\/networkservicemesh\/networkservicemesh\/controlplane\/pkg\/nsmd\"\n\t\"github.com\/networkservicemesh\/networkservicemesh\/pkg\/tools\"\n\t\"github.com\/networkservicemesh\/networkservicemesh\/sdk\/client\"\n\t\"github.com\/opentracing\/opentracing-go\"\n\t\"github.com\/sirupsen\/logrus\"\n\t\"os\"\n\t\"sync\"\n)\n\nconst (\n\tdefaultVPPAgentEndpoint = \"localhost:9113\"\n)\n\ntype nsClientBackend struct {\n\tworkspace        string\n\tvppAgentEndpoint string\n}\n\nfunc (nscb *nsClientBackend) New() error {\n\tif err := Reset(nscb.vppAgentEndpoint); err != nil {\n\t\tlogrus.Fatal(err)\n\t}\n\tlogrus.Infof(\"workspace: %s\", nscb.workspace)\n\treturn nil\n}\n\nfunc (nscb *nsClientBackend) Connect(connection *connection.Connection) error {\n\tlogrus.Infof(\"nsClientBackend received: %v\", connection)\n\terr := CreateVppInterface(connection, nscb.workspace, nscb.vppAgentEndpoint)\n\tif err != nil {\n\t\tlogrus.Errorf(\"VPPAgent failed creating the requested interface with: %v\", err)\n\t}\n\treturn err\n}\n\nfunc main() {\n\t\/\/ Capture signals to cleanup before exiting\n\tc := tools.NewOSSignalChannel()\n\n\ttracer, closer := tools.InitJaeger(\"nsc\")\n\topentracing.SetGlobalTracer(tracer)\n\tdefer closer.Close()\n\n\tworkspace, ok := os.LookupEnv(nsmd.WorkspaceEnv)\n\tif !ok {\n\t\tlogrus.Fatalf(\"Failed gettign %s\", nsmd.WorkspaceEnv)\n\t}\n\n\tbackend := &nsClientBackend{\n\t\tworkspace:        workspace,\n\t\tvppAgentEndpoint: defaultVPPAgentEndpoint,\n\t}\n\n\tclient, err := client.NewNSMClient(nil, nil)\n\tif err != nil {\n\t\tlogrus.Fatalf(\"Unable to create the NSM client %v\", err)\n\t}\n\n\terr = backend.New()\n\tif err != nil {\n\t\tlogrus.Fatalf(\"Unable to create the backend %v\", err)\n\t}\n\n\tvar outgoingConnection *connection.Connection\n\toutgoingConnection, err = client.Connect(\"if1\", \"mem\", \"Primary interface\")\n\tif err != nil {\n\t\tlogrus.Fatalf(\"Unable to connect %v\", err)\n\t}\n\n\terr = backend.Connect(outgoingConnection)\n\tif err != nil {\n\t\tlogrus.Fatalf(\"Unable to connect %v\", err)\n\t}\n\n\tlogrus.Info(\"nsm client: initialization is completed successfully, wait for Ctrl+C...\")\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\n\t<-c\n}\n<commit_msg>Update nsc.go (#1052)<commit_after>\/\/ Copyright (c) 2018 Cisco and\/or its affiliates.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at:\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"github.com\/networkservicemesh\/networkservicemesh\/controlplane\/pkg\/apis\/local\/connection\"\n\t\"github.com\/networkservicemesh\/networkservicemesh\/controlplane\/pkg\/nsmd\"\n\t\"github.com\/networkservicemesh\/networkservicemesh\/pkg\/tools\"\n\t\"github.com\/networkservicemesh\/networkservicemesh\/sdk\/client\"\n\t\"github.com\/opentracing\/opentracing-go\"\n\t\"github.com\/sirupsen\/logrus\"\n\t\"os\"\n\t\"sync\"\n)\n\nconst (\n\tdefaultVPPAgentEndpoint = \"localhost:9113\"\n)\n\ntype nsClientBackend struct {\n\tworkspace        string\n\tvppAgentEndpoint string\n}\n\nfunc (nscb *nsClientBackend) New() error {\n\tif err := Reset(nscb.vppAgentEndpoint); err != nil {\n\t\tlogrus.Fatal(err)\n\t}\n\tlogrus.Infof(\"workspace: %s\", nscb.workspace)\n\treturn nil\n}\n\nfunc (nscb *nsClientBackend) Connect(connection *connection.Connection) error {\n\tlogrus.Infof(\"nsClientBackend received: %v\", connection)\n\terr := CreateVppInterface(connection, nscb.workspace, nscb.vppAgentEndpoint)\n\tif err != nil {\n\t\tlogrus.Errorf(\"VPPAgent failed creating the requested interface with: %v\", err)\n\t}\n\treturn err\n}\n\nfunc main() {\n\t\/\/ Capture signals to cleanup before exiting\n\tc := tools.NewOSSignalChannel()\n\n\ttracer, closer := tools.InitJaeger(\"nsc\")\n\topentracing.SetGlobalTracer(tracer)\n\tdefer closer.Close()\n\n\tworkspace, ok := os.LookupEnv(nsmd.WorkspaceEnv)\n\tif !ok {\n\t\tlogrus.Fatalf(\"Failed getting %s\", nsmd.WorkspaceEnv)\n\t}\n\n\tbackend := &nsClientBackend{\n\t\tworkspace:        workspace,\n\t\tvppAgentEndpoint: defaultVPPAgentEndpoint,\n\t}\n\n\tclient, err := client.NewNSMClient(nil, nil)\n\tif err != nil {\n\t\tlogrus.Fatalf(\"Unable to create the NSM client %v\", err)\n\t}\n\n\terr = backend.New()\n\tif err != nil {\n\t\tlogrus.Fatalf(\"Unable to create the backend %v\", err)\n\t}\n\n\tvar outgoingConnection *connection.Connection\n\toutgoingConnection, err = client.Connect(\"if1\", \"mem\", \"Primary interface\")\n\tif err != nil {\n\t\tlogrus.Fatalf(\"Unable to connect %v\", err)\n\t}\n\n\terr = backend.Connect(outgoingConnection)\n\tif err != nil {\n\t\tlogrus.Fatalf(\"Unable to connect %v\", err)\n\t}\n\n\tlogrus.Info(\"nsm client: initialization is completed successfully, wait for Ctrl+C...\")\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\n\t<-c\n}\n<|endoftext|>"}
{"text":"<commit_before>package control\n\nimport (\n\t\"TOGY\/util\"\n\t\"os\/exec\"\n)\n\n\/\/ Starts PowerPoint in presentation mode.\nfunc StartPresentation(ppExe, path string) error {\n\terr := exec.Command(ppExe, \"\/s\", path).Start()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/Sends Terminate signal to PowerPoint.\nfunc KillPresentation() {\n\texec.Command(\"taskkill\", \"\/IM\", \"POWERPNT.exe\").Run()\n}\n\n\/\/Kills powerpoint and loads presentation at p.\nfunc ReloadPresentation(ppExe, p string) {\n\tKillPresentation()\n\tutil.Sleep(1)\n\tStartPresentation(ppExe, p)\n}\n<commit_msg>Reworked powerpoint API to use Broadcast interface<commit_after>package control\n\nimport (\n\t\"TOGY\/util\"\n\t\"os\/exec\"\n)\n\ntype PowerPointBroadcast struct {\n\t\/\/Path to the presentation\n\tpath string\n\t\/\/Path to PowerPoint executable\n\tpowerPoint string\n\t\/\/Current running PowerPoint instance\n\tcmd exec.Cmd\n}\n\n\/\/ Starts PowerPoint in presentation mode.\nfunc (*PowerPointBroadcast b) Start() error {\n\tcmd := exec.Command(b.powerPoint, \"\/s\", b.path)\n\terr = cmd.start()\n\tif err != nil {\n\t\treturn err\n\t}\n\tb.cmd = cmd\n\treturn nil\n}\n\n\/\/Sends Terminate signal to PowerPoint.\nfunc (*PowerPointBroadcast b) Kill() error {\n\terr = b.cmd.Process.Kill()\n\tif err != nil {\n\t\treturn err\n\t}\n\tb.cmd = nil\n\treturn\n}\n\nfunc (PowerPointBroadcast b) Status() bool {\n\tif b.cmd == nil {\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc NewPowerPoint(ppExe, presentation string) (*PowerPointBroadcast) {\n\treturn &PowerPointBroadcast{path: presentation, powerPoint: ppExe}\n}<|endoftext|>"}
{"text":"<commit_before>package routing\n\nimport (\n\t\"bytes\"\n\n\t\"github.com\/btcsuite\/btcd\/btcec\"\n\t\"github.com\/btcsuite\/btcd\/chaincfg\/chainhash\"\n\t\"github.com\/btcsuite\/btcutil\"\n\t\"github.com\/davecgh\/go-spew\/spew\"\n\t\"github.com\/go-errors\/errors\"\n\t\"github.com\/lightningnetwork\/lnd\/lnwire\"\n)\n\n\/\/ ValidateChannelAnn validates the channel announcement message and checks\n\/\/ that node signatures covers the announcement message, and that the bitcoin\n\/\/ signatures covers the node keys.\nfunc ValidateChannelAnn(a *lnwire.ChannelAnnouncement) error {\n\t\/\/ First, we'll compute the digest (h) which is to be signed by each of\n\t\/\/ the keys included within the node announcement message. This hash\n\t\/\/ digest includes all the keys, so the (up to 4 signatures) will\n\t\/\/ attest to the validity of each of the keys.\n\tdata, err := a.DataToSign()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdataHash := chainhash.DoubleHashB(data)\n\n\t\/\/ First we'll verify that the passed bitcoin key signature is indeed a\n\t\/\/ signature over the computed hash digest.\n\tbitcoinSig1, err := a.BitcoinSig1.ToSignature()\n\tif err != nil {\n\t\treturn err\n\t}\n\tbitcoinKey1, err := btcec.ParsePubKey(a.BitcoinKey1[:], btcec.S256())\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !bitcoinSig1.Verify(dataHash, bitcoinKey1) {\n\t\treturn errors.New(\"can't verify first bitcoin signature\")\n\t}\n\n\t\/\/ If that checks out, then we'll verify that the second bitcoin\n\t\/\/ signature is a valid signature of the bitcoin public key over hash\n\t\/\/ digest as well.\n\tbitcoinSig2, err := a.BitcoinSig2.ToSignature()\n\tif err != nil {\n\t\treturn err\n\t}\n\tbitcoinKey2, err := btcec.ParsePubKey(a.BitcoinKey2[:], btcec.S256())\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !bitcoinSig2.Verify(dataHash, bitcoinKey2) {\n\t\treturn errors.New(\"can't verify second bitcoin signature\")\n\t}\n\n\t\/\/ Both node signatures attached should indeed be a valid signature\n\t\/\/ over the selected digest of the channel announcement signature.\n\tnodeSig1, err := a.NodeSig1.ToSignature()\n\tif err != nil {\n\t\treturn err\n\t}\n\tnodeKey1, err := btcec.ParsePubKey(a.NodeID1[:], btcec.S256())\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !nodeSig1.Verify(dataHash, nodeKey1) {\n\t\treturn errors.New(\"can't verify data in first node signature\")\n\t}\n\n\tnodeSig2, err := a.NodeSig2.ToSignature()\n\tif err != nil {\n\t\treturn err\n\t}\n\tnodeKey2, err := btcec.ParsePubKey(a.NodeID2[:], btcec.S256())\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !nodeSig2.Verify(dataHash, nodeKey2) {\n\t\treturn errors.New(\"can't verify data in second node signature\")\n\t}\n\n\treturn nil\n\n}\n\n\/\/ ValidateNodeAnn validates the node announcement by ensuring that the\n\/\/ attached signature is needed a signature of the node announcement under the\n\/\/ specified node public key.\nfunc ValidateNodeAnn(a *lnwire.NodeAnnouncement) error {\n\t\/\/ Reconstruct the data of announcement which should be covered by the\n\t\/\/ signature so we can verify the signature shortly below\n\tdata, err := a.DataToSign()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnodeSig, err := a.Signature.ToSignature()\n\tif err != nil {\n\t\treturn err\n\t}\n\tnodeKey, err := btcec.ParsePubKey(a.NodeID[:], btcec.S256())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Finally ensure that the passed signature is valid, if not we'll\n\t\/\/ return an error so this node announcement can be rejected.\n\tdataHash := chainhash.DoubleHashB(data)\n\tif !nodeSig.Verify(dataHash, nodeKey) {\n\t\tvar msgBuf bytes.Buffer\n\t\tif _, err := lnwire.WriteMessage(&msgBuf, a, 0); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn errors.Errorf(\"signature on NodeAnnouncement(%x) is \"+\n\t\t\t\"invalid: %x\", nodeKey.SerializeCompressed(),\n\t\t\tmsgBuf.Bytes())\n\t}\n\n\treturn nil\n}\n\n\/\/ ValidateChannelUpdateAnn validates the channel update announcement by\n\/\/ checking (1) that the included signature covers the announcement and has been\n\/\/ signed by the node's private key, and (2) that the announcement's message\n\/\/ flags and optional fields are sane.\nfunc ValidateChannelUpdateAnn(pubKey *btcec.PublicKey, capacity btcutil.Amount,\n\ta *lnwire.ChannelUpdate) error {\n\n\tif err := validateOptionalFields(capacity, a); err != nil {\n\t\treturn err\n\t}\n\n\tdata, err := a.DataToSign()\n\tif err != nil {\n\t\treturn errors.Errorf(\"unable to reconstruct message: %v\", err)\n\t}\n\tdataHash := chainhash.DoubleHashB(data)\n\n\tnodeSig, err := a.Signature.ToSignature()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !nodeSig.Verify(dataHash, pubKey) {\n\t\treturn errors.Errorf(\"invalid signature for channel \"+\n\t\t\t\"update %v\", spew.Sdump(a))\n\t}\n\n\treturn nil\n}\n\n\/\/ validateOptionalFields validates a channel update's message flags and\n\/\/ corresponding update fields.\nfunc validateOptionalFields(capacity btcutil.Amount,\n\tmsg *lnwire.ChannelUpdate) error {\n\n\tif msg.MessageFlags.HasMaxHtlc() {\n\t\tmaxHtlc := msg.HtlcMaximumMsat\n\t\tif maxHtlc == 0 || maxHtlc < msg.HtlcMinimumMsat {\n\t\t\treturn errors.Errorf(\"invalid max htlc for channel \"+\n\t\t\t\t\"update %v\", spew.Sdump(msg))\n\t\t}\n\t\tcap := lnwire.NewMSatFromSatoshis(capacity)\n\t\tif maxHtlc > cap {\n\t\t\treturn errors.Errorf(\"max_htlc(%v) for channel \"+\n\t\t\t\t\"update greater than capacity(%v)\", maxHtlc,\n\t\t\t\tcap)\n\t\t}\n\t}\n\n\treturn nil\n}\n<commit_msg>routing: expose VerifyChannelUpdateSignature function<commit_after>package routing\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\n\t\"github.com\/btcsuite\/btcd\/btcec\"\n\t\"github.com\/btcsuite\/btcd\/chaincfg\/chainhash\"\n\t\"github.com\/btcsuite\/btcutil\"\n\t\"github.com\/davecgh\/go-spew\/spew\"\n\t\"github.com\/go-errors\/errors\"\n\t\"github.com\/lightningnetwork\/lnd\/lnwire\"\n)\n\n\/\/ ValidateChannelAnn validates the channel announcement message and checks\n\/\/ that node signatures covers the announcement message, and that the bitcoin\n\/\/ signatures covers the node keys.\nfunc ValidateChannelAnn(a *lnwire.ChannelAnnouncement) error {\n\t\/\/ First, we'll compute the digest (h) which is to be signed by each of\n\t\/\/ the keys included within the node announcement message. This hash\n\t\/\/ digest includes all the keys, so the (up to 4 signatures) will\n\t\/\/ attest to the validity of each of the keys.\n\tdata, err := a.DataToSign()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdataHash := chainhash.DoubleHashB(data)\n\n\t\/\/ First we'll verify that the passed bitcoin key signature is indeed a\n\t\/\/ signature over the computed hash digest.\n\tbitcoinSig1, err := a.BitcoinSig1.ToSignature()\n\tif err != nil {\n\t\treturn err\n\t}\n\tbitcoinKey1, err := btcec.ParsePubKey(a.BitcoinKey1[:], btcec.S256())\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !bitcoinSig1.Verify(dataHash, bitcoinKey1) {\n\t\treturn errors.New(\"can't verify first bitcoin signature\")\n\t}\n\n\t\/\/ If that checks out, then we'll verify that the second bitcoin\n\t\/\/ signature is a valid signature of the bitcoin public key over hash\n\t\/\/ digest as well.\n\tbitcoinSig2, err := a.BitcoinSig2.ToSignature()\n\tif err != nil {\n\t\treturn err\n\t}\n\tbitcoinKey2, err := btcec.ParsePubKey(a.BitcoinKey2[:], btcec.S256())\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !bitcoinSig2.Verify(dataHash, bitcoinKey2) {\n\t\treturn errors.New(\"can't verify second bitcoin signature\")\n\t}\n\n\t\/\/ Both node signatures attached should indeed be a valid signature\n\t\/\/ over the selected digest of the channel announcement signature.\n\tnodeSig1, err := a.NodeSig1.ToSignature()\n\tif err != nil {\n\t\treturn err\n\t}\n\tnodeKey1, err := btcec.ParsePubKey(a.NodeID1[:], btcec.S256())\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !nodeSig1.Verify(dataHash, nodeKey1) {\n\t\treturn errors.New(\"can't verify data in first node signature\")\n\t}\n\n\tnodeSig2, err := a.NodeSig2.ToSignature()\n\tif err != nil {\n\t\treturn err\n\t}\n\tnodeKey2, err := btcec.ParsePubKey(a.NodeID2[:], btcec.S256())\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !nodeSig2.Verify(dataHash, nodeKey2) {\n\t\treturn errors.New(\"can't verify data in second node signature\")\n\t}\n\n\treturn nil\n\n}\n\n\/\/ ValidateNodeAnn validates the node announcement by ensuring that the\n\/\/ attached signature is needed a signature of the node announcement under the\n\/\/ specified node public key.\nfunc ValidateNodeAnn(a *lnwire.NodeAnnouncement) error {\n\t\/\/ Reconstruct the data of announcement which should be covered by the\n\t\/\/ signature so we can verify the signature shortly below\n\tdata, err := a.DataToSign()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnodeSig, err := a.Signature.ToSignature()\n\tif err != nil {\n\t\treturn err\n\t}\n\tnodeKey, err := btcec.ParsePubKey(a.NodeID[:], btcec.S256())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Finally ensure that the passed signature is valid, if not we'll\n\t\/\/ return an error so this node announcement can be rejected.\n\tdataHash := chainhash.DoubleHashB(data)\n\tif !nodeSig.Verify(dataHash, nodeKey) {\n\t\tvar msgBuf bytes.Buffer\n\t\tif _, err := lnwire.WriteMessage(&msgBuf, a, 0); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn errors.Errorf(\"signature on NodeAnnouncement(%x) is \"+\n\t\t\t\"invalid: %x\", nodeKey.SerializeCompressed(),\n\t\t\tmsgBuf.Bytes())\n\t}\n\n\treturn nil\n}\n\n\/\/ ValidateChannelUpdateAnn validates the channel update announcement by\n\/\/ checking (1) that the included signature covers the announcement and has been\n\/\/ signed by the node's private key, and (2) that the announcement's message\n\/\/ flags and optional fields are sane.\nfunc ValidateChannelUpdateAnn(pubKey *btcec.PublicKey, capacity btcutil.Amount,\n\ta *lnwire.ChannelUpdate) error {\n\n\tif err := validateOptionalFields(capacity, a); err != nil {\n\t\treturn err\n\t}\n\n\treturn VerifyChannelUpdateSignature(a, pubKey)\n}\n\n\/\/ VerifyChannelUpdateSignature verifies that the channel update message was\n\/\/ signed by the party with the given node public key.\nfunc VerifyChannelUpdateSignature(msg *lnwire.ChannelUpdate,\n\tpubKey *btcec.PublicKey) error {\n\n\tdata, err := msg.DataToSign()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to reconstruct message data: %v\", err)\n\t}\n\tdataHash := chainhash.DoubleHashB(data)\n\n\tnodeSig, err := msg.Signature.ToSignature()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !nodeSig.Verify(dataHash, pubKey) {\n\t\treturn fmt.Errorf(\"invalid signature for channel update %v\",\n\t\t\tspew.Sdump(msg))\n\t}\n\n\treturn nil\n}\n\n\/\/ validateOptionalFields validates a channel update's message flags and\n\/\/ corresponding update fields.\nfunc validateOptionalFields(capacity btcutil.Amount,\n\tmsg *lnwire.ChannelUpdate) error {\n\n\tif msg.MessageFlags.HasMaxHtlc() {\n\t\tmaxHtlc := msg.HtlcMaximumMsat\n\t\tif maxHtlc == 0 || maxHtlc < msg.HtlcMinimumMsat {\n\t\t\treturn errors.Errorf(\"invalid max htlc for channel \"+\n\t\t\t\t\"update %v\", spew.Sdump(msg))\n\t\t}\n\t\tcap := lnwire.NewMSatFromSatoshis(capacity)\n\t\tif maxHtlc > cap {\n\t\t\treturn errors.Errorf(\"max_htlc(%v) for channel \"+\n\t\t\t\t\"update greater than capacity(%v)\", maxHtlc,\n\t\t\t\tcap)\n\t\t}\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package kite\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/op\/go-logging\"\n\t\"koding\/newkite\/dnode\/rpc\"\n\t\"koding\/newkite\/protocol\"\n\t\"koding\/newkite\/utils\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"runtime\"\n\t\"syscall\"\n\t\"time\"\n)\n\nfunc init() {\n\t\/\/ Use all available CPUS.\n\truntime.GOMAXPROCS(runtime.NumCPU())\n\n\t\/\/ Debugging helper: Prints stacktrace on SIGUSR1.\n\tc := make(chan os.Signal)\n\tsignal.Notify(c, syscall.SIGUSR1)\n\tgo func() {\n\t\tfor {\n\t\t\ts := <-c\n\t\t\tfmt.Println(\"Got signal:\", s)\n\t\t\tbuf := make([]byte, 1<<16)\n\t\t\truntime.Stack(buf, true)\n\t\t\tfmt.Println(string(buf))\n\t\t\tfmt.Print(\"Number of goroutines:\", runtime.NumGoroutine())\n\t\t\tm := new(runtime.MemStats)\n\t\t\truntime.GC()\n\t\t\truntime.ReadMemStats(m)\n\t\t\tfmt.Printf(\", Memory allocated: %+v\\n\", m.Alloc)\n\t\t}\n\t}()\n}\n\n\/\/ Kite defines a single process that enables distributed service messaging\n\/\/ amongst the peers it is connected. A Kite process acts as a Client and as a\n\/\/ Server. That means it can receive request, process them, but it also can\n\/\/ make request to other kites. A Kite can be anything. It can be simple Image\n\/\/ processing kite (which would process data), it could be a Chat kite that\n\/\/ enables peer-to-peer chat. For examples we have FileSystem kite that expose\n\/\/ the file system to a client, which in order build the filetree.\ntype Kite struct {\n\tprotocol.Kite\n\n\t\/\/ KodingKey is used for authenticate to Kontrol.\n\tKodingKey string\n\n\t\/\/ Is this Kite Public or Private? Default is Private.\n\tVisibility protocol.Visibility\n\n\t\/\/ Points to the Kontrol instance if enabled\n\tKontrol *Kontrol\n\n\t\/\/ Wheter we want to connect to Kontrol on startup, true by default.\n\tKontrolEnabled bool\n\n\t\/\/ Wheter we want to register our Kite to Kontrol, true by default.\n\tRegisterToKontrol bool\n\n\t\/\/ method map for exported methods\n\thandlers map[string]HandlerFunc\n\n\t\/\/ Dnode rpc server\n\tserver *rpc.Server\n\n\t\/\/ Handlers to call when a Kite opens a connection to this Kite.\n\tonConnectHandlers []func(*RemoteKite)\n\n\t\/\/ Handlers to call when a client has disconnected.\n\tonDisconnectHandlers []func(*RemoteKite)\n\n\t\/\/ Contains different functions for authenticating user from request.\n\t\/\/ Keys are the authentication types (options.authentication.type).\n\tAuthenticators map[string]func(*Request) error\n\n\t\/\/ Used to signal if the kite is ready to start and make calls to\n\t\/\/ other kites.\n\tready chan bool\n\n\t\/\/ Prints logging messages to stderr and syslog.\n\tLog *logging.Logger\n}\n\n\/\/ New creates, initialize and then returns a new Kite instance. It accepts\n\/\/ a single options argument that is a config struct that needs to be filled\n\/\/ with several informations like Name, Port, IP and so on.\nfunc New(options *Options) *Kite {\n\tvar err error\n\tif options == nil {\n\t\toptions, err = ReadKiteOptions(\"manifest.json\")\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"error: could not read config file\", err)\n\t\t}\n\t}\n\n\toptions.validate() \/\/ exits if validating fails\n\n\thostname, _ := os.Hostname()\n\tkiteID := utils.GenerateUUID()\n\tkodingKey, err := utils.GetKodingKey()\n\tif err != nil {\n\t\tlog.Fatal(\"Couldn't find koding.key. Please run 'kd register'.\")\n\t}\n\n\tk := &Kite{\n\t\tKite: protocol.Kite{\n\t\t\tName:        options.Kitename,\n\t\t\tUsername:    options.Username,\n\t\t\tID:          kiteID,\n\t\t\tVersion:     options.Version,\n\t\t\tHostname:    hostname,\n\t\t\tPort:        options.Port,\n\t\t\tEnvironment: options.Environment,\n\t\t\tRegion:      options.Region,\n\t\t\tVisibility:  options.Visibility,\n\n\t\t\t\/\/ PublicIP will be set by Kontrol after registering if it is not set.\n\t\t\tPublicIP: options.PublicIP,\n\t\t},\n\t\tKodingKey:         kodingKey,\n\t\tserver:            rpc.NewServer(),\n\t\tKontrolEnabled:    true,\n\t\tRegisterToKontrol: true,\n\t\tAuthenticators:    make(map[string]func(*Request) error),\n\t\thandlers:          make(map[string]HandlerFunc),\n\t\tready:             make(chan bool),\n\t}\n\n\tk.Log = newLogger(k.Name, k.hasDebugFlag())\n\tk.Kontrol = k.NewKontrol(options.KontrolAddr)\n\n\t\/\/ Call registered handlers when a client has disconnected.\n\tk.server.OnDisconnect(func(c *rpc.Client) {\n\t\tif r, ok := c.Properties()[\"remoteKite\"]; ok {\n\t\t\t\/\/ Run OnDisconnect handlers.\n\t\t\tk.notifyRemoteKiteDisconnected(r.(*RemoteKite))\n\t\t}\n\t})\n\n\t\/\/ Every kite should be able to authenticate the user from token.\n\tk.Authenticators[\"token\"] = k.AuthenticateFromToken\n\t\/\/ A kite accepts requests from Kontrol.\n\tk.Authenticators[\"kodingKey\"] = k.AuthenticateFromKodingKey\n\n\t\/\/ Register our internal methods\n\tk.HandleFunc(\"systemInfo\", new(Status).Info)\n\tk.HandleFunc(\"heartbeat\", k.handleHeartbeat)\n\tk.HandleFunc(\"log\", k.handleLog)\n\n\treturn k\n}\n\n\/\/ Run is a blocking method. It runs the kite server and then accepts requests\n\/\/ asynchronously.\nfunc (k *Kite) Run() {\n\tk.Start()\n\tselect {}\n}\n\n\/\/ Start is like Run(), but does not wait for it to complete. It's nonblocking.\nfunc (k *Kite) Start() {\n\tk.parseVersionFlag()\n\n\tgo func() {\n\t\terr := k.listenAndServe()\n\t\tif err != nil {\n\t\t\tk.Log.Fatal(err)\n\t\t}\n\t}()\n\n\t<-k.ready \/\/ wait until we are ready\n}\n\nfunc (k *Kite) handleHeartbeat(r *Request) (interface{}, error) {\n\targs := r.Args.MustSliceOfLength(2)\n\tseconds := args[0].MustFloat64()\n\tping := args[1].MustFunction()\n\n\tgo func() {\n\t\tfor {\n\t\t\ttime.Sleep(time.Duration(seconds) * time.Second)\n\t\t\tif ping() != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn nil, nil\n}\n\n\/\/ handleLog prints a log message to stdout.\nfunc (k *Kite) handleLog(r *Request) (interface{}, error) {\n\tmsg := r.Args.MustString()\n\tk.Log.Info(fmt.Sprintf(\"%s: %s\", r.RemoteKite.Name, msg))\n\treturn nil, nil\n}\n\nfunc init() {\n\t\/\/ These logging related stuff needs to be called once because stupid\n\t\/\/ logging library uses global variables and resets the backends every time.\n\tlogging.SetFormatter(logging.MustStringFormatter(\"%{level:-8s} ▶ %{message}\"))\n\tstderrBackend := logging.NewLogBackend(os.Stderr, \"\", log.LstdFlags)\n\tstderrBackend.Color = true\n\tsyslogBackend, _ := logging.NewSyslogBackend(\"\")\n\tlogging.SetBackend(stderrBackend, syslogBackend)\n}\n\n\/\/ newLogger returns a new logger object for desired name and level.\nfunc newLogger(name string, debug bool) *logging.Logger {\n\tlogger := logging.MustGetLogger(name)\n\n\tlevel := logging.INFO\n\tif debug {\n\t\tlevel = logging.DEBUG\n\t}\n\n\tlogging.SetLevel(level, name)\n\treturn logger\n}\n\n\/\/ If the user wants to call flag.Parse() the flag must be defined in advance.\nvar _ = flag.Bool(\"version\", false, \"show version\")\nvar _ = flag.Bool(\"debug\", false, \"print debug logs\")\n\n\/\/ parseVersionFlag prints the version number of the kite and exits with 0\n\/\/ if \"-version\" flag is enabled.\n\/\/ We did not use the \"flag\" package because it causes trouble if the user\n\/\/ also calls \"flag.Parse()\" in his code. flag.Parse() can be called only once.\nfunc (k *Kite) parseVersionFlag() {\n\tfor _, flag := range os.Args {\n\t\tif flag == \"-version\" {\n\t\t\tfmt.Println(k.Version)\n\t\t\tos.Exit(0)\n\t\t}\n\t}\n}\n\n\/\/ hasDebugFlag returns true if -debug flag is present in os.Args.\nfunc (k *Kite) hasDebugFlag() bool {\n\tfor _, flag := range os.Args {\n\t\tif flag == \"-debug\" {\n\t\t\treturn true\n\t\t}\n\t}\n\n\t\/\/ We can't use flags when running \"go test\" command.\n\t\/\/ This is another way to print debug logs.\n\tif os.Getenv(\"DEBUG\") != \"\" {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n\/\/ listenAndServe starts our rpc server with the given addr.\nfunc (k *Kite) listenAndServe() error {\n\tlistener, err := net.Listen(\"tcp4\", \":\"+k.Port)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tk.Log.Info(\"Listening: %s\", listener.Addr().String())\n\n\t\/\/ Port is known here if \"0\" is used as port number\n\t_, k.Port, _ = net.SplitHostPort(listener.Addr().String())\n\n\t\/\/ We must connect to Kontrol after starting to listen on port\n\tif k.KontrolEnabled {\n\t\tif k.RegisterToKontrol {\n\t\t\tk.Kontrol.OnConnect(k.registerToKontrol)\n\t\t}\n\n\t\tk.Kontrol.DialForever()\n\t}\n\n\tk.ready <- true \/\/ listener is ready, means we are ready too\n\treturn http.Serve(listener, k.server)\n}\n\nfunc (k *Kite) registerToKontrol() {\n\terr := k.Kontrol.Register()\n\tif err != nil {\n\t\tk.Log.Fatalf(\"Cannot register to Kontrol: %s\", err)\n\t}\n}\n\n\/\/ OnConnect registers a function to run when a Kite connects to this Kite.\nfunc (k *Kite) OnConnect(handler func(*RemoteKite)) {\n\tk.onConnectHandlers = append(k.onConnectHandlers, handler)\n}\n\n\/\/ OnDisconnect registers a function to run when a connected Kite is disconnected.\nfunc (k *Kite) OnDisconnect(handler func(*RemoteKite)) {\n\tk.onDisconnectHandlers = append(k.onDisconnectHandlers, handler)\n}\n\n\/\/ notifyRemoteKiteConnected runs the registered handlers with OnConnect().\nfunc (k *Kite) notifyRemoteKiteConnected(r *RemoteKite) {\n\tk.Log.Info(\"Client is connected to us: [%s %s]\", r.Name, r.Addr())\n\n\tfor _, handler := range k.onConnectHandlers {\n\t\tgo handler(r)\n\t}\n}\n\nfunc (k *Kite) notifyRemoteKiteDisconnected(r *RemoteKite) {\n\tk.Log.Info(\"Client has disconnected: [%s %s]\", r.Name, r.Addr())\n\n\tfor _, handler := range k.onDisconnectHandlers {\n\t\tgo handler(r)\n\t}\n}\n<commit_msg>kite: add Kite.Close() method<commit_after>package kite\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/op\/go-logging\"\n\t\"koding\/newkite\/dnode\/rpc\"\n\t\"koding\/newkite\/protocol\"\n\t\"koding\/newkite\/utils\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"runtime\"\n\t\"strings\"\n\t\"syscall\"\n\t\"time\"\n)\n\nfunc init() {\n\t\/\/ Use all available CPUS.\n\truntime.GOMAXPROCS(runtime.NumCPU())\n\n\t\/\/ Debugging helper: Prints stacktrace on SIGUSR1.\n\tc := make(chan os.Signal)\n\tsignal.Notify(c, syscall.SIGUSR1)\n\tgo func() {\n\t\tfor {\n\t\t\ts := <-c\n\t\t\tfmt.Println(\"Got signal:\", s)\n\t\t\tbuf := make([]byte, 1<<16)\n\t\t\truntime.Stack(buf, true)\n\t\t\tfmt.Println(string(buf))\n\t\t\tfmt.Print(\"Number of goroutines:\", runtime.NumGoroutine())\n\t\t\tm := new(runtime.MemStats)\n\t\t\truntime.GC()\n\t\t\truntime.ReadMemStats(m)\n\t\t\tfmt.Printf(\", Memory allocated: %+v\\n\", m.Alloc)\n\t\t}\n\t}()\n}\n\n\/\/ Kite defines a single process that enables distributed service messaging\n\/\/ amongst the peers it is connected. A Kite process acts as a Client and as a\n\/\/ Server. That means it can receive request, process them, but it also can\n\/\/ make request to other kites. A Kite can be anything. It can be simple Image\n\/\/ processing kite (which would process data), it could be a Chat kite that\n\/\/ enables peer-to-peer chat. For examples we have FileSystem kite that expose\n\/\/ the file system to a client, which in order build the filetree.\ntype Kite struct {\n\tprotocol.Kite\n\n\t\/\/ KodingKey is used for authenticate to Kontrol.\n\tKodingKey string\n\n\t\/\/ Is this Kite Public or Private? Default is Private.\n\tVisibility protocol.Visibility\n\n\t\/\/ Points to the Kontrol instance if enabled\n\tKontrol *Kontrol\n\n\t\/\/ Wheter we want to connect to Kontrol on startup, true by default.\n\tKontrolEnabled bool\n\n\t\/\/ Wheter we want to register our Kite to Kontrol, true by default.\n\tRegisterToKontrol bool\n\n\t\/\/ method map for exported methods\n\thandlers map[string]HandlerFunc\n\n\t\/\/ Dnode rpc server\n\tserver *rpc.Server\n\n\tlistener net.Listener\n\n\t\/\/ Handlers to call when a Kite opens a connection to this Kite.\n\tonConnectHandlers []func(*RemoteKite)\n\n\t\/\/ Handlers to call when a client has disconnected.\n\tonDisconnectHandlers []func(*RemoteKite)\n\n\t\/\/ Contains different functions for authenticating user from request.\n\t\/\/ Keys are the authentication types (options.authentication.type).\n\tAuthenticators map[string]func(*Request) error\n\n\t\/\/ Used to signal if the kite is ready to start and make calls to\n\t\/\/ other kites.\n\tready chan bool\n\tend   chan bool\n\n\t\/\/ Prints logging messages to stderr and syslog.\n\tLog *logging.Logger\n}\n\n\/\/ New creates, initialize and then returns a new Kite instance. It accepts\n\/\/ a single options argument that is a config struct that needs to be filled\n\/\/ with several informations like Name, Port, IP and so on.\nfunc New(options *Options) *Kite {\n\tvar err error\n\tif options == nil {\n\t\toptions, err = ReadKiteOptions(\"manifest.json\")\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"error: could not read config file\", err)\n\t\t}\n\t}\n\n\toptions.validate() \/\/ exits if validating fails\n\n\thostname, _ := os.Hostname()\n\tkiteID := utils.GenerateUUID()\n\tkodingKey, err := utils.GetKodingKey()\n\tif err != nil {\n\t\tlog.Fatal(\"Couldn't find koding.key. Please run 'kd register'.\")\n\t}\n\n\tk := &Kite{\n\t\tKite: protocol.Kite{\n\t\t\tName:        options.Kitename,\n\t\t\tUsername:    options.Username,\n\t\t\tID:          kiteID,\n\t\t\tVersion:     options.Version,\n\t\t\tHostname:    hostname,\n\t\t\tPort:        options.Port,\n\t\t\tEnvironment: options.Environment,\n\t\t\tRegion:      options.Region,\n\t\t\tVisibility:  options.Visibility,\n\n\t\t\t\/\/ PublicIP will be set by Kontrol after registering if it is not set.\n\t\t\tPublicIP: options.PublicIP,\n\t\t},\n\t\tKodingKey:         kodingKey,\n\t\tserver:            rpc.NewServer(),\n\t\tKontrolEnabled:    true,\n\t\tRegisterToKontrol: true,\n\t\tAuthenticators:    make(map[string]func(*Request) error),\n\t\thandlers:          make(map[string]HandlerFunc),\n\t\tready:             make(chan bool),\n\t\tend:               make(chan bool, 1),\n\t}\n\n\tk.Log = newLogger(k.Name, k.hasDebugFlag())\n\tk.Kontrol = k.NewKontrol(options.KontrolAddr)\n\n\t\/\/ Call registered handlers when a client has disconnected.\n\tk.server.OnDisconnect(func(c *rpc.Client) {\n\t\tif r, ok := c.Properties()[\"remoteKite\"]; ok {\n\t\t\t\/\/ Run OnDisconnect handlers.\n\t\t\tk.notifyRemoteKiteDisconnected(r.(*RemoteKite))\n\t\t}\n\t})\n\n\t\/\/ Every kite should be able to authenticate the user from token.\n\tk.Authenticators[\"token\"] = k.AuthenticateFromToken\n\t\/\/ A kite accepts requests from Kontrol.\n\tk.Authenticators[\"kodingKey\"] = k.AuthenticateFromKodingKey\n\n\t\/\/ Register our internal methods\n\tk.HandleFunc(\"systemInfo\", new(Status).Info)\n\tk.HandleFunc(\"heartbeat\", k.handleHeartbeat)\n\tk.HandleFunc(\"log\", k.handleLog)\n\n\treturn k\n}\n\n\/\/ Run is a blocking method. It runs the kite server and then accepts requests\n\/\/ asynchronously.\nfunc (k *Kite) Run() {\n\tk.Start()\n\t<-k.end\n\tk.Log.Notice(\"Kite server is closed.\")\n}\n\n\/\/ Start is like Run(), but does not wait for it to complete. It's nonblocking.\nfunc (k *Kite) Start() {\n\tk.parseVersionFlag()\n\n\tgo func() {\n\t\terr := k.listenAndServe()\n\t\tif err != nil {\n\t\t\tk.Log.Fatal(err)\n\t\t}\n\t}()\n\n\t<-k.ready \/\/ wait until we are ready\n}\n\n\/\/ Close stops the server.\nfunc (k *Kite) Close() {\n\tk.Log.Notice(\"Closing server...\")\n\tk.listener.Close()\n}\n\nfunc (k *Kite) handleHeartbeat(r *Request) (interface{}, error) {\n\targs := r.Args.MustSliceOfLength(2)\n\tseconds := args[0].MustFloat64()\n\tping := args[1].MustFunction()\n\n\tgo func() {\n\t\tfor {\n\t\t\ttime.Sleep(time.Duration(seconds) * time.Second)\n\t\t\tif ping() != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn nil, nil\n}\n\n\/\/ handleLog prints a log message to stdout.\nfunc (k *Kite) handleLog(r *Request) (interface{}, error) {\n\tmsg := r.Args.MustString()\n\tk.Log.Info(fmt.Sprintf(\"%s: %s\", r.RemoteKite.Name, msg))\n\treturn nil, nil\n}\n\nfunc init() {\n\t\/\/ These logging related stuff needs to be called once because stupid\n\t\/\/ logging library uses global variables and resets the backends every time.\n\tlogging.SetFormatter(logging.MustStringFormatter(\"%{level:-8s} ▶ %{message}\"))\n\tstderrBackend := logging.NewLogBackend(os.Stderr, \"\", log.LstdFlags)\n\tstderrBackend.Color = true\n\tsyslogBackend, _ := logging.NewSyslogBackend(\"\")\n\tlogging.SetBackend(stderrBackend, syslogBackend)\n}\n\n\/\/ newLogger returns a new logger object for desired name and level.\nfunc newLogger(name string, debug bool) *logging.Logger {\n\tlogger := logging.MustGetLogger(name)\n\n\tlevel := logging.INFO\n\tif debug {\n\t\tlevel = logging.DEBUG\n\t}\n\n\tlogging.SetLevel(level, name)\n\treturn logger\n}\n\n\/\/ If the user wants to call flag.Parse() the flag must be defined in advance.\nvar _ = flag.Bool(\"version\", false, \"show version\")\nvar _ = flag.Bool(\"debug\", false, \"print debug logs\")\n\n\/\/ parseVersionFlag prints the version number of the kite and exits with 0\n\/\/ if \"-version\" flag is enabled.\n\/\/ We did not use the \"flag\" package because it causes trouble if the user\n\/\/ also calls \"flag.Parse()\" in his code. flag.Parse() can be called only once.\nfunc (k *Kite) parseVersionFlag() {\n\tfor _, flag := range os.Args {\n\t\tif flag == \"-version\" {\n\t\t\tfmt.Println(k.Version)\n\t\t\tos.Exit(0)\n\t\t}\n\t}\n}\n\n\/\/ hasDebugFlag returns true if -debug flag is present in os.Args.\nfunc (k *Kite) hasDebugFlag() bool {\n\tfor _, flag := range os.Args {\n\t\tif flag == \"-debug\" {\n\t\t\treturn true\n\t\t}\n\t}\n\n\t\/\/ We can't use flags when running \"go test\" command.\n\t\/\/ This is another way to print debug logs.\n\tif os.Getenv(\"DEBUG\") != \"\" {\n\t\treturn true\n\t}\n\n\treturn false\n}\n\n\/\/ listenAndServe starts our rpc server with the given addr.\nfunc (k *Kite) listenAndServe() (err error) {\n\t\/\/ An error string equivalent to net.errClosing for using with http.Serve()\n\t\/\/ during a graceful exit.\n\t\/\/ I had to put it here because it is not exported by \"net\" package.\n\tconst errClosing = \"use of closed network connection\"\n\n\tk.listener, err = net.Listen(\"tcp4\", \":\"+k.Port)\n\tif err != nil {\n\t\treturn err\n\t}\n\tk.Log.Info(\"Listening: %s\", k.listener.Addr().String())\n\n\t\/\/ Port is known here if \"0\" is used as port number\n\t_, k.Port, _ = net.SplitHostPort(k.listener.Addr().String())\n\n\t\/\/ We must connect to Kontrol after starting to listen on port\n\tif k.KontrolEnabled {\n\t\tif k.RegisterToKontrol {\n\t\t\tk.Kontrol.OnConnect(k.registerToKontrol)\n\t\t}\n\n\t\tk.Kontrol.DialForever()\n\t}\n\n\tk.ready <- true \/\/ listener is ready, means we are ready too\n\n\terr = http.Serve(k.listener, k.server)\n\tif strings.Contains(err.Error(), errClosing) {\n\t\t\/\/ The server is closed by Close() method\n\t\terr = nil\n\t}\n\n\tk.end <- true \/\/ Serving is finished.\n\n\treturn err\n}\n\nfunc (k *Kite) registerToKontrol() {\n\terr := k.Kontrol.Register()\n\tif err != nil {\n\t\tk.Log.Fatalf(\"Cannot register to Kontrol: %s\", err)\n\t}\n}\n\n\/\/ OnConnect registers a function to run when a Kite connects to this Kite.\nfunc (k *Kite) OnConnect(handler func(*RemoteKite)) {\n\tk.onConnectHandlers = append(k.onConnectHandlers, handler)\n}\n\n\/\/ OnDisconnect registers a function to run when a connected Kite is disconnected.\nfunc (k *Kite) OnDisconnect(handler func(*RemoteKite)) {\n\tk.onDisconnectHandlers = append(k.onDisconnectHandlers, handler)\n}\n\n\/\/ notifyRemoteKiteConnected runs the registered handlers with OnConnect().\nfunc (k *Kite) notifyRemoteKiteConnected(r *RemoteKite) {\n\tk.Log.Info(\"Client is connected to us: [%s %s]\", r.Name, r.Addr())\n\n\tfor _, handler := range k.onConnectHandlers {\n\t\tgo handler(r)\n\t}\n}\n\nfunc (k *Kite) notifyRemoteKiteDisconnected(r *RemoteKite) {\n\tk.Log.Info(\"Client has disconnected: [%s %s]\", r.Name, r.Addr())\n\n\tfor _, handler := range k.onDisconnectHandlers {\n\t\tgo handler(r)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2012 Aaron Jacobs. All Rights Reserved.\n\/\/ Author: aaronjjacobs@gmail.com (Aaron Jacobs)\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage oglematchers_test\n\nimport (\n\t. \"github.com\/jacobsa\/oglematchers\"\n\t. \"github.com\/jacobsa\/ogletest\"\n)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Helpers\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntype IdenticalToTest struct {\n}\n\nfunc init() { RegisterTestSuite(&IdenticalToTest{}) }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Tests\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nfunc (t *IdenticalToTest) TypesNotIdentical() {\n\tvar m Matcher\n\tvar err error\n\n\ttype intAlias int\n\n\t\/\/ Type alias expected value\n\tm = IdenticalTo(intAlias(17))\n\terr = m.Matches(int(17))\n\tExpectThat(err, Error(Equals(\"which is of type int\")))\n\n\t\/\/ Type alias candidate\n\tm = IdenticalTo(int(17))\n\terr = m.Matches(intAlias(17))\n\tExpectThat(err, Error(Equals(\"which is of type intAlias\")))\n\n\t\/\/ int and uint\n\tm = IdenticalTo(int(17))\n\terr = m.Matches(uint(17))\n\tExpectThat(err, Error(Equals(\"which is of type uint\")))\n}\n\nfunc (t *IdenticalToTest) InvalidTypeExpectedValue() {\n\tf := func() { IdenticalTo(nil) }\n\tExpectThat(f, Panics(AllOf(HasSubstr(\"IdenticalTo\"), HasSubstr(\"invalid\"))))\n}\n\nfunc (t *IdenticalToTest) InvalidTypeCandidate() {\n\tvar m Matcher\n\tvar err error\n\n\t\/\/ Nil chan expected value\n\tm = IdenticalTo((chan int)(nil))\n\terr = m.Matches(nil)\n\tExpectThat(err, Error(Equals(\"which is of type <nil>\")))\n\n\t\/\/ Non-nil chan expected value\n\tm = IdenticalTo(make(chan int))\n\terr = m.Matches(nil)\n\tExpectThat(err, Error(Equals(\"which is of type <nil>\")))\n}\n\nfunc (t *IdenticalToTest) Slices() {\n}\n\nfunc (t *IdenticalToTest) Maps() {\n}\n\nfunc (t *IdenticalToTest) Functions() {\n}\n\nfunc (t *IdenticalToTest) Channels() {\n}\n\nfunc (t *IdenticalToTest) Bools() {\n}\n\nfunc (t *IdenticalToTest) Ints() {\n}\n\nfunc (t *IdenticalToTest) Int8s() {\n}\n\nfunc (t *IdenticalToTest) Int16s() {\n}\n\nfunc (t *IdenticalToTest) Int32s() {\n}\n\nfunc (t *IdenticalToTest) Int64s() {\n}\n\nfunc (t *IdenticalToTest) Uints() {\n}\n\nfunc (t *IdenticalToTest) Uint8s() {\n}\n\nfunc (t *IdenticalToTest) Uint16s() {\n}\n\nfunc (t *IdenticalToTest) Uint32s() {\n}\n\nfunc (t *IdenticalToTest) Uint64s() {\n}\n\nfunc (t *IdenticalToTest) Float32s() {\n}\n\nfunc (t *IdenticalToTest) Float64s() {\n}\n\nfunc (t *IdenticalToTest) Complex64s() {\n}\n\nfunc (t *IdenticalToTest) Complex128s() {\n}\n\nfunc (t *IdenticalToTest) ComparableArrays() {\n}\n\nfunc (t *IdenticalToTest) NonComparableArrays() {\n}\n\nfunc (t *IdenticalToTest) ComparableInterfaces() {\n}\n\nfunc (t *IdenticalToTest) NonComparableInterfaces() {\n}\n\nfunc (t *IdenticalToTest) Pointers() {\n}\n\nfunc (t *IdenticalToTest) Strings() {\n}\n\nfunc (t *IdenticalToTest) ComparableStructs() {\n}\n\nfunc (t *IdenticalToTest) NonComparableStructs() {\n}\n\nfunc (t *IdenticalToTest) UnsafePointers() {\n}\n\nfunc (t *IdenticalToTest) IntAlias() {\n}\n<commit_msg>IdenticalToTest.Slices<commit_after>\/\/ Copyright 2012 Aaron Jacobs. All Rights Reserved.\n\/\/ Author: aaronjjacobs@gmail.com (Aaron Jacobs)\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage oglematchers_test\n\nimport (\n\t. \"github.com\/jacobsa\/oglematchers\"\n\t. \"github.com\/jacobsa\/ogletest\"\n)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Helpers\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntype IdenticalToTest struct {\n}\n\nfunc init() { RegisterTestSuite(&IdenticalToTest{}) }\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Tests\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nfunc (t *IdenticalToTest) TypesNotIdentical() {\n\tvar m Matcher\n\tvar err error\n\n\ttype intAlias int\n\n\t\/\/ Type alias expected value\n\tm = IdenticalTo(intAlias(17))\n\terr = m.Matches(int(17))\n\tExpectThat(err, Error(Equals(\"which is of type int\")))\n\n\t\/\/ Type alias candidate\n\tm = IdenticalTo(int(17))\n\terr = m.Matches(intAlias(17))\n\tExpectThat(err, Error(Equals(\"which is of type intAlias\")))\n\n\t\/\/ int and uint\n\tm = IdenticalTo(int(17))\n\terr = m.Matches(uint(17))\n\tExpectThat(err, Error(Equals(\"which is of type uint\")))\n}\n\nfunc (t *IdenticalToTest) InvalidTypeExpectedValue() {\n\tf := func() { IdenticalTo(nil) }\n\tExpectThat(f, Panics(AllOf(HasSubstr(\"IdenticalTo\"), HasSubstr(\"invalid\"))))\n}\n\nfunc (t *IdenticalToTest) InvalidTypeCandidate() {\n\tvar m Matcher\n\tvar err error\n\n\t\/\/ Nil chan expected value\n\tm = IdenticalTo((chan int)(nil))\n\terr = m.Matches(nil)\n\tExpectThat(err, Error(Equals(\"which is of type <nil>\")))\n\n\t\/\/ Non-nil chan expected value\n\tm = IdenticalTo(make(chan int))\n\terr = m.Matches(nil)\n\tExpectThat(err, Error(Equals(\"which is of type <nil>\")))\n}\n\nfunc (t *IdenticalToTest) Slices() {\n\tvar m Matcher\n\tvar err error\n\n\t\/\/ Nil expected value\n\tm = IdenticalTo(([]int)(nil))\n\n\terr = m.Matches(([]int)(nil))\n\tExpectEq(nil, err)\n\n\terr = m.Matches([]int{})\n\tExpectThat(err, Equals(\"which is not an identical reference\"))\n\n\t\/\/ Non-nil expected value\n\ts1 := []int{}\n\ts2 := []int{}\n\tm = IdenticalTo(s1)\n\n\terr = m.Matches(s1)\n\tExpectEq(nil, err)\n\n\terr = m.Matches(s2)\n\tExpectThat(err, Equals(\"which is not an identical reference\"))\n}\n\nfunc (t *IdenticalToTest) Maps() {\n}\n\nfunc (t *IdenticalToTest) Functions() {\n}\n\nfunc (t *IdenticalToTest) Channels() {\n}\n\nfunc (t *IdenticalToTest) Bools() {\n}\n\nfunc (t *IdenticalToTest) Ints() {\n}\n\nfunc (t *IdenticalToTest) Int8s() {\n}\n\nfunc (t *IdenticalToTest) Int16s() {\n}\n\nfunc (t *IdenticalToTest) Int32s() {\n}\n\nfunc (t *IdenticalToTest) Int64s() {\n}\n\nfunc (t *IdenticalToTest) Uints() {\n}\n\nfunc (t *IdenticalToTest) Uint8s() {\n}\n\nfunc (t *IdenticalToTest) Uint16s() {\n}\n\nfunc (t *IdenticalToTest) Uint32s() {\n}\n\nfunc (t *IdenticalToTest) Uint64s() {\n}\n\nfunc (t *IdenticalToTest) Float32s() {\n}\n\nfunc (t *IdenticalToTest) Float64s() {\n}\n\nfunc (t *IdenticalToTest) Complex64s() {\n}\n\nfunc (t *IdenticalToTest) Complex128s() {\n}\n\nfunc (t *IdenticalToTest) ComparableArrays() {\n}\n\nfunc (t *IdenticalToTest) NonComparableArrays() {\n}\n\nfunc (t *IdenticalToTest) ComparableInterfaces() {\n}\n\nfunc (t *IdenticalToTest) NonComparableInterfaces() {\n}\n\nfunc (t *IdenticalToTest) Pointers() {\n}\n\nfunc (t *IdenticalToTest) Strings() {\n}\n\nfunc (t *IdenticalToTest) ComparableStructs() {\n}\n\nfunc (t *IdenticalToTest) NonComparableStructs() {\n}\n\nfunc (t *IdenticalToTest) UnsafePointers() {\n}\n\nfunc (t *IdenticalToTest) IntAlias() {\n}\n<|endoftext|>"}
{"text":"<commit_before>package handler\n\nimport (\n\t\"context\"\n\n\t\"github.com\/micro\/go-micro\/v2\/broker\"\n\tpb \"github.com\/micro\/go-micro\/v2\/broker\/service\/proto\"\n\t\"github.com\/micro\/go-micro\/v2\/errors\"\n\tlog \"github.com\/micro\/go-micro\/v2\/logger\"\n\t\"github.com\/micro\/micro\/v2\/internal\/namespace\"\n)\n\ntype Broker struct {\n\tBroker broker.Broker\n}\n\nfunc (b *Broker) Publish(ctx context.Context, req *pb.PublishRequest, rsp *pb.Empty) error {\n\tns := namespace.FromContext(ctx)\n\n\tlog.Debugf(\"Publishing message to %s topic in the %v namespace\", req.Topic, ns)\n\terr := b.Broker.Publish(ns+\".\"+req.Topic, &broker.Message{\n\t\tHeader: req.Message.Header,\n\t\tBody:   req.Message.Body,\n\t})\n\tlog.Debugf(\"Published message to %s topic in the %v namespace\", req.Topic, ns)\n\tif err != nil {\n\t\treturn errors.InternalServerError(\"go.micro.broker\", err.Error())\n\t}\n\treturn nil\n}\n\nfunc (b *Broker) Subscribe(ctx context.Context, req *pb.SubscribeRequest, stream pb.Broker_SubscribeStream) error {\n\tns := namespace.FromContext(ctx)\n\terrChan := make(chan error, 1)\n\n\t\/\/ message handler to stream back messages from broker\n\thandler := func(p broker.Event) error {\n\t\tif err := stream.Send(&pb.Message{\n\t\t\tHeader: p.Message().Header,\n\t\t\tBody:   p.Message().Body,\n\t\t}); err != nil {\n\t\t\tselect {\n\t\t\tcase errChan <- err:\n\t\t\t\treturn err\n\t\t\tdefault:\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\n\tlog.Debugf(\"Subscribing to %s topic in namespace %v\", req.Topic, ns)\n\tsub, err := b.Broker.Subscribe(ns+\".\"+req.Topic, handler, broker.Queue(ns+\".\"+req.Queue))\n\tif err != nil {\n\t\treturn errors.InternalServerError(\"go.micro.broker\", err.Error())\n\t}\n\tdefer func() {\n\t\tlog.Debugf(\"Unsubscribing from topic %s in namespace %v\", req.Topic, ns)\n\t\tsub.Unsubscribe()\n\t}()\n\n\tselect {\n\tcase <-ctx.Done():\n\t\tlog.Debugf(\"Context done for subscription to topic %s\", req.Topic)\n\t\treturn nil\n\tcase err := <-errChan:\n\t\tlog.Debugf(\"Subscription error for topic %s: %v\", req.Topic, err)\n\t\treturn err\n\t}\n}\n<commit_msg>service\/broker: use namespace.Authorize<commit_after>package handler\n\nimport (\n\t\"context\"\n\n\t\"github.com\/micro\/go-micro\/v2\/broker\"\n\tpb \"github.com\/micro\/go-micro\/v2\/broker\/service\/proto\"\n\t\"github.com\/micro\/go-micro\/v2\/errors\"\n\tlog \"github.com\/micro\/go-micro\/v2\/logger\"\n\t\"github.com\/micro\/micro\/v2\/internal\/namespace\"\n)\n\ntype Broker struct {\n\tBroker broker.Broker\n}\n\nfunc (b *Broker) Publish(ctx context.Context, req *pb.PublishRequest, rsp *pb.Empty) error {\n\tns := namespace.FromContext(ctx)\n\n\t\/\/ authorize the request\n\tif err := namespace.Authorize(ctx, ns); err == namespace.ErrForbidden {\n\t\treturn errors.Forbidden(\"go.micro.broker\", err.Error())\n\t} else if err == namespace.ErrUnauthorized {\n\t\treturn errors.Unauthorized(\"go.micro.broker\", err.Error())\n\t} else if err != nil {\n\t\treturn errors.InternalServerError(\"go.micro.broker\", err.Error())\n\t}\n\n\tlog.Debugf(\"Publishing message to %s topic in the %v namespace\", req.Topic, ns)\n\terr := b.Broker.Publish(ns+\".\"+req.Topic, &broker.Message{\n\t\tHeader: req.Message.Header,\n\t\tBody:   req.Message.Body,\n\t})\n\tlog.Debugf(\"Published message to %s topic in the %v namespace\", req.Topic, ns)\n\tif err != nil {\n\t\treturn errors.InternalServerError(\"go.micro.broker\", err.Error())\n\t}\n\treturn nil\n}\n\nfunc (b *Broker) Subscribe(ctx context.Context, req *pb.SubscribeRequest, stream pb.Broker_SubscribeStream) error {\n\tns := namespace.FromContext(ctx)\n\terrChan := make(chan error, 1)\n\n\t\/\/ authorize the request\n\tif err := namespace.Authorize(ctx, ns); err == namespace.ErrForbidden {\n\t\treturn errors.Forbidden(\"go.micro.broker\", err.Error())\n\t} else if err == namespace.ErrUnauthorized {\n\t\treturn errors.Unauthorized(\"go.micro.broker\", err.Error())\n\t} else if err != nil {\n\t\treturn errors.InternalServerError(\"go.micro.broker\", err.Error())\n\t}\n\n\t\/\/ message handler to stream back messages from broker\n\thandler := func(p broker.Event) error {\n\t\tif err := stream.Send(&pb.Message{\n\t\t\tHeader: p.Message().Header,\n\t\t\tBody:   p.Message().Body,\n\t\t}); err != nil {\n\t\t\tselect {\n\t\t\tcase errChan <- err:\n\t\t\t\treturn err\n\t\t\tdefault:\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\n\tlog.Debugf(\"Subscribing to %s topic in namespace %v\", req.Topic, ns)\n\tsub, err := b.Broker.Subscribe(ns+\".\"+req.Topic, handler, broker.Queue(ns+\".\"+req.Queue))\n\tif err != nil {\n\t\treturn errors.InternalServerError(\"go.micro.broker\", err.Error())\n\t}\n\tdefer func() {\n\t\tlog.Debugf(\"Unsubscribing from topic %s in namespace %v\", req.Topic, ns)\n\t\tsub.Unsubscribe()\n\t}()\n\n\tselect {\n\tcase <-ctx.Done():\n\t\tlog.Debugf(\"Context done for subscription to topic %s\", req.Topic)\n\t\treturn nil\n\tcase err := <-errChan:\n\t\tlog.Debugf(\"Subscription error for topic %s: %v\", req.Topic, err)\n\t\treturn err\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright © 2016 NAME HERE <EMAIL ADDRESS>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage cmd\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/spf13\/viper\"\n\t\"github.com\/tylerharter\/open-lambda\/lambda-generator\/experimental\/frontends\"\n\t\"github.com\/tylerharter\/open-lambda\/lambda-generator\/experimental\/frontends\/effe\"\n)\n\nvar (\n\tcfgFile     string\n\tfrontendStr string\n\tfe          frontends.FrontEnd\n)\n\n\/\/ This represents the base command when called without any subcommands\nvar RootCmd = &cobra.Command{\n\tUse:   fmt.Sprintf(\"%s\", os.Args[0]),\n\tShort: \"Helps to template, organize, build and deploy OpenLambda Lambdas\",\n\tLong:  \"Helps to template, organize, build and deploy OpenLambda Lambdas\",\n\t\/\/ Uncomment the following line if your bare application\n\t\/\/ has an action associated with it:\n\t\/\/\tRun: func(cmd *cobra.Command, args []string) { },\n}\n\n\/\/ Execute adds all child commands to the root command sets flags appropriately.\n\/\/ This is called by main.main(). It only needs to happen once to the rootCmd.\nfunc Execute() {\n\tif err := RootCmd.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(-1)\n\t}\n}\n\nfunc init() {\n\tcobra.OnInitialize(initConfig)\n\n\t\/\/ Here you will define your flags and configuration settings.\n\t\/\/ Cobra supports Persistent Flags, which, if defined here,\n\t\/\/ will be global for your application.\n\n\tRootCmd.PersistentFlags().StringVar(&cfgFile, \"config\", \"\", \"config file (default is $HOME\/.experimental.yaml)\")\n\tRootCmd.PersistentFlags().StringVar(&frontendStr, \"frontend\", \"effe\", \"OpenLambda frontend framework (default is effe)\")\n\t\/\/ Cobra also supports local flags, which will only run\n\t\/\/ when this action is called directly.\n\tRootCmd.Flags().BoolP(\"toggle\", \"t\", false, \"Help message for toggle\")\n\n\t\/\/ find the .openlambda folder or warn user if not found\n\tolDir := findOlDir()\n\tif olDir == \"\" {\n\t\tfmt.Printf(\"WARNING: no .openlambda directory found (Have you called %s init yet?)\\n\\n\", os.Args[0])\n\t\treturn\n\t}\n\n\t\/\/ Here we select the frontend, based on user configs found from above\n\tswitch frontendStr {\n\tcase \"effe\":\n\t\tfe = effe.NewFrontEnd(olDir)\n\tdefault:\n\t\tfmt.Println(\"frontend %s is unsupported\\n\")\n\t\tos.Exit(1)\n\t}\n}\n\nfunc findOlDir() string {\n\twd, err := os.Getwd()\n\tif err != nil {\n\t\tfmt.Printf(\"failed to get wd with err %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\tcurr, err := filepath.Abs(wd)\n\tif err != nil {\n\t\tfmt.Printf(\"failed to get create abs path with err %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\t\/\/ Walk one dir up each loop\n\t\/\/ TODO \"\/\" is ommitted. Do we want this?\n\tfor ; curr != \"\/\"; curr = filepath.Dir(curr) {\n\t\tdir := filepath.Join(curr, \".openlambda\")\n\t\tinfo, err := os.Stat(dir)\n\t\tif err != nil {\n\t\t\tif !os.IsNotExist(err) {\n\t\t\t\tfmt.Printf(\"failed to get info on %s with err %v\\n\", dir, err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif !info.IsDir() {\n\t\t\tfmt.Printf(\"warning: non-directory .openlambda at %s\\n\", dir)\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ found dir\n\t\treturn dir\n\t}\n\t\/\/ caller will log\n\treturn \"\"\n}\n\n\/\/ initConfig reads in config file and ENV variables if set.\nfunc initConfig() {\n\tif cfgFile != \"\" { \/\/ enable ability to specify config file via flag\n\t\tviper.SetConfigFile(cfgFile)\n\t}\n\n\tviper.SetConfigName(\".experimental\") \/\/ name of config file (without extension)\n\tviper.AddConfigPath(\"$HOME\")         \/\/ adding home directory as first search path\n\tviper.AutomaticEnv()                 \/\/ read in environment variables that match\n\n\t\/\/ If a config file is found, read it in.\n\tif err := viper.ReadInConfig(); err == nil {\n\t\tfmt.Println(\"Using config file:\", viper.ConfigFileUsed())\n\t}\n}\n<commit_msg>remove duplicate default log<commit_after>\/\/ Copyright © 2016 NAME HERE <EMAIL ADDRESS>\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage cmd\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/spf13\/viper\"\n\t\"github.com\/tylerharter\/open-lambda\/lambda-generator\/experimental\/frontends\"\n\t\"github.com\/tylerharter\/open-lambda\/lambda-generator\/experimental\/frontends\/effe\"\n)\n\nvar (\n\tcfgFile     string\n\tfrontendStr string\n\tfe          frontends.FrontEnd\n)\n\n\/\/ This represents the base command when called without any subcommands\nvar RootCmd = &cobra.Command{\n\tUse:   fmt.Sprintf(\"%s\", os.Args[0]),\n\tShort: \"Helps to template, organize, build and deploy OpenLambda Lambdas\",\n\tLong:  \"Helps to template, organize, build and deploy OpenLambda Lambdas\",\n\t\/\/ Uncomment the following line if your bare application\n\t\/\/ has an action associated with it:\n\t\/\/\tRun: func(cmd *cobra.Command, args []string) { },\n}\n\n\/\/ Execute adds all child commands to the root command sets flags appropriately.\n\/\/ This is called by main.main(). It only needs to happen once to the rootCmd.\nfunc Execute() {\n\tif err := RootCmd.Execute(); err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(-1)\n\t}\n}\n\nfunc init() {\n\tcobra.OnInitialize(initConfig)\n\n\t\/\/ Here you will define your flags and configuration settings.\n\t\/\/ Cobra supports Persistent Flags, which, if defined here,\n\t\/\/ will be global for your application.\n\n\tRootCmd.PersistentFlags().StringVar(&cfgFile, \"config\", \"\", \"config file (default is $HOME\/.experimental.yaml)\")\n\tRootCmd.PersistentFlags().StringVar(&frontendStr, \"frontend\", \"effe\", \"OpenLambda frontend framework\")\n\t\/\/ Cobra also supports local flags, which will only run\n\t\/\/ when this action is called directly.\n\tRootCmd.Flags().BoolP(\"toggle\", \"t\", false, \"Help message for toggle\")\n\n\t\/\/ find the .openlambda folder or warn user if not found\n\tolDir := findOlDir()\n\tif olDir == \"\" {\n\t\tfmt.Printf(\"WARNING: no .openlambda directory found (Have you called %s init yet?)\\n\\n\", os.Args[0])\n\t\treturn\n\t}\n\n\t\/\/ Here we select the frontend, based on user configs found from above\n\tswitch frontendStr {\n\tcase \"effe\":\n\t\tfe = effe.NewFrontEnd(olDir)\n\tdefault:\n\t\tfmt.Println(\"frontend %s is unsupported\\n\")\n\t\tos.Exit(1)\n\t}\n}\n\nfunc findOlDir() string {\n\twd, err := os.Getwd()\n\tif err != nil {\n\t\tfmt.Printf(\"failed to get wd with err %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\tcurr, err := filepath.Abs(wd)\n\tif err != nil {\n\t\tfmt.Printf(\"failed to get create abs path with err %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\t\/\/ Walk one dir up each loop\n\t\/\/ TODO \"\/\" is ommitted. Do we want this?\n\tfor ; curr != \"\/\"; curr = filepath.Dir(curr) {\n\t\tdir := filepath.Join(curr, \".openlambda\")\n\t\tinfo, err := os.Stat(dir)\n\t\tif err != nil {\n\t\t\tif !os.IsNotExist(err) {\n\t\t\t\tfmt.Printf(\"failed to get info on %s with err %v\\n\", dir, err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tif !info.IsDir() {\n\t\t\tfmt.Printf(\"warning: non-directory .openlambda at %s\\n\", dir)\n\t\t\tcontinue\n\t\t}\n\t\t\/\/ found dir\n\t\treturn dir\n\t}\n\t\/\/ caller will log\n\treturn \"\"\n}\n\n\/\/ initConfig reads in config file and ENV variables if set.\nfunc initConfig() {\n\tif cfgFile != \"\" { \/\/ enable ability to specify config file via flag\n\t\tviper.SetConfigFile(cfgFile)\n\t}\n\n\tviper.SetConfigName(\".experimental\") \/\/ name of config file (without extension)\n\tviper.AddConfigPath(\"$HOME\")         \/\/ adding home directory as first search path\n\tviper.AutomaticEnv()                 \/\/ read in environment variables that match\n\n\t\/\/ If a config file is found, read it in.\n\tif err := viper.ReadInConfig(); err == nil {\n\t\tfmt.Println(\"Using config file:\", viper.ConfigFileUsed())\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ (c) 2019-2020, Ava Labs, Inc. All rights reserved.\n\/\/ See the file LICENSE for licensing terms.\n\npackage avalanche\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/ava-labs\/gecko\/cache\"\n\t\"github.com\/ava-labs\/gecko\/ids\"\n\t\"github.com\/ava-labs\/gecko\/snow\/choices\"\n\t\"github.com\/ava-labs\/gecko\/snow\/consensus\/avalanche\"\n\t\"github.com\/ava-labs\/gecko\/snow\/engine\/common\"\n\t\"github.com\/ava-labs\/gecko\/snow\/engine\/common\/queue\"\n\t\"github.com\/ava-labs\/gecko\/utils\/formatting\"\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n)\n\nconst (\n\t\/\/ We cache processed vertices where height = c * stripeDistance for c = {1,2,3...}\n\t\/\/ This forms a \"stripe\" of cached DAG vertices at height stripeDistance, 2*stripeDistance, etc.\n\t\/\/ This helps to limit the number of repeated DAG traversals performed\n\tstripeDistance = 2000\n\tstripeWidth    = 5\n\tcacheSize      = 100000\n)\n\n\/\/ BootstrapConfig ...\ntype BootstrapConfig struct {\n\tcommon.Config\n\n\t\/\/ VtxBlocked tracks operations that are blocked on vertices\n\t\/\/ TxBlocked tracks operations that are blocked on transactions\n\tVtxBlocked, TxBlocked *queue.Jobs\n\n\tState State\n\tVM    DAGVM\n}\n\ntype bootstrapper struct {\n\tBootstrapConfig\n\tmetrics\n\tcommon.Bootstrapper\n\n\t\/\/ number of vertices fetched so far\n\tnumFetched uint32\n\n\t\/\/ tracks which validators were asked for which containers in which requests\n\toutstandingRequests common.Requests\n\n\t\/\/ IDs of vertices that we will send a GetAncestors request for once we are\n\t\/\/ not at the max number of outstanding requests\n\t\/\/ Invariant: The intersection of needToFetch and outstandingRequests is\n\t\/\/            empty\n\tneedToFetch ids.Set\n\n\t\/\/ Contains IDs of vertices that have recently been processed\n\tprocessedCache *cache.LRU\n\n\t\/\/ true if bootstrapping is done\n\tfinished bool\n\n\t\/\/ Called when bootstrapping is done\n\tonFinished func() error\n}\n\n\/\/ Initialize this engine.\nfunc (b *bootstrapper) Initialize(config BootstrapConfig) error {\n\tb.BootstrapConfig = config\n\tb.processedCache = &cache.LRU{Size: cacheSize}\n\n\tb.VtxBlocked.SetParser(&vtxParser{\n\t\tlog:         config.Context.Log,\n\t\tnumAccepted: b.numBSVtx,\n\t\tnumDropped:  b.numBSDroppedVtx,\n\t\tstate:       b.State,\n\t})\n\n\tb.TxBlocked.SetParser(&txParser{\n\t\tlog:         config.Context.Log,\n\t\tnumAccepted: b.numBSTx,\n\t\tnumDropped:  b.numBSDroppedTx,\n\t\tvm:          b.VM,\n\t})\n\n\tconfig.Bootstrapable = b\n\tb.Bootstrapper.Initialize(config.Config)\n\treturn nil\n}\n\n\/\/ CurrentAcceptedFrontier ...\nfunc (b *bootstrapper) CurrentAcceptedFrontier() ids.Set {\n\tacceptedFrontier := ids.Set{}\n\tacceptedFrontier.Add(b.State.Edge()...)\n\treturn acceptedFrontier\n}\n\n\/\/ FilterAccepted ...\nfunc (b *bootstrapper) FilterAccepted(containerIDs ids.Set) ids.Set {\n\tacceptedVtxIDs := ids.Set{}\n\tfor _, vtxID := range containerIDs.List() {\n\t\tif vtx, err := b.State.GetVertex(vtxID); err == nil && vtx.Status() == choices.Accepted {\n\t\t\tacceptedVtxIDs.Add(vtxID)\n\t\t}\n\t}\n\treturn acceptedVtxIDs\n}\n\n\/\/ Fetch vertices and their ancestors from the set of vertices that are needed\n\/\/ to be fetched.\nfunc (b *bootstrapper) fetch(vtxIDs ...ids.ID) error {\n\tb.needToFetch.Add(vtxIDs...)\n\tfor b.needToFetch.Len() > 0 && b.outstandingRequests.Len() < common.MaxOutstandingRequests {\n\t\tvtxID := b.needToFetch.CappedList(1)[0]\n\t\tb.needToFetch.Remove(vtxID)\n\n\t\t\/\/ Make sure we haven't already requested this vertex\n\t\tif b.outstandingRequests.Contains(vtxID) {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Make sure we don't already have this vertex\n\t\tif _, err := b.State.GetVertex(vtxID); err == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tvalidators := b.BootstrapConfig.Validators.Sample(1) \/\/ validator to send request to\n\t\tif len(validators) == 0 {\n\t\t\treturn fmt.Errorf(\"Dropping request for %s as there are no validators\", vtxID)\n\t\t}\n\t\tvalidatorID := validators[0].ID()\n\t\tb.RequestID++\n\n\t\tb.outstandingRequests.Add(validatorID, b.RequestID, vtxID)\n\t\tb.needToFetch.Remove(vtxID)                                            \/\/ maintains invariant that intersection with outstandingRequests is empty\n\t\tb.BootstrapConfig.Sender.GetAncestors(validatorID, b.RequestID, vtxID) \/\/ request vertex and ancestors\n\t}\n\treturn b.finish()\n}\n\n\/\/ Process vertices\nfunc (b *bootstrapper) process(vtxs ...avalanche.Vertex) error {\n\ttoProcess := newMaxVertexHeap()\n\tfor _, vtx := range vtxs {\n\t\tif _, ok := b.processedCache.Get(vtx.ID()); !ok { \/\/ only process if we haven't already\n\t\t\ttoProcess.Push(vtx)\n\t\t}\n\t}\n\n\tfor toProcess.Len() > 0 {\n\t\tvtx := toProcess.Pop()\n\t\tvtxID := vtx.ID()\n\n\t\tswitch vtx.Status() {\n\t\tcase choices.Unknown:\n\t\t\tb.fetch(vtxID)\n\t\tcase choices.Rejected:\n\t\t\tb.needToFetch.Remove(vtxID)\n\t\t\treturn fmt.Errorf(\"tried to accept %s even though it was previously rejected\", vtx.ID())\n\t\tcase choices.Processing:\n\t\t\tb.needToFetch.Remove(vtxID)\n\n\t\t\tif err := b.VtxBlocked.Push(&vertexJob{\n\t\t\t\tlog:         b.BootstrapConfig.Context.Log,\n\t\t\t\tnumAccepted: b.numBSVtx,\n\t\t\t\tnumDropped:  b.numBSDroppedVtx,\n\t\t\t\tvtx:         vtx,\n\t\t\t}); err == nil {\n\t\t\t\tb.numBSBlockedVtx.Inc()\n\t\t\t\tb.numFetched++ \/\/ Progress tracker\n\t\t\t\tif b.numFetched%common.StatusUpdateFrequency == 0 {\n\t\t\t\t\tb.BootstrapConfig.Context.Log.Info(\"fetched %d vertices\", b.numFetched)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tb.BootstrapConfig.Context.Log.Verbo(\"couldn't push to vtxBlocked: %s\", err)\n\t\t\t}\n\t\t\tfor _, tx := range vtx.Txs() {\n\t\t\t\tif err := b.TxBlocked.Push(&txJob{\n\t\t\t\t\tlog:         b.BootstrapConfig.Context.Log,\n\t\t\t\t\tnumAccepted: b.numBSTx,\n\t\t\t\t\tnumDropped:  b.numBSDroppedTx,\n\t\t\t\t\ttx:          tx,\n\t\t\t\t}); err == nil {\n\t\t\t\t\tb.numBSBlockedTx.Inc()\n\t\t\t\t} else {\n\t\t\t\t\tb.BootstrapConfig.Context.Log.Verbo(\"couldn't push to txBlocked: %s\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor _, parent := range vtx.Parents() {\n\t\t\t\tif _, ok := b.processedCache.Get(parent.ID()); !ok { \/\/ already processed this\n\t\t\t\t\ttoProcess.Push(parent)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif vtx.Height()%stripeDistance < stripeWidth {\n\t\t\t\tb.processedCache.Put(vtx.ID(), nil)\n\t\t\t}\n\t\t}\n\t}\n\n\tif err := b.VtxBlocked.Commit(); err != nil {\n\t\treturn err\n\t}\n\tif err := b.TxBlocked.Commit(); err != nil {\n\t\treturn err\n\t}\n\n\treturn b.fetch()\n}\n\n\/\/ MultiPut handles the receipt of multiple containers. Should be received in response to a GetAncestors message to [vdr]\n\/\/ with request ID [requestID]. Expects vtxs[0] to be the vertex requested in the corresponding GetAncestors.\nfunc (b *bootstrapper) MultiPut(vdr ids.ShortID, requestID uint32, vtxs [][]byte) error {\n\tif lenVtxs := len(vtxs); lenVtxs > common.MaxContainersPerMultiPut {\n\t\tb.BootstrapConfig.Context.Log.Debug(\"MultiPut(%s, %d) contains more than maximum number of vertices\", vdr, requestID)\n\t\treturn b.GetAncestorsFailed(vdr, requestID)\n\t} else if lenVtxs == 0 {\n\t\tb.BootstrapConfig.Context.Log.Debug(\"MultiPut(%s, %d) contains no vertices\", vdr, requestID)\n\t\treturn b.GetAncestorsFailed(vdr, requestID)\n\t}\n\n\t\/\/ Make sure this is in response to a request we made\n\tneededVtxID, needed := b.outstandingRequests.Remove(vdr, requestID)\n\tif !needed { \/\/ this message isn't in response to a request we made\n\t\tb.BootstrapConfig.Context.Log.Debug(\"received unexpected MultiPut from %s with ID %d\", vdr, requestID)\n\t\treturn nil\n\t}\n\n\tneededVtx, err := b.State.ParseVertex(vtxs[0]) \/\/ the vertex we requested\n\tif err != nil {\n\t\tb.BootstrapConfig.Context.Log.Debug(\"Failed to parse requested vertex %s: %w\", neededVtxID, err)\n\t\tb.BootstrapConfig.Context.Log.Verbo(\"vertex: %s\", formatting.DumpBytes{Bytes: vtxs[0]})\n\t\treturn b.fetch(neededVtxID)\n\t} else if actualID := neededVtx.ID(); !actualID.Equals(neededVtxID) {\n\t\tb.BootstrapConfig.Context.Log.Debug(\"expected the first block to be the requested block, %s, but is %s\", neededVtxID, actualID)\n\t\treturn b.fetch(neededVtxID)\n\t}\n\n\tprocessVertices := make([]avalanche.Vertex, 1, len(vtxs))\n\tprocessVertices[0] = neededVtx\n\n\tfor _, vtxBytes := range vtxs[1:] { \/\/ Parse\/persist all the vertices\n\t\tif vtx, err := b.State.ParseVertex(vtxBytes); err != nil { \/\/ Persists the vtx\n\t\t\tb.BootstrapConfig.Context.Log.Debug(\"Failed to parse vertex: %w\", err)\n\t\t\tb.BootstrapConfig.Context.Log.Verbo(\"vertex: %s\", formatting.DumpBytes{Bytes: vtxBytes})\n\t\t} else {\n\t\t\tprocessVertices = append(processVertices, vtx)\n\t\t\tb.needToFetch.Remove(vtx.ID()) \/\/ No need to fetch this vertex since we have it now\n\t\t}\n\t}\n\n\treturn b.process(processVertices...)\n}\n\n\/\/ GetAncestorsFailed is called when a GetAncestors message we sent fails\nfunc (b *bootstrapper) GetAncestorsFailed(vdr ids.ShortID, requestID uint32) error {\n\tvtxID, ok := b.outstandingRequests.Remove(vdr, requestID)\n\tif !ok {\n\t\tb.BootstrapConfig.Context.Log.Debug(\"GetAncestorsFailed(%s, %d) called but there was no outstanding request to this validator with this ID\", vdr, requestID)\n\t\treturn nil\n\t}\n\t\/\/ Send another request for the vertex\n\treturn b.fetch(vtxID)\n}\n\n\/\/ ForceAccepted ...\nfunc (b *bootstrapper) ForceAccepted(acceptedContainerIDs ids.Set) error {\n\tif err := b.VM.Bootstrapping(); err != nil {\n\t\treturn fmt.Errorf(\"failed to notify VM that bootstrapping has started: %w\",\n\t\t\terr)\n\t}\n\n\tstoredVtxs := make([]avalanche.Vertex, 0, acceptedContainerIDs.Len())\n\tfor _, vtxID := range acceptedContainerIDs.List() {\n\t\tif vtx, err := b.State.GetVertex(vtxID); err == nil {\n\t\t\tstoredVtxs = append(storedVtxs, vtx)\n\t\t} else {\n\t\t\tb.needToFetch.Add(vtxID)\n\t\t}\n\t}\n\tif err := b.process(storedVtxs...); err != nil {\n\t\treturn err\n\t}\n\treturn b.fetch()\n}\n\n\/\/ Finish bootstrapping\nfunc (b *bootstrapper) finish() error {\n\tif b.finished || b.outstandingRequests.Len() > 0 || b.needToFetch.Len() > 0 {\n\t\treturn nil\n\t}\n\tb.BootstrapConfig.Context.Log.Info(\"finished fetching vertices. executing transaction state transitions...\")\n\n\tif err := b.executeAll(b.TxBlocked, b.numBSBlockedTx); err != nil {\n\t\treturn err\n\t}\n\n\tb.BootstrapConfig.Context.Log.Info(\"executing vertex state transitions...\")\n\n\tif err := b.executeAll(b.VtxBlocked, b.numBSBlockedVtx); err != nil {\n\t\treturn err\n\t}\n\n\tif err := b.VM.Bootstrapped(); err != nil {\n\t\treturn fmt.Errorf(\"failed to notify VM that bootstrapping has finished: %w\",\n\t\t\terr)\n\t}\n\n\t\/\/ Start consensus\n\tif err := b.onFinished(); err != nil {\n\t\treturn err\n\t}\n\tb.finished = true\n\treturn nil\n}\n\nfunc (b *bootstrapper) executeAll(jobs *queue.Jobs, numBlocked prometheus.Gauge) error {\n\tnumExecuted := 0\n\tfor job, err := jobs.Pop(); err == nil; job, err = jobs.Pop() {\n\t\tnumBlocked.Dec()\n\t\tb.BootstrapConfig.Context.Log.Debug(\"Executing: %s\", job.ID())\n\t\tif err := jobs.Execute(job); err != nil {\n\t\t\tb.BootstrapConfig.Context.Log.Error(\"Error executing: %s\", err)\n\t\t\treturn err\n\t\t}\n\t\tif err := jobs.Commit(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tnumExecuted++\n\t\tif numExecuted%common.StatusUpdateFrequency == 0 { \/\/ Periodically print progress\n\t\t\tb.BootstrapConfig.Context.Log.Info(\"executed %d operations\", numExecuted)\n\t\t}\n\t}\n\treturn nil\n}\n<commit_msg>Removed no longer upheld invariant<commit_after>\/\/ (c) 2019-2020, Ava Labs, Inc. All rights reserved.\n\/\/ See the file LICENSE for licensing terms.\n\npackage avalanche\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/ava-labs\/gecko\/cache\"\n\t\"github.com\/ava-labs\/gecko\/ids\"\n\t\"github.com\/ava-labs\/gecko\/snow\/choices\"\n\t\"github.com\/ava-labs\/gecko\/snow\/consensus\/avalanche\"\n\t\"github.com\/ava-labs\/gecko\/snow\/engine\/common\"\n\t\"github.com\/ava-labs\/gecko\/snow\/engine\/common\/queue\"\n\t\"github.com\/ava-labs\/gecko\/utils\/formatting\"\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n)\n\nconst (\n\t\/\/ We cache processed vertices where height = c * stripeDistance for c = {1,2,3...}\n\t\/\/ This forms a \"stripe\" of cached DAG vertices at height stripeDistance, 2*stripeDistance, etc.\n\t\/\/ This helps to limit the number of repeated DAG traversals performed\n\tstripeDistance = 2000\n\tstripeWidth    = 5\n\tcacheSize      = 100000\n)\n\n\/\/ BootstrapConfig ...\ntype BootstrapConfig struct {\n\tcommon.Config\n\n\t\/\/ VtxBlocked tracks operations that are blocked on vertices\n\t\/\/ TxBlocked tracks operations that are blocked on transactions\n\tVtxBlocked, TxBlocked *queue.Jobs\n\n\tState State\n\tVM    DAGVM\n}\n\ntype bootstrapper struct {\n\tBootstrapConfig\n\tmetrics\n\tcommon.Bootstrapper\n\n\t\/\/ number of vertices fetched so far\n\tnumFetched uint32\n\n\t\/\/ tracks which validators were asked for which containers in which requests\n\toutstandingRequests common.Requests\n\n\t\/\/ IDs of vertices that we will send a GetAncestors request for once we are\n\t\/\/ not at the max number of outstanding requests\n\tneedToFetch ids.Set\n\n\t\/\/ Contains IDs of vertices that have recently been processed\n\tprocessedCache *cache.LRU\n\n\t\/\/ true if bootstrapping is done\n\tfinished bool\n\n\t\/\/ Called when bootstrapping is done\n\tonFinished func() error\n}\n\n\/\/ Initialize this engine.\nfunc (b *bootstrapper) Initialize(config BootstrapConfig) error {\n\tb.BootstrapConfig = config\n\tb.processedCache = &cache.LRU{Size: cacheSize}\n\n\tb.VtxBlocked.SetParser(&vtxParser{\n\t\tlog:         config.Context.Log,\n\t\tnumAccepted: b.numBSVtx,\n\t\tnumDropped:  b.numBSDroppedVtx,\n\t\tstate:       b.State,\n\t})\n\n\tb.TxBlocked.SetParser(&txParser{\n\t\tlog:         config.Context.Log,\n\t\tnumAccepted: b.numBSTx,\n\t\tnumDropped:  b.numBSDroppedTx,\n\t\tvm:          b.VM,\n\t})\n\n\tconfig.Bootstrapable = b\n\tb.Bootstrapper.Initialize(config.Config)\n\treturn nil\n}\n\n\/\/ CurrentAcceptedFrontier ...\nfunc (b *bootstrapper) CurrentAcceptedFrontier() ids.Set {\n\tacceptedFrontier := ids.Set{}\n\tacceptedFrontier.Add(b.State.Edge()...)\n\treturn acceptedFrontier\n}\n\n\/\/ FilterAccepted ...\nfunc (b *bootstrapper) FilterAccepted(containerIDs ids.Set) ids.Set {\n\tacceptedVtxIDs := ids.Set{}\n\tfor _, vtxID := range containerIDs.List() {\n\t\tif vtx, err := b.State.GetVertex(vtxID); err == nil && vtx.Status() == choices.Accepted {\n\t\t\tacceptedVtxIDs.Add(vtxID)\n\t\t}\n\t}\n\treturn acceptedVtxIDs\n}\n\n\/\/ Fetch vertices and their ancestors from the set of vertices that are needed\n\/\/ to be fetched.\nfunc (b *bootstrapper) fetch(vtxIDs ...ids.ID) error {\n\tb.needToFetch.Add(vtxIDs...)\n\tfor b.needToFetch.Len() > 0 && b.outstandingRequests.Len() < common.MaxOutstandingRequests {\n\t\tvtxID := b.needToFetch.CappedList(1)[0]\n\t\tb.needToFetch.Remove(vtxID)\n\n\t\t\/\/ Make sure we haven't already requested this vertex\n\t\tif b.outstandingRequests.Contains(vtxID) {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Make sure we don't already have this vertex\n\t\tif _, err := b.State.GetVertex(vtxID); err == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tvalidators := b.BootstrapConfig.Validators.Sample(1) \/\/ validator to send request to\n\t\tif len(validators) == 0 {\n\t\t\treturn fmt.Errorf(\"Dropping request for %s as there are no validators\", vtxID)\n\t\t}\n\t\tvalidatorID := validators[0].ID()\n\t\tb.RequestID++\n\n\t\tb.outstandingRequests.Add(validatorID, b.RequestID, vtxID)\n\t\tb.needToFetch.Remove(vtxID)                                            \/\/ maintains invariant that intersection with outstandingRequests is empty\n\t\tb.BootstrapConfig.Sender.GetAncestors(validatorID, b.RequestID, vtxID) \/\/ request vertex and ancestors\n\t}\n\treturn b.finish()\n}\n\n\/\/ Process vertices\nfunc (b *bootstrapper) process(vtxs ...avalanche.Vertex) error {\n\ttoProcess := newMaxVertexHeap()\n\tfor _, vtx := range vtxs {\n\t\tif _, ok := b.processedCache.Get(vtx.ID()); !ok { \/\/ only process if we haven't already\n\t\t\ttoProcess.Push(vtx)\n\t\t}\n\t}\n\n\tfor toProcess.Len() > 0 {\n\t\tvtx := toProcess.Pop()\n\t\tvtxID := vtx.ID()\n\n\t\tswitch vtx.Status() {\n\t\tcase choices.Unknown:\n\t\t\tb.fetch(vtxID)\n\t\tcase choices.Rejected:\n\t\t\tb.needToFetch.Remove(vtxID)\n\t\t\treturn fmt.Errorf(\"tried to accept %s even though it was previously rejected\", vtx.ID())\n\t\tcase choices.Processing:\n\t\t\tb.needToFetch.Remove(vtxID)\n\n\t\t\tif err := b.VtxBlocked.Push(&vertexJob{\n\t\t\t\tlog:         b.BootstrapConfig.Context.Log,\n\t\t\t\tnumAccepted: b.numBSVtx,\n\t\t\t\tnumDropped:  b.numBSDroppedVtx,\n\t\t\t\tvtx:         vtx,\n\t\t\t}); err == nil {\n\t\t\t\tb.numBSBlockedVtx.Inc()\n\t\t\t\tb.numFetched++ \/\/ Progress tracker\n\t\t\t\tif b.numFetched%common.StatusUpdateFrequency == 0 {\n\t\t\t\t\tb.BootstrapConfig.Context.Log.Info(\"fetched %d vertices\", b.numFetched)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tb.BootstrapConfig.Context.Log.Verbo(\"couldn't push to vtxBlocked: %s\", err)\n\t\t\t}\n\t\t\tfor _, tx := range vtx.Txs() {\n\t\t\t\tif err := b.TxBlocked.Push(&txJob{\n\t\t\t\t\tlog:         b.BootstrapConfig.Context.Log,\n\t\t\t\t\tnumAccepted: b.numBSTx,\n\t\t\t\t\tnumDropped:  b.numBSDroppedTx,\n\t\t\t\t\ttx:          tx,\n\t\t\t\t}); err == nil {\n\t\t\t\t\tb.numBSBlockedTx.Inc()\n\t\t\t\t} else {\n\t\t\t\t\tb.BootstrapConfig.Context.Log.Verbo(\"couldn't push to txBlocked: %s\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor _, parent := range vtx.Parents() {\n\t\t\t\tif _, ok := b.processedCache.Get(parent.ID()); !ok { \/\/ already processed this\n\t\t\t\t\ttoProcess.Push(parent)\n\t\t\t\t}\n\t\t\t}\n\t\t\tif vtx.Height()%stripeDistance < stripeWidth {\n\t\t\t\tb.processedCache.Put(vtx.ID(), nil)\n\t\t\t}\n\t\t}\n\t}\n\n\tif err := b.VtxBlocked.Commit(); err != nil {\n\t\treturn err\n\t}\n\tif err := b.TxBlocked.Commit(); err != nil {\n\t\treturn err\n\t}\n\n\treturn b.fetch()\n}\n\n\/\/ MultiPut handles the receipt of multiple containers. Should be received in response to a GetAncestors message to [vdr]\n\/\/ with request ID [requestID]. Expects vtxs[0] to be the vertex requested in the corresponding GetAncestors.\nfunc (b *bootstrapper) MultiPut(vdr ids.ShortID, requestID uint32, vtxs [][]byte) error {\n\tif lenVtxs := len(vtxs); lenVtxs > common.MaxContainersPerMultiPut {\n\t\tb.BootstrapConfig.Context.Log.Debug(\"MultiPut(%s, %d) contains more than maximum number of vertices\", vdr, requestID)\n\t\treturn b.GetAncestorsFailed(vdr, requestID)\n\t} else if lenVtxs == 0 {\n\t\tb.BootstrapConfig.Context.Log.Debug(\"MultiPut(%s, %d) contains no vertices\", vdr, requestID)\n\t\treturn b.GetAncestorsFailed(vdr, requestID)\n\t}\n\n\t\/\/ Make sure this is in response to a request we made\n\tneededVtxID, needed := b.outstandingRequests.Remove(vdr, requestID)\n\tif !needed { \/\/ this message isn't in response to a request we made\n\t\tb.BootstrapConfig.Context.Log.Debug(\"received unexpected MultiPut from %s with ID %d\", vdr, requestID)\n\t\treturn nil\n\t}\n\n\tneededVtx, err := b.State.ParseVertex(vtxs[0]) \/\/ the vertex we requested\n\tif err != nil {\n\t\tb.BootstrapConfig.Context.Log.Debug(\"Failed to parse requested vertex %s: %w\", neededVtxID, err)\n\t\tb.BootstrapConfig.Context.Log.Verbo(\"vertex: %s\", formatting.DumpBytes{Bytes: vtxs[0]})\n\t\treturn b.fetch(neededVtxID)\n\t} else if actualID := neededVtx.ID(); !actualID.Equals(neededVtxID) {\n\t\tb.BootstrapConfig.Context.Log.Debug(\"expected the first block to be the requested block, %s, but is %s\", neededVtxID, actualID)\n\t\treturn b.fetch(neededVtxID)\n\t}\n\n\tprocessVertices := make([]avalanche.Vertex, 1, len(vtxs))\n\tprocessVertices[0] = neededVtx\n\n\tfor _, vtxBytes := range vtxs[1:] { \/\/ Parse\/persist all the vertices\n\t\tif vtx, err := b.State.ParseVertex(vtxBytes); err != nil { \/\/ Persists the vtx\n\t\t\tb.BootstrapConfig.Context.Log.Debug(\"Failed to parse vertex: %w\", err)\n\t\t\tb.BootstrapConfig.Context.Log.Verbo(\"vertex: %s\", formatting.DumpBytes{Bytes: vtxBytes})\n\t\t} else {\n\t\t\tprocessVertices = append(processVertices, vtx)\n\t\t\tb.needToFetch.Remove(vtx.ID()) \/\/ No need to fetch this vertex since we have it now\n\t\t}\n\t}\n\n\treturn b.process(processVertices...)\n}\n\n\/\/ GetAncestorsFailed is called when a GetAncestors message we sent fails\nfunc (b *bootstrapper) GetAncestorsFailed(vdr ids.ShortID, requestID uint32) error {\n\tvtxID, ok := b.outstandingRequests.Remove(vdr, requestID)\n\tif !ok {\n\t\tb.BootstrapConfig.Context.Log.Debug(\"GetAncestorsFailed(%s, %d) called but there was no outstanding request to this validator with this ID\", vdr, requestID)\n\t\treturn nil\n\t}\n\t\/\/ Send another request for the vertex\n\treturn b.fetch(vtxID)\n}\n\n\/\/ ForceAccepted ...\nfunc (b *bootstrapper) ForceAccepted(acceptedContainerIDs ids.Set) error {\n\tif err := b.VM.Bootstrapping(); err != nil {\n\t\treturn fmt.Errorf(\"failed to notify VM that bootstrapping has started: %w\",\n\t\t\terr)\n\t}\n\n\tstoredVtxs := make([]avalanche.Vertex, 0, acceptedContainerIDs.Len())\n\tfor _, vtxID := range acceptedContainerIDs.List() {\n\t\tif vtx, err := b.State.GetVertex(vtxID); err == nil {\n\t\t\tstoredVtxs = append(storedVtxs, vtx)\n\t\t} else {\n\t\t\tb.needToFetch.Add(vtxID)\n\t\t}\n\t}\n\tif err := b.process(storedVtxs...); err != nil {\n\t\treturn err\n\t}\n\treturn b.fetch()\n}\n\n\/\/ Finish bootstrapping\nfunc (b *bootstrapper) finish() error {\n\tif b.finished || b.outstandingRequests.Len() > 0 || b.needToFetch.Len() > 0 {\n\t\treturn nil\n\t}\n\tb.BootstrapConfig.Context.Log.Info(\"finished fetching vertices. executing transaction state transitions...\")\n\n\tif err := b.executeAll(b.TxBlocked, b.numBSBlockedTx); err != nil {\n\t\treturn err\n\t}\n\n\tb.BootstrapConfig.Context.Log.Info(\"executing vertex state transitions...\")\n\n\tif err := b.executeAll(b.VtxBlocked, b.numBSBlockedVtx); err != nil {\n\t\treturn err\n\t}\n\n\tif err := b.VM.Bootstrapped(); err != nil {\n\t\treturn fmt.Errorf(\"failed to notify VM that bootstrapping has finished: %w\",\n\t\t\terr)\n\t}\n\n\t\/\/ Start consensus\n\tif err := b.onFinished(); err != nil {\n\t\treturn err\n\t}\n\tb.finished = true\n\treturn nil\n}\n\nfunc (b *bootstrapper) executeAll(jobs *queue.Jobs, numBlocked prometheus.Gauge) error {\n\tnumExecuted := 0\n\tfor job, err := jobs.Pop(); err == nil; job, err = jobs.Pop() {\n\t\tnumBlocked.Dec()\n\t\tb.BootstrapConfig.Context.Log.Debug(\"Executing: %s\", job.ID())\n\t\tif err := jobs.Execute(job); err != nil {\n\t\t\tb.BootstrapConfig.Context.Log.Error(\"Error executing: %s\", err)\n\t\t\treturn err\n\t\t}\n\t\tif err := jobs.Commit(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tnumExecuted++\n\t\tif numExecuted%common.StatusUpdateFrequency == 0 { \/\/ Periodically print progress\n\t\t\tb.BootstrapConfig.Context.Log.Info(\"executed %d operations\", numExecuted)\n\t\t}\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package command\n\nimport (\n\t\"os\"\n)\n\ntype MountOptions struct {\n\tfiler                       *string\n\tfilerMountRootPath          *string\n\tdir                         *string\n\tdirListCacheLimit           *int64\n\tcollection                  *string\n\treplication                 *string\n\tttlSec                      *int\n\tchunkSizeLimitMB            *int\n\tcacheDir                    *string\n\tcacheSizeMB                 *int64\n\tdataCenter                  *string\n\tallowOthers                 *bool\n\tumaskString                 *string\n\tnonempty                    *bool\n\toutsideContainerClusterMode *bool\n}\n\nvar (\n\tmountOptions    MountOptions\n\tmountCpuProfile *string\n\tmountMemProfile *string\n)\n\nfunc init() {\n\tcmdMount.Run = runMount \/\/ break init cycle\n\tmountOptions.filer = cmdMount.Flag.String(\"filer\", \"localhost:8888\", \"weed filer location\")\n\tmountOptions.filerMountRootPath = cmdMount.Flag.String(\"filer.path\", \"\/\", \"mount this remote path from filer server\")\n\tmountOptions.dir = cmdMount.Flag.String(\"dir\", \".\", \"mount weed filer to this directory\")\n\tmountOptions.dirListCacheLimit = cmdMount.Flag.Int64(\"dirListCacheLimit\", 1000000, \"limit cache size to speed up directory long format listing\")\n\tmountOptions.collection = cmdMount.Flag.String(\"collection\", \"\", \"collection to create the files\")\n\tmountOptions.replication = cmdMount.Flag.String(\"replication\", \"\", \"replication(e.g. 000, 001) to create to files. If empty, let filer decide.\")\n\tmountOptions.ttlSec = cmdMount.Flag.Int(\"ttl\", 0, \"file ttl in seconds\")\n\tmountOptions.chunkSizeLimitMB = cmdMount.Flag.Int(\"chunkSizeLimitMB\", 4, \"local write buffer size, also chunk large files\")\n\tmountOptions.cacheDir = cmdMount.Flag.String(\"cacheDir\", os.TempDir(), \"local cache directory for file chunks\")\n\tmountOptions.cacheSizeMB = cmdMount.Flag.Int64(\"cacheCapacityMB\", 1000, \"local cache capacity in MB\")\n\tmountOptions.dataCenter = cmdMount.Flag.String(\"dataCenter\", \"\", \"prefer to write to the data center\")\n\tmountOptions.allowOthers = cmdMount.Flag.Bool(\"allowOthers\", true, \"allows other users to access the file system\")\n\tmountOptions.umaskString = cmdMount.Flag.String(\"umask\", \"022\", \"octal umask, e.g., 022, 0111\")\n\tmountOptions.nonempty = cmdMount.Flag.Bool(\"nonempty\", false, \"allows the mounting over a non-empty directory\")\n\tmountCpuProfile = cmdMount.Flag.String(\"cpuprofile\", \"\", \"cpu profile output file\")\n\tmountMemProfile = cmdMount.Flag.String(\"memprofile\", \"\", \"memory profile output file\")\n\tmountOptions.outsideContainerClusterMode = cmdMount.Flag.Bool(\"outsideContainerClusterMode\", false, \"allows other users to access the file system\")\n}\n\nvar cmdMount = &Command{\n\tUsageLine: \"mount -filer=localhost:8888 -dir=\/some\/dir\",\n\tShort:     \"mount weed filer to a directory as file system in userspace(FUSE)\",\n\tLong: `mount weed filer to userspace.\n\n  Pre-requisites:\n  1) have SeaweedFS master and volume servers running\n  2) have a \"weed filer\" running\n  These 2 requirements can be achieved with one command \"weed server -filer=true\"\n\n  This uses github.com\/seaweedfs\/fuse, which enables writing FUSE file systems on\n  Linux, and OS X.\n\n  On OS X, it requires OSXFUSE (http:\/\/osxfuse.github.com\/).\n\n  If the SeaweedFS system runs in a container cluster, e.g. managed by kubernetes or docker compose,\n  the volume servers are not accessible by their own ip addresses. \n  In \"outsideContainerClusterMode\", the mount will use the filer ip address instead, assuming:\n    * All volume server containers are accessible through the same hostname or IP address as the filer.\n    * All volume server container ports are open external to the cluster.\n\n  `,\n}\n<commit_msg>set default chunk size to 16<commit_after>package command\n\nimport (\n\t\"os\"\n)\n\ntype MountOptions struct {\n\tfiler                       *string\n\tfilerMountRootPath          *string\n\tdir                         *string\n\tdirListCacheLimit           *int64\n\tcollection                  *string\n\treplication                 *string\n\tttlSec                      *int\n\tchunkSizeLimitMB            *int\n\tcacheDir                    *string\n\tcacheSizeMB                 *int64\n\tdataCenter                  *string\n\tallowOthers                 *bool\n\tumaskString                 *string\n\tnonempty                    *bool\n\toutsideContainerClusterMode *bool\n}\n\nvar (\n\tmountOptions    MountOptions\n\tmountCpuProfile *string\n\tmountMemProfile *string\n)\n\nfunc init() {\n\tcmdMount.Run = runMount \/\/ break init cycle\n\tmountOptions.filer = cmdMount.Flag.String(\"filer\", \"localhost:8888\", \"weed filer location\")\n\tmountOptions.filerMountRootPath = cmdMount.Flag.String(\"filer.path\", \"\/\", \"mount this remote path from filer server\")\n\tmountOptions.dir = cmdMount.Flag.String(\"dir\", \".\", \"mount weed filer to this directory\")\n\tmountOptions.dirListCacheLimit = cmdMount.Flag.Int64(\"dirListCacheLimit\", 1000000, \"limit cache size to speed up directory long format listing\")\n\tmountOptions.collection = cmdMount.Flag.String(\"collection\", \"\", \"collection to create the files\")\n\tmountOptions.replication = cmdMount.Flag.String(\"replication\", \"\", \"replication(e.g. 000, 001) to create to files. If empty, let filer decide.\")\n\tmountOptions.ttlSec = cmdMount.Flag.Int(\"ttl\", 0, \"file ttl in seconds\")\n\tmountOptions.chunkSizeLimitMB = cmdMount.Flag.Int(\"chunkSizeLimitMB\", 16, \"local write buffer size, also chunk large files\")\n\tmountOptions.cacheDir = cmdMount.Flag.String(\"cacheDir\", os.TempDir(), \"local cache directory for file chunks\")\n\tmountOptions.cacheSizeMB = cmdMount.Flag.Int64(\"cacheCapacityMB\", 1000, \"local cache capacity in MB\")\n\tmountOptions.dataCenter = cmdMount.Flag.String(\"dataCenter\", \"\", \"prefer to write to the data center\")\n\tmountOptions.allowOthers = cmdMount.Flag.Bool(\"allowOthers\", true, \"allows other users to access the file system\")\n\tmountOptions.umaskString = cmdMount.Flag.String(\"umask\", \"022\", \"octal umask, e.g., 022, 0111\")\n\tmountOptions.nonempty = cmdMount.Flag.Bool(\"nonempty\", false, \"allows the mounting over a non-empty directory\")\n\tmountCpuProfile = cmdMount.Flag.String(\"cpuprofile\", \"\", \"cpu profile output file\")\n\tmountMemProfile = cmdMount.Flag.String(\"memprofile\", \"\", \"memory profile output file\")\n\tmountOptions.outsideContainerClusterMode = cmdMount.Flag.Bool(\"outsideContainerClusterMode\", false, \"allows other users to access the file system\")\n}\n\nvar cmdMount = &Command{\n\tUsageLine: \"mount -filer=localhost:8888 -dir=\/some\/dir\",\n\tShort:     \"mount weed filer to a directory as file system in userspace(FUSE)\",\n\tLong: `mount weed filer to userspace.\n\n  Pre-requisites:\n  1) have SeaweedFS master and volume servers running\n  2) have a \"weed filer\" running\n  These 2 requirements can be achieved with one command \"weed server -filer=true\"\n\n  This uses github.com\/seaweedfs\/fuse, which enables writing FUSE file systems on\n  Linux, and OS X.\n\n  On OS X, it requires OSXFUSE (http:\/\/osxfuse.github.com\/).\n\n  If the SeaweedFS system runs in a container cluster, e.g. managed by kubernetes or docker compose,\n  the volume servers are not accessible by their own ip addresses. \n  In \"outsideContainerClusterMode\", the mount will use the filer ip address instead, assuming:\n    * All volume server containers are accessible through the same hostname or IP address as the filer.\n    * All volume server container ports are open external to the cluster.\n\n  `,\n}\n<|endoftext|>"}
{"text":"<commit_before>package vsphere\n\nimport (\n\t\"log\"\n\n\t\"github.com\/vmware\/govmomi\"\n\t\"github.com\/vmware\/govmomi\/find\"\n\t\"github.com\/vmware\/govmomi\/object\"\n\t\"github.com\/vmware\/govmomi\/vim25\/mo\"\n\t\"github.com\/vmware\/govmomi\/vim25\/types\"\n\t\"golang.org\/x\/net\/context\"\n)\n\nconst (\n\tdefaultTimeZone = \"Etc\/UTC\"\n\tdefaultDomain   = \"vsphere.local\"\n)\n\ntype networkInterface struct {\n\tdeviceName string\n\tlabel      string\n\tipAddress  string\n\tsubnetMask string\n}\n\ntype additionalHardDisk struct {\n\tsize int64\n\tiops int64\n}\n\ntype virtualMachine struct {\n\tname                string\n\tdatacenter          string\n\tcluster             string\n\tresourcePool        string\n\tdatastore           string\n\tvcpu                int\n\tmemoryMb            int64\n\ttemplate            string\n\tnetworkInterfaces   []networkInterface\n\tadditionalHardDisks []additionalHardDisk\n\tgateway             string\n\tdomain              string\n\ttimeZone            string\n\tdnsSuffixes         []string\n\tdnsServers          []string\n}\n\nfunc (vm *virtualMachine) deployVirtualMachine(c *govmomi.Client) error {\n\tif len(vm.dnsServers) == 0 {\n\t\tvm.dnsServers = []string{\n\t\t\t\"8.8.8.8\",\n\t\t\t\"8.8.4.4\",\n\t\t}\n\t}\n\n\tif len(vm.dnsSuffixes) == 0 {\n\t\tvm.dnsSuffixes = []string{\n\t\t\tdefaultDomain,\n\t\t}\n\t}\n\n\tif vm.domain == \"\" {\n\t\tvm.domain = defaultDomain\n\t}\n\n\tif vm.timeZone == \"\" {\n\t\tvm.timeZone = defaultTimeZone\n\t}\n\n\tfinder := find.NewFinder(c.Client, true)\n\tdc, err := findDatacenter(finder, vm.datacenter)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfinder = finder.SetDatacenter(dc)\n\n\ttemplate, err := finder.VirtualMachine(context.TODO(), vm.template)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Printf(\"[DEBUG] template: %#v\", template)\n\n\tresourcePool, err := findResourcePool(finder, vm.resourcePool, vm.cluster)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Printf(\"[DEBUG] resource pool: %#v\", resourcePool)\n\n\tdcFolders, err := dc.Folders(context.TODO())\n\tif err != nil {\n\t\treturn err\n\t}\n\tdatastore, err := findDatastore(c, finder, dcFolders, template, resourcePool, vm.datastore)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Printf(\"[DEBUG] datastore: %#v\", datastore)\n\n\trelocateSpec, err := getVMRelocateSpec(resourcePool, datastore, template)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Printf(\"[DEBUG] relocate spec: %v\", relocateSpec)\n\n\t\/\/ network\n\tnetworkDevices := []types.BaseVirtualDeviceConfigSpec{}\n\tnetworkConfigs := []types.CustomizationAdapterMapping{}\n\tfor _, network := range vm.networkInterfaces {\n\t\t\/\/ network device\n\t\tdevice, err := networkDevice(finder, network.label)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tnetworkDevices = append(networkDevices, device)\n\n\t\tvar ipSetting types.CustomizationIPSettings\n\t\tif network.ipAddress == \"\" {\n\t\t\tipSetting = types.CustomizationIPSettings{\n\t\t\t\tIp: &types.CustomizationDhcpIpGenerator{},\n\t\t\t}\n\t\t} else {\n\t\t\tipSetting = types.CustomizationIPSettings{\n\t\t\t\tGateway: []string{\n\t\t\t\t\tvm.gateway,\n\t\t\t\t},\n\t\t\t\tIp: &types.CustomizationFixedIp{\n\t\t\t\t\tIpAddress: network.ipAddress,\n\t\t\t\t},\n\t\t\t\tSubnetMask: network.subnetMask,\n\t\t\t}\n\t\t}\n\n\t\t\/\/ network config\n\t\tconfig := types.CustomizationAdapterMapping{\n\t\t\tAdapter: ipSetting,\n\t\t}\n\t\tnetworkConfigs = append(networkConfigs, config)\n\t}\n\tlog.Printf(\"[DEBUG] network configs: %v\", networkConfigs[0].Adapter)\n\n\t\/\/ make config spec\n\tconfigSpec := types.VirtualMachineConfigSpec{\n\t\tNumCPUs:           vm.vcpu,\n\t\tNumCoresPerSocket: 1,\n\t\tMemoryMB:          vm.memoryMb,\n\t\tDeviceChange:      networkDevices,\n\t}\n\tlog.Printf(\"[DEBUG] virtual machine config spec: %v\", configSpec)\n\n\t\/\/ make custom spec\n\tcustomSpec := createCustomizationSpec(vm.name, vm.domain, vm.timeZone, vm.dnsSuffixes, vm.dnsServers, networkConfigs)\n\tlog.Printf(\"[DEBUG] custom spec: %v\", customSpec)\n\n\t\/\/ make vm clone spec\n\tcloneSpec := types.VirtualMachineCloneSpec{\n\t\tLocation:      relocateSpec,\n\t\tTemplate:      false,\n\t\tConfig:        &configSpec,\n\t\tCustomization: &customSpec,\n\t\tPowerOn:       true,\n\t}\n\tlog.Printf(\"[DEBUG] clone spec: %v\", cloneSpec)\n\n\ttask, err := template.Clone(context.TODO(), dcFolders.VmFolder, vm.name, cloneSpec)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = task.Wait(context.TODO())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnewVM, err := finder.VirtualMachine(context.TODO(), vm.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Printf(\"[DEBUG] new vm: %v\", newVM)\n\n\tip, err := newVM.WaitForIP(context.TODO())\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Printf(\"[DEBUG] ip address: %v\", ip)\n\n\tfor _, hd := range vm.additionalHardDisks {\n\t\terr = addHardDisk(newVM, hd.size, hd.iops)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc findDatastoreForClone(c *govmomi.Client, storagePod *object.Folder, template *object.VirtualMachine, vmFolder *object.Folder, resourcePool *object.ResourcePool) (*object.Datastore, error) {\n\n\ttemplateRef := template.Reference()\n\tvmFolderRef := vmFolder.Reference()\n\tresourcePoolRef := resourcePool.Reference()\n\tstoragePodRef := storagePod.Reference()\n\n\tvar o mo.VirtualMachine\n\terr := template.Properties(context.TODO(), templateRef, []string{\"datastore\"}, &o)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttemplateDatastore := object.NewDatastore(c.Client, o.Datastore[0])\n\tlog.Printf(\"[DEBUG] %#v\\n\", templateDatastore)\n\n\tdevices, err := template.Device(context.TODO())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar key int\n\tfor _, d := range devices.SelectByType((*types.VirtualDisk)(nil)) {\n\t\tkey = d.GetVirtualDevice().Key\n\t\tlog.Printf(\"[DEBUG] %#v\\n\", d.GetVirtualDevice())\n\t}\n\n\tsps := types.StoragePlacementSpec{\n\t\tType: \"clone\",\n\t\tVm:   &templateRef,\n\t\tPodSelectionSpec: types.StorageDrsPodSelectionSpec{\n\t\t\tStoragePod: &storagePodRef,\n\t\t},\n\t\tCloneSpec: &types.VirtualMachineCloneSpec{\n\t\t\tLocation: types.VirtualMachineRelocateSpec{\n\t\t\t\tDisk: []types.VirtualMachineRelocateSpecDiskLocator{\n\t\t\t\t\ttypes.VirtualMachineRelocateSpecDiskLocator{\n\t\t\t\t\t\tDatastore:       templateDatastore.Reference(),\n\t\t\t\t\t\tDiskBackingInfo: &types.VirtualDiskFlatVer2BackingInfo{},\n\t\t\t\t\t\tDiskId:          key,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tPool: &resourcePoolRef,\n\t\t\t},\n\t\t\tPowerOn:  false,\n\t\t\tTemplate: false,\n\t\t},\n\t\tCloneName: \"dummy\",\n\t\tFolder:    &vmFolderRef,\n\t}\n\tlog.Printf(\"[DEBUG] findDatastoreForClone: StoragePlacementSpec: %v\", sps)\n\n\tsrm := object.NewStorageResourceManager(c.Client)\n\tresult, err := srm.RecommendDatastores(context.TODO(), sps)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Printf(\"[DEBUG] findDatastoreForClone: result: %v\", result)\n\tspa := result.Recommendations[0].Action[0].(*types.StoragePlacementAction)\n\tdatastore := object.NewDatastore(c.Client, spa.Destination)\n\n\treturn datastore, nil\n}\n\n\/\/ findDatastore finds Datastore object.\nfunc findDatastore(c *govmomi.Client, finder *find.Finder, f *object.DatacenterFolders, template *object.VirtualMachine, resourcePool *object.ResourcePool, name string) (*object.Datastore, error) {\n\tif name == \"\" {\n\t\tdatastore, err := finder.DefaultDatastore(context.TODO())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tlog.Printf(\"[DEBUG] findDatastore: datastore: %#v\", datastore)\n\t\treturn datastore, nil\n\t} else {\n\t\tvar datastore *object.Datastore\n\t\ts := object.NewSearchIndex(c.Client)\n\t\tref, err := s.FindChild(context.TODO(), f.DatastoreFolder, name)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tlog.Printf(\"[DEBUG] findDatastore: reference: %#v\", ref)\n\n\t\tmor := ref.Reference()\n\t\tif mor.Type == \"StoragePod\" {\n\t\t\ts := object.NewFolder(c.Client, mor)\n\t\t\tdatastore, err = findDatastoreForClone(c, s, template, f.VmFolder, resourcePool)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else {\n\t\t\tdatastore = object.NewDatastore(c.Client, mor)\n\t\t}\n\t\tlog.Printf(\"[DEBUG] findDatastore: datastore: %#v\", datastore)\n\t\treturn datastore, nil\n\t}\n}\n\nfunc networkDevice(f *find.Finder, label string) (*types.VirtualDeviceConfigSpec, error) {\n\tnetwork, err := f.Network(context.TODO(), \"*\"+label)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbacking, err := network.EthernetCardBackingInfo(context.TODO())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\td := types.VirtualDeviceConfigSpec{\n\t\tOperation: types.VirtualDeviceConfigSpecOperationAdd,\n\t\tDevice: &types.VirtualVmxnet3{\n\t\t\ttypes.VirtualVmxnet{\n\t\t\t\ttypes.VirtualEthernetCard{\n\t\t\t\t\tVirtualDevice: types.VirtualDevice{\n\t\t\t\t\t\tKey:     -1,\n\t\t\t\t\t\tBacking: backing,\n\t\t\t\t\t},\n\t\t\t\t\tAddressType: string(types.VirtualEthernetCardMacTypeGenerated),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\treturn &d, nil\n}\n\n\/\/ findDatacenter finds Datacenter object.\nfunc findDatacenter(f *find.Finder, name string) (*object.Datacenter, error) {\n\tif name != \"\" {\n\t\tdc, err := f.Datacenter(context.TODO(), name)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn dc, nil\n\t} else {\n\t\tdc, err := f.DefaultDatacenter(context.TODO())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn dc, nil\n\t}\n}\n\n\/\/ findResourcePool finds ResourcePool object\nfunc findResourcePool(f *find.Finder, name, cluster string) (*object.ResourcePool, error) {\n\tif name == \"\" {\n\t\tif cluster == \"\" {\n\t\t\tresourcePool, err := f.DefaultResourcePool(context.TODO())\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn resourcePool, nil\n\t\t} else {\n\t\t\tresourcePool, err := f.ResourcePool(context.TODO(), \"*\"+cluster+\"\/Resources\")\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn resourcePool, nil\n\t\t}\n\t} else {\n\t\tresourcePool, err := f.ResourcePool(context.TODO(), name)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn resourcePool, nil\n\t}\n}\n\nfunc getVMRelocateSpec(rp *object.ResourcePool, ds *object.Datastore, vm *object.VirtualMachine) (types.VirtualMachineRelocateSpec, error) {\n\tvar key int\n\n\tdevices, err := vm.Device(context.TODO())\n\tif err != nil {\n\t\treturn types.VirtualMachineRelocateSpec{}, err\n\t}\n\tfor _, d := range devices {\n\t\tif devices.Type(d) == \"disk\" {\n\t\t\tkey = d.GetVirtualDevice().Key\n\t\t}\n\t}\n\n\trpr := rp.Reference()\n\tdsr := ds.Reference()\n\treturn types.VirtualMachineRelocateSpec{\n\t\tDatastore: &dsr,\n\t\tPool:      &rpr,\n\t\tDisk: []types.VirtualMachineRelocateSpecDiskLocator{\n\t\t\ttypes.VirtualMachineRelocateSpecDiskLocator{\n\t\t\t\tDatastore: dsr,\n\t\t\t\tDiskBackingInfo: &types.VirtualDiskFlatVer2BackingInfo{\n\t\t\t\t\tDiskMode:        \"persistent\",\n\t\t\t\t\tThinProvisioned: types.NewBool(false),\n\t\t\t\t\tEagerlyScrub:    types.NewBool(true),\n\t\t\t\t},\n\t\t\t\tDiskId: key,\n\t\t\t},\n\t\t},\n\t}, nil\n}\n\n\/\/ createCustomizationSpec creates the CustomizationSpec object.\nfunc createCustomizationSpec(name, domain, tz string, suffixes, servers []string, nics []types.CustomizationAdapterMapping) types.CustomizationSpec {\n\treturn types.CustomizationSpec{\n\t\tIdentity: &types.CustomizationLinuxPrep{\n\t\t\tHostName: &types.CustomizationFixedName{\n\t\t\t\tName: name,\n\t\t\t},\n\t\t\tDomain:     domain,\n\t\t\tTimeZone:   tz,\n\t\t\tHwClockUTC: types.NewBool(true),\n\t\t},\n\t\tGlobalIPSettings: types.CustomizationGlobalIPSettings{\n\t\t\tDnsSuffixList: suffixes,\n\t\t\tDnsServerList: servers,\n\t\t},\n\t\tNicSettingMap: nics,\n\t}\n}\n\nfunc addHardDisk(vm *object.VirtualMachine, size, iops int64) error {\n\tdevices, err := vm.Device(context.TODO())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcontroller, err := devices.FindDiskController(\"scsi\")\n\tif err != nil {\n\t\tlog.Printf(\"[ERROR] %s\", err)\n\t}\n\tlog.Printf(\"[DEBUG] %#v\\n\", controller)\n\n\tdisk := devices.CreateDisk(controller, \"\")\n\n\texisting := devices.SelectByBackingInfo(disk.Backing)\n\tlog.Printf(\"[DEBUG] %#v\\n\", existing)\n\n\tif len(existing) == 0 {\n\t\tdisk.CapacityInKB = int64(size * 1024 * 1024)\n\t\tdisk.StorageIOAllocation = &types.StorageIOAllocationInfo{\n\t\t\tLimit: iops,\n\t\t}\n\t} else {\n\t\tlog.Printf(\"Disk already present\\n\")\n\t}\n\n\tbacking := disk.Backing.(*types.VirtualDiskFlatVer2BackingInfo)\n\n\t\/\/ eager zeroed thick virtual disk\n\tbacking.ThinProvisioned = types.NewBool(false)\n\tbacking.EagerlyScrub = types.NewBool(true)\n\n\treturn vm.AddDevice(context.TODO(), disk)\n}\n<commit_msg>Add if statement for empty of iops value<commit_after>package vsphere\n\nimport (\n\t\"log\"\n\n\t\"github.com\/vmware\/govmomi\"\n\t\"github.com\/vmware\/govmomi\/find\"\n\t\"github.com\/vmware\/govmomi\/object\"\n\t\"github.com\/vmware\/govmomi\/vim25\/mo\"\n\t\"github.com\/vmware\/govmomi\/vim25\/types\"\n\t\"golang.org\/x\/net\/context\"\n)\n\nconst (\n\tdefaultTimeZone = \"Etc\/UTC\"\n\tdefaultDomain   = \"vsphere.local\"\n)\n\ntype networkInterface struct {\n\tdeviceName string\n\tlabel      string\n\tipAddress  string\n\tsubnetMask string\n}\n\ntype additionalHardDisk struct {\n\tsize int64\n\tiops int64\n}\n\ntype virtualMachine struct {\n\tname                string\n\tdatacenter          string\n\tcluster             string\n\tresourcePool        string\n\tdatastore           string\n\tvcpu                int\n\tmemoryMb            int64\n\ttemplate            string\n\tnetworkInterfaces   []networkInterface\n\tadditionalHardDisks []additionalHardDisk\n\tgateway             string\n\tdomain              string\n\ttimeZone            string\n\tdnsSuffixes         []string\n\tdnsServers          []string\n}\n\nfunc (vm *virtualMachine) deployVirtualMachine(c *govmomi.Client) error {\n\tif len(vm.dnsServers) == 0 {\n\t\tvm.dnsServers = []string{\n\t\t\t\"8.8.8.8\",\n\t\t\t\"8.8.4.4\",\n\t\t}\n\t}\n\n\tif len(vm.dnsSuffixes) == 0 {\n\t\tvm.dnsSuffixes = []string{\n\t\t\tdefaultDomain,\n\t\t}\n\t}\n\n\tif vm.domain == \"\" {\n\t\tvm.domain = defaultDomain\n\t}\n\n\tif vm.timeZone == \"\" {\n\t\tvm.timeZone = defaultTimeZone\n\t}\n\n\tfinder := find.NewFinder(c.Client, true)\n\tdc, err := findDatacenter(finder, vm.datacenter)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfinder = finder.SetDatacenter(dc)\n\n\ttemplate, err := finder.VirtualMachine(context.TODO(), vm.template)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Printf(\"[DEBUG] template: %#v\", template)\n\n\tresourcePool, err := findResourcePool(finder, vm.resourcePool, vm.cluster)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Printf(\"[DEBUG] resource pool: %#v\", resourcePool)\n\n\tdcFolders, err := dc.Folders(context.TODO())\n\tif err != nil {\n\t\treturn err\n\t}\n\tdatastore, err := findDatastore(c, finder, dcFolders, template, resourcePool, vm.datastore)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Printf(\"[DEBUG] datastore: %#v\", datastore)\n\n\trelocateSpec, err := getVMRelocateSpec(resourcePool, datastore, template)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Printf(\"[DEBUG] relocate spec: %v\", relocateSpec)\n\n\t\/\/ network\n\tnetworkDevices := []types.BaseVirtualDeviceConfigSpec{}\n\tnetworkConfigs := []types.CustomizationAdapterMapping{}\n\tfor _, network := range vm.networkInterfaces {\n\t\t\/\/ network device\n\t\tdevice, err := networkDevice(finder, network.label)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tnetworkDevices = append(networkDevices, device)\n\n\t\tvar ipSetting types.CustomizationIPSettings\n\t\tif network.ipAddress == \"\" {\n\t\t\tipSetting = types.CustomizationIPSettings{\n\t\t\t\tIp: &types.CustomizationDhcpIpGenerator{},\n\t\t\t}\n\t\t} else {\n\t\t\tipSetting = types.CustomizationIPSettings{\n\t\t\t\tGateway: []string{\n\t\t\t\t\tvm.gateway,\n\t\t\t\t},\n\t\t\t\tIp: &types.CustomizationFixedIp{\n\t\t\t\t\tIpAddress: network.ipAddress,\n\t\t\t\t},\n\t\t\t\tSubnetMask: network.subnetMask,\n\t\t\t}\n\t\t}\n\n\t\t\/\/ network config\n\t\tconfig := types.CustomizationAdapterMapping{\n\t\t\tAdapter: ipSetting,\n\t\t}\n\t\tnetworkConfigs = append(networkConfigs, config)\n\t}\n\tlog.Printf(\"[DEBUG] network configs: %v\", networkConfigs[0].Adapter)\n\n\t\/\/ make config spec\n\tconfigSpec := types.VirtualMachineConfigSpec{\n\t\tNumCPUs:           vm.vcpu,\n\t\tNumCoresPerSocket: 1,\n\t\tMemoryMB:          vm.memoryMb,\n\t\tDeviceChange:      networkDevices,\n\t}\n\tlog.Printf(\"[DEBUG] virtual machine config spec: %v\", configSpec)\n\n\t\/\/ make custom spec\n\tcustomSpec := createCustomizationSpec(vm.name, vm.domain, vm.timeZone, vm.dnsSuffixes, vm.dnsServers, networkConfigs)\n\tlog.Printf(\"[DEBUG] custom spec: %v\", customSpec)\n\n\t\/\/ make vm clone spec\n\tcloneSpec := types.VirtualMachineCloneSpec{\n\t\tLocation:      relocateSpec,\n\t\tTemplate:      false,\n\t\tConfig:        &configSpec,\n\t\tCustomization: &customSpec,\n\t\tPowerOn:       true,\n\t}\n\tlog.Printf(\"[DEBUG] clone spec: %v\", cloneSpec)\n\n\ttask, err := template.Clone(context.TODO(), dcFolders.VmFolder, vm.name, cloneSpec)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = task.Wait(context.TODO())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnewVM, err := finder.VirtualMachine(context.TODO(), vm.name)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Printf(\"[DEBUG] new vm: %v\", newVM)\n\n\tip, err := newVM.WaitForIP(context.TODO())\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Printf(\"[DEBUG] ip address: %v\", ip)\n\n\tfor _, hd := range vm.additionalHardDisks {\n\t\terr = addHardDisk(newVM, hd.size, hd.iops)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc findDatastoreForClone(c *govmomi.Client, storagePod *object.Folder, template *object.VirtualMachine, vmFolder *object.Folder, resourcePool *object.ResourcePool) (*object.Datastore, error) {\n\n\ttemplateRef := template.Reference()\n\tvmFolderRef := vmFolder.Reference()\n\tresourcePoolRef := resourcePool.Reference()\n\tstoragePodRef := storagePod.Reference()\n\n\tvar o mo.VirtualMachine\n\terr := template.Properties(context.TODO(), templateRef, []string{\"datastore\"}, &o)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttemplateDatastore := object.NewDatastore(c.Client, o.Datastore[0])\n\tlog.Printf(\"[DEBUG] %#v\\n\", templateDatastore)\n\n\tdevices, err := template.Device(context.TODO())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar key int\n\tfor _, d := range devices.SelectByType((*types.VirtualDisk)(nil)) {\n\t\tkey = d.GetVirtualDevice().Key\n\t\tlog.Printf(\"[DEBUG] %#v\\n\", d.GetVirtualDevice())\n\t}\n\n\tsps := types.StoragePlacementSpec{\n\t\tType: \"clone\",\n\t\tVm:   &templateRef,\n\t\tPodSelectionSpec: types.StorageDrsPodSelectionSpec{\n\t\t\tStoragePod: &storagePodRef,\n\t\t},\n\t\tCloneSpec: &types.VirtualMachineCloneSpec{\n\t\t\tLocation: types.VirtualMachineRelocateSpec{\n\t\t\t\tDisk: []types.VirtualMachineRelocateSpecDiskLocator{\n\t\t\t\t\ttypes.VirtualMachineRelocateSpecDiskLocator{\n\t\t\t\t\t\tDatastore:       templateDatastore.Reference(),\n\t\t\t\t\t\tDiskBackingInfo: &types.VirtualDiskFlatVer2BackingInfo{},\n\t\t\t\t\t\tDiskId:          key,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tPool: &resourcePoolRef,\n\t\t\t},\n\t\t\tPowerOn:  false,\n\t\t\tTemplate: false,\n\t\t},\n\t\tCloneName: \"dummy\",\n\t\tFolder:    &vmFolderRef,\n\t}\n\tlog.Printf(\"[DEBUG] findDatastoreForClone: StoragePlacementSpec: %v\", sps)\n\n\tsrm := object.NewStorageResourceManager(c.Client)\n\tresult, err := srm.RecommendDatastores(context.TODO(), sps)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Printf(\"[DEBUG] findDatastoreForClone: result: %v\", result)\n\tspa := result.Recommendations[0].Action[0].(*types.StoragePlacementAction)\n\tdatastore := object.NewDatastore(c.Client, spa.Destination)\n\n\treturn datastore, nil\n}\n\n\/\/ findDatastore finds Datastore object.\nfunc findDatastore(c *govmomi.Client, finder *find.Finder, f *object.DatacenterFolders, template *object.VirtualMachine, resourcePool *object.ResourcePool, name string) (*object.Datastore, error) {\n\tif name == \"\" {\n\t\tdatastore, err := finder.DefaultDatastore(context.TODO())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tlog.Printf(\"[DEBUG] findDatastore: datastore: %#v\", datastore)\n\t\treturn datastore, nil\n\t} else {\n\t\tvar datastore *object.Datastore\n\t\ts := object.NewSearchIndex(c.Client)\n\t\tref, err := s.FindChild(context.TODO(), f.DatastoreFolder, name)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tlog.Printf(\"[DEBUG] findDatastore: reference: %#v\", ref)\n\n\t\tmor := ref.Reference()\n\t\tif mor.Type == \"StoragePod\" {\n\t\t\ts := object.NewFolder(c.Client, mor)\n\t\t\tdatastore, err = findDatastoreForClone(c, s, template, f.VmFolder, resourcePool)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else {\n\t\t\tdatastore = object.NewDatastore(c.Client, mor)\n\t\t}\n\t\tlog.Printf(\"[DEBUG] findDatastore: datastore: %#v\", datastore)\n\t\treturn datastore, nil\n\t}\n}\n\nfunc networkDevice(f *find.Finder, label string) (*types.VirtualDeviceConfigSpec, error) {\n\tnetwork, err := f.Network(context.TODO(), \"*\"+label)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbacking, err := network.EthernetCardBackingInfo(context.TODO())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\td := types.VirtualDeviceConfigSpec{\n\t\tOperation: types.VirtualDeviceConfigSpecOperationAdd,\n\t\tDevice: &types.VirtualVmxnet3{\n\t\t\ttypes.VirtualVmxnet{\n\t\t\t\ttypes.VirtualEthernetCard{\n\t\t\t\t\tVirtualDevice: types.VirtualDevice{\n\t\t\t\t\t\tKey:     -1,\n\t\t\t\t\t\tBacking: backing,\n\t\t\t\t\t},\n\t\t\t\t\tAddressType: string(types.VirtualEthernetCardMacTypeGenerated),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\treturn &d, nil\n}\n\n\/\/ findDatacenter finds Datacenter object.\nfunc findDatacenter(f *find.Finder, name string) (*object.Datacenter, error) {\n\tif name != \"\" {\n\t\tdc, err := f.Datacenter(context.TODO(), name)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn dc, nil\n\t} else {\n\t\tdc, err := f.DefaultDatacenter(context.TODO())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn dc, nil\n\t}\n}\n\n\/\/ findResourcePool finds ResourcePool object\nfunc findResourcePool(f *find.Finder, name, cluster string) (*object.ResourcePool, error) {\n\tif name == \"\" {\n\t\tif cluster == \"\" {\n\t\t\tresourcePool, err := f.DefaultResourcePool(context.TODO())\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn resourcePool, nil\n\t\t} else {\n\t\t\tresourcePool, err := f.ResourcePool(context.TODO(), \"*\"+cluster+\"\/Resources\")\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn resourcePool, nil\n\t\t}\n\t} else {\n\t\tresourcePool, err := f.ResourcePool(context.TODO(), name)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn resourcePool, nil\n\t}\n}\n\nfunc getVMRelocateSpec(rp *object.ResourcePool, ds *object.Datastore, vm *object.VirtualMachine) (types.VirtualMachineRelocateSpec, error) {\n\tvar key int\n\n\tdevices, err := vm.Device(context.TODO())\n\tif err != nil {\n\t\treturn types.VirtualMachineRelocateSpec{}, err\n\t}\n\tfor _, d := range devices {\n\t\tif devices.Type(d) == \"disk\" {\n\t\t\tkey = d.GetVirtualDevice().Key\n\t\t}\n\t}\n\n\trpr := rp.Reference()\n\tdsr := ds.Reference()\n\treturn types.VirtualMachineRelocateSpec{\n\t\tDatastore: &dsr,\n\t\tPool:      &rpr,\n\t\tDisk: []types.VirtualMachineRelocateSpecDiskLocator{\n\t\t\ttypes.VirtualMachineRelocateSpecDiskLocator{\n\t\t\t\tDatastore: dsr,\n\t\t\t\tDiskBackingInfo: &types.VirtualDiskFlatVer2BackingInfo{\n\t\t\t\t\tDiskMode:        \"persistent\",\n\t\t\t\t\tThinProvisioned: types.NewBool(false),\n\t\t\t\t\tEagerlyScrub:    types.NewBool(true),\n\t\t\t\t},\n\t\t\t\tDiskId: key,\n\t\t\t},\n\t\t},\n\t}, nil\n}\n\n\/\/ createCustomizationSpec creates the CustomizationSpec object.\nfunc createCustomizationSpec(name, domain, tz string, suffixes, servers []string, nics []types.CustomizationAdapterMapping) types.CustomizationSpec {\n\treturn types.CustomizationSpec{\n\t\tIdentity: &types.CustomizationLinuxPrep{\n\t\t\tHostName: &types.CustomizationFixedName{\n\t\t\t\tName: name,\n\t\t\t},\n\t\t\tDomain:     domain,\n\t\t\tTimeZone:   tz,\n\t\t\tHwClockUTC: types.NewBool(true),\n\t\t},\n\t\tGlobalIPSettings: types.CustomizationGlobalIPSettings{\n\t\t\tDnsSuffixList: suffixes,\n\t\t\tDnsServerList: servers,\n\t\t},\n\t\tNicSettingMap: nics,\n\t}\n}\n\nfunc addHardDisk(vm *object.VirtualMachine, size, iops int64) error {\n\tdevices, err := vm.Device(context.TODO())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcontroller, err := devices.FindDiskController(\"scsi\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdisk := devices.CreateDisk(controller, \"\")\n\texisting := devices.SelectByBackingInfo(disk.Backing)\n\n\tif len(existing) == 0 {\n\t\tdisk.CapacityInKB = int64(size * 1024 * 1024)\n\t\tif iops != 0 {\n\t\t\tdisk.StorageIOAllocation = &types.StorageIOAllocationInfo{\n\t\t\t\tLimit: iops,\n\t\t\t}\n\t\t}\n\t\tbacking := disk.Backing.(*types.VirtualDiskFlatVer2BackingInfo)\n\n\t\t\/\/ eager zeroed thick virtual disk\n\t\tbacking.ThinProvisioned = types.NewBool(false)\n\t\tbacking.EagerlyScrub = types.NewBool(true)\n\n\t\tlog.Printf(\"[DEBUG] addHardDisk: %#v\\n\", disk)\n\n\t\treturn vm.AddDevice(context.TODO(), disk)\n\t} else {\n\t\tlog.Printf(\"[DEBUG] addHardDisk: Disk already present.\\n\")\n\n\t\treturn nil\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n *   Copyright 2015 Benoit LETONDOR\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\/\n\npackage main\n\n\/\/ Rename this file conf.go and replace with actual values\n\n\/\/const USER_NAME = \"twitterName\"\n\/\/const ACTIONS_INTERVAL = \"@every 30m\"\n\/\/const WAKE_UP_HOUR int = 16\n\/\/const GO_TO_BED_HOUR int = 8\n\n\/\/const CONSUMER_KEY string = \"\"\n\/\/const CONSUMER_SECRET string = \"\"\n\/\/const TOKEN string = \"\"\n\/\/const TOKEN_SECRET string = \"\"\n\n\/\/const WIT_ACCESS_TOKEN string = \"\"\n\n\/\/const ACTION_FOLLOW_WEIGHT int = 1\n\/\/const ACTION_UNFOLLOW_WEIGHT int = 1\n\/\/const ACTION_FAVORITE_WEIGHT int = 1\n\/\/const ACTION_UNFAVORITE_WEIGHT int = 1\n\/\/const ACTION_TWEET_WEIGHT int = 1\n\/\/const ACTION_REPLY_WEIGHT int = 1\n\/\/const ACTION_NIGHTLY_FOLLOW_WEIGHT int = 1\n\/\/const ACTION_NIGHTLY_UNFOLLOW_WEIGHT int = 1\n\/\/const ACTION_NIGHTLY_FAVORITE_WEIGHT int = 1\n\/\/const ACTION_NIGHTLY_UNFAVORITE_WEIGHT int = 1\n\/\/const ACTION_NIGHTLY_TWEET_WEIGHT int = 1\n\/\/const ACTION_NIGHTLY_REPLY_WEIGHT int = 1\n\/\/const FAV_LIMIT_IN_A_ROW int = 5\n\/\/const UNFOLLOW_LIMIT_IN_A_ROW int = 5\n\/\/const UNFAVORITE_LIMIT_IN_A_ROW int = 1\n\/\/const MAX_TWEET_IN_A_DAY int = 5\n\n\/\/const T_CO_URL_LENGTH = 25\n\n\/\/const MYSQL_USER string = \"\"\n\/\/const MYSQL_PASSWORD string = \"\"\n\/\/const MYSQL_SCHEMA string = \"\"\n\n\/\/var KIMONO_DATA_SOURCES = []string{\"https:\/\/www.kimonolabs.com\/api\", \"https:\/\/www.kimonolabs.com\/api\"}\n\/\/var KEYWORDS = []string{\"key1\", \"key2}\n\/\/var HASHTAGS = []string{\"hash1\", \"hash2\"}\n\n\/\/const ACCEPTED_LANGUAGE string = \"en\"\n\n\/\/var BANNED_KEYWORDS = []string{\"porn\"}\n<commit_msg>Change conf example according to time.Duration format.<commit_after>\/*\n *   Copyright 2015 Benoit LETONDOR\n *\n *   Licensed under the Apache License, Version 2.0 (the \"License\");\n *   you may not use this file except in compliance with the License.\n *   You may obtain a copy of the License at\n *\n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *   Unless required by applicable law or agreed to in writing, software\n *   distributed under the License is distributed on an \"AS IS\" BASIS,\n *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *   See the License for the specific language governing permissions and\n *   limitations under the License.\n *\/\n\npackage main\n\n\/\/ Rename this file conf.go and replace with actual values\n\n\/\/const USER_NAME = \"twitterName\"\n\/\/const ACTIONS_INTERVAL = \"30m\"\n\/\/const WAKE_UP_HOUR int = 16\n\/\/const GO_TO_BED_HOUR int = 8\n\n\/\/const CONSUMER_KEY string = \"\"\n\/\/const CONSUMER_SECRET string = \"\"\n\/\/const TOKEN string = \"\"\n\/\/const TOKEN_SECRET string = \"\"\n\n\/\/const WIT_ACCESS_TOKEN string = \"\"\n\n\/\/const ACTION_FOLLOW_WEIGHT int = 1\n\/\/const ACTION_UNFOLLOW_WEIGHT int = 1\n\/\/const ACTION_FAVORITE_WEIGHT int = 1\n\/\/const ACTION_UNFAVORITE_WEIGHT int = 1\n\/\/const ACTION_TWEET_WEIGHT int = 1\n\/\/const ACTION_REPLY_WEIGHT int = 1\n\/\/const ACTION_NIGHTLY_FOLLOW_WEIGHT int = 1\n\/\/const ACTION_NIGHTLY_UNFOLLOW_WEIGHT int = 1\n\/\/const ACTION_NIGHTLY_FAVORITE_WEIGHT int = 1\n\/\/const ACTION_NIGHTLY_UNFAVORITE_WEIGHT int = 1\n\/\/const ACTION_NIGHTLY_TWEET_WEIGHT int = 1\n\/\/const ACTION_NIGHTLY_REPLY_WEIGHT int = 1\n\/\/const FAV_LIMIT_IN_A_ROW int = 5\n\/\/const UNFOLLOW_LIMIT_IN_A_ROW int = 5\n\/\/const UNFAVORITE_LIMIT_IN_A_ROW int = 1\n\/\/const MAX_TWEET_IN_A_DAY int = 5\n\n\/\/const T_CO_URL_LENGTH = 25\n\n\/\/const MYSQL_USER string = \"\"\n\/\/const MYSQL_PASSWORD string = \"\"\n\/\/const MYSQL_SCHEMA string = \"\"\n\n\/\/var KIMONO_DATA_SOURCES = []string{\"https:\/\/www.kimonolabs.com\/api\", \"https:\/\/www.kimonolabs.com\/api\"}\n\/\/var KEYWORDS = []string{\"key1\", \"key2}\n\/\/var HASHTAGS = []string{\"hash1\", \"hash2\"}\n\n\/\/const ACCEPTED_LANGUAGE string = \"en\"\n\n\/\/var BANNED_KEYWORDS = []string{\"porn\"}\n<|endoftext|>"}
{"text":"<commit_before>package credentials\n\nimport (\n\t\"bytes\"\n\t\"encoding\/binary\"\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"strings\"\n\t\"time\"\n\t\"unsafe\"\n\n\t\"github.com\/jcmturner\/gofork\/encoding\/asn1\"\n\t\"gopkg.in\/jcmturner\/gokrb5.v6\/types\"\n)\n\nconst (\n\theaderFieldTagKDCOffset = 1\n)\n\n\/\/ The first byte of the file always has the value 5.\n\/\/ The value of the second byte contains the version number (1 through 4)\n\/\/ Versions 1 and 2 of the file format use native byte order for integer representations.\n\/\/ Versions 3 and 4 always use big-endian byte order\n\/\/ After the two-byte version indicator, the file has three parts:\n\/\/   1) the header (in version 4 only)\n\/\/   2) the default principal name\n\/\/   3) a sequence of credentials\n\n\/\/ CCache is the file credentials cache as define here: https:\/\/web.mit.edu\/kerberos\/krb5-latest\/doc\/formats\/ccache_file_format.html\ntype CCache struct {\n\tVersion          uint8\n\tHeader           header\n\tDefaultPrincipal principal\n\tCredentials      []credential\n\tPath             string\n}\n\ntype header struct {\n\tlength uint16\n\tfields []headerField\n}\n\ntype headerField struct {\n\ttag    uint16\n\tlength uint16\n\tvalue  []byte\n}\n\n\/\/ Credential cache entry principal struct.\ntype principal struct {\n\tRealm         string\n\tPrincipalName types.PrincipalName\n}\n\ntype credential struct {\n\tClient       principal\n\tServer       principal\n\tKey          types.EncryptionKey\n\tAuthTime     time.Time\n\tStartTime    time.Time\n\tEndTime      time.Time\n\tRenewTill    time.Time\n\tIsSKey       bool\n\tTicketFlags  asn1.BitString\n\tAddresses    []types.HostAddress\n\tAuthData     []types.AuthorizationDataEntry\n\tTicket       []byte\n\tSecondTicket []byte\n}\n\n\/\/ LoadCCache loads a credential cache file into a CCache type.\nfunc LoadCCache(cpath string) (CCache, error) {\n\tk, err := ioutil.ReadFile(cpath)\n\tif err != nil {\n\t\treturn CCache{}, err\n\t}\n\tc, err := ParseCCache(k)\n\tc.Path = cpath\n\treturn c, err\n}\n\n\/\/ ParseCCache byte slice of credential cache data into CCache type.\nfunc ParseCCache(b []byte) (c CCache, err error) {\n\tp := 0\n\t\/\/The first byte of the file always has the value 5\n\tif int8(b[p]) != 5 {\n\t\terr = errors.New(\"Invalid credential cache data. First byte does not equal 5\")\n\t\treturn\n\t}\n\tp++\n\t\/\/Get credential cache version\n\t\/\/The second byte contains the version number (1 to 4)\n\tc.Version = uint8(b[p])\n\tif c.Version < 1 || c.Version > 4 {\n\t\terr = errors.New(\"Invalid credential cache data. Keytab version is not within 1 to 4\")\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tp++\n\t\/\/Version 1 or 2 of the file format uses native byte order for integer representations. Versions 3 & 4 always uses big-endian byte order\n\tvar endian binary.ByteOrder\n\tendian = binary.BigEndian\n\tif (c.Version == 1 || c.Version == 2) && isNativeEndianLittle() {\n\t\tendian = binary.LittleEndian\n\t}\n\tif c.Version == 4 {\n\t\terr = parseHeader(b, &p, &c, &endian)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tc.DefaultPrincipal = parsePrincipal(b, &p, &c, &endian)\n\tfor p < len(b) {\n\t\tcred, e := parseCredential(b, &p, &c, &endian)\n\t\tif e != nil {\n\t\t\terr = e\n\t\t\treturn\n\t\t}\n\t\tc.Credentials = append(c.Credentials, cred)\n\t}\n\treturn\n}\n\nfunc parseHeader(b []byte, p *int, c *CCache, e *binary.ByteOrder) error {\n\tif c.Version != 4 {\n\t\treturn errors.New(\"Credentials cache version is not 4 so there is no header to parse.\")\n\t}\n\th := header{}\n\th.length = uint16(readInt16(b, p, e))\n\tfor *p <= int(h.length) {\n\t\tf := headerField{}\n\t\tf.tag = uint16(readInt16(b, p, e))\n\t\tf.length = uint16(readInt16(b, p, e))\n\t\tf.value = b[*p : *p+int(f.length)]\n\t\t*p += int(f.length)\n\t\tif !f.valid() {\n\t\t\treturn errors.New(\"Invalid credential cache header found\")\n\t\t}\n\t\th.fields = append(h.fields, f)\n\t}\n\tc.Header = h\n\treturn nil\n}\n\n\/\/ Parse the Keytab bytes of a principal into a Keytab entry's principal.\nfunc parsePrincipal(b []byte, p *int, c *CCache, e *binary.ByteOrder) (princ principal) {\n\tif c.Version != 1 {\n\t\t\/\/Name Type is omitted in version 1\n\t\tprinc.PrincipalName.NameType = int32(readInt32(b, p, e))\n\t}\n\tnc := int(readInt32(b, p, e))\n\tif c.Version == 1 {\n\t\t\/\/In version 1 the number of components includes the realm. Minus 1 to make consistent with version 2\n\t\tnc--\n\t}\n\tlenRealm := readInt32(b, p, e)\n\tprinc.Realm = string(readBytes(b, p, int(lenRealm), e))\n\tfor i := 0; i < int(nc); i++ {\n\t\tl := readInt32(b, p, e)\n\t\tprinc.PrincipalName.NameString = append(princ.PrincipalName.NameString, string(readBytes(b, p, int(l), e)))\n\t}\n\treturn princ\n}\n\nfunc parseCredential(b []byte, p *int, c *CCache, e *binary.ByteOrder) (cred credential, err error) {\n\tcred.Client = parsePrincipal(b, p, c, e)\n\tcred.Server = parsePrincipal(b, p, c, e)\n\tkey := types.EncryptionKey{}\n\tkey.KeyType = int32(readInt16(b, p, e))\n\tif c.Version == 3 {\n\t\t\/\/repeated twice in version 3\n\t\tkey.KeyType = int32(readInt16(b, p, e))\n\t}\n\tkey.KeyValue = readData(b, p, e)\n\tcred.Key = key\n\tcred.AuthTime = readTimestamp(b, p, e)\n\tcred.StartTime = readTimestamp(b, p, e)\n\tcred.EndTime = readTimestamp(b, p, e)\n\tcred.RenewTill = readTimestamp(b, p, e)\n\tif ik := readInt8(b, p, e); ik == 0 {\n\t\tcred.IsSKey = false\n\t} else {\n\t\tcred.IsSKey = true\n\t}\n\tcred.TicketFlags = types.NewKrbFlags()\n\tcred.TicketFlags.Bytes = readBytes(b, p, 4, e)\n\tl := int(readInt32(b, p, e))\n\tcred.Addresses = make([]types.HostAddress, l, l)\n\tfor i := range cred.Addresses {\n\t\tcred.Addresses[i] = readAddress(b, p, e)\n\t}\n\tl = int(readInt32(b, p, e))\n\tcred.AuthData = make([]types.AuthorizationDataEntry, l, l)\n\tfor i := range cred.AuthData {\n\t\tcred.AuthData[i] = readAuthDataEntry(b, p, e)\n\t}\n\tcred.Ticket = readData(b, p, e)\n\tcred.SecondTicket = readData(b, p, e)\n\treturn\n}\n\n\/\/ GetClientPrincipalName returns a PrincipalName type for the client the credentials cache is for.\nfunc (c *CCache) GetClientPrincipalName() types.PrincipalName {\n\treturn c.DefaultPrincipal.PrincipalName\n}\n\n\/\/ GetClientRealm returns the reals of the client the credentials cache is for.\nfunc (c *CCache) GetClientRealm() string {\n\treturn c.DefaultPrincipal.Realm\n}\n\n\/\/ GetClientCredentials returns a Credentials object representing the client of the credentials cache.\nfunc (c *CCache) GetClientCredentials() *Credentials {\n\treturn &Credentials{\n\t\tUsername: c.DefaultPrincipal.PrincipalName.GetPrincipalNameString(),\n\t\tRealm:    c.GetClientRealm(),\n\t\tCName:    c.DefaultPrincipal.PrincipalName,\n\t}\n}\n\n\/\/ Contains tests if the cache contains a credential for the provided server PrincipalName\nfunc (c *CCache) Contains(p types.PrincipalName) bool {\n\tfor _, cred := range c.Credentials {\n\t\tif cred.Server.PrincipalName.Equal(p) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ GetEntry returns a specific credential for the PrincipalName provided.\nfunc (c *CCache) GetEntry(p types.PrincipalName) (credential, bool) {\n\tvar cred credential\n\tvar found bool\n\tfor i := range c.Credentials {\n\t\tif c.Credentials[i].Server.PrincipalName.Equal(p) {\n\t\t\tcred = c.Credentials[i]\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !found {\n\t\treturn cred, false\n\t}\n\treturn cred, true\n}\n\n\/\/ GetEntries filters out configuration entries an returns a slice of credentials.\nfunc (c *CCache) GetEntries() []credential {\n\tvar creds []credential\n\tfor _, cred := range c.Credentials {\n\t\t\/\/ Filter out configuration entries\n\t\tif strings.HasPrefix(cred.Server.Realm, \"X-CACHECONF\") {\n\t\t\tcontinue\n\t\t}\n\t\tcreds = append(creds, cred)\n\t}\n\treturn creds\n}\n\nfunc (h *headerField) valid() bool {\n\t\/\/ At this time there is only one defined header field.\n\t\/\/ Its tag value is 1, its length is always 8.\n\t\/\/ Its contents are two 32-bit integers giving the seconds and microseconds\n\t\/\/ of the time offset of the KDC relative to the client.\n\t\/\/ Adding this offset to the current time on the client should give the current time on the KDC, if that offset has not changed since the initial authentication.\n\n\t\/\/ Done as a switch in case other tag values are added in the future.\n\tswitch h.tag {\n\tcase headerFieldTagKDCOffset:\n\t\tif h.length != 8 || len(h.value) != 8 {\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc readData(b []byte, p *int, e *binary.ByteOrder) []byte {\n\tl := readInt32(b, p, e)\n\treturn readBytes(b, p, int(l), e)\n}\n\nfunc readAddress(b []byte, p *int, e *binary.ByteOrder) types.HostAddress {\n\ta := types.HostAddress{}\n\ta.AddrType = int32(readInt16(b, p, e))\n\ta.Address = readData(b, p, e)\n\treturn a\n}\n\nfunc readAuthDataEntry(b []byte, p *int, e *binary.ByteOrder) types.AuthorizationDataEntry {\n\ta := types.AuthorizationDataEntry{}\n\ta.ADType = int32(readInt16(b, p, e))\n\ta.ADData = readData(b, p, e)\n\treturn a\n}\n\n\/\/ Read bytes representing a timestamp.\nfunc readTimestamp(b []byte, p *int, e *binary.ByteOrder) time.Time {\n\treturn time.Unix(int64(readInt32(b, p, e)), 0)\n}\n\n\/\/ Read bytes representing an eight bit integer.\nfunc readInt8(b []byte, p *int, e *binary.ByteOrder) (i int8) {\n\tbuf := bytes.NewBuffer(b[*p : *p+1])\n\tbinary.Read(buf, *e, &i)\n\t*p++\n\treturn\n}\n\n\/\/ Read bytes representing a sixteen bit integer.\nfunc readInt16(b []byte, p *int, e *binary.ByteOrder) (i int16) {\n\tbuf := bytes.NewBuffer(b[*p : *p+2])\n\tbinary.Read(buf, *e, &i)\n\t*p += 2\n\treturn\n}\n\n\/\/ Read bytes representing a thirty two bit integer.\nfunc readInt32(b []byte, p *int, e *binary.ByteOrder) (i int32) {\n\tbuf := bytes.NewBuffer(b[*p : *p+4])\n\tbinary.Read(buf, *e, &i)\n\t*p += 4\n\treturn\n}\n\nfunc readBytes(b []byte, p *int, s int, e *binary.ByteOrder) []byte {\n\tbuf := bytes.NewBuffer(b[*p : *p+s])\n\tr := make([]byte, s)\n\tbinary.Read(buf, *e, &r)\n\t*p += s\n\treturn r\n}\n\nfunc isNativeEndianLittle() bool {\n\tvar x = 0x012345678\n\tvar p = unsafe.Pointer(&x)\n\tvar bp = (*[4]byte)(p)\n\n\tvar endian bool\n\tif 0x01 == bp[0] {\n\t\tendian = false\n\t} else if (0x78 & 0xff) == (bp[0] & 0xff) {\n\t\tendian = true\n\t} else {\n\t\t\/\/ Default to big endian\n\t\tendian = false\n\t}\n\treturn endian\n}\n<commit_msg>credentials\/ccache.go: Fix unconvert issues<commit_after>package credentials\n\nimport (\n\t\"bytes\"\n\t\"encoding\/binary\"\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"strings\"\n\t\"time\"\n\t\"unsafe\"\n\n\t\"github.com\/jcmturner\/gofork\/encoding\/asn1\"\n\t\"gopkg.in\/jcmturner\/gokrb5.v6\/types\"\n)\n\nconst (\n\theaderFieldTagKDCOffset = 1\n)\n\n\/\/ The first byte of the file always has the value 5.\n\/\/ The value of the second byte contains the version number (1 through 4)\n\/\/ Versions 1 and 2 of the file format use native byte order for integer representations.\n\/\/ Versions 3 and 4 always use big-endian byte order\n\/\/ After the two-byte version indicator, the file has three parts:\n\/\/   1) the header (in version 4 only)\n\/\/   2) the default principal name\n\/\/   3) a sequence of credentials\n\n\/\/ CCache is the file credentials cache as define here: https:\/\/web.mit.edu\/kerberos\/krb5-latest\/doc\/formats\/ccache_file_format.html\ntype CCache struct {\n\tVersion          uint8\n\tHeader           header\n\tDefaultPrincipal principal\n\tCredentials      []credential\n\tPath             string\n}\n\ntype header struct {\n\tlength uint16\n\tfields []headerField\n}\n\ntype headerField struct {\n\ttag    uint16\n\tlength uint16\n\tvalue  []byte\n}\n\n\/\/ Credential cache entry principal struct.\ntype principal struct {\n\tRealm         string\n\tPrincipalName types.PrincipalName\n}\n\ntype credential struct {\n\tClient       principal\n\tServer       principal\n\tKey          types.EncryptionKey\n\tAuthTime     time.Time\n\tStartTime    time.Time\n\tEndTime      time.Time\n\tRenewTill    time.Time\n\tIsSKey       bool\n\tTicketFlags  asn1.BitString\n\tAddresses    []types.HostAddress\n\tAuthData     []types.AuthorizationDataEntry\n\tTicket       []byte\n\tSecondTicket []byte\n}\n\n\/\/ LoadCCache loads a credential cache file into a CCache type.\nfunc LoadCCache(cpath string) (CCache, error) {\n\tk, err := ioutil.ReadFile(cpath)\n\tif err != nil {\n\t\treturn CCache{}, err\n\t}\n\tc, err := ParseCCache(k)\n\tc.Path = cpath\n\treturn c, err\n}\n\n\/\/ ParseCCache byte slice of credential cache data into CCache type.\nfunc ParseCCache(b []byte) (c CCache, err error) {\n\tp := 0\n\t\/\/The first byte of the file always has the value 5\n\tif int8(b[p]) != 5 {\n\t\terr = errors.New(\"Invalid credential cache data. First byte does not equal 5\")\n\t\treturn\n\t}\n\tp++\n\t\/\/Get credential cache version\n\t\/\/The second byte contains the version number (1 to 4)\n\tc.Version = b[p]\n\tif c.Version < 1 || c.Version > 4 {\n\t\terr = errors.New(\"Invalid credential cache data. Keytab version is not within 1 to 4\")\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tp++\n\t\/\/Version 1 or 2 of the file format uses native byte order for integer representations. Versions 3 & 4 always uses big-endian byte order\n\tvar endian binary.ByteOrder\n\tendian = binary.BigEndian\n\tif (c.Version == 1 || c.Version == 2) && isNativeEndianLittle() {\n\t\tendian = binary.LittleEndian\n\t}\n\tif c.Version == 4 {\n\t\terr = parseHeader(b, &p, &c, &endian)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\tc.DefaultPrincipal = parsePrincipal(b, &p, &c, &endian)\n\tfor p < len(b) {\n\t\tcred, e := parseCredential(b, &p, &c, &endian)\n\t\tif e != nil {\n\t\t\terr = e\n\t\t\treturn\n\t\t}\n\t\tc.Credentials = append(c.Credentials, cred)\n\t}\n\treturn\n}\n\nfunc parseHeader(b []byte, p *int, c *CCache, e *binary.ByteOrder) error {\n\tif c.Version != 4 {\n\t\treturn errors.New(\"Credentials cache version is not 4 so there is no header to parse.\")\n\t}\n\th := header{}\n\th.length = uint16(readInt16(b, p, e))\n\tfor *p <= int(h.length) {\n\t\tf := headerField{}\n\t\tf.tag = uint16(readInt16(b, p, e))\n\t\tf.length = uint16(readInt16(b, p, e))\n\t\tf.value = b[*p : *p+int(f.length)]\n\t\t*p += int(f.length)\n\t\tif !f.valid() {\n\t\t\treturn errors.New(\"Invalid credential cache header found\")\n\t\t}\n\t\th.fields = append(h.fields, f)\n\t}\n\tc.Header = h\n\treturn nil\n}\n\n\/\/ Parse the Keytab bytes of a principal into a Keytab entry's principal.\nfunc parsePrincipal(b []byte, p *int, c *CCache, e *binary.ByteOrder) (princ principal) {\n\tif c.Version != 1 {\n\t\t\/\/Name Type is omitted in version 1\n\t\tprinc.PrincipalName.NameType = readInt32(b, p, e)\n\t}\n\tnc := int(readInt32(b, p, e))\n\tif c.Version == 1 {\n\t\t\/\/In version 1 the number of components includes the realm. Minus 1 to make consistent with version 2\n\t\tnc--\n\t}\n\tlenRealm := readInt32(b, p, e)\n\tprinc.Realm = string(readBytes(b, p, int(lenRealm), e))\n\tfor i := 0; i < nc; i++ {\n\t\tl := readInt32(b, p, e)\n\t\tprinc.PrincipalName.NameString = append(princ.PrincipalName.NameString, string(readBytes(b, p, int(l), e)))\n\t}\n\treturn princ\n}\n\nfunc parseCredential(b []byte, p *int, c *CCache, e *binary.ByteOrder) (cred credential, err error) {\n\tcred.Client = parsePrincipal(b, p, c, e)\n\tcred.Server = parsePrincipal(b, p, c, e)\n\tkey := types.EncryptionKey{}\n\tkey.KeyType = int32(readInt16(b, p, e))\n\tif c.Version == 3 {\n\t\t\/\/repeated twice in version 3\n\t\tkey.KeyType = int32(readInt16(b, p, e))\n\t}\n\tkey.KeyValue = readData(b, p, e)\n\tcred.Key = key\n\tcred.AuthTime = readTimestamp(b, p, e)\n\tcred.StartTime = readTimestamp(b, p, e)\n\tcred.EndTime = readTimestamp(b, p, e)\n\tcred.RenewTill = readTimestamp(b, p, e)\n\tif ik := readInt8(b, p, e); ik == 0 {\n\t\tcred.IsSKey = false\n\t} else {\n\t\tcred.IsSKey = true\n\t}\n\tcred.TicketFlags = types.NewKrbFlags()\n\tcred.TicketFlags.Bytes = readBytes(b, p, 4, e)\n\tl := int(readInt32(b, p, e))\n\tcred.Addresses = make([]types.HostAddress, l, l)\n\tfor i := range cred.Addresses {\n\t\tcred.Addresses[i] = readAddress(b, p, e)\n\t}\n\tl = int(readInt32(b, p, e))\n\tcred.AuthData = make([]types.AuthorizationDataEntry, l, l)\n\tfor i := range cred.AuthData {\n\t\tcred.AuthData[i] = readAuthDataEntry(b, p, e)\n\t}\n\tcred.Ticket = readData(b, p, e)\n\tcred.SecondTicket = readData(b, p, e)\n\treturn\n}\n\n\/\/ GetClientPrincipalName returns a PrincipalName type for the client the credentials cache is for.\nfunc (c *CCache) GetClientPrincipalName() types.PrincipalName {\n\treturn c.DefaultPrincipal.PrincipalName\n}\n\n\/\/ GetClientRealm returns the reals of the client the credentials cache is for.\nfunc (c *CCache) GetClientRealm() string {\n\treturn c.DefaultPrincipal.Realm\n}\n\n\/\/ GetClientCredentials returns a Credentials object representing the client of the credentials cache.\nfunc (c *CCache) GetClientCredentials() *Credentials {\n\treturn &Credentials{\n\t\tUsername: c.DefaultPrincipal.PrincipalName.GetPrincipalNameString(),\n\t\tRealm:    c.GetClientRealm(),\n\t\tCName:    c.DefaultPrincipal.PrincipalName,\n\t}\n}\n\n\/\/ Contains tests if the cache contains a credential for the provided server PrincipalName\nfunc (c *CCache) Contains(p types.PrincipalName) bool {\n\tfor _, cred := range c.Credentials {\n\t\tif cred.Server.PrincipalName.Equal(p) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n\/\/ GetEntry returns a specific credential for the PrincipalName provided.\nfunc (c *CCache) GetEntry(p types.PrincipalName) (credential, bool) {\n\tvar cred credential\n\tvar found bool\n\tfor i := range c.Credentials {\n\t\tif c.Credentials[i].Server.PrincipalName.Equal(p) {\n\t\t\tcred = c.Credentials[i]\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !found {\n\t\treturn cred, false\n\t}\n\treturn cred, true\n}\n\n\/\/ GetEntries filters out configuration entries an returns a slice of credentials.\nfunc (c *CCache) GetEntries() []credential {\n\tvar creds []credential\n\tfor _, cred := range c.Credentials {\n\t\t\/\/ Filter out configuration entries\n\t\tif strings.HasPrefix(cred.Server.Realm, \"X-CACHECONF\") {\n\t\t\tcontinue\n\t\t}\n\t\tcreds = append(creds, cred)\n\t}\n\treturn creds\n}\n\nfunc (h *headerField) valid() bool {\n\t\/\/ At this time there is only one defined header field.\n\t\/\/ Its tag value is 1, its length is always 8.\n\t\/\/ Its contents are two 32-bit integers giving the seconds and microseconds\n\t\/\/ of the time offset of the KDC relative to the client.\n\t\/\/ Adding this offset to the current time on the client should give the current time on the KDC, if that offset has not changed since the initial authentication.\n\n\t\/\/ Done as a switch in case other tag values are added in the future.\n\tswitch h.tag {\n\tcase headerFieldTagKDCOffset:\n\t\tif h.length != 8 || len(h.value) != 8 {\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc readData(b []byte, p *int, e *binary.ByteOrder) []byte {\n\tl := readInt32(b, p, e)\n\treturn readBytes(b, p, int(l), e)\n}\n\nfunc readAddress(b []byte, p *int, e *binary.ByteOrder) types.HostAddress {\n\ta := types.HostAddress{}\n\ta.AddrType = int32(readInt16(b, p, e))\n\ta.Address = readData(b, p, e)\n\treturn a\n}\n\nfunc readAuthDataEntry(b []byte, p *int, e *binary.ByteOrder) types.AuthorizationDataEntry {\n\ta := types.AuthorizationDataEntry{}\n\ta.ADType = int32(readInt16(b, p, e))\n\ta.ADData = readData(b, p, e)\n\treturn a\n}\n\n\/\/ Read bytes representing a timestamp.\nfunc readTimestamp(b []byte, p *int, e *binary.ByteOrder) time.Time {\n\treturn time.Unix(int64(readInt32(b, p, e)), 0)\n}\n\n\/\/ Read bytes representing an eight bit integer.\nfunc readInt8(b []byte, p *int, e *binary.ByteOrder) (i int8) {\n\tbuf := bytes.NewBuffer(b[*p : *p+1])\n\tbinary.Read(buf, *e, &i)\n\t*p++\n\treturn\n}\n\n\/\/ Read bytes representing a sixteen bit integer.\nfunc readInt16(b []byte, p *int, e *binary.ByteOrder) (i int16) {\n\tbuf := bytes.NewBuffer(b[*p : *p+2])\n\tbinary.Read(buf, *e, &i)\n\t*p += 2\n\treturn\n}\n\n\/\/ Read bytes representing a thirty two bit integer.\nfunc readInt32(b []byte, p *int, e *binary.ByteOrder) (i int32) {\n\tbuf := bytes.NewBuffer(b[*p : *p+4])\n\tbinary.Read(buf, *e, &i)\n\t*p += 4\n\treturn\n}\n\nfunc readBytes(b []byte, p *int, s int, e *binary.ByteOrder) []byte {\n\tbuf := bytes.NewBuffer(b[*p : *p+s])\n\tr := make([]byte, s)\n\tbinary.Read(buf, *e, &r)\n\t*p += s\n\treturn r\n}\n\nfunc isNativeEndianLittle() bool {\n\tvar x = 0x012345678\n\tvar p = unsafe.Pointer(&x)\n\tvar bp = (*[4]byte)(p)\n\n\tvar endian bool\n\tif 0x01 == bp[0] {\n\t\tendian = false\n\t} else if (0x78 & 0xff) == (bp[0] & 0xff) {\n\t\tendian = true\n\t} else {\n\t\t\/\/ Default to big endian\n\t\tendian = false\n\t}\n\treturn endian\n}\n<|endoftext|>"}
{"text":"<commit_before>package aws\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com\/hashicorp\/terraform\/helper\/resource\"\n\t\"github.com\/hashicorp\/terraform\/terraform\"\n\t\"github.com\/mitchellh\/goamz\/route53\"\n)\n\nfunc TestAccRoute53Record(t *testing.T) {\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckRoute53RecordDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccRoute53RecordConfig,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckRoute53RecordExists(\"aws_route53_record.default\"),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc testAccCheckRoute53RecordDestroy(s *terraform.State) error {\n\tconn := testAccProvider.route53\n\tfor _, rs := range s.Resources {\n\t\tif rs.Type != \"aws_route53_record\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tparts := strings.Split(rs.ID, \"_\")\n\t\tzone := parts[0]\n\t\tname := parts[1]\n\t\trType := parts[2]\n\n\t\tlopts := &route53.ListOpts{Name: name, Type: rType}\n\t\tresp, err := conn.ListResourceRecordSets(zone, lopts)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(resp.Records) == 0 {\n\t\t\treturn nil\n\t\t}\n\t\trec := resp.Records[0]\n\t\tif route53.FQDN(rec.Name) == route53.FQDN(name) && rec.Type == rType {\n\t\t\treturn fmt.Errorf(\"Record still exists: %#v\", rec)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc testAccCheckRoute53RecordExists(n string) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\tconn := testAccProvider.route53\n\t\trs, ok := s.Resources[n]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Not found: %s\", n)\n\t\t}\n\n\t\tif rs.ID == \"\" {\n\t\t\treturn fmt.Errorf(\"No hosted zone ID is set\")\n\t\t}\n\n\t\tparts := strings.Split(rs.ID, \"_\")\n\t\tzone := parts[0]\n\t\tname := parts[1]\n\t\trType := parts[2]\n\n\t\tlopts := &route53.ListOpts{Name: name, Type: rType}\n\t\tresp, err := conn.ListResourceRecordSets(zone, lopts)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(resp.Records) == 0 {\n\t\t\treturn fmt.Errorf(\"Record does not exist\")\n\t\t}\n\t\trec := resp.Records[0]\n\t\tif route53.FQDN(rec.Name) == route53.FQDN(name) && rec.Type == rType {\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"Record does not exist: %#v\", rec)\n\t}\n}\n\nconst testAccRoute53RecordConfig = `\nresource \"aws_route53_zone\" \"main\" {\n\tname = \"example.com\"\n}\n\nresource \"aws_route53_record\" \"default\" {\n\tzone_id = \"${aws_route53_zone.main.zone_id}\"\n\tname = \"www.example.com\"\n\ttype = \"A\"\n\tttl = \"30\"\n\trecords = [\"127.0.0.1\"]\n}\n`\n<commit_msg>providers\/aws: can create records with multiple values [GH-221]<commit_after>package aws\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com\/hashicorp\/terraform\/helper\/resource\"\n\t\"github.com\/hashicorp\/terraform\/terraform\"\n\t\"github.com\/mitchellh\/goamz\/route53\"\n)\n\nfunc TestAccRoute53Record(t *testing.T) {\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck:     func() { testAccPreCheck(t) },\n\t\tProviders:    testAccProviders,\n\t\tCheckDestroy: testAccCheckRoute53RecordDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccRoute53RecordConfig,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\ttestAccCheckRoute53RecordExists(\"aws_route53_record.default\"),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc testAccCheckRoute53RecordDestroy(s *terraform.State) error {\n\tconn := testAccProvider.route53\n\tfor _, rs := range s.Resources {\n\t\tif rs.Type != \"aws_route53_record\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tparts := strings.Split(rs.ID, \"_\")\n\t\tzone := parts[0]\n\t\tname := parts[1]\n\t\trType := parts[2]\n\n\t\tlopts := &route53.ListOpts{Name: name, Type: rType}\n\t\tresp, err := conn.ListResourceRecordSets(zone, lopts)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(resp.Records) == 0 {\n\t\t\treturn nil\n\t\t}\n\t\trec := resp.Records[0]\n\t\tif route53.FQDN(rec.Name) == route53.FQDN(name) && rec.Type == rType {\n\t\t\treturn fmt.Errorf(\"Record still exists: %#v\", rec)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc testAccCheckRoute53RecordExists(n string) resource.TestCheckFunc {\n\treturn func(s *terraform.State) error {\n\t\tconn := testAccProvider.route53\n\t\trs, ok := s.Resources[n]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Not found: %s\", n)\n\t\t}\n\n\t\tif rs.ID == \"\" {\n\t\t\treturn fmt.Errorf(\"No hosted zone ID is set\")\n\t\t}\n\n\t\tparts := strings.Split(rs.ID, \"_\")\n\t\tzone := parts[0]\n\t\tname := parts[1]\n\t\trType := parts[2]\n\n\t\tlopts := &route53.ListOpts{Name: name, Type: rType}\n\t\tresp, err := conn.ListResourceRecordSets(zone, lopts)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(resp.Records) == 0 {\n\t\t\treturn fmt.Errorf(\"Record does not exist\")\n\t\t}\n\t\trec := resp.Records[0]\n\t\tif route53.FQDN(rec.Name) == route53.FQDN(name) && rec.Type == rType {\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"Record does not exist: %#v\", rec)\n\t}\n}\n\nconst testAccRoute53RecordConfig = `\nresource \"aws_route53_zone\" \"main\" {\n\tname = \"notexample.com\"\n}\n\nresource \"aws_route53_record\" \"default\" {\n\tzone_id = \"${aws_route53_zone.main.zone_id}\"\n\tname = \"www.notexample.com\"\n\ttype = \"A\"\n\tttl = \"30\"\n\trecords = [\"127.0.0.1\", \"127.0.0.27\"]\n}\n`\n<|endoftext|>"}
{"text":"<commit_before>package cmder\n\nvar cmders = map[string]Cmder{}\n\nfunc Register(name string, cmder Cmder) {\n\tcmders[name] = cmder\n}\n\nfunc Get(name string) Cmder {\n\tcmder, _ := cmders[name]\n\treturn cmder\n}\n\nfunc Unregister(name string) {\n\tif _, ok := cmders[name]; ok {\n\t\tdelete(cmders, name)\n\t}\n}\n<commit_msg>update<commit_after>package cmder\n\nvar cmders = map[string]Cmder{}\n\nfunc Register(name string, cmder Cmder) {\n\tcmders[name] = cmder\n}\n\nfunc Get(name string) Cmder {\n\tcmder := cmders[name]\n\treturn cmder\n}\n\nfunc Has(name string) bool {\n\t_, ok := cmders[name]\n\treturn ok\n}\n\nfunc Unregister(name string) {\n\tdelete(cmders, name)\n}\n<|endoftext|>"}
{"text":"<commit_before>package middleware\n\nimport (\n\tcheck \"gopkg.in\/check.v1\"\n\t\"testing\"\n)\n\nfunc Test(t *testing.T) { check.TestingT(t) }\n\ntype MiddlewareSuite struct{}\n\nvar _ = check.Suite(&MiddlewareSuite{})\n\nfunc (s *MiddlewareSuite) TestNoConfig(c *check.C) {\n\toptions := make(map[string]interface{})\n\t_, err := newRedirectStorageMiddleware(nil, options)\n\tc.Assert(err, check.ErrorMatches, \"no baseurl provided\")\n}\n\nfunc (s *MiddlewareSuite) TestMissingScheme(c *check.C) {\n\toptions := make(map[string]interface{})\n\toptions[\"baseurl\"] = \"example.com\"\n\t_, err := newRedirectStorageMiddleware(nil, options)\n\tc.Assert(err, check.ErrorMatches, \"no scheme specified for redirect baseurl\")\n}\n\nfunc (s *MiddlewareSuite) TestHTTPS(c *check.C) {\n\toptions := make(map[string]interface{})\n\toptions[\"baseurl\"] = \"https:\/\/example.com\"\n\tmiddleware, err := newRedirectStorageMiddleware(nil, options)\n\tc.Assert(err, check.Equals, nil)\n\n\tm, ok := middleware.(*redirectStorageMiddleware)\n\tc.Assert(ok, check.Equals, true)\n\tc.Assert(m.scheme, check.Equals, \"https\")\n\tc.Assert(m.host, check.Equals, \"example.com\")\n\n\turl, err := middleware.URLFor(nil, \"\/rick\/data\", nil)\n\tc.Assert(err, check.Equals, nil)\n\tc.Assert(url, check.Equals, \"https:\/\/example.com\/rick\/data\")\n}\n\nfunc (s *MiddlewareSuite) TestHTTP(c *check.C) {\n\toptions := make(map[string]interface{})\n\toptions[\"baseurl\"] = \"http:\/\/example.com\"\n\tmiddleware, err := newRedirectStorageMiddleware(nil, options)\n\tc.Assert(err, check.Equals, nil)\n\n\tm, ok := middleware.(*redirectStorageMiddleware)\n\tc.Assert(ok, check.Equals, true)\n\tc.Assert(m.scheme, check.Equals, \"http\")\n\tc.Assert(m.host, check.Equals, \"example.com\")\n\n\turl, err := middleware.URLFor(nil, \"morty\/data\", nil)\n\tc.Assert(err, check.Equals, nil)\n\tc.Assert(url, check.Equals, \"http:\/\/example.com\/morty\/data\")\n}\n<commit_msg>modify redirect test to include port<commit_after>package middleware\n\nimport (\n\tcheck \"gopkg.in\/check.v1\"\n\t\"testing\"\n)\n\nfunc Test(t *testing.T) { check.TestingT(t) }\n\ntype MiddlewareSuite struct{}\n\nvar _ = check.Suite(&MiddlewareSuite{})\n\nfunc (s *MiddlewareSuite) TestNoConfig(c *check.C) {\n\toptions := make(map[string]interface{})\n\t_, err := newRedirectStorageMiddleware(nil, options)\n\tc.Assert(err, check.ErrorMatches, \"no baseurl provided\")\n}\n\nfunc (s *MiddlewareSuite) TestMissingScheme(c *check.C) {\n\toptions := make(map[string]interface{})\n\toptions[\"baseurl\"] = \"example.com\"\n\t_, err := newRedirectStorageMiddleware(nil, options)\n\tc.Assert(err, check.ErrorMatches, \"no scheme specified for redirect baseurl\")\n}\n\nfunc (s *MiddlewareSuite) TestHttpsPort(c *check.C) {\n\toptions := make(map[string]interface{})\n\toptions[\"baseurl\"] = \"https:\/\/example.com:5443\"\n\tmiddleware, err := newRedirectStorageMiddleware(nil, options)\n\tc.Assert(err, check.Equals, nil)\n\n\tm, ok := middleware.(*redirectStorageMiddleware)\n\tc.Assert(ok, check.Equals, true)\n\tc.Assert(m.scheme, check.Equals, \"https\")\n\tc.Assert(m.host, check.Equals, \"example.com:5443\")\n\n\turl, err := middleware.URLFor(nil, \"\/rick\/data\", nil)\n\tc.Assert(err, check.Equals, nil)\n\tc.Assert(url, check.Equals, \"https:\/\/example.com:5443\/rick\/data\")\n}\n\nfunc (s *MiddlewareSuite) TestHTTP(c *check.C) {\n\toptions := make(map[string]interface{})\n\toptions[\"baseurl\"] = \"http:\/\/example.com\"\n\tmiddleware, err := newRedirectStorageMiddleware(nil, options)\n\tc.Assert(err, check.Equals, nil)\n\n\tm, ok := middleware.(*redirectStorageMiddleware)\n\tc.Assert(ok, check.Equals, true)\n\tc.Assert(m.scheme, check.Equals, \"http\")\n\tc.Assert(m.host, check.Equals, \"example.com\")\n\n\turl, err := middleware.URLFor(nil, \"morty\/data\", nil)\n\tc.Assert(err, check.Equals, nil)\n\tc.Assert(url, check.Equals, \"http:\/\/example.com\/morty\/data\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package registry\n\nimport (\n\t\"github.com\/dotcloud\/docker\/engine\"\n)\n\n\/\/ Service exposes registry capabilities in the standard Engine\n\/\/ interface. Once installed, it extends the engine with the\n\/\/ following calls:\n\/\/\n\/\/  'auth': Authenticate against the public registry\n\/\/  'search': Search for images on the public registry (TODO)\n\/\/  'pull': Download images from any registry (TODO)\n\/\/  'push': Upload images to any registry (TODO)\ntype Service struct {\n}\n\n\/\/ NewService returns a new instance of Service ready to be\n\/\/ installed no an engine.\nfunc NewService() *Service {\n\treturn &Service{}\n}\n\n\/\/ Install installs registry capabilities to eng.\nfunc (s *Service) Install(eng *engine.Engine) error {\n\teng.Register(\"auth\", s.Auth)\n\treturn nil\n}\n\n\/\/ Auth contacts the public registry with the provided credentials,\n\/\/ and returns OK if authentication was sucessful.\n\/\/ It can be used to verify the validity of a client's credentials.\nfunc (s *Service) Auth(job *engine.Job) engine.Status {\n\tvar (\n\t\terr        error\n\t\tauthConfig = &AuthConfig{}\n\t)\n\n\tjob.GetenvJson(\"authConfig\", authConfig)\n\t\/\/ TODO: this is only done here because auth and registry need to be merged into one pkg\n\tif addr := authConfig.ServerAddress; addr != \"\" && addr != IndexServerAddress() {\n\t\taddr, err = ExpandAndVerifyRegistryUrl(addr)\n\t\tif err != nil {\n\t\t\treturn job.Error(err)\n\t\t}\n\t\tauthConfig.ServerAddress = addr\n\t}\n\tstatus, err := Login(authConfig, HTTPRequestFactory(nil))\n\tif err != nil {\n\t\treturn job.Error(err)\n\t}\n\tjob.Printf(\"%s\\n\", status)\n\treturn engine.StatusOK\n}\n<commit_msg>Move 'search' to the registry subsystem<commit_after>package registry\n\nimport (\n\t\"github.com\/dotcloud\/docker\/engine\"\n)\n\n\/\/ Service exposes registry capabilities in the standard Engine\n\/\/ interface. Once installed, it extends the engine with the\n\/\/ following calls:\n\/\/\n\/\/  'auth': Authenticate against the public registry\n\/\/  'search': Search for images on the public registry\n\/\/  'pull': Download images from any registry (TODO)\n\/\/  'push': Upload images to any registry (TODO)\ntype Service struct {\n}\n\n\/\/ NewService returns a new instance of Service ready to be\n\/\/ installed no an engine.\nfunc NewService() *Service {\n\treturn &Service{}\n}\n\n\/\/ Install installs registry capabilities to eng.\nfunc (s *Service) Install(eng *engine.Engine) error {\n\teng.Register(\"auth\", s.Auth)\n\teng.Register(\"search\", s.Search)\n\treturn nil\n}\n\n\/\/ Auth contacts the public registry with the provided credentials,\n\/\/ and returns OK if authentication was sucessful.\n\/\/ It can be used to verify the validity of a client's credentials.\nfunc (s *Service) Auth(job *engine.Job) engine.Status {\n\tvar (\n\t\terr        error\n\t\tauthConfig = &AuthConfig{}\n\t)\n\n\tjob.GetenvJson(\"authConfig\", authConfig)\n\t\/\/ TODO: this is only done here because auth and registry need to be merged into one pkg\n\tif addr := authConfig.ServerAddress; addr != \"\" && addr != IndexServerAddress() {\n\t\taddr, err = ExpandAndVerifyRegistryUrl(addr)\n\t\tif err != nil {\n\t\t\treturn job.Error(err)\n\t\t}\n\t\tauthConfig.ServerAddress = addr\n\t}\n\tstatus, err := Login(authConfig, HTTPRequestFactory(nil))\n\tif err != nil {\n\t\treturn job.Error(err)\n\t}\n\tjob.Printf(\"%s\\n\", status)\n\treturn engine.StatusOK\n}\n\n\/\/ Search queries the public registry for images matching the specified\n\/\/ search terms, and returns the results.\n\/\/\n\/\/ Argument syntax: search TERM\n\/\/\n\/\/ Option environment:\n\/\/\t'authConfig': json-encoded credentials to authenticate against the registry.\n\/\/\t\tThe search extends to images only accessible via the credentials.\n\/\/\n\/\/\t'metaHeaders': extra HTTP headers to include in the request to the registry.\n\/\/\t\tThe headers should be passed as a json-encoded dictionary.\n\/\/\n\/\/ Output:\n\/\/\tResults are sent as a collection of structured messages (using engine.Table).\n\/\/\tEach result is sent as a separate message.\n\/\/\tResults are ordered by number of stars on the public registry.\nfunc (s *Service) Search(job *engine.Job) engine.Status {\n\tif n := len(job.Args); n != 1 {\n\t\treturn job.Errorf(\"Usage: %s TERM\", job.Name)\n\t}\n\tvar (\n\t\tterm        = job.Args[0]\n\t\tmetaHeaders = map[string][]string{}\n\t\tauthConfig  = &AuthConfig{}\n\t)\n\tjob.GetenvJson(\"authConfig\", authConfig)\n\tjob.GetenvJson(\"metaHeaders\", metaHeaders)\n\n\tr, err := NewRegistry(authConfig, HTTPRequestFactory(metaHeaders), IndexServerAddress())\n\tif err != nil {\n\t\treturn job.Error(err)\n\t}\n\tresults, err := r.SearchRepositories(term)\n\tif err != nil {\n\t\treturn job.Error(err)\n\t}\n\touts := engine.NewTable(\"star_count\", 0)\n\tfor _, result := range results.Results {\n\t\tout := &engine.Env{}\n\t\tout.Import(result)\n\t\touts.Add(out)\n\t}\n\touts.ReverseSort()\n\tif _, err := outs.WriteListTo(job.Stdout); err != nil {\n\t\treturn job.Error(err)\n\t}\n\treturn engine.StatusOK\n}\n<|endoftext|>"}
{"text":"<commit_before>package sqldb_test\n\nimport (\n\t\"encoding\/json\"\n\n\t\"github.com\/cloudfoundry-incubator\/bbs\/db\/sqldb\"\n\t\"github.com\/cloudfoundry-incubator\/bbs\/models\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\nvar _ = Describe(\"Version\", func() {\n\tDescribe(\"SetVersion\", func() {\n\t\tContext(\"when the version is not set\", func() {\n\t\t\tIt(\"sets the version into the database\", func() {\n\t\t\t\texpectedVersion := &models.Version{CurrentVersion: 99, TargetVersion: 100}\n\t\t\t\terr := sqlDB.SetVersion(logger, expectedVersion)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\trows, err := db.Query(\"SELECT value FROM configurations WHERE id = ?\", sqldb.VersionID)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tExpect(rows.Next()).To(BeTrue())\n\n\t\t\t\tvar versionData string\n\t\t\t\terr = rows.Scan(&versionData)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tvar actualVersion models.Version\n\t\t\t\terr = json.Unmarshal([]byte(versionData), &actualVersion)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tExpect(actualVersion).To(Equal(*expectedVersion))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when a version is already set\", func() {\n\t\t\tvar existingVersion *models.Version\n\t\t\tBeforeEach(func() {\n\t\t\t\texistingVersion = &models.Version{CurrentVersion: 99, TargetVersion: 100}\n\t\t\t\tversionJSON, err := json.Marshal(existingVersion)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tresult, err := db.Exec(\"INSERT INTO configurations (id, value) VALUES (?, ?)\", sqldb.VersionID, versionJSON)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\t\tExpect(result.RowsAffected()).To(BeEquivalentTo(1))\n\t\t\t})\n\n\t\t\tIt(\"updates the version in the db\", func() {\n\t\t\t\tversion := &models.Version{CurrentVersion: 20, TargetVersion: 1001}\n\n\t\t\t\terr := sqlDB.SetVersion(logger, version)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\trows, err := db.Query(\"SELECT value FROM configurations WHERE id = ?\", sqldb.VersionID)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tExpect(rows.Next()).To(BeTrue())\n\n\t\t\t\tvar versionData string\n\t\t\t\terr = rows.Scan(&versionData)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tvar actualVersion models.Version\n\t\t\t\terr = json.Unmarshal([]byte(versionData), &actualVersion)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tExpect(actualVersion).To(Equal(*version))\n\t\t\t})\n\t\t})\n\t})\n\n\tDescribe(\"Version\", func() {\n\t\tContext(\"when the version exists\", func() {\n\t\t\tIt(\"retrieves the version from the database\", func() {\n\t\t\t\texpectedVersion := &models.Version{CurrentVersion: 199, TargetVersion: 200}\n\t\t\t\tvalue, err := json.Marshal(expectedVersion)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\t_, err = db.Exec(\"INSERT INTO configurations (id, value) VALUES (?, ?)\", sqldb.VersionID, value)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tversion, err := sqlDB.Version(logger)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tExpect(*version).To(Equal(*expectedVersion))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when the version key does not exist\", func() {\n\t\t\tIt(\"returns a ErrResourceNotFound\", func() {\n\t\t\t\tversion, err := sqlDB.Version(logger)\n\t\t\t\tExpect(err).To(MatchError(models.ErrResourceNotFound))\n\t\t\t\tExpect(version).To(BeNil())\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when the version key is not valid json\", func() {\n\t\t\tIt(\"returns a ErrDeserialize\", func() {\n\t\t\t\t_, err := db.Exec(\"INSERT INTO configurations (id, value) VALUES (?, ?)\", sqldb.VersionID, \"{{\")\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\t_, err = sqlDB.Version(logger)\n\t\t\t\tExpect(err).To(MatchError(models.ErrDeserializenk))\n\t\t\t})\n\t\t})\n\t})\n})\n<commit_msg>Fix typo in sql tests<commit_after>package sqldb_test\n\nimport (\n\t\"encoding\/json\"\n\n\t\"github.com\/cloudfoundry-incubator\/bbs\/db\/sqldb\"\n\t\"github.com\/cloudfoundry-incubator\/bbs\/models\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\nvar _ = Describe(\"Version\", func() {\n\tDescribe(\"SetVersion\", func() {\n\t\tContext(\"when the version is not set\", func() {\n\t\t\tIt(\"sets the version into the database\", func() {\n\t\t\t\texpectedVersion := &models.Version{CurrentVersion: 99, TargetVersion: 100}\n\t\t\t\terr := sqlDB.SetVersion(logger, expectedVersion)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\trows, err := db.Query(\"SELECT value FROM configurations WHERE id = ?\", sqldb.VersionID)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tExpect(rows.Next()).To(BeTrue())\n\n\t\t\t\tvar versionData string\n\t\t\t\terr = rows.Scan(&versionData)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tvar actualVersion models.Version\n\t\t\t\terr = json.Unmarshal([]byte(versionData), &actualVersion)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tExpect(actualVersion).To(Equal(*expectedVersion))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when a version is already set\", func() {\n\t\t\tvar existingVersion *models.Version\n\t\t\tBeforeEach(func() {\n\t\t\t\texistingVersion = &models.Version{CurrentVersion: 99, TargetVersion: 100}\n\t\t\t\tversionJSON, err := json.Marshal(existingVersion)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tresult, err := db.Exec(\"INSERT INTO configurations (id, value) VALUES (?, ?)\", sqldb.VersionID, versionJSON)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\t\tExpect(result.RowsAffected()).To(BeEquivalentTo(1))\n\t\t\t})\n\n\t\t\tIt(\"updates the version in the db\", func() {\n\t\t\t\tversion := &models.Version{CurrentVersion: 20, TargetVersion: 1001}\n\n\t\t\t\terr := sqlDB.SetVersion(logger, version)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\trows, err := db.Query(\"SELECT value FROM configurations WHERE id = ?\", sqldb.VersionID)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tExpect(rows.Next()).To(BeTrue())\n\n\t\t\t\tvar versionData string\n\t\t\t\terr = rows.Scan(&versionData)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tvar actualVersion models.Version\n\t\t\t\terr = json.Unmarshal([]byte(versionData), &actualVersion)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tExpect(actualVersion).To(Equal(*version))\n\t\t\t})\n\t\t})\n\t})\n\n\tDescribe(\"Version\", func() {\n\t\tContext(\"when the version exists\", func() {\n\t\t\tIt(\"retrieves the version from the database\", func() {\n\t\t\t\texpectedVersion := &models.Version{CurrentVersion: 199, TargetVersion: 200}\n\t\t\t\tvalue, err := json.Marshal(expectedVersion)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\t_, err = db.Exec(\"INSERT INTO configurations (id, value) VALUES (?, ?)\", sqldb.VersionID, value)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tversion, err := sqlDB.Version(logger)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tExpect(*version).To(Equal(*expectedVersion))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when the version key does not exist\", func() {\n\t\t\tIt(\"returns a ErrResourceNotFound\", func() {\n\t\t\t\tversion, err := sqlDB.Version(logger)\n\t\t\t\tExpect(err).To(MatchError(models.ErrResourceNotFound))\n\t\t\t\tExpect(version).To(BeNil())\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when the version key is not valid json\", func() {\n\t\t\tIt(\"returns a ErrDeserialize\", func() {\n\t\t\t\t_, err := db.Exec(\"INSERT INTO configurations (id, value) VALUES (?, ?)\", sqldb.VersionID, \"{{\")\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\t_, err = sqlDB.Version(logger)\n\t\t\t\tExpect(err).To(MatchError(models.ErrDeserialize))\n\t\t\t})\n\t\t})\n\t})\n})\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 The Serviced Authors.\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage rpcutils\n\nimport (\n\t\"bytes\"\n\t\"encoding\/binary\"\n\t\"errors\"\n\t\"io\"\n\t\"net\/rpc\"\n\t\"net\/rpc\/jsonrpc\"\n\t\"sync\"\n\n\t\"github.com\/control-center\/serviced\/auth\"\n\t\"github.com\/control-center\/serviced\/logging\"\n)\n\nvar (\n\t\/\/ RPC Calls that do not require authentication or who handle authentication separately:\n\tNonAuthenticatingCalls = []string{\"Master.AuthenticateHost\", \"Agent.BuildHost\"}\n\t\/\/ RPC calls that do not require admin access:\n\tNonAdminRequiredCalls = map[string]struct{}{\n\t\t\"Master.GetHost\":                         struct{}{},\n\t\t\"Master.GetHosts\":                        struct{}{},\n\t\t\"Master.GetEvaluatedService\":             struct{}{},\n\t\t\"Master.GetSystemUser\":                   struct{}{},\n\t\t\"Master.ReportHealthStatus\":              struct{}{},\n\t\t\"Master.ReportInstanceDead\":              struct{}{},\n\t\t\"ControlCenter.GetServices\":              struct{}{},\n\t\t\"ControlCenterAgent.GetEvaluatedService\": struct{}{},\n\t\t\"ControlCenterAgent.GetHostID\":           struct{}{},\n\t\t\"ControlCenterAgent.GetZkInfo\":           struct{}{},\n\t\t\"ControlCenterAgent.Ping\":                struct{}{},\n\t\t\"ControlCenterAgent.GetISvcEndpoints\":    struct{}{},\n\t\t\"ControlCenterAgent.ReportHealthStatus\":  struct{}{},\n\t\t\"ControlCenterAgent.ReportInstanceDead\":  struct{}{},\n\t\t\"ControlCenterAgent.SendLogMessage\":      struct{}{},\n\t}\n\tendian = binary.BigEndian\n\n\tErrNoAdmin = errors.New(\"Delegate does not have admin access\")\n\n\tlog = logging.PackageLogger()\n)\n\n\/\/ Checks the RPC method name to see if authentication is required.\n\/\/  If it is, calls on the client side will include a signed header, which will be\n\/\/  Verified on the server side\nfunc requiresAuthentication(callName string) bool {\n\tfor _, name := range NonAuthenticatingCalls {\n\t\tif name == callName {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\/\/ Checks the RPC method name to see if admin-level permissions are required.\n\/\/  If they are, it will also check the \"admin\" attribute on the identity after validating it.\nfunc requiresAdmin(callName string) bool {\n\t_, ok := NonAdminRequiredCalls[callName]\n\treturn !ok\n}\n\n\/\/ We nead a ReadWriteCloser that we can pass to the underlying codec and use\n\/\/  To buffer requests and responses from the actual connection\ntype ByteBufferReadWriteCloser struct {\n\tReadBuff  bytes.Buffer \/\/ Reads will happen from this buffer\n\tWriteBuff bytes.Buffer \/\/ Writes will happen to this buffer\n}\n\nfunc (b *ByteBufferReadWriteCloser) Read(p []byte) (int, error) {\n\treturn b.ReadBuff.Read(p)\n}\n\nfunc (b *ByteBufferReadWriteCloser) Write(p []byte) (int, error) {\n\treturn b.WriteBuff.Write(p)\n}\n\nfunc (b *ByteBufferReadWriteCloser) Close() error {\n\treturn nil\n}\n\ntype ServerCodecCreator func(io.ReadWriteCloser) rpc.ServerCodec\n\n\/\/ Server Codec\ntype AuthServerCodec struct {\n\tconn         io.ReadWriteCloser\n\tbuff         *ByteBufferReadWriteCloser\n\twrappedcodec rpc.ServerCodec\n\tparser       auth.RPCHeaderParser\n\twBuffMutex   sync.Mutex \/\/ Make sure we buffer one response at a time\n\tlastError    error\n}\n\nfunc NewDefaultAuthServerCodec(conn io.ReadWriteCloser) rpc.ServerCodec {\n\treturn NewAuthServerCodec(conn, jsonrpc.NewServerCodec, &auth.RPCHeaderHandler{})\n}\n\nfunc NewAuthServerCodec(conn io.ReadWriteCloser, createCodec ServerCodecCreator, parser auth.RPCHeaderParser) rpc.ServerCodec {\n\tbuff := &ByteBufferReadWriteCloser{}\n\treturn &AuthServerCodec{\n\t\tconn:         conn,\n\t\tbuff:         buff,\n\t\twrappedcodec: createCodec(buff),\n\t\tparser:       parser,\n\t}\n}\n\n\/\/ Reads the request header and populates the rpc.Request object.\n\/\/  This implementation reads the auth header off the stream first, then\n\/\/  lets the underlying codec read the rest.\n\/\/  Finally, it validates the identity if necessary.\nfunc (a *AuthServerCodec) ReadRequestHeader(r *rpc.Request) error {\n\n\t\/\/ There is no need for synchronization here, since go's RPC server\n\t\/\/  ensures that requests are read one-at-a-time\n\n\t\/\/ Reset state\n\ta.lastError = nil\n\ta.buff.ReadBuff.Reset()\n\n\tident, body, err := a.parser.ReadHeader(a.conn)\n\tif err != nil {\n\t\tlog.WithError(err).WithField(\"ServiceMethod\", r.ServiceMethod).Debug(\"Could not authenticate RPC request\")\n\t\tif e, ok := err.(*auth.AuthHeaderError); ok {\n\t\t\tbody = e.Payload\n\t\t\ta.lastError = e.Err\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Now write the actual request to the buffer\n\tif _, err = a.buff.ReadBuff.Write(body); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Let the underlying codec read the request from the buffer and parse it\n\tif err := a.wrappedcodec.ReadRequestHeader(r); err != nil {\n\t\treturn err\n\t}\n\n\tlog.WithField(\"ServiceMethod\", r.ServiceMethod).Debug(\"Received RPC request\")\n\n\t\/\/ Now we can get the method name from r and authenticate if required\n\t\/\/  If this fails, save the error to return later\n\t\/\/  If we return an error now, the server will simply close the connection\n\t\/\/  This is safe because go's rpc server always calls ReadRequestHeader and ReadRequestBody back-to-back\n\t\/\/   (unless ReadRequestHeader returns an error)\n\tif requiresAuthentication(r.ServiceMethod) {\n\t\tif a.lastError == nil {\n\t\t\tif requiresAdmin(r.ServiceMethod) && (ident == nil || !ident.HasAdminAccess()) {\n\t\t\t\tlog.WithField(\"ServiceMethod\", r.ServiceMethod).Debug(\"Received unauthorized RPC request\")\n\t\t\t\ta.lastError = ErrNoAdmin\n\t\t\t}\n\t\t}\n\t\t\/\/TODO: save the identity so we can inject it into the request body later\n\t}\n\treturn nil\n}\n\n\/\/ Decodes the request and populates the body object with the body of the request\n\/\/  We don't change anything here, just let the underlying codec handle it.\n\/\/  This always gets called after ReadRequestHeader\nfunc (a *AuthServerCodec) ReadRequestBody(body interface{}) error {\n\tif a.lastError != nil {\n\t\treturn a.lastError\n\t}\n\t\/\/ TODO: Use reflection and add the identity to the body if necessary\n\treturn a.wrappedcodec.ReadRequestBody(body)\n}\n\n\/\/  Encodes the response before sending it back down to the client.\n\/\/  We don't change anything here, just let the underlying codec handle it.\nfunc (a *AuthServerCodec) WriteResponse(r *rpc.Response, body interface{}) error {\n\t\/\/ We do need a lock here, because the ServerCodec interface specifies\n\t\/\/  that WriteResponse must be safe for concurrent use by multiple goroutines\n\ta.wBuffMutex.Lock()\n\tdefer a.wBuffMutex.Unlock()\n\n\ta.buff.WriteBuff.Reset()\n\n\t\/\/ Let the underlying codec write the response to the buffer\n\tif err := a.wrappedcodec.WriteResponse(r, body); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Get the response from the buffer and write it to the actual connection\n\tresponse := a.buff.WriteBuff.Bytes()\n\tif err := auth.WriteLengthAndBytes(response, a.conn); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ Closes the connection on the server side\n\/\/  We don't change anything here, just let the underlying codec handle it.\nfunc (a *AuthServerCodec) Close() error {\n\tvar err error\n\tif err = a.wrappedcodec.Close(); err != nil {\n\t\tlog.WithError(err).Debug(\"Error closing wrapped RPC client codec\")\n\t}\n\tif ourErr := a.conn.Close(); ourErr != nil {\n\t\tlog.WithError(ourErr).Debug(\"Error closing RPC client connection\")\n\t\t\/\/ This error is probably more important\n\t\terr = ourErr\n\t}\n\treturn err\n}\n\n\/\/ Client Codec\ntype ClientCodecCreator func(io.ReadWriteCloser) rpc.ClientCodec\ntype AuthClientCodec struct {\n\tconn          io.ReadWriteCloser\n\tbuff          *ByteBufferReadWriteCloser\n\twrappedcodec  rpc.ClientCodec\n\theaderBuilder auth.RPCHeaderBuilder\n\twBuffMutex    sync.Mutex \/\/ Make sure we buffer a whole request before starting the next one\n}\n\nfunc NewDefaultAuthClientCodec(conn io.ReadWriteCloser) rpc.ClientCodec {\n\treturn NewAuthClientCodec(conn, jsonrpc.NewClientCodec, &auth.RPCHeaderHandler{})\n}\n\nfunc NewAuthClientCodec(conn io.ReadWriteCloser, createCodec ClientCodecCreator, headerBuilder auth.RPCHeaderBuilder) rpc.ClientCodec {\n\tbuff := &ByteBufferReadWriteCloser{}\n\treturn &AuthClientCodec{\n\t\tconn:          conn,\n\t\tbuff:          buff,\n\t\twrappedcodec:  createCodec(buff),\n\t\theaderBuilder: headerBuilder,\n\t}\n}\n\n\/\/ Encodes the request and sends it to the server.\n\/\/ This implementation gets an auth header when appropriate, and writes it to the stream\n\/\/  before letting the underlying codec send the rest of the request.\nfunc (a *AuthClientCodec) WriteRequest(r *rpc.Request, body interface{}) error {\n\t\/\/ Lock to ensure we write the header and the rest of the request back-to-back\n\t\/\/  This method may be called by multiple goroutines concurrently\n\ta.wBuffMutex.Lock()\n\tdefer a.wBuffMutex.Unlock()\n\ta.buff.WriteBuff.Reset()\n\n\t\/\/ Let the underlying codec write the request to the buffer\n\tif err := a.wrappedcodec.WriteRequest(r, body); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Get the request off the buffer\n\trequest := a.buff.WriteBuff.Bytes()\n\n\tneedsAuth := requiresAuthentication(r.ServiceMethod)\n\tif err := a.headerBuilder.WriteHeader(a.conn, request, needsAuth); err != nil {\n\t\treturn err\n\t}\n\n\tlog.WithField(\"ServiceMethod\", r.ServiceMethod).Debug(\"Successfully sent RPC request\")\n\n\treturn nil\n}\n\n\/\/ Decodes the response and reads the header, building the rpc.Response object\n\/\/  We don't change anything here, just let the underlying codec handle it.\nfunc (a *AuthClientCodec) ReadResponseHeader(r *rpc.Response) error {\n\n\t\/\/ No need for synchronization here, Go's RPC Client makes sure only\n\t\/\/  One response is read at a time.\n\n\ta.buff.ReadBuff.Reset()\n\n\t\/\/ Read the response from the connection\n\tresponse, err := auth.ReadLengthAndBytes(a.conn)\n\tif err != nil {\n\t\t\/\/ It is common to get harmless errors here whenever the client is closed\n\t\treturn err\n\t}\n\n\t\/\/ Write the response to the buffer\n\tif _, err = a.buff.ReadBuff.Write(response); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Let the underlying codec read and parse the response from the buffer\n\tif err = a.wrappedcodec.ReadResponseHeader(r); err != nil {\n\t\treturn err\n\t}\n\n\tlog.WithField(\"ServiceMethod\", r.ServiceMethod).Debug(\"Successfully read RPC response\")\n\n\treturn nil\n}\n\n\/\/ Decodes the body of the response and builds the body object.\n\/\/ We don't change anything here, just let the underlying codec handle it.\nfunc (a *AuthClientCodec) ReadResponseBody(body interface{}) error {\n\treturn a.wrappedcodec.ReadResponseBody(body)\n}\n\n\/\/ Closes the connection on the client side\n\/\/  We don't change anything here, just let the underlying codec handle it.\nfunc (a *AuthClientCodec) Close() error {\n\tvar err error\n\tif err = a.wrappedcodec.Close(); err != nil {\n\t\tlog.WithError(err).Debug(\"Error closing wrapped RPC client codec\")\n\t}\n\tif ourErr := a.conn.Close(); ourErr != nil {\n\t\tlog.WithError(ourErr).Debug(\"Error closing RPC client connection\")\n\t\t\/\/ This error is more important\n\t\terr = ourErr\n\t}\n\treturn err\n}\n\n\/\/ NewDefaultAuthClient returns a new rpc.Client that uses our default client codec\nfunc NewDefaultAuthClient(conn io.ReadWriteCloser) *rpc.Client {\n\treturn rpc.NewClientWithCodec(NewDefaultAuthClientCodec(conn))\n}\n<commit_msg>Add Master.UpdateHost to the non-admin RPC list<commit_after>\/\/ Copyright 2016 The Serviced Authors.\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage rpcutils\n\nimport (\n\t\"bytes\"\n\t\"encoding\/binary\"\n\t\"errors\"\n\t\"io\"\n\t\"net\/rpc\"\n\t\"net\/rpc\/jsonrpc\"\n\t\"sync\"\n\n\t\"github.com\/control-center\/serviced\/auth\"\n\t\"github.com\/control-center\/serviced\/logging\"\n)\n\nvar (\n\t\/\/ RPC Calls that do not require authentication or who handle authentication separately:\n\tNonAuthenticatingCalls = []string{\"Master.AuthenticateHost\", \"Agent.BuildHost\"}\n\t\/\/ RPC calls that do not require admin access:\n\tNonAdminRequiredCalls = map[string]struct{}{\n\t\t\"Master.GetHost\":                         struct{}{},\n\t\t\"Master.GetHosts\":                        struct{}{},\n\t\t\"Master.GetEvaluatedService\":             struct{}{},\n\t\t\"Master.GetSystemUser\":                   struct{}{},\n\t\t\"Master.ReportHealthStatus\":              struct{}{},\n\t\t\"Master.ReportInstanceDead\":              struct{}{},\n\t\t\"Master.UpdateHost\":                      struct{}{},\n\t\t\"ControlCenter.GetServices\":              struct{}{},\n\t\t\"ControlCenterAgent.GetEvaluatedService\": struct{}{},\n\t\t\"ControlCenterAgent.GetHostID\":           struct{}{},\n\t\t\"ControlCenterAgent.GetZkInfo\":           struct{}{},\n\t\t\"ControlCenterAgent.Ping\":                struct{}{},\n\t\t\"ControlCenterAgent.GetISvcEndpoints\":    struct{}{},\n\t\t\"ControlCenterAgent.ReportHealthStatus\":  struct{}{},\n\t\t\"ControlCenterAgent.ReportInstanceDead\":  struct{}{},\n\t\t\"ControlCenterAgent.SendLogMessage\":      struct{}{},\n\t}\n\tendian = binary.BigEndian\n\n\tErrNoAdmin = errors.New(\"Delegate does not have admin access\")\n\n\tlog = logging.PackageLogger()\n)\n\n\/\/ Checks the RPC method name to see if authentication is required.\n\/\/  If it is, calls on the client side will include a signed header, which will be\n\/\/  Verified on the server side\nfunc requiresAuthentication(callName string) bool {\n\tfor _, name := range NonAuthenticatingCalls {\n\t\tif name == callName {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\/\/ Checks the RPC method name to see if admin-level permissions are required.\n\/\/  If they are, it will also check the \"admin\" attribute on the identity after validating it.\nfunc requiresAdmin(callName string) bool {\n\t_, ok := NonAdminRequiredCalls[callName]\n\treturn !ok\n}\n\n\/\/ We nead a ReadWriteCloser that we can pass to the underlying codec and use\n\/\/  To buffer requests and responses from the actual connection\ntype ByteBufferReadWriteCloser struct {\n\tReadBuff  bytes.Buffer \/\/ Reads will happen from this buffer\n\tWriteBuff bytes.Buffer \/\/ Writes will happen to this buffer\n}\n\nfunc (b *ByteBufferReadWriteCloser) Read(p []byte) (int, error) {\n\treturn b.ReadBuff.Read(p)\n}\n\nfunc (b *ByteBufferReadWriteCloser) Write(p []byte) (int, error) {\n\treturn b.WriteBuff.Write(p)\n}\n\nfunc (b *ByteBufferReadWriteCloser) Close() error {\n\treturn nil\n}\n\ntype ServerCodecCreator func(io.ReadWriteCloser) rpc.ServerCodec\n\n\/\/ Server Codec\ntype AuthServerCodec struct {\n\tconn         io.ReadWriteCloser\n\tbuff         *ByteBufferReadWriteCloser\n\twrappedcodec rpc.ServerCodec\n\tparser       auth.RPCHeaderParser\n\twBuffMutex   sync.Mutex \/\/ Make sure we buffer one response at a time\n\tlastError    error\n}\n\nfunc NewDefaultAuthServerCodec(conn io.ReadWriteCloser) rpc.ServerCodec {\n\treturn NewAuthServerCodec(conn, jsonrpc.NewServerCodec, &auth.RPCHeaderHandler{})\n}\n\nfunc NewAuthServerCodec(conn io.ReadWriteCloser, createCodec ServerCodecCreator, parser auth.RPCHeaderParser) rpc.ServerCodec {\n\tbuff := &ByteBufferReadWriteCloser{}\n\treturn &AuthServerCodec{\n\t\tconn:         conn,\n\t\tbuff:         buff,\n\t\twrappedcodec: createCodec(buff),\n\t\tparser:       parser,\n\t}\n}\n\n\/\/ Reads the request header and populates the rpc.Request object.\n\/\/  This implementation reads the auth header off the stream first, then\n\/\/  lets the underlying codec read the rest.\n\/\/  Finally, it validates the identity if necessary.\nfunc (a *AuthServerCodec) ReadRequestHeader(r *rpc.Request) error {\n\n\t\/\/ There is no need for synchronization here, since go's RPC server\n\t\/\/  ensures that requests are read one-at-a-time\n\n\t\/\/ Reset state\n\ta.lastError = nil\n\ta.buff.ReadBuff.Reset()\n\n\tident, body, err := a.parser.ReadHeader(a.conn)\n\tif err != nil {\n\t\tlog.WithError(err).WithField(\"ServiceMethod\", r.ServiceMethod).Debug(\"Could not authenticate RPC request\")\n\t\tif e, ok := err.(*auth.AuthHeaderError); ok {\n\t\t\tbody = e.Payload\n\t\t\ta.lastError = e.Err\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Now write the actual request to the buffer\n\tif _, err = a.buff.ReadBuff.Write(body); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Let the underlying codec read the request from the buffer and parse it\n\tif err := a.wrappedcodec.ReadRequestHeader(r); err != nil {\n\t\treturn err\n\t}\n\n\tlog.WithField(\"ServiceMethod\", r.ServiceMethod).Debug(\"Received RPC request\")\n\n\t\/\/ Now we can get the method name from r and authenticate if required\n\t\/\/  If this fails, save the error to return later\n\t\/\/  If we return an error now, the server will simply close the connection\n\t\/\/  This is safe because go's rpc server always calls ReadRequestHeader and ReadRequestBody back-to-back\n\t\/\/   (unless ReadRequestHeader returns an error)\n\tif requiresAuthentication(r.ServiceMethod) {\n\t\tif a.lastError == nil {\n\t\t\tif requiresAdmin(r.ServiceMethod) && (ident == nil || !ident.HasAdminAccess()) {\n\t\t\t\tlog.WithField(\"ServiceMethod\", r.ServiceMethod).Debug(\"Received unauthorized RPC request\")\n\t\t\t\ta.lastError = ErrNoAdmin\n\t\t\t}\n\t\t}\n\t\t\/\/TODO: save the identity so we can inject it into the request body later\n\t}\n\treturn nil\n}\n\n\/\/ Decodes the request and populates the body object with the body of the request\n\/\/  We don't change anything here, just let the underlying codec handle it.\n\/\/  This always gets called after ReadRequestHeader\nfunc (a *AuthServerCodec) ReadRequestBody(body interface{}) error {\n\tif a.lastError != nil {\n\t\treturn a.lastError\n\t}\n\t\/\/ TODO: Use reflection and add the identity to the body if necessary\n\treturn a.wrappedcodec.ReadRequestBody(body)\n}\n\n\/\/  Encodes the response before sending it back down to the client.\n\/\/  We don't change anything here, just let the underlying codec handle it.\nfunc (a *AuthServerCodec) WriteResponse(r *rpc.Response, body interface{}) error {\n\t\/\/ We do need a lock here, because the ServerCodec interface specifies\n\t\/\/  that WriteResponse must be safe for concurrent use by multiple goroutines\n\ta.wBuffMutex.Lock()\n\tdefer a.wBuffMutex.Unlock()\n\n\ta.buff.WriteBuff.Reset()\n\n\t\/\/ Let the underlying codec write the response to the buffer\n\tif err := a.wrappedcodec.WriteResponse(r, body); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Get the response from the buffer and write it to the actual connection\n\tresponse := a.buff.WriteBuff.Bytes()\n\tif err := auth.WriteLengthAndBytes(response, a.conn); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ Closes the connection on the server side\n\/\/  We don't change anything here, just let the underlying codec handle it.\nfunc (a *AuthServerCodec) Close() error {\n\tvar err error\n\tif err = a.wrappedcodec.Close(); err != nil {\n\t\tlog.WithError(err).Debug(\"Error closing wrapped RPC client codec\")\n\t}\n\tif ourErr := a.conn.Close(); ourErr != nil {\n\t\tlog.WithError(ourErr).Debug(\"Error closing RPC client connection\")\n\t\t\/\/ This error is probably more important\n\t\terr = ourErr\n\t}\n\treturn err\n}\n\n\/\/ Client Codec\ntype ClientCodecCreator func(io.ReadWriteCloser) rpc.ClientCodec\ntype AuthClientCodec struct {\n\tconn          io.ReadWriteCloser\n\tbuff          *ByteBufferReadWriteCloser\n\twrappedcodec  rpc.ClientCodec\n\theaderBuilder auth.RPCHeaderBuilder\n\twBuffMutex    sync.Mutex \/\/ Make sure we buffer a whole request before starting the next one\n}\n\nfunc NewDefaultAuthClientCodec(conn io.ReadWriteCloser) rpc.ClientCodec {\n\treturn NewAuthClientCodec(conn, jsonrpc.NewClientCodec, &auth.RPCHeaderHandler{})\n}\n\nfunc NewAuthClientCodec(conn io.ReadWriteCloser, createCodec ClientCodecCreator, headerBuilder auth.RPCHeaderBuilder) rpc.ClientCodec {\n\tbuff := &ByteBufferReadWriteCloser{}\n\treturn &AuthClientCodec{\n\t\tconn:          conn,\n\t\tbuff:          buff,\n\t\twrappedcodec:  createCodec(buff),\n\t\theaderBuilder: headerBuilder,\n\t}\n}\n\n\/\/ Encodes the request and sends it to the server.\n\/\/ This implementation gets an auth header when appropriate, and writes it to the stream\n\/\/  before letting the underlying codec send the rest of the request.\nfunc (a *AuthClientCodec) WriteRequest(r *rpc.Request, body interface{}) error {\n\t\/\/ Lock to ensure we write the header and the rest of the request back-to-back\n\t\/\/  This method may be called by multiple goroutines concurrently\n\ta.wBuffMutex.Lock()\n\tdefer a.wBuffMutex.Unlock()\n\ta.buff.WriteBuff.Reset()\n\n\t\/\/ Let the underlying codec write the request to the buffer\n\tif err := a.wrappedcodec.WriteRequest(r, body); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Get the request off the buffer\n\trequest := a.buff.WriteBuff.Bytes()\n\n\tneedsAuth := requiresAuthentication(r.ServiceMethod)\n\tif err := a.headerBuilder.WriteHeader(a.conn, request, needsAuth); err != nil {\n\t\treturn err\n\t}\n\n\tlog.WithField(\"ServiceMethod\", r.ServiceMethod).Debug(\"Successfully sent RPC request\")\n\n\treturn nil\n}\n\n\/\/ Decodes the response and reads the header, building the rpc.Response object\n\/\/  We don't change anything here, just let the underlying codec handle it.\nfunc (a *AuthClientCodec) ReadResponseHeader(r *rpc.Response) error {\n\n\t\/\/ No need for synchronization here, Go's RPC Client makes sure only\n\t\/\/  One response is read at a time.\n\n\ta.buff.ReadBuff.Reset()\n\n\t\/\/ Read the response from the connection\n\tresponse, err := auth.ReadLengthAndBytes(a.conn)\n\tif err != nil {\n\t\t\/\/ It is common to get harmless errors here whenever the client is closed\n\t\treturn err\n\t}\n\n\t\/\/ Write the response to the buffer\n\tif _, err = a.buff.ReadBuff.Write(response); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Let the underlying codec read and parse the response from the buffer\n\tif err = a.wrappedcodec.ReadResponseHeader(r); err != nil {\n\t\treturn err\n\t}\n\n\tlog.WithField(\"ServiceMethod\", r.ServiceMethod).Debug(\"Successfully read RPC response\")\n\n\treturn nil\n}\n\n\/\/ Decodes the body of the response and builds the body object.\n\/\/ We don't change anything here, just let the underlying codec handle it.\nfunc (a *AuthClientCodec) ReadResponseBody(body interface{}) error {\n\treturn a.wrappedcodec.ReadResponseBody(body)\n}\n\n\/\/ Closes the connection on the client side\n\/\/  We don't change anything here, just let the underlying codec handle it.\nfunc (a *AuthClientCodec) Close() error {\n\tvar err error\n\tif err = a.wrappedcodec.Close(); err != nil {\n\t\tlog.WithError(err).Debug(\"Error closing wrapped RPC client codec\")\n\t}\n\tif ourErr := a.conn.Close(); ourErr != nil {\n\t\tlog.WithError(ourErr).Debug(\"Error closing RPC client connection\")\n\t\t\/\/ This error is more important\n\t\terr = ourErr\n\t}\n\treturn err\n}\n\n\/\/ NewDefaultAuthClient returns a new rpc.Client that uses our default client codec\nfunc NewDefaultAuthClient(conn io.ReadWriteCloser) *rpc.Client {\n\treturn rpc.NewClientWithCodec(NewDefaultAuthClientCodec(conn))\n}\n<|endoftext|>"}
{"text":"<commit_before>package angularjs\n\nimport \"github.com\/gopherjs\/gopherjs\/js\"\n\ntype Module struct{ *js.Object }\n\nfunc (m *Module) NewController(name string, constructor func(scope *Scope)) {\n\tm.Call(\"controller\", name, func(dollar_scope *js.Object) {\n\t\tconstructor(&Scope{dollar_scope})\n\t})\n}\n\ntype Scope struct{ *js.Object }\n\nfunc (s *Scope) Apply(f func()) {\n\ts.Call(\"$apply\", f)\n}\n\nfunc (s *Scope) EvalAsync(f func()) {\n\ts.Call(\"$evalAsync\", f)\n}\n\ntype JQueryElement struct{ *js.Object }\n\nfunc (e *JQueryElement) Prop(name string) *js.Object {\n\treturn e.Call(\"prop\", name)\n}\n\nfunc (e *JQueryElement) SetProp(name, value interface{}) {\n\te.Call(\"prop\", name, value)\n}\n\nfunc (e *JQueryElement) On(events string, handler func(*Event)) {\n\te.Call(\"on\", events, func(e *js.Object) {\n\t\thandler(&Event{Object: e})\n\t})\n}\n\nfunc (e *JQueryElement) Val() *js.Object {\n\treturn e.Call(\"val\")\n}\n\nfunc (e *JQueryElement) SetVal(value interface{}) {\n\te.Call(\"val\", value)\n}\n\ntype Event struct {\n\t*js.Object\n\tKeyCode int `js:\"keyCode\"`\n}\n\nfunc (e *Event) PreventDefault() {\n\te.Call(\"preventDefault\")\n}\n\nfunc NewModule(name string, requires []string, configFn func()) *Module {\n\treturn &Module{js.Global.Get(\"angular\").Call(\"module\", name, requires, configFn)}\n}\n\nfunc ElementById(id string) *JQueryElement {\n\treturn &JQueryElement{js.Global.Get(\"angular\").Call(\"element\", js.Global.Get(\"document\").Call(\"getElementById\", id))}\n}\n\nfunc Service(name string) *js.Object {\n\treturn js.Global.Get(\"angular\").Call(\"element\", js.Global.Get(\"document\")).Call(\"injector\").Call(\"get\", name)\n}\n\ntype HttpService struct{}\n\nvar HTTP = new(HttpService)\n\nfunc (s *HttpService) Get(url string, callback func(data string, status int)) {\n\tfuture := Service(\"$http\").Call(\"get\", url)\n\tfuture.Call(\"success\", func(data string, status int, headers *js.Object, config *js.Object) {\n\t\tcallback(data, status)\n\t})\n\tfuture.Call(\"error\", func(data string, status int, headers *js.Object, config *js.Object) {\n\t\tcallback(data, status)\n\t})\n}\n<commit_msg>explicit names for AngularJS injector<commit_after>package angularjs\n\nimport \"github.com\/gopherjs\/gopherjs\/js\"\n\ntype Module struct{ *js.Object }\n\nfunc (m *Module) NewController(name string, constructor func(scope *Scope)) {\n\tm.Call(\"controller\", name, js.S{\"$scope\", func(scope *js.Object) {\n\t\tconstructor(&Scope{scope})\n\t}})\n}\n\ntype Scope struct{ *js.Object }\n\nfunc (s *Scope) Apply(f func()) {\n\ts.Call(\"$apply\", f)\n}\n\nfunc (s *Scope) EvalAsync(f func()) {\n\ts.Call(\"$evalAsync\", f)\n}\n\ntype JQueryElement struct{ *js.Object }\n\nfunc (e *JQueryElement) Prop(name string) *js.Object {\n\treturn e.Call(\"prop\", name)\n}\n\nfunc (e *JQueryElement) SetProp(name, value interface{}) {\n\te.Call(\"prop\", name, value)\n}\n\nfunc (e *JQueryElement) On(events string, handler func(*Event)) {\n\te.Call(\"on\", events, func(e *js.Object) {\n\t\thandler(&Event{Object: e})\n\t})\n}\n\nfunc (e *JQueryElement) Val() *js.Object {\n\treturn e.Call(\"val\")\n}\n\nfunc (e *JQueryElement) SetVal(value interface{}) {\n\te.Call(\"val\", value)\n}\n\ntype Event struct {\n\t*js.Object\n\tKeyCode int `js:\"keyCode\"`\n}\n\nfunc (e *Event) PreventDefault() {\n\te.Call(\"preventDefault\")\n}\n\nfunc NewModule(name string, requires []string, configFn func()) *Module {\n\treturn &Module{js.Global.Get(\"angular\").Call(\"module\", name, requires, configFn)}\n}\n\nfunc ElementById(id string) *JQueryElement {\n\treturn &JQueryElement{js.Global.Get(\"angular\").Call(\"element\", js.Global.Get(\"document\").Call(\"getElementById\", id))}\n}\n\nfunc Service(name string) *js.Object {\n\treturn js.Global.Get(\"angular\").Call(\"element\", js.Global.Get(\"document\")).Call(\"injector\").Call(\"get\", name)\n}\n\ntype HttpService struct{}\n\nvar HTTP = new(HttpService)\n\nfunc (s *HttpService) Get(url string, callback func(data string, status int)) {\n\tfuture := Service(\"$http\").Call(\"get\", url)\n\tfuture.Call(\"success\", func(data string, status int, headers *js.Object, config *js.Object) {\n\t\tcallback(data, status)\n\t})\n\tfuture.Call(\"error\", func(data string, status int, headers *js.Object, config *js.Object) {\n\t\tcallback(data, status)\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2012, Google Inc. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage tabletserver\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\tlog \"github.com\/golang\/glog\"\n\t\"github.com\/youtube\/vitess\/go\/mysql\"\n\t\"github.com\/youtube\/vitess\/go\/tb\"\n\t\"github.com\/youtube\/vitess\/go\/vt\/logutil\"\n)\n\nconst (\n\t\/\/ ErrFail is returned when a query fails\n\tErrFail = iota\n\n\t\/\/ ErrRetry is returned when a query can be retried\n\tErrRetry\n\n\t\/\/ ErrFatal is returned when a query cannot be retried\n\tErrFatal\n\n\t\/\/ ErrTxPoolFull is returned when we can't get a connection\n\tErrTxPoolFull\n\n\t\/\/ ErrNotInTx is returned when we're not in a transaction but should be\n\tErrNotInTx\n)\n\nvar logTxPoolFull = logutil.NewThrottledLogger(\"TxPoolFull\", 1*time.Minute)\n\n\/\/ TabletError is the erro type we use in this library\ntype TabletError struct {\n\tErrorType int\n\tMessage   string\n\tSqlError  int\n}\n\n\/\/ This is how go-mysql exports its error number\ntype hasNumber interface {\n\tNumber() int\n}\n\n\/\/ NewTabletError returns a TabletError of the given type\nfunc NewTabletError(errorType int, format string, args ...interface{}) *TabletError {\n\treturn &TabletError{\n\t\tErrorType: errorType,\n\t\tMessage:   fmt.Sprintf(format, args...),\n\t}\n}\n\n\/\/ NewTabletErrorSql returns a TabletError based on the error\nfunc NewTabletErrorSql(errorType int, err error) *TabletError {\n\tvar errnum int\n\terrstr := err.Error()\n\tif sqlErr, ok := err.(hasNumber); ok {\n\t\terrnum = sqlErr.Number()\n\t\t\/\/ Override error type if MySQL is in read-only mode. It's probably because\n\t\t\/\/ there was a remaster and there are old clients still connected.\n\t\tif errnum == mysql.ErrOptionPreventsStatement && strings.Contains(errstr, \"read-only\") {\n\t\t\terrorType = ErrRetry\n\t\t}\n\t}\n\treturn &TabletError{\n\t\tErrorType: errorType,\n\t\tMessage:   errstr,\n\t\tSqlError:  errnum,\n\t}\n}\n\nvar errExtract = regexp.MustCompile(`.*\\(errno ([0-9]*)\\).*`)\n\n\/\/ IsConnErr returns true if the error is a connection error. If\n\/\/ the error is of type TabletError or hasNumber, it checks the error\n\/\/ code. Otherwise, it parses the string looking for (errno xxxx)\n\/\/ and uses the extracted value to determine if it's a conn error.\nfunc IsConnErr(err error) bool {\n\tvar sqlError int\n\tswitch err := err.(type) {\n\tcase *TabletError:\n\t\tsqlError = err.SqlError\n\tcase hasNumber:\n\t\tsqlError = err.Number()\n\tdefault:\n\t\tmatch := errExtract.FindStringSubmatch(err.Error())\n\t\tif len(match) < 2 {\n\t\t\treturn false\n\t\t}\n\t\tvar convErr error\n\t\tsqlError, convErr = strconv.Atoi(match[1])\n\t\tif convErr != nil {\n\t\t\treturn false\n\t\t}\n\t}\n\t\/\/ 2013 means that someone sniped the query.\n\tif sqlError == 2013 {\n\t\treturn false\n\t}\n\treturn sqlError >= 2000 && sqlError <= 2018\n}\n\nfunc (te *TabletError) Error() string {\n\tformat := \"error: %s\"\n\tswitch te.ErrorType {\n\tcase ErrRetry:\n\t\tformat = \"retry: %s\"\n\tcase ErrFatal:\n\t\tformat = \"fatal: %s\"\n\tcase ErrTxPoolFull:\n\t\tformat = \"tx_pool_full: %s\"\n\tcase ErrNotInTx:\n\t\tformat = \"not_in_tx: %s\"\n\t}\n\treturn fmt.Sprintf(format, te.Message)\n}\n\n\/\/ RecordStats will record the error in the proper stat bucket\nfunc (te *TabletError) RecordStats() {\n\tswitch te.ErrorType {\n\tcase ErrRetry:\n\t\tinfoErrors.Add(\"Retry\", 1)\n\tcase ErrFatal:\n\t\tinfoErrors.Add(\"Fatal\", 1)\n\tcase ErrTxPoolFull:\n\t\terrorStats.Add(\"TxPoolFull\", 1)\n\tcase ErrNotInTx:\n\t\terrorStats.Add(\"NotInTx\", 1)\n\tdefault:\n\t\tswitch te.SqlError {\n\t\tcase mysql.ErrDupEntry:\n\t\t\tinfoErrors.Add(\"DupKey\", 1)\n\t\tcase mysql.ErrLockWaitTimeout, mysql.ErrLockDeadlock:\n\t\t\terrorStats.Add(\"Deadlock\", 1)\n\t\tdefault:\n\t\t\terrorStats.Add(\"Fail\", 1)\n\t\t}\n\t}\n}\n\nfunc handleError(err *error, logStats *SQLQueryStats) {\n\tif x := recover(); x != nil {\n\t\tterr, ok := x.(*TabletError)\n\t\tif !ok {\n\t\t\tlog.Errorf(\"Uncaught panic:\\n%v\\n%s\", x, tb.Stack(4))\n\t\t\t*err = NewTabletError(ErrFail, \"%v: uncaught panic\", x)\n\t\t\tinternalErrors.Add(\"Panic\", 1)\n\t\t\treturn\n\t\t}\n\t\t*err = terr\n\t\tterr.RecordStats()\n\t\tif terr.ErrorType == ErrRetry { \/\/ Retry errors are too spammy\n\t\t\treturn\n\t\t}\n\t\tif terr.ErrorType == ErrTxPoolFull {\n\t\t\tlogTxPoolFull.Errorf(\"%v\", terr)\n\t\t} else {\n\t\t\tlog.Errorf(\"%v\", terr)\n\t\t}\n\t}\n\tif logStats != nil {\n\t\tlogStats.Error = *err\n\t\tlogStats.Send()\n\t}\n}\n\nfunc logError() {\n\tif x := recover(); x != nil {\n\t\tterr, ok := x.(*TabletError)\n\t\tif !ok {\n\t\t\tlog.Errorf(\"Uncaught panic:\\n%v\\n%s\", x, tb.Stack(4))\n\t\t\tinternalErrors.Add(\"Panic\", 1)\n\t\t\treturn\n\t\t}\n\t\tif terr.ErrorType == ErrTxPoolFull {\n\t\t\tlogTxPoolFull.Errorf(\"%v\", terr)\n\t\t} else {\n\t\t\tlog.Errorf(\"%v\", terr)\n\t\t}\n\t}\n}\n<commit_msg>tabletserver: readable error messages<commit_after>\/\/ Copyright 2012, Google Inc. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage tabletserver\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\tlog \"github.com\/golang\/glog\"\n\t\"github.com\/youtube\/vitess\/go\/mysql\"\n\t\"github.com\/youtube\/vitess\/go\/tb\"\n\t\"github.com\/youtube\/vitess\/go\/vt\/logutil\"\n)\n\nconst (\n\t\/\/ ErrFail is returned when a query fails\n\tErrFail = iota\n\n\t\/\/ ErrRetry is returned when a query can be retried\n\tErrRetry\n\n\t\/\/ ErrFatal is returned when a query cannot be retried\n\tErrFatal\n\n\t\/\/ ErrTxPoolFull is returned when we can't get a connection\n\tErrTxPoolFull\n\n\t\/\/ ErrNotInTx is returned when we're not in a transaction but should be\n\tErrNotInTx\n)\n\nconst (\n\tmaxErrLen = 5000\n)\n\nvar logTxPoolFull = logutil.NewThrottledLogger(\"TxPoolFull\", 1*time.Minute)\n\n\/\/ TabletError is the erro type we use in this library\ntype TabletError struct {\n\tErrorType int\n\tMessage   string\n\tSqlError  int\n}\n\n\/\/ This is how go-mysql exports its error number\ntype hasNumber interface {\n\tNumber() int\n}\n\n\/\/ NewTabletError returns a TabletError of the given type\nfunc NewTabletError(errorType int, format string, args ...interface{}) *TabletError {\n\treturn &TabletError{\n\t\tErrorType: errorType,\n\t\tMessage:   printable(fmt.Sprintf(format, args...)),\n\t}\n}\n\n\/\/ NewTabletErrorSql returns a TabletError based on the error\nfunc NewTabletErrorSql(errorType int, err error) *TabletError {\n\tvar errnum int\n\terrstr := err.Error()\n\tif sqlErr, ok := err.(hasNumber); ok {\n\t\terrnum = sqlErr.Number()\n\t\t\/\/ Override error type if MySQL is in read-only mode. It's probably because\n\t\t\/\/ there was a remaster and there are old clients still connected.\n\t\tif errnum == mysql.ErrOptionPreventsStatement && strings.Contains(errstr, \"read-only\") {\n\t\t\terrorType = ErrRetry\n\t\t}\n\t}\n\treturn &TabletError{\n\t\tErrorType: errorType,\n\t\tMessage:   printable(errstr),\n\t\tSqlError:  errnum,\n\t}\n}\n\nfunc printable(in string) string {\n\tif len(in) > maxErrLen {\n\t\tin = in[:maxErrLen]\n\t}\n\tin = fmt.Sprintf(\"%q\", in)\n\treturn in[1 : len(in)-1]\n}\n\nvar errExtract = regexp.MustCompile(`.*\\(errno ([0-9]*)\\).*`)\n\n\/\/ IsConnErr returns true if the error is a connection error. If\n\/\/ the error is of type TabletError or hasNumber, it checks the error\n\/\/ code. Otherwise, it parses the string looking for (errno xxxx)\n\/\/ and uses the extracted value to determine if it's a conn error.\nfunc IsConnErr(err error) bool {\n\tvar sqlError int\n\tswitch err := err.(type) {\n\tcase *TabletError:\n\t\tsqlError = err.SqlError\n\tcase hasNumber:\n\t\tsqlError = err.Number()\n\tdefault:\n\t\tmatch := errExtract.FindStringSubmatch(err.Error())\n\t\tif len(match) < 2 {\n\t\t\treturn false\n\t\t}\n\t\tvar convErr error\n\t\tsqlError, convErr = strconv.Atoi(match[1])\n\t\tif convErr != nil {\n\t\t\treturn false\n\t\t}\n\t}\n\t\/\/ 2013 means that someone sniped the query.\n\tif sqlError == 2013 {\n\t\treturn false\n\t}\n\treturn sqlError >= 2000 && sqlError <= 2018\n}\n\nfunc (te *TabletError) Error() string {\n\tprefix := \"error: \"\n\tswitch te.ErrorType {\n\tcase ErrRetry:\n\t\tprefix = \"retry: \"\n\tcase ErrFatal:\n\t\tprefix = \"fatal: \"\n\tcase ErrTxPoolFull:\n\t\tprefix = \"tx_pool_full: \"\n\tcase ErrNotInTx:\n\t\tprefix = \"not_in_tx: \"\n\t}\n\treturn prefix + te.Message\n}\n\n\/\/ RecordStats will record the error in the proper stat bucket\nfunc (te *TabletError) RecordStats() {\n\tswitch te.ErrorType {\n\tcase ErrRetry:\n\t\tinfoErrors.Add(\"Retry\", 1)\n\tcase ErrFatal:\n\t\tinfoErrors.Add(\"Fatal\", 1)\n\tcase ErrTxPoolFull:\n\t\terrorStats.Add(\"TxPoolFull\", 1)\n\tcase ErrNotInTx:\n\t\terrorStats.Add(\"NotInTx\", 1)\n\tdefault:\n\t\tswitch te.SqlError {\n\t\tcase mysql.ErrDupEntry:\n\t\t\tinfoErrors.Add(\"DupKey\", 1)\n\t\tcase mysql.ErrLockWaitTimeout, mysql.ErrLockDeadlock:\n\t\t\terrorStats.Add(\"Deadlock\", 1)\n\t\tdefault:\n\t\t\terrorStats.Add(\"Fail\", 1)\n\t\t}\n\t}\n}\n\nfunc handleError(err *error, logStats *SQLQueryStats) {\n\tif x := recover(); x != nil {\n\t\tterr, ok := x.(*TabletError)\n\t\tif !ok {\n\t\t\tlog.Errorf(\"Uncaught panic:\\n%v\\n%s\", x, tb.Stack(4))\n\t\t\t*err = NewTabletError(ErrFail, \"%v: uncaught panic\", x)\n\t\t\tinternalErrors.Add(\"Panic\", 1)\n\t\t\treturn\n\t\t}\n\t\t*err = terr\n\t\tterr.RecordStats()\n\t\tif terr.ErrorType == ErrRetry { \/\/ Retry errors are too spammy\n\t\t\treturn\n\t\t}\n\t\tif terr.ErrorType == ErrTxPoolFull {\n\t\t\tlogTxPoolFull.Errorf(\"%v\", terr)\n\t\t} else {\n\t\t\tlog.Errorf(\"%v\", terr)\n\t\t}\n\t}\n\tif logStats != nil {\n\t\tlogStats.Error = *err\n\t\tlogStats.Send()\n\t}\n}\n\nfunc logError() {\n\tif x := recover(); x != nil {\n\t\tterr, ok := x.(*TabletError)\n\t\tif !ok {\n\t\t\tlog.Errorf(\"Uncaught panic:\\n%v\\n%s\", x, tb.Stack(4))\n\t\t\tinternalErrors.Add(\"Panic\", 1)\n\t\t\treturn\n\t\t}\n\t\tif terr.ErrorType == ErrTxPoolFull {\n\t\t\tlogTxPoolFull.Errorf(\"%v\", terr)\n\t\t} else {\n\t\t\tlog.Errorf(\"%v\", terr)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ (c) 2019-2020, Ava Labs, Inc. All rights reserved.\n\/\/ See the file LICENSE for licensing terms.\n\npackage state\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"sort\"\n\n\t\"github.com\/ava-labs\/gecko\/ids\"\n\t\"github.com\/ava-labs\/gecko\/snow\/consensus\/snowstorm\"\n\t\"github.com\/ava-labs\/gecko\/snow\/engine\/avalanche\/vertex\"\n\t\"github.com\/ava-labs\/gecko\/utils\"\n\t\"github.com\/ava-labs\/gecko\/utils\/hashing\"\n\t\"github.com\/ava-labs\/gecko\/utils\/wrappers\"\n)\n\n\/\/ maxSize is the maximum allowed vertex size. It is necessary to deter DoS.\nconst maxSize = 1 << 20\n\nvar (\n\terrBadCodec       = errors.New(\"invalid codec\")\n\terrExtraSpace     = errors.New(\"trailing buffer space\")\n\terrInvalidParents = errors.New(\"vertex contains non-sorted or duplicated parentIDs\")\n\terrInvalidTxs     = errors.New(\"vertex contains non-sorted or duplicated transactions\")\n\terrNoTxs          = errors.New(\"vertex contains no transactions\")\n)\n\ntype innerVertex struct {\n\tid ids.ID\n\n\tchainID ids.ID\n\theight  uint64\n\n\tparentIDs []ids.ID\n\ttxs       []snowstorm.Tx\n\n\tbytes []byte\n}\n\nfunc (vtx *innerVertex) ID() ids.ID    { return vtx.id }\nfunc (vtx *innerVertex) Bytes() []byte { return vtx.bytes }\n\nfunc (vtx *innerVertex) Verify() error {\n\tswitch {\n\tcase !ids.IsSortedAndUniqueIDs(vtx.parentIDs):\n\t\treturn errInvalidParents\n\tcase len(vtx.txs) == 0:\n\t\treturn errNoTxs\n\tcase !isSortedAndUniqueTxs(vtx.txs):\n\t\treturn errInvalidTxs\n\tdefault:\n\t\treturn nil\n\t}\n}\n\n\/*\n * Vertex:\n * Codec        | 04 Bytes\n * Chain        | 32 Bytes\n * Height       | 08 Bytes\n * NumParents   | 04 Bytes\n * Repeated (NumParents):\n *     ParentID | 32 bytes\n * NumTxs       | 04 Bytes\n * Repeated (NumTxs):\n *     TxSize   | 04 bytes\n *     Tx       | ?? bytes\n *\/\n\n\/\/ Marshal creates the byte representation of the vertex\nfunc (vtx *innerVertex) Marshal() ([]byte, error) {\n\tp := wrappers.Packer{MaxSize: maxSize}\n\n\tp.PackInt(uint32(CustomID))\n\tp.PackFixedBytes(vtx.chainID.Bytes())\n\tp.PackLong(vtx.height)\n\n\tp.PackInt(uint32(len(vtx.parentIDs)))\n\tfor _, parentID := range vtx.parentIDs {\n\t\tp.PackFixedBytes(parentID.Bytes())\n\t}\n\n\tp.PackInt(uint32(len(vtx.txs)))\n\tfor _, tx := range vtx.txs {\n\t\tp.PackBytes(tx.Bytes())\n\t}\n\treturn p.Bytes, p.Err\n}\n\n\/\/ Unmarshal attempts to set the contents of this vertex to the value encoded in\n\/\/ the stream of bytes.\nfunc (vtx *innerVertex) Unmarshal(b []byte, vm vertex.DAGVM) error {\n\tp := wrappers.Packer{Bytes: b}\n\n\tif codecID := ID(p.UnpackInt()); codecID != CustomID {\n\t\tp.Add(errBadCodec)\n\t}\n\n\tchainID, _ := ids.ToID(p.UnpackFixedBytes(hashing.HashLen))\n\theight := p.UnpackLong()\n\n\tparentIDs := []ids.ID(nil)\n\tfor i := p.UnpackInt(); i > 0 && !p.Errored(); i-- {\n\t\tparentID, _ := ids.ToID(p.UnpackFixedBytes(hashing.HashLen))\n\t\tparentIDs = append(parentIDs, parentID)\n\t}\n\n\ttxs := []snowstorm.Tx(nil)\n\tfor i := p.UnpackInt(); i > 0 && !p.Errored(); i-- {\n\t\ttx, err := vm.ParseTx(p.UnpackBytes())\n\t\tp.Add(err)\n\t\ttxs = append(txs, tx)\n\t}\n\n\tif p.Offset != len(b) {\n\t\tp.Add(errExtraSpace)\n\t}\n\n\tif p.Errored() {\n\t\treturn p.Err\n\t}\n\n\t*vtx = innerVertex{\n\t\tid:        ids.NewID(hashing.ComputeHash256Array(b)),\n\t\tparentIDs: parentIDs,\n\t\tchainID:   chainID,\n\t\theight:    height,\n\t\ttxs:       txs,\n\t\tbytes:     b,\n\t}\n\treturn nil\n}\n\ntype sortTxsData []snowstorm.Tx\n\nfunc (txs sortTxsData) Less(i, j int) bool {\n\treturn bytes.Compare(txs[i].ID().Bytes(), txs[j].ID().Bytes()) == -1\n}\nfunc (txs sortTxsData) Len() int      { return len(txs) }\nfunc (txs sortTxsData) Swap(i, j int) { txs[j], txs[i] = txs[i], txs[j] }\n\nfunc sortTxs(txs []snowstorm.Tx) { sort.Sort(sortTxsData(txs)) }\nfunc isSortedAndUniqueTxs(txs []snowstorm.Tx) bool {\n\treturn utils.IsSortedAndUnique(sortTxsData(txs))\n}\n<commit_msg>Added epochs to the vertex format<commit_after>\/\/ (c) 2019-2020, Ava Labs, Inc. All rights reserved.\n\/\/ See the file LICENSE for licensing terms.\n\npackage state\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"sort\"\n\n\t\"github.com\/ava-labs\/gecko\/ids\"\n\t\"github.com\/ava-labs\/gecko\/snow\/consensus\/snowstorm\"\n\t\"github.com\/ava-labs\/gecko\/snow\/engine\/avalanche\/vertex\"\n\t\"github.com\/ava-labs\/gecko\/utils\"\n\t\"github.com\/ava-labs\/gecko\/utils\/hashing\"\n\t\"github.com\/ava-labs\/gecko\/utils\/wrappers\"\n)\n\n\/\/ maxSize is the maximum allowed vertex size. It is necessary to deter DoS.\nconst maxSize = 1 << 20\n\nvar (\n\terrBadCodec       = errors.New(\"invalid codec\")\n\terrBadEpoch       = errors.New(\"invalid epoch\")\n\terrExtraSpace     = errors.New(\"trailing buffer space\")\n\terrInvalidParents = errors.New(\"vertex contains non-sorted or duplicated parentIDs\")\n\terrInvalidTxs     = errors.New(\"vertex contains non-sorted or duplicated transactions\")\n\terrNoTxs          = errors.New(\"vertex contains no transactions\")\n)\n\ntype innerVertex struct {\n\tid ids.ID\n\n\tchainID ids.ID\n\theight  uint64\n\n\tparentIDs []ids.ID\n\ttxs       []snowstorm.Tx\n\n\tbytes []byte\n}\n\nfunc (vtx *innerVertex) ID() ids.ID    { return vtx.id }\nfunc (vtx *innerVertex) Bytes() []byte { return vtx.bytes }\n\nfunc (vtx *innerVertex) Verify() error {\n\tswitch {\n\tcase !ids.IsSortedAndUniqueIDs(vtx.parentIDs):\n\t\treturn errInvalidParents\n\tcase len(vtx.txs) == 0:\n\t\treturn errNoTxs\n\tcase !isSortedAndUniqueTxs(vtx.txs):\n\t\treturn errInvalidTxs\n\tdefault:\n\t\treturn nil\n\t}\n}\n\n\/*\n * Vertex:\n * Codec        | 04 Bytes\n * Chain        | 32 Bytes\n * Height       | 08 Bytes\n * Epoch        | 04 Bytes\n * NumParents   | 04 Bytes\n * Repeated (NumParents):\n *     ParentID | 32 bytes\n * NumTxs       | 04 Bytes\n * Repeated (NumTxs):\n *     TxSize   | 04 bytes\n *     Tx       | ?? bytes\n *\/\n\n\/\/ Marshal creates the byte representation of the vertex\nfunc (vtx *innerVertex) Marshal() ([]byte, error) {\n\tp := wrappers.Packer{MaxSize: maxSize}\n\n\tp.PackInt(uint32(CustomID))\n\tp.PackFixedBytes(vtx.chainID.Bytes())\n\tp.PackLong(vtx.height)\n\tp.PackInt(0)\n\n\tp.PackInt(uint32(len(vtx.parentIDs)))\n\tfor _, parentID := range vtx.parentIDs {\n\t\tp.PackFixedBytes(parentID.Bytes())\n\t}\n\n\tp.PackInt(uint32(len(vtx.txs)))\n\tfor _, tx := range vtx.txs {\n\t\tp.PackBytes(tx.Bytes())\n\t}\n\treturn p.Bytes, p.Err\n}\n\n\/\/ Unmarshal attempts to set the contents of this vertex to the value encoded in\n\/\/ the stream of bytes.\nfunc (vtx *innerVertex) Unmarshal(b []byte, vm vertex.DAGVM) error {\n\tp := wrappers.Packer{Bytes: b}\n\n\tif codecID := ID(p.UnpackInt()); codecID != CustomID {\n\t\tp.Add(errBadCodec)\n\t}\n\n\tchainID, _ := ids.ToID(p.UnpackFixedBytes(hashing.HashLen))\n\theight := p.UnpackLong()\n\tif epoch := p.UnpackInt(); epoch != 0 {\n\t\tp.Add(errBadEpoch)\n\t}\n\n\tparentIDs := []ids.ID(nil)\n\tfor i := p.UnpackInt(); i > 0 && !p.Errored(); i-- {\n\t\tparentID, _ := ids.ToID(p.UnpackFixedBytes(hashing.HashLen))\n\t\tparentIDs = append(parentIDs, parentID)\n\t}\n\n\ttxs := []snowstorm.Tx(nil)\n\tfor i := p.UnpackInt(); i > 0 && !p.Errored(); i-- {\n\t\ttx, err := vm.ParseTx(p.UnpackBytes())\n\t\tp.Add(err)\n\t\ttxs = append(txs, tx)\n\t}\n\n\tif p.Offset != len(b) {\n\t\tp.Add(errExtraSpace)\n\t}\n\n\tif p.Errored() {\n\t\treturn p.Err\n\t}\n\n\t*vtx = innerVertex{\n\t\tid:        ids.NewID(hashing.ComputeHash256Array(b)),\n\t\tparentIDs: parentIDs,\n\t\tchainID:   chainID,\n\t\theight:    height,\n\t\ttxs:       txs,\n\t\tbytes:     b,\n\t}\n\treturn nil\n}\n\ntype sortTxsData []snowstorm.Tx\n\nfunc (txs sortTxsData) Less(i, j int) bool {\n\treturn bytes.Compare(txs[i].ID().Bytes(), txs[j].ID().Bytes()) == -1\n}\nfunc (txs sortTxsData) Len() int      { return len(txs) }\nfunc (txs sortTxsData) Swap(i, j int) { txs[j], txs[i] = txs[i], txs[j] }\n\nfunc sortTxs(txs []snowstorm.Tx) { sort.Sort(sortTxsData(txs)) }\nfunc isSortedAndUniqueTxs(txs []snowstorm.Tx) bool {\n\treturn utils.IsSortedAndUnique(sortTxsData(txs))\n}\n<|endoftext|>"}
{"text":"<commit_before>package app\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/goph\/fxt\/dev\"\n\t\"github.com\/goph\/fxt\/log\"\n\t\"github.com\/goph\/fxt\/test\/nettest\"\n\t\"github.com\/goph\/nest\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"github.com\/stretchr\/testify\/require\"\n)\n\nfunc init() {\n\tdev.LoadEnvFromFile(\"..\/.env.test\")\n\tdev.LoadEnvFromFile(\"..\/.env.dist\")\n}\n\nfunc newConfig() (Config, error) {\n\tdebugPort, _ := nettest.GetFreePort()\n\n\tconfig := Config{\n\t\tEnvironment: \"test\",\n\t\tLogFormat:   \"logfmt\",\n\t\tDebugAddr:   fmt.Sprintf(\"127.0.0.1:%d\", debugPort),\n\t}\n\n\tconfigurator := nest.NewConfigurator()\n\tconfigurator.SetName(FriendlyServiceName)\n\tconfigurator.SetArgs([]string{})\n\n\terr := configurator.Load(&config)\n\n\treturn config, err\n}\n\nfunc TestConfig(t *testing.T) {\n\tos.Clearenv()\n\tdefer func() {\n\t\tos.Clearenv()\n\t\tdev.LoadEnvFromFile(\"..\/.env.test\")\n\t\tdev.LoadEnvFromFile(\"..\/.env.dist\")\n\t}()\n\n\tenv := map[string]string{\n\t\t\"ENVIRONMENT\": \"test\",\n\t\t\"DEBUG\":       \"false\",\n\t\t\"LOG_FORMAT\":  \"json\",\n\t}\n\n\tfor key, value := range env {\n\t\tos.Setenv(key, value)\n\t}\n\n\texpected := Config{\n\t\tEnvironment:     \"test\",\n\t\tDebug:           false,\n\t\tLogFormat:       log.JsonFormat.String(),\n\t\tDebugAddr:       \":10000\",\n\t\tShutdownTimeout: 15 * time.Second,\n\t}\n\tactual := Config{}\n\n\tconfigurator := nest.NewConfigurator()\n\tconfigurator.SetName(FriendlyServiceName)\n\tconfigurator.SetArgs([]string{})\n\n\terr := configurator.Load(&actual)\n\trequire.NoError(t, err)\n\tassert.Equal(t, expected, actual)\n}\n<commit_msg>Improve config tests<commit_after>package app\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/goph\/fxt\/dev\"\n\t\"github.com\/goph\/fxt\/log\"\n\t\"github.com\/goph\/fxt\/test\/nettest\"\n\t\"github.com\/goph\/nest\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"github.com\/stretchr\/testify\/require\"\n)\n\nfunc init() {\n\tdev.LoadEnvFromFile(\"..\/.env.test\")\n\tdev.LoadEnvFromFile(\"..\/.env.dist\")\n}\n\nfunc newConfig() (Config, error) {\n\tdebugPort, _ := nettest.GetFreePort()\n\n\tconfig := Config{\n\t\tEnvironment: \"test\",\n\t\tLogFormat:   \"logfmt\",\n\t\tDebugAddr:   fmt.Sprintf(\"127.0.0.1:%d\", debugPort),\n\t}\n\n\tconfigurator := nest.NewConfigurator()\n\tconfigurator.SetName(FriendlyServiceName)\n\tconfigurator.SetArgs([]string{})\n\n\terr := configurator.Load(&config)\n\n\treturn config, err\n}\n\nfunc TestConfig(t *testing.T) {\n\tdefer func() {\n\t\tos.Clearenv()\n\t\tdev.LoadEnvFromFile(\"..\/.env.test\")\n\t\tdev.LoadEnvFromFile(\"..\/.env.dist\")\n\t}()\n\n\ttests := map[string]struct {\n\t\tenv      map[string]string\n\t\targs     []string\n\t\tactual   Config\n\t\texpected Config\n\t}{\n\t\t\"full config\": {\n\t\t\tmap[string]string{\n\t\t\t\t\"ENVIRONMENT\": \"test\",\n\t\t\t\t\"DEBUG\":       \"false\",\n\t\t\t\t\"LOG_FORMAT\":  \"logfmt\",\n\t\t\t},\n\t\t\t[]string{\"service\", \"--debug-addr\", \":10001\", \"--shutdown-timeout\", \"10s\"},\n\t\t\tConfig{},\n\t\t\tConfig{\n\t\t\t\tEnvironment:     \"test\",\n\t\t\t\tDebug:           false,\n\t\t\t\tLogFormat:       log.LogfmtFormat.String(),\n\t\t\t\tDebugAddr:       \":10001\",\n\t\t\t\tShutdownTimeout: 10 * time.Second,\n\t\t\t},\n\t\t},\n\t\t\"defaults\": {\n\t\t\tmap[string]string{},\n\t\t\t[]string{},\n\t\t\tConfig{},\n\t\t\tConfig{\n\t\t\t\tEnvironment:     \"production\",\n\t\t\t\tDebug:           false,\n\t\t\t\tLogFormat:       log.JsonFormat.String(),\n\t\t\t\tDebugAddr:       \":10000\",\n\t\t\t\tShutdownTimeout: 15 * time.Second,\n\t\t\t},\n\t\t},\n\t}\n\n\tfor name, test := range tests {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tos.Clearenv()\n\n\t\t\tfor key, value := range test.env {\n\t\t\t\tos.Setenv(key, value)\n\t\t\t}\n\n\t\t\tconfigurator := nest.NewConfigurator()\n\t\t\tconfigurator.SetName(FriendlyServiceName)\n\t\t\tconfigurator.SetArgs(test.args)\n\n\t\t\terr := configurator.Load(&test.actual)\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.Equal(t, test.expected, test.actual)\n\t\t})\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\tmm \"github.com\/mattermost\/platform\/model\"\n)\n\n\/*\nmain\nUsage: go run main.go -u <username> -p <password> <server-url> [team-name]\nAuthenticates your login information, then gives you your AuthToken.\nIf the team name is unentered or invalid main shows valid team names.\n*\/\nfunc main() {\n\tusername := flag.String(\"u\", \"\", \"Username\")\n\tpassword := flag.String(\"p\", \"\", \"Password\")\n\tflag.Parse()\n\turl := flag.Arg(0)\n\tteamName := flag.Arg(1)\n\tclient := mm.NewClient(url)\n\t_, err := client.Login(*username, *password)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tfmt.Println(\"Auth successful! Token: \", client.AuthToken)\n\n\t\/\/Gathers all availible teams in a map,\n\tteamListResult, teamListAppError := client.GetAllTeamListings()\n\tteamMap := teamListResult.Data.(map[string]*mm.Team)\n\tif teamListAppError != nil {\n\t\tfmt.Println(teamListAppError)\n\t\treturn\n\t}\n\t\/\/Validates input team name\n\tteamObjMap, teamError := client.GetTeamByName(teamName)\n\tif teamError != nil {\n\t\tfmt.Println(teamError)\n\t\treturn\n\t}\n\t\/\/Prints availible teams\n\tfmt.Println(\"teams:\")\n\tfor _, value := range teamMap {\n\t\tfmt.Println(\"\\t\", value.Name)\n\t}\n\t\/\/Creates team map that can be accessed without string key, then assigns team ID\n\tlocalTeamSlice := make([]*mm.Team, len(teamMap))\n\ti := 0\n\tfor _, value := range teamMap {\n\t\tlocalTeamSlice[i] = value\n\t\ti++\n\t}\n\tclient.SetTeamId(localTeamSlice[0].Id)\n\t\/\/Gather map of channels availible\n\tchannelResult, channelErr := client.GetChannels(teamObjMap.Etag)\n\tif channelErr != nil {\n\t\tfmt.Println(\"Channel Error\")\n\t\tfmt.Println(channeslErr)\n\t\treturn\n\t}\n\t\/\/List availible channels (direct messages appear as address string, still in progress)\n\tchannelSlice := channelResult.Data.(*mm.ChannelList)\n\tfmt.Print(\"\\nChannels:\\n\")\n\tindex := 0\n\tfor _, channel := range *channelSlice {\n\t\tfmt.Print(\"\\t\", index, \": \")\n\t\tfmt.Println(channel.Name)\n\t\tindex++\n\t}\n\n}\n<commit_msg>Made some changes including displaying index with chennel list. Fixed a bug<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\tmm \"github.com\/mattermost\/platform\/model\"\n)\n\n\/*\nmain\nUsage: go run main.go -u <username> -p <password> <server-url> [team-name]\nAuthenticates your login information, then gives you your AuthToken.\nIf the team name is unentered or invalid main shows valid team names.\n*\/\nfunc main() {\n\tusername := flag.String(\"u\", \"\", \"Username\")\n\tpassword := flag.String(\"p\", \"\", \"Password\")\n\tflag.Parse()\n\turl := flag.Arg(0)\n\tteamName := flag.Arg(1)\n\tclient := mm.NewClient(url)\n\t_, err := client.Login(*username, *password)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tfmt.Println(\"Auth successful! Token: \", client.AuthToken)\n\n\t\/\/Gathers all availible teams in a map,\n\tteamListResult, teamListAppError := client.GetAllTeamListings()\n\tteamMap := teamListResult.Data.(map[string]*mm.Team)\n\tif teamListAppError != nil {\n\t\tfmt.Println(teamListAppError)\n\t\treturn\n\t}\n\t\/\/Validates input team name\n\tteamObjMap, teamError := client.GetTeamByName(teamName)\n\tif teamError != nil {\n\t\tfmt.Println(teamError)\n\t\treturn\n\t}\n\t\/\/Prints availible teams\n\tfmt.Println(\"teams:\")\n\tfor _, value := range teamMap {\n\t\tfmt.Println(\"\\t\", value.Name)\n\t}\n\t\/\/Creates team map that can be accessed without string key, then assigns team ID\n\tlocalTeamSlice := make([]*mm.Team, len(teamMap))\n\ti := 0\n\tfor _, value := range teamMap {\n\t\tlocalTeamSlice[i] = value\n\t\ti++\n\t}\n\tclient.SetTeamId(localTeamSlice[0].Id)\n\t\/\/Gather map of channels availible\n\tchannelResult, channelErr := client.GetChannels(teamObjMap.Etag)\n\tif channelErr != nil {\n\t\tfmt.Println(\"Channel Error\")\n\t\tfmt.Println(channelErr)\n\t\treturn\n\t}\n\t\/\/List availible channels (direct messages appear as address string, still in progress)\n\tchannelSlice := channelResult.Data.(*mm.ChannelList)\n\tfmt.Print(\"\\nChannels:\\n\")\n\tindex := 0\n\tfor _, channel := range *channelSlice {\n\t\tfmt.Print(\"\\t\", index, \": \")\n\t\tfmt.Println(channel.DisplayName)\n\t\tindex++\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package pcf_pipelines_test\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\n\tyaml \"gopkg.in\/yaml.v2\"\n\n\t\"github.com\/concourse\/atc\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\nvar placeholderRegexp = regexp.MustCompile(\"{{([a-zA-Z0-9-_]+)}}\")\n\nvar _ = Describe(\"pcf-pipelines\", func() {\n\tcwd, err := os.Getwd()\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to get working dir: %s\", err)\n\t}\n\n\troot := filepath.Dir(cwd)\n\tbaseDir := filepath.Base(cwd)\n\n\tvar pipelinePaths []string\n\terr = filepath.Walk(cwd, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif filepath.Base(path) == \"pipeline.yml\" {\n\t\t\trelPipelinePath, err := filepath.Rel(cwd, path)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tpipelinePaths = append(pipelinePaths, relPipelinePath)\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to walk: %s\", err)\n\t}\n\n\tfor _, path := range pipelinePaths {\n\t\tpipelinePath := path\n\n\t\tContext(fmt.Sprintf(\"pipeline at %s\", pipelinePath), func() {\n\t\t\tvar configBytes []byte\n\n\t\t\tBeforeEach(func() {\n\t\t\t\tvar err error\n\t\t\t\tconfigBytes, err = ioutil.ReadFile(pipelinePath)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\t})\n\n\t\t\tIt(\"specifies only valid job names in any `passed` definitions in the buildplan\", func() {\n\t\t\t\tvar config atc.Config\n\t\t\t\tcleanConfigBytes := placeholderRegexp.ReplaceAll(configBytes, []byte(\"true\"))\n\t\t\t\terr := yaml.Unmarshal(cleanConfigBytes, &config)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tfor _, job := range config.Jobs {\n\t\t\t\t\tfor _, plan := range job.Plans() {\n\t\t\t\t\t\tcheckValidJobsList(config.Jobs, plan.Passed, job.Name)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\n\t\t\tIt(\"specifies all and only the params that the pipeline's tasks expect\", func() {\n\t\t\t\tvar config atc.Config\n\t\t\t\tcleanConfigBytes := placeholderRegexp.ReplaceAll(configBytes, []byte(\"true\"))\n\t\t\t\terr := yaml.Unmarshal(cleanConfigBytes, &config)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tfor _, job := range config.Jobs {\n\t\t\t\t\tfor _, task := range allTasksInPlan(&job.Plan) {\n\t\t\t\t\t\tfailMessage := fmt.Sprintf(\"Found error in the following pipeline:\\n    %s\\n\\nin the following task's params:\\n    %s\/%s\\n\", pipelinePath, job.Name, task.Name())\n\n\t\t\t\t\t\tvar configParams []string\n\t\t\t\t\t\tfor k := range task.Params {\n\t\t\t\t\t\t\tconfigParams = append(configParams, k)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif strings.HasPrefix(task.TaskConfigPath, baseDir) {\n\t\t\t\t\t\t\ttaskPath := strings.TrimPrefix(task.TaskConfigPath, baseDir+\"\/\")\n\t\t\t\t\t\t\trelpath, err := filepath.Rel(cwd, filepath.Join(cwd, taskPath))\n\t\t\t\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\t\t\t\tbs, err := ioutil.ReadFile(relpath)\n\t\t\t\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\t\t\t\ttaskConfig := atc.TaskConfig{}\n\t\t\t\t\t\t\terr = yaml.Unmarshal(bs, &taskConfig)\n\t\t\t\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\t\t\t\tvar taskParams []string\n\t\t\t\t\t\t\tfor k := range taskConfig.Params {\n\t\t\t\t\t\t\t\ttaskParams = append(taskParams, k)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tassertUnorderedEqual(taskParams, configParams, failMessage)\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\tIt(\"has a params file with all and only the params that the pipeline specifies\", func() {\n\t\t\t\tparamsPath := filepath.Join(filepath.Dir(pipelinePath), \"params.yml\")\n\t\t\t\t_, err := os.Lstat(paramsPath)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tbs, err := ioutil.ReadFile(paramsPath)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tparamsMap := map[string]interface{}{}\n\t\t\t\terr = yaml.Unmarshal(bs, paramsMap)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tvar params []string\n\t\t\t\tfor k := range paramsMap {\n\t\t\t\t\tparams = append(params, k)\n\t\t\t\t}\n\n\t\t\t\tmatches := placeholderRegexp.FindAllStringSubmatch(string(configBytes), -1)\n\n\t\t\t\tuniqueMatches := map[string]struct{}{}\n\t\t\t\tfor _, match := range matches {\n\t\t\t\t\tuniqueMatches[match[1]] = struct{}{}\n\t\t\t\t}\n\n\t\t\t\tvar placeholders []string\n\t\t\t\tfor match := range uniqueMatches {\n\t\t\t\t\tplaceholders = append(placeholders, match)\n\t\t\t\t}\n\n\t\t\t\tfailMessage := fmt.Sprintf(`\nFound error with the following pipeline:\n%s\n\nin the following params template:\n%s\n`, pipelinePath, paramsPath)\n\n\t\t\t\tassertUnorderedEqual(placeholders, params, failMessage)\n\t\t\t})\n\n\t\t\tIt(\"provides all of the resources that the tasks it defines require\", func() {\n\t\t\t\tvar config atc.Config\n\t\t\t\tcleanConfigBytes := placeholderRegexp.ReplaceAll(configBytes, []byte(\"true\"))\n\t\t\t\terr := yaml.Unmarshal(cleanConfigBytes, &config)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tfor _, job := range config.Jobs {\n\t\t\t\t\ttasks := allTasksInPlan(&job.Plan)\n\t\t\t\t\tresources := availableResources(&job.Plan)\n\n\t\t\t\t\tfor i, task := range tasks {\n\t\t\t\t\t\tif !strings.HasPrefix(task.TaskConfigPath, \"pcf-pipelines\") {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tvar inputs []atc.TaskInputConfig\n\t\t\t\t\t\tif task.TaskConfig != nil {\n\t\t\t\t\t\t\tinputs = task.TaskConfig.Inputs\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tinputs = taskInputConfigs(filepath.Join(root, task.TaskConfigPath))\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor k := range task.InputMapping {\n\t\t\t\t\t\t\tvar validInputMapping bool\n\t\t\t\t\t\t\tfor _, input := range inputs {\n\t\t\t\t\t\t\t\tif input.Name == k {\n\t\t\t\t\t\t\t\t\tvalidInputMapping = true\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif !validInputMapping {\n\t\t\t\t\t\t\t\tFail(fmt.Sprintf(\"could not find input mapping for '%s' in '%s'\\n\", k, inputs))\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor j := 0; j < i; j++ {\n\t\t\t\t\t\t\tupstreamTask := tasks[j]\n\n\t\t\t\t\t\t\tif upstreamTask.TaskConfig != nil {\n\t\t\t\t\t\t\t\tfor _, output := range upstreamTask.TaskConfig.Outputs {\n\t\t\t\t\t\t\t\t\tresources = append(resources, output.Name)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif upstreamTask.TaskConfigPath != \"\" {\n\t\t\t\t\t\t\t\tvar upstreamTaskConfig atc.TaskConfig\n\t\t\t\t\t\t\t\tbs, err := ioutil.ReadFile(filepath.Join(root, upstreamTask.TaskConfigPath))\n\t\t\t\t\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\t\t\t\t\terr = yaml.Unmarshal(bs, &upstreamTaskConfig)\n\t\t\t\t\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\t\t\t\t\tfor _, output := range upstreamTaskConfig.Outputs {\n\t\t\t\t\t\t\t\t\tresources = append(resources, output.Name)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tfor _, v := range upstreamTask.OutputMapping {\n\t\t\t\t\t\t\t\tresources = append(resources, v)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\tOUTER:\n\t\t\t\t\t\tfor _, input := range inputs {\n\t\t\t\t\t\t\tfor _, actual := range resources {\n\t\t\t\t\t\t\t\tif input.Name == actual {\n\t\t\t\t\t\t\t\t\tcontinue OUTER\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tfor k, v := range task.InputMapping {\n\t\t\t\t\t\t\t\t\tif k == input.Name && v == actual {\n\t\t\t\t\t\t\t\t\t\tcontinue OUTER\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\n\t\t\t\t\t\t\tFail(fmt.Sprintf(\"did not find matching get, put, output or input_mapping of '%s', which is required by task '%s'\", input.Name, task.Name()))\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t})\n\t}\n})\n\nfunc checkValidJobsList(jobs atc.JobConfigs, jobNames []string, location string) {\n\tfor _, jobName := range jobNames {\n\t\t_, exists := jobs.Lookup(jobName)\n\t\tExpect(exists).Should(BeTrue(), fmt.Sprintf(\"%s is not a valid job defined in %s\", jobName, location))\n\t}\n}\n\nfunc allTasksInPlan(seq *atc.PlanSequence) []atc.PlanConfig {\n\tvar tasks []atc.PlanConfig\n\n\tfor _, planConfig := range *seq {\n\t\tif planConfig.Aggregate != nil {\n\t\t\ttasks = append(tasks, allTasksInPlan(planConfig.Aggregate)...)\n\t\t}\n\t\tif planConfig.Do != nil {\n\t\t\ttasks = append(tasks, allTasksInPlan(planConfig.Do)...)\n\t\t}\n\t\tif planConfig.Task != \"\" {\n\t\t\ttasks = append(tasks, planConfig)\n\t\t}\n\t}\n\n\treturn tasks\n}\n\nfunc availableResources(seq *atc.PlanSequence) []string {\n\tvar resources []string\n\n\tfor _, planConfig := range *seq {\n\t\tif planConfig.Aggregate != nil {\n\t\t\tresources = append(resources, availableResources(planConfig.Aggregate)...)\n\t\t}\n\n\t\tif planConfig.Do != nil {\n\t\t\tresources = append(resources, availableResources(planConfig.Do)...)\n\t\t}\n\n\t\tif planConfig.Get != \"\" {\n\t\t\tresources = append(resources, planConfig.Get)\n\t\t}\n\n\t\tif planConfig.Put != \"\" {\n\t\t\tresources = append(resources, planConfig.Put)\n\t\t}\n\t}\n\n\treturn resources\n}\n\nfunc assertUnorderedEqual(left, right []string, failMessage string) {\n\tfor _, l := range left {\n\t\tExpect(right).To(ContainElement(l), failMessage)\n\t}\n\n\tfor _, r := range right {\n\t\tvar found bool\n\n\t\tfor _, l := range left {\n\t\t\tif r == l {\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\tExpect(right).NotTo(ContainElement(r), failMessage)\n\t\t}\n\t}\n}\n\nvar taskConfigs = map[string]*atc.TaskConfig{}\n\nfunc taskInputConfigs(path string) []atc.TaskInputConfig {\n\ttaskConfig, ok := taskConfigs[path]\n\n\tif !ok {\n\t\tbs, err := ioutil.ReadFile(path)\n\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\terr = yaml.Unmarshal(bs, &taskConfig)\n\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\ttaskConfigs[path] = taskConfig\n\t}\n\n\treturn taskConfig.Inputs\n}\n<commit_msg>Update placeholderRegexp to support parens<commit_after>package pcf_pipelines_test\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\n\tyaml \"gopkg.in\/yaml.v2\"\n\n\t\"github.com\/concourse\/atc\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\nvar oldPlaceholderRegexp = regexp.MustCompile(\"{{([a-zA-Z0-9-_]+)}}\")\nvar placeholderRegexp = regexp.MustCompile(\"[({]{2}([a-zA-Z0-9-_]+)(?:)[)}]{2}\")\n\nvar _ = Describe(\"pcf-pipelines\", func() {\n\tcwd, err := os.Getwd()\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to get working dir: %s\", err)\n\t}\n\n\troot := filepath.Dir(cwd)\n\tbaseDir := filepath.Base(cwd)\n\n\tvar pipelinePaths []string\n\terr = filepath.Walk(cwd, func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif filepath.Base(path) == \"pipeline.yml\" {\n\t\t\trelPipelinePath, err := filepath.Rel(cwd, path)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tpipelinePaths = append(pipelinePaths, relPipelinePath)\n\t\t}\n\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to walk: %s\", err)\n\t}\n\n\tfor _, path := range pipelinePaths {\n\t\tpipelinePath := path\n\n\t\tContext(fmt.Sprintf(\"pipeline at %s\", pipelinePath), func() {\n\t\t\tvar configBytes []byte\n\n\t\t\tBeforeEach(func() {\n\t\t\t\tvar err error\n\t\t\t\tconfigBytes, err = ioutil.ReadFile(pipelinePath)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\t})\n\n\t\t\tIt(\"specifies only valid job names in any `passed` definitions in the buildplan\", func() {\n\t\t\t\tvar config atc.Config\n\t\t\t\tcleanConfigBytes := oldPlaceholderRegexp.ReplaceAll(configBytes, []byte(\"true\"))\n\t\t\t\terr := yaml.Unmarshal(cleanConfigBytes, &config)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tfor _, job := range config.Jobs {\n\t\t\t\t\tfor _, plan := range job.Plans() {\n\t\t\t\t\t\tcheckValidJobsList(config.Jobs, plan.Passed, job.Name)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\n\t\t\tIt(\"specifies all and only the params that the pipeline's tasks expect\", func() {\n\t\t\t\tvar config atc.Config\n\t\t\t\tcleanConfigBytes := oldPlaceholderRegexp.ReplaceAll(configBytes, []byte(\"true\"))\n\t\t\t\terr := yaml.Unmarshal(cleanConfigBytes, &config)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tfor _, job := range config.Jobs {\n\t\t\t\t\tfor _, task := range allTasksInPlan(&job.Plan) {\n\t\t\t\t\t\tfailMessage := fmt.Sprintf(\"Found error in the following pipeline:\\n    %s\\n\\nin the following task's params:\\n    %s\/%s\\n\", pipelinePath, job.Name, task.Name())\n\n\t\t\t\t\t\tvar configParams []string\n\t\t\t\t\t\tfor k := range task.Params {\n\t\t\t\t\t\t\tconfigParams = append(configParams, k)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif strings.HasPrefix(task.TaskConfigPath, baseDir) {\n\t\t\t\t\t\t\ttaskPath := strings.TrimPrefix(task.TaskConfigPath, baseDir+\"\/\")\n\t\t\t\t\t\t\trelpath, err := filepath.Rel(cwd, filepath.Join(cwd, taskPath))\n\t\t\t\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\t\t\t\tbs, err := ioutil.ReadFile(relpath)\n\t\t\t\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\t\t\t\ttaskConfig := atc.TaskConfig{}\n\t\t\t\t\t\t\terr = yaml.Unmarshal(bs, &taskConfig)\n\t\t\t\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\t\t\t\tvar taskParams []string\n\t\t\t\t\t\t\tfor k := range taskConfig.Params {\n\t\t\t\t\t\t\t\ttaskParams = append(taskParams, k)\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tassertUnorderedEqual(taskParams, configParams, failMessage)\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\tIt(\"has a params file with all and only the params that the pipeline specifies\", func() {\n\t\t\t\tparamsPath := filepath.Join(filepath.Dir(pipelinePath), \"params.yml\")\n\t\t\t\t_, err := os.Lstat(paramsPath)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tbs, err := ioutil.ReadFile(paramsPath)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tparamsMap := map[string]interface{}{}\n\t\t\t\terr = yaml.Unmarshal(bs, paramsMap)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tvar params []string\n\t\t\t\tfor k := range paramsMap {\n\t\t\t\t\tparams = append(params, k)\n\t\t\t\t}\n\n\t\t\t\tmatches := placeholderRegexp.FindAllStringSubmatch(string(configBytes), -1)\n\n\t\t\t\tuniqueMatches := map[string]struct{}{}\n\t\t\t\tfor _, match := range matches {\n\t\t\t\t\tuniqueMatches[match[1]] = struct{}{}\n\t\t\t\t}\n\n\t\t\t\tvar placeholders []string\n\t\t\t\tfor match := range uniqueMatches {\n\t\t\t\t\tplaceholders = append(placeholders, match)\n\t\t\t\t}\n\n\t\t\t\tfailMessage := fmt.Sprintf(`\nFound error with the following pipeline:\n%s\n\nin the following params template:\n%s\n`, pipelinePath, paramsPath)\n\n\t\t\t\tassertUnorderedEqual(placeholders, params, failMessage)\n\t\t\t})\n\n\t\t\tIt(\"provides all of the resources that the tasks it defines require\", func() {\n\t\t\t\tvar config atc.Config\n\t\t\t\tcleanConfigBytes := placeholderRegexp.ReplaceAll(configBytes, []byte(\"true\"))\n\t\t\t\terr := yaml.Unmarshal(cleanConfigBytes, &config)\n\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\tfor _, job := range config.Jobs {\n\t\t\t\t\ttasks := allTasksInPlan(&job.Plan)\n\t\t\t\t\tresources := availableResources(&job.Plan)\n\n\t\t\t\t\tfor i, task := range tasks {\n\t\t\t\t\t\tif !strings.HasPrefix(task.TaskConfigPath, \"pcf-pipelines\") {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tvar inputs []atc.TaskInputConfig\n\t\t\t\t\t\tif task.TaskConfig != nil {\n\t\t\t\t\t\t\tinputs = task.TaskConfig.Inputs\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tinputs = taskInputConfigs(filepath.Join(root, task.TaskConfigPath))\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor k := range task.InputMapping {\n\t\t\t\t\t\t\tvar validInputMapping bool\n\t\t\t\t\t\t\tfor _, input := range inputs {\n\t\t\t\t\t\t\t\tif input.Name == k {\n\t\t\t\t\t\t\t\t\tvalidInputMapping = true\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif !validInputMapping {\n\t\t\t\t\t\t\t\tFail(fmt.Sprintf(\"could not find input mapping for '%s' in '%s'\\n\", k, inputs))\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tfor j := 0; j < i; j++ {\n\t\t\t\t\t\t\tupstreamTask := tasks[j]\n\n\t\t\t\t\t\t\tif upstreamTask.TaskConfig != nil {\n\t\t\t\t\t\t\t\tfor _, output := range upstreamTask.TaskConfig.Outputs {\n\t\t\t\t\t\t\t\t\tresources = append(resources, output.Name)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif upstreamTask.TaskConfigPath != \"\" {\n\t\t\t\t\t\t\t\tvar upstreamTaskConfig atc.TaskConfig\n\t\t\t\t\t\t\t\tbs, err := ioutil.ReadFile(filepath.Join(root, upstreamTask.TaskConfigPath))\n\t\t\t\t\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\t\t\t\t\terr = yaml.Unmarshal(bs, &upstreamTaskConfig)\n\t\t\t\t\t\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\t\t\t\t\t\tfor _, output := range upstreamTaskConfig.Outputs {\n\t\t\t\t\t\t\t\t\tresources = append(resources, output.Name)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tfor _, v := range upstreamTask.OutputMapping {\n\t\t\t\t\t\t\t\tresources = append(resources, v)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\tOUTER:\n\t\t\t\t\t\tfor _, input := range inputs {\n\t\t\t\t\t\t\tfor _, actual := range resources {\n\t\t\t\t\t\t\t\tif input.Name == actual {\n\t\t\t\t\t\t\t\t\tcontinue OUTER\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tfor k, v := range task.InputMapping {\n\t\t\t\t\t\t\t\t\tif k == input.Name && v == actual {\n\t\t\t\t\t\t\t\t\t\tcontinue OUTER\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\n\t\t\t\t\t\t\tFail(fmt.Sprintf(\"did not find matching get, put, output or input_mapping of '%s', which is required by task '%s'\", input.Name, task.Name()))\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t})\n\t\t})\n\t}\n})\n\nfunc checkValidJobsList(jobs atc.JobConfigs, jobNames []string, location string) {\n\tfor _, jobName := range jobNames {\n\t\t_, exists := jobs.Lookup(jobName)\n\t\tExpect(exists).Should(BeTrue(), fmt.Sprintf(\"%s is not a valid job defined in %s\", jobName, location))\n\t}\n}\n\nfunc allTasksInPlan(seq *atc.PlanSequence) []atc.PlanConfig {\n\tvar tasks []atc.PlanConfig\n\n\tfor _, planConfig := range *seq {\n\t\tif planConfig.Aggregate != nil {\n\t\t\ttasks = append(tasks, allTasksInPlan(planConfig.Aggregate)...)\n\t\t}\n\t\tif planConfig.Do != nil {\n\t\t\ttasks = append(tasks, allTasksInPlan(planConfig.Do)...)\n\t\t}\n\t\tif planConfig.Task != \"\" {\n\t\t\ttasks = append(tasks, planConfig)\n\t\t}\n\t}\n\n\treturn tasks\n}\n\nfunc availableResources(seq *atc.PlanSequence) []string {\n\tvar resources []string\n\n\tfor _, planConfig := range *seq {\n\t\tif planConfig.Aggregate != nil {\n\t\t\tresources = append(resources, availableResources(planConfig.Aggregate)...)\n\t\t}\n\n\t\tif planConfig.Do != nil {\n\t\t\tresources = append(resources, availableResources(planConfig.Do)...)\n\t\t}\n\n\t\tif planConfig.Get != \"\" {\n\t\t\tresources = append(resources, planConfig.Get)\n\t\t}\n\n\t\tif planConfig.Put != \"\" {\n\t\t\tresources = append(resources, planConfig.Put)\n\t\t}\n\t}\n\n\treturn resources\n}\n\nfunc assertUnorderedEqual(left, right []string, failMessage string) {\n\tfor _, l := range left {\n\t\tExpect(right).To(ContainElement(l), failMessage)\n\t}\n\n\tfor _, r := range right {\n\t\tvar found bool\n\n\t\tfor _, l := range left {\n\t\t\tif r == l {\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\tExpect(right).NotTo(ContainElement(r), failMessage)\n\t\t}\n\t}\n}\n\nvar taskConfigs = map[string]*atc.TaskConfig{}\n\nfunc taskInputConfigs(path string) []atc.TaskInputConfig {\n\ttaskConfig, ok := taskConfigs[path]\n\n\tif !ok {\n\t\tbs, err := ioutil.ReadFile(path)\n\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\terr = yaml.Unmarshal(bs, &taskConfig)\n\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\ttaskConfigs[path] = taskConfig\n\t}\n\n\treturn taskConfig.Inputs\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t. \"github.com\/frezadev\/hdc\/hive\"\n\t\/\/ . \"github.com\/eaciit\/hdc\/hive\"\n\t\"github.com\/pkg\/profile\"\n\t\"log\"\n)\n\ntype Students struct {\n\tName    string\n\tAge     int\n\tPhone   string\n\tAddress string\n}\n\nfunc fatalCheck(what string, e error) {\n\tif e != nil {\n\t\tlog.Fatalf(\"%s: %s\", what, e.Error())\n\t}\n}\n\nfunc main() {\n\tdefer profile.Start(profile.CPUProfile, profile.MemProfile, profile.BlockProfile).Stop()\n\n\th := HiveConfig(\"192.168.0.223:10000\", \"default\", \"hdfs\", \"\", \"\")\n\terr := h.Conn.Open()\n\tfatalCheck(\"Populate\", err)\n\n\tvar student Students\n\n\ttotalWorker := 10\n\tretVal, err := h.LoadFileWithWorker(\"\/home\/developer\/contoh.txt\", \"students\", \"csv\", \"dd\/MM\/yyyy\", &student, totalWorker)\n\n\tif err != nil {\n\t\tfatalCheck(\"Populate\", err)\n\t}\n\n\th.Conn.Close()\n\tlog.Printf(\"retVal: \\n%v\\n\", retVal)\n}\n<commit_msg>change import part<commit_after>package main\n\nimport (\n\t\/\/ . \"github.com\/frezadev\/hdc\/hive\"\n\t. \"github.com\/eaciit\/hdc\/hive\"\n\t\"github.com\/pkg\/profile\"\n\t\"log\"\n)\n\ntype Students struct {\n\tName    string\n\tAge     int\n\tPhone   string\n\tAddress string\n}\n\nfunc fatalCheck(what string, e error) {\n\tif e != nil {\n\t\tlog.Fatalf(\"%s: %s\", what, e.Error())\n\t}\n}\n\nfunc main() {\n\tdefer profile.Start(profile.CPUProfile, profile.MemProfile, profile.BlockProfile).Stop()\n\n\th := HiveConfig(\"192.168.0.223:10000\", \"default\", \"hdfs\", \"\", \"\")\n\terr := h.Conn.Open()\n\tfatalCheck(\"Populate\", err)\n\n\tvar student Students\n\n\ttotalWorker := 10\n\tretVal, err := h.LoadFileWithWorker(\"\/home\/developer\/contoh.txt\", \"students\", \"csv\", \"dd\/MM\/yyyy\", &student, totalWorker)\n\n\tif err != nil {\n\t\tfatalCheck(\"Populate\", err)\n\t}\n\n\th.Conn.Close()\n\tlog.Printf(\"retVal: \\n%v\\n\", retVal)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016-2021 The Libsacloud Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage certificateauthority\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/sacloud\/libsacloud\/v2\/sacloud\"\n\t\"github.com\/sacloud\/libsacloud\/v2\/sacloud\/testutil\"\n\t\"github.com\/sacloud\/libsacloud\/v2\/sacloud\/types\"\n)\n\nfunc TestCertificateAuthorityService_CRUD(t *testing.T) {\n\tif !testutil.IsAccTest() {\n\t\tt.Skip(\"TestCertificateAuthorityService_CRUD only exec when running an Acceptance Test\")\n\t}\n\n\tsvc := New(testutil.SingletonAPICaller())\n\tname := testutil.ResourceName(\"ca\")\n\n\ttestutil.RunCRUD(t, &testutil.CRUDTestCase{\n\t\tParallel:           true,\n\t\tPreCheck:           nil,\n\t\tSetupAPICallerFunc: testutil.SingletonAPICaller,\n\t\tSetup:              nil,\n\t\tCreate: &testutil.CRUDTestFunc{\n\t\t\tFunc: func(ctx *testutil.CRUDTestContext, _ sacloud.APICaller) (interface{}, error) {\n\t\t\t\treturn svc.Create(&CreateRequest{\n\t\t\t\t\tName:             name,\n\t\t\t\t\tDescription:      \"test\",\n\t\t\t\t\tTags:             types.Tags{\"tag1\", \"tag2\"},\n\t\t\t\t\tCountry:          \"JP\",\n\t\t\t\t\tOrganization:     \"usacloud\",\n\t\t\t\t\tOrganizationUnit: []string{\"ou1\",\"ou2\"},\n\t\t\t\t\tCommonName:       \"www.usacloud.jp\",\n\t\t\t\t\tNotAfter:         time.Now().Add(365 * 24 * time.Hour),\n\t\t\t\t\tClients:          []*ClientCert{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tCountry:                   \"JP\",\n\t\t\t\t\t\t\tOrganization:              \"usacloud\",\n\t\t\t\t\t\t\tCommonName:                \"client.usacloud.jp\",\n\t\t\t\t\t\t\tNotAfter:                  time.Now().Add(365 * 24 * time.Hour),\n\t\t\t\t\t\t\tIssuanceMethod:            \"url\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tWaitDuration:     0,\n\t\t\t\t})\n\t\t\t},\n\t\t},\n\t\tRead: &testutil.CRUDTestFunc{\n\t\t\tFunc: func(ctx *testutil.CRUDTestContext, _ sacloud.APICaller) (interface{}, error) {\n\t\t\t\treturn svc.Read(&ReadRequest{ID: ctx.ID})\n\t\t\t},\n\t\t},\n\t\tDelete: &testutil.CRUDTestDeleteFunc{\n\t\t\tFunc: func(ctx *testutil.CRUDTestContext, _ sacloud.APICaller) error {\n\t\t\t\treturn svc.Delete(&DeleteRequest{ID: ctx.ID})\n\t\t\t},\n\t\t},\n\t})\n}\n<commit_msg>go fmt<commit_after>\/\/ Copyright 2016-2021 The Libsacloud Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage certificateauthority\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/sacloud\/libsacloud\/v2\/sacloud\"\n\t\"github.com\/sacloud\/libsacloud\/v2\/sacloud\/testutil\"\n\t\"github.com\/sacloud\/libsacloud\/v2\/sacloud\/types\"\n)\n\nfunc TestCertificateAuthorityService_CRUD(t *testing.T) {\n\tif !testutil.IsAccTest() {\n\t\tt.Skip(\"TestCertificateAuthorityService_CRUD only exec when running an Acceptance Test\")\n\t}\n\n\tsvc := New(testutil.SingletonAPICaller())\n\tname := testutil.ResourceName(\"ca\")\n\n\ttestutil.RunCRUD(t, &testutil.CRUDTestCase{\n\t\tParallel:           true,\n\t\tPreCheck:           nil,\n\t\tSetupAPICallerFunc: testutil.SingletonAPICaller,\n\t\tSetup:              nil,\n\t\tCreate: &testutil.CRUDTestFunc{\n\t\t\tFunc: func(ctx *testutil.CRUDTestContext, _ sacloud.APICaller) (interface{}, error) {\n\t\t\t\treturn svc.Create(&CreateRequest{\n\t\t\t\t\tName:             name,\n\t\t\t\t\tDescription:      \"test\",\n\t\t\t\t\tTags:             types.Tags{\"tag1\", \"tag2\"},\n\t\t\t\t\tCountry:          \"JP\",\n\t\t\t\t\tOrganization:     \"usacloud\",\n\t\t\t\t\tOrganizationUnit: []string{\"ou1\", \"ou2\"},\n\t\t\t\t\tCommonName:       \"www.usacloud.jp\",\n\t\t\t\t\tNotAfter:         time.Now().Add(365 * 24 * time.Hour),\n\t\t\t\t\tClients: []*ClientCert{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tCountry:        \"JP\",\n\t\t\t\t\t\t\tOrganization:   \"usacloud\",\n\t\t\t\t\t\t\tCommonName:     \"client.usacloud.jp\",\n\t\t\t\t\t\t\tNotAfter:       time.Now().Add(365 * 24 * time.Hour),\n\t\t\t\t\t\t\tIssuanceMethod: \"url\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tWaitDuration: 0,\n\t\t\t\t})\n\t\t\t},\n\t\t},\n\t\tRead: &testutil.CRUDTestFunc{\n\t\t\tFunc: func(ctx *testutil.CRUDTestContext, _ sacloud.APICaller) (interface{}, error) {\n\t\t\t\treturn svc.Read(&ReadRequest{ID: ctx.ID})\n\t\t\t},\n\t\t},\n\t\tDelete: &testutil.CRUDTestDeleteFunc{\n\t\t\tFunc: func(ctx *testutil.CRUDTestContext, _ sacloud.APICaller) error {\n\t\t\t\treturn svc.Delete(&DeleteRequest{ID: ctx.ID})\n\t\t\t},\n\t\t},\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n\t\"syscall\"\n\n\t\"github.com\/olekukonko\/tablewriter\"\n\t\"gopkg.in\/yaml.v2\"\n\n\t\"github.com\/lxc\/lxd\"\n\t\"github.com\/lxc\/lxd\/shared\"\n\t\"github.com\/lxc\/lxd\/shared\/api\"\n\t\"github.com\/lxc\/lxd\/shared\/i18n\"\n\t\"github.com\/lxc\/lxd\/shared\/termios\"\n)\n\ntype networkCmd struct {\n}\n\nfunc (c *networkCmd) showByDefault() bool {\n\treturn true\n}\n\nfunc (c *networkCmd) networkEditHelp() string {\n\treturn i18n.G(\n\t\t`### This is a yaml representation of the network.\n### Any line starting with a '# will be ignored.\n###\n### A network consists of a set of configuration items.\n###\n### An example would look like:\n### name: lxdbr0\n### config:\n###   ipv4.address: 10.62.42.1\/24\n###   ipv4.nat: true\n###   ipv6.address: fd00:56ad:9f7a:9800::1\/64\n###   ipv6.nat: true\n### managed: true\n### type: bridge\n###\n### Note that only the configuration can be changed.`)\n}\n\nfunc (c *networkCmd) usage() string {\n\treturn i18n.G(\n\t\t`Manage networks.\n\nlxc network list [<remote>:]                              List available networks.\nlxc network show [<remote>:]<network>                     Show details of a network.\nlxc network create [<remote>:]<network> [key=value...]    Create a network.\nlxc network get [<remote>:]<network> <key>                Get network configuration.\nlxc network set [<remote>:]<network> <key> <value>        Set network configuration.\nlxc network unset [<remote>:]<network> <key>              Unset network configuration.\nlxc network delete [<remote>:]<network>                   Delete a network.\nlxc network edit [<remote>:]<network>\n    Edit network, either by launching external editor or reading STDIN.\n    Example: lxc network edit <network> # launch editor\n             cat network.yaml | lxc network edit <network> # read from network.yaml\n\nlxc network attach [<remote>:]<network> <container> [device name]\nlxc network attach-profile [<remote>:]<network> <profile> [device name]\n\nlxc network detach [<remote>:]<network> <container> [device name]\nlxc network detach-profile [<remote>:]<network> <container> [device name]`)\n}\n\nfunc (c *networkCmd) flags() {}\n\nfunc (c *networkCmd) run(config *lxd.Config, args []string) error {\n\tif len(args) < 1 {\n\t\treturn errArgs\n\t}\n\n\tif args[0] == \"list\" {\n\t\treturn c.doNetworkList(config, args)\n\t}\n\n\tif len(args) < 2 {\n\t\treturn errArgs\n\t}\n\n\tremote, network := config.ParseRemoteAndContainer(args[1])\n\tclient, err := lxd.NewClient(config, remote)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch args[0] {\n\tcase \"attach\":\n\t\treturn c.doNetworkAttach(client, network, args[2:])\n\tcase \"attach-profile\":\n\t\treturn c.doNetworkAttachProfile(client, network, args[2:])\n\tcase \"create\":\n\t\treturn c.doNetworkCreate(client, network, args[2:])\n\tcase \"delete\":\n\t\treturn c.doNetworkDelete(client, network)\n\tcase \"detach\":\n\t\treturn c.doNetworkDetach(client, network, args[2:])\n\tcase \"detach-profile\":\n\t\treturn c.doNetworkDetachProfile(client, network, args[2:])\n\tcase \"edit\":\n\t\treturn c.doNetworkEdit(client, network)\n\tcase \"get\":\n\t\treturn c.doNetworkGet(client, network, args[2:])\n\tcase \"set\":\n\t\treturn c.doNetworkSet(client, network, args[2:])\n\tcase \"unset\":\n\t\treturn c.doNetworkSet(client, network, args[2:])\n\tcase \"show\":\n\t\treturn c.doNetworkShow(client, network)\n\tdefault:\n\t\treturn errArgs\n\t}\n}\n\nfunc (c *networkCmd) doNetworkAttach(client *lxd.Client, name string, args []string) error {\n\tif len(args) < 1 || len(args) > 2 {\n\t\treturn errArgs\n\t}\n\n\tcontainer := args[0]\n\tdevName := name\n\tif len(args) > 1 {\n\t\tdevName = args[1]\n\t}\n\n\tnetwork, err := client.NetworkGet(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnicType := \"macvlan\"\n\tif network.Type == \"bridge\" {\n\t\tnicType = \"bridged\"\n\t}\n\n\tprops := []string{fmt.Sprintf(\"nictype=%s\", nicType), fmt.Sprintf(\"parent=%s\", name)}\n\tresp, err := client.ContainerDeviceAdd(container, devName, \"nic\", props)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn client.WaitForSuccess(resp.Operation)\n}\n\nfunc (c *networkCmd) doNetworkAttachProfile(client *lxd.Client, name string, args []string) error {\n\tif len(args) < 1 || len(args) > 2 {\n\t\treturn errArgs\n\t}\n\n\tprofile := args[0]\n\tdevName := name\n\tif len(args) > 1 {\n\t\tdevName = args[1]\n\t}\n\n\tnetwork, err := client.NetworkGet(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnicType := \"macvlan\"\n\tif network.Type == \"bridge\" {\n\t\tnicType = \"bridged\"\n\t}\n\n\tprops := []string{fmt.Sprintf(\"nictype=%s\", nicType), fmt.Sprintf(\"parent=%s\", name)}\n\t_, err = client.ProfileDeviceAdd(profile, devName, \"nic\", props)\n\treturn err\n}\n\nfunc (c *networkCmd) doNetworkCreate(client *lxd.Client, name string, args []string) error {\n\tconfig := map[string]string{}\n\n\tfor i := 0; i < len(args); i++ {\n\t\tentry := strings.SplitN(args[i], \"=\", 2)\n\t\tif len(entry) < 2 {\n\t\t\treturn errArgs\n\t\t}\n\n\t\tconfig[entry[0]] = entry[1]\n\t}\n\n\terr := client.NetworkCreate(name, config)\n\tif err == nil {\n\t\tfmt.Printf(i18n.G(\"Network %s created\")+\"\\n\", name)\n\t}\n\n\treturn err\n}\n\nfunc (c *networkCmd) doNetworkDetach(client *lxd.Client, name string, args []string) error {\n\tif len(args) < 1 || len(args) > 2 {\n\t\treturn errArgs\n\t}\n\n\tcontainerName := args[0]\n\tdevName := \"\"\n\tif len(args) > 1 {\n\t\tdevName = args[1]\n\t}\n\n\tcontainer, err := client.ContainerInfo(containerName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif devName == \"\" {\n\t\tfor n, d := range container.Devices {\n\t\t\tif d[\"type\"] == \"nic\" && d[\"parent\"] == name {\n\t\t\t\tif devName != \"\" {\n\t\t\t\t\treturn fmt.Errorf(i18n.G(\"More than one device matches, specify the device name.\"))\n\t\t\t\t}\n\n\t\t\t\tdevName = n\n\t\t\t}\n\t\t}\n\t}\n\n\tif devName == \"\" {\n\t\treturn fmt.Errorf(i18n.G(\"No device found for this network\"))\n\t}\n\n\tdevice, ok := container.Devices[devName]\n\tif !ok {\n\t\treturn fmt.Errorf(i18n.G(\"The specified device doesn't exist\"))\n\t}\n\n\tif device[\"type\"] != \"nic\" || device[\"parent\"] != name {\n\t\treturn fmt.Errorf(i18n.G(\"The specified device doesn't match the network\"))\n\t}\n\n\tresp, err := client.ContainerDeviceDelete(containerName, devName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn client.WaitForSuccess(resp.Operation)\n}\n\nfunc (c *networkCmd) doNetworkDetachProfile(client *lxd.Client, name string, args []string) error {\n\tif len(args) < 1 || len(args) > 2 {\n\t\treturn errArgs\n\t}\n\n\tprofileName := args[0]\n\tdevName := \"\"\n\tif len(args) > 1 {\n\t\tdevName = args[1]\n\t}\n\n\tprofile, err := client.ProfileConfig(profileName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif devName == \"\" {\n\t\tfor n, d := range profile.Devices {\n\t\t\tif d[\"type\"] == \"nic\" && d[\"parent\"] == name {\n\t\t\t\tif devName != \"\" {\n\t\t\t\t\treturn fmt.Errorf(i18n.G(\"More than one device matches, specify the device name.\"))\n\t\t\t\t}\n\n\t\t\t\tdevName = n\n\t\t\t}\n\t\t}\n\t}\n\n\tif devName == \"\" {\n\t\treturn fmt.Errorf(i18n.G(\"No device found for this network\"))\n\t}\n\n\tdevice, ok := profile.Devices[devName]\n\tif !ok {\n\t\treturn fmt.Errorf(i18n.G(\"The specified device doesn't exist\"))\n\t}\n\n\tif device[\"type\"] != \"nic\" || device[\"parent\"] != name {\n\t\treturn fmt.Errorf(i18n.G(\"The specified device doesn't match the network\"))\n\t}\n\n\t_, err = client.ProfileDeviceDelete(profileName, devName)\n\treturn err\n}\n\nfunc (c *networkCmd) doNetworkDelete(client *lxd.Client, name string) error {\n\terr := client.NetworkDelete(name)\n\tif err == nil {\n\t\tfmt.Printf(i18n.G(\"Network %s deleted\")+\"\\n\", name)\n\t}\n\n\treturn err\n}\n\nfunc (c *networkCmd) doNetworkEdit(client *lxd.Client, name string) error {\n\t\/\/ If stdin isn't a terminal, read text from it\n\tif !termios.IsTerminal(int(syscall.Stdin)) {\n\t\tcontents, err := ioutil.ReadAll(os.Stdin)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tnewdata := api.NetworkPut{}\n\t\terr = yaml.Unmarshal(contents, &newdata)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn client.NetworkPut(name, newdata)\n\t}\n\n\t\/\/ Extract the current value\n\tnetwork, err := client.NetworkGet(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdata, err := yaml.Marshal(&network)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Spawn the editor\n\tcontent, err := shared.TextEditor(\"\", []byte(c.networkEditHelp()+\"\\n\\n\"+string(data)))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor {\n\t\t\/\/ Parse the text received from the editor\n\t\tnewdata := api.NetworkPut{}\n\t\terr = yaml.Unmarshal(content, &newdata)\n\t\tif err == nil {\n\t\t\terr = client.NetworkPut(name, newdata)\n\t\t}\n\n\t\t\/\/ Respawn the editor\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, i18n.G(\"Config parsing error: %s\")+\"\\n\", err)\n\t\t\tfmt.Println(i18n.G(\"Press enter to open the editor again\"))\n\n\t\t\t_, err := os.Stdin.Read(make([]byte, 1))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tcontent, err = shared.TextEditor(\"\", content)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n\treturn nil\n}\n\nfunc (c *networkCmd) doNetworkGet(client *lxd.Client, name string, args []string) error {\n\t\/\/ we shifted @args so so it should read \"<key>\"\n\tif len(args) != 1 {\n\t\treturn errArgs\n\t}\n\n\tresp, err := client.NetworkGet(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor k, v := range resp.Config {\n\t\tif k == args[0] {\n\t\t\tfmt.Printf(\"%s\\n\", v)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (c *networkCmd) doNetworkList(config *lxd.Config, args []string) error {\n\tvar remote string\n\tif len(args) > 1 {\n\t\tvar name string\n\t\tremote, name = config.ParseRemoteAndContainer(args[1])\n\t\tif name != \"\" {\n\t\t\treturn fmt.Errorf(i18n.G(\"Cannot provide container name to list\"))\n\t\t}\n\t} else {\n\t\tremote = config.DefaultRemote\n\t}\n\n\tclient, err := lxd.NewClient(config, remote)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnetworks, err := client.ListNetworks()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdata := [][]string{}\n\tfor _, network := range networks {\n\t\tif shared.StringInSlice(network.Type, []string{\"loopback\", \"unknown\"}) {\n\t\t\tcontinue\n\t\t}\n\n\t\tstrManaged := i18n.G(\"NO\")\n\t\tif network.Managed {\n\t\t\tstrManaged = i18n.G(\"YES\")\n\t\t}\n\n\t\tstrUsedBy := fmt.Sprintf(\"%d\", len(network.UsedBy))\n\t\tdata = append(data, []string{network.Name, network.Type, strManaged, strUsedBy})\n\t}\n\n\ttable := tablewriter.NewWriter(os.Stdout)\n\ttable.SetAutoWrapText(false)\n\ttable.SetAlignment(tablewriter.ALIGN_LEFT)\n\ttable.SetRowLine(true)\n\ttable.SetHeader([]string{\n\t\ti18n.G(\"NAME\"),\n\t\ti18n.G(\"TYPE\"),\n\t\ti18n.G(\"MANAGED\"),\n\t\ti18n.G(\"USED BY\")})\n\tsort.Sort(byName(data))\n\ttable.AppendBulk(data)\n\ttable.Render()\n\n\treturn nil\n}\n\nfunc (c *networkCmd) doNetworkSet(client *lxd.Client, name string, args []string) error {\n\t\/\/ we shifted @args so so it should read \"<key> [<value>]\"\n\tif len(args) < 1 {\n\t\treturn errArgs\n\t}\n\n\tnetwork, err := client.NetworkGet(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tkey := args[0]\n\tvar value string\n\tif len(args) < 2 {\n\t\tvalue = \"\"\n\t} else {\n\t\tvalue = args[1]\n\t}\n\n\tif !termios.IsTerminal(int(syscall.Stdin)) && value == \"-\" {\n\t\tbuf, err := ioutil.ReadAll(os.Stdin)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Can't read from stdin: %s\", err)\n\t\t}\n\t\tvalue = string(buf[:])\n\t}\n\n\tnetwork.Config[key] = value\n\n\treturn client.NetworkPut(name, network.Writable())\n}\n\nfunc (c *networkCmd) doNetworkShow(client *lxd.Client, name string) error {\n\tnetwork, err := client.NetworkGet(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdata, err := yaml.Marshal(&network)\n\tfmt.Printf(\"%s\", data)\n\n\treturn nil\n}\n<commit_msg>lxc: Better handle network modifications<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n\t\"syscall\"\n\n\t\"github.com\/olekukonko\/tablewriter\"\n\t\"gopkg.in\/yaml.v2\"\n\n\t\"github.com\/lxc\/lxd\"\n\t\"github.com\/lxc\/lxd\/shared\"\n\t\"github.com\/lxc\/lxd\/shared\/api\"\n\t\"github.com\/lxc\/lxd\/shared\/i18n\"\n\t\"github.com\/lxc\/lxd\/shared\/termios\"\n)\n\ntype networkCmd struct {\n}\n\nfunc (c *networkCmd) showByDefault() bool {\n\treturn true\n}\n\nfunc (c *networkCmd) networkEditHelp() string {\n\treturn i18n.G(\n\t\t`### This is a yaml representation of the network.\n### Any line starting with a '# will be ignored.\n###\n### A network consists of a set of configuration items.\n###\n### An example would look like:\n### name: lxdbr0\n### config:\n###   ipv4.address: 10.62.42.1\/24\n###   ipv4.nat: true\n###   ipv6.address: fd00:56ad:9f7a:9800::1\/64\n###   ipv6.nat: true\n### managed: true\n### type: bridge\n###\n### Note that only the configuration can be changed.`)\n}\n\nfunc (c *networkCmd) usage() string {\n\treturn i18n.G(\n\t\t`Manage networks.\n\nlxc network list [<remote>:]                              List available networks.\nlxc network show [<remote>:]<network>                     Show details of a network.\nlxc network create [<remote>:]<network> [key=value...]    Create a network.\nlxc network get [<remote>:]<network> <key>                Get network configuration.\nlxc network set [<remote>:]<network> <key> <value>        Set network configuration.\nlxc network unset [<remote>:]<network> <key>              Unset network configuration.\nlxc network delete [<remote>:]<network>                   Delete a network.\nlxc network edit [<remote>:]<network>\n    Edit network, either by launching external editor or reading STDIN.\n    Example: lxc network edit <network> # launch editor\n             cat network.yaml | lxc network edit <network> # read from network.yaml\n\nlxc network attach [<remote>:]<network> <container> [device name]\nlxc network attach-profile [<remote>:]<network> <profile> [device name]\n\nlxc network detach [<remote>:]<network> <container> [device name]\nlxc network detach-profile [<remote>:]<network> <container> [device name]`)\n}\n\nfunc (c *networkCmd) flags() {}\n\nfunc (c *networkCmd) run(config *lxd.Config, args []string) error {\n\tif len(args) < 1 {\n\t\treturn errArgs\n\t}\n\n\tif args[0] == \"list\" {\n\t\treturn c.doNetworkList(config, args)\n\t}\n\n\tif len(args) < 2 {\n\t\treturn errArgs\n\t}\n\n\tremote, network := config.ParseRemoteAndContainer(args[1])\n\tclient, err := lxd.NewClient(config, remote)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch args[0] {\n\tcase \"attach\":\n\t\treturn c.doNetworkAttach(client, network, args[2:])\n\tcase \"attach-profile\":\n\t\treturn c.doNetworkAttachProfile(client, network, args[2:])\n\tcase \"create\":\n\t\treturn c.doNetworkCreate(client, network, args[2:])\n\tcase \"delete\":\n\t\treturn c.doNetworkDelete(client, network)\n\tcase \"detach\":\n\t\treturn c.doNetworkDetach(client, network, args[2:])\n\tcase \"detach-profile\":\n\t\treturn c.doNetworkDetachProfile(client, network, args[2:])\n\tcase \"edit\":\n\t\treturn c.doNetworkEdit(client, network)\n\tcase \"get\":\n\t\treturn c.doNetworkGet(client, network, args[2:])\n\tcase \"set\":\n\t\treturn c.doNetworkSet(client, network, args[2:])\n\tcase \"unset\":\n\t\treturn c.doNetworkSet(client, network, args[2:])\n\tcase \"show\":\n\t\treturn c.doNetworkShow(client, network)\n\tdefault:\n\t\treturn errArgs\n\t}\n}\n\nfunc (c *networkCmd) doNetworkAttach(client *lxd.Client, name string, args []string) error {\n\tif len(args) < 1 || len(args) > 2 {\n\t\treturn errArgs\n\t}\n\n\tcontainer := args[0]\n\tdevName := name\n\tif len(args) > 1 {\n\t\tdevName = args[1]\n\t}\n\n\tnetwork, err := client.NetworkGet(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnicType := \"macvlan\"\n\tif network.Type == \"bridge\" {\n\t\tnicType = \"bridged\"\n\t}\n\n\tprops := []string{fmt.Sprintf(\"nictype=%s\", nicType), fmt.Sprintf(\"parent=%s\", name)}\n\tresp, err := client.ContainerDeviceAdd(container, devName, \"nic\", props)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn client.WaitForSuccess(resp.Operation)\n}\n\nfunc (c *networkCmd) doNetworkAttachProfile(client *lxd.Client, name string, args []string) error {\n\tif len(args) < 1 || len(args) > 2 {\n\t\treturn errArgs\n\t}\n\n\tprofile := args[0]\n\tdevName := name\n\tif len(args) > 1 {\n\t\tdevName = args[1]\n\t}\n\n\tnetwork, err := client.NetworkGet(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnicType := \"macvlan\"\n\tif network.Type == \"bridge\" {\n\t\tnicType = \"bridged\"\n\t}\n\n\tprops := []string{fmt.Sprintf(\"nictype=%s\", nicType), fmt.Sprintf(\"parent=%s\", name)}\n\t_, err = client.ProfileDeviceAdd(profile, devName, \"nic\", props)\n\treturn err\n}\n\nfunc (c *networkCmd) doNetworkCreate(client *lxd.Client, name string, args []string) error {\n\tconfig := map[string]string{}\n\n\tfor i := 0; i < len(args); i++ {\n\t\tentry := strings.SplitN(args[i], \"=\", 2)\n\t\tif len(entry) < 2 {\n\t\t\treturn errArgs\n\t\t}\n\n\t\tconfig[entry[0]] = entry[1]\n\t}\n\n\terr := client.NetworkCreate(name, config)\n\tif err == nil {\n\t\tfmt.Printf(i18n.G(\"Network %s created\")+\"\\n\", name)\n\t}\n\n\treturn err\n}\n\nfunc (c *networkCmd) doNetworkDetach(client *lxd.Client, name string, args []string) error {\n\tif len(args) < 1 || len(args) > 2 {\n\t\treturn errArgs\n\t}\n\n\tcontainerName := args[0]\n\tdevName := \"\"\n\tif len(args) > 1 {\n\t\tdevName = args[1]\n\t}\n\n\tcontainer, err := client.ContainerInfo(containerName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif devName == \"\" {\n\t\tfor n, d := range container.Devices {\n\t\t\tif d[\"type\"] == \"nic\" && d[\"parent\"] == name {\n\t\t\t\tif devName != \"\" {\n\t\t\t\t\treturn fmt.Errorf(i18n.G(\"More than one device matches, specify the device name.\"))\n\t\t\t\t}\n\n\t\t\t\tdevName = n\n\t\t\t}\n\t\t}\n\t}\n\n\tif devName == \"\" {\n\t\treturn fmt.Errorf(i18n.G(\"No device found for this network\"))\n\t}\n\n\tdevice, ok := container.Devices[devName]\n\tif !ok {\n\t\treturn fmt.Errorf(i18n.G(\"The specified device doesn't exist\"))\n\t}\n\n\tif device[\"type\"] != \"nic\" || device[\"parent\"] != name {\n\t\treturn fmt.Errorf(i18n.G(\"The specified device doesn't match the network\"))\n\t}\n\n\tresp, err := client.ContainerDeviceDelete(containerName, devName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn client.WaitForSuccess(resp.Operation)\n}\n\nfunc (c *networkCmd) doNetworkDetachProfile(client *lxd.Client, name string, args []string) error {\n\tif len(args) < 1 || len(args) > 2 {\n\t\treturn errArgs\n\t}\n\n\tprofileName := args[0]\n\tdevName := \"\"\n\tif len(args) > 1 {\n\t\tdevName = args[1]\n\t}\n\n\tprofile, err := client.ProfileConfig(profileName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif devName == \"\" {\n\t\tfor n, d := range profile.Devices {\n\t\t\tif d[\"type\"] == \"nic\" && d[\"parent\"] == name {\n\t\t\t\tif devName != \"\" {\n\t\t\t\t\treturn fmt.Errorf(i18n.G(\"More than one device matches, specify the device name.\"))\n\t\t\t\t}\n\n\t\t\t\tdevName = n\n\t\t\t}\n\t\t}\n\t}\n\n\tif devName == \"\" {\n\t\treturn fmt.Errorf(i18n.G(\"No device found for this network\"))\n\t}\n\n\tdevice, ok := profile.Devices[devName]\n\tif !ok {\n\t\treturn fmt.Errorf(i18n.G(\"The specified device doesn't exist\"))\n\t}\n\n\tif device[\"type\"] != \"nic\" || device[\"parent\"] != name {\n\t\treturn fmt.Errorf(i18n.G(\"The specified device doesn't match the network\"))\n\t}\n\n\t_, err = client.ProfileDeviceDelete(profileName, devName)\n\treturn err\n}\n\nfunc (c *networkCmd) doNetworkDelete(client *lxd.Client, name string) error {\n\terr := client.NetworkDelete(name)\n\tif err == nil {\n\t\tfmt.Printf(i18n.G(\"Network %s deleted\")+\"\\n\", name)\n\t}\n\n\treturn err\n}\n\nfunc (c *networkCmd) doNetworkEdit(client *lxd.Client, name string) error {\n\t\/\/ If stdin isn't a terminal, read text from it\n\tif !termios.IsTerminal(int(syscall.Stdin)) {\n\t\tcontents, err := ioutil.ReadAll(os.Stdin)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tnewdata := api.NetworkPut{}\n\t\terr = yaml.Unmarshal(contents, &newdata)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn client.NetworkPut(name, newdata)\n\t}\n\n\t\/\/ Extract the current value\n\tnetwork, err := client.NetworkGet(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !network.Managed {\n\t\treturn fmt.Errorf(i18n.G(\"Only managed networks can be modified.\"))\n\t}\n\n\tdata, err := yaml.Marshal(&network)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Spawn the editor\n\tcontent, err := shared.TextEditor(\"\", []byte(c.networkEditHelp()+\"\\n\\n\"+string(data)))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor {\n\t\t\/\/ Parse the text received from the editor\n\t\tnewdata := api.NetworkPut{}\n\t\terr = yaml.Unmarshal(content, &newdata)\n\t\tif err == nil {\n\t\t\terr = client.NetworkPut(name, newdata)\n\t\t}\n\n\t\t\/\/ Respawn the editor\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, i18n.G(\"Config parsing error: %s\")+\"\\n\", err)\n\t\t\tfmt.Println(i18n.G(\"Press enter to open the editor again\"))\n\n\t\t\t_, err := os.Stdin.Read(make([]byte, 1))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tcontent, err = shared.TextEditor(\"\", content)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n\treturn nil\n}\n\nfunc (c *networkCmd) doNetworkGet(client *lxd.Client, name string, args []string) error {\n\t\/\/ we shifted @args so so it should read \"<key>\"\n\tif len(args) != 1 {\n\t\treturn errArgs\n\t}\n\n\tresp, err := client.NetworkGet(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor k, v := range resp.Config {\n\t\tif k == args[0] {\n\t\t\tfmt.Printf(\"%s\\n\", v)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (c *networkCmd) doNetworkList(config *lxd.Config, args []string) error {\n\tvar remote string\n\tif len(args) > 1 {\n\t\tvar name string\n\t\tremote, name = config.ParseRemoteAndContainer(args[1])\n\t\tif name != \"\" {\n\t\t\treturn fmt.Errorf(i18n.G(\"Cannot provide container name to list\"))\n\t\t}\n\t} else {\n\t\tremote = config.DefaultRemote\n\t}\n\n\tclient, err := lxd.NewClient(config, remote)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tnetworks, err := client.ListNetworks()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdata := [][]string{}\n\tfor _, network := range networks {\n\t\tif shared.StringInSlice(network.Type, []string{\"loopback\", \"unknown\"}) {\n\t\t\tcontinue\n\t\t}\n\n\t\tstrManaged := i18n.G(\"NO\")\n\t\tif network.Managed {\n\t\t\tstrManaged = i18n.G(\"YES\")\n\t\t}\n\n\t\tstrUsedBy := fmt.Sprintf(\"%d\", len(network.UsedBy))\n\t\tdata = append(data, []string{network.Name, network.Type, strManaged, strUsedBy})\n\t}\n\n\ttable := tablewriter.NewWriter(os.Stdout)\n\ttable.SetAutoWrapText(false)\n\ttable.SetAlignment(tablewriter.ALIGN_LEFT)\n\ttable.SetRowLine(true)\n\ttable.SetHeader([]string{\n\t\ti18n.G(\"NAME\"),\n\t\ti18n.G(\"TYPE\"),\n\t\ti18n.G(\"MANAGED\"),\n\t\ti18n.G(\"USED BY\")})\n\tsort.Sort(byName(data))\n\ttable.AppendBulk(data)\n\ttable.Render()\n\n\treturn nil\n}\n\nfunc (c *networkCmd) doNetworkSet(client *lxd.Client, name string, args []string) error {\n\t\/\/ we shifted @args so so it should read \"<key> [<value>]\"\n\tif len(args) < 1 {\n\t\treturn errArgs\n\t}\n\n\tnetwork, err := client.NetworkGet(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !network.Managed {\n\t\treturn fmt.Errorf(i18n.G(\"Only managed networks can be modified.\"))\n\t}\n\n\tkey := args[0]\n\tvar value string\n\tif len(args) < 2 {\n\t\tvalue = \"\"\n\t} else {\n\t\tvalue = args[1]\n\t}\n\n\tif !termios.IsTerminal(int(syscall.Stdin)) && value == \"-\" {\n\t\tbuf, err := ioutil.ReadAll(os.Stdin)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(i18n.G(\"Can't read from stdin: %s\"), err)\n\t\t}\n\t\tvalue = string(buf[:])\n\t}\n\n\tnetwork.Config[key] = value\n\n\treturn client.NetworkPut(name, network.Writable())\n}\n\nfunc (c *networkCmd) doNetworkShow(client *lxd.Client, name string) error {\n\tnetwork, err := client.NetworkGet(name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdata, err := yaml.Marshal(&network)\n\tfmt.Printf(\"%s\", data)\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package drain\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"logyard\/util\/pubsub\"\n\t\"net\/url\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text\/template\"\n)\n\ntype DrainConfig struct {\n\tName    string\n\tType    string\n\tScheme  string\n\tHost    string \/\/ host+port part of the uri (optional in some drains)\n\tPath    string\n\tFilters []string           \/\/ Filter messages by these keys.\n\tFormat  *template.Template \/\/ Format message json using Go's\n\t\/\/ template library; if\n\t\/\/ format==raw, send the raw\n\t\/\/ stream: \"<key> <msg>\"\n\tParams    map[string]string \/\/ Params specific to that drain type.\n\trawFormat bool\n}\n\n\/\/ GetParam returns the corresponding param; else the default value (def)\nfunc (c *DrainConfig) GetParam(key string, def string) string {\n\tif val, ok := c.Params[key]; ok {\n\t\treturn val\n\t}\n\treturn def\n}\n\nfunc (c *DrainConfig) GetParamInt(key string, def int) (int, error) {\n\tdata := c.GetParam(key, \"\")\n\tif data == \"\" {\n\t\treturn def, nil\n\t}\n\tvar val int\n\tvar err error\n\tif val, err = strconv.Atoi(data); err != nil {\n\t\treturn 0, err\n\t}\n\treturn val, nil\n}\n\nfunc (c *DrainConfig) GetParamBool(key string, def bool) (bool, error) {\n\tdata := c.GetParam(key, \"\")\n\tif data == \"\" {\n\t\treturn def, nil\n\t}\n\tvar val bool\n\tvar err error\n\tif val, err = strconv.ParseBool(data); err != nil {\n\t\treturn false, err\n\t}\n\treturn val, nil\n}\n\n\/\/ FormatJSON formats the given message and returns it with a newline\nfunc (c *DrainConfig) FormatJSON(msg pubsub.Message) ([]byte, error) {\n\tif c.Format == nil {\n\t\tif c.rawFormat {\n\t\t\t\/\/ <key> <json>\n\t\t\treturn []byte(fmt.Sprintf(\"%s %s\\n\", msg.Key, msg.Value)), nil\n\t\t} else {\n\t\t\t\/\/ <json>\n\t\t\treturn []byte(msg.Value + \"\\n\"), nil\n\t\t}\n\t}\n\trecord := make(map[string]interface{})\n\terr := json.Unmarshal([]byte(msg.Value), &record)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar buf bytes.Buffer\n\terr = c.Format.Execute(&buf, record)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn append(buf.Bytes(), byte('\\n')), nil\n}\n\n\/\/ ParseDrainUri creates a DrainConfig from the drain URI.\nfunc ParseDrainUri(name string, uri string, namedFormats map[string]string) (*DrainConfig, error) {\n\turl, err := url.Parse(uri)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconfig := DrainConfig{Name: name, Type: url.Scheme}\n\tif _, ok := DRAINS[config.Type]; !ok {\n\t\treturn nil, fmt.Errorf(\"unknown drain type: %s\", uri)\n\t}\n\n\tconfig.Scheme = url.Scheme\n\tconfig.Host = url.Host\n\tconfig.Path = url.Path\n\n\t\/\/ Go doesn't correctly parse file:\/\/ uris with empty <host>.\n\t\/\/ http:\/\/tools.ietf.org\/html\/rfc1738\n\tif url.Scheme == \"file\" {\n\t\tif strings.HasPrefix(url.Path, \"\/\/\") {\n\t\t\tconfig.Path = url.Path[2:]\n\t\t}\n\t}\n\n\tparams := url.Query()\n\n\t\/\/ parse filters\n\tif filters, ok := params[\"filter\"]; ok {\n\t\tparams.Del(\"filter\")\n\t\tconfig.Filters = filters\n\t} else {\n\t\t\/\/ default filter: all\n\t\tconfig.Filters = []string{\"\"}\n\t}\n\n\tif len(config.Filters) == 0 {\n\t\tpanic(\"filters can't be empty\")\n\t}\n\n\t\/\/ parse format\n\tif format, ok := params[\"format\"]; ok {\n\t\tparams.Del(\"format\")\n\n\t\tconfig.Format, config.rawFormat, err = parseFormat(name, format[0], namedFormats)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t\/\/ assign the rest of the params\n\tconfig.Params = make(map[string]string)\n\tfor k, v := range params {\n\t\t\/\/ NOTE: multi value params are not supported.\n\t\tconfig.Params[k] = v[0]\n\t}\n\n\treturn &config, nil\n}\n\nfunc parseFormat(\n\tname, format string, aliases map[string]string) (*template.Template, bool, error) {\n\tif format == \"raw\" {\n\t\treturn nil, true, nil\n\t}\n\tif value, ok := aliases[format]; ok {\n\t\tformat = value\n\t}\n\ttmpl, err := template.New(name).Parse(format)\n\treturn tmpl, false, err\n}\n\n\/\/ ConstructDrainURI constructs the drain URI from given parameters.\nfunc ConstructDrainURI(\n\tname, uri string, filters []string, params map[string]string) (string, error) {\n\tif uri == \"\" {\n\t\treturn \"\", fmt.Errorf(\"URI cannot be empty\")\n\t}\n\n\tif !strings.Contains(uri, \":\/\/\") {\n\t\treturn \"\", fmt.Errorf(\"Not an URI: %s\", uri)\n\t}\n\n\t\/\/ Build the query string\n\tquery := url.Values{}\n\tfor _, filter := range filters {\n\t\tquery.Add(\"filter\", filter)\n\t}\n\tfor key, value := range params {\n\t\tif key == \"filter\" {\n\t\t\treturn \"\", fmt.Errorf(\"params cannot have a key called 'filter'\")\n\t\t}\n\t\tquery.Set(key, value)\n\t}\n\n\turi += \"?\" + query.Encode()\n\treturn uri, nil\n}\n<commit_msg>recognize format=json in drain URIs<commit_after>package drain\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"logyard\/util\/pubsub\"\n\t\"net\/url\"\n\t\"strconv\"\n\t\"strings\"\n\t\"text\/template\"\n)\n\ntype DrainConfig struct {\n\tName    string\n\tType    string\n\tScheme  string\n\tHost    string \/\/ host+port part of the uri (optional in some drains)\n\tPath    string\n\tFilters []string           \/\/ Filter messages by these keys.\n\tFormat  *template.Template \/\/ Format message json using Go's\n\t\/\/ template library; if\n\t\/\/ format==raw, send the raw\n\t\/\/ stream: \"<key> <msg>\"\n\tParams    map[string]string \/\/ Params specific to that drain type.\n\trawFormat bool\n}\n\n\/\/ GetParam returns the corresponding param; else the default value (def)\nfunc (c *DrainConfig) GetParam(key string, def string) string {\n\tif val, ok := c.Params[key]; ok {\n\t\treturn val\n\t}\n\treturn def\n}\n\nfunc (c *DrainConfig) GetParamInt(key string, def int) (int, error) {\n\tdata := c.GetParam(key, \"\")\n\tif data == \"\" {\n\t\treturn def, nil\n\t}\n\tvar val int\n\tvar err error\n\tif val, err = strconv.Atoi(data); err != nil {\n\t\treturn 0, err\n\t}\n\treturn val, nil\n}\n\nfunc (c *DrainConfig) GetParamBool(key string, def bool) (bool, error) {\n\tdata := c.GetParam(key, \"\")\n\tif data == \"\" {\n\t\treturn def, nil\n\t}\n\tvar val bool\n\tvar err error\n\tif val, err = strconv.ParseBool(data); err != nil {\n\t\treturn false, err\n\t}\n\treturn val, nil\n}\n\n\/\/ FormatJSON formats the given message and returns it with a newline\nfunc (c *DrainConfig) FormatJSON(msg pubsub.Message) ([]byte, error) {\n\tif c.Format == nil {\n\t\tif c.rawFormat {\n\t\t\t\/\/ <key> <json>\n\t\t\treturn []byte(fmt.Sprintf(\"%s %s\\n\", msg.Key, msg.Value)), nil\n\t\t} else {\n\t\t\t\/\/ <json>\n\t\t\treturn []byte(msg.Value + \"\\n\"), nil\n\t\t}\n\t}\n\trecord := make(map[string]interface{})\n\terr := json.Unmarshal([]byte(msg.Value), &record)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar buf bytes.Buffer\n\terr = c.Format.Execute(&buf, record)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn append(buf.Bytes(), byte('\\n')), nil\n}\n\n\/\/ ParseDrainUri creates a DrainConfig from the drain URI.\nfunc ParseDrainUri(name string, uri string, namedFormats map[string]string) (*DrainConfig, error) {\n\turl, err := url.Parse(uri)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconfig := DrainConfig{Name: name, Type: url.Scheme}\n\tif _, ok := DRAINS[config.Type]; !ok {\n\t\treturn nil, fmt.Errorf(\"unknown drain type: %s\", uri)\n\t}\n\n\tconfig.Scheme = url.Scheme\n\tconfig.Host = url.Host\n\tconfig.Path = url.Path\n\n\t\/\/ Go doesn't correctly parse file:\/\/ uris with empty <host>.\n\t\/\/ http:\/\/tools.ietf.org\/html\/rfc1738\n\tif url.Scheme == \"file\" {\n\t\tif strings.HasPrefix(url.Path, \"\/\/\") {\n\t\t\tconfig.Path = url.Path[2:]\n\t\t}\n\t}\n\n\tparams := url.Query()\n\n\t\/\/ parse filters\n\tif filters, ok := params[\"filter\"]; ok {\n\t\tparams.Del(\"filter\")\n\t\tconfig.Filters = filters\n\t} else {\n\t\t\/\/ default filter: all\n\t\tconfig.Filters = []string{\"\"}\n\t}\n\n\tif len(config.Filters) == 0 {\n\t\tpanic(\"filters can't be empty\")\n\t}\n\n\t\/\/ parse format\n\tif format, ok := params[\"format\"]; ok {\n\t\tparams.Del(\"format\")\n\n\t\tif format[0] != \"json\" {\n\t\t\tconfig.Format, config.rawFormat, err = parseFormat(name, format[0], namedFormats)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ assign the rest of the params\n\tconfig.Params = make(map[string]string)\n\tfor k, v := range params {\n\t\t\/\/ NOTE: multi value params are not supported.\n\t\tconfig.Params[k] = v[0]\n\t}\n\n\treturn &config, nil\n}\n\nfunc parseFormat(\n\tname, format string, aliases map[string]string) (*template.Template, bool, error) {\n\tif format == \"raw\" {\n\t\treturn nil, true, nil\n\t}\n\tif value, ok := aliases[format]; ok {\n\t\tformat = value\n\t}\n\ttmpl, err := template.New(name).Parse(format)\n\treturn tmpl, false, err\n}\n\n\/\/ ConstructDrainURI constructs the drain URI from given parameters.\nfunc ConstructDrainURI(\n\tname, uri string, filters []string, params map[string]string) (string, error) {\n\tif uri == \"\" {\n\t\treturn \"\", fmt.Errorf(\"URI cannot be empty\")\n\t}\n\n\tif !strings.Contains(uri, \":\/\/\") {\n\t\treturn \"\", fmt.Errorf(\"Not an URI: %s\", uri)\n\t}\n\n\t\/\/ Build the query string\n\tquery := url.Values{}\n\tfor _, filter := range filters {\n\t\tquery.Add(\"filter\", filter)\n\t}\n\tfor key, value := range params {\n\t\tif key == \"filter\" {\n\t\t\treturn \"\", fmt.Errorf(\"params cannot have a key called 'filter'\")\n\t\t}\n\t\tquery.Set(key, value)\n\t}\n\n\turi += \"?\" + query.Encode()\n\treturn uri, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2017 Jeff Foley. All rights reserved.\n\/\/ Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n\npackage amass\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/PuerkitoBio\/gocrawl\"\n\t\"github.com\/PuerkitoBio\/goquery\"\n)\n\ntype ArchiveService struct {\n\tBaseAmassService\n\n\tresponses chan *AmassRequest\n\tarchives  []Archiver\n\tfilter    map[string]struct{}\n}\n\nfunc NewArchiveService(in, out chan *AmassRequest, config *AmassConfig) *ArchiveService {\n\tas := &ArchiveService{\n\t\tresponses: make(chan *AmassRequest, 50),\n\t\tfilter:    make(map[string]struct{}),\n\t}\n\t\/\/ Modify the crawler's http client to use our DialContext\n\tgocrawl.HttpClient.Transport = &http.Transport{\n\t\tDialContext:           config.DialContext,\n\t\tMaxIdleConns:          200,\n\t\tIdleConnTimeout:       90 * time.Second,\n\t\tTLSHandshakeTimeout:   10 * time.Second,\n\t\tExpectContinueTimeout: 5 * time.Second,\n\t}\n\t\/\/ Setup the service\n\tas.BaseAmassService = *NewBaseAmassService(\"Web Archive Service\", config, as)\n\tas.archives = []Archiver{\n\t\tWaybackMachineArchive(as.responses),\n\t\tLibraryCongressArchive(as.responses),\n\t\tArchiveIsArchive(as.responses),\n\t\tArchiveItArchive(as.responses),\n\t\tArquivoArchive(as.responses),\n\t\tUKWebArchive(as.responses),\n\t\tUKGovArchive(as.responses),\n\t}\n\n\tas.input = in\n\tas.output = out\n\treturn as\n}\n\nfunc (as *ArchiveService) OnStart() error {\n\tas.BaseAmassService.OnStart()\n\n\tgo as.processRequests()\n\tgo as.processOutput()\n\treturn nil\n}\n\nfunc (as *ArchiveService) OnStop() error {\n\tas.BaseAmassService.OnStop()\n\treturn nil\n}\n\nfunc (as *ArchiveService) processRequests() {\nloop:\n\tfor {\n\t\tselect {\n\t\tcase req := <-as.Input():\n\t\t\tgo as.executeAllArchives(req)\n\t\tcase <-as.Quit():\n\t\t\tbreak loop\n\t\t}\n\t}\n}\n\nfunc (as *ArchiveService) processOutput() {\n\tt := time.NewTicker(10 * time.Second)\n\tdefer t.Stop()\nloop:\n\tfor {\n\t\tselect {\n\t\tcase out := <-as.responses:\n\t\t\tas.SetActive(true)\n\t\t\tif !as.duplicate(out.Name) {\n\t\t\t\tas.SendOut(out)\n\t\t\t}\n\t\tcase <-t.C:\n\t\t\tas.SetActive(false)\n\t\tcase <-as.Quit():\n\t\t\tbreak loop\n\t\t}\n\t}\n}\n\n\/\/ Returns true if the subdomain name is a duplicate entry in the filter.\n\/\/ If not, the subdomain name is added to the filter\nfunc (as *ArchiveService) duplicate(sub string) bool {\n\tif _, found := as.filter[sub]; found {\n\t\treturn true\n\t}\n\tas.filter[sub] = struct{}{}\n\treturn false\n}\n\nfunc (as *ArchiveService) executeAllArchives(req *AmassRequest) {\n\tas.SetActive(true)\n\n\tfor _, archive := range as.archives {\n\t\tgo archive.Search(req)\n\t}\n}\n\n\/\/ Archiver - represents all objects that perform Memento web archive searches for domain names\ntype Archiver interface {\n\tSearch(req *AmassRequest)\n}\n\ntype memento struct {\n\tName     string\n\tURL      string\n\tOutput   chan<- *AmassRequest\n\tRequests chan *AmassRequest\n}\n\nfunc (m *memento) Search(req *AmassRequest) {\n\tm.Requests <- req\n}\n\nfunc MementoWebArchive(u, name string, out chan<- *AmassRequest) Archiver {\n\tm := &memento{\n\t\tName:     name,\n\t\tURL:      u,\n\t\tOutput:   out,\n\t\tRequests: make(chan *AmassRequest, 100),\n\t}\n\tgo m.processRequests()\n\treturn m\n}\n\nfunc ArchiveItArchive(out chan<- *AmassRequest) Archiver {\n\treturn MementoWebArchive(\"https:\/\/wayback.archive-it.org\/all\", \"Archive-It\", out)\n}\n\nfunc ArchiveIsArchive(out chan<- *AmassRequest) Archiver {\n\treturn MementoWebArchive(\"http:\/\/archive.is\", \"Archive Today\", out)\n}\n\nfunc ArquivoArchive(out chan<- *AmassRequest) Archiver {\n\treturn MementoWebArchive(\"http:\/\/arquivo.pt\/wayback\", \"Arquivo Arc\", out)\n}\n\nfunc LibraryCongressArchive(out chan<- *AmassRequest) Archiver {\n\treturn MementoWebArchive(\"http:\/\/webarchive.loc.gov\/all\", \"LoC Archive\", out)\n}\n\nfunc UKWebArchive(out chan<- *AmassRequest) Archiver {\n\treturn MementoWebArchive(\"http:\/\/www.webarchive.org.uk\/wayback\/archive\", \"Open UK Arc\", out)\n}\n\nfunc UKGovArchive(out chan<- *AmassRequest) Archiver {\n\treturn MementoWebArchive(\"http:\/\/webarchive.nationalarchives.gov.uk\", \"UK Gov Arch\", out)\n}\n\nfunc WaybackMachineArchive(out chan<- *AmassRequest) Archiver {\n\treturn MementoWebArchive(\"http:\/\/web.archive.org\/web\", \"Wayback Arc\", out)\n}\n\n\/* Private functions *\/\n\nfunc (m *memento) processRequests() {\n\tvar running int\n\tvar queue []*AmassRequest\n\tdone := make(chan int, 10)\n\n\tt := time.NewTicker(1 * time.Second)\n\tdefer t.Stop()\n\n\tyear := time.Now().Year()\n\t\/\/ Only have up to 10 crawlers running at the same time\n\tfor {\n\t\tselect {\n\t\tcase sd := <-m.Requests:\n\t\t\tqueue = append(queue, sd)\n\t\tcase <-t.C:\n\t\t\tif running >= 10 || len(queue) <= 0 {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\ts := queue[0]\n\t\t\tif len(queue) == 1 {\n\t\t\t\tqueue = []*AmassRequest{}\n\t\t\t} else {\n\t\t\t\tqueue = queue[1:]\n\t\t\t}\n\n\t\t\tgo m.crawl(strconv.Itoa(year), s, done, 10*time.Second)\n\t\t\trunning++\n\t\tcase <-done:\n\t\t\trunning--\n\t\t}\n\t}\n}\n\nfunc (m *memento) crawl(year string, req *AmassRequest, done chan int, timeout time.Duration) {\n\tdomain := req.Domain\n\tif domain == \"\" {\n\t\tdone <- 1\n\t\treturn\n\t}\n\n\text := &ext{\n\t\tDefaultExtender: &gocrawl.DefaultExtender{},\n\t\tdomainRE:        SubdomainRegex(domain),\n\t\tmementoRE:       regexp.MustCompile(m.URL + \"\/[0-9]+\/\"),\n\t\tfilter:          make(map[string]bool), \/\/ Filter for not double-checking URLs\n\t\tbase:            m.URL,\n\t\tyear:            year,\n\t\tsub:             req.Name,\n\t\tdomain:          domain,\n\t\tnames:           m.Output,\n\t\tsource:          m.Name,\n\t}\n\n\t\/\/ Set custom options\n\topts := gocrawl.NewOptions(ext)\n\topts.CrawlDelay = 500 * time.Millisecond\n\topts.LogFlags = gocrawl.LogError\n\topts.SameHostOnly = true\n\topts.MaxVisits = 20\n\n\tc := gocrawl.NewCrawlerWithOptions(opts)\n\tgo c.Run(fmt.Sprintf(\"%s\/%s\/%s\", m.URL, year, req.Name))\n\n\t<-time.After(timeout)\n\tc.Stop()\n\tdone <- 1\n}\n\ntype ext struct {\n\t*gocrawl.DefaultExtender\n\tdomainRE                *regexp.Regexp\n\tmementoRE               *regexp.Regexp\n\tfilter                  map[string]bool\n\tflock                   sync.RWMutex\n\tbase, year, sub, domain string\n\tnames                   chan<- *AmassRequest\n\tsource                  string\n}\n\nfunc (e *ext) reducedURL(u *url.URL) string {\n\torig := u.String()\n\n\tidx := e.mementoRE.FindStringIndex(orig)\n\tif idx == nil {\n\t\treturn \"\"\n\t}\n\n\ti := idx[1]\n\treturn fmt.Sprintf(\"%s\/%s\/%s\", e.base, e.year, orig[i:])\n}\n\nfunc (e *ext) Log(logFlags gocrawl.LogFlags, msgLevel gocrawl.LogFlags, msg string) {\n\treturn\n}\n\nfunc (e *ext) RequestRobots(ctx *gocrawl.URLContext, robotAgent string) (data []byte, doRequest bool) {\n\treturn nil, false\n}\n\nfunc (e *ext) Filter(ctx *gocrawl.URLContext, isVisited bool) bool {\n\tif isVisited {\n\t\treturn false\n\t}\n\n\tu := ctx.URL().String()\n\tr := e.reducedURL(ctx.URL())\n\n\tif !strings.Contains(ctx.URL().Path, e.sub) {\n\t\treturn false\n\t}\n\n\te.flock.RLock()\n\t_, ok := e.filter[r]\n\te.flock.RUnlock()\n\n\tif ok {\n\t\treturn false\n\t}\n\n\tif u != r {\n\t\t\/\/ The more refined version has been requested\n\t\t\/\/ and will cause the reduced version to be filtered\n\t\te.flock.Lock()\n\t\te.filter[r] = true\n\t\te.flock.Unlock()\n\t}\n\treturn true\n}\n\nfunc (e *ext) Visit(ctx *gocrawl.URLContext, res *http.Response, doc *goquery.Document) (interface{}, bool) {\n\tin, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn nil, true\n\t}\n\n\tfor _, f := range e.domainRE.FindAllString(string(in), -1) {\n\t\te.names <- &AmassRequest{\n\t\t\tName:   f,\n\t\t\tDomain: e.domain,\n\t\t\tTag:    ARCHIVE,\n\t\t\tSource: e.source,\n\t\t}\n\t}\n\treturn nil, true\n}\n<commit_msg>small improvement to web crawling for archives due to issue #34<commit_after>\/\/ Copyright 2017 Jeff Foley. All rights reserved.\n\/\/ Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.\n\npackage amass\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/PuerkitoBio\/gocrawl\"\n\t\"github.com\/PuerkitoBio\/goquery\"\n)\n\ntype ArchiveService struct {\n\tBaseAmassService\n\n\tresponses chan *AmassRequest\n\tarchives  []Archiver\n\tfilter    map[string]struct{}\n}\n\nfunc NewArchiveService(in, out chan *AmassRequest, config *AmassConfig) *ArchiveService {\n\tas := &ArchiveService{\n\t\tresponses: make(chan *AmassRequest, 50),\n\t\tfilter:    make(map[string]struct{}),\n\t}\n\t\/\/ Modify the crawler's http client to use our DialContext\n\tgocrawl.HttpClient.Transport = &http.Transport{\n\t\tDialContext:           config.DialContext,\n\t\tMaxIdleConns:          200,\n\t\tIdleConnTimeout:       90 * time.Second,\n\t\tTLSHandshakeTimeout:   10 * time.Second,\n\t\tExpectContinueTimeout: 5 * time.Second,\n\t}\n\t\/\/ Setup the service\n\tas.BaseAmassService = *NewBaseAmassService(\"Web Archive Service\", config, as)\n\tas.archives = []Archiver{\n\t\tWaybackMachineArchive(as.responses),\n\t\tLibraryCongressArchive(as.responses),\n\t\tArchiveIsArchive(as.responses),\n\t\tArchiveItArchive(as.responses),\n\t\tArquivoArchive(as.responses),\n\t\tUKWebArchive(as.responses),\n\t\tUKGovArchive(as.responses),\n\t}\n\n\tas.input = in\n\tas.output = out\n\treturn as\n}\n\nfunc (as *ArchiveService) OnStart() error {\n\tas.BaseAmassService.OnStart()\n\n\tgo as.processRequests()\n\tgo as.processOutput()\n\treturn nil\n}\n\nfunc (as *ArchiveService) OnStop() error {\n\tas.BaseAmassService.OnStop()\n\treturn nil\n}\n\nfunc (as *ArchiveService) processRequests() {\nloop:\n\tfor {\n\t\tselect {\n\t\tcase req := <-as.Input():\n\t\t\tgo as.executeAllArchives(req)\n\t\tcase <-as.Quit():\n\t\t\tbreak loop\n\t\t}\n\t}\n}\n\nfunc (as *ArchiveService) processOutput() {\n\tt := time.NewTicker(10 * time.Second)\n\tdefer t.Stop()\nloop:\n\tfor {\n\t\tselect {\n\t\tcase out := <-as.responses:\n\t\t\tas.SetActive(true)\n\t\t\tif !as.duplicate(out.Name) {\n\t\t\t\tas.SendOut(out)\n\t\t\t}\n\t\tcase <-t.C:\n\t\t\tas.SetActive(false)\n\t\tcase <-as.Quit():\n\t\t\tbreak loop\n\t\t}\n\t}\n}\n\n\/\/ Returns true if the subdomain name is a duplicate entry in the filter.\n\/\/ If not, the subdomain name is added to the filter\nfunc (as *ArchiveService) duplicate(sub string) bool {\n\tif _, found := as.filter[sub]; found {\n\t\treturn true\n\t}\n\tas.filter[sub] = struct{}{}\n\treturn false\n}\n\nfunc (as *ArchiveService) executeAllArchives(req *AmassRequest) {\n\tas.SetActive(true)\n\n\tfor _, archive := range as.archives {\n\t\tgo archive.Search(req)\n\t}\n}\n\n\/\/ Archiver - represents all objects that perform Memento web archive searches for domain names\ntype Archiver interface {\n\tSearch(req *AmassRequest)\n}\n\ntype memento struct {\n\tName     string\n\tURL      string\n\tOutput   chan<- *AmassRequest\n\tRequests chan *AmassRequest\n}\n\nfunc (m *memento) Search(req *AmassRequest) {\n\tm.Requests <- req\n}\n\nfunc MementoWebArchive(u, name string, out chan<- *AmassRequest) Archiver {\n\tm := &memento{\n\t\tName:     name,\n\t\tURL:      u,\n\t\tOutput:   out,\n\t\tRequests: make(chan *AmassRequest, 100),\n\t}\n\tgo m.processRequests()\n\treturn m\n}\n\nfunc ArchiveItArchive(out chan<- *AmassRequest) Archiver {\n\treturn MementoWebArchive(\"https:\/\/wayback.archive-it.org\/all\", \"Archive-It\", out)\n}\n\nfunc ArchiveIsArchive(out chan<- *AmassRequest) Archiver {\n\treturn MementoWebArchive(\"http:\/\/archive.is\", \"Archive Today\", out)\n}\n\nfunc ArquivoArchive(out chan<- *AmassRequest) Archiver {\n\treturn MementoWebArchive(\"http:\/\/arquivo.pt\/wayback\", \"Arquivo Arc\", out)\n}\n\nfunc LibraryCongressArchive(out chan<- *AmassRequest) Archiver {\n\treturn MementoWebArchive(\"http:\/\/webarchive.loc.gov\/all\", \"LoC Archive\", out)\n}\n\nfunc UKWebArchive(out chan<- *AmassRequest) Archiver {\n\treturn MementoWebArchive(\"http:\/\/www.webarchive.org.uk\/wayback\/archive\", \"Open UK Arc\", out)\n}\n\nfunc UKGovArchive(out chan<- *AmassRequest) Archiver {\n\treturn MementoWebArchive(\"http:\/\/webarchive.nationalarchives.gov.uk\", \"UK Gov Arch\", out)\n}\n\nfunc WaybackMachineArchive(out chan<- *AmassRequest) Archiver {\n\treturn MementoWebArchive(\"http:\/\/web.archive.org\/web\", \"Wayback Arc\", out)\n}\n\n\/* Private functions *\/\n\nfunc (m *memento) processRequests() {\n\tvar running int\n\tvar queue []*AmassRequest\n\tdone := make(chan struct{}, 10)\n\n\tt := time.NewTicker(1 * time.Second)\n\tdefer t.Stop()\n\n\tyear := time.Now().Year()\n\t\/\/ Only have up to 10 crawlers running at the same time\n\tfor {\n\t\tselect {\n\t\tcase sd := <-m.Requests:\n\t\t\tqueue = append(queue, sd)\n\t\tcase <-t.C:\n\t\t\tif running >= 10 || len(queue) <= 0 {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\ts := queue[0]\n\t\t\tif len(queue) == 1 {\n\t\t\t\tqueue = []*AmassRequest{}\n\t\t\t} else {\n\t\t\t\tqueue = queue[1:]\n\t\t\t}\n\n\t\t\tgo m.crawl(strconv.Itoa(year), s, done)\n\t\t\trunning++\n\t\tcase <-done:\n\t\t\trunning--\n\t\t}\n\t}\n}\n\nfunc (m *memento) crawl(year string, req *AmassRequest, done chan struct{}) {\n\tdomain := req.Domain\n\tif domain == \"\" {\n\t\tdone <- struct{}{}\n\t\treturn\n\t}\n\n\text := &ext{\n\t\tDefaultExtender: &gocrawl.DefaultExtender{},\n\t\tdomainRE:        SubdomainRegex(domain),\n\t\tmementoRE:       regexp.MustCompile(m.URL + \"\/[0-9]+\/\"),\n\t\tfilter:          make(map[string]bool), \/\/ Filter for not double-checking URLs\n\t\tbase:            m.URL,\n\t\tyear:            year,\n\t\tsub:             req.Name,\n\t\tdomain:          domain,\n\t\tnames:           m.Output,\n\t\tsource:          m.Name,\n\t}\n\n\t\/\/ Set custom options\n\topts := gocrawl.NewOptions(ext)\n\topts.CrawlDelay = 500 * time.Millisecond\n\topts.LogFlags = gocrawl.LogError\n\topts.SameHostOnly = true\n\topts.MaxVisits = 20\n\n\tc := gocrawl.NewCrawlerWithOptions(opts)\n\tc.Run(fmt.Sprintf(\"%s\/%s\/%s\", m.URL, year, req.Name))\n\tdone <- struct{}{}\n}\n\ntype ext struct {\n\t*gocrawl.DefaultExtender\n\tdomainRE                *regexp.Regexp\n\tmementoRE               *regexp.Regexp\n\tfilter                  map[string]bool\n\tflock                   sync.RWMutex\n\tbase, year, sub, domain string\n\tnames                   chan<- *AmassRequest\n\tsource                  string\n}\n\nfunc (e *ext) reducedURL(u *url.URL) string {\n\torig := u.String()\n\n\tidx := e.mementoRE.FindStringIndex(orig)\n\tif idx == nil {\n\t\treturn \"\"\n\t}\n\n\ti := idx[1]\n\treturn fmt.Sprintf(\"%s\/%s\/%s\", e.base, e.year, orig[i:])\n}\n\nfunc (e *ext) Log(logFlags gocrawl.LogFlags, msgLevel gocrawl.LogFlags, msg string) {\n\treturn\n}\n\nfunc (e *ext) RequestRobots(ctx *gocrawl.URLContext, robotAgent string) (data []byte, doRequest bool) {\n\treturn nil, false\n}\n\nfunc (e *ext) Filter(ctx *gocrawl.URLContext, isVisited bool) bool {\n\tif isVisited {\n\t\treturn false\n\t}\n\n\tu := ctx.URL().String()\n\tr := e.reducedURL(ctx.URL())\n\n\tif !strings.Contains(ctx.URL().Path, e.sub) {\n\t\treturn false\n\t}\n\n\te.flock.RLock()\n\t_, ok := e.filter[r]\n\te.flock.RUnlock()\n\n\tif ok {\n\t\treturn false\n\t}\n\n\tif u != r {\n\t\t\/\/ The more refined version has been requested\n\t\t\/\/ and will cause the reduced version to be filtered\n\t\te.flock.Lock()\n\t\te.filter[r] = true\n\t\te.flock.Unlock()\n\t}\n\treturn true\n}\n\nfunc (e *ext) Visit(ctx *gocrawl.URLContext, res *http.Response, doc *goquery.Document) (interface{}, bool) {\n\tin, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn nil, true\n\t}\n\n\tfor _, f := range e.domainRE.FindAllString(string(in), -1) {\n\t\te.names <- &AmassRequest{\n\t\t\tName:   f,\n\t\t\tDomain: e.domain,\n\t\t\tTag:    ARCHIVE,\n\t\t\tSource: e.source,\n\t\t}\n\t}\n\treturn nil, true\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (c) 2016 Uber Technologies, Inc.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\npackage instrument\n\nimport (\n\t\"sync\/atomic\"\n\t\"time\"\n\n\t\"github.com\/uber-go\/tally\"\n)\n\nvar (\n\tnullStopWatchStart tally.Stopwatch\n)\n\n\/\/ sampledTimer is a sampled timer that implements the tally timer interface.\n\/\/ NB(xichen): the sampling logic should eventually be implemented in tally.\ntype sampledTimer struct {\n\ttally.Timer\n\n\tcnt  uint64\n\trate uint64\n}\n\n\/\/ NB(xichen): return an error instead of panicing.\nfunc newSampledTimer(base tally.Timer, rate float64) tally.Timer {\n\tif rate <= 0.0 || rate > 1.0 {\n\t\tpanic(\"sampled timer must have a sampling rate between 0.0 and 1.0\")\n\t}\n\treturn &sampledTimer{\n\t\tTimer: base,\n\t\trate:  uint64(1.0 \/ rate),\n\t}\n}\n\nfunc (t *sampledTimer) shouldSample() bool {\n\treturn atomic.AddUint64(&t.cnt, 1)%t.rate == 0\n}\n\nfunc (t *sampledTimer) Start() tally.Stopwatch {\n\tif !t.shouldSample() {\n\t\treturn nullStopWatchStart\n\t}\n\treturn t.Timer.Start()\n}\n\nfunc (t *sampledTimer) Stop(startTime tally.Stopwatch) {\n\tif startTime == nullStopWatchStart { \/\/ nolint: badtime\n\t\t\/\/ If startTime is nullStopWatchStart, do nothing.\n\t\treturn\n\t}\n\tstartTime.Stop()\n}\n\nfunc (t *sampledTimer) Record(d time.Duration) {\n\tif !t.shouldSample() {\n\t\treturn\n\t}\n\tt.Timer.Record(d)\n}\n\n\/\/ MethodMetrics is a bundle of common metrics with a uniform naming scheme.\ntype MethodMetrics struct {\n\tErrors         tally.Counter\n\tSuccess        tally.Counter\n\tErrorsLatency  tally.Timer\n\tSuccessLatency tally.Timer\n}\n\n\/\/ ReportSuccess reports a success.\nfunc (m *MethodMetrics) ReportSuccess(d time.Duration) {\n\tm.Success.Inc(1)\n\tm.SuccessLatency.Record(d)\n}\n\n\/\/ ReportError reports an error.\nfunc (m *MethodMetrics) ReportError(d time.Duration) {\n\tm.Errors.Inc(1)\n\tm.ErrorsLatency.Record(d)\n}\n\n\/\/ ReportSuccessOrError increments Error\/Success counter dependending on the error.\nfunc (m *MethodMetrics) ReportSuccessOrError(e error, d time.Duration) {\n\tif e != nil {\n\t\tm.ReportError(d)\n\t} else {\n\t\tm.ReportSuccess(d)\n\t}\n}\n\n\/\/ NewMethodMetrics returns a new Method metrics for the given method name.\nfunc NewMethodMetrics(scope tally.Scope, methodName string, samplingRate float64) MethodMetrics {\n\treturn MethodMetrics{\n\t\tErrors:         scope.Counter(methodName + \".errors\"),\n\t\tSuccess:        scope.Counter(methodName + \".success\"),\n\t\tErrorsLatency:  newSampledTimer(scope.Timer(methodName+\".errors-latency\"), samplingRate),\n\t\tSuccessLatency: newSampledTimer(scope.Timer(methodName+\".success-latency\"), samplingRate),\n\t}\n}\n\n\/\/ BatchMethodMetrics is a bundle of common metrics for methods with batch semantics.\ntype BatchMethodMetrics struct {\n\tRetryableErrors    tally.Counter\n\tNonRetryableErrors tally.Counter\n\tErrors             tally.Counter\n\tSuccess            tally.Counter\n\tLatency            tally.Timer\n}\n\n\/\/ NewBatchMethodMetrics creates new batch method metrics.\nfunc NewBatchMethodMetrics(\n\tscope tally.Scope,\n\tmethodName string,\n\tsamplingRate float64,\n) BatchMethodMetrics {\n\treturn BatchMethodMetrics{\n\t\tRetryableErrors:    scope.Counter(methodName + \".retryable-errors\"),\n\t\tNonRetryableErrors: scope.Counter(methodName + \".non-retryable-errors\"),\n\t\tErrors:             scope.Counter(methodName + \".errors\"),\n\t\tSuccess:            scope.Counter(methodName + \".success\"),\n\t\tLatency:            newSampledTimer(scope.Timer(methodName+\".latency\"), samplingRate),\n\t}\n}\n\n\/\/ ReportSuccess reports successess.\nfunc (m *BatchMethodMetrics) ReportSuccess(n int) {\n\tm.Success.Inc(int64(n))\n}\n\n\/\/ ReportRetryableErrors reports retryable errors.\nfunc (m *BatchMethodMetrics) ReportRetryableErrors(n int) {\n\tm.RetryableErrors.Inc(int64(n))\n\tm.Errors.Inc(int64(n))\n}\n\n\/\/ ReportNonRetryableErrors reports non-retryable errors.\nfunc (m *BatchMethodMetrics) ReportNonRetryableErrors(n int) {\n\tm.NonRetryableErrors.Inc(int64(n))\n\tm.Errors.Inc(int64(n))\n}\n\n\/\/ ReportLatency reports latency.\nfunc (m *BatchMethodMetrics) ReportLatency(d time.Duration) {\n\tm.Latency.Record(d)\n}\n<commit_msg>Export constructors for creating sampled timers (#117)<commit_after>\/\/ Copyright (c) 2016 Uber Technologies, Inc.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\npackage instrument\n\nimport (\n\t\"fmt\"\n\t\"sync\/atomic\"\n\t\"time\"\n\n\t\"github.com\/uber-go\/tally\"\n)\n\nvar (\n\tnullStopWatchStart tally.Stopwatch\n)\n\n\/\/ sampledTimer is a sampled timer that implements the tally timer interface.\n\/\/ NB(xichen): the sampling logic should eventually be implemented in tally.\ntype sampledTimer struct {\n\ttally.Timer\n\n\tcnt  uint64\n\trate uint64\n}\n\n\/\/ NewSampledTimer creates a new sampled timer.\nfunc NewSampledTimer(base tally.Timer, rate float64) (tally.Timer, error) {\n\tif rate <= 0.0 || rate > 1.0 {\n\t\treturn nil, fmt.Errorf(\"sampling rate %f must be between 0.0 and 1.0\", rate)\n\t}\n\treturn &sampledTimer{\n\t\tTimer: base,\n\t\trate:  uint64(1.0 \/ rate),\n\t}, nil\n}\n\n\/\/ MustCreateSampledTimer creates a new sampled timer, and panics if an error\n\/\/ is encountered.\nfunc MustCreateSampledTimer(base tally.Timer, rate float64) tally.Timer {\n\tt, err := NewSampledTimer(base, rate)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn t\n}\n\nfunc (t *sampledTimer) shouldSample() bool {\n\treturn atomic.AddUint64(&t.cnt, 1)%t.rate == 0\n}\n\nfunc (t *sampledTimer) Start() tally.Stopwatch {\n\tif !t.shouldSample() {\n\t\treturn nullStopWatchStart\n\t}\n\treturn t.Timer.Start()\n}\n\nfunc (t *sampledTimer) Stop(startTime tally.Stopwatch) {\n\tif startTime == nullStopWatchStart { \/\/ nolint: badtime\n\t\t\/\/ If startTime is nullStopWatchStart, do nothing.\n\t\treturn\n\t}\n\tstartTime.Stop()\n}\n\nfunc (t *sampledTimer) Record(d time.Duration) {\n\tif !t.shouldSample() {\n\t\treturn\n\t}\n\tt.Timer.Record(d)\n}\n\n\/\/ MethodMetrics is a bundle of common metrics with a uniform naming scheme.\ntype MethodMetrics struct {\n\tErrors         tally.Counter\n\tSuccess        tally.Counter\n\tErrorsLatency  tally.Timer\n\tSuccessLatency tally.Timer\n}\n\n\/\/ ReportSuccess reports a success.\nfunc (m *MethodMetrics) ReportSuccess(d time.Duration) {\n\tm.Success.Inc(1)\n\tm.SuccessLatency.Record(d)\n}\n\n\/\/ ReportError reports an error.\nfunc (m *MethodMetrics) ReportError(d time.Duration) {\n\tm.Errors.Inc(1)\n\tm.ErrorsLatency.Record(d)\n}\n\n\/\/ ReportSuccessOrError increments Error\/Success counter dependending on the error.\nfunc (m *MethodMetrics) ReportSuccessOrError(e error, d time.Duration) {\n\tif e != nil {\n\t\tm.ReportError(d)\n\t} else {\n\t\tm.ReportSuccess(d)\n\t}\n}\n\n\/\/ NewMethodMetrics returns a new Method metrics for the given method name.\nfunc NewMethodMetrics(scope tally.Scope, methodName string, samplingRate float64) MethodMetrics {\n\treturn MethodMetrics{\n\t\tErrors:         scope.Counter(methodName + \".errors\"),\n\t\tSuccess:        scope.Counter(methodName + \".success\"),\n\t\tErrorsLatency:  MustCreateSampledTimer(scope.Timer(methodName+\".errors-latency\"), samplingRate),\n\t\tSuccessLatency: MustCreateSampledTimer(scope.Timer(methodName+\".success-latency\"), samplingRate),\n\t}\n}\n\n\/\/ BatchMethodMetrics is a bundle of common metrics for methods with batch semantics.\ntype BatchMethodMetrics struct {\n\tRetryableErrors    tally.Counter\n\tNonRetryableErrors tally.Counter\n\tErrors             tally.Counter\n\tSuccess            tally.Counter\n\tLatency            tally.Timer\n}\n\n\/\/ NewBatchMethodMetrics creates new batch method metrics.\nfunc NewBatchMethodMetrics(\n\tscope tally.Scope,\n\tmethodName string,\n\tsamplingRate float64,\n) BatchMethodMetrics {\n\treturn BatchMethodMetrics{\n\t\tRetryableErrors:    scope.Counter(methodName + \".retryable-errors\"),\n\t\tNonRetryableErrors: scope.Counter(methodName + \".non-retryable-errors\"),\n\t\tErrors:             scope.Counter(methodName + \".errors\"),\n\t\tSuccess:            scope.Counter(methodName + \".success\"),\n\t\tLatency:            MustCreateSampledTimer(scope.Timer(methodName+\".latency\"), samplingRate),\n\t}\n}\n\n\/\/ ReportSuccess reports successess.\nfunc (m *BatchMethodMetrics) ReportSuccess(n int) {\n\tm.Success.Inc(int64(n))\n}\n\n\/\/ ReportRetryableErrors reports retryable errors.\nfunc (m *BatchMethodMetrics) ReportRetryableErrors(n int) {\n\tm.RetryableErrors.Inc(int64(n))\n\tm.Errors.Inc(int64(n))\n}\n\n\/\/ ReportNonRetryableErrors reports non-retryable errors.\nfunc (m *BatchMethodMetrics) ReportNonRetryableErrors(n int) {\n\tm.NonRetryableErrors.Inc(int64(n))\n\tm.Errors.Inc(int64(n))\n}\n\n\/\/ ReportLatency reports latency.\nfunc (m *BatchMethodMetrics) ReportLatency(d time.Duration) {\n\tm.Latency.Record(d)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright ©2011-2012 The bíogo Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage align\n\nimport (\n\t\"code.google.com\/p\/biogo\/alphabet\"\n\t\"code.google.com\/p\/biogo\/io\/seqio\/fasta\"\n\t\"code.google.com\/p\/biogo\/seq\/linear\"\n\tcheck \"launchpad.net\/gocheck\"\n\t\"strings\"\n\t\"testing\"\n)\n\n\/\/ Tests\nfunc Test(t *testing.T) { check.TestingT(t) }\n\ntype S struct{}\n\nvar _ = check.Suite(&S{})\n\nfunc (s *S) TestWarning(c *check.C) { c.Log(\"\\nFIXME: Tests only in example tests.\\n\") }\n\nfunc BenchmarkSWAlign(b *testing.B) {\n\tb.StopTimer()\n\tt := &linear.Seq{}\n\tt.Alpha = alphabet.DNA\n\tr := fasta.NewReader(strings.NewReader(crspFa), t)\n\tswsa, _ := r.Read()\n\tswsb, _ := r.Read()\n\n\tsmith := SW{\n\t\t{2, -1, -1, -1, -1},\n\t\t{-1, 2, -1, -1, -1},\n\t\t{-1, -1, 2, -1, -1},\n\t\t{-1, -1, -1, 2, -1},\n\t\t{-1, -1, -1, -1, 0},\n\t}\n\tb.StartTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tsmith.Align(swsa, swsb)\n\t}\n}\n\nfunc BenchmarkNWAlign(b *testing.B) {\n\tb.StopTimer()\n\tt := &linear.Seq{}\n\tt.Alpha = alphabet.DNA\n\tr := fasta.NewReader(strings.NewReader(crspFa), t)\n\tnwsa, _ := r.Read()\n\tnwsb, _ := r.Read()\n\n\tneedle := NW{\n\t\t{10, -3, -1, -4, -5},\n\t\t{-3, 9, -5, 0, -5},\n\t\t{-1, -5, 7, -3, -5},\n\t\t{-4, 0, -3, 8, -5},\n\t\t{-4, -4, -4, -4, 0},\n\t}\n\n\tb.StartTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tneedle.Align(nwsa, nwsb)\n\t}\n}\n\nfunc BenchmarkSWAffineAlign(b *testing.B) {\n\tb.StopTimer()\n\tt := &linear.Seq{}\n\tt.Alpha = alphabet.DNA\n\tr := fasta.NewReader(strings.NewReader(crspFa), t)\n\tswsa, _ := r.Read()\n\tswsb, _ := r.Read()\n\n\tsmith := SWAffine{\n\t\tMatrix: Linear{\n\t\t\t{2, -1, -1, -1, -1},\n\t\t\t{-1, 2, -1, -1, -1},\n\t\t\t{-1, -1, 2, -1, -1},\n\t\t\t{-1, -1, -1, 2, -1},\n\t\t\t{-1, -1, -1, -1, 0},\n\t\t},\n\t\tGapOpen: -5,\n\t}\n\tb.StartTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tsmith.Align(swsa, swsb)\n\t}\n}\n\nfunc BenchmarkNWAffineAlign(b *testing.B) {\n\tb.StopTimer()\n\tt := &linear.Seq{}\n\tt.Alpha = alphabet.DNA\n\tr := fasta.NewReader(strings.NewReader(crspFa), t)\n\tnwsa, _ := r.Read()\n\tnwsb, _ := r.Read()\n\n\tneedle := NWAffine{\n\t\tMatrix: Linear{\n\t\t\t{10, -3, -1, -4, -5},\n\t\t\t{-3, 9, -5, 0, -5},\n\t\t\t{-1, -5, 7, -3, -5},\n\t\t\t{-4, 0, -3, 8, -5},\n\t\t\t{-4, -4, -4, -4, 0},\n\t\t},\n\t\tGapOpen: -10,\n\t}\n\n\tb.StartTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tneedle.Align(nwsa, nwsb)\n\t}\n}\n<commit_msg>Update benchmarks to use gapped alphabet<commit_after>\/\/ Copyright ©2011-2012 The bíogo Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage align\n\nimport (\n\t\"code.google.com\/p\/biogo\/alphabet\"\n\t\"code.google.com\/p\/biogo\/io\/seqio\/fasta\"\n\t\"code.google.com\/p\/biogo\/seq\/linear\"\n\tcheck \"launchpad.net\/gocheck\"\n\t\"strings\"\n\t\"testing\"\n)\n\n\/\/ Tests\nfunc Test(t *testing.T) { check.TestingT(t) }\n\ntype S struct{}\n\nvar _ = check.Suite(&S{})\n\nfunc (s *S) TestWarning(c *check.C) { c.Log(\"\\nFIXME: Tests only in example tests.\\n\") }\n\nfunc BenchmarkSWAlign(b *testing.B) {\n\tb.StopTimer()\n\tt := &linear.Seq{}\n\tt.Alpha = alphabet.DNAgapped\n\tr := fasta.NewReader(strings.NewReader(crspFa), t)\n\tswsa, _ := r.Read()\n\tswsb, _ := r.Read()\n\n\tsmith := SW{\n\t\t{2, -1, -1, -1, -1},\n\t\t{-1, 2, -1, -1, -1},\n\t\t{-1, -1, 2, -1, -1},\n\t\t{-1, -1, -1, 2, -1},\n\t\t{-1, -1, -1, -1, 0},\n\t}\n\tb.StartTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tsmith.Align(swsa, swsb)\n\t}\n}\n\nfunc BenchmarkNWAlign(b *testing.B) {\n\tb.StopTimer()\n\tt := &linear.Seq{}\n\tt.Alpha = alphabet.DNAgapped\n\tr := fasta.NewReader(strings.NewReader(crspFa), t)\n\tnwsa, _ := r.Read()\n\tnwsb, _ := r.Read()\n\n\tneedle := NW{\n\t\t{10, -3, -1, -4, -5},\n\t\t{-3, 9, -5, 0, -5},\n\t\t{-1, -5, 7, -3, -5},\n\t\t{-4, 0, -3, 8, -5},\n\t\t{-4, -4, -4, -4, 0},\n\t}\n\n\tb.StartTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tneedle.Align(nwsa, nwsb)\n\t}\n}\n\nfunc BenchmarkSWAffineAlign(b *testing.B) {\n\tb.StopTimer()\n\tt := &linear.Seq{}\n\tt.Alpha = alphabet.DNAgapped\n\tr := fasta.NewReader(strings.NewReader(crspFa), t)\n\tswsa, _ := r.Read()\n\tswsb, _ := r.Read()\n\n\tsmith := SWAffine{\n\t\tMatrix: Linear{\n\t\t\t{2, -1, -1, -1, -1},\n\t\t\t{-1, 2, -1, -1, -1},\n\t\t\t{-1, -1, 2, -1, -1},\n\t\t\t{-1, -1, -1, 2, -1},\n\t\t\t{-1, -1, -1, -1, 0},\n\t\t},\n\t\tGapOpen: -5,\n\t}\n\tb.StartTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tsmith.Align(swsa, swsb)\n\t}\n}\n\nfunc BenchmarkNWAffineAlign(b *testing.B) {\n\tb.StopTimer()\n\tt := &linear.Seq{}\n\tt.Alpha = alphabet.DNAgapped\n\tr := fasta.NewReader(strings.NewReader(crspFa), t)\n\tnwsa, _ := r.Read()\n\tnwsb, _ := r.Read()\n\n\tneedle := NWAffine{\n\t\tMatrix: Linear{\n\t\t\t{10, -3, -1, -4, -5},\n\t\t\t{-3, 9, -5, 0, -5},\n\t\t\t{-1, -5, 7, -3, -5},\n\t\t\t{-4, 0, -3, 8, -5},\n\t\t\t{-4, -4, -4, -4, 0},\n\t\t},\n\t\tGapOpen: -10,\n\t}\n\n\tb.StartTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tneedle.Align(nwsa, nwsb)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2021 The Vitess Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"time\"\n\tvtgatepb \"vitess.io\/vitess\/go\/vt\/proto\/vtgate\"\n\n\tbinlogdatapb \"vitess.io\/vitess\/go\/vt\/proto\/binlogdata\"\n\ttopodatapb \"vitess.io\/vitess\/go\/vt\/proto\/topodata\"\n\t_ \"vitess.io\/vitess\/go\/vt\/vtctl\/grpcvtctlclient\"\n\t_ \"vitess.io\/vitess\/go\/vt\/vtgate\/grpcvtgateconn\"\n\t\"vitess.io\/vitess\/go\/vt\/vtgate\/vtgateconn\"\n)\n\n\/*\n\tThis is a sample client for streaming using the vstream API. It is setup to work with the local example and you can\n    either stream from the unsharded commerce keyspace or the customer keyspace after the sharding step.\n*\/\nfunc main() {\n\tctx := context.Background()\n\tstreamCustomer := true\n\tvar vgtid *binlogdatapb.VGtid\n\tif streamCustomer {\n\t\tvgtid = &binlogdatapb.VGtid{\n\t\t\tShardGtids: []*binlogdatapb.ShardGtid{{\n\t\t\t\tKeyspace: \"customer\",\n\t\t\t\tShard:    \"-80\",\n\t\t\t\t\/\/ Gtid \"\" is to stream from the start, \"current\" is to stream from the current gtid\n\t\t\t\t\/\/ you can also specify a gtid to start with.\n\t\t\t\tGtid:     \"\", \/\/\"current\"  \/\/ \"MySQL56\/36a89abd-978f-11eb-b312-04ed332e05c2:1-265\"\n\t\t\t}, {\n\t\t\t\tKeyspace: \"customer\",\n\t\t\t\tShard:    \"80-\",\n\t\t\t\tGtid:     \"\",\n\t\t\t}}}\n\t} else {\n\t\tvgtid = &binlogdatapb.VGtid{\n\t\t\tShardGtids: []*binlogdatapb.ShardGtid{{\n\t\t\t\tKeyspace: \"commerce\",\n\t\t\t\tShard:    \"0\",\n\t\t\t\tGtid:     \"\",\n\t\t\t}}}\n\t}\n\tfilter := &binlogdatapb.Filter{\n\t\tRules: []*binlogdatapb.Rule{{\n\t\t\tMatch:  \"customer\",\n\t\t\tFilter: \"select * from customer\",\n\t\t}},\n\t}\n\tconn, err := vtgateconn.Dial(ctx, \"localhost:15991\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer conn.Close()\n\tflags := &vtgatepb.VStreamFlags{\n\t\t\/\/MinimizeSkew:      false,\n\t\t\/\/HeartbeatInterval: 60, \/\/seconds\n\t}\n\treader, err := conn.VStream(ctx, topodatapb.TabletType_MASTER, vgtid, filter, flags)\n\tfor {\n\t\te, err := reader.Recv()\n\t\tswitch err {\n\t\tcase nil:\n\t\t\t_ = e\n\t\t\tfmt.Printf(\"%v\\n\", e)\n\t\tcase io.EOF:\n\t\t\tfmt.Printf(\"stream ended\\n\")\n\t\t\treturn\n\t\tdefault:\n\t\t\tfmt.Printf(\"%s:: remote error: %v\\n\", time.Now(), err)\n\t\t\treturn\n\t\t}\n\t}\n}\n<commit_msg>go-fmted<commit_after>\/*\nCopyright 2021 The Vitess Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"time\"\n\tvtgatepb \"vitess.io\/vitess\/go\/vt\/proto\/vtgate\"\n\n\tbinlogdatapb \"vitess.io\/vitess\/go\/vt\/proto\/binlogdata\"\n\ttopodatapb \"vitess.io\/vitess\/go\/vt\/proto\/topodata\"\n\t_ \"vitess.io\/vitess\/go\/vt\/vtctl\/grpcvtctlclient\"\n\t_ \"vitess.io\/vitess\/go\/vt\/vtgate\/grpcvtgateconn\"\n\t\"vitess.io\/vitess\/go\/vt\/vtgate\/vtgateconn\"\n)\n\n\/*\n\tThis is a sample client for streaming using the vstream API. It is setup to work with the local example and you can\n    either stream from the unsharded commerce keyspace or the customer keyspace after the sharding step.\n*\/\nfunc main() {\n\tctx := context.Background()\n\tstreamCustomer := true\n\tvar vgtid *binlogdatapb.VGtid\n\tif streamCustomer {\n\t\tvgtid = &binlogdatapb.VGtid{\n\t\t\tShardGtids: []*binlogdatapb.ShardGtid{{\n\t\t\t\tKeyspace: \"customer\",\n\t\t\t\tShard:    \"-80\",\n\t\t\t\t\/\/ Gtid \"\" is to stream from the start, \"current\" is to stream from the current gtid\n\t\t\t\t\/\/ you can also specify a gtid to start with.\n\t\t\t\tGtid: \"\", \/\/\"current\"  \/\/ \"MySQL56\/36a89abd-978f-11eb-b312-04ed332e05c2:1-265\"\n\t\t\t}, {\n\t\t\t\tKeyspace: \"customer\",\n\t\t\t\tShard:    \"80-\",\n\t\t\t\tGtid:     \"\",\n\t\t\t}}}\n\t} else {\n\t\tvgtid = &binlogdatapb.VGtid{\n\t\t\tShardGtids: []*binlogdatapb.ShardGtid{{\n\t\t\t\tKeyspace: \"commerce\",\n\t\t\t\tShard:    \"0\",\n\t\t\t\tGtid:     \"\",\n\t\t\t}}}\n\t}\n\tfilter := &binlogdatapb.Filter{\n\t\tRules: []*binlogdatapb.Rule{{\n\t\t\tMatch:  \"customer\",\n\t\t\tFilter: \"select * from customer\",\n\t\t}},\n\t}\n\tconn, err := vtgateconn.Dial(ctx, \"localhost:15991\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer conn.Close()\n\tflags := &vtgatepb.VStreamFlags{\n\t\t\/\/MinimizeSkew:      false,\n\t\t\/\/HeartbeatInterval: 60, \/\/seconds\n\t}\n\treader, err := conn.VStream(ctx, topodatapb.TabletType_MASTER, vgtid, filter, flags)\n\tfor {\n\t\te, err := reader.Recv()\n\t\tswitch err {\n\t\tcase nil:\n\t\t\t_ = e\n\t\t\tfmt.Printf(\"%v\\n\", e)\n\t\tcase io.EOF:\n\t\t\tfmt.Printf(\"stream ended\\n\")\n\t\t\treturn\n\t\tdefault:\n\t\t\tfmt.Printf(\"%s:: remote error: %v\\n\", time.Now(), err)\n\t\t\treturn\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Code generated by counterfeiter. DO NOT EDIT.\npackage providerfakes\n\nimport (\n\t\"net\/http\"\n\t\"sync\"\n\n\t\"code.cloudfoundry.org\/lager\"\n\t\"github.com\/concourse\/atc\/auth\/provider\"\n\t\"golang.org\/x\/net\/context\"\n\t\"golang.org\/x\/oauth2\"\n)\n\ntype FakeProvider struct {\n\tPreTokenClientStub        func() (*http.Client, error)\n\tpreTokenClientMutex       sync.RWMutex\n\tpreTokenClientArgsForCall []struct{}\n\tpreTokenClientReturns     struct {\n\t\tresult1 *http.Client\n\t\tresult2 error\n\t}\n\tpreTokenClientReturnsOnCall map[int]struct {\n\t\tresult1 *http.Client\n\t\tresult2 error\n\t}\n\tAuthCodeURLStub        func(string, ...oauth2.AuthCodeOption) string\n\tauthCodeURLMutex       sync.RWMutex\n\tauthCodeURLArgsForCall []struct {\n\t\targ1 string\n\t\targ2 []oauth2.AuthCodeOption\n\t}\n\tauthCodeURLReturns struct {\n\t\tresult1 string\n\t}\n\tauthCodeURLReturnsOnCall map[int]struct {\n\t\tresult1 string\n\t}\n\tExchangeStub        func(context.Context, string) (*oauth2.Token, error)\n\texchangeMutex       sync.RWMutex\n\texchangeArgsForCall []struct {\n\t\targ1 context.Context\n\t\targ2 string\n\t}\n\texchangeReturns struct {\n\t\tresult1 *oauth2.Token\n\t\tresult2 error\n\t}\n\texchangeReturnsOnCall map[int]struct {\n\t\tresult1 *oauth2.Token\n\t\tresult2 error\n\t}\n\tClientStub        func(context.Context, *oauth2.Token) *http.Client\n\tclientMutex       sync.RWMutex\n\tclientArgsForCall []struct {\n\t\targ1 context.Context\n\t\targ2 *oauth2.Token\n\t}\n\tclientReturns struct {\n\t\tresult1 *http.Client\n\t}\n\tclientReturnsOnCall map[int]struct {\n\t\tresult1 *http.Client\n\t}\n\tVerifyStub        func(lager.Logger, *http.Client) (bool, error)\n\tverifyMutex       sync.RWMutex\n\tverifyArgsForCall []struct {\n\t\targ1 lager.Logger\n\t\targ2 *http.Client\n\t}\n\tverifyReturns struct {\n\t\tresult1 bool\n\t\tresult2 error\n\t}\n\tverifyReturnsOnCall map[int]struct {\n\t\tresult1 bool\n\t\tresult2 error\n\t}\n\tinvocations      map[string][][]interface{}\n\tinvocationsMutex sync.RWMutex\n}\n\nfunc (fake *FakeProvider) PreTokenClient() (*http.Client, error) {\n\tfake.preTokenClientMutex.Lock()\n\tret, specificReturn := fake.preTokenClientReturnsOnCall[len(fake.preTokenClientArgsForCall)]\n\tfake.preTokenClientArgsForCall = append(fake.preTokenClientArgsForCall, struct{}{})\n\tfake.recordInvocation(\"PreTokenClient\", []interface{}{})\n\tfake.preTokenClientMutex.Unlock()\n\tif fake.PreTokenClientStub != nil {\n\t\treturn fake.PreTokenClientStub()\n\t}\n\tif specificReturn {\n\t\treturn ret.result1, ret.result2\n\t}\n\treturn fake.preTokenClientReturns.result1, fake.preTokenClientReturns.result2\n}\n\nfunc (fake *FakeProvider) PreTokenClientCallCount() int {\n\tfake.preTokenClientMutex.RLock()\n\tdefer fake.preTokenClientMutex.RUnlock()\n\treturn len(fake.preTokenClientArgsForCall)\n}\n\nfunc (fake *FakeProvider) PreTokenClientReturns(result1 *http.Client, result2 error) {\n\tfake.PreTokenClientStub = nil\n\tfake.preTokenClientReturns = struct {\n\t\tresult1 *http.Client\n\t\tresult2 error\n\t}{result1, result2}\n}\n\nfunc (fake *FakeProvider) PreTokenClientReturnsOnCall(i int, result1 *http.Client, result2 error) {\n\tfake.PreTokenClientStub = nil\n\tif fake.preTokenClientReturnsOnCall == nil {\n\t\tfake.preTokenClientReturnsOnCall = make(map[int]struct {\n\t\t\tresult1 *http.Client\n\t\t\tresult2 error\n\t\t})\n\t}\n\tfake.preTokenClientReturnsOnCall[i] = struct {\n\t\tresult1 *http.Client\n\t\tresult2 error\n\t}{result1, result2}\n}\n\nfunc (fake *FakeProvider) AuthCodeURL(arg1 string, arg2 ...oauth2.AuthCodeOption) string {\n\tfake.authCodeURLMutex.Lock()\n\tret, specificReturn := fake.authCodeURLReturnsOnCall[len(fake.authCodeURLArgsForCall)]\n\tfake.authCodeURLArgsForCall = append(fake.authCodeURLArgsForCall, struct {\n\t\targ1 string\n\t\targ2 []oauth2.AuthCodeOption\n\t}{arg1, arg2})\n\tfake.recordInvocation(\"AuthCodeURL\", []interface{}{arg1, arg2})\n\tfake.authCodeURLMutex.Unlock()\n\tif fake.AuthCodeURLStub != nil {\n\t\treturn fake.AuthCodeURLStub(arg1, arg2...)\n\t}\n\tif specificReturn {\n\t\treturn ret.result1\n\t}\n\treturn fake.authCodeURLReturns.result1\n}\n\nfunc (fake *FakeProvider) AuthCodeURLCallCount() int {\n\tfake.authCodeURLMutex.RLock()\n\tdefer fake.authCodeURLMutex.RUnlock()\n\treturn len(fake.authCodeURLArgsForCall)\n}\n\nfunc (fake *FakeProvider) AuthCodeURLArgsForCall(i int) (string, []oauth2.AuthCodeOption) {\n\tfake.authCodeURLMutex.RLock()\n\tdefer fake.authCodeURLMutex.RUnlock()\n\treturn fake.authCodeURLArgsForCall[i].arg1, fake.authCodeURLArgsForCall[i].arg2\n}\n\nfunc (fake *FakeProvider) AuthCodeURLReturns(result1 string) {\n\tfake.AuthCodeURLStub = nil\n\tfake.authCodeURLReturns = struct {\n\t\tresult1 string\n\t}{result1}\n}\n\nfunc (fake *FakeProvider) AuthCodeURLReturnsOnCall(i int, result1 string) {\n\tfake.AuthCodeURLStub = nil\n\tif fake.authCodeURLReturnsOnCall == nil {\n\t\tfake.authCodeURLReturnsOnCall = make(map[int]struct {\n\t\t\tresult1 string\n\t\t})\n\t}\n\tfake.authCodeURLReturnsOnCall[i] = struct {\n\t\tresult1 string\n\t}{result1}\n}\n\nfunc (fake *FakeProvider) Exchange(arg1 context.Context, arg2 string) (*oauth2.Token, error) {\n\tfake.exchangeMutex.Lock()\n\tret, specificReturn := fake.exchangeReturnsOnCall[len(fake.exchangeArgsForCall)]\n\tfake.exchangeArgsForCall = append(fake.exchangeArgsForCall, struct {\n\t\targ1 context.Context\n\t\targ2 string\n\t}{arg1, arg2})\n\tfake.recordInvocation(\"Exchange\", []interface{}{arg1, arg2})\n\tfake.exchangeMutex.Unlock()\n\tif fake.ExchangeStub != nil {\n\t\treturn fake.ExchangeStub(arg1, arg2)\n\t}\n\tif specificReturn {\n\t\treturn ret.result1, ret.result2\n\t}\n\treturn fake.exchangeReturns.result1, fake.exchangeReturns.result2\n}\n\nfunc (fake *FakeProvider) ExchangeCallCount() int {\n\tfake.exchangeMutex.RLock()\n\tdefer fake.exchangeMutex.RUnlock()\n\treturn len(fake.exchangeArgsForCall)\n}\n\nfunc (fake *FakeProvider) ExchangeArgsForCall(i int) (context.Context, string) {\n\tfake.exchangeMutex.RLock()\n\tdefer fake.exchangeMutex.RUnlock()\n\treturn fake.exchangeArgsForCall[i].arg1, fake.exchangeArgsForCall[i].arg2\n}\n\nfunc (fake *FakeProvider) ExchangeReturns(result1 *oauth2.Token, result2 error) {\n\tfake.ExchangeStub = nil\n\tfake.exchangeReturns = struct {\n\t\tresult1 *oauth2.Token\n\t\tresult2 error\n\t}{result1, result2}\n}\n\nfunc (fake *FakeProvider) ExchangeReturnsOnCall(i int, result1 *oauth2.Token, result2 error) {\n\tfake.ExchangeStub = nil\n\tif fake.exchangeReturnsOnCall == nil {\n\t\tfake.exchangeReturnsOnCall = make(map[int]struct {\n\t\t\tresult1 *oauth2.Token\n\t\t\tresult2 error\n\t\t})\n\t}\n\tfake.exchangeReturnsOnCall[i] = struct {\n\t\tresult1 *oauth2.Token\n\t\tresult2 error\n\t}{result1, result2}\n}\n\nfunc (fake *FakeProvider) Client(arg1 context.Context, arg2 *oauth2.Token) *http.Client {\n\tfake.clientMutex.Lock()\n\tret, specificReturn := fake.clientReturnsOnCall[len(fake.clientArgsForCall)]\n\tfake.clientArgsForCall = append(fake.clientArgsForCall, struct {\n\t\targ1 context.Context\n\t\targ2 *oauth2.Token\n\t}{arg1, arg2})\n\tfake.recordInvocation(\"Client\", []interface{}{arg1, arg2})\n\tfake.clientMutex.Unlock()\n\tif fake.ClientStub != nil {\n\t\treturn fake.ClientStub(arg1, arg2)\n\t}\n\tif specificReturn {\n\t\treturn ret.result1\n\t}\n\treturn fake.clientReturns.result1\n}\n\nfunc (fake *FakeProvider) ClientCallCount() int {\n\tfake.clientMutex.RLock()\n\tdefer fake.clientMutex.RUnlock()\n\treturn len(fake.clientArgsForCall)\n}\n\nfunc (fake *FakeProvider) ClientArgsForCall(i int) (context.Context, *oauth2.Token) {\n\tfake.clientMutex.RLock()\n\tdefer fake.clientMutex.RUnlock()\n\treturn fake.clientArgsForCall[i].arg1, fake.clientArgsForCall[i].arg2\n}\n\nfunc (fake *FakeProvider) ClientReturns(result1 *http.Client) {\n\tfake.ClientStub = nil\n\tfake.clientReturns = struct {\n\t\tresult1 *http.Client\n\t}{result1}\n}\n\nfunc (fake *FakeProvider) ClientReturnsOnCall(i int, result1 *http.Client) {\n\tfake.ClientStub = nil\n\tif fake.clientReturnsOnCall == nil {\n\t\tfake.clientReturnsOnCall = make(map[int]struct {\n\t\t\tresult1 *http.Client\n\t\t})\n\t}\n\tfake.clientReturnsOnCall[i] = struct {\n\t\tresult1 *http.Client\n\t}{result1}\n}\n\nfunc (fake *FakeProvider) Verify(arg1 lager.Logger, arg2 *http.Client) (bool, error) {\n\tfake.verifyMutex.Lock()\n\tret, specificReturn := fake.verifyReturnsOnCall[len(fake.verifyArgsForCall)]\n\tfake.verifyArgsForCall = append(fake.verifyArgsForCall, struct {\n\t\targ1 lager.Logger\n\t\targ2 *http.Client\n\t}{arg1, arg2})\n\tfake.recordInvocation(\"Verify\", []interface{}{arg1, arg2})\n\tfake.verifyMutex.Unlock()\n\tif fake.VerifyStub != nil {\n\t\treturn fake.VerifyStub(arg1, arg2)\n\t}\n\tif specificReturn {\n\t\treturn ret.result1, ret.result2\n\t}\n\treturn fake.verifyReturns.result1, fake.verifyReturns.result2\n}\n\nfunc (fake *FakeProvider) VerifyCallCount() int {\n\tfake.verifyMutex.RLock()\n\tdefer fake.verifyMutex.RUnlock()\n\treturn len(fake.verifyArgsForCall)\n}\n\nfunc (fake *FakeProvider) VerifyArgsForCall(i int) (lager.Logger, *http.Client) {\n\tfake.verifyMutex.RLock()\n\tdefer fake.verifyMutex.RUnlock()\n\treturn fake.verifyArgsForCall[i].arg1, fake.verifyArgsForCall[i].arg2\n}\n\nfunc (fake *FakeProvider) VerifyReturns(result1 bool, result2 error) {\n\tfake.VerifyStub = nil\n\tfake.verifyReturns = struct {\n\t\tresult1 bool\n\t\tresult2 error\n\t}{result1, result2}\n}\n\nfunc (fake *FakeProvider) VerifyReturnsOnCall(i int, result1 bool, result2 error) {\n\tfake.VerifyStub = nil\n\tif fake.verifyReturnsOnCall == nil {\n\t\tfake.verifyReturnsOnCall = make(map[int]struct {\n\t\t\tresult1 bool\n\t\t\tresult2 error\n\t\t})\n\t}\n\tfake.verifyReturnsOnCall[i] = struct {\n\t\tresult1 bool\n\t\tresult2 error\n\t}{result1, result2}\n}\n\nfunc (fake *FakeProvider) Invocations() map[string][][]interface{} {\n\tfake.invocationsMutex.RLock()\n\tdefer fake.invocationsMutex.RUnlock()\n\tfake.preTokenClientMutex.RLock()\n\tdefer fake.preTokenClientMutex.RUnlock()\n\tfake.authCodeURLMutex.RLock()\n\tdefer fake.authCodeURLMutex.RUnlock()\n\tfake.exchangeMutex.RLock()\n\tdefer fake.exchangeMutex.RUnlock()\n\tfake.clientMutex.RLock()\n\tdefer fake.clientMutex.RUnlock()\n\tfake.verifyMutex.RLock()\n\tdefer fake.verifyMutex.RUnlock()\n\tcopiedInvocations := map[string][][]interface{}{}\n\tfor key, value := range fake.invocations {\n\t\tcopiedInvocations[key] = value\n\t}\n\treturn copiedInvocations\n}\n\nfunc (fake *FakeProvider) recordInvocation(key string, args []interface{}) {\n\tfake.invocationsMutex.Lock()\n\tdefer fake.invocationsMutex.Unlock()\n\tif fake.invocations == nil {\n\t\tfake.invocations = map[string][][]interface{}{}\n\t}\n\tif fake.invocations[key] == nil {\n\t\tfake.invocations[key] = [][]interface{}{}\n\t}\n\tfake.invocations[key] = append(fake.invocations[key], args)\n}\n\nvar _ provider.Provider = new(FakeProvider)\n<commit_msg>Update Provider fake<commit_after>\/\/ Code generated by counterfeiter. DO NOT EDIT.\npackage providerfakes\n\nimport (\n\t\"net\/http\"\n\t\"sync\"\n\n\t\"code.cloudfoundry.org\/lager\"\n\t\"github.com\/concourse\/atc\/auth\/provider\"\n\t\"golang.org\/x\/net\/context\"\n\t\"golang.org\/x\/oauth2\"\n)\n\ntype FakeProvider struct {\n\tPreTokenClientStub        func() (*http.Client, error)\n\tpreTokenClientMutex       sync.RWMutex\n\tpreTokenClientArgsForCall []struct{}\n\tpreTokenClientReturns     struct {\n\t\tresult1 *http.Client\n\t\tresult2 error\n\t}\n\tpreTokenClientReturnsOnCall map[int]struct {\n\t\tresult1 *http.Client\n\t\tresult2 error\n\t}\n\tAuthCodeURLStub        func(string, ...oauth2.AuthCodeOption) string\n\tauthCodeURLMutex       sync.RWMutex\n\tauthCodeURLArgsForCall []struct {\n\t\targ1 string\n\t\targ2 []oauth2.AuthCodeOption\n\t}\n\tauthCodeURLReturns struct {\n\t\tresult1 string\n\t}\n\tauthCodeURLReturnsOnCall map[int]struct {\n\t\tresult1 string\n\t}\n\tExchangeStub        func(context.Context, *http.Request) (*oauth2.Token, error)\n\texchangeMutex       sync.RWMutex\n\texchangeArgsForCall []struct {\n\t\targ1 context.Context\n\t\targ2 *http.Request\n\t}\n\texchangeReturns struct {\n\t\tresult1 *oauth2.Token\n\t\tresult2 error\n\t}\n\texchangeReturnsOnCall map[int]struct {\n\t\tresult1 *oauth2.Token\n\t\tresult2 error\n\t}\n\tClientStub        func(context.Context, *oauth2.Token) *http.Client\n\tclientMutex       sync.RWMutex\n\tclientArgsForCall []struct {\n\t\targ1 context.Context\n\t\targ2 *oauth2.Token\n\t}\n\tclientReturns struct {\n\t\tresult1 *http.Client\n\t}\n\tclientReturnsOnCall map[int]struct {\n\t\tresult1 *http.Client\n\t}\n\tVerifyStub        func(lager.Logger, *http.Client) (bool, error)\n\tverifyMutex       sync.RWMutex\n\tverifyArgsForCall []struct {\n\t\targ1 lager.Logger\n\t\targ2 *http.Client\n\t}\n\tverifyReturns struct {\n\t\tresult1 bool\n\t\tresult2 error\n\t}\n\tverifyReturnsOnCall map[int]struct {\n\t\tresult1 bool\n\t\tresult2 error\n\t}\n\tinvocations      map[string][][]interface{}\n\tinvocationsMutex sync.RWMutex\n}\n\nfunc (fake *FakeProvider) PreTokenClient() (*http.Client, error) {\n\tfake.preTokenClientMutex.Lock()\n\tret, specificReturn := fake.preTokenClientReturnsOnCall[len(fake.preTokenClientArgsForCall)]\n\tfake.preTokenClientArgsForCall = append(fake.preTokenClientArgsForCall, struct{}{})\n\tfake.recordInvocation(\"PreTokenClient\", []interface{}{})\n\tfake.preTokenClientMutex.Unlock()\n\tif fake.PreTokenClientStub != nil {\n\t\treturn fake.PreTokenClientStub()\n\t}\n\tif specificReturn {\n\t\treturn ret.result1, ret.result2\n\t}\n\treturn fake.preTokenClientReturns.result1, fake.preTokenClientReturns.result2\n}\n\nfunc (fake *FakeProvider) PreTokenClientCallCount() int {\n\tfake.preTokenClientMutex.RLock()\n\tdefer fake.preTokenClientMutex.RUnlock()\n\treturn len(fake.preTokenClientArgsForCall)\n}\n\nfunc (fake *FakeProvider) PreTokenClientReturns(result1 *http.Client, result2 error) {\n\tfake.PreTokenClientStub = nil\n\tfake.preTokenClientReturns = struct {\n\t\tresult1 *http.Client\n\t\tresult2 error\n\t}{result1, result2}\n}\n\nfunc (fake *FakeProvider) PreTokenClientReturnsOnCall(i int, result1 *http.Client, result2 error) {\n\tfake.PreTokenClientStub = nil\n\tif fake.preTokenClientReturnsOnCall == nil {\n\t\tfake.preTokenClientReturnsOnCall = make(map[int]struct {\n\t\t\tresult1 *http.Client\n\t\t\tresult2 error\n\t\t})\n\t}\n\tfake.preTokenClientReturnsOnCall[i] = struct {\n\t\tresult1 *http.Client\n\t\tresult2 error\n\t}{result1, result2}\n}\n\nfunc (fake *FakeProvider) AuthCodeURL(arg1 string, arg2 ...oauth2.AuthCodeOption) string {\n\tfake.authCodeURLMutex.Lock()\n\tret, specificReturn := fake.authCodeURLReturnsOnCall[len(fake.authCodeURLArgsForCall)]\n\tfake.authCodeURLArgsForCall = append(fake.authCodeURLArgsForCall, struct {\n\t\targ1 string\n\t\targ2 []oauth2.AuthCodeOption\n\t}{arg1, arg2})\n\tfake.recordInvocation(\"AuthCodeURL\", []interface{}{arg1, arg2})\n\tfake.authCodeURLMutex.Unlock()\n\tif fake.AuthCodeURLStub != nil {\n\t\treturn fake.AuthCodeURLStub(arg1, arg2...)\n\t}\n\tif specificReturn {\n\t\treturn ret.result1\n\t}\n\treturn fake.authCodeURLReturns.result1\n}\n\nfunc (fake *FakeProvider) AuthCodeURLCallCount() int {\n\tfake.authCodeURLMutex.RLock()\n\tdefer fake.authCodeURLMutex.RUnlock()\n\treturn len(fake.authCodeURLArgsForCall)\n}\n\nfunc (fake *FakeProvider) AuthCodeURLArgsForCall(i int) (string, []oauth2.AuthCodeOption) {\n\tfake.authCodeURLMutex.RLock()\n\tdefer fake.authCodeURLMutex.RUnlock()\n\treturn fake.authCodeURLArgsForCall[i].arg1, fake.authCodeURLArgsForCall[i].arg2\n}\n\nfunc (fake *FakeProvider) AuthCodeURLReturns(result1 string) {\n\tfake.AuthCodeURLStub = nil\n\tfake.authCodeURLReturns = struct {\n\t\tresult1 string\n\t}{result1}\n}\n\nfunc (fake *FakeProvider) AuthCodeURLReturnsOnCall(i int, result1 string) {\n\tfake.AuthCodeURLStub = nil\n\tif fake.authCodeURLReturnsOnCall == nil {\n\t\tfake.authCodeURLReturnsOnCall = make(map[int]struct {\n\t\t\tresult1 string\n\t\t})\n\t}\n\tfake.authCodeURLReturnsOnCall[i] = struct {\n\t\tresult1 string\n\t}{result1}\n}\n\nfunc (fake *FakeProvider) Exchange(arg1 context.Context, arg2 *http.Request) (*oauth2.Token, error) {\n\tfake.exchangeMutex.Lock()\n\tret, specificReturn := fake.exchangeReturnsOnCall[len(fake.exchangeArgsForCall)]\n\tfake.exchangeArgsForCall = append(fake.exchangeArgsForCall, struct {\n\t\targ1 context.Context\n\t\targ2 *http.Request\n\t}{arg1, arg2})\n\tfake.recordInvocation(\"Exchange\", []interface{}{arg1, arg2})\n\tfake.exchangeMutex.Unlock()\n\tif fake.ExchangeStub != nil {\n\t\treturn fake.ExchangeStub(arg1, arg2)\n\t}\n\tif specificReturn {\n\t\treturn ret.result1, ret.result2\n\t}\n\treturn fake.exchangeReturns.result1, fake.exchangeReturns.result2\n}\n\nfunc (fake *FakeProvider) ExchangeCallCount() int {\n\tfake.exchangeMutex.RLock()\n\tdefer fake.exchangeMutex.RUnlock()\n\treturn len(fake.exchangeArgsForCall)\n}\n\nfunc (fake *FakeProvider) ExchangeArgsForCall(i int) (context.Context, *http.Request) {\n\tfake.exchangeMutex.RLock()\n\tdefer fake.exchangeMutex.RUnlock()\n\treturn fake.exchangeArgsForCall[i].arg1, fake.exchangeArgsForCall[i].arg2\n}\n\nfunc (fake *FakeProvider) ExchangeReturns(result1 *oauth2.Token, result2 error) {\n\tfake.ExchangeStub = nil\n\tfake.exchangeReturns = struct {\n\t\tresult1 *oauth2.Token\n\t\tresult2 error\n\t}{result1, result2}\n}\n\nfunc (fake *FakeProvider) ExchangeReturnsOnCall(i int, result1 *oauth2.Token, result2 error) {\n\tfake.ExchangeStub = nil\n\tif fake.exchangeReturnsOnCall == nil {\n\t\tfake.exchangeReturnsOnCall = make(map[int]struct {\n\t\t\tresult1 *oauth2.Token\n\t\t\tresult2 error\n\t\t})\n\t}\n\tfake.exchangeReturnsOnCall[i] = struct {\n\t\tresult1 *oauth2.Token\n\t\tresult2 error\n\t}{result1, result2}\n}\n\nfunc (fake *FakeProvider) Client(arg1 context.Context, arg2 *oauth2.Token) *http.Client {\n\tfake.clientMutex.Lock()\n\tret, specificReturn := fake.clientReturnsOnCall[len(fake.clientArgsForCall)]\n\tfake.clientArgsForCall = append(fake.clientArgsForCall, struct {\n\t\targ1 context.Context\n\t\targ2 *oauth2.Token\n\t}{arg1, arg2})\n\tfake.recordInvocation(\"Client\", []interface{}{arg1, arg2})\n\tfake.clientMutex.Unlock()\n\tif fake.ClientStub != nil {\n\t\treturn fake.ClientStub(arg1, arg2)\n\t}\n\tif specificReturn {\n\t\treturn ret.result1\n\t}\n\treturn fake.clientReturns.result1\n}\n\nfunc (fake *FakeProvider) ClientCallCount() int {\n\tfake.clientMutex.RLock()\n\tdefer fake.clientMutex.RUnlock()\n\treturn len(fake.clientArgsForCall)\n}\n\nfunc (fake *FakeProvider) ClientArgsForCall(i int) (context.Context, *oauth2.Token) {\n\tfake.clientMutex.RLock()\n\tdefer fake.clientMutex.RUnlock()\n\treturn fake.clientArgsForCall[i].arg1, fake.clientArgsForCall[i].arg2\n}\n\nfunc (fake *FakeProvider) ClientReturns(result1 *http.Client) {\n\tfake.ClientStub = nil\n\tfake.clientReturns = struct {\n\t\tresult1 *http.Client\n\t}{result1}\n}\n\nfunc (fake *FakeProvider) ClientReturnsOnCall(i int, result1 *http.Client) {\n\tfake.ClientStub = nil\n\tif fake.clientReturnsOnCall == nil {\n\t\tfake.clientReturnsOnCall = make(map[int]struct {\n\t\t\tresult1 *http.Client\n\t\t})\n\t}\n\tfake.clientReturnsOnCall[i] = struct {\n\t\tresult1 *http.Client\n\t}{result1}\n}\n\nfunc (fake *FakeProvider) Verify(arg1 lager.Logger, arg2 *http.Client) (bool, error) {\n\tfake.verifyMutex.Lock()\n\tret, specificReturn := fake.verifyReturnsOnCall[len(fake.verifyArgsForCall)]\n\tfake.verifyArgsForCall = append(fake.verifyArgsForCall, struct {\n\t\targ1 lager.Logger\n\t\targ2 *http.Client\n\t}{arg1, arg2})\n\tfake.recordInvocation(\"Verify\", []interface{}{arg1, arg2})\n\tfake.verifyMutex.Unlock()\n\tif fake.VerifyStub != nil {\n\t\treturn fake.VerifyStub(arg1, arg2)\n\t}\n\tif specificReturn {\n\t\treturn ret.result1, ret.result2\n\t}\n\treturn fake.verifyReturns.result1, fake.verifyReturns.result2\n}\n\nfunc (fake *FakeProvider) VerifyCallCount() int {\n\tfake.verifyMutex.RLock()\n\tdefer fake.verifyMutex.RUnlock()\n\treturn len(fake.verifyArgsForCall)\n}\n\nfunc (fake *FakeProvider) VerifyArgsForCall(i int) (lager.Logger, *http.Client) {\n\tfake.verifyMutex.RLock()\n\tdefer fake.verifyMutex.RUnlock()\n\treturn fake.verifyArgsForCall[i].arg1, fake.verifyArgsForCall[i].arg2\n}\n\nfunc (fake *FakeProvider) VerifyReturns(result1 bool, result2 error) {\n\tfake.VerifyStub = nil\n\tfake.verifyReturns = struct {\n\t\tresult1 bool\n\t\tresult2 error\n\t}{result1, result2}\n}\n\nfunc (fake *FakeProvider) VerifyReturnsOnCall(i int, result1 bool, result2 error) {\n\tfake.VerifyStub = nil\n\tif fake.verifyReturnsOnCall == nil {\n\t\tfake.verifyReturnsOnCall = make(map[int]struct {\n\t\t\tresult1 bool\n\t\t\tresult2 error\n\t\t})\n\t}\n\tfake.verifyReturnsOnCall[i] = struct {\n\t\tresult1 bool\n\t\tresult2 error\n\t}{result1, result2}\n}\n\nfunc (fake *FakeProvider) Invocations() map[string][][]interface{} {\n\tfake.invocationsMutex.RLock()\n\tdefer fake.invocationsMutex.RUnlock()\n\tfake.preTokenClientMutex.RLock()\n\tdefer fake.preTokenClientMutex.RUnlock()\n\tfake.authCodeURLMutex.RLock()\n\tdefer fake.authCodeURLMutex.RUnlock()\n\tfake.exchangeMutex.RLock()\n\tdefer fake.exchangeMutex.RUnlock()\n\tfake.clientMutex.RLock()\n\tdefer fake.clientMutex.RUnlock()\n\tfake.verifyMutex.RLock()\n\tdefer fake.verifyMutex.RUnlock()\n\tcopiedInvocations := map[string][][]interface{}{}\n\tfor key, value := range fake.invocations {\n\t\tcopiedInvocations[key] = value\n\t}\n\treturn copiedInvocations\n}\n\nfunc (fake *FakeProvider) recordInvocation(key string, args []interface{}) {\n\tfake.invocationsMutex.Lock()\n\tdefer fake.invocationsMutex.Unlock()\n\tif fake.invocations == nil {\n\t\tfake.invocations = map[string][][]interface{}{}\n\t}\n\tif fake.invocations[key] == nil {\n\t\tfake.invocations[key] = [][]interface{}{}\n\t}\n\tfake.invocations[key] = append(fake.invocations[key], args)\n}\n\nvar _ provider.Provider = new(FakeProvider)\n<|endoftext|>"}
{"text":"<commit_before>package xc\n\nimport (\n\t\"math\"\n\t\"strconv\"\n\n\t\"github.com\/h8liu\/xlang\/parser\"\n)\n\nvar voidNode = &enode{isVoid: true, t: typeVoid}\n\nfunc (ast *AST) prepareBuild() {\n\tast.ir = newIrBlock()\n\tast.scope = newScope()\n\tast.scope.push() \/\/ buildin scope\n\n\t\/\/ TODO: fix this\n\tt := &xtype{isFunc: true}\n\tv := &enode{\n\t\tname: \"print\",\n\t\tt: t,\n\t\tonHeap: true,\n\t\taddr: 0x8000,\n\t}\n\ts := &symbol {\n\t\tname: \"print\",\n\t\tpos: nil,\n\t\ttyp: t,\n\t\tv: v,\n\t}\n\tast.scope.put(s)\n}\n\n\/\/ builds a function\nfunc (ast *AST) buildFunc() {\n\tast.scope.push()\n\n\tb := ast.root.(*ASTBlock)\n\tfor _, s := range b.Nodes {\n\t\tast.buildStmt(s)\n\t}\n\n\tast.scope.pop()\n\n\tast.obj = new(Object)\n\tast.obj.ir = ast.ir\n}\n\n\/\/ builds an expression\nfunc (ast *AST) buildExpr(s ASTNode) *enode {\n\tswitch n := s.(type) {\n\tcase *ASTOpExpr:\n\t\treturn ast.buildOp(n)\n\tcase *ASTCall:\n\t\treturn ast.buildCall(n)\n\tcase *parser.Tok:\n\t\tif n.Type == parser.TypeIdent {\n\t\t\treturn ast.buildVarRef(n)\n\t\t} else if n.Type == parser.TypeInt {\n\t\t\treturn ast.buildIntConst(n)\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ builds an operation\nfunc (ast *AST) buildOp(n *ASTOpExpr) *enode {\n\tconst arithErr = \"arithmetic operation on non-number\"\n\tconst typeErr = \"type mismatch on operation %q\"\n\n\tif n.A == nil {\n\t\t\/\/ unary op\n\t\tswitch n.Op.Lit {\n\t\tcase \"+\":\n\t\t\tret := ast.buildExpr(n.B)\n\t\t\tif ret == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif !ret.typ().isNum() {\n\t\t\t\tast.errs.Log(n.Op.Pos, arithErr)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn ret\n\t\tcase \"-\":\n\t\t\tb := ast.buildExpr(n.B)\n\t\t\tif b == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif !b.typ().isNum() {\n\t\t\t\tast.errs.Log(n.Op.Pos, arithErr)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tret := ast.newTemp(b.typ())\n\t\t\tast.ir.addUnaryOp(ret, \"-\", b)\n\t\t\treturn ret\n\t\tdefault:\n\t\t\tpanic(\"unknown op\")\n\t\t}\n\t}\n\n\tswitch n.Op.Lit {\n\tcase \"+\", \"-\":\n\t\ta := ast.buildExpr(n.A)\n\t\tb := ast.buildExpr(n.B)\n\t\tif a == nil || b == nil {\n\t\t\treturn nil\n\t\t}\n\t\tif !a.typ().isNum() {\n\t\t\tast.errs.Log(n.Op.Pos, arithErr)\n\t\t\treturn nil\n\t\t}\n\t\tif !a.typ().numEquals(b.typ()) {\n\t\t\tast.errs.Log(n.Op.Pos, typeErr, n.Op.Lit)\n\t\t\treturn nil\n\t\t}\n\n\t\tret := ast.newTemp(a.typ())\n\t\tast.ir.addBinaryOp(ret, a, n.Op.Lit, b)\n\t\treturn ret\n\tdefault:\n\t\tpanic(\"unknown op\")\n\t}\n}\n\n\/\/ builds a function call\nfunc (ast *AST) buildCall(n *ASTCall) *enode {\n\tf := ast.buildExpr(n.Func)\n\tif f == nil {\n\t\treturn nil\n\t}\n\n\tvar args []*enode\n\tfor _, p := range n.Paras {\n\t\tr := ast.buildExpr(p)\n\t\tif r == nil {\n\t\t\treturn nil\n\t\t}\n\t\targs = append(args, r)\n\t}\n\n\t\/\/ TODO: function signature type check\n\t\/\/ we now assume it is always print with one parameter\n\n\tif len(n.Paras) != 1 {\n\t\tast.errs.Log(n.Lparen.Pos, \"print only accepts one paramter\")\n\t\treturn nil\n\t}\n\n\tast.ir.addCall(voidNode, f, args...)\n\treturn voidNode\n}\n\n\/\/ builds a variable reference\nfunc (ast *AST) buildVarRef(t *parser.Tok) *enode {\n\tfound := ast.scope.find(t.Lit)\n\tif found == nil {\n\t\tast.errs.Log(t.Pos, \"%s not defined\", t.Lit)\n\t\treturn nil\n\t}\n\n\treturn found.v\n}\n\n\/\/ builds a integer constant.\n\/\/ for integer within int32 range, the type is int32\n\/\/ otherwise, for integer within uint32 range, the type is uint32\n\/\/ otherwise, it is out of range and invalid\nfunc (ast *AST) buildIntConst(t *parser.Tok) *enode {\n\tv, e := strconv.ParseInt(t.Lit, 0, 64)\n\tif e != nil {\n\t\tast.errs.Log(t.Pos, \"invalid integer\")\n\t\treturn nil\n\t}\n\n\tif v > math.MaxUint32 || v < math.MinInt32 {\n\t\tast.errs.Log(t.Pos, \"integer out of range\")\n\t\treturn nil\n\t}\n\n\tif v > math.MaxInt32 {\n\t\treturn ast.newConst(typeUint, int32(v))\n\t}\n\n\treturn ast.newConst(typeInt, int32(v))\n}\n\n\/\/ build assignment\nfunc (ast *AST) buildAssign(n *ASTAssign) {\n\tnleft := len(n.LHS)\n\tnright := len(n.RHS)\n\tif nleft != nright {\n\t\tast.errs.Log(n.Pos, \"expect %d on left hand side, got %d\",\n\t\t\tnright, nleft,\n\t\t)\n\t\treturn\n\t}\n\n\tvar temps []*enode\n\tfor _, expr := range n.RHS {\n\t\tt := ast.buildExpr(expr)\n\t\tif t == nil {\n\t\t\treturn\n\t\t}\n\t\ttemps = append(temps, t)\n\t}\n\n\tfor i, d := range n.LHS {\n\t\tdest := ast.buildExpr(d)\n\t\tif dest == nil {\n\t\t\treturn\n\t\t}\n\n\t\tif !dest.addressable() {\n\t\t\tast.errs.Log(n.Pos, \"assigning to not addressable\")\n\t\t\treturn\n\t\t}\n\n\t\tdestType := dest.typ()\n\t\tsrc := temps[i]\n\t\tsrcType := src.typ()\n\t\tif !srcType.canAssignTo(destType) {\n\t\t\tast.errs.Log(n.Pos, \"cannot assign %s to %s\", srcType, destType)\n\t\t\treturn\n\t\t}\n\n\t\tast.ir.addAssign(dest, src)\n\t}\n}\n\n\/\/ build variable declaration\nfunc (ast *AST) buildVarDecl(n *ASTVarDecl) {\n\tvar src *enode\n\tif n.Expr != nil {\n\t\tsrc = ast.buildExpr(n.Expr)\n\t\tif src == nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\tvarName := n.Name.Lit\n\tpre := ast.scope.findTop(varName)\n\tif pre != nil {\n\t\tast.errs.Log(n.Name.Pos, \"%s already declared\", n.Name.Lit)\n\t\tast.errs.Log(pre.pos, \"  previously declared here\")\n\t\treturn\n\t}\n\n\ttyp := typeInt \/\/ TODO: parse the type\n\tv := ast.newVar(varName, typ)\n\tsym := &symbol{\n\t\tname: varName,\n\t\tpos:  n.Name.Pos,\n\t\ttyp:  typ,\n\t\tv:    v,\n\t}\n\tast.scope.put(sym)\n\n\tif n.Expr != nil {\n\t\tif src == nil {\n\t\t\treturn\n\t\t}\n\t\tsrcType := src.typ()\n\t\tdestType := v.typ()\n\n\t\tif !srcType.canAssignTo(destType) {\n\t\t\tast.errs.Log(n.Name.Pos, \"cannot assign %s to %s\", srcType, destType)\n\t\t\treturn\n\t\t}\n\n\t\tast.ir.addAssign(v, src)\n\t} else {\n\t\tast.ir.addAssign(v, ast.newZero(v.typ()))\n\t}\n}\n\nfunc (ast *AST) buildExprStmt(n *ASTExprStmt) {\n\tast.buildExpr(n.Expr)\n}\n\n\/\/ build a statement\nfunc (ast *AST) buildStmt(s ASTNode) {\n\tswitch n := s.(type) {\n\tcase *ASTAssign:\n\t\tast.buildAssign(n)\n\tcase *ASTVarDecl:\n\t\tast.buildVarDecl(n)\n\tcase *ASTExprStmt:\n\t\tast.buildExprStmt(n)\n\tdefault:\n\t\tpanic(\"invalid statement\")\n\t}\n}\n<commit_msg>build<commit_after>package xc\n\nimport (\n\t\"math\"\n\t\"strconv\"\n\n\t\"github.com\/h8liu\/xlang\/parser\"\n)\n\nvar voidNode = &enode{isVoid: true, t: typeVoid}\n\nfunc (ast *AST) prepareBuild() {\n\tast.ir = newIrBlock()\n\tast.scope = newScope()\n\tast.scope.push() \/\/ buildin scope\n\n\t\/\/ TODO: fix this\n\tt := &xtype{isFunc: true}\n\tv := &enode{\n\t\tname:   \"print\",\n\t\tt:      t,\n\t\tonHeap: true,\n\t\taddr:   0x8000,\n\t}\n\ts := &symbol{\n\t\tname: \"print\",\n\t\tpos:  nil,\n\t\ttyp:  t,\n\t\tv:    v,\n\t}\n\tast.scope.put(s)\n}\n\n\/\/ builds a function\nfunc (ast *AST) buildFunc() {\n\tast.scope.push()\n\n\tb := ast.root.(*ASTBlock)\n\tfor _, s := range b.Nodes {\n\t\tast.buildStmt(s)\n\t}\n\n\tast.scope.pop()\n\n\tast.obj = new(Object)\n\tast.obj.ir = ast.ir\n}\n\n\/\/ builds an expression\nfunc (ast *AST) buildExpr(s ASTNode) *enode {\n\tswitch n := s.(type) {\n\tcase *ASTOpExpr:\n\t\treturn ast.buildOp(n)\n\tcase *ASTCall:\n\t\treturn ast.buildCall(n)\n\tcase *parser.Tok:\n\t\tif n.Type == parser.TypeIdent {\n\t\t\treturn ast.buildVarRef(n)\n\t\t} else if n.Type == parser.TypeInt {\n\t\t\treturn ast.buildIntConst(n)\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ builds an operation\nfunc (ast *AST) buildOp(n *ASTOpExpr) *enode {\n\tconst arithErr = \"arithmetic operation on non-number\"\n\tconst typeErr = \"type mismatch on operation %q\"\n\n\tif n.A == nil {\n\t\t\/\/ unary op\n\t\tswitch n.Op.Lit {\n\t\tcase \"+\":\n\t\t\tret := ast.buildExpr(n.B)\n\t\t\tif ret == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif !ret.typ().isNum() {\n\t\t\t\tast.errs.Log(n.Op.Pos, arithErr)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn ret\n\t\tcase \"-\":\n\t\t\tb := ast.buildExpr(n.B)\n\t\t\tif b == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif !b.typ().isNum() {\n\t\t\t\tast.errs.Log(n.Op.Pos, arithErr)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tret := ast.newTemp(b.typ())\n\t\t\tast.ir.addUnaryOp(ret, \"-\", b)\n\t\t\treturn ret\n\t\tdefault:\n\t\t\tpanic(\"unknown op\")\n\t\t}\n\t}\n\n\tswitch n.Op.Lit {\n\tcase \"+\", \"-\":\n\t\ta := ast.buildExpr(n.A)\n\t\tb := ast.buildExpr(n.B)\n\t\tif a == nil || b == nil {\n\t\t\treturn nil\n\t\t}\n\t\tif !a.typ().isNum() {\n\t\t\tast.errs.Log(n.Op.Pos, arithErr)\n\t\t\treturn nil\n\t\t}\n\t\tif !a.typ().numEquals(b.typ()) {\n\t\t\tast.errs.Log(n.Op.Pos, typeErr, n.Op.Lit)\n\t\t\treturn nil\n\t\t}\n\n\t\tret := ast.newTemp(a.typ())\n\t\tast.ir.addBinaryOp(ret, a, n.Op.Lit, b)\n\t\treturn ret\n\tdefault:\n\t\tpanic(\"unknown op\")\n\t}\n}\n\n\/\/ builds a function call\nfunc (ast *AST) buildCall(n *ASTCall) *enode {\n\tf := ast.buildExpr(n.Func)\n\tif f == nil {\n\t\treturn nil\n\t}\n\n\tvar args []*enode\n\tfor _, p := range n.Paras {\n\t\tr := ast.buildExpr(p)\n\t\tif r == nil {\n\t\t\treturn nil\n\t\t}\n\t\targs = append(args, r)\n\t}\n\n\t\/\/ TODO: function signature type check\n\t\/\/ we now assume it is always print with one parameter\n\n\tif len(n.Paras) != 1 {\n\t\tast.errs.Log(n.Lparen.Pos, \"print only accepts one paramter\")\n\t\treturn nil\n\t}\n\n\tast.ir.addCall(voidNode, f, args...)\n\treturn voidNode\n}\n\n\/\/ builds a variable reference\nfunc (ast *AST) buildVarRef(t *parser.Tok) *enode {\n\tfound := ast.scope.find(t.Lit)\n\tif found == nil {\n\t\tast.errs.Log(t.Pos, \"%s not defined\", t.Lit)\n\t\treturn nil\n\t}\n\n\treturn found.v\n}\n\n\/\/ builds a integer constant.\n\/\/ for integer within int32 range, the type is int32\n\/\/ otherwise, for integer within uint32 range, the type is uint32\n\/\/ otherwise, it is out of range and invalid\nfunc (ast *AST) buildIntConst(t *parser.Tok) *enode {\n\tv, e := strconv.ParseInt(t.Lit, 0, 64)\n\tif e != nil {\n\t\tast.errs.Log(t.Pos, \"invalid integer\")\n\t\treturn nil\n\t}\n\n\tif v > math.MaxUint32 || v < math.MinInt32 {\n\t\tast.errs.Log(t.Pos, \"integer out of range\")\n\t\treturn nil\n\t}\n\n\tif v > math.MaxInt32 {\n\t\treturn ast.newConst(typeUint, int32(v))\n\t}\n\n\treturn ast.newConst(typeInt, int32(v))\n}\n\n\/\/ build assignment\nfunc (ast *AST) buildAssign(n *ASTAssign) {\n\tnleft := len(n.LHS)\n\tnright := len(n.RHS)\n\tif nleft != nright {\n\t\tast.errs.Log(n.Pos, \"expect %d on left hand side, got %d\",\n\t\t\tnright, nleft,\n\t\t)\n\t\treturn\n\t}\n\n\tvar temps []*enode\n\tfor _, expr := range n.RHS {\n\t\tt := ast.buildExpr(expr)\n\t\tif t == nil {\n\t\t\treturn\n\t\t}\n\t\ttemps = append(temps, t)\n\t}\n\n\tfor i, d := range n.LHS {\n\t\tdest := ast.buildExpr(d)\n\t\tif dest == nil {\n\t\t\treturn\n\t\t}\n\n\t\tif !dest.addressable() {\n\t\t\tast.errs.Log(n.Pos, \"assigning to not addressable\")\n\t\t\treturn\n\t\t}\n\n\t\tdestType := dest.typ()\n\t\tsrc := temps[i]\n\t\tsrcType := src.typ()\n\t\tif !srcType.canAssignTo(destType) {\n\t\t\tast.errs.Log(n.Pos, \"cannot assign %s to %s\", srcType, destType)\n\t\t\treturn\n\t\t}\n\n\t\tast.ir.addAssign(dest, src)\n\t}\n}\n\n\/\/ build variable declaration\nfunc (ast *AST) buildVarDecl(n *ASTVarDecl) {\n\tvar src *enode\n\tif n.Expr != nil {\n\t\tsrc = ast.buildExpr(n.Expr)\n\t\tif src == nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\tvarName := n.Name.Lit\n\tpre := ast.scope.findTop(varName)\n\tif pre != nil {\n\t\tast.errs.Log(n.Name.Pos, \"%s already declared\", n.Name.Lit)\n\t\tast.errs.Log(pre.pos, \"  previously declared here\")\n\t\treturn\n\t}\n\n\ttyp := typeInt \/\/ TODO: parse the type\n\tv := ast.newVar(varName, typ)\n\tsym := &symbol{\n\t\tname: varName,\n\t\tpos:  n.Name.Pos,\n\t\ttyp:  typ,\n\t\tv:    v,\n\t}\n\tast.scope.put(sym)\n\n\tif n.Expr != nil {\n\t\tif src == nil {\n\t\t\treturn\n\t\t}\n\t\tsrcType := src.typ()\n\t\tdestType := v.typ()\n\n\t\tif !srcType.canAssignTo(destType) {\n\t\t\tast.errs.Log(n.Name.Pos, \"cannot assign %s to %s\", srcType, destType)\n\t\t\treturn\n\t\t}\n\n\t\tast.ir.addAssign(v, src)\n\t} else {\n\t\tast.ir.addAssign(v, ast.newZero(v.typ()))\n\t}\n}\n\nfunc (ast *AST) buildExprStmt(n *ASTExprStmt) {\n\tast.buildExpr(n.Expr)\n}\n\n\/\/ build a statement\nfunc (ast *AST) buildStmt(s ASTNode) {\n\tswitch n := s.(type) {\n\tcase *ASTAssign:\n\t\tast.buildAssign(n)\n\tcase *ASTVarDecl:\n\t\tast.buildVarDecl(n)\n\tcase *ASTExprStmt:\n\t\tast.buildExprStmt(n)\n\tdefault:\n\t\tpanic(\"invalid statement\")\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/**\n *  Copyright 2014 Paul Querna\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *\/\n\npackage ffjsoninception\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n)\n\nfunc typeInInception(ic *Inception, typ reflect.Type) bool {\n\tfor _, v := range ic.objs {\n\t\tif v.Typ == typ {\n\t\t\treturn true\n\t\t}\n\t\tif typ.Kind() == reflect.Ptr {\n\t\t\tif v.Typ == typ.Elem() {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc getOmitEmpty(ic *Inception, sf *StructField) string {\n\tswitch sf.Typ.Kind() {\n\n\tcase reflect.Array, reflect.Map, reflect.Slice, reflect.String:\n\t\treturn \"if len(mj.\" + sf.Name + \") != 0 {\" + \"\\n\"\n\n\tcase reflect.Int,\n\t\treflect.Int8,\n\t\treflect.Int16,\n\t\treflect.Int32,\n\t\treflect.Int64,\n\t\treflect.Uint,\n\t\treflect.Uint8,\n\t\treflect.Uint16,\n\t\treflect.Uint32,\n\t\treflect.Uint64,\n\t\treflect.Uintptr,\n\t\treflect.Float32,\n\t\treflect.Float64:\n\t\treturn \"if mj.\" + sf.Name + \" != 0 {\" + \"\\n\"\n\n\tcase reflect.Bool:\n\t\treturn \"if mj.\" + sf.Name + \" != false {\" + \"\\n\"\n\n\tcase reflect.Interface, reflect.Ptr:\n\t\treturn \"if mj.\" + sf.Name + \" != nil {\" + \"\\n\"\n\n\tdefault:\n\t\t\/\/ TODO(pquerna): fix types\n\t\treturn \"if true {\" + \"\\n\"\n\t}\n}\n\nfunc getGetInnerValue(ic *Inception, name string, typ reflect.Type, ptr bool) string {\n\tvar out = \"\"\n\n\tif typ.Implements(marshalerBufType) ||\n\t\ttypeInInception(ic, typ) ||\n\t\ttyp.Implements(marshalerType) ||\n\t\treflect.PtrTo(typ).Implements(marshalerType) {\n\n\t\tout += tplStr(encodeTpl[\"handleMarshaler\"], handleMarshaler{\n\t\t\tIC:             ic,\n\t\t\tName:           name,\n\t\t\tMarshalJSONBuf: typ.Implements(marshalerBufType) || typeInInception(ic, typ),\n\t\t\tMarshaler:      typ.Implements(marshalerType) || reflect.PtrTo(typ).Implements(marshalerType),\n\t\t})\n\t\treturn out\n\t}\n\n\tptname := name\n\tif ptr {\n\t\tptname = \"*\" + name\n\t}\n\n\tswitch typ.Kind() {\n\tcase reflect.Int,\n\t\treflect.Int8,\n\t\treflect.Int16,\n\t\treflect.Int32,\n\t\treflect.Int64:\n\t\tic.OutputImports[`fflib \"github.com\/pquerna\/ffjson\/fflib\/v1\"`] = true\n\t\tout += \"fflib.FormatBits(&scratch, buf, uint64(\" + ptname + \"), 10, \" + ptname + \" < 0)\" + \"\\n\"\n\tcase reflect.Uint,\n\t\treflect.Uint8,\n\t\treflect.Uint16,\n\t\treflect.Uint32,\n\t\treflect.Uint64,\n\t\treflect.Uintptr:\n\t\tic.OutputImports[`fflib \"github.com\/pquerna\/ffjson\/fflib\/v1\"`] = true\n\t\tout += \"fflib.FormatBits(&scratch, buf, uint64(\" + ptname + \"), 10, false)\" + \"\\n\"\n\tcase reflect.Float32:\n\t\tic.OutputImports[`\"strconv\"`] = true\n\t\tout += \"buf.Write(strconv.AppendFloat([]byte{}, float64(\" + ptname + \"), 'f', 10, 32))\" + \"\\n\"\n\tcase reflect.Float64:\n\t\tic.OutputImports[`\"strconv\"`] = true\n\t\tout += \"buf.Write(strconv.AppendFloat([]byte{}, \" + ptname + \", 'f', 10, 64))\" + \"\\n\"\n\tcase reflect.Array,\n\t\treflect.Slice:\n\t\tout += \"if \" + name + \"!= nil {\" + \"\\n\"\n\t\tout += \"buf.WriteString(`[`)\" + \"\\n\"\n\t\tout += \"for i, v := range \" + name + \"{\" + \"\\n\"\n\t\tout += \"if i != 0 {\" + \"\\n\"\n\t\tout += \"buf.WriteString(`,`)\" + \"\\n\"\n\t\tout += \"}\" + \"\\n\"\n\t\tout += getGetInnerValue(ic, \"v\", typ.Elem(), false)\n\t\tout += \"}\" + \"\\n\"\n\t\tout += \"buf.WriteString(`]`)\" + \"\\n\"\n\t\tout += \"} else {\" + \"\\n\"\n\t\tout += \"buf.WriteString(`null`)\" + \"\\n\"\n\t\tout += \"}\" + \"\\n\"\n\tcase reflect.String:\n\t\tic.OutputImports[`fflib \"github.com\/pquerna\/ffjson\/fflib\/v1\"`] = true\n\t\tout += \"fflib.WriteJsonString(buf, \" + ptname + \")\" + \"\\n\"\n\tcase reflect.Ptr:\n\t\tout += \"if \" + name + \"!= nil {\" + \"\\n\"\n\t\tswitch typ.Elem().Kind() {\n\t\tcase reflect.Struct:\n\t\t\tout += getGetInnerValue(ic, name, typ.Elem(), false)\n\t\tdefault:\n\t\t\tout += getGetInnerValue(ic, \"*\"+name, typ.Elem(), false)\n\t\t}\n\t\tout += \"} else {\" + \"\\n\"\n\t\tout += \"buf.WriteString(`null`)\" + \"\\n\"\n\t\tout += \"}\" + \"\\n\"\n\tcase reflect.Bool:\n\t\tout += \"if \" + ptname + \" {\" + \"\\n\"\n\t\tout += \"buf.WriteString(`true`)\" + \"\\n\"\n\t\tout += \"} else {\" + \"\\n\"\n\t\tout += \"buf.WriteString(`false`)\" + \"\\n\"\n\t\tout += \"}\" + \"\\n\"\n\tcase reflect.Interface:\n\t\tic.OutputImports[`\"encoding\/json\"`] = true\n\t\tout += fmt.Sprintf(\"\/* Interface types must use runtime reflection. type=%v kind=%v *\/\\n\", typ, typ.Kind())\n\t\tout += \"obj, err = json.Marshal(\" + name + \")\" + \"\\n\"\n\t\tout += \"if err != nil {\" + \"\\n\"\n\t\tout += \"  return err\" + \"\\n\"\n\t\tout += \"}\" + \"\\n\"\n\t\tout += \"buf.Write(obj)\" + \"\\n\"\n\tdefault:\n\t\tic.OutputImports[`\"encoding\/json\"`] = true\n\t\tout += fmt.Sprintf(\"\/* Falling back. type=%v kind=%v *\/\\n\", typ, typ.Kind())\n\t\tout += \"obj, err = json.Marshal(\" + name + \")\" + \"\\n\"\n\t\tout += \"if err != nil {\" + \"\\n\"\n\t\tout += \"  return err\" + \"\\n\"\n\t\tout += \"}\" + \"\\n\"\n\t\tout += \"buf.Write(obj)\" + \"\\n\"\n\t}\n\n\treturn out\n}\n\nfunc getValue(ic *Inception, sf *StructField) string {\n\treturn getGetInnerValue(ic, \"mj.\"+sf.Name, sf.Typ, sf.Pointer)\n}\n\nfunc p2(v uint32) uint32 {\n\tv--\n\tv |= v >> 1\n\tv |= v >> 2\n\tv |= v >> 4\n\tv |= v >> 8\n\tv |= v >> 16\n\tv++\n\treturn v\n}\n\nfunc getTotalSize(si *StructInfo) uintptr {\n\trv := si.Typ.Size()\n\tfor _, f := range si.Fields {\n\t\trv += f.Typ.Size()\n\t}\n\treturn rv\n}\n\nfunc getBufGrowSize(si *StructInfo) uint32 {\n\n\t\/\/ TOOD(pquerna): automatically calc a better grow size based on history\n\t\/\/ of a struct.\n\treturn p2(uint32(float32(getTotalSize(si)) * 3.0))\n}\n\nfunc isInt(t reflect.Type) bool {\n\tif t.Kind() >= reflect.Int && t.Kind() <= reflect.Uintptr {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc CreateMarshalJSON(ic *Inception, si *StructInfo) error {\n\tconditionalWrites := false\n\tneedScratch := false\n\tout := \"\"\n\n\tic.OutputImports[`\"bytes\"`] = true\n\n\tout += `func (mj *` + si.Name + `) MarshalJSON() ([]byte, error) {` + \"\\n\"\n\tout += `var buf fflib.Buffer` + \"\\n\"\n\n\tout += fmt.Sprintf(\"buf.Grow(%d)\\n\", getBufGrowSize(si))\n\tout += `err := mj.MarshalJSONBuf(&buf)` + \"\\n\"\n\tout += `if err != nil {` + \"\\n\"\n\tout += \"  return nil, err\" + \"\\n\"\n\tout += `}` + \"\\n\"\n\tout += `return buf.Bytes(), nil` + \"\\n\"\n\tout += `}` + \"\\n\"\n\n\tfor _, f := range si.Fields {\n\t\tif isInt(f.Typ) {\n\t\t\tneedScratch = true\n\t\t}\n\t}\n\n\tfor _, f := range si.Fields {\n\t\tif f.OmitEmpty || f.Pointer {\n\t\t\t\/\/ if we have >= 1 non-conditional write, we can\n\t\t\t\/\/ assume our trailing logic is reaosnable.\n\t\t\tif conditionalWrites {\n\t\t\t\tconditionalWrites = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tconditionalWrites = true\n\t\t}\n\t}\n\n\tout += `func (mj *` + si.Name + `) MarshalJSONBuf(buf fflib.EncodingBuffer) (error) {` + \"\\n\"\n\tout += `var err error` + \"\\n\"\n\tout += `var obj []byte` + \"\\n\"\n\tif needScratch {\n\t\tout += `var scratch fflib.FormatBitsScratch` + \"\\n\"\n\t}\n\n\tif conditionalWrites {\n\t\tout += `var wroteAnyFields bool = false` + \"\\n\"\n\t}\n\n\tout += `_ = obj` + \"\\n\"\n\tout += `_ = err` + \"\\n\"\n\tout += \"buf.WriteString(`{`)\" + \"\\n\"\n\n\tfor _, f := range si.Fields {\n\t\tif f.OmitEmpty {\n\t\t\tout += getOmitEmpty(ic, f)\n\t\t}\n\n\t\tif f.Pointer {\n\t\t\tout += \"if mj.\" + f.Name + \" != nil {\" + \"\\n\"\n\t\t}\n\n\t\tif conditionalWrites {\n\t\t\tout += `wroteAnyFields = true` + \"\\n\"\n\t\t}\n\n\t\t\/\/ JsonName is already escaped and quoted.\n\t\tout += \"buf.WriteString(`\" + f.JsonName + \":`)\" + \"\\n\"\n\t\tout += getValue(ic, f)\n\t\tout += \"buf.WriteString(`, `)\" + \"\\n\"\n\n\t\tif f.Pointer {\n\t\t\tout += \"}\" + \"\\n\"\n\t\t}\n\n\t\tif f.OmitEmpty {\n\t\t\tout += \"}\" + \"\\n\"\n\t\t}\n\t}\n\n\tif conditionalWrites {\n\t\tout += `if wroteAnyFields {` + \"\\n\"\n\t\tout += \"  \tbuf.Rewind(2)\" + \"\\n\"\n\t\tout += \"\tbuf.WriteByte('}')\" + \"\\n\"\n\t\tout += `} else {` + \"\\n\"\n\t\tout += \"\tbuf.WriteByte('}')\" + \"\\n\"\n\t\tout += `}` + \"\\n\"\n\t} else {\n\t\tout += \"buf.Rewind(2)\" + \"\\n\"\n\t\tout += \"buf.WriteByte('}')\" + \"\\n\"\n\t}\n\n\tout += `return nil` + \"\\n\"\n\tout += `}` + \"\\n\"\n\tic.OutputFuncs = append(ic.OutputFuncs, out)\n\treturn nil\n}\n<commit_msg>improve size estimation<commit_after>\/**\n *  Copyright 2014 Paul Querna\n *\n *  Licensed under the Apache License, Version 2.0 (the \"License\");\n *  you may not use this file except in compliance with the License.\n *  You may obtain a copy of the License at\n *\n *      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *  Unless required by applicable law or agreed to in writing, software\n *  distributed under the License is distributed on an \"AS IS\" BASIS,\n *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *  See the License for the specific language governing permissions and\n *  limitations under the License.\n *\n *\/\n\npackage ffjsoninception\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n)\n\nfunc typeInInception(ic *Inception, typ reflect.Type) bool {\n\tfor _, v := range ic.objs {\n\t\tif v.Typ == typ {\n\t\t\treturn true\n\t\t}\n\t\tif typ.Kind() == reflect.Ptr {\n\t\t\tif v.Typ == typ.Elem() {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc getOmitEmpty(ic *Inception, sf *StructField) string {\n\tswitch sf.Typ.Kind() {\n\n\tcase reflect.Array, reflect.Map, reflect.Slice, reflect.String:\n\t\treturn \"if len(mj.\" + sf.Name + \") != 0 {\" + \"\\n\"\n\n\tcase reflect.Int,\n\t\treflect.Int8,\n\t\treflect.Int16,\n\t\treflect.Int32,\n\t\treflect.Int64,\n\t\treflect.Uint,\n\t\treflect.Uint8,\n\t\treflect.Uint16,\n\t\treflect.Uint32,\n\t\treflect.Uint64,\n\t\treflect.Uintptr,\n\t\treflect.Float32,\n\t\treflect.Float64:\n\t\treturn \"if mj.\" + sf.Name + \" != 0 {\" + \"\\n\"\n\n\tcase reflect.Bool:\n\t\treturn \"if mj.\" + sf.Name + \" != false {\" + \"\\n\"\n\n\tcase reflect.Interface, reflect.Ptr:\n\t\treturn \"if mj.\" + sf.Name + \" != nil {\" + \"\\n\"\n\n\tdefault:\n\t\t\/\/ TODO(pquerna): fix types\n\t\treturn \"if true {\" + \"\\n\"\n\t}\n}\n\nfunc getGetInnerValue(ic *Inception, name string, typ reflect.Type, ptr bool) string {\n\tvar out = \"\"\n\n\tif typ.Implements(marshalerBufType) ||\n\t\ttypeInInception(ic, typ) ||\n\t\ttyp.Implements(marshalerType) ||\n\t\treflect.PtrTo(typ).Implements(marshalerType) {\n\n\t\tout += tplStr(encodeTpl[\"handleMarshaler\"], handleMarshaler{\n\t\t\tIC:             ic,\n\t\t\tName:           name,\n\t\t\tMarshalJSONBuf: typ.Implements(marshalerBufType) || typeInInception(ic, typ),\n\t\t\tMarshaler:      typ.Implements(marshalerType) || reflect.PtrTo(typ).Implements(marshalerType),\n\t\t})\n\t\treturn out\n\t}\n\n\tptname := name\n\tif ptr {\n\t\tptname = \"*\" + name\n\t}\n\n\tswitch typ.Kind() {\n\tcase reflect.Int,\n\t\treflect.Int8,\n\t\treflect.Int16,\n\t\treflect.Int32,\n\t\treflect.Int64:\n\t\tic.OutputImports[`fflib \"github.com\/pquerna\/ffjson\/fflib\/v1\"`] = true\n\t\tout += \"fflib.FormatBits(&scratch, buf, uint64(\" + ptname + \"), 10, \" + ptname + \" < 0)\" + \"\\n\"\n\tcase reflect.Uint,\n\t\treflect.Uint8,\n\t\treflect.Uint16,\n\t\treflect.Uint32,\n\t\treflect.Uint64,\n\t\treflect.Uintptr:\n\t\tic.OutputImports[`fflib \"github.com\/pquerna\/ffjson\/fflib\/v1\"`] = true\n\t\tout += \"fflib.FormatBits(&scratch, buf, uint64(\" + ptname + \"), 10, false)\" + \"\\n\"\n\tcase reflect.Float32:\n\t\tic.OutputImports[`\"strconv\"`] = true\n\t\tout += \"buf.Write(strconv.AppendFloat([]byte{}, float64(\" + ptname + \"), 'f', 10, 32))\" + \"\\n\"\n\tcase reflect.Float64:\n\t\tic.OutputImports[`\"strconv\"`] = true\n\t\tout += \"buf.Write(strconv.AppendFloat([]byte{}, \" + ptname + \", 'f', 10, 64))\" + \"\\n\"\n\tcase reflect.Array,\n\t\treflect.Slice:\n\t\tout += \"if \" + name + \"!= nil {\" + \"\\n\"\n\t\tout += \"buf.WriteString(`[`)\" + \"\\n\"\n\t\tout += \"for i, v := range \" + name + \"{\" + \"\\n\"\n\t\tout += \"if i != 0 {\" + \"\\n\"\n\t\tout += \"buf.WriteString(`,`)\" + \"\\n\"\n\t\tout += \"}\" + \"\\n\"\n\t\tout += getGetInnerValue(ic, \"v\", typ.Elem(), false)\n\t\tout += \"}\" + \"\\n\"\n\t\tout += \"buf.WriteString(`]`)\" + \"\\n\"\n\t\tout += \"} else {\" + \"\\n\"\n\t\tout += \"buf.WriteString(`null`)\" + \"\\n\"\n\t\tout += \"}\" + \"\\n\"\n\tcase reflect.String:\n\t\tic.OutputImports[`fflib \"github.com\/pquerna\/ffjson\/fflib\/v1\"`] = true\n\t\tout += \"fflib.WriteJsonString(buf, \" + ptname + \")\" + \"\\n\"\n\tcase reflect.Ptr:\n\t\tout += \"if \" + name + \"!= nil {\" + \"\\n\"\n\t\tswitch typ.Elem().Kind() {\n\t\tcase reflect.Struct:\n\t\t\tout += getGetInnerValue(ic, name, typ.Elem(), false)\n\t\tdefault:\n\t\t\tout += getGetInnerValue(ic, \"*\"+name, typ.Elem(), false)\n\t\t}\n\t\tout += \"} else {\" + \"\\n\"\n\t\tout += \"buf.WriteString(`null`)\" + \"\\n\"\n\t\tout += \"}\" + \"\\n\"\n\tcase reflect.Bool:\n\t\tout += \"if \" + ptname + \" {\" + \"\\n\"\n\t\tout += \"buf.WriteString(`true`)\" + \"\\n\"\n\t\tout += \"} else {\" + \"\\n\"\n\t\tout += \"buf.WriteString(`false`)\" + \"\\n\"\n\t\tout += \"}\" + \"\\n\"\n\tcase reflect.Interface:\n\t\tic.OutputImports[`\"encoding\/json\"`] = true\n\t\tout += fmt.Sprintf(\"\/* Interface types must use runtime reflection. type=%v kind=%v *\/\\n\", typ, typ.Kind())\n\t\tout += \"obj, err = json.Marshal(\" + name + \")\" + \"\\n\"\n\t\tout += \"if err != nil {\" + \"\\n\"\n\t\tout += \"  return err\" + \"\\n\"\n\t\tout += \"}\" + \"\\n\"\n\t\tout += \"buf.Write(obj)\" + \"\\n\"\n\tdefault:\n\t\tic.OutputImports[`\"encoding\/json\"`] = true\n\t\tout += fmt.Sprintf(\"\/* Falling back. type=%v kind=%v *\/\\n\", typ, typ.Kind())\n\t\tout += \"obj, err = json.Marshal(\" + name + \")\" + \"\\n\"\n\t\tout += \"if err != nil {\" + \"\\n\"\n\t\tout += \"  return err\" + \"\\n\"\n\t\tout += \"}\" + \"\\n\"\n\t\tout += \"buf.Write(obj)\" + \"\\n\"\n\t}\n\n\treturn out\n}\n\nfunc getValue(ic *Inception, sf *StructField) string {\n\treturn getGetInnerValue(ic, \"mj.\"+sf.Name, sf.Typ, sf.Pointer)\n}\n\nfunc p2(v uint32) uint32 {\n\tv--\n\tv |= v >> 1\n\tv |= v >> 2\n\tv |= v >> 4\n\tv |= v >> 8\n\tv |= v >> 16\n\tv++\n\treturn v\n}\n\nfunc getTypeSize(t reflect.Type) uint32 {\n\tswitch t.Kind() {\n\tcase reflect.String:\n\t\t\/\/ TODO: consider runtime analysis.\n\t\treturn 32\n\tcase reflect.Array, reflect.Map, reflect.Slice:\n\t\t\/\/ TODO: consider runtime analysis.\n\t\treturn 4 * getTypeSize(t.Elem())\n\tcase reflect.Int,\n\t\treflect.Int8,\n\t\treflect.Int16,\n\t\treflect.Int32,\n\t\treflect.Uint,\n\t\treflect.Uint8,\n\t\treflect.Uint16,\n\t\treflect.Uint32:\n\t\treturn 8\n\tcase reflect.Int64,\n\t\treflect.Uint64,\n\t\treflect.Uintptr:\n\t\treturn 16\n\tcase reflect.Float32,\n\t\treflect.Float64:\n\t\treturn 16\n\tcase reflect.Bool:\n\t\treturn 4\n\tcase reflect.Ptr:\n\t\treturn getTypeSize(t.Elem())\n\tdefault:\n\t\treturn 16\n\t}\n}\n\nfunc getTotalSize(si *StructInfo) uint32 {\n\trv := uint32(si.Typ.Size())\n\tfor _, f := range si.Fields {\n\t\trv += getTypeSize(f.Typ)\n\t}\n\treturn rv\n}\n\nfunc getBufGrowSize(si *StructInfo) uint32 {\n\n\t\/\/ TOOD(pquerna): automatically calc a better grow size based on history\n\t\/\/ of a struct.\n\treturn p2(getTotalSize(si))\n}\n\nfunc isInt(t reflect.Type) bool {\n\tif t.Kind() >= reflect.Int && t.Kind() <= reflect.Uintptr {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc CreateMarshalJSON(ic *Inception, si *StructInfo) error {\n\tconditionalWrites := false\n\tneedScratch := false\n\tout := \"\"\n\n\tic.OutputImports[`\"bytes\"`] = true\n\n\tout += `func (mj *` + si.Name + `) MarshalJSON() ([]byte, error) {` + \"\\n\"\n\tout += `var buf fflib.Buffer` + \"\\n\"\n\n\tout += fmt.Sprintf(\"buf.Grow(%d)\\n\", getBufGrowSize(si))\n\tout += `err := mj.MarshalJSONBuf(&buf)` + \"\\n\"\n\tout += `if err != nil {` + \"\\n\"\n\tout += \"  return nil, err\" + \"\\n\"\n\tout += `}` + \"\\n\"\n\tout += `return buf.Bytes(), nil` + \"\\n\"\n\tout += `}` + \"\\n\"\n\n\tfor _, f := range si.Fields {\n\t\tif isInt(f.Typ) {\n\t\t\tneedScratch = true\n\t\t}\n\t}\n\n\tfor _, f := range si.Fields {\n\t\tif f.OmitEmpty || f.Pointer {\n\t\t\t\/\/ if we have >= 1 non-conditional write, we can\n\t\t\t\/\/ assume our trailing logic is reaosnable.\n\t\t\tif conditionalWrites {\n\t\t\t\tconditionalWrites = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tconditionalWrites = true\n\t\t}\n\t}\n\n\tout += `func (mj *` + si.Name + `) MarshalJSONBuf(buf fflib.EncodingBuffer) (error) {` + \"\\n\"\n\tout += `var err error` + \"\\n\"\n\tout += `var obj []byte` + \"\\n\"\n\tif needScratch {\n\t\tout += `var scratch fflib.FormatBitsScratch` + \"\\n\"\n\t}\n\n\tif conditionalWrites {\n\t\tout += `var wroteAnyFields bool = false` + \"\\n\"\n\t}\n\n\tout += `_ = obj` + \"\\n\"\n\tout += `_ = err` + \"\\n\"\n\tout += \"buf.WriteString(`{`)\" + \"\\n\"\n\n\tfor _, f := range si.Fields {\n\t\tif f.OmitEmpty {\n\t\t\tout += getOmitEmpty(ic, f)\n\t\t}\n\n\t\tif f.Pointer {\n\t\t\tout += \"if mj.\" + f.Name + \" != nil {\" + \"\\n\"\n\t\t}\n\n\t\tif conditionalWrites {\n\t\t\tout += `wroteAnyFields = true` + \"\\n\"\n\t\t}\n\n\t\t\/\/ JsonName is already escaped and quoted.\n\t\tout += \"buf.WriteString(`\" + f.JsonName + \":`)\" + \"\\n\"\n\t\tout += getValue(ic, f)\n\t\tout += \"buf.WriteString(`, `)\" + \"\\n\"\n\n\t\tif f.Pointer {\n\t\t\tout += \"}\" + \"\\n\"\n\t\t}\n\n\t\tif f.OmitEmpty {\n\t\t\tout += \"}\" + \"\\n\"\n\t\t}\n\t}\n\n\tif conditionalWrites {\n\t\tout += `if wroteAnyFields {` + \"\\n\"\n\t\tout += \"  \tbuf.Rewind(2)\" + \"\\n\"\n\t\tout += \"\tbuf.WriteByte('}')\" + \"\\n\"\n\t\tout += `} else {` + \"\\n\"\n\t\tout += \"\tbuf.WriteByte('}')\" + \"\\n\"\n\t\tout += `}` + \"\\n\"\n\t} else {\n\t\tout += \"buf.Rewind(2)\" + \"\\n\"\n\t\tout += \"buf.WriteByte('}')\" + \"\\n\"\n\t}\n\n\tout += `return nil` + \"\\n\"\n\tout += `}` + \"\\n\"\n\tic.OutputFuncs = append(ic.OutputFuncs, out)\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package common\n\n\/\/ Defalut value\nvar (\n\tDefaultCleanSession      = true\n\tDefaultKeepAlive    uint = 60\n)\n\n\/\/ OptionsPacketCONNECT is options for creating a CONNECT Packet.\ntype OptionsPacketCONNECT struct {\n\t\/\/ CleanSession is the Clean Session of the connect flags.\n\tCleanSession *bool\n\t\/\/ WillTopic is the Will Topic of the payload.\n\tWillTopic string\n\t\/\/ WillMessage is the Will Message of the payload.\n\tWillMessage string\n\t\/\/ WillQoS is the Will QoS of the connect flags.\n\tWillQoS uint\n\t\/\/ WillRetain is the Will Retain of the connect flags.\n\tWillRetain bool\n\t\/\/ UserName is the user name used by the server for authentication and authorization.\n\tUserName string\n\t\/\/ Password is the password used by the server for authentication and authorization.\n\tPassword string\n\t\/\/ KeepAlive is the Keep Alive in the variable header.\n\tKeepAlive *uint\n}\n\n\/\/ Init initialize the ConnectOpts.\nfunc (opts *OptionsPacketCONNECT) Init() {\n\tif opts.CleanSession == nil {\n\t\topts.CleanSession = &DefaultCleanSession\n\t}\n\n\tif opts.KeepAlive == nil {\n\t\topts.KeepAlive = &DefaultKeepAlive\n\t}\n}\n<commit_msg>Update options_packet_connect.go<commit_after>package common\n\n\/\/ Defalut value\nvar (\n\tDefaultCleanSession      = true\n\tDefaultKeepAlive    uint = 60\n)\n\n\/\/ OptionsPacketCONNECT is options for creating a CONNECT Packet.\ntype OptionsPacketCONNECT struct {\n\t\/\/ CleanSession is the Clean Session of the connect flags.\n\tCleanSession *bool\n\t\/\/ WillTopic is the Will Topic of the payload.\n\tWillTopic string\n\t\/\/ WillMessage is the Will Message of the payload.\n\tWillMessage string\n\t\/\/ WillQoS is the Will QoS of the connect flags.\n\tWillQoS uint\n\t\/\/ WillRetain is the Will Retain of the connect flags.\n\tWillRetain bool\n\t\/\/ UserName is the user name used by the server for authentication and authorization.\n\tUserName string\n\t\/\/ Password is the password used by the server for authentication and authorization.\n\tPassword string\n\t\/\/ KeepAlive is the Keep Alive in the variable header.\n\tKeepAlive *uint\n}\n\n\/\/ Init initializes the OptionsPacketCONNECT.\nfunc (opts *OptionsPacketCONNECT) Init() {\n\tif opts.CleanSession == nil {\n\t\topts.CleanSession = &DefaultCleanSession\n\t}\n\n\tif opts.KeepAlive == nil {\n\t\topts.KeepAlive = &DefaultKeepAlive\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2018 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\npackage main\n\n\/\/ This server runs along side the karma tests and listens for POST requests\n\/\/ when any test case reports it has output for Gold. See testReporter.js\n\/\/ for the browser side part.\n\nimport (\n\t\"bytes\"\n\t\"crypto\/md5\"\n\t\"encoding\/base64\"\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"image\"\n\t\"image\/png\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"go.skia.org\/infra\/go\/util\"\n\t\"go.skia.org\/infra\/golden\/go\/jsonio\"\n\t\"go.skia.org\/infra\/golden\/go\/types\"\n)\n\n\/\/ This allows us to use upload_dm_results.py out of the box\nconst JSON_FILENAME = \"dm.json\"\n\nvar (\n\toutDir = flag.String(\"out_dir\", \"\/OUT\/\", \"location to dump the Gold JSON and pngs\")\n\tport   = flag.String(\"port\", \"8081\", \"Port to listen on.\")\n\n\tbrowser          = flag.String(\"browser\", \"Chrome\", \"Browser Key\")\n\tbuildBucketID    = flag.String(\"buildbucket_build_id\", \"\", \"Buildbucket build id key\")\n\tbuilder          = flag.String(\"builder\", \"\", \"Builder, like 'Test-Debian9-EMCC-GCE-CPU-AVX2-wasm-Debug-All-PathKit'\")\n\tcompiledLanguage = flag.String(\"compiled_language\", \"wasm\", \"wasm or asm.js\")\n\tconfig           = flag.String(\"config\", \"Release\", \"Configuration (e.g. Debug\/Release) key\")\n\tgitHash          = flag.String(\"git_hash\", \"-\", \"The git commit hash of the version being tested\")\n\thostOS           = flag.String(\"host_os\", \"Debian9\", \"OS Key\")\n\tissue            = flag.String(\"issue\", \"\", \"ChangelistID (if tryjob)\")\n\tpatchset         = flag.Int(\"patchset\", 0, \"patchset (if tryjob)\")\n\tsourceType       = flag.String(\"source_type\", \"pathkit\", \"Gold Source type, like pathkit,canvaskit\")\n)\n\n\/\/ Received from the JS side.\ntype reportBody struct {\n\t\/\/ e.g. \"canvas\" or \"svg\"\n\tOutputType string `json:\"output_type\"`\n\t\/\/ a base64 encoded PNG image.\n\tData string `json:\"data\"`\n\t\/\/ a name describing the test. Should be unique enough to allow use of grep.\n\tTestName string `json:\"test_name\"`\n}\n\n\/\/ The keys to be used at the top level for all Results.\nvar defaultKeys map[string]string\n\n\/\/ contains all the results reported in through report_gold_data\nvar results []*jsonio.Result\nvar resultsMutex sync.Mutex\n\nfunc main() {\n\tflag.Parse()\n\n\tcpuGPU := \"CPU\"\n\tif strings.Index(*builder, \"-GPU-\") != -1 {\n\t\tcpuGPU = \"GPU\"\n\t}\n\tdefaultKeys = map[string]string{\n\t\t\"arch\":              \"WASM\",\n\t\t\"browser\":           *browser,\n\t\t\"compiled_language\": *compiledLanguage,\n\t\t\"compiler\":          \"emsdk\",\n\t\t\"configuration\":     *config,\n\t\t\"cpu_or_gpu\":        cpuGPU,\n\t\t\"cpu_or_gpu_value\":  \"Browser\",\n\t\t\"os\":                *hostOS,\n\t\t\"source_type\":       *sourceType,\n\t}\n\n\tresults = []*jsonio.Result{}\n\n\thttp.HandleFunc(\"\/report_gold_data\", reporter)\n\thttp.HandleFunc(\"\/dump_json\", dumpJSON)\n\n\tfmt.Printf(\"Waiting for gold ingestion on port %s\\n\", *port)\n\n\tlog.Fatal(http.ListenAndServe(\":\"+*port, nil))\n}\n\n\/\/ reporter handles when the client reports a test has Gold output.\n\/\/ It writes the corresponding PNG to disk and appends a Result, assuming\n\/\/ no errors.\nfunc reporter(w http.ResponseWriter, r *http.Request) {\n\tif r.Method != \"POST\" {\n\t\thttp.Error(w, \"Only POST accepted\", 400)\n\t\treturn\n\t}\n\tdefer util.Close(r.Body)\n\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\thttp.Error(w, \"Malformed body\", 400)\n\t\treturn\n\t}\n\n\ttestOutput := reportBody{}\n\tif err := json.Unmarshal(body, &testOutput); err != nil {\n\t\tfmt.Println(err)\n\t\thttp.Error(w, \"Could not unmarshal JSON\", 400)\n\t\treturn\n\t}\n\n\thash := \"\"\n\tif hash, err = writeBase64EncodedPNG(testOutput.Data); err != nil {\n\t\tfmt.Println(err)\n\t\thttp.Error(w, \"Could not write image to disk\", 500)\n\t\treturn\n\t}\n\n\tif _, err := w.Write([]byte(\"Accepted\")); err != nil {\n\t\tfmt.Printf(\"Could not write response: %s\\n\", err)\n\t\treturn\n\t}\n\n\tresultsMutex.Lock()\n\tdefer resultsMutex.Unlock()\n\tresults = append(results, &jsonio.Result{\n\t\tDigest: types.Digest(hash),\n\t\tKey: map[string]string{\n\t\t\t\"name\":   testOutput.TestName,\n\t\t\t\"config\": testOutput.OutputType,\n\t\t},\n\t\tOptions: map[string]string{\n\t\t\t\"ext\": \"png\",\n\t\t},\n\t})\n}\n\n\/\/ createOutputFile creates a file and set permissions correctly.\nfunc createOutputFile(p string) (*os.File, error) {\n\toutputFile, err := os.Create(p)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Could not open file %s on disk: %s\", p, err)\n\t}\n\t\/\/ Make this accessible (and deletable) by all users\n\tif err = outputFile.Chmod(0666); err != nil {\n\t\treturn nil, fmt.Errorf(\"Could not change permissions of file %s: %s\", p, err)\n\t}\n\treturn outputFile, nil\n}\n\n\/\/ dumpJSON writes out a JSON file with all the results, typically at the end of\n\/\/ all the tests.\nfunc dumpJSON(w http.ResponseWriter, r *http.Request) {\n\tif r.Method != \"POST\" {\n\t\thttp.Error(w, \"Only POST accepted\", 400)\n\t\treturn\n\t}\n\n\tp := path.Join(*outDir, JSON_FILENAME)\n\toutputFile, err := createOutputFile(p)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\thttp.Error(w, \"Could not open json file on disk\", 500)\n\t\treturn\n\t}\n\tdefer util.Close(outputFile)\n\n\tdmresults := jsonio.GoldResults{\n\t\tGitHash: *gitHash,\n\t\tKey:     defaultKeys,\n\t\tResults: results,\n\t}\n\n\tif *patchset > 0 {\n\t\tdmresults.ChangelistID = *issue\n\t\tdmresults.PatchsetOrder = *patchset\n\t\tdmresults.CodeReviewSystem = \"gerrit\"\n\t\tdmresults.ContinuousIntegrationSystem = \"buildbucket\"\n\t\tdmresults.TryJobID = *buildBucketID\n\t}\n\n\tenc := json.NewEncoder(outputFile)\n\tenc.SetIndent(\"\", \"  \") \/\/ Make it human readable.\n\tif err := enc.Encode(&dmresults); err != nil {\n\t\tfmt.Println(err)\n\t\thttp.Error(w, \"Could not write json to disk\", 500)\n\t\treturn\n\t}\n\tfmt.Println(\"JSON Written\")\n}\n\n\/\/ writeBase64EncodedPNG writes a PNG to disk and returns the md5 of the\n\/\/ decoded PNG bytes and any error. This hash is what will be used as\n\/\/ the gold digest and the file name.\nfunc writeBase64EncodedPNG(data string) (string, error) {\n\t\/\/ data starts with something like data:image\/png;base64,[data]\n\t\/\/ https:\/\/en.wikipedia.org\/wiki\/Data_URI_scheme\n\tstart := strings.Index(data, \",\")\n\tb := bytes.NewBufferString(data[start+1:])\n\tpngReader := base64.NewDecoder(base64.StdEncoding, b)\n\n\tpngBytes, err := ioutil.ReadAll(pngReader)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Could not decode base 64 encoding %s\", err)\n\t}\n\n\t\/\/ compute the hash of the pixel values, like DM does\n\timg, err := png.Decode(bytes.NewBuffer(pngBytes))\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Not a valid png: %s\", err)\n\t}\n\thash := \"\"\n\tswitch img.(type) {\n\tcase *image.NRGBA:\n\t\ti := img.(*image.NRGBA)\n\t\thash = fmt.Sprintf(\"%x\", md5.Sum(i.Pix))\n\tcase *image.RGBA:\n\t\ti := img.(*image.RGBA)\n\t\thash = fmt.Sprintf(\"%x\", md5.Sum(i.Pix))\n\tcase *image.RGBA64:\n\t\ti := img.(*image.RGBA64)\n\t\thash = fmt.Sprintf(\"%x\", md5.Sum(i.Pix))\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"Unknown type of image\")\n\t}\n\n\tp := path.Join(*outDir, hash+\".png\")\n\toutputFile, err := createOutputFile(p)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Could not create png file %s: %s\", p, err)\n\t}\n\tif _, err = outputFile.Write(pngBytes); err != nil {\n\t\tutil.Close(outputFile)\n\t\treturn \"\", fmt.Errorf(\"Could not write to file %s: %s\", p, err)\n\t}\n\treturn hash, outputFile.Close()\n}\n<commit_msg>[infra] Update wasm_gold_aggregator<commit_after>\/\/ Copyright 2018 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\npackage main\n\n\/\/ This server runs along side the karma tests and listens for POST requests\n\/\/ when any test case reports it has output for Gold. See testReporter.js\n\/\/ for the browser side part.\n\nimport (\n\t\"bytes\"\n\t\"crypto\/md5\"\n\t\"encoding\/base64\"\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"image\"\n\t\"image\/png\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"go.skia.org\/infra\/go\/util\"\n\t\"go.skia.org\/infra\/golden\/go\/jsonio\"\n\t\"go.skia.org\/infra\/golden\/go\/types\"\n)\n\n\/\/ This allows us to use upload_dm_results.py out of the box\nconst JSON_FILENAME = \"dm.json\"\n\nvar (\n\toutDir = flag.String(\"out_dir\", \"\/OUT\/\", \"location to dump the Gold JSON and pngs\")\n\tport   = flag.String(\"port\", \"8081\", \"Port to listen on.\")\n\n\tbrowser          = flag.String(\"browser\", \"Chrome\", \"Browser Key\")\n\tbuildBucketID    = flag.String(\"buildbucket_build_id\", \"\", \"Buildbucket build id key\")\n\tbuilder          = flag.String(\"builder\", \"\", \"Builder, like 'Test-Debian9-EMCC-GCE-CPU-AVX2-wasm-Debug-All-PathKit'\")\n\tcompiledLanguage = flag.String(\"compiled_language\", \"wasm\", \"wasm or asm.js\")\n\tconfig           = flag.String(\"config\", \"Release\", \"Configuration (e.g. Debug\/Release) key\")\n\tgitHash          = flag.String(\"git_hash\", \"-\", \"The git commit hash of the version being tested\")\n\thostOS           = flag.String(\"host_os\", \"Debian9\", \"OS Key\")\n\tissue            = flag.String(\"issue\", \"\", \"ChangelistID (if tryjob)\")\n\tpatchset         = flag.Int(\"patchset\", 0, \"patchset (if tryjob)\")\n\tsourceType       = flag.String(\"source_type\", \"pathkit\", \"Gold Source type, like pathkit,canvaskit\")\n)\n\n\/\/ Received from the JS side.\ntype reportBody struct {\n\t\/\/ e.g. \"canvas\" or \"svg\"\n\tOutputType string `json:\"output_type\"`\n\t\/\/ a base64 encoded PNG image.\n\tData string `json:\"data\"`\n\t\/\/ a name describing the test. Should be unique enough to allow use of grep.\n\tTestName string `json:\"test_name\"`\n}\n\n\/\/ The keys to be used at the top level for all Results.\nvar defaultKeys map[string]string\n\n\/\/ contains all the results reported in through report_gold_data\nvar results []jsonio.Result\nvar resultsMutex sync.Mutex\n\nfunc main() {\n\tflag.Parse()\n\n\tcpuGPU := \"CPU\"\n\tif strings.Index(*builder, \"-GPU-\") != -1 {\n\t\tcpuGPU = \"GPU\"\n\t}\n\tdefaultKeys = map[string]string{\n\t\t\"arch\":              \"WASM\",\n\t\t\"browser\":           *browser,\n\t\t\"compiled_language\": *compiledLanguage,\n\t\t\"compiler\":          \"emsdk\",\n\t\t\"configuration\":     *config,\n\t\t\"cpu_or_gpu\":        cpuGPU,\n\t\t\"cpu_or_gpu_value\":  \"Browser\",\n\t\t\"os\":                *hostOS,\n\t\t\"source_type\":       *sourceType,\n\t}\n\n\tresults = []jsonio.Result{}\n\n\thttp.HandleFunc(\"\/report_gold_data\", reporter)\n\thttp.HandleFunc(\"\/dump_json\", dumpJSON)\n\n\tfmt.Printf(\"Waiting for gold ingestion on port %s\\n\", *port)\n\n\tlog.Fatal(http.ListenAndServe(\":\"+*port, nil))\n}\n\n\/\/ reporter handles when the client reports a test has Gold output.\n\/\/ It writes the corresponding PNG to disk and appends a Result, assuming\n\/\/ no errors.\nfunc reporter(w http.ResponseWriter, r *http.Request) {\n\tif r.Method != \"POST\" {\n\t\thttp.Error(w, \"Only POST accepted\", 400)\n\t\treturn\n\t}\n\tdefer util.Close(r.Body)\n\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\thttp.Error(w, \"Malformed body\", 400)\n\t\treturn\n\t}\n\n\ttestOutput := reportBody{}\n\tif err := json.Unmarshal(body, &testOutput); err != nil {\n\t\tfmt.Println(err)\n\t\thttp.Error(w, \"Could not unmarshal JSON\", 400)\n\t\treturn\n\t}\n\n\thash := \"\"\n\tif hash, err = writeBase64EncodedPNG(testOutput.Data); err != nil {\n\t\tfmt.Println(err)\n\t\thttp.Error(w, \"Could not write image to disk\", 500)\n\t\treturn\n\t}\n\n\tif _, err := w.Write([]byte(\"Accepted\")); err != nil {\n\t\tfmt.Printf(\"Could not write response: %s\\n\", err)\n\t\treturn\n\t}\n\n\tresultsMutex.Lock()\n\tdefer resultsMutex.Unlock()\n\tresults = append(results, jsonio.Result{\n\t\tDigest: types.Digest(hash),\n\t\tKey: map[string]string{\n\t\t\t\"name\":   testOutput.TestName,\n\t\t\t\"config\": testOutput.OutputType,\n\t\t},\n\t\tOptions: map[string]string{\n\t\t\t\"ext\": \"png\",\n\t\t},\n\t})\n}\n\n\/\/ createOutputFile creates a file and set permissions correctly.\nfunc createOutputFile(p string) (*os.File, error) {\n\toutputFile, err := os.Create(p)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Could not open file %s on disk: %s\", p, err)\n\t}\n\t\/\/ Make this accessible (and deletable) by all users\n\tif err = outputFile.Chmod(0666); err != nil {\n\t\treturn nil, fmt.Errorf(\"Could not change permissions of file %s: %s\", p, err)\n\t}\n\treturn outputFile, nil\n}\n\n\/\/ dumpJSON writes out a JSON file with all the results, typically at the end of\n\/\/ all the tests.\nfunc dumpJSON(w http.ResponseWriter, r *http.Request) {\n\tif r.Method != \"POST\" {\n\t\thttp.Error(w, \"Only POST accepted\", 400)\n\t\treturn\n\t}\n\n\tp := path.Join(*outDir, JSON_FILENAME)\n\toutputFile, err := createOutputFile(p)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\thttp.Error(w, \"Could not open json file on disk\", 500)\n\t\treturn\n\t}\n\tdefer util.Close(outputFile)\n\n\tdmresults := jsonio.GoldResults{\n\t\tGitHash: *gitHash,\n\t\tKey:     defaultKeys,\n\t\tResults: results,\n\t}\n\n\tif *patchset > 0 {\n\t\tdmresults.ChangelistID = *issue\n\t\tdmresults.PatchsetOrder = *patchset\n\t\tdmresults.CodeReviewSystem = \"gerrit\"\n\t\tdmresults.ContinuousIntegrationSystem = \"buildbucket\"\n\t\tdmresults.TryJobID = *buildBucketID\n\t}\n\n\tenc := json.NewEncoder(outputFile)\n\tenc.SetIndent(\"\", \"  \") \/\/ Make it human readable.\n\tif err := enc.Encode(&dmresults); err != nil {\n\t\tfmt.Println(err)\n\t\thttp.Error(w, \"Could not write json to disk\", 500)\n\t\treturn\n\t}\n\tfmt.Println(\"JSON Written\")\n}\n\n\/\/ writeBase64EncodedPNG writes a PNG to disk and returns the md5 of the\n\/\/ decoded PNG bytes and any error. This hash is what will be used as\n\/\/ the gold digest and the file name.\nfunc writeBase64EncodedPNG(data string) (string, error) {\n\t\/\/ data starts with something like data:image\/png;base64,[data]\n\t\/\/ https:\/\/en.wikipedia.org\/wiki\/Data_URI_scheme\n\tstart := strings.Index(data, \",\")\n\tb := bytes.NewBufferString(data[start+1:])\n\tpngReader := base64.NewDecoder(base64.StdEncoding, b)\n\n\tpngBytes, err := ioutil.ReadAll(pngReader)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Could not decode base 64 encoding %s\", err)\n\t}\n\n\t\/\/ compute the hash of the pixel values, like DM does\n\timg, err := png.Decode(bytes.NewBuffer(pngBytes))\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Not a valid png: %s\", err)\n\t}\n\thash := \"\"\n\tswitch img.(type) {\n\tcase *image.NRGBA:\n\t\ti := img.(*image.NRGBA)\n\t\thash = fmt.Sprintf(\"%x\", md5.Sum(i.Pix))\n\tcase *image.RGBA:\n\t\ti := img.(*image.RGBA)\n\t\thash = fmt.Sprintf(\"%x\", md5.Sum(i.Pix))\n\tcase *image.RGBA64:\n\t\ti := img.(*image.RGBA64)\n\t\thash = fmt.Sprintf(\"%x\", md5.Sum(i.Pix))\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"Unknown type of image\")\n\t}\n\n\tp := path.Join(*outDir, hash+\".png\")\n\toutputFile, err := createOutputFile(p)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"Could not create png file %s: %s\", p, err)\n\t}\n\tif _, err = outputFile.Write(pngBytes); err != nil {\n\t\tutil.Close(outputFile)\n\t\treturn \"\", fmt.Errorf(\"Could not write to file %s: %s\", p, err)\n\t}\n\treturn hash, outputFile.Close()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ This is a client that writes out to a file, and optionally rolls the file\n\npackage main\n\nimport (\n\t\"compress\/gzip\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/bitly\/nsq\/nsq\"\n\t\"github.com\/bitly\/nsq\/util\"\n\t\"log\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"path\"\n\t\"strings\"\n\t\"syscall\"\n\t\"time\"\n)\n\nvar (\n\tdatetimeFormat   = flag.String(\"datetime-format\", \"%Y-%m-%d_%H\", \"strftime compatible format for <DATETIME> in filename format\")\n\tfilenameFormat   = flag.String(\"filename-format\", \"<TOPIC>.<HOST><GZIPREV>.<DATETIME>.log\", \"output filename format (<TOPIC>, <HOST>, <DATETIME>, <GZIPREV> are replaced. <GZIPREV> is a suffix when an existing gzip file already exists)\")\n\tshowVersion      = flag.Bool(\"version\", false, \"print version string\")\n\thostIdentifier   = flag.String(\"host-identifier\", \"\", \"value to output in log filename in place of hostname. <SHORT_HOST> and <HOSTNAME> are valid replacement tokens\")\n\toutputDir        = flag.String(\"output-dir\", \"\/tmp\", \"directory to write output files to\")\n\ttopic            = flag.String(\"topic\", \"\", \"nsq topic\")\n\tchannel          = flag.String(\"channel\", \"nsq_to_file\", \"nsq channel\")\n\tmaxInFlight      = flag.Int(\"max-in-flight\", 1000, \"max number of messages to allow in flight\")\n\tgzipCompression  = flag.Int(\"gzip-compression\", 3, \"gzip compression level. 1 BestSpeed, 2 BestCompression, 3 DefaultCompression\")\n\tgzipEnabled      = flag.Bool(\"gzip\", false, \"gzip output files.\")\n\tverbose          = flag.Bool(\"verbose\", false, \"verbose logging\")\n\tnsqdTCPAddrs     = util.StringArray{}\n\tlookupdHTTPAddrs = util.StringArray{}\n)\n\nfunc init() {\n\tflag.Var(&nsqdTCPAddrs, \"nsqd-tcp-address\", \"nsqd TCP address (may be given multiple times)\")\n\tflag.Var(&lookupdHTTPAddrs, \"lookupd-http-address\", \"lookupd HTTP address (may be given multiple times)\")\n}\n\ntype FileLogger struct {\n\tout              *os.File\n\tgzipWriter       *gzip.Writer\n\tlastFilename     string\n\tlogChan          chan *Message\n\tcompressionLevel int\n\tgzipEnabled      bool\n\tfilenameFormat   string\n}\n\ntype Message struct {\n\t*nsq.Message\n\treturnChannel chan *nsq.FinishedMessage\n}\n\ntype SyncMsg struct {\n\tm             *nsq.FinishedMessage\n\treturnChannel chan *nsq.FinishedMessage\n}\n\nfunc (l *FileLogger) HandleMessage(m *nsq.Message, responseChannel chan *nsq.FinishedMessage) {\n\tl.logChan <- &Message{m, responseChannel}\n}\n\nfunc router(r *nsq.Reader, f *FileLogger, termChan chan os.Signal, hupChan chan os.Signal) {\n\tpos := 0\n\toutput := make([]*Message, *maxInFlight)\n\tsync := false\n\tticker := time.NewTicker(time.Duration(30) * time.Second)\n\tclosing := false\n\n\tfor {\n\t\tselect {\n\t\tcase <-termChan:\n\t\t\tticker.Stop()\n\t\t\tr.Stop()\n\t\t\t\/\/ ensures that we keep flushing whatever is left in the channels\n\t\t\tclosing = true\n\t\tcase <-hupChan:\n\t\t\tf.Close()\n\t\t\tf.updateFile()\n\t\t\tsync = true\n\t\tcase <-ticker.C:\n\t\t\tf.updateFile()\n\t\t\tsync = true\n\t\tcase m := <-f.logChan:\n\t\t\tif f.updateFile() {\n\t\t\t\tsync = true\n\t\t\t}\n\t\t\t_, err := f.Write(m.Body)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"ERROR: writing message to disk - %s\", err.Error())\n\t\t\t}\n\t\t\t_, err = f.Write([]byte(\"\\n\"))\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"ERROR: writing newline to disk - %s\", err.Error())\n\t\t\t}\n\t\t\toutput[pos] = m\n\t\t\tpos++\n\t\t\tif pos == *maxInFlight {\n\t\t\t\tsync = true\n\t\t\t}\n\t\t}\n\n\t\tif closing || sync || r.IsStarved() {\n\t\t\tif pos > 0 {\n\t\t\t\tlog.Printf(\"syncing %d records to disk\", pos)\n\t\t\t\terr := f.Sync()\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatalf(\"ERROR: failed syncing messages - %s\", err.Error())\n\t\t\t\t}\n\t\t\t\tfor pos > 0 {\n\t\t\t\t\tpos--\n\t\t\t\t\tm := output[pos]\n\t\t\t\t\tm.returnChannel <- &nsq.FinishedMessage{m.Id, 0, true}\n\t\t\t\t\toutput[pos] = nil\n\t\t\t\t}\n\t\t\t}\n\t\t\tsync = false\n\t\t}\n\t}\n}\n\nfunc (f *FileLogger) Close() {\n\tif f.out != nil {\n\t\tif f.gzipWriter != nil {\n\t\t\tf.gzipWriter.Close()\n\t\t}\n\t\tf.out.Close()\n\t\tf.out = nil\n\t}\n}\nfunc (f *FileLogger) Write(p []byte) (n int, err error) {\n\tif f.gzipWriter != nil {\n\t\treturn f.gzipWriter.Write(p)\n\t}\n\treturn f.out.Write(p)\n}\nfunc (f *FileLogger) Sync() error {\n\tvar err error\n\tif f.gzipWriter != nil {\n\t\tf.gzipWriter.Close()\n\t\terr = f.out.Sync()\n\t\tf.gzipWriter, _ = gzip.NewWriterLevel(f.out, f.compressionLevel)\n\t} else {\n\t\terr = f.out.Sync()\n\t}\n\treturn err\n}\n\nfunc (f *FileLogger) calculateCurrentFilename() string {\n\tt := time.Now()\n\n\tdatetime := strftime(*datetimeFormat, t)\n\tfilename := strings.Replace(f.filenameFormat, \"<DATETIME>\", datetime, -1)\n\tif !f.gzipEnabled {\n\t\tfilename = strings.Replace(filename, \"<GZIPREV>\", \"\", -1)\n\t}\n\treturn filename\n\n}\n\nfunc (f *FileLogger) updateFile() bool {\n\tfilename := f.calculateCurrentFilename()\n\tmaxGzipRevisions := 1000\n\tif filename != f.lastFilename || f.out == nil {\n\t\tf.Close()\n\t\tos.MkdirAll(*outputDir, 777)\n\t\tvar newFile *os.File\n\t\tvar err error\n\t\tif f.gzipEnabled {\n\t\t\t\/\/ for gzip files, we never append to an existing file\n\t\t\t\/\/ we try to create different revisions, replacing <GZIPREV> in the filename\n\t\t\tfor gzipRevision := 0; gzipRevision < maxGzipRevisions; gzipRevision += 1 {\n\t\t\t\tvar revisionSuffix string\n\t\t\t\tif gzipRevision > 0 {\n\t\t\t\t\trevisionSuffix = fmt.Sprintf(\"-%d\", gzipRevision)\n\t\t\t\t}\n\t\t\t\ttempFilename := strings.Replace(filename, \"<GZIPREV>\", revisionSuffix, -1)\n\t\t\t\tfullPath := path.Join(*outputDir, tempFilename)\n\t\t\t\tnewFile, err = os.OpenFile(fullPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0666)\n\t\t\t\tif err != nil && os.IsExist(err) {\n\t\t\t\t\tlog.Printf(\"INFO: file already exists: %s\", fullPath)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatalf(\"ERROR: %s Unable to open %s\", err, fullPath)\n\t\t\t\t}\n\t\t\t\tlog.Printf(\"opening %s\", fullPath)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif newFile == nil {\n\t\t\t\tlog.Fatalf(\"ERROR: Unable to open a new gzip file after %d tries\", maxGzipRevisions)\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Printf(\"opening %s\/%s\", *outputDir, filename)\n\t\t\tnewFile, err = os.OpenFile(path.Join(*outputDir, filename), os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t}\n\n\t\tf.out = newFile\n\t\tf.lastFilename = filename\n\t\tif f.gzipEnabled {\n\t\t\tf.gzipWriter, _ = gzip.NewWriterLevel(newFile, f.compressionLevel)\n\t\t}\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc NewFileLogger(gzipEnabled bool, compressionLevel int, filenameFormat string) (*FileLogger, error) {\n\tvar speed int\n\tswitch compressionLevel {\n\tcase 1:\n\t\tspeed = gzip.BestSpeed\n\tcase 2:\n\t\tspeed = gzip.BestCompression\n\tcase 3:\n\t\tspeed = gzip.DefaultCompression\n\t}\n\n\tif gzipEnabled && strings.Index(filenameFormat, \"<GZIPREV>\") == -1 {\n\t\treturn nil, errors.New(\"missing <GZIPREV> in filenameFormat\")\n\t}\n\n\thostname, err := os.Hostname()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tshortHostname := strings.Split(hostname, \".\")[0]\n\tidentifier := shortHostname\n\tif len(*hostIdentifier) != 0 {\n\t\tidentifier = strings.Replace(*hostIdentifier, \"<SHORT_HOST>\", shortHostname, -1)\n\t\tidentifier = strings.Replace(identifier, \"<HOSTNAME>\", hostname, -1)\n\t}\n\tfilenameFormat = strings.Replace(filenameFormat, \"<TOPIC>\", *topic, -1)\n\tfilenameFormat = strings.Replace(filenameFormat, \"<HOST>\", identifier, -1)\n\tif gzipEnabled && !strings.HasSuffix(filenameFormat, \".gz\") {\n\t\tfilenameFormat = filenameFormat + \".gz\"\n\t}\n\n\tf := &FileLogger{\n\t\tlogChan:          make(chan *Message, 1),\n\t\tcompressionLevel: speed,\n\t\tfilenameFormat:   filenameFormat,\n\t\tgzipEnabled:      gzipEnabled,\n\t}\n\treturn f, nil\n}\n\nfunc main() {\n\tflag.Parse()\n\n\tif *showVersion {\n\t\tfmt.Printf(\"nsq_to_file v%s\\n\", util.BINARY_VERSION)\n\t\treturn\n\t}\n\n\tif *topic == \"\" || *channel == \"\" {\n\t\tlog.Fatalf(\"--topic and --channel are required\")\n\t}\n\n\tif *maxInFlight < 0 {\n\t\tlog.Fatalf(\"--max-in-flight must be > 0\")\n\t}\n\n\tif len(nsqdTCPAddrs) == 0 && len(lookupdHTTPAddrs) == 0 {\n\t\tlog.Fatalf(\"--nsqd-tcp-address or --lookupd-http-address required.\")\n\t}\n\tif len(nsqdTCPAddrs) != 0 && len(lookupdHTTPAddrs) != 0 {\n\t\tlog.Fatalf(\"use --nsqd-tcp-address or --lookupd-http-address not both\")\n\t}\n\n\tif *gzipCompression < 1 || *gzipCompression > 3 {\n\t\tlog.Fatalf(\"invalid --gzip-compresion value (%v). should be 1,2 or 3\", *gzipCompression)\n\t}\n\n\thupChan := make(chan os.Signal, 1)\n\ttermChan := make(chan os.Signal, 1)\n\tsignal.Notify(hupChan, syscall.SIGHUP)\n\tsignal.Notify(termChan, syscall.SIGINT, syscall.SIGTERM)\n\n\tf, err := NewFileLogger(*gzipEnabled, *gzipCompression, *filenameFormat)\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t}\n\n\tr, err := nsq.NewReader(*topic, *channel)\n\tif err != nil {\n\t\tlog.Fatalf(err.Error())\n\t}\n\tr.SetMaxInFlight(*maxInFlight)\n\tr.VerboseLogging = *verbose\n\n\tr.AddAsyncHandler(f)\n\tgo router(r, f, termChan, hupChan)\n\n\tfor _, addrString := range nsqdTCPAddrs {\n\t\terr := r.ConnectToNSQ(addrString)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(err.Error())\n\t\t}\n\t}\n\n\tfor _, addrString := range lookupdHTTPAddrs {\n\t\tlog.Printf(\"lookupd addr %s\", addrString)\n\t\terr := r.ConnectToLookupd(addrString)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(err.Error())\n\t\t}\n\t}\n\n\t<-r.ExitChan\n}\n<commit_msg>fix cases that caused empty files<commit_after>\/\/ This is a client that writes out to a file, and optionally rolls the file\n\npackage main\n\nimport (\n\t\"compress\/gzip\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/bitly\/nsq\/nsq\"\n\t\"github.com\/bitly\/nsq\/util\"\n\t\"log\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"path\"\n\t\"strings\"\n\t\"syscall\"\n\t\"time\"\n)\n\nvar (\n\tdatetimeFormat   = flag.String(\"datetime-format\", \"%Y-%m-%d_%H\", \"strftime compatible format for <DATETIME> in filename format\")\n\tfilenameFormat   = flag.String(\"filename-format\", \"<TOPIC>.<HOST><GZIPREV>.<DATETIME>.log\", \"output filename format (<TOPIC>, <HOST>, <DATETIME>, <GZIPREV> are replaced. <GZIPREV> is a suffix when an existing gzip file already exists)\")\n\tshowVersion      = flag.Bool(\"version\", false, \"print version string\")\n\thostIdentifier   = flag.String(\"host-identifier\", \"\", \"value to output in log filename in place of hostname. <SHORT_HOST> and <HOSTNAME> are valid replacement tokens\")\n\toutputDir        = flag.String(\"output-dir\", \"\/tmp\", \"directory to write output files to\")\n\ttopic            = flag.String(\"topic\", \"\", \"nsq topic\")\n\tchannel          = flag.String(\"channel\", \"nsq_to_file\", \"nsq channel\")\n\tmaxInFlight      = flag.Int(\"max-in-flight\", 1000, \"max number of messages to allow in flight\")\n\tgzipCompression  = flag.Int(\"gzip-compression\", 3, \"gzip compression level. 1 BestSpeed, 2 BestCompression, 3 DefaultCompression\")\n\tgzipEnabled      = flag.Bool(\"gzip\", false, \"gzip output files.\")\n\tverbose          = flag.Bool(\"verbose\", false, \"verbose logging\")\n\tskipEmptyFiles   = flag.Bool(\"skip-empty-files\", false, \"Skip writting empty files\")\n\tnsqdTCPAddrs     = util.StringArray{}\n\tlookupdHTTPAddrs = util.StringArray{}\n)\n\nfunc init() {\n\tflag.Var(&nsqdTCPAddrs, \"nsqd-tcp-address\", \"nsqd TCP address (may be given multiple times)\")\n\tflag.Var(&lookupdHTTPAddrs, \"lookupd-http-address\", \"lookupd HTTP address (may be given multiple times)\")\n}\n\ntype FileLogger struct {\n\tout              *os.File\n\tgzipWriter       *gzip.Writer\n\tlastFilename     string\n\tlogChan          chan *Message\n\tcompressionLevel int\n\tgzipEnabled      bool\n\tfilenameFormat   string\n\n\tExitChan chan int\n}\n\ntype Message struct {\n\t*nsq.Message\n\treturnChannel chan *nsq.FinishedMessage\n}\n\ntype SyncMsg struct {\n\tm             *nsq.FinishedMessage\n\treturnChannel chan *nsq.FinishedMessage\n}\n\nfunc (l *FileLogger) HandleMessage(m *nsq.Message, responseChannel chan *nsq.FinishedMessage) {\n\tl.logChan <- &Message{m, responseChannel}\n}\n\nfunc (f *FileLogger) router(r *nsq.Reader, termChan chan os.Signal, hupChan chan os.Signal) {\n\tpos := 0\n\toutput := make([]*Message, *maxInFlight)\n\tsync := false\n\tticker := time.NewTicker(time.Duration(30) * time.Second)\n\tclosing := false\n\tcloseFile := false\n\texit := false\n\n\tfor {\n\t\tselect {\n\t\tcase <-r.ExitChan:\n\t\t\tsync = true\n\t\t\tcloseFile = true\n\t\t\texit = true\n\t\tcase <-termChan:\n\t\t\tticker.Stop()\n\t\t\tr.Stop()\n\t\t\tsync = true\n\t\t\tclosing = true\n\t\tcase <-hupChan:\n\t\t\tsync = true\n\t\t\tcloseFile = true\n\t\tcase <-ticker.C:\n\t\t\tif f.needsFileRotate() {\n\t\t\t\tif *skipEmptyFiles {\n\t\t\t\t\tcloseFile = true\n\t\t\t\t} else {\n\t\t\t\t\tf.updateFile()\n\t\t\t\t}\n\t\t\t}\n\t\t\tsync = true\n\t\tcase m := <-f.logChan:\n\t\t\tif f.updateFile() {\n\t\t\t\tsync = true\n\t\t\t}\n\t\t\t_, err := f.Write(m.Body)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"ERROR: writing message to disk - %s\", err.Error())\n\t\t\t}\n\t\t\t_, err = f.Write([]byte(\"\\n\"))\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"ERROR: writing newline to disk - %s\", err.Error())\n\t\t\t}\n\t\t\toutput[pos] = m\n\t\t\tpos++\n\t\t\tif pos == *maxInFlight {\n\t\t\t\tsync = true\n\t\t\t}\n\t\t}\n\n\t\tif closing || sync || r.IsStarved() {\n\t\t\tif pos > 0 {\n\t\t\t\tlog.Printf(\"syncing %d records to disk\", pos)\n\t\t\t\terr := f.Sync()\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatalf(\"ERROR: failed syncing messages - %s\", err.Error())\n\t\t\t\t}\n\t\t\t\tfor pos > 0 {\n\t\t\t\t\tpos--\n\t\t\t\t\tm := output[pos]\n\t\t\t\t\tm.returnChannel <- &nsq.FinishedMessage{m.Id, 0, true}\n\t\t\t\t\toutput[pos] = nil\n\t\t\t\t}\n\t\t\t}\n\t\t\tsync = false\n\t\t}\n\n\t\tif closeFile {\n\t\t\tf.Close()\n\t\t\tcloseFile = false\n\t\t}\n\t\tif exit {\n\t\t\tclose(f.ExitChan)\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nfunc (f *FileLogger) Close() {\n\tif f.out != nil {\n\t\tif f.gzipWriter != nil {\n\t\t\tf.gzipWriter.Close()\n\t\t}\n\t\tf.out.Close()\n\t\tf.out = nil\n\t}\n}\nfunc (f *FileLogger) Write(p []byte) (n int, err error) {\n\tif f.gzipWriter != nil {\n\t\treturn f.gzipWriter.Write(p)\n\t}\n\treturn f.out.Write(p)\n}\nfunc (f *FileLogger) Sync() error {\n\tvar err error\n\tif f.gzipWriter != nil {\n\t\tf.gzipWriter.Close()\n\t\terr = f.out.Sync()\n\t\tf.gzipWriter, _ = gzip.NewWriterLevel(f.out, f.compressionLevel)\n\t} else {\n\t\terr = f.out.Sync()\n\t}\n\treturn err\n}\n\nfunc (f *FileLogger) calculateCurrentFilename() string {\n\tt := time.Now()\n\n\tdatetime := strftime(*datetimeFormat, t)\n\tfilename := strings.Replace(f.filenameFormat, \"<DATETIME>\", datetime, -1)\n\tif !f.gzipEnabled {\n\t\tfilename = strings.Replace(filename, \"<GZIPREV>\", \"\", -1)\n\t}\n\treturn filename\n\n}\n\nfunc (f *FileLogger) needsFileRotate() bool {\n\tfilename := f.calculateCurrentFilename()\n\treturn filename != f.lastFilename\n}\n\nfunc (f *FileLogger) updateFile() bool {\n\tfilename := f.calculateCurrentFilename()\n\tmaxGzipRevisions := 1000\n\tif filename != f.lastFilename || f.out == nil {\n\t\tf.Close()\n\t\tos.MkdirAll(*outputDir, 777)\n\t\tvar newFile *os.File\n\t\tvar err error\n\t\tif f.gzipEnabled {\n\t\t\t\/\/ for gzip files, we never append to an existing file\n\t\t\t\/\/ we try to create different revisions, replacing <GZIPREV> in the filename\n\t\t\tfor gzipRevision := 0; gzipRevision < maxGzipRevisions; gzipRevision += 1 {\n\t\t\t\tvar revisionSuffix string\n\t\t\t\tif gzipRevision > 0 {\n\t\t\t\t\trevisionSuffix = fmt.Sprintf(\"-%d\", gzipRevision)\n\t\t\t\t}\n\t\t\t\ttempFilename := strings.Replace(filename, \"<GZIPREV>\", revisionSuffix, -1)\n\t\t\t\tfullPath := path.Join(*outputDir, tempFilename)\n\t\t\t\tnewFile, err = os.OpenFile(fullPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0666)\n\t\t\t\tif err != nil && os.IsExist(err) {\n\t\t\t\t\tlog.Printf(\"INFO: file already exists: %s\", fullPath)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatalf(\"ERROR: %s Unable to open %s\", err, fullPath)\n\t\t\t\t}\n\t\t\t\tlog.Printf(\"opening %s\", fullPath)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif newFile == nil {\n\t\t\t\tlog.Fatalf(\"ERROR: Unable to open a new gzip file after %d tries\", maxGzipRevisions)\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Printf(\"opening %s\/%s\", *outputDir, filename)\n\t\t\tnewFile, err = os.OpenFile(path.Join(*outputDir, filename), os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t}\n\n\t\tf.out = newFile\n\t\tf.lastFilename = filename\n\t\tif f.gzipEnabled {\n\t\t\tf.gzipWriter, _ = gzip.NewWriterLevel(newFile, f.compressionLevel)\n\t\t}\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc NewFileLogger(gzipEnabled bool, compressionLevel int, filenameFormat string) (*FileLogger, error) {\n\tvar speed int\n\tswitch compressionLevel {\n\tcase 1:\n\t\tspeed = gzip.BestSpeed\n\tcase 2:\n\t\tspeed = gzip.BestCompression\n\tcase 3:\n\t\tspeed = gzip.DefaultCompression\n\t}\n\n\tif gzipEnabled && strings.Index(filenameFormat, \"<GZIPREV>\") == -1 {\n\t\treturn nil, errors.New(\"missing <GZIPREV> in filenameFormat\")\n\t}\n\n\thostname, err := os.Hostname()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tshortHostname := strings.Split(hostname, \".\")[0]\n\tidentifier := shortHostname\n\tif len(*hostIdentifier) != 0 {\n\t\tidentifier = strings.Replace(*hostIdentifier, \"<SHORT_HOST>\", shortHostname, -1)\n\t\tidentifier = strings.Replace(identifier, \"<HOSTNAME>\", hostname, -1)\n\t}\n\tfilenameFormat = strings.Replace(filenameFormat, \"<TOPIC>\", *topic, -1)\n\tfilenameFormat = strings.Replace(filenameFormat, \"<HOST>\", identifier, -1)\n\tif gzipEnabled && !strings.HasSuffix(filenameFormat, \".gz\") {\n\t\tfilenameFormat = filenameFormat + \".gz\"\n\t}\n\n\tf := &FileLogger{\n\t\tlogChan:          make(chan *Message, 1),\n\t\tcompressionLevel: speed,\n\t\tfilenameFormat:   filenameFormat,\n\t\tgzipEnabled:      gzipEnabled,\n\t\tExitChan:         make(chan int),\n\t}\n\treturn f, nil\n}\n\nfunc main() {\n\tflag.Parse()\n\n\tif *showVersion {\n\t\tfmt.Printf(\"nsq_to_file v%s\\n\", util.BINARY_VERSION)\n\t\treturn\n\t}\n\n\tif *topic == \"\" || *channel == \"\" {\n\t\tlog.Fatalf(\"--topic and --channel are required\")\n\t}\n\n\tif *maxInFlight < 0 {\n\t\tlog.Fatalf(\"--max-in-flight must be > 0\")\n\t}\n\n\tif len(nsqdTCPAddrs) == 0 && len(lookupdHTTPAddrs) == 0 {\n\t\tlog.Fatalf(\"--nsqd-tcp-address or --lookupd-http-address required.\")\n\t}\n\tif len(nsqdTCPAddrs) != 0 && len(lookupdHTTPAddrs) != 0 {\n\t\tlog.Fatalf(\"use --nsqd-tcp-address or --lookupd-http-address not both\")\n\t}\n\n\tif *gzipCompression < 1 || *gzipCompression > 3 {\n\t\tlog.Fatalf(\"invalid --gzip-compresion value (%v). should be 1,2 or 3\", *gzipCompression)\n\t}\n\n\thupChan := make(chan os.Signal, 1)\n\ttermChan := make(chan os.Signal, 1)\n\tsignal.Notify(hupChan, syscall.SIGHUP)\n\tsignal.Notify(termChan, syscall.SIGINT, syscall.SIGTERM)\n\n\tf, err := NewFileLogger(*gzipEnabled, *gzipCompression, *filenameFormat)\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t}\n\n\tr, err := nsq.NewReader(*topic, *channel)\n\tif err != nil {\n\t\tlog.Fatalf(err.Error())\n\t}\n\tr.SetMaxInFlight(*maxInFlight)\n\tr.VerboseLogging = *verbose\n\n\tr.AddAsyncHandler(f)\n\tgo f.router(r, termChan, hupChan)\n\n\tfor _, addrString := range nsqdTCPAddrs {\n\t\terr := r.ConnectToNSQ(addrString)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(err.Error())\n\t\t}\n\t}\n\n\tfor _, addrString := range lookupdHTTPAddrs {\n\t\tlog.Printf(\"lookupd addr %s\", addrString)\n\t\terr := r.ConnectToLookupd(addrString)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(err.Error())\n\t\t}\n\t}\n\n\t<-f.ExitChan\n}\n<|endoftext|>"}
{"text":"<commit_before>package utils\n\nimport (\n  \"strings\"\n  \"net\/http\"\n)\n\ntype ipAddress string\n\n\/\/ IP address helpers taken\n\/\/ from https:\/\/groups.google.com\/forum\/#!topic\/golang-nuts\/lomWKs0kOfE\n\n\/\/ Request.RemoteAddress contains port, which we want to remove i.e.:\n\/\/ \"[::1]:58292\" => \"[::1]\"\nfunc ipAddrFromRemoteAddr(s string) string {\n  idx := strings.LastIndex(s, \":\")\n  if idx == -1 {\n    return s\n  }\n  return s[:idx]\n}\n\nfunc GetIpAddress(r *http.Request) string {\n  hdr := r.Header\n  hdrRealIp := hdr.Get(\"X-Real-Ip\")\n  hdrForwardedFor := hdr.Get(\"X-Forwarded-For\")\n  if hdrRealIp == \"\" && hdrForwardedFor == \"\" {\n    return ipAddrFromRemoteAddr(r.RemoteAddr)\n  }\n  if hdrForwardedFor != \"\" {\n    \/\/ X-Forwarded-For is potentially a list of addresses separated with \",\"\n    parts := strings.Split(hdrForwardedFor, \",\")\n    for i, p := range parts {\n      parts[i] = strings.TrimSpace(p)\n    }\n    \/\/ TODO: should return first non-local address\n    return parts[0]\n  }\n  return hdrRealIp\n}\n<commit_msg>Update utils.go with gofmt<commit_after>package utils\n\nimport (\n\t\"net\/http\"\n\t\"strings\"\n)\n\ntype ipAddress string\n\n\/\/ IP address helpers taken\n\/\/ from https:\/\/groups.google.com\/forum\/#!topic\/golang-nuts\/lomWKs0kOfE\n\n\/\/ Request.RemoteAddress contains port, which we want to remove i.e.:\n\/\/ \"[::1]:58292\" => \"[::1]\"\nfunc ipAddrFromRemoteAddr(s string) string {\n\tidx := strings.LastIndex(s, \":\")\n\tif idx == -1 {\n\t\treturn s\n\t}\n\treturn s[:idx]\n}\n\nfunc GetIpAddress(r *http.Request) string {\n\thdr := r.Header\n\thdrRealIp := hdr.Get(\"X-Real-Ip\")\n\thdrForwardedFor := hdr.Get(\"X-Forwarded-For\")\n\tif hdrRealIp == \"\" && hdrForwardedFor == \"\" {\n\t\treturn ipAddrFromRemoteAddr(r.RemoteAddr)\n\t}\n\tif hdrForwardedFor != \"\" {\n\t\t\/\/ X-Forwarded-For is potentially a list of addresses separated with \",\"\n\t\tparts := strings.Split(hdrForwardedFor, \",\")\n\t\tfor i, p := range parts {\n\t\t\tparts[i] = strings.TrimSpace(p)\n\t\t}\n\t\t\/\/ TODO: should return first non-local address\n\t\treturn parts[0]\n\t}\n\treturn hdrRealIp\n}\n<|endoftext|>"}
{"text":"<commit_before>package wats\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"time\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t\"github.com\/onsi\/gomega\/gexec\"\n\n\t\"github.com\/cloudfoundry-incubator\/cf-test-helpers\/cf\"\n\t\"github.com\/cloudfoundry-incubator\/cf-test-helpers\/helpers\"\n)\n\nvar _ = Describe(\"Application Lifecycle\", func() {\n\treportedComputerNames := func(instances int) map[string]bool {\n\t\ttimer := time.NewTimer(time.Second * 120)\n\t\tdefer timer.Stop()\n\t\trun := true\n\t\tgo func() {\n\t\t\t<-timer.C\n\t\t\trun = false\n\t\t}()\n\n\t\tseenComputerNames := map[string]bool{}\n\t\tfor len(seenComputerNames) != instances && run == true {\n\t\t\tseenComputerNames[helpers.CurlApp(config, appName, \"\/ENV\/CF_INSTANCE_IP\")] = true\n\t\t}\n\n\t\treturn seenComputerNames\n\t}\n\n\tBeforeEach(func() {\n\t\tmemLimit := config.GetNumWindowsCells() * 2 * 4\n\t\tif memLimit < 10 {\n\t\t\tmemLimit = 10\n\t\t}\n\t\tsetTotalMemoryLimit(fmt.Sprintf(\"%dG\", memLimit))\n\t})\n\n\tAfterEach(func() {\n\t\tsetTotalMemoryLimit(\"10G\")\n\t})\n\n\tDescribe(\"An app staged on Diego and running on Diego\", func() {\n\t\tIt(\"attempts to forkbomb the environment\", func() {\n\t\t\tsrc, err := os.Open(\"..\/..\/assets\/greenhouse-security-fixtures\/bin\/BreakoutBomb.exe\")\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tdefer src.Close()\n\t\t\tdst, err := os.Create(\"..\/..\/assets\/nora\/NoraPublished\/bin\/breakoutbomb.exe\")\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tdefer dst.Close()\n\t\t\t_, err = io.Copy(dst, src)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tdst.Close()\n\n\t\t\tBy(\"pushing it\", func() {\n\t\t\t\tExpect(pushNoraWithOptions(appName, config.GetNumWindowsCells()*2, \"2G\").Wait(CF_PUSH_TIMEOUT)).To(gexec.Exit(0))\n\t\t\t})\n\n\t\t\tBy(\"staging and running it on Diego\", func() {\n\t\t\t\tExpect(cf.Cf(\"start\", appName).Wait(CF_PUSH_TIMEOUT)).To(gexec.Exit(0))\n\t\t\t})\n\n\t\t\tBy(\"verifying it's up\", func() {\n\t\t\t\tEventually(appRunning(appName, config.GetNumWindowsCells()*2, CF_PUSH_TIMEOUT), CF_PUSH_TIMEOUT).Should(Succeed())\n\t\t\t\tEventually(helpers.CurlingAppRoot(config, appName)).Should(ContainSubstring(\"hello i am nora\"))\n\t\t\t})\n\n\t\t\tBy(\"storing the current computer names\")\n\t\t\tcomputerNames := reportedComputerNames(config.GetNumWindowsCells())\n\t\t\tExpect(len(computerNames)).To(Equal(config.GetNumWindowsCells()))\n\n\t\t\tBy(\"Running fork bomb\", func() {\n\t\t\t\thelpers.CurlApp(config, appName, \"\/run\", \"-f\", \"-X\", \"POST\", \"-d\", \"bin\/breakoutbomb.exe\")\n\t\t\t})\n\n\t\t\ttime.Sleep(3 * time.Second)\n\n\t\t\tBy(\"Making sure the bomb did not take down the machine\", func() {\n\t\t\t\tnewComputerNames := reportedComputerNames(config.GetNumWindowsCells())\n\t\t\t\tExpect(newComputerNames).To(Equal(computerNames))\n\t\t\t})\n\t\t})\n\t})\n})\n<commit_msg>Revert \"Don't skip forkbomb test on windows2016\"<commit_after>package wats\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"time\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t\"github.com\/onsi\/gomega\/gexec\"\n\n\t\"github.com\/cloudfoundry-incubator\/cf-test-helpers\/cf\"\n\t\"github.com\/cloudfoundry-incubator\/cf-test-helpers\/helpers\"\n)\n\nvar _ = Describe(\"Application Lifecycle\", func() {\n\treportedComputerNames := func(instances int) map[string]bool {\n\t\ttimer := time.NewTimer(time.Second * 120)\n\t\tdefer timer.Stop()\n\t\trun := true\n\t\tgo func() {\n\t\t\t<-timer.C\n\t\t\trun = false\n\t\t}()\n\n\t\tseenComputerNames := map[string]bool{}\n\t\tfor len(seenComputerNames) != instances && run == true {\n\t\t\tseenComputerNames[helpers.CurlApp(config, appName, \"\/ENV\/CF_INSTANCE_IP\")] = true\n\t\t}\n\n\t\treturn seenComputerNames\n\t}\n\n\tBeforeEach(func() {\n\t\tif config.GetStack() == \"windows2016\" {\n\t\t\tSkip(\"this test may not pass on windows2016\")\n\t\t}\n\n\t\tmemLimit := config.GetNumWindowsCells() * 2 * 4\n\t\tif memLimit < 10 {\n\t\t\tmemLimit = 10\n\t\t}\n\t\tsetTotalMemoryLimit(fmt.Sprintf(\"%dG\", memLimit))\n\t})\n\n\tAfterEach(func() {\n\t\tsetTotalMemoryLimit(\"10G\")\n\t})\n\n\tDescribe(\"An app staged on Diego and running on Diego\", func() {\n\t\tIt(\"attempts to forkbomb the environment\", func() {\n\t\t\tsrc, err := os.Open(\"..\/..\/assets\/greenhouse-security-fixtures\/bin\/BreakoutBomb.exe\")\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tdefer src.Close()\n\t\t\tdst, err := os.Create(\"..\/..\/assets\/nora\/NoraPublished\/bin\/breakoutbomb.exe\")\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tdefer dst.Close()\n\t\t\t_, err = io.Copy(dst, src)\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\t\t\tdst.Close()\n\n\t\t\tBy(\"pushing it\", func() {\n\t\t\t\tExpect(pushNoraWithOptions(appName, config.GetNumWindowsCells()*2, \"2G\").Wait(CF_PUSH_TIMEOUT)).To(gexec.Exit(0))\n\t\t\t})\n\n\t\t\tBy(\"staging and running it on Diego\", func() {\n\t\t\t\tExpect(cf.Cf(\"start\", appName).Wait(CF_PUSH_TIMEOUT)).To(gexec.Exit(0))\n\t\t\t})\n\n\t\t\tBy(\"verifying it's up\", func() {\n\t\t\t\tEventually(appRunning(appName, config.GetNumWindowsCells()*2, CF_PUSH_TIMEOUT), CF_PUSH_TIMEOUT).Should(Succeed())\n\t\t\t\tEventually(helpers.CurlingAppRoot(config, appName)).Should(ContainSubstring(\"hello i am nora\"))\n\t\t\t})\n\n\t\t\tBy(\"storing the current computer names\")\n\t\t\tcomputerNames := reportedComputerNames(config.GetNumWindowsCells())\n\t\t\tExpect(len(computerNames)).To(Equal(config.GetNumWindowsCells()))\n\n\t\t\tBy(\"Running fork bomb\", func() {\n\t\t\t\thelpers.CurlApp(config, appName, \"\/run\", \"-f\", \"-X\", \"POST\", \"-d\", \"bin\/breakoutbomb.exe\")\n\t\t\t})\n\n\t\t\ttime.Sleep(3 * time.Second)\n\n\t\t\tBy(\"Making sure the bomb did not take down the machine\", func() {\n\t\t\t\tnewComputerNames := reportedComputerNames(config.GetNumWindowsCells())\n\t\t\t\tExpect(newComputerNames).To(Equal(computerNames))\n\t\t\t})\n\t\t})\n\t})\n})\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package ql exposes implementations and functions that enables ngorm to work\n\/\/ with ql database.\n\/\/\n\/\/ ql is an embedded sql database. This database doesn't conform 100% qith the\n\/\/ SQL standard. The link to the project is https:\/\/github.com\/cznic\/ql\npackage ql\n\nimport (\n\t\"fmt\"\n\t\"math\/big\"\n\t\"reflect\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/gernest\/ngorm\/dialects\"\n\t\"github.com\/gernest\/ngorm\/model\"\n\t\"github.com\/gernest\/ngorm\/regexes\"\n)\n\n\/\/QL implements the dialects.Dialect interface that uses ql database as the SQl\n\/\/backend.\n\/\/\n\/\/ For some reason the ql database doesn't support multiple databases, as\n\/\/ databases are file based. So, the name of the file is the name of the\n\/\/ database.. Which doesn't affect the querries, since the database name is\n\/\/ irrelevant assuming the SQLCommon interface is the handle over the open\n\/\/ database.\ntype QL struct {\n\tname string\n\tdb   model.SQLCommon\n}\n\n\/\/ Memory returns the dialect for in memory ql database. This is not persistent\n\/\/ everything will be lost when the process exits.\nfunc Memory() *QL {\n\treturn &QL{name: \"ql-mem\"}\n}\n\n\/\/File returns the dialcet for file backed ql database. This is the recommended\n\/\/way use the Memory only for testing else you might lose all of your data.\nfunc File() *QL {\n\treturn &QL{name: \"ql\"}\n}\n\n\/\/ GetName get dialect's name\nfunc (q *QL) GetName() string {\n\treturn q.name\n}\n\n\/\/ SetDB set db for dialect\nfunc (q *QL) SetDB(db model.SQLCommon) {\n\tq.db = db\n}\n\n\/\/ BindVar return the placeholder for actual values in SQL statements, in many dbs it is \"?\", Postgres using $1\nfunc (q QL) BindVar(i int) string {\n\treturn fmt.Sprintf(\"$%d\", i)\n}\n\n\/\/ Quote quotes field name to avoid SQL parsing exceptions by using a reserved word as a field name\nfunc (q *QL) Quote(key string) string {\n\t\/\/return fmt.Sprintf(`\"%s\"`, key)\n\treturn key\n}\n\nfunc (q *QL) PrimaryKey(keys []string) string {\n\treturn \"\"\n}\n\n\/\/ DataTypeOf return data's sql type\nfunc (q *QL) DataTypeOf(field *model.StructField) (string, error) {\n\tvar dataValue, sqlType, _, additionalType = dialects.ParseFieldStructForDialect(field)\n\n\tif sqlType == \"\" {\n\t\tswitch dataValue.Kind() {\n\t\tcase reflect.Bool:\n\t\t\tsqlType = \"boolean\"\n\t\tcase reflect.Int,\n\t\t\treflect.Int8,\n\t\t\treflect.Int16,\n\t\t\treflect.Int32,\n\t\t\treflect.Int64,\n\t\t\treflect.Uint,\n\t\t\treflect.Uint8,\n\t\t\treflect.Uint16,\n\t\t\treflect.Uint32,\n\t\t\treflect.Uint64,\n\t\t\treflect.Float32,\n\t\t\treflect.Float64,\n\t\t\treflect.String:\n\t\t\tsqlType = dataValue.Kind().String()\n\t\tcase reflect.Struct:\n\t\t\tswitch dataValue.Interface().(type) {\n\t\t\tcase time.Time:\n\t\t\t\tsqlType = \"time\"\n\t\t\tcase big.Int:\n\t\t\t\tsqlType = \"bigint\"\n\t\t\tcase big.Rat:\n\t\t\t\tsqlType = \"bigrat\"\n\t\t\t}\n\t\tdefault:\n\t\t\tif _, ok := dataValue.Interface().([]byte); ok {\n\t\t\t\tsqlType = \"blob\"\n\t\t\t}\n\t\t}\n\t}\n\n\tif sqlType == \"\" {\n\t\treturn \"\", fmt.Errorf(\"invalid sql type %s (%s) for ql\", dataValue.Type().Name(), dataValue.Kind().String())\n\t}\n\n\tif strings.TrimSpace(additionalType) == \"\" {\n\t\treturn sqlType, nil\n\t}\n\treturn fmt.Sprintf(\"%v %v\", sqlType, additionalType), nil\n}\n\n\/\/ HasIndex check has index or not\nfunc (q *QL) HasIndex(tableName string, indexName string) bool {\n\tquerry := \"select count() from __Index where Name=$1  && TableName=$2\"\n\tvar count int\n\terr := q.db.QueryRow(querry, indexName, tableName).Scan(&count)\n\tif err != nil {\n\t\t\/\/TODO; Propery log or return this error?\n\t}\n\treturn count > 0\n}\n\n\/\/ HasForeignKey check has foreign key or not\nfunc (q *QL) HasForeignKey(tableName string, foreignKeyName string) bool {\n\treturn false\n}\n\n\/\/ RemoveIndex remove index\nfunc (q *QL) RemoveIndex(tableName string, indexName string) error {\n\ttx, err := q.db.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = tx.Exec(fmt.Sprintf(\"DROP INDEX %v\", indexName))\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn tx.Commit()\n}\n\n\/\/ HasTable check has table or not\nfunc (q *QL) HasTable(tableName string) bool {\n\tquerry := \"select count() from __Table where Name=$1\"\n\tvar count int\n\terr := q.db.QueryRow(querry, tableName).Scan(&count)\n\tif err != nil {\n\t\t\/\/TODO; Propery log or return this error?\n\t}\n\treturn count > 0\n}\n\n\/\/ HasColumn check has column or not\nfunc (q *QL) HasColumn(tableName string, columnName string) bool {\n\tquerry := \"select count() from __Column where Name=$1  && TableName=$2\"\n\tvar count int\n\terr := q.db.QueryRow(querry, columnName, tableName).Scan(&count)\n\tif err != nil {\n\t\t\/\/TODO; Propery log or return this error?\n\t}\n\treturn count > 0\n}\n\n\/\/ LimitAndOffsetSQL return generated SQL with Limit and Offset, as mssql has special case\nfunc (q *QL) LimitAndOffsetSQL(limit, offset interface{}) (sql string) {\n\tif limit != nil {\n\t\tif parsedLimit, err := strconv.ParseInt(fmt.Sprint(limit), 0, 0); err == nil && parsedLimit > 0 {\n\t\t\tsql += fmt.Sprintf(\" LIMIT %d\", parsedLimit)\n\t\t}\n\t}\n\tif offset != nil {\n\t\tif parsedOffset, err := strconv.ParseInt(fmt.Sprint(offset), 0, 0); err == nil && parsedOffset > 0 {\n\t\t\tsql += fmt.Sprintf(\" OFFSET %d\", parsedOffset)\n\t\t}\n\t}\n\treturn\n}\n\n\/\/ SelectFromDummyTable return select values, for most dbs, `SELECT values` just works, mysql needs `SELECT value FROM DUAL`\nfunc (q *QL) SelectFromDummyTable() string {\n\treturn \"\"\n}\n\n\/\/ LastInsertIDReturningSuffix ost dbs support LastInsertId, but postgres needs to use `RETURNING`\nfunc (q *QL) LastInsertIDReturningSuffix(tableName, columnName string) string {\n\treturn \"\"\n}\n\n\/\/ BuildForeignKeyName returns a foreign key name for the given table, field and reference\nfunc (q *QL) BuildForeignKeyName(tableName, field, dest string) string {\n\tkeyName := fmt.Sprintf(\"%s_%s_%s_foreign\", tableName, field, dest)\n\tkeyName = regexes.KeyName.ReplaceAllString(keyName, \"_\")\n\treturn keyName\n}\n\n\/\/ CurrentDatabase return current database name\nfunc (q *QL) CurrentDatabase() string {\n\treturn \"\"\n}\n<commit_msg>[dialects] Add godoc<commit_after>\/\/ Package ql exposes implementations and functions that enables ngorm to work\n\/\/ with ql database.\n\/\/\n\/\/ ql is an embedded sql database. This database doesn't conform 100% qith the\n\/\/ SQL standard. The link to the project is https:\/\/github.com\/cznic\/ql\npackage ql\n\nimport (\n\t\"fmt\"\n\t\"math\/big\"\n\t\"reflect\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/gernest\/ngorm\/dialects\"\n\t\"github.com\/gernest\/ngorm\/model\"\n\t\"github.com\/gernest\/ngorm\/regexes\"\n)\n\n\/\/QL implements the dialects.Dialect interface that uses ql database as the SQl\n\/\/backend.\n\/\/\n\/\/ For some reason the ql database doesn't support multiple databases, as\n\/\/ databases are file based. So, the name of the file is the name of the\n\/\/ database.. Which doesn't affect the querries, since the database name is\n\/\/ irrelevant assuming the SQLCommon interface is the handle over the open\n\/\/ database.\ntype QL struct {\n\tname string\n\tdb   model.SQLCommon\n}\n\n\/\/ Memory returns the dialect for in memory ql database. This is not persistent\n\/\/ everything will be lost when the process exits.\nfunc Memory() *QL {\n\treturn &QL{name: \"ql-mem\"}\n}\n\n\/\/File returns the dialcet for file backed ql database. This is the recommended\n\/\/way use the Memory only for testing else you might lose all of your data.\nfunc File() *QL {\n\treturn &QL{name: \"ql\"}\n}\n\n\/\/ GetName get dialect's name\nfunc (q *QL) GetName() string {\n\treturn q.name\n}\n\n\/\/ SetDB set db for dialect\nfunc (q *QL) SetDB(db model.SQLCommon) {\n\tq.db = db\n}\n\n\/\/ BindVar return the placeholder for actual values in SQL statements, in many dbs it is \"?\", Postgres using $1\nfunc (q QL) BindVar(i int) string {\n\treturn fmt.Sprintf(\"$%d\", i)\n}\n\n\/\/ Quote quotes field name to avoid SQL parsing exceptions by using a reserved word as a field name\nfunc (q *QL) Quote(key string) string {\n\t\/\/return fmt.Sprintf(`\"%s\"`, key)\n\treturn key\n}\n\n\/\/PrimaryKey implements dialects.Dialect interface. This is supposed to return a\n\/\/comma separated string of primary keys.\n\/\/\n\/\/ ql does not support PRIMARY KEY so no matter how many keys are passed this\n\/\/ method will return an empty string.\nfunc (q *QL) PrimaryKey(keys []string) string {\n\treturn \"\"\n}\n\n\/\/ DataTypeOf return data's sql type\nfunc (q *QL) DataTypeOf(field *model.StructField) (string, error) {\n\tvar dataValue, sqlType, _, additionalType = dialects.ParseFieldStructForDialect(field)\n\n\tif sqlType == \"\" {\n\t\tswitch dataValue.Kind() {\n\t\tcase reflect.Bool:\n\t\t\tsqlType = \"boolean\"\n\t\tcase reflect.Int,\n\t\t\treflect.Int8,\n\t\t\treflect.Int16,\n\t\t\treflect.Int32,\n\t\t\treflect.Int64,\n\t\t\treflect.Uint,\n\t\t\treflect.Uint8,\n\t\t\treflect.Uint16,\n\t\t\treflect.Uint32,\n\t\t\treflect.Uint64,\n\t\t\treflect.Float32,\n\t\t\treflect.Float64,\n\t\t\treflect.String:\n\t\t\tsqlType = dataValue.Kind().String()\n\t\tcase reflect.Struct:\n\t\t\tswitch dataValue.Interface().(type) {\n\t\t\tcase time.Time:\n\t\t\t\tsqlType = \"time\"\n\t\t\tcase big.Int:\n\t\t\t\tsqlType = \"bigint\"\n\t\t\tcase big.Rat:\n\t\t\t\tsqlType = \"bigrat\"\n\t\t\t}\n\t\tdefault:\n\t\t\tif _, ok := dataValue.Interface().([]byte); ok {\n\t\t\t\tsqlType = \"blob\"\n\t\t\t}\n\t\t}\n\t}\n\n\tif sqlType == \"\" {\n\t\treturn \"\", fmt.Errorf(\"invalid sql type %s (%s) for ql\", dataValue.Type().Name(), dataValue.Kind().String())\n\t}\n\n\tif strings.TrimSpace(additionalType) == \"\" {\n\t\treturn sqlType, nil\n\t}\n\treturn fmt.Sprintf(\"%v %v\", sqlType, additionalType), nil\n}\n\n\/\/ HasIndex check has index or not\nfunc (q *QL) HasIndex(tableName string, indexName string) bool {\n\tquerry := \"select count() from __Index where Name=$1  && TableName=$2\"\n\tvar count int\n\terr := q.db.QueryRow(querry, indexName, tableName).Scan(&count)\n\tif err != nil {\n\t\t\/\/TODO; Propery log or return this error?\n\t}\n\treturn count > 0\n}\n\n\/\/ HasForeignKey check has foreign key or not\nfunc (q *QL) HasForeignKey(tableName string, foreignKeyName string) bool {\n\treturn false\n}\n\n\/\/ RemoveIndex remove index\nfunc (q *QL) RemoveIndex(tableName string, indexName string) error {\n\ttx, err := q.db.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = tx.Exec(fmt.Sprintf(\"DROP INDEX %v\", indexName))\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn tx.Commit()\n}\n\n\/\/ HasTable check has table or not\nfunc (q *QL) HasTable(tableName string) bool {\n\tquerry := \"select count() from __Table where Name=$1\"\n\tvar count int\n\terr := q.db.QueryRow(querry, tableName).Scan(&count)\n\tif err != nil {\n\t\t\/\/TODO; Propery log or return this error?\n\t}\n\treturn count > 0\n}\n\n\/\/ HasColumn check has column or not\nfunc (q *QL) HasColumn(tableName string, columnName string) bool {\n\tquerry := \"select count() from __Column where Name=$1  && TableName=$2\"\n\tvar count int\n\terr := q.db.QueryRow(querry, columnName, tableName).Scan(&count)\n\tif err != nil {\n\t\t\/\/TODO; Propery log or return this error?\n\t}\n\treturn count > 0\n}\n\n\/\/ LimitAndOffsetSQL return generated SQL with Limit and Offset, as mssql has special case\nfunc (q *QL) LimitAndOffsetSQL(limit, offset interface{}) (sql string) {\n\tif limit != nil {\n\t\tif parsedLimit, err := strconv.ParseInt(fmt.Sprint(limit), 0, 0); err == nil && parsedLimit > 0 {\n\t\t\tsql += fmt.Sprintf(\" LIMIT %d\", parsedLimit)\n\t\t}\n\t}\n\tif offset != nil {\n\t\tif parsedOffset, err := strconv.ParseInt(fmt.Sprint(offset), 0, 0); err == nil && parsedOffset > 0 {\n\t\t\tsql += fmt.Sprintf(\" OFFSET %d\", parsedOffset)\n\t\t}\n\t}\n\treturn\n}\n\n\/\/ SelectFromDummyTable return select values, for most dbs, `SELECT values` just works, mysql needs `SELECT value FROM DUAL`\nfunc (q *QL) SelectFromDummyTable() string {\n\treturn \"\"\n}\n\n\/\/ LastInsertIDReturningSuffix ost dbs support LastInsertId, but postgres needs to use `RETURNING`\nfunc (q *QL) LastInsertIDReturningSuffix(tableName, columnName string) string {\n\treturn \"\"\n}\n\n\/\/ BuildForeignKeyName returns a foreign key name for the given table, field and reference\nfunc (q *QL) BuildForeignKeyName(tableName, field, dest string) string {\n\tkeyName := fmt.Sprintf(\"%s_%s_%s_foreign\", tableName, field, dest)\n\tkeyName = regexes.KeyName.ReplaceAllString(keyName, \"_\")\n\treturn keyName\n}\n\n\/\/ CurrentDatabase return current database name\nfunc (q *QL) CurrentDatabase() string {\n\treturn \"\"\n}\n<|endoftext|>"}
{"text":"<commit_before>package git\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"net\/url\"\n\t\"testing\"\n\n\t\"github.com\/google\/go-github\/github\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"github.com\/stretchr\/testify\/require\"\n\n\t\"golang.org\/x\/net\/context\"\n)\n\nfunc TestNewGithubRepositories_WithToken(t *testing.T) {\n\tctx := context.WithValue(context.Background(), GithubToken, \"secret_token\")\n\n\tr, err := NewGithubRepositories(ctx)\n\trequire.NoError(t, err, \"Expected NewGithubRepositories to succeed\")\n\tassert.NotNil(t, r, \"Expected NewGithubRepositories to return new instance\")\n}\n\nfunc TestNewGithubRepositories_NoToken(t *testing.T) {\n\t_, err := NewGithubRepositories(context.Background())\n\tassert.Error(t, err, \"Expected NewGithubRepositories to return an error\")\n}\n\nfunc TestNewGithubRepositories_EmptyToken(t *testing.T) {\n\tctx := context.WithValue(context.Background(), GithubToken, \"\")\n\n\t_, err := NewGithubRepositories(ctx)\n\tassert.Error(t, err, \"Expected NewGithubRepositories to return an error\")\n}\n\nfunc TestGithubRepositoriesAll_SingleRepository_DefaultFields(t *testing.T) {\n\tctx, mux, teardown := setup()\n\tdefer teardown()\n\n\tmux.HandleFunc(\"\/user\/repos\", func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprint(w, `[{\n                    \"full_name\": \"user1\/repo1\",\n                    \"git_url\": \"git@github.com:user1\/repo1.git\"\n                }]`)\n\t})\n\n\tgithubRepos, err := NewGithubRepositories(ctx)\n\trequire.NoError(t, err)\n\n\trepos, err := githubRepos.All()\n\trequire.NoError(t, err)\n\n\tif assert.Len(t, repos, 1) {\n\t\trepo := repos[0]\n\t\tassert.Equal(t, repo.FullName, \"user1\/repo1\")\n\t\tassert.Equal(t, repo.Master, \"master\")\n\t\tassert.Empty(t, repo.Description)\n\t\tassert.Empty(t, repo.GitURL)\n\t\tassert.Empty(t, repo.HTMLURL)\n\t}\n}\n\nfunc TestGithubRepositoriesAll_SingleRepository_AllFields(t *testing.T) {\n\tctx, mux, teardown := setup()\n\tdefer teardown()\n\n\tmux.HandleFunc(\"\/user\/repos\", func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprint(w, `[{\n                    \"full_name\": \"user1\/repo1\",\n                    \"description\": \"Repo1\",\n                    \"default_branch\": \"production\",\n                    \"git_url\": \"git@github.com:user1\/repo1.git\",\n                    \"html_url\": \"https:\/\/github.com\/user1\/repo1\"\n                }]`)\n\t})\n\n\tgithubRepos, err := NewGithubRepositories(ctx)\n\trequire.NoError(t, err)\n\n\trepos, err := githubRepos.All()\n\trequire.NoError(t, err)\n\n\tif assert.Len(t, repos, 1) {\n\t\trepo := repos[0]\n\t\tassert.Equal(t, repo.FullName, \"user1\/repo1\")\n\t\tassert.Equal(t, repo.Description, \"Repo1\")\n\t\tassert.Equal(t, repo.Master, \"production\")\n\t\tassert.Empty(t, repo.GitURL)\n\t}\n}\n\nfunc TestGithubRepositoriesAll_MultipleRepositories(t *testing.T) {\n\tctx, mux, teardown := setup()\n\tdefer teardown()\n\n\tmux.HandleFunc(\"\/user\/repos\", func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprint(w, `[{\n                    \"full_name\": \"user1\/repo1\",\n                    \"git_url\": \"https:\/\/github.com\/user1\/repo1\"\n                },{\n                    \"full_name\": \"user2\/repo2\",\n                    \"git_url\": \"https:\/\/github.com\/user2\/repo2\"\n                }]`)\n\t})\n\n\tgithubRepos, err := NewGithubRepositories(ctx)\n\trequire.NoError(t, err)\n\n\trepos, err := githubRepos.All()\n\trequire.NoError(t, err)\n\n\tassert.Len(t, repos, 2)\n}\n\nfunc TestGithubRepositoriesAll_SkipWithoutGitURL(t *testing.T) {\n\tctx, mux, teardown := setup()\n\tdefer teardown()\n\n\tmux.HandleFunc(\"\/user\/repos\", func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprint(w, `[{\n                    \"full_name\": \"user1\/repo1\"\n                },{\n                    \"full_name\": \"user2\/repo2\",\n                    \"git_url\": \"git:git@github.com:user2\/repo2.git\"\n                }]`)\n\t})\n\n\tgithubRepos, err := NewGithubRepositories(ctx)\n\trequire.NoError(t, err)\n\n\trepos, err := githubRepos.All()\n\trequire.NoError(t, err)\n\n\tif assert.Len(t, repos, 1, \"Should exclude one repository without git_url\") {\n\t\tassert.Equal(t, repos[0].FullName, \"user2\/repo2\")\n\t}\n}\n\nfunc TestGithubRepositoriesAll_SkipWithoutFullName(t *testing.T) {\n\tctx, mux, teardown := setup()\n\tdefer teardown()\n\n\tmux.HandleFunc(\"\/user\/repos\", func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprint(w, `[{\n                    \"full_name\": \"user1\/repo1\",\n                    \"git_url\": \"git:git@github.com:user1\/repo1.git\"\n                },{\n                    \"git_url\": \"git:git@github.com:user2\/repo2.git\"\n                }]`)\n\t})\n\n\tgithubRepos, err := NewGithubRepositories(ctx)\n\trequire.NoError(t, err)\n\n\trepos, err := githubRepos.All()\n\trequire.NoError(t, err)\n\n\tif assert.Len(t, repos, 1, \"Should exclude one repository without full_name\") {\n\t\tassert.Equal(t, repos[0].FullName, \"user1\/repo1\")\n\t}\n}\n\nfunc TestGithubRepositoriesAll_HandlePagination(t *testing.T) {\n\tctx, mux, teardown := setup()\n\tdefer teardown()\n\n\tmux.HandleFunc(\"\/user\/repos\", func(w http.ResponseWriter, r *http.Request) {\n\t\tif page := r.FormValue(\"page\"); page == \"\" || page == \"1\" {\n\t\t\tperPage := r.FormValue(\"per_page\")\n\t\t\tif perPage == \"\" {\n\t\t\t\tperPage = \"30\"\n\t\t\t}\n\n\t\t\tw.Header().Set(\"Link\", fmt.Sprintf(`<https:\/\/api.github.com\/user\/repos?page=2&per_page=%s>; rel=\"next\"`, perPage))\n\t\t}\n\n\t\tfmt.Fprint(w, `[{\"full_name\": \"user1\/repo1\",\"git_url\": \"git:git@github.com:user1\/repo1.git\"}]`)\n\t})\n\n\tgithubRepos, err := NewGithubRepositories(ctx)\n\trequire.NoError(t, err)\n\n\trepos, err := githubRepos.All()\n\trequire.NoError(t, err)\n\n\tassert.Len(t, repos, 2)\n}\n\nfunc setup() (ctx context.Context, mux *http.ServeMux, teardownFn func()) {\n\tmux = http.NewServeMux()\n\tserver := httptest.NewServer(mux)\n\n\tclient := github.NewClient(nil)\n\turl, _ := url.Parse(server.URL)\n\tclient.BaseURL = url\n\n\tctx = context.Background()\n\tctx = context.WithValue(ctx, GithubToken, \"secret_token\")\n\tctx = context.WithValue(ctx, httpClient, client)\n\n\treturn ctx, mux, server.Close\n}\n<commit_msg>Add tests for git.ParseRepositoryName<commit_after>package git\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"net\/url\"\n\t\"testing\"\n\n\t\"github.com\/google\/go-github\/github\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"github.com\/stretchr\/testify\/require\"\n\n\t\"golang.org\/x\/net\/context\"\n)\n\nfunc TestParseRepositoryName(t *testing.T) {\n\towner, repo := ParseRepositoryName(\"test\/me\")\n\tassert.Equal(t, owner, \"test\")\n\tassert.Equal(t, repo, \"me\")\n}\n\nfunc TestNewGithubRepositories_WithToken(t *testing.T) {\n\tctx := context.WithValue(context.Background(), GithubToken, \"secret_token\")\n\n\tr, err := NewGithubRepositories(ctx)\n\trequire.NoError(t, err, \"Expected NewGithubRepositories to succeed\")\n\tassert.NotNil(t, r, \"Expected NewGithubRepositories to return new instance\")\n}\n\nfunc TestNewGithubRepositories_NoToken(t *testing.T) {\n\t_, err := NewGithubRepositories(context.Background())\n\tassert.Error(t, err, \"Expected NewGithubRepositories to return an error\")\n}\n\nfunc TestNewGithubRepositories_EmptyToken(t *testing.T) {\n\tctx := context.WithValue(context.Background(), GithubToken, \"\")\n\n\t_, err := NewGithubRepositories(ctx)\n\tassert.Error(t, err, \"Expected NewGithubRepositories to return an error\")\n}\n\nfunc TestGithubRepositoriesAll_SingleRepository_DefaultFields(t *testing.T) {\n\tctx, mux, teardown := setup()\n\tdefer teardown()\n\n\tmux.HandleFunc(\"\/user\/repos\", func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprint(w, `[{\n                    \"full_name\": \"user1\/repo1\",\n                    \"git_url\": \"git@github.com:user1\/repo1.git\"\n                }]`)\n\t})\n\n\tgithubRepos, err := NewGithubRepositories(ctx)\n\trequire.NoError(t, err)\n\n\trepos, err := githubRepos.All()\n\trequire.NoError(t, err)\n\n\tif assert.Len(t, repos, 1) {\n\t\trepo := repos[0]\n\t\tassert.Equal(t, repo.FullName, \"user1\/repo1\")\n\t\tassert.Equal(t, repo.Master, \"master\")\n\t\tassert.Empty(t, repo.Description)\n\t\tassert.Empty(t, repo.GitURL)\n\t\tassert.Empty(t, repo.HTMLURL)\n\t}\n}\n\nfunc TestGithubRepositoriesAll_SingleRepository_AllFields(t *testing.T) {\n\tctx, mux, teardown := setup()\n\tdefer teardown()\n\n\tmux.HandleFunc(\"\/user\/repos\", func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprint(w, `[{\n                    \"full_name\": \"user1\/repo1\",\n                    \"description\": \"Repo1\",\n                    \"default_branch\": \"production\",\n                    \"git_url\": \"git@github.com:user1\/repo1.git\",\n                    \"html_url\": \"https:\/\/github.com\/user1\/repo1\"\n                }]`)\n\t})\n\n\tgithubRepos, err := NewGithubRepositories(ctx)\n\trequire.NoError(t, err)\n\n\trepos, err := githubRepos.All()\n\trequire.NoError(t, err)\n\n\tif assert.Len(t, repos, 1) {\n\t\trepo := repos[0]\n\t\tassert.Equal(t, repo.FullName, \"user1\/repo1\")\n\t\tassert.Equal(t, repo.Description, \"Repo1\")\n\t\tassert.Equal(t, repo.Master, \"production\")\n\t\tassert.Empty(t, repo.GitURL)\n\t}\n}\n\nfunc TestGithubRepositoriesAll_MultipleRepositories(t *testing.T) {\n\tctx, mux, teardown := setup()\n\tdefer teardown()\n\n\tmux.HandleFunc(\"\/user\/repos\", func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprint(w, `[{\n                    \"full_name\": \"user1\/repo1\",\n                    \"git_url\": \"https:\/\/github.com\/user1\/repo1\"\n                },{\n                    \"full_name\": \"user2\/repo2\",\n                    \"git_url\": \"https:\/\/github.com\/user2\/repo2\"\n                }]`)\n\t})\n\n\tgithubRepos, err := NewGithubRepositories(ctx)\n\trequire.NoError(t, err)\n\n\trepos, err := githubRepos.All()\n\trequire.NoError(t, err)\n\n\tassert.Len(t, repos, 2)\n}\n\nfunc TestGithubRepositoriesAll_SkipWithoutGitURL(t *testing.T) {\n\tctx, mux, teardown := setup()\n\tdefer teardown()\n\n\tmux.HandleFunc(\"\/user\/repos\", func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprint(w, `[{\n                    \"full_name\": \"user1\/repo1\"\n                },{\n                    \"full_name\": \"user2\/repo2\",\n                    \"git_url\": \"git:git@github.com:user2\/repo2.git\"\n                }]`)\n\t})\n\n\tgithubRepos, err := NewGithubRepositories(ctx)\n\trequire.NoError(t, err)\n\n\trepos, err := githubRepos.All()\n\trequire.NoError(t, err)\n\n\tif assert.Len(t, repos, 1, \"Should exclude one repository without git_url\") {\n\t\tassert.Equal(t, repos[0].FullName, \"user2\/repo2\")\n\t}\n}\n\nfunc TestGithubRepositoriesAll_SkipWithoutFullName(t *testing.T) {\n\tctx, mux, teardown := setup()\n\tdefer teardown()\n\n\tmux.HandleFunc(\"\/user\/repos\", func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprint(w, `[{\n                    \"full_name\": \"user1\/repo1\",\n                    \"git_url\": \"git:git@github.com:user1\/repo1.git\"\n                },{\n                    \"git_url\": \"git:git@github.com:user2\/repo2.git\"\n                }]`)\n\t})\n\n\tgithubRepos, err := NewGithubRepositories(ctx)\n\trequire.NoError(t, err)\n\n\trepos, err := githubRepos.All()\n\trequire.NoError(t, err)\n\n\tif assert.Len(t, repos, 1, \"Should exclude one repository without full_name\") {\n\t\tassert.Equal(t, repos[0].FullName, \"user1\/repo1\")\n\t}\n}\n\nfunc TestGithubRepositoriesAll_HandlePagination(t *testing.T) {\n\tctx, mux, teardown := setup()\n\tdefer teardown()\n\n\tmux.HandleFunc(\"\/user\/repos\", func(w http.ResponseWriter, r *http.Request) {\n\t\tif page := r.FormValue(\"page\"); page == \"\" || page == \"1\" {\n\t\t\tperPage := r.FormValue(\"per_page\")\n\t\t\tif perPage == \"\" {\n\t\t\t\tperPage = \"30\"\n\t\t\t}\n\n\t\t\tw.Header().Set(\"Link\", fmt.Sprintf(`<https:\/\/api.github.com\/user\/repos?page=2&per_page=%s>; rel=\"next\"`, perPage))\n\t\t}\n\n\t\tfmt.Fprint(w, `[{\"full_name\": \"user1\/repo1\",\"git_url\": \"git:git@github.com:user1\/repo1.git\"}]`)\n\t})\n\n\tgithubRepos, err := NewGithubRepositories(ctx)\n\trequire.NoError(t, err)\n\n\trepos, err := githubRepos.All()\n\trequire.NoError(t, err)\n\n\tassert.Len(t, repos, 2)\n}\n\nfunc setup() (ctx context.Context, mux *http.ServeMux, teardownFn func()) {\n\tmux = http.NewServeMux()\n\tserver := httptest.NewServer(mux)\n\n\tclient := github.NewClient(nil)\n\turl, _ := url.Parse(server.URL)\n\tclient.BaseURL = url\n\n\tctx = context.Background()\n\tctx = context.WithValue(ctx, GithubToken, \"secret_token\")\n\tctx = context.WithValue(ctx, httpClient, client)\n\n\treturn ctx, mux, server.Close\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2019 Istio Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage helmreconciler\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n\n\tappsv1 \"k8s.io\/api\/apps\/v1\"\n\tv1 \"k8s.io\/api\/core\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/wait\"\n\n\t\"k8s.io\/apimachinery\/pkg\/runtime\"\n\tutilerrors \"k8s.io\/apimachinery\/pkg\/util\/errors\"\n\t\"sigs.k8s.io\/controller-runtime\/pkg\/client\"\n\n\t\"istio.io\/api\/operator\/v1alpha1\"\n\tv1alpha12 \"istio.io\/istio\/operator\/pkg\/apis\/istio\/v1alpha1\"\n\t\"istio.io\/istio\/operator\/pkg\/name\"\n\t\"istio.io\/istio\/operator\/pkg\/object\"\n\t\"istio.io\/istio\/operator\/pkg\/translate\"\n\t\"istio.io\/istio\/operator\/pkg\/util\"\n\tbinversion \"istio.io\/istio\/operator\/version\"\n\t\"istio.io\/pkg\/log\"\n)\n\nconst (\n\tpollTimeout  = 100 * time.Second\n\tpollInterval = 2 * time.Second\n)\n\n\/\/ HelmReconciler reconciles resources rendered by a set of helm charts for a specific instances of a custom resource,\n\/\/ or deletes all resources associated with a specific instance of a custom resource.\ntype HelmReconciler struct {\n\tclient             client.Client\n\tcustomizer         RenderingCustomizer\n\tinstance           runtime.Object\n\tneedUpdateAndPrune bool\n}\n\n\/\/ NewHelmReconciler creates a HelmReconciler and returns a ptr to it\nfunc NewHelmReconciler(instance runtime.Object, customizer RenderingCustomizer, client client.Client) *HelmReconciler {\n\treturn &HelmReconciler{\n\t\tinstance:   instance,\n\t\tclient:     client,\n\t\tcustomizer: customizer,\n\t}\n}\n\n\/\/ Factory is a factory for creating HelmReconciler objects using the specified CustomizerFactory.\ntype Factory struct {\n\t\/\/ CustomizerFactory is a factory for creating the Customizer object for the HelmReconciler.\n\tCustomizerFactory RenderingCustomizerFactory\n}\n\n\/\/ New Returns a new HelmReconciler for the custom resource.\n\/\/ instance is the custom resource to be reconciled\/deleted.\n\/\/ client is the kubernetes client\n\/\/ logger is the logger\nfunc (f *Factory) New(instance runtime.Object, client client.Client) (*HelmReconciler, error) {\n\tdelegate, err := f.CustomizerFactory.NewCustomizer(instance)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\twrappedcustomizer, err := wrapCustomizer(instance, delegate)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treconciler := &HelmReconciler{client: client, customizer: wrappedcustomizer, instance: instance, needUpdateAndPrune: true}\n\twrappedcustomizer.RegisterReconciler(reconciler)\n\treturn reconciler, nil\n}\n\n\/\/ wrapCustomizer creates a new internalCustomizer object wrapping the delegate, by inject a LoggingRenderingListener,\n\/\/ an OwnerReferenceDecorator, and a PruningDetailsDecorator into a CompositeRenderingListener that includes the listener\n\/\/ from the delegate.  This ensures the HelmReconciler can properly implement pruning, etc.\n\/\/ instance is the custom resource to be processed by the HelmReconciler\n\/\/ delegate is the delegate\nfunc wrapCustomizer(instance runtime.Object, delegate RenderingCustomizer) (*SimpleRenderingCustomizer, error) {\n\townerReferenceDecorator, err := NewOwnerReferenceDecorator(instance)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &SimpleRenderingCustomizer{\n\t\tInputValue:          delegate.Input(),\n\t\tPruningDetailsValue: delegate.PruningDetails(),\n\t\tListenerValue: &CompositeRenderingListener{\n\t\t\tListeners: []RenderingListener{\n\t\t\t\t&LoggingRenderingListener{Level: 1},\n\t\t\t\townerReferenceDecorator,\n\t\t\t\tNewPruningMarkingsDecorator(delegate.PruningDetails()),\n\t\t\t\tdelegate.Listener(),\n\t\t\t},\n\t\t},\n\t}, nil\n}\n\n\/\/ Reconcile the resources associated with the custom resource instance.\nfunc (h *HelmReconciler) Reconcile() error {\n\t\/\/ any processing required before processing the charts\n\terr := h.customizer.Listener().BeginReconcile(h.instance)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ render charts\n\tmanifestMap, err := h.RenderCharts(h.customizer.Input())\n\tif err != nil {\n\t\t\/\/ TODO: this needs to update status to RECONCILING.\n\t\treturn err\n\t}\n\n\tstatus := h.processRecursive(manifestMap)\n\n\t\/\/ Delete any resources not in the manifest but managed by operator.\n\tvar errs util.Errors\n\tif h.needUpdateAndPrune {\n\t\terrs = util.AppendErr(errs, h.Prune(allObjectHashes(manifestMap), false))\n\t}\n\terrs = util.AppendErr(errs, h.customizer.Listener().EndReconcile(h.instance, status))\n\n\treturn errs.ToError()\n}\n\n\/\/ processRecursive processes the given manifests in an order of dependencies defined in h. Dependencies are a tree,\n\/\/ where a child must wait for the parent to complete before starting.\nfunc (h *HelmReconciler) processRecursive(manifests ChartManifestsMap) *v1alpha1.InstallStatus {\n\tdeps, dch := h.customizer.Input().GetProcessingOrder(manifests)\n\tcomponentStatus := make(map[string]*v1alpha1.InstallStatus_VersionStatus)\n\n\t\/\/ mu protects the shared InstallStatus componentStatus across goroutines\n\tvar mu sync.Mutex\n\t\/\/ wg waits for all manifest processing goroutines to finish\n\tvar wg sync.WaitGroup\n\n\tfor c, m := range manifests {\n\t\tc, m := c, m\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tcn := name.ComponentName(c)\n\t\t\tif s := dch[cn]; s != nil {\n\t\t\t\tlog.Infof(\"%s is waiting on dependency...\", c)\n\t\t\t\t<-s\n\t\t\t\tlog.Infof(\"Dependency for %s has completed, proceeding.\", c)\n\t\t\t}\n\n\t\t\t\/\/ Set status when reconciling starts\n\t\t\tstatus := v1alpha1.InstallStatus_RECONCILING\n\t\t\tmu.Lock()\n\t\t\tif _, ok := componentStatus[c]; !ok {\n\t\t\t\tcomponentStatus[c] = &v1alpha1.InstallStatus_VersionStatus{}\n\t\t\t\tcomponentStatus[c].Status = status\n\t\t\t}\n\t\t\tmu.Unlock()\n\n\t\t\t\/\/ Process manifests and get the status result\n\t\t\terrString := \"\"\n\t\t\tif len(m) == 0 {\n\t\t\t\tstatus = v1alpha1.InstallStatus_NONE\n\t\t\t} else {\n\t\t\t\tstatus = v1alpha1.InstallStatus_HEALTHY\n\t\t\t\tif cnt, err := h.ProcessManifest(m[0]); err != nil {\n\t\t\t\t\terrString = err.Error()\n\t\t\t\t\tstatus = v1alpha1.InstallStatus_ERROR\n\t\t\t\t} else if cnt == 0 {\n\t\t\t\t\tstatus = v1alpha1.InstallStatus_NONE\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ Update status based on the result\n\t\t\tmu.Lock()\n\t\t\tif status == v1alpha1.InstallStatus_NONE {\n\t\t\t\tdelete(componentStatus, c)\n\t\t\t} else {\n\t\t\t\tcomponentStatus[c].Status = status\n\t\t\t\tif errString != \"\" {\n\t\t\t\t\tcomponentStatus[c].Error = errString\n\t\t\t\t}\n\t\t\t}\n\t\t\tmu.Unlock()\n\n\t\t\t\/\/ Signal all the components that depend on us.\n\t\t\tfor _, ch := range deps[cn] {\n\t\t\t\tlog.Infof(\"Unblocking dependency %s.\", ch)\n\t\t\t\tdch[ch] <- struct{}{}\n\t\t\t}\n\t\t}()\n\t}\n\twg.Wait()\n\n\t\/\/ Update overall status\n\t\/\/ - If all components are HEALTHY, overall status is HEALTHY.\n\t\/\/ - If one or more components are RECONCILING and others are HEALTHY, overall status is RECONCILING.\n\t\/\/ - If one or more components are UPDATING and others are HEALTHY, overall status is UPDATING.\n\t\/\/ - If components are a mix of RECONCILING, UPDATING and HEALTHY, overall status is UPDATING.\n\t\/\/ - If any component is in ERROR state, overall status is ERROR.\n\toverallStatus := v1alpha1.InstallStatus_HEALTHY\n\tfor _, cs := range componentStatus {\n\t\tif cs.Status == v1alpha1.InstallStatus_ERROR {\n\t\t\toverallStatus = v1alpha1.InstallStatus_ERROR\n\t\t\tbreak\n\t\t} else if cs.Status == v1alpha1.InstallStatus_UPDATING {\n\t\t\toverallStatus = v1alpha1.InstallStatus_UPDATING\n\t\t\tbreak\n\t\t} else if cs.Status == v1alpha1.InstallStatus_RECONCILING {\n\t\t\toverallStatus = v1alpha1.InstallStatus_RECONCILING\n\t\t\tbreak\n\t\t}\n\t}\n\t\/\/ update status further based on the in cluster resources status if manifests processed successfully,\n\t\/\/ otherwise just use status obtained from processing manifests.\n\tif overallStatus == v1alpha1.InstallStatus_HEALTHY {\n\t\terr := h.checkResourceStatus(&componentStatus, &overallStatus)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"failed to check resource status %v\", err)\n\t\t}\n\t}\n\tout := &v1alpha1.InstallStatus{\n\t\tStatus:          overallStatus,\n\t\tComponentStatus: componentStatus,\n\t}\n\n\treturn out\n}\n\n\/\/ checkResourceStatus check and wait for resource to be ready,\n\/\/ update overallStatus and componentStatus correspondingly\nfunc (h *HelmReconciler) checkResourceStatus(componentStatus *map[string]*v1alpha1.InstallStatus_VersionStatus,\n\toverallStatus *v1alpha1.InstallStatus_Status) error {\n\tcs := h.client\n\tiop := h.GetInstance().(*v1alpha12.IstioOperator)\n\tif iop == nil {\n\t\treturn fmt.Errorf(\"failed to get IstioOperator instance\")\n\t}\n\tt, err := translate.NewTranslator(binversion.OperatorBinaryVersion.MinorVersion)\n\tif err != nil {\n\t\treturn err\n\t}\n\terrPoll := wait.Poll(pollInterval, pollTimeout, func() (bool, error) {\n\t\tfor cn := range *componentStatus {\n\t\t\tcnMap, ok := t.ComponentMaps[name.ComponentName(cn)]\n\t\t\tif ok && cnMap.ResourceName != \"\" {\n\t\t\t\tdp := &appsv1.Deployment{}\n\t\t\t\tkey := client.ObjectKey{Namespace: iop.Namespace, Name: cnMap.ResourceName}\n\t\t\t\terr := cs.Get(context.TODO(), key, dp)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Warnf(\"deployment: %v not found\", cnMap.ResourceName)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif dp.Status.ReadyReplicas != dp.Status.UnavailableReplicas+dp.Status.AvailableReplicas {\n\t\t\t\t\t(*componentStatus)[cn].Status = v1alpha1.InstallStatus_UPDATING\n\t\t\t\t\treturn false, nil\n\t\t\t\t}\n\t\t\t}\n\t\t\t(*componentStatus)[cn].Status = v1alpha1.InstallStatus_HEALTHY\n\t\t}\n\n\t\tpodList := &v1.PodList{}\n\t\terr := cs.List(context.TODO(), podList, client.InNamespace(iop.Namespace))\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tfor _, pod := range podList.Items {\n\t\t\tif len(pod.Status.Conditions) > 0 {\n\t\t\t\tfor _, condition := range pod.Status.Conditions {\n\t\t\t\t\tif condition.Type == v1.PodReady && condition.Status != v1.ConditionTrue {\n\t\t\t\t\t\treturn false, nil\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn true, nil\n\t})\n\tif errPoll != nil {\n\t\t*overallStatus = v1alpha1.InstallStatus_UPDATING\n\t}\n\treturn nil\n}\n\n\/\/ Delete resources associated with the custom resource instance\nfunc (h *HelmReconciler) Delete() error {\n\th.needUpdateAndPrune = true\n\tallErrors := []error{}\n\n\t\/\/ any processing required before processing the charts\n\terr := h.customizer.Listener().BeginDelete(h.instance)\n\tif err != nil {\n\t\tallErrors = append(allErrors, err)\n\t}\n\n\terr = h.customizer.Listener().BeginPrune(true)\n\tif err != nil {\n\t\tallErrors = append(allErrors, err)\n\t}\n\terr = h.Prune(nil, true)\n\tif err != nil {\n\t\tallErrors = append(allErrors, err)\n\t}\n\terr = h.customizer.Listener().EndPrune()\n\tif err != nil {\n\t\tallErrors = append(allErrors, err)\n\t}\n\n\t\/\/ any post processing required after deleting\n\terr = utilerrors.NewAggregate(allErrors)\n\tif listenerErr := h.customizer.Listener().EndDelete(h.instance, err); listenerErr != nil {\n\t\tlog.Errorf(\"error calling listener: %s\", listenerErr)\n\t}\n\n\t\/\/ return any errors\n\treturn err\n}\n\n\/\/ allObjectHashes returns a map with object hashes of all the objects contained in cmm as the keys.\nfunc allObjectHashes(cmm ChartManifestsMap) map[string]bool {\n\tret := make(map[string]bool)\n\tfor _, mm := range cmm {\n\t\tfor _, m := range mm {\n\t\t\tobjs, err := object.ParseK8sObjectsFromYAMLManifest(m.Content)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(err.Error())\n\t\t\t}\n\t\t\tfor _, o := range objs {\n\t\t\t\tret[o.Hash()] = true\n\t\t\t}\n\t\t}\n\t}\n\treturn ret\n}\n\n\/\/ GetClient returns the kubernetes client associated with this HelmReconciler\nfunc (h *HelmReconciler) GetClient() client.Client {\n\treturn h.client\n}\n\n\/\/ GetInstance returns the instance associated with this HelmReconciler\nfunc (h *HelmReconciler) GetInstance() runtime.Object {\n\treturn h.instance\n}\n\n\/\/ SetInstance set the instance associated with this HelmReconciler\nfunc (h *HelmReconciler) SetInstance(instance runtime.Object) {\n\th.instance = instance\n}\n\n\/\/ SetNeedUpdateAndPrune set the needUpdateAndPrune flag associated with this HelmReconciler\nfunc (h *HelmReconciler) SetNeedUpdateAndPrune(u bool) {\n\th.needUpdateAndPrune = u\n}\n<commit_msg>add container status check (#22924)<commit_after>\/\/ Copyright 2019 Istio Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage helmreconciler\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n\n\tappsv1 \"k8s.io\/api\/apps\/v1\"\n\tv1 \"k8s.io\/api\/core\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/wait\"\n\n\t\"k8s.io\/apimachinery\/pkg\/runtime\"\n\tutilerrors \"k8s.io\/apimachinery\/pkg\/util\/errors\"\n\t\"sigs.k8s.io\/controller-runtime\/pkg\/client\"\n\n\t\"istio.io\/api\/operator\/v1alpha1\"\n\tv1alpha12 \"istio.io\/istio\/operator\/pkg\/apis\/istio\/v1alpha1\"\n\t\"istio.io\/istio\/operator\/pkg\/name\"\n\t\"istio.io\/istio\/operator\/pkg\/object\"\n\t\"istio.io\/istio\/operator\/pkg\/translate\"\n\t\"istio.io\/istio\/operator\/pkg\/util\"\n\tbinversion \"istio.io\/istio\/operator\/version\"\n\t\"istio.io\/pkg\/log\"\n)\n\nconst (\n\tpollTimeout  = 100 * time.Second\n\tpollInterval = 2 * time.Second\n)\n\n\/\/ HelmReconciler reconciles resources rendered by a set of helm charts for a specific instances of a custom resource,\n\/\/ or deletes all resources associated with a specific instance of a custom resource.\ntype HelmReconciler struct {\n\tclient             client.Client\n\tcustomizer         RenderingCustomizer\n\tinstance           runtime.Object\n\tneedUpdateAndPrune bool\n}\n\n\/\/ NewHelmReconciler creates a HelmReconciler and returns a ptr to it\nfunc NewHelmReconciler(instance runtime.Object, customizer RenderingCustomizer, client client.Client) *HelmReconciler {\n\treturn &HelmReconciler{\n\t\tinstance:   instance,\n\t\tclient:     client,\n\t\tcustomizer: customizer,\n\t}\n}\n\n\/\/ Factory is a factory for creating HelmReconciler objects using the specified CustomizerFactory.\ntype Factory struct {\n\t\/\/ CustomizerFactory is a factory for creating the Customizer object for the HelmReconciler.\n\tCustomizerFactory RenderingCustomizerFactory\n}\n\n\/\/ New Returns a new HelmReconciler for the custom resource.\n\/\/ instance is the custom resource to be reconciled\/deleted.\n\/\/ client is the kubernetes client\n\/\/ logger is the logger\nfunc (f *Factory) New(instance runtime.Object, client client.Client) (*HelmReconciler, error) {\n\tdelegate, err := f.CustomizerFactory.NewCustomizer(instance)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\twrappedcustomizer, err := wrapCustomizer(instance, delegate)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treconciler := &HelmReconciler{client: client, customizer: wrappedcustomizer, instance: instance, needUpdateAndPrune: true}\n\twrappedcustomizer.RegisterReconciler(reconciler)\n\treturn reconciler, nil\n}\n\n\/\/ wrapCustomizer creates a new internalCustomizer object wrapping the delegate, by inject a LoggingRenderingListener,\n\/\/ an OwnerReferenceDecorator, and a PruningDetailsDecorator into a CompositeRenderingListener that includes the listener\n\/\/ from the delegate.  This ensures the HelmReconciler can properly implement pruning, etc.\n\/\/ instance is the custom resource to be processed by the HelmReconciler\n\/\/ delegate is the delegate\nfunc wrapCustomizer(instance runtime.Object, delegate RenderingCustomizer) (*SimpleRenderingCustomizer, error) {\n\townerReferenceDecorator, err := NewOwnerReferenceDecorator(instance)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &SimpleRenderingCustomizer{\n\t\tInputValue:          delegate.Input(),\n\t\tPruningDetailsValue: delegate.PruningDetails(),\n\t\tListenerValue: &CompositeRenderingListener{\n\t\t\tListeners: []RenderingListener{\n\t\t\t\t&LoggingRenderingListener{Level: 1},\n\t\t\t\townerReferenceDecorator,\n\t\t\t\tNewPruningMarkingsDecorator(delegate.PruningDetails()),\n\t\t\t\tdelegate.Listener(),\n\t\t\t},\n\t\t},\n\t}, nil\n}\n\n\/\/ Reconcile the resources associated with the custom resource instance.\nfunc (h *HelmReconciler) Reconcile() error {\n\t\/\/ any processing required before processing the charts\n\terr := h.customizer.Listener().BeginReconcile(h.instance)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ render charts\n\tmanifestMap, err := h.RenderCharts(h.customizer.Input())\n\tif err != nil {\n\t\t\/\/ TODO: this needs to update status to RECONCILING.\n\t\treturn err\n\t}\n\n\tstatus := h.processRecursive(manifestMap)\n\n\t\/\/ Delete any resources not in the manifest but managed by operator.\n\tvar errs util.Errors\n\tif h.needUpdateAndPrune {\n\t\terrs = util.AppendErr(errs, h.Prune(allObjectHashes(manifestMap), false))\n\t}\n\terrs = util.AppendErr(errs, h.customizer.Listener().EndReconcile(h.instance, status))\n\n\treturn errs.ToError()\n}\n\n\/\/ processRecursive processes the given manifests in an order of dependencies defined in h. Dependencies are a tree,\n\/\/ where a child must wait for the parent to complete before starting.\nfunc (h *HelmReconciler) processRecursive(manifests ChartManifestsMap) *v1alpha1.InstallStatus {\n\tdeps, dch := h.customizer.Input().GetProcessingOrder(manifests)\n\tcomponentStatus := make(map[string]*v1alpha1.InstallStatus_VersionStatus)\n\n\t\/\/ mu protects the shared InstallStatus componentStatus across goroutines\n\tvar mu sync.Mutex\n\t\/\/ wg waits for all manifest processing goroutines to finish\n\tvar wg sync.WaitGroup\n\n\tfor c, m := range manifests {\n\t\tc, m := c, m\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tcn := name.ComponentName(c)\n\t\t\tif s := dch[cn]; s != nil {\n\t\t\t\tlog.Infof(\"%s is waiting on dependency...\", c)\n\t\t\t\t<-s\n\t\t\t\tlog.Infof(\"Dependency for %s has completed, proceeding.\", c)\n\t\t\t}\n\n\t\t\t\/\/ Set status when reconciling starts\n\t\t\tstatus := v1alpha1.InstallStatus_RECONCILING\n\t\t\tmu.Lock()\n\t\t\tif _, ok := componentStatus[c]; !ok {\n\t\t\t\tcomponentStatus[c] = &v1alpha1.InstallStatus_VersionStatus{}\n\t\t\t\tcomponentStatus[c].Status = status\n\t\t\t}\n\t\t\tmu.Unlock()\n\n\t\t\t\/\/ Process manifests and get the status result\n\t\t\terrString := \"\"\n\t\t\tif len(m) == 0 {\n\t\t\t\tstatus = v1alpha1.InstallStatus_NONE\n\t\t\t} else {\n\t\t\t\tstatus = v1alpha1.InstallStatus_HEALTHY\n\t\t\t\tif cnt, err := h.ProcessManifest(m[0]); err != nil {\n\t\t\t\t\terrString = err.Error()\n\t\t\t\t\tstatus = v1alpha1.InstallStatus_ERROR\n\t\t\t\t} else if cnt == 0 {\n\t\t\t\t\tstatus = v1alpha1.InstallStatus_NONE\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ Update status based on the result\n\t\t\tmu.Lock()\n\t\t\tif status == v1alpha1.InstallStatus_NONE {\n\t\t\t\tdelete(componentStatus, c)\n\t\t\t} else {\n\t\t\t\tcomponentStatus[c].Status = status\n\t\t\t\tif errString != \"\" {\n\t\t\t\t\tcomponentStatus[c].Error = errString\n\t\t\t\t}\n\t\t\t}\n\t\t\tmu.Unlock()\n\n\t\t\t\/\/ Signal all the components that depend on us.\n\t\t\tfor _, ch := range deps[cn] {\n\t\t\t\tlog.Infof(\"Unblocking dependency %s.\", ch)\n\t\t\t\tdch[ch] <- struct{}{}\n\t\t\t}\n\t\t}()\n\t}\n\twg.Wait()\n\n\t\/\/ Update overall status\n\t\/\/ - If all components are HEALTHY, overall status is HEALTHY.\n\t\/\/ - If one or more components are RECONCILING and others are HEALTHY, overall status is RECONCILING.\n\t\/\/ - If one or more components are UPDATING and others are HEALTHY, overall status is UPDATING.\n\t\/\/ - If components are a mix of RECONCILING, UPDATING and HEALTHY, overall status is UPDATING.\n\t\/\/ - If any component is in ERROR state, overall status is ERROR.\n\toverallStatus := v1alpha1.InstallStatus_HEALTHY\n\tfor _, cs := range componentStatus {\n\t\tif cs.Status == v1alpha1.InstallStatus_ERROR {\n\t\t\toverallStatus = v1alpha1.InstallStatus_ERROR\n\t\t\tbreak\n\t\t} else if cs.Status == v1alpha1.InstallStatus_UPDATING {\n\t\t\toverallStatus = v1alpha1.InstallStatus_UPDATING\n\t\t\tbreak\n\t\t} else if cs.Status == v1alpha1.InstallStatus_RECONCILING {\n\t\t\toverallStatus = v1alpha1.InstallStatus_RECONCILING\n\t\t\tbreak\n\t\t}\n\t}\n\t\/\/ update status further based on the in cluster resources status if manifests processed successfully,\n\t\/\/ otherwise just use status obtained from processing manifests.\n\tif overallStatus == v1alpha1.InstallStatus_HEALTHY {\n\t\terr := h.checkResourceStatus(&componentStatus, &overallStatus)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"failed to check resource status %v\", err)\n\t\t}\n\t}\n\tout := &v1alpha1.InstallStatus{\n\t\tStatus:          overallStatus,\n\t\tComponentStatus: componentStatus,\n\t}\n\n\treturn out\n}\n\n\/\/ checkResourceStatus check and wait for resource to be ready,\n\/\/ update overallStatus and componentStatus correspondingly\nfunc (h *HelmReconciler) checkResourceStatus(componentStatus *map[string]*v1alpha1.InstallStatus_VersionStatus,\n\toverallStatus *v1alpha1.InstallStatus_Status) error {\n\tcs := h.client\n\tiop := h.GetInstance().(*v1alpha12.IstioOperator)\n\tif iop == nil {\n\t\treturn fmt.Errorf(\"failed to get IstioOperator instance\")\n\t}\n\tt, err := translate.NewTranslator(binversion.OperatorBinaryVersion.MinorVersion)\n\tif err != nil {\n\t\treturn err\n\t}\n\terrPoll := wait.Poll(pollInterval, pollTimeout, func() (bool, error) {\n\t\tfor cn := range *componentStatus {\n\t\t\tcnMap, ok := t.ComponentMaps[name.ComponentName(cn)]\n\t\t\tif ok && cnMap.ResourceName != \"\" {\n\t\t\t\tdp := &appsv1.Deployment{}\n\t\t\t\tkey := client.ObjectKey{Namespace: iop.Namespace, Name: cnMap.ResourceName}\n\t\t\t\terr := cs.Get(context.TODO(), key, dp)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Warnf(\"deployment: %v not found\", cnMap.ResourceName)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif dp.Status.ReadyReplicas != dp.Status.UnavailableReplicas+dp.Status.AvailableReplicas {\n\t\t\t\t\t(*componentStatus)[cn].Status = v1alpha1.InstallStatus_UPDATING\n\t\t\t\t\treturn false, nil\n\t\t\t\t}\n\t\t\t}\n\t\t\t(*componentStatus)[cn].Status = v1alpha1.InstallStatus_HEALTHY\n\t\t}\n\n\t\tpodList := &v1.PodList{}\n\t\terr := cs.List(context.TODO(), podList, client.InNamespace(iop.Namespace))\n\t\tif err != nil {\n\t\t\treturn false, err\n\t\t}\n\t\tfor _, pod := range podList.Items {\n\t\t\tif len(pod.Status.Conditions) > 0 {\n\t\t\t\tfor _, condition := range pod.Status.Conditions {\n\t\t\t\t\tif condition.Type == v1.PodReady && condition.Status != v1.ConditionTrue {\n\t\t\t\t\t\treturn false, nil\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif pod.Status.Phase != v1.PodSucceeded && pod.Status.Phase != v1.PodRunning {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\tif pod.Status.Phase == v1.PodRunning {\n\t\t\t\tfor _, containerStatus := range pod.Status.ContainerStatuses {\n\t\t\t\t\tif !containerStatus.Ready {\n\t\t\t\t\t\treturn false, nil\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn true, nil\n\t})\n\tif errPoll != nil {\n\t\t*overallStatus = v1alpha1.InstallStatus_UPDATING\n\t}\n\treturn nil\n}\n\n\/\/ Delete resources associated with the custom resource instance\nfunc (h *HelmReconciler) Delete() error {\n\th.needUpdateAndPrune = true\n\tallErrors := []error{}\n\n\t\/\/ any processing required before processing the charts\n\terr := h.customizer.Listener().BeginDelete(h.instance)\n\tif err != nil {\n\t\tallErrors = append(allErrors, err)\n\t}\n\n\terr = h.customizer.Listener().BeginPrune(true)\n\tif err != nil {\n\t\tallErrors = append(allErrors, err)\n\t}\n\terr = h.Prune(nil, true)\n\tif err != nil {\n\t\tallErrors = append(allErrors, err)\n\t}\n\terr = h.customizer.Listener().EndPrune()\n\tif err != nil {\n\t\tallErrors = append(allErrors, err)\n\t}\n\n\t\/\/ any post processing required after deleting\n\terr = utilerrors.NewAggregate(allErrors)\n\tif listenerErr := h.customizer.Listener().EndDelete(h.instance, err); listenerErr != nil {\n\t\tlog.Errorf(\"error calling listener: %s\", listenerErr)\n\t}\n\n\t\/\/ return any errors\n\treturn err\n}\n\n\/\/ allObjectHashes returns a map with object hashes of all the objects contained in cmm as the keys.\nfunc allObjectHashes(cmm ChartManifestsMap) map[string]bool {\n\tret := make(map[string]bool)\n\tfor _, mm := range cmm {\n\t\tfor _, m := range mm {\n\t\t\tobjs, err := object.ParseK8sObjectsFromYAMLManifest(m.Content)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(err.Error())\n\t\t\t}\n\t\t\tfor _, o := range objs {\n\t\t\t\tret[o.Hash()] = true\n\t\t\t}\n\t\t}\n\t}\n\treturn ret\n}\n\n\/\/ GetClient returns the kubernetes client associated with this HelmReconciler\nfunc (h *HelmReconciler) GetClient() client.Client {\n\treturn h.client\n}\n\n\/\/ GetInstance returns the instance associated with this HelmReconciler\nfunc (h *HelmReconciler) GetInstance() runtime.Object {\n\treturn h.instance\n}\n\n\/\/ SetInstance set the instance associated with this HelmReconciler\nfunc (h *HelmReconciler) SetInstance(instance runtime.Object) {\n\th.instance = instance\n}\n\n\/\/ SetNeedUpdateAndPrune set the needUpdateAndPrune flag associated with this HelmReconciler\nfunc (h *HelmReconciler) SetNeedUpdateAndPrune(u bool) {\n\th.needUpdateAndPrune = u\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2017 The go-github AUTHORS. All rights reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage github\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"testing\"\n\n\t\"github.com\/google\/go-cmp\/cmp\"\n)\n\nfunc TestMarketplaceService_ListPlans(t *testing.T) {\n\tclient, mux, _, teardown := setup()\n\tdefer teardown()\n\n\tmux.HandleFunc(\"\/marketplace_listing\/plans\", func(w http.ResponseWriter, r *http.Request) {\n\t\ttestMethod(t, r, \"GET\")\n\t\ttestFormValues(t, r, values{\n\t\t\t\"page\":     \"1\",\n\t\t\t\"per_page\": \"2\",\n\t\t})\n\t\tfmt.Fprint(w, `[{\"id\":1}]`)\n\t})\n\n\topt := &ListOptions{Page: 1, PerPage: 2}\n\tclient.Marketplace.Stubbed = false\n\tctx := context.Background()\n\tplans, _, err := client.Marketplace.ListPlans(ctx, opt)\n\tif err != nil {\n\t\tt.Errorf(\"Marketplace.ListPlans returned error: %v\", err)\n\t}\n\n\twant := []*MarketplacePlan{{ID: Int64(1)}}\n\tif !cmp.Equal(plans, want) {\n\t\tt.Errorf(\"Marketplace.ListPlans returned %+v, want %+v\", plans, want)\n\t}\n\n\tconst methodName = \"ListPlans\"\n\ttestNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) {\n\t\tgot, resp, err := client.Marketplace.ListPlans(ctx, opt)\n\t\tif got != nil {\n\t\t\tt.Errorf(\"testNewRequestAndDoFailure %v = %#v, want nil\", methodName, got)\n\t\t}\n\t\treturn resp, err\n\t})\n}\n\nfunc TestMarketplaceService_Stubbed_ListPlans(t *testing.T) {\n\tclient, mux, _, teardown := setup()\n\tdefer teardown()\n\n\tmux.HandleFunc(\"\/marketplace_listing\/stubbed\/plans\", func(w http.ResponseWriter, r *http.Request) {\n\t\ttestMethod(t, r, \"GET\")\n\t\tfmt.Fprint(w, `[{\"id\":1}]`)\n\t})\n\n\topt := &ListOptions{Page: 1, PerPage: 2}\n\tclient.Marketplace.Stubbed = true\n\tctx := context.Background()\n\tplans, _, err := client.Marketplace.ListPlans(ctx, opt)\n\tif err != nil {\n\t\tt.Errorf(\"Marketplace.ListPlans (Stubbed) returned error: %v\", err)\n\t}\n\n\twant := []*MarketplacePlan{{ID: Int64(1)}}\n\tif !cmp.Equal(plans, want) {\n\t\tt.Errorf(\"Marketplace.ListPlans (Stubbed) returned %+v, want %+v\", plans, want)\n\t}\n}\n\nfunc TestMarketplaceService_ListPlanAccountsForPlan(t *testing.T) {\n\tclient, mux, _, teardown := setup()\n\tdefer teardown()\n\n\tmux.HandleFunc(\"\/marketplace_listing\/plans\/1\/accounts\", func(w http.ResponseWriter, r *http.Request) {\n\t\ttestMethod(t, r, \"GET\")\n\t\tfmt.Fprint(w, `[{\"id\":1}]`)\n\t})\n\n\topt := &ListOptions{Page: 1, PerPage: 2}\n\tclient.Marketplace.Stubbed = false\n\tctx := context.Background()\n\taccounts, _, err := client.Marketplace.ListPlanAccountsForPlan(ctx, 1, opt)\n\tif err != nil {\n\t\tt.Errorf(\"Marketplace.ListPlanAccountsForPlan returned error: %v\", err)\n\t}\n\n\twant := []*MarketplacePlanAccount{{ID: Int64(1)}}\n\tif !cmp.Equal(accounts, want) {\n\t\tt.Errorf(\"Marketplace.ListPlanAccountsForPlan returned %+v, want %+v\", accounts, want)\n\t}\n\n\tconst methodName = \"ListPlanAccountsForPlan\"\n\ttestNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) {\n\t\tgot, resp, err := client.Marketplace.ListPlanAccountsForPlan(ctx, 1, opt)\n\t\tif got != nil {\n\t\t\tt.Errorf(\"testNewRequestAndDoFailure %v = %#v, want nil\", methodName, got)\n\t\t}\n\t\treturn resp, err\n\t})\n}\n\nfunc TestMarketplaceService_Stubbed_ListPlanAccountsForPlan(t *testing.T) {\n\tclient, mux, _, teardown := setup()\n\tdefer teardown()\n\n\tmux.HandleFunc(\"\/marketplace_listing\/stubbed\/plans\/1\/accounts\", func(w http.ResponseWriter, r *http.Request) {\n\t\ttestMethod(t, r, \"GET\")\n\t\tfmt.Fprint(w, `[{\"id\":1}]`)\n\t})\n\n\topt := &ListOptions{Page: 1, PerPage: 2}\n\tclient.Marketplace.Stubbed = true\n\tctx := context.Background()\n\taccounts, _, err := client.Marketplace.ListPlanAccountsForPlan(ctx, 1, opt)\n\tif err != nil {\n\t\tt.Errorf(\"Marketplace.ListPlanAccountsForPlan (Stubbed) returned error: %v\", err)\n\t}\n\n\twant := []*MarketplacePlanAccount{{ID: Int64(1)}}\n\tif !cmp.Equal(accounts, want) {\n\t\tt.Errorf(\"Marketplace.ListPlanAccountsForPlan (Stubbed) returned %+v, want %+v\", accounts, want)\n\t}\n}\n\nfunc TestMarketplaceService_GetPlanAccountForAccount(t *testing.T) {\n\tclient, mux, _, teardown := setup()\n\tdefer teardown()\n\n\tmux.HandleFunc(\"\/marketplace_listing\/accounts\/1\", func(w http.ResponseWriter, r *http.Request) {\n\t\ttestMethod(t, r, \"GET\")\n\t\tfmt.Fprint(w, `{\"id\":1, \"marketplace_pending_change\": {\"id\": 77}}`)\n\t})\n\n\tclient.Marketplace.Stubbed = false\n\tctx := context.Background()\n\taccount, _, err := client.Marketplace.GetPlanAccountForAccount(ctx, 1)\n\tif err != nil {\n\t\tt.Errorf(\"Marketplace.GetPlanAccountForAccount returned error: %v\", err)\n\t}\n\n\twant := &MarketplacePlanAccount{ID: Int64(1), MarketplacePendingChange: &MarketplacePendingChange{ID: Int64(77)}}\n\tif !cmp.Equal(account, want) {\n\t\tt.Errorf(\"Marketplace.GetPlanAccountForAccount returned %+v, want %+v\", account, want)\n\t}\n\n\tconst methodName = \"GetPlanAccountForAccount\"\n\ttestNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) {\n\t\tgot, resp, err := client.Marketplace.GetPlanAccountForAccount(ctx, 1)\n\t\tif got != nil {\n\t\t\tt.Errorf(\"testNewRequestAndDoFailure %v = %#v, want nil\", methodName, got)\n\t\t}\n\t\treturn resp, err\n\t})\n}\n\nfunc TestMarketplaceService_Stubbed_GetPlanAccountForAccount(t *testing.T) {\n\tclient, mux, _, teardown := setup()\n\tdefer teardown()\n\n\tmux.HandleFunc(\"\/marketplace_listing\/stubbed\/accounts\/1\", func(w http.ResponseWriter, r *http.Request) {\n\t\ttestMethod(t, r, \"GET\")\n\t\tfmt.Fprint(w, `{\"id\":1}`)\n\t})\n\n\tclient.Marketplace.Stubbed = true\n\tctx := context.Background()\n\taccount, _, err := client.Marketplace.GetPlanAccountForAccount(ctx, 1)\n\tif err != nil {\n\t\tt.Errorf(\"Marketplace.GetPlanAccountForAccount (Stubbed) returned error: %v\", err)\n\t}\n\n\twant := &MarketplacePlanAccount{ID: Int64(1)}\n\tif !cmp.Equal(account, want) {\n\t\tt.Errorf(\"Marketplace.GetPlanAccountForAccount (Stubbed) returned %+v, want %+v\", account, want)\n\t}\n}\n\nfunc TestMarketplaceService_ListMarketplacePurchasesForUser(t *testing.T) {\n\tclient, mux, _, teardown := setup()\n\tdefer teardown()\n\n\tmux.HandleFunc(\"\/user\/marketplace_purchases\", func(w http.ResponseWriter, r *http.Request) {\n\t\ttestMethod(t, r, \"GET\")\n\t\tfmt.Fprint(w, `[{\"billing_cycle\":\"monthly\"}]`)\n\t})\n\n\topt := &ListOptions{Page: 1, PerPage: 2}\n\tclient.Marketplace.Stubbed = false\n\tctx := context.Background()\n\tpurchases, _, err := client.Marketplace.ListMarketplacePurchasesForUser(ctx, opt)\n\tif err != nil {\n\t\tt.Errorf(\"Marketplace.ListMarketplacePurchasesForUser returned error: %v\", err)\n\t}\n\n\twant := []*MarketplacePurchase{{BillingCycle: String(\"monthly\")}}\n\tif !cmp.Equal(purchases, want) {\n\t\tt.Errorf(\"Marketplace.ListMarketplacePurchasesForUser returned %+v, want %+v\", purchases, want)\n\t}\n\n\tconst methodName = \"ListMarketplacePurchasesForUser\"\n\ttestNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) {\n\t\tgot, resp, err := client.Marketplace.ListMarketplacePurchasesForUser(ctx, opt)\n\t\tif got != nil {\n\t\t\tt.Errorf(\"testNewRequestAndDoFailure %v = %#v, want nil\", methodName, got)\n\t\t}\n\t\treturn resp, err\n\t})\n}\n\nfunc TestMarketplaceService_Stubbed_ListMarketplacePurchasesForUser(t *testing.T) {\n\tclient, mux, _, teardown := setup()\n\tdefer teardown()\n\n\tmux.HandleFunc(\"\/user\/marketplace_purchases\/stubbed\", func(w http.ResponseWriter, r *http.Request) {\n\t\ttestMethod(t, r, \"GET\")\n\t\tfmt.Fprint(w, `[{\"billing_cycle\":\"monthly\"}]`)\n\t})\n\n\topt := &ListOptions{Page: 1, PerPage: 2}\n\tclient.Marketplace.Stubbed = true\n\tctx := context.Background()\n\tpurchases, _, err := client.Marketplace.ListMarketplacePurchasesForUser(ctx, opt)\n\tif err != nil {\n\t\tt.Errorf(\"Marketplace.ListMarketplacePurchasesForUser returned error: %v\", err)\n\t}\n\n\twant := []*MarketplacePurchase{{BillingCycle: String(\"monthly\")}}\n\tif !cmp.Equal(purchases, want) {\n\t\tt.Errorf(\"Marketplace.ListMarketplacePurchasesForUser returned %+v, want %+v\", purchases, want)\n\t}\n}\n<commit_msg>Add test cases for JSON resource marshaling (#1927)<commit_after>\/\/ Copyright 2017 The go-github AUTHORS. All rights reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage github\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"testing\"\n\n\t\"github.com\/google\/go-cmp\/cmp\"\n)\n\nfunc TestMarketplaceService_ListPlans(t *testing.T) {\n\tclient, mux, _, teardown := setup()\n\tdefer teardown()\n\n\tmux.HandleFunc(\"\/marketplace_listing\/plans\", func(w http.ResponseWriter, r *http.Request) {\n\t\ttestMethod(t, r, \"GET\")\n\t\ttestFormValues(t, r, values{\n\t\t\t\"page\":     \"1\",\n\t\t\t\"per_page\": \"2\",\n\t\t})\n\t\tfmt.Fprint(w, `[{\"id\":1}]`)\n\t})\n\n\topt := &ListOptions{Page: 1, PerPage: 2}\n\tclient.Marketplace.Stubbed = false\n\tctx := context.Background()\n\tplans, _, err := client.Marketplace.ListPlans(ctx, opt)\n\tif err != nil {\n\t\tt.Errorf(\"Marketplace.ListPlans returned error: %v\", err)\n\t}\n\n\twant := []*MarketplacePlan{{ID: Int64(1)}}\n\tif !cmp.Equal(plans, want) {\n\t\tt.Errorf(\"Marketplace.ListPlans returned %+v, want %+v\", plans, want)\n\t}\n\n\tconst methodName = \"ListPlans\"\n\ttestNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) {\n\t\tgot, resp, err := client.Marketplace.ListPlans(ctx, opt)\n\t\tif got != nil {\n\t\t\tt.Errorf(\"testNewRequestAndDoFailure %v = %#v, want nil\", methodName, got)\n\t\t}\n\t\treturn resp, err\n\t})\n}\n\nfunc TestMarketplaceService_Stubbed_ListPlans(t *testing.T) {\n\tclient, mux, _, teardown := setup()\n\tdefer teardown()\n\n\tmux.HandleFunc(\"\/marketplace_listing\/stubbed\/plans\", func(w http.ResponseWriter, r *http.Request) {\n\t\ttestMethod(t, r, \"GET\")\n\t\tfmt.Fprint(w, `[{\"id\":1}]`)\n\t})\n\n\topt := &ListOptions{Page: 1, PerPage: 2}\n\tclient.Marketplace.Stubbed = true\n\tctx := context.Background()\n\tplans, _, err := client.Marketplace.ListPlans(ctx, opt)\n\tif err != nil {\n\t\tt.Errorf(\"Marketplace.ListPlans (Stubbed) returned error: %v\", err)\n\t}\n\n\twant := []*MarketplacePlan{{ID: Int64(1)}}\n\tif !cmp.Equal(plans, want) {\n\t\tt.Errorf(\"Marketplace.ListPlans (Stubbed) returned %+v, want %+v\", plans, want)\n\t}\n}\n\nfunc TestMarketplaceService_ListPlanAccountsForPlan(t *testing.T) {\n\tclient, mux, _, teardown := setup()\n\tdefer teardown()\n\n\tmux.HandleFunc(\"\/marketplace_listing\/plans\/1\/accounts\", func(w http.ResponseWriter, r *http.Request) {\n\t\ttestMethod(t, r, \"GET\")\n\t\tfmt.Fprint(w, `[{\"id\":1}]`)\n\t})\n\n\topt := &ListOptions{Page: 1, PerPage: 2}\n\tclient.Marketplace.Stubbed = false\n\tctx := context.Background()\n\taccounts, _, err := client.Marketplace.ListPlanAccountsForPlan(ctx, 1, opt)\n\tif err != nil {\n\t\tt.Errorf(\"Marketplace.ListPlanAccountsForPlan returned error: %v\", err)\n\t}\n\n\twant := []*MarketplacePlanAccount{{ID: Int64(1)}}\n\tif !cmp.Equal(accounts, want) {\n\t\tt.Errorf(\"Marketplace.ListPlanAccountsForPlan returned %+v, want %+v\", accounts, want)\n\t}\n\n\tconst methodName = \"ListPlanAccountsForPlan\"\n\ttestNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) {\n\t\tgot, resp, err := client.Marketplace.ListPlanAccountsForPlan(ctx, 1, opt)\n\t\tif got != nil {\n\t\t\tt.Errorf(\"testNewRequestAndDoFailure %v = %#v, want nil\", methodName, got)\n\t\t}\n\t\treturn resp, err\n\t})\n}\n\nfunc TestMarketplaceService_Stubbed_ListPlanAccountsForPlan(t *testing.T) {\n\tclient, mux, _, teardown := setup()\n\tdefer teardown()\n\n\tmux.HandleFunc(\"\/marketplace_listing\/stubbed\/plans\/1\/accounts\", func(w http.ResponseWriter, r *http.Request) {\n\t\ttestMethod(t, r, \"GET\")\n\t\tfmt.Fprint(w, `[{\"id\":1}]`)\n\t})\n\n\topt := &ListOptions{Page: 1, PerPage: 2}\n\tclient.Marketplace.Stubbed = true\n\tctx := context.Background()\n\taccounts, _, err := client.Marketplace.ListPlanAccountsForPlan(ctx, 1, opt)\n\tif err != nil {\n\t\tt.Errorf(\"Marketplace.ListPlanAccountsForPlan (Stubbed) returned error: %v\", err)\n\t}\n\n\twant := []*MarketplacePlanAccount{{ID: Int64(1)}}\n\tif !cmp.Equal(accounts, want) {\n\t\tt.Errorf(\"Marketplace.ListPlanAccountsForPlan (Stubbed) returned %+v, want %+v\", accounts, want)\n\t}\n}\n\nfunc TestMarketplaceService_GetPlanAccountForAccount(t *testing.T) {\n\tclient, mux, _, teardown := setup()\n\tdefer teardown()\n\n\tmux.HandleFunc(\"\/marketplace_listing\/accounts\/1\", func(w http.ResponseWriter, r *http.Request) {\n\t\ttestMethod(t, r, \"GET\")\n\t\tfmt.Fprint(w, `{\"id\":1, \"marketplace_pending_change\": {\"id\": 77}}`)\n\t})\n\n\tclient.Marketplace.Stubbed = false\n\tctx := context.Background()\n\taccount, _, err := client.Marketplace.GetPlanAccountForAccount(ctx, 1)\n\tif err != nil {\n\t\tt.Errorf(\"Marketplace.GetPlanAccountForAccount returned error: %v\", err)\n\t}\n\n\twant := &MarketplacePlanAccount{ID: Int64(1), MarketplacePendingChange: &MarketplacePendingChange{ID: Int64(77)}}\n\tif !cmp.Equal(account, want) {\n\t\tt.Errorf(\"Marketplace.GetPlanAccountForAccount returned %+v, want %+v\", account, want)\n\t}\n\n\tconst methodName = \"GetPlanAccountForAccount\"\n\ttestNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) {\n\t\tgot, resp, err := client.Marketplace.GetPlanAccountForAccount(ctx, 1)\n\t\tif got != nil {\n\t\t\tt.Errorf(\"testNewRequestAndDoFailure %v = %#v, want nil\", methodName, got)\n\t\t}\n\t\treturn resp, err\n\t})\n}\n\nfunc TestMarketplaceService_Stubbed_GetPlanAccountForAccount(t *testing.T) {\n\tclient, mux, _, teardown := setup()\n\tdefer teardown()\n\n\tmux.HandleFunc(\"\/marketplace_listing\/stubbed\/accounts\/1\", func(w http.ResponseWriter, r *http.Request) {\n\t\ttestMethod(t, r, \"GET\")\n\t\tfmt.Fprint(w, `{\"id\":1}`)\n\t})\n\n\tclient.Marketplace.Stubbed = true\n\tctx := context.Background()\n\taccount, _, err := client.Marketplace.GetPlanAccountForAccount(ctx, 1)\n\tif err != nil {\n\t\tt.Errorf(\"Marketplace.GetPlanAccountForAccount (Stubbed) returned error: %v\", err)\n\t}\n\n\twant := &MarketplacePlanAccount{ID: Int64(1)}\n\tif !cmp.Equal(account, want) {\n\t\tt.Errorf(\"Marketplace.GetPlanAccountForAccount (Stubbed) returned %+v, want %+v\", account, want)\n\t}\n}\n\nfunc TestMarketplaceService_ListMarketplacePurchasesForUser(t *testing.T) {\n\tclient, mux, _, teardown := setup()\n\tdefer teardown()\n\n\tmux.HandleFunc(\"\/user\/marketplace_purchases\", func(w http.ResponseWriter, r *http.Request) {\n\t\ttestMethod(t, r, \"GET\")\n\t\tfmt.Fprint(w, `[{\"billing_cycle\":\"monthly\"}]`)\n\t})\n\n\topt := &ListOptions{Page: 1, PerPage: 2}\n\tclient.Marketplace.Stubbed = false\n\tctx := context.Background()\n\tpurchases, _, err := client.Marketplace.ListMarketplacePurchasesForUser(ctx, opt)\n\tif err != nil {\n\t\tt.Errorf(\"Marketplace.ListMarketplacePurchasesForUser returned error: %v\", err)\n\t}\n\n\twant := []*MarketplacePurchase{{BillingCycle: String(\"monthly\")}}\n\tif !cmp.Equal(purchases, want) {\n\t\tt.Errorf(\"Marketplace.ListMarketplacePurchasesForUser returned %+v, want %+v\", purchases, want)\n\t}\n\n\tconst methodName = \"ListMarketplacePurchasesForUser\"\n\ttestNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) {\n\t\tgot, resp, err := client.Marketplace.ListMarketplacePurchasesForUser(ctx, opt)\n\t\tif got != nil {\n\t\t\tt.Errorf(\"testNewRequestAndDoFailure %v = %#v, want nil\", methodName, got)\n\t\t}\n\t\treturn resp, err\n\t})\n}\n\nfunc TestMarketplaceService_Stubbed_ListMarketplacePurchasesForUser(t *testing.T) {\n\tclient, mux, _, teardown := setup()\n\tdefer teardown()\n\n\tmux.HandleFunc(\"\/user\/marketplace_purchases\/stubbed\", func(w http.ResponseWriter, r *http.Request) {\n\t\ttestMethod(t, r, \"GET\")\n\t\tfmt.Fprint(w, `[{\"billing_cycle\":\"monthly\"}]`)\n\t})\n\n\topt := &ListOptions{Page: 1, PerPage: 2}\n\tclient.Marketplace.Stubbed = true\n\tctx := context.Background()\n\tpurchases, _, err := client.Marketplace.ListMarketplacePurchasesForUser(ctx, opt)\n\tif err != nil {\n\t\tt.Errorf(\"Marketplace.ListMarketplacePurchasesForUser returned error: %v\", err)\n\t}\n\n\twant := []*MarketplacePurchase{{BillingCycle: String(\"monthly\")}}\n\tif !cmp.Equal(purchases, want) {\n\t\tt.Errorf(\"Marketplace.ListMarketplacePurchasesForUser returned %+v, want %+v\", purchases, want)\n\t}\n}\n\nfunc TestMarketplacePlan_Marshal(t *testing.T) {\n\ttestJSONMarshal(t, &MarketplacePlan{}, \"{}\")\n\n\tu := &MarketplacePlan{\n\t\tURL:                 String(\"u\"),\n\t\tAccountsURL:         String(\"au\"),\n\t\tID:                  Int64(1),\n\t\tNumber:              Int(1),\n\t\tName:                String(\"n\"),\n\t\tDescription:         String(\"d\"),\n\t\tMonthlyPriceInCents: Int(1),\n\t\tYearlyPriceInCents:  Int(1),\n\t\tPriceModel:          String(\"pm\"),\n\t\tUnitName:            String(\"un\"),\n\t\tBullets:             &[]string{\"b\"},\n\t\tState:               String(\"s\"),\n\t\tHasFreeTrial:        Bool(false),\n\t}\n\n\twant := `{\n\t\t\"url\": \"u\",\n\t\t\"accounts_url\": \"au\",\n\t\t\"id\": 1,\n\t\t\"number\": 1,\n\t\t\"name\": \"n\",\n\t\t\"description\": \"d\",\n\t\t\"monthly_price_in_cents\": 1,\n\t\t\"yearly_price_in_cents\": 1,\n\t\t\"price_model\": \"pm\",\n\t\t\"unit_name\": \"un\",\n\t\t\"bullets\": [\"b\"],\n\t\t\"state\": \"s\",\n\t\t\"has_free_trial\": false\n\t}`\n\n\ttestJSONMarshal(t, u, want)\n}\n\nfunc TestMarketplacePurchase_Marshal(t *testing.T) {\n\ttestJSONMarshal(t, &MarketplacePurchase{}, \"{}\")\n\n\tu := &MarketplacePurchase{\n\t\tBillingCycle:    String(\"bc\"),\n\t\tNextBillingDate: &Timestamp{referenceTime},\n\t\tUnitCount:       Int(1),\n\t\tPlan: &MarketplacePlan{\n\t\t\tURL:                 String(\"u\"),\n\t\t\tAccountsURL:         String(\"au\"),\n\t\t\tID:                  Int64(1),\n\t\t\tNumber:              Int(1),\n\t\t\tName:                String(\"n\"),\n\t\t\tDescription:         String(\"d\"),\n\t\t\tMonthlyPriceInCents: Int(1),\n\t\t\tYearlyPriceInCents:  Int(1),\n\t\t\tPriceModel:          String(\"pm\"),\n\t\t\tUnitName:            String(\"un\"),\n\t\t\tBullets:             &[]string{\"b\"},\n\t\t\tState:               String(\"s\"),\n\t\t\tHasFreeTrial:        Bool(false),\n\t\t},\n\t\tOnFreeTrial:     Bool(false),\n\t\tFreeTrialEndsOn: &Timestamp{referenceTime},\n\t\tUpdatedAt:       &Timestamp{referenceTime},\n\t}\n\n\twant := `{\n\t\t\"billing_cycle\": \"bc\",\n\t\t\"next_billing_date\": ` + referenceTimeStr + `,\n\t\t\"unit_count\": 1,\n\t\t\"plan\": {\n\t\t\t\"url\": \"u\",\n\t\t\t\"accounts_url\": \"au\",\n\t\t\t\"id\": 1,\n\t\t\t\"number\": 1,\n\t\t\t\"name\": \"n\",\n\t\t\t\"description\": \"d\",\n\t\t\t\"monthly_price_in_cents\": 1,\n\t\t\t\"yearly_price_in_cents\": 1,\n\t\t\t\"price_model\": \"pm\",\n\t\t\t\"unit_name\": \"un\",\n\t\t\t\"bullets\": [\"b\"],\n\t\t\t\"state\": \"s\",\n\t\t\t\"has_free_trial\": false\n\t\t\t},\n\t\t\"on_free_trial\": false,\n\t\t\"free_trial_ends_on\": ` + referenceTimeStr + `,\n\t\t\"updated_at\": ` + referenceTimeStr + `\n\t}`\n\n\ttestJSONMarshal(t, u, want)\n}\n\nfunc TestMarketplacePendingChange_Marshal(t *testing.T) {\n\ttestJSONMarshal(t, &MarketplacePendingChange{}, \"{}\")\n\n\tu := &MarketplacePendingChange{\n\t\tEffectiveDate: &Timestamp{referenceTime},\n\t\tUnitCount:     Int(1),\n\t\tID:            Int64(1),\n\t\tPlan: &MarketplacePlan{\n\t\t\tURL:                 String(\"u\"),\n\t\t\tAccountsURL:         String(\"au\"),\n\t\t\tID:                  Int64(1),\n\t\t\tNumber:              Int(1),\n\t\t\tName:                String(\"n\"),\n\t\t\tDescription:         String(\"d\"),\n\t\t\tMonthlyPriceInCents: Int(1),\n\t\t\tYearlyPriceInCents:  Int(1),\n\t\t\tPriceModel:          String(\"pm\"),\n\t\t\tUnitName:            String(\"un\"),\n\t\t\tBullets:             &[]string{\"b\"},\n\t\t\tState:               String(\"s\"),\n\t\t\tHasFreeTrial:        Bool(false),\n\t\t},\n\t}\n\n\twant := `{\n\t\t\"effective_date\": ` + referenceTimeStr + `,\n\t\t\"unit_count\": 1,\n\t\t\"id\": 1,\n\t\t\"plan\": {\n\t\t\t\"url\": \"u\",\n\t\t\t\"accounts_url\": \"au\",\n\t\t\t\"id\": 1,\n\t\t\t\"number\": 1,\n\t\t\t\"name\": \"n\",\n\t\t\t\"description\": \"d\",\n\t\t\t\"monthly_price_in_cents\": 1,\n\t\t\t\"yearly_price_in_cents\": 1,\n\t\t\t\"price_model\": \"pm\",\n\t\t\t\"unit_name\": \"un\",\n\t\t\t\"bullets\": [\"b\"],\n\t\t\t\"state\": \"s\",\n\t\t\t\"has_free_trial\": false\n\t\t\t}\n\t}`\n\n\ttestJSONMarshal(t, u, want)\n}\n\nfunc TestMarketplacePlanAccount_Marshal(t *testing.T) {\n\ttestJSONMarshal(t, &MarketplacePlanAccount{}, \"{}\")\n\n\tu := &MarketplacePlanAccount{\n\t\tURL:                      String(\"u\"),\n\t\tType:                     String(\"t\"),\n\t\tID:                       Int64(1),\n\t\tLogin:                    String(\"l\"),\n\t\tOrganizationBillingEmail: String(\"obe\"),\n\t\tMarketplacePurchase: &MarketplacePurchase{\n\t\t\tBillingCycle:    String(\"bc\"),\n\t\t\tNextBillingDate: &Timestamp{referenceTime},\n\t\t\tUnitCount:       Int(1),\n\t\t\tPlan: &MarketplacePlan{\n\t\t\t\tURL:                 String(\"u\"),\n\t\t\t\tAccountsURL:         String(\"au\"),\n\t\t\t\tID:                  Int64(1),\n\t\t\t\tNumber:              Int(1),\n\t\t\t\tName:                String(\"n\"),\n\t\t\t\tDescription:         String(\"d\"),\n\t\t\t\tMonthlyPriceInCents: Int(1),\n\t\t\t\tYearlyPriceInCents:  Int(1),\n\t\t\t\tPriceModel:          String(\"pm\"),\n\t\t\t\tUnitName:            String(\"un\"),\n\t\t\t\tBullets:             &[]string{\"b\"},\n\t\t\t\tState:               String(\"s\"),\n\t\t\t\tHasFreeTrial:        Bool(false),\n\t\t\t},\n\t\t\tOnFreeTrial:     Bool(false),\n\t\t\tFreeTrialEndsOn: &Timestamp{referenceTime},\n\t\t\tUpdatedAt:       &Timestamp{referenceTime},\n\t\t},\n\t\tMarketplacePendingChange: &MarketplacePendingChange{\n\t\t\tEffectiveDate: &Timestamp{referenceTime},\n\t\t\tUnitCount:     Int(1),\n\t\t\tID:            Int64(1),\n\t\t\tPlan: &MarketplacePlan{\n\t\t\t\tURL:                 String(\"u\"),\n\t\t\t\tAccountsURL:         String(\"au\"),\n\t\t\t\tID:                  Int64(1),\n\t\t\t\tNumber:              Int(1),\n\t\t\t\tName:                String(\"n\"),\n\t\t\t\tDescription:         String(\"d\"),\n\t\t\t\tMonthlyPriceInCents: Int(1),\n\t\t\t\tYearlyPriceInCents:  Int(1),\n\t\t\t\tPriceModel:          String(\"pm\"),\n\t\t\t\tUnitName:            String(\"un\"),\n\t\t\t\tBullets:             &[]string{\"b\"},\n\t\t\t\tState:               String(\"s\"),\n\t\t\t\tHasFreeTrial:        Bool(false),\n\t\t\t},\n\t\t},\n\t}\n\n\twant := `{\n\t\t\"url\": \"u\",\n\t\t\"type\": \"t\",\n\t\t\"id\": 1,\n\t\t\"login\": \"l\",\n\t\t\"organization_billing_email\": \"obe\",\n\t\t\"marketplace_purchase\": {\n\t\t\t\"billing_cycle\": \"bc\",\n\t\t\t\"next_billing_date\": ` + referenceTimeStr + `,\n\t\t\t\"unit_count\": 1,\n\t\t\t\"plan\": {\n\t\t\t\t\"url\": \"u\",\n\t\t\t\t\"accounts_url\": \"au\",\n\t\t\t\t\"id\": 1,\n\t\t\t\t\"number\": 1,\n\t\t\t\t\"name\": \"n\",\n\t\t\t\t\"description\": \"d\",\n\t\t\t\t\"monthly_price_in_cents\": 1,\n\t\t\t\t\"yearly_price_in_cents\": 1,\n\t\t\t\t\"price_model\": \"pm\",\n\t\t\t\t\"unit_name\": \"un\",\n\t\t\t\t\"bullets\": [\"b\"],\n\t\t\t\t\"state\": \"s\",\n\t\t\t\t\"has_free_trial\": false\n\t\t\t\t},\n\t\t\t\"on_free_trial\": false,\n\t\t\t\"free_trial_ends_on\": ` + referenceTimeStr + `,\n\t\t\t\"updated_at\": ` + referenceTimeStr + `\n\t\t},\n\t\t\"marketplace_pending_change\": {\n\t\t\t\"effective_date\": ` + referenceTimeStr + `,\n\t\t\t\"unit_count\": 1,\n\t\t\t\"id\": 1,\n\t\t\t\"plan\": {\n\t\t\t\t\"url\": \"u\",\n\t\t\t\t\"accounts_url\": \"au\",\n\t\t\t\t\"id\": 1,\n\t\t\t\t\"number\": 1,\n\t\t\t\t\"name\": \"n\",\n\t\t\t\t\"description\": \"d\",\n\t\t\t\t\"monthly_price_in_cents\": 1,\n\t\t\t\t\"yearly_price_in_cents\": 1,\n\t\t\t\t\"price_model\": \"pm\",\n\t\t\t\t\"unit_name\": \"un\",\n\t\t\t\t\"bullets\": [\"b\"],\n\t\t\t\t\"state\": \"s\",\n\t\t\t\t\"has_free_trial\": false\n\t\t\t}\n\t\t}\n\t}`\n\n\ttestJSONMarshal(t, u, want)\n}\n<|endoftext|>"}
{"text":"<commit_before>package app\n\nimport (\n\t\"reflect\"\n\t\"sync\"\n\n\t\"github.com\/google\/uuid\"\n\t\"github.com\/pkg\/errors\"\n)\n\n\/\/ Event is a string that identifies an app event.\ntype Event string\n\n\/\/ Subscriber is a struct to subscribe to events emitted by a event registry.\ntype Subscriber struct {\n\tevents      *eventRegistry\n\tunsuscribes []func()\n}\n\n\/\/ Subscribe subscribes a function to the given event. Emit fails if the\n\/\/ subscribbed func have more arguments than the emitted event.\n\/\/\n\/\/ Panics if f is not a func.\nfunc (s *Subscriber) Subscribe(e Event, f interface{}) *Subscriber {\n\tunsubscribe := s.events.subscribe(e, f)\n\ts.unsuscribes = append(s.unsuscribes, unsubscribe)\n\treturn s\n}\n\n\/\/ Close unsubscribes all the subscriptions.\nfunc (s *Subscriber) Close() {\n\tfor _, unsuscribe := range s.unsuscribes {\n\t\tunsuscribe()\n\t}\n}\n\ntype eventHandler struct {\n\tID         string\n\tMsgHandler interface{}\n}\n\ntype eventRegistry struct {\n\tmutex    sync.RWMutex\n\thandlers map[Event][]eventHandler\n\tui       chan func()\n}\n\nfunc newEventRegistry(ui chan func()) *eventRegistry {\n\treturn &eventRegistry{\n\t\thandlers: make(map[Event][]eventHandler),\n\t\tui:       ui,\n\t}\n}\n\nfunc (r *eventRegistry) subscribe(e Event, handler interface{}) func() {\n\tr.mutex.Lock()\n\tdefer r.mutex.Unlock()\n\n\tif reflect.ValueOf(handler).Kind() != reflect.Func {\n\t\tPanic(errors.Errorf(\"can't subscribe to event %s: handler is not a func: %T\",\n\t\t\te,\n\t\t\thandler,\n\t\t))\n\t}\n\n\tid := uuid.New().String()\n\thandlers := r.handlers[e]\n\n\thandlers = append(handlers, eventHandler{\n\t\tID:         id,\n\t\tMsgHandler: handler,\n\t})\n\n\tr.handlers[e] = handlers\n\n\treturn func() {\n\t\tr.unsubscribe(e, id)\n\t}\n}\n\nfunc (r *eventRegistry) unsubscribe(e Event, id string) {\n\tr.mutex.Lock()\n\tdefer r.mutex.Unlock()\n\n\thandlers := r.handlers[e]\n\n\tfor i, h := range handlers {\n\t\tif h.ID == id {\n\t\t\tend := len(handlers) - 1\n\t\t\thandlers[i] = handlers[end]\n\t\t\thandlers[end] = eventHandler{}\n\t\t\thandlers = handlers[:end]\n\n\t\t\tr.handlers[e] = handlers\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/ Emit emits the event with the given arguments.\nfunc (r *eventRegistry) Emit(e Event, args ...interface{}) {\n\tr.mutex.RLock()\n\tdefer r.mutex.RUnlock()\n\n\tfor _, h := range r.handlers[e] {\n\t\tif err := r.callHandler(h.MsgHandler, args...); err != nil {\n\t\t\tLogf(\"emitting %s failed: %s\", e, err)\n\t\t}\n\t}\n}\n\nfunc (r *eventRegistry) callHandler(h interface{}, args ...interface{}) error {\n\tv := reflect.ValueOf(h)\n\tt := v.Type()\n\n\targsv := make([]reflect.Value, t.NumIn())\n\n\tfor i := 0; i < t.NumIn(); i++ {\n\t\targt := t.In(i)\n\n\t\tif i >= len(args) {\n\t\t\treturn errors.Errorf(\"missing %v at index %v\", argt, i)\n\t\t}\n\n\t\targv := reflect.ValueOf(args[i])\n\t\tif !argv.Type().ConvertibleTo(argt) {\n\t\t\treturn errors.Errorf(\"arg at index %v is not a %v: %v\", i, argt, argv.Type())\n\t\t}\n\n\t\targsv[i] = argv.Convert(argt)\n\t}\n\n\tr.ui <- func() {\n\t\tv.Call(argsv)\n\t}\n\n\treturn nil\n}\n<commit_msg>misspell<commit_after>package app\n\nimport (\n\t\"reflect\"\n\t\"sync\"\n\n\t\"github.com\/google\/uuid\"\n\t\"github.com\/pkg\/errors\"\n)\n\n\/\/ Event is a string that identifies an app event.\ntype Event string\n\n\/\/ Subscriber is a struct to subscribe to events emitted by a event registry.\ntype Subscriber struct {\n\tevents      *eventRegistry\n\tunsuscribes []func()\n}\n\n\/\/ Subscribe subscribes a function to the given event. Emit fails if the\n\/\/ subscribed func have more arguments than the emitted event.\n\/\/\n\/\/ Panics if f is not a func.\nfunc (s *Subscriber) Subscribe(e Event, f interface{}) *Subscriber {\n\tunsubscribe := s.events.subscribe(e, f)\n\ts.unsuscribes = append(s.unsuscribes, unsubscribe)\n\treturn s\n}\n\n\/\/ Close unsubscribes all the subscriptions.\nfunc (s *Subscriber) Close() {\n\tfor _, unsuscribe := range s.unsuscribes {\n\t\tunsuscribe()\n\t}\n}\n\ntype eventHandler struct {\n\tID         string\n\tMsgHandler interface{}\n}\n\ntype eventRegistry struct {\n\tmutex    sync.RWMutex\n\thandlers map[Event][]eventHandler\n\tui       chan func()\n}\n\nfunc newEventRegistry(ui chan func()) *eventRegistry {\n\treturn &eventRegistry{\n\t\thandlers: make(map[Event][]eventHandler),\n\t\tui:       ui,\n\t}\n}\n\nfunc (r *eventRegistry) subscribe(e Event, handler interface{}) func() {\n\tr.mutex.Lock()\n\tdefer r.mutex.Unlock()\n\n\tif reflect.ValueOf(handler).Kind() != reflect.Func {\n\t\tPanic(errors.Errorf(\"can't subscribe to event %s: handler is not a func: %T\",\n\t\t\te,\n\t\t\thandler,\n\t\t))\n\t}\n\n\tid := uuid.New().String()\n\thandlers := r.handlers[e]\n\n\thandlers = append(handlers, eventHandler{\n\t\tID:         id,\n\t\tMsgHandler: handler,\n\t})\n\n\tr.handlers[e] = handlers\n\n\treturn func() {\n\t\tr.unsubscribe(e, id)\n\t}\n}\n\nfunc (r *eventRegistry) unsubscribe(e Event, id string) {\n\tr.mutex.Lock()\n\tdefer r.mutex.Unlock()\n\n\thandlers := r.handlers[e]\n\n\tfor i, h := range handlers {\n\t\tif h.ID == id {\n\t\t\tend := len(handlers) - 1\n\t\t\thandlers[i] = handlers[end]\n\t\t\thandlers[end] = eventHandler{}\n\t\t\thandlers = handlers[:end]\n\n\t\t\tr.handlers[e] = handlers\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/ Emit emits the event with the given arguments.\nfunc (r *eventRegistry) Emit(e Event, args ...interface{}) {\n\tr.mutex.RLock()\n\tdefer r.mutex.RUnlock()\n\n\tfor _, h := range r.handlers[e] {\n\t\tif err := r.callHandler(h.MsgHandler, args...); err != nil {\n\t\t\tLogf(\"emitting %s failed: %s\", e, err)\n\t\t}\n\t}\n}\n\nfunc (r *eventRegistry) callHandler(h interface{}, args ...interface{}) error {\n\tv := reflect.ValueOf(h)\n\tt := v.Type()\n\n\targsv := make([]reflect.Value, t.NumIn())\n\n\tfor i := 0; i < t.NumIn(); i++ {\n\t\targt := t.In(i)\n\n\t\tif i >= len(args) {\n\t\t\treturn errors.Errorf(\"missing %v at index %v\", argt, i)\n\t\t}\n\n\t\targv := reflect.ValueOf(args[i])\n\t\tif !argv.Type().ConvertibleTo(argt) {\n\t\t\treturn errors.Errorf(\"arg at index %v is not a %v: %v\", i, argt, argv.Type())\n\t\t}\n\n\t\targsv[i] = argv.Convert(argt)\n\t}\n\n\tr.ui <- func() {\n\t\tv.Call(argsv)\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\/\/\"context\"\n\t\"fmt\"\n\t\"github.com\/google\/uuid\"\n\t\"io\"\n\t\"net\/http\"\n\t\"net\/url\"\n)\n\nfunc init() {\n\thttp.HandleFunc(\"\/\", handleIndex)\n\thttp.HandleFunc(\"\/githublogin\", handleGithubLogin)\n\thttp.HandleFunc(\"\/oauthcallback\", handleOauthCallback)\n\n}\n\n\/\/ https:\/\/developer.github.com\/apps\/building-integrations\/setting-up-and-registering-oauth-apps\/about-authorization-options-for-oauth-apps\/\n\nconst loginhtml = `<!DOCTYPE html>\n<html>\n<head>\n<\/head>\n<body>\n<a href=\"\/githublogin\">LOGIN WITH GITHUB<\/a>\n<\/body>\n<\/html>\n`\n\nfunc handleIndex(w http.ResponseWriter, r *http.Request) {\n\tio.WriteString(w, loginhtml)\n}\n\nfunc handleGithubLogin(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"&&& handleGithubLogin begin\")\n\n\tfmt.Println(\"app url:\", r.Host)\n\n\tid := uuid.New()\n\tfmt.Println(\"id:\", id)\n\t\/\/ctx := r.Context()\n\t\/\/TODO: get session from context\n\n\t\/\/redirect_uri := \"http:\/\/localhost:8080\/callback\"\n\tredirect_uri := \"http:\/\/\" + r.Host + \"\/callback\"\n\tfmt.Println(\"redirect_uri:\", redirect_uri)\n\n\tvalues := url.Values{}\n\tvalues.Add(\"client_id\", \"03712bbff7dae4203b4e\")\n\tvalues.Add(\"redirect_uri\", redirect_uri)\n\tvalues.Add(\"scope\", \"user:email\")\n\tvalues.Add(\"state\", id.String())\n\n\tredirectRequestUrl := fmt.Sprintf(\"https:\/\/github.com\/login\/oauth\/authorize?%s\",\n\t\tvalues.Encode())\n\n\tfmt.Println(\"redirectRequestUrl:\", redirectRequestUrl)\n\n\t\/\/TODO: save session back to context after saving the id.String()  to a field in session.State\n\n\thttp.Redirect(w, r, redirectRequestUrl, 302)\n}\n\nfunc handleOauthCallback(w http.ResponseWriter, r *http.Request) {\n\t\/*\tstate := r.FormValue(\"state\")\n\t\t\/\/\/\/ctx := context.WithValue(r.Context(), \"state\", state)\n\n\t\tctx := r.Context()\n\t\t\/\/TODO: get session from context\n\n\t\t\/\/TODO: compare the state from session with the state from request. if no match, red flag\n\t*\/\n}\n<commit_msg>github oauth callback fix<commit_after>package main\n\nimport (\n\t\/\/\"context\"\n\t\"fmt\"\n\t\"github.com\/google\/uuid\"\n\t\"io\"\n\t\"net\/http\"\n\t\"net\/url\"\n)\n\nfunc init() {\n\thttp.HandleFunc(\"\/\", handleIndex)\n\thttp.HandleFunc(\"\/githublogin\", handleGithubLogin)\n\thttp.HandleFunc(\"\/callback\", handleOauthCallback)\n\n}\n\n\/\/ https:\/\/developer.github.com\/apps\/building-integrations\/setting-up-and-registering-oauth-apps\/about-authorization-options-for-oauth-apps\/\n\nconst loginhtml = `<!DOCTYPE html>\n<html>\n<head>\n<\/head>\n<body>\n<a href=\"\/githublogin\">LOGIN WITH GITHUB<\/a>\n<\/body>\n<\/html>\n`\n\nfunc handleIndex(w http.ResponseWriter, r *http.Request) {\n\tio.WriteString(w, loginhtml)\n}\n\nfunc handleGithubLogin(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"&&& handleGithubLogin begin\")\n\n\tfmt.Println(\"app url:\", r.Host)\n\n\tid := uuid.New()\n\tfmt.Println(\"id:\", id)\n\t\/\/ctx := r.Context()\n\t\/\/TODO: get session from context\n\n\t\/\/redirect_uri := \"http:\/\/localhost:8080\/callback\"\n\tredirect_uri := \"http:\/\/\" + r.Host + \"\/callback\"\n\tfmt.Println(\"redirect_uri:\", redirect_uri)\n\n\tvalues := url.Values{}\n\tvalues.Add(\"client_id\", \"03712bbff7dae4203b4e\")\n\tvalues.Add(\"redirect_uri\", redirect_uri)\n\tvalues.Add(\"scope\", \"user:email\")\n\tvalues.Add(\"state\", id.String())\n\n\tredirectRequestUrl := fmt.Sprintf(\"https:\/\/github.com\/login\/oauth\/authorize?%s\",\n\t\tvalues.Encode())\n\n\tfmt.Println(\"redirectRequestUrl:\", redirectRequestUrl)\n\n\t\/\/TODO: save session back to context after saving the id.String()  to a field in session.State\n\n\thttp.Redirect(w, r, redirectRequestUrl, 302)\n}\n\nfunc handleOauthCallback(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprint(w, r.FormValue(\"state\"))\n\t\/*\tstate := r.FormValue(\"state\")\n\t\t\/\/\/\/ctx := context.WithValue(r.Context(), \"state\", state)\n\n\t\tctx := r.Context()\n\t\t\/\/TODO: get session from context\n\n\n\t\t\/\/TODO: compare the state from session with the state from request. if no match, red flag\n\t*\/\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2020 The Rook Authors. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n\thttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage controller\n\nimport (\n\t\"encoding\/json\"\n\t\"strings\"\n\n\t\"github.com\/banzaicloud\/k8s-objectmatcher\/patch\"\n\t\"github.com\/google\/go-cmp\/cmp\"\n\t\"github.com\/pkg\/errors\"\n\tcephv1 \"github.com\/rook\/rook\/pkg\/apis\/ceph.rook.io\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/api\/meta\"\n\t\"k8s.io\/apimachinery\/pkg\/api\/resource\"\n\t\"k8s.io\/apimachinery\/pkg\/runtime\"\n\t\"sigs.k8s.io\/controller-runtime\/pkg\/event\"\n\t\"sigs.k8s.io\/controller-runtime\/pkg\/predicate\"\n)\n\n\/\/ WatchControllerPredicate is a special update filter for update events\n\/\/ do not reconcile if the the status changes, this avoids a reconcile storm loop\n\/\/\n\/\/ returning 'true' means triggering a reconciliation\n\/\/ returning 'false' means do NOT trigger a reconciliation\nfunc WatchControllerPredicate() predicate.Funcs {\n\treturn predicate.Funcs{\n\t\tCreateFunc: func(e event.CreateEvent) bool {\n\t\t\tlogger.Debug(\"create event from the parent object\")\n\t\t\treturn true\n\t\t},\n\t\tDeleteFunc: func(e event.DeleteEvent) bool {\n\t\t\tlogger.Debug(\"delete event from the parent object\")\n\t\t\treturn true\n\t\t},\n\t\tUpdateFunc: func(e event.UpdateEvent) bool {\n\t\t\tlogger.Debug(\"update event from the parent object\")\n\t\t\t\/\/ resource.Quantity has non-exportable fields, so we use its comparator method\n\t\t\tresourceQtyComparer := cmp.Comparer(func(x, y resource.Quantity) bool { return x.Cmp(y) == 0 })\n\n\t\t\tswitch objOld := e.ObjectOld.(type) {\n\t\t\tcase *cephv1.CephObjectStore:\n\t\t\t\tobjNew := e.ObjectNew.(*cephv1.CephObjectStore)\n\t\t\t\tlogger.Debug(\"update event from the parent object CephObjectStore\")\n\t\t\t\tdiff := cmp.Diff(objOld.Spec, objNew.Spec, resourceQtyComparer)\n\t\t\t\tif diff != \"\" ||\n\t\t\t\t\tobjOld.GetDeletionTimestamp() != objNew.GetDeletionTimestamp() ||\n\t\t\t\t\tobjOld.GetGeneration() != objNew.GetGeneration() {\n\t\t\t\t\t\/\/ Checking if diff is not empty so we don't print it when the CR gets deleted\n\t\t\t\t\tif diff != \"\" {\n\t\t\t\t\t\tlogger.Infof(\"CR has changed for %q. diff=%s\", objNew.Name, diff)\n\t\t\t\t\t}\n\t\t\t\t\treturn true\n\t\t\t\t}\n\n\t\t\tcase *cephv1.CephObjectStoreUser:\n\t\t\t\tobjNew := e.ObjectNew.(*cephv1.CephObjectStoreUser)\n\t\t\t\tlogger.Debug(\"update event from the parent object CephObjectStoreUser\")\n\t\t\t\tdiff := cmp.Diff(objOld.Spec, objNew.Spec, resourceQtyComparer)\n\t\t\t\tif diff != \"\" ||\n\t\t\t\t\tobjOld.GetDeletionTimestamp() != objNew.GetDeletionTimestamp() ||\n\t\t\t\t\tobjOld.GetGeneration() != objNew.GetGeneration() {\n\t\t\t\t\t\/\/ Checking if diff is not empty so we don't print it when the CR gets deleted\n\t\t\t\t\tif diff != \"\" {\n\t\t\t\t\t\tlogger.Infof(\"CR has changed for %q. diff=%s\", objNew.Name, diff)\n\t\t\t\t\t}\n\t\t\t\t\treturn true\n\t\t\t\t}\n\n\t\t\tcase *cephv1.CephBlockPool:\n\t\t\t\tobjNew := e.ObjectNew.(*cephv1.CephBlockPool)\n\t\t\t\tlogger.Debug(\"update event from the parent object CephBlockPool\")\n\t\t\t\tdiff := cmp.Diff(objOld.Spec, objNew.Spec, resourceQtyComparer)\n\t\t\t\tif diff != \"\" ||\n\t\t\t\t\tobjOld.GetDeletionTimestamp() != objNew.GetDeletionTimestamp() ||\n\t\t\t\t\tobjOld.GetGeneration() != objNew.GetGeneration() {\n\t\t\t\t\t\/\/ Checking if diff is not empty so we don't print it when the CR gets deleted\n\t\t\t\t\tif diff != \"\" {\n\t\t\t\t\t\tlogger.Infof(\"CR has changed for %q. diff=%s\", objNew.Name, diff)\n\t\t\t\t\t}\n\t\t\t\t\treturn true\n\t\t\t\t}\n\n\t\t\tcase *cephv1.CephFilesystem:\n\t\t\t\tobjNew := e.ObjectNew.(*cephv1.CephFilesystem)\n\t\t\t\tlogger.Debug(\"update event from the parent object CephFilesystem\")\n\t\t\t\tdiff := cmp.Diff(objOld.Spec, objNew.Spec, resourceQtyComparer)\n\t\t\t\tif diff != \"\" ||\n\t\t\t\t\tobjOld.GetDeletionTimestamp() != objNew.GetDeletionTimestamp() ||\n\t\t\t\t\tobjOld.GetGeneration() != objNew.GetGeneration() {\n\t\t\t\t\t\/\/ Checking if diff is not empty so we don't print it when the CR gets deleted\n\t\t\t\t\tif diff != \"\" {\n\t\t\t\t\t\tlogger.Infof(\"CR has changed for %q. diff=%s\", objNew.Name, diff)\n\t\t\t\t\t}\n\t\t\t\t\treturn true\n\t\t\t\t}\n\n\t\t\tcase *cephv1.CephNFS:\n\t\t\t\tobjNew := e.ObjectNew.(*cephv1.CephNFS)\n\t\t\t\tlogger.Debug(\"update event from the parent object CephNFS\")\n\t\t\t\tdiff := cmp.Diff(objOld.Spec, objNew.Spec, resourceQtyComparer)\n\t\t\t\tif diff != \"\" ||\n\t\t\t\t\tobjOld.GetDeletionTimestamp() != objNew.GetDeletionTimestamp() ||\n\t\t\t\t\tobjOld.GetGeneration() != objNew.GetGeneration() {\n\t\t\t\t\t\/\/ Checking if diff is not empty so we don't print it when the CR gets deleted\n\t\t\t\t\tif diff != \"\" {\n\t\t\t\t\t\tlogger.Infof(\"CR has changed for %q. diff=%s\", objNew.Name, diff)\n\t\t\t\t\t}\n\t\t\t\t\treturn true\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tlogger.Debug(\"wont update unknown object\")\n\t\t\treturn false\n\t\t},\n\t\tGenericFunc: func(e event.GenericEvent) bool {\n\t\t\treturn false\n\t\t},\n\t}\n}\n\n\/\/ objectChanged checks whether the object has been updated\nfunc objectChanged(oldObj, newObj runtime.Object) (bool, error) {\n\tvar doReconcile bool\n\told := oldObj.DeepCopyObject()\n\tnew := newObj.DeepCopyObject()\n\n\t\/\/ Set resource version\n\taccessor := meta.NewAccessor()\n\tcurrentResourceVersion, err := accessor.ResourceVersion(old)\n\tif err == nil {\n\t\taccessor.SetResourceVersion(new, currentResourceVersion)\n\t}\n\n\t\/\/ Calculate diff between old and new object\n\tdiff, err := patch.DefaultPatchMaker.Calculate(old, new)\n\tif err != nil {\n\t\tdoReconcile = true\n\t\treturn doReconcile, errors.Wrap(err, \"failed to calculate object diff\")\n\t} else if diff.IsEmpty() {\n\t\treturn doReconcile, nil\n\t}\n\n\treturn isValidEvent(diff.Patch), nil\n}\n\n\/\/ WatchPredicateForNonCRDObject is a special filter for create events\n\/\/ It only applies to non-CRD objects, meaning, for instance a cephv1.CephBlockPool{}\n\/\/ object will not have this filter\n\/\/ Only for objects like &v1.Secret{} etc...\n\/\/\n\/\/ We return 'false' on a create event so we don't overstep with the main watcher on cephv1.CephBlockPool{}\n\/\/ This avoids a double reconcile when the secret gets deleted.\nfunc WatchPredicateForNonCRDObject(owner runtime.Object, scheme *runtime.Scheme) predicate.Funcs {\n\t\/\/ Initialize the Owner Matcher, which is the main controller object: e.g. cephv1.CephBlockPool{}\n\townerMatcher := NewOwnerReferenceMatcher(owner, scheme)\n\n\treturn predicate.Funcs{\n\t\tCreateFunc: func(e event.CreateEvent) bool {\n\t\t\treturn false\n\t\t},\n\t\tDeleteFunc: func(e event.DeleteEvent) bool {\n\t\t\tmatch, object, err := ownerMatcher.Match(e.Object)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorf(\"failed to check if object kind %q matched. %v\", e.Object.GetObjectKind(), err)\n\t\t\t}\n\t\t\tif match {\n\t\t\t\tlogger.Debugf(\"object %q matched on delete\", object.GetName())\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\tlogger.Debugf(\"object %q did not match on delete\", object.GetName())\n\t\t\treturn false\n\t\t},\n\t\tUpdateFunc: func(e event.UpdateEvent) bool {\n\t\t\tmatch, object, err := ownerMatcher.Match(e.ObjectNew)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorf(\"failed to check if object matched. %v\", err)\n\t\t\t}\n\t\t\tif match {\n\t\t\t\tlogger.Debugf(\"object %q matched on update\", object.GetName())\n\t\t\t\tobjectChanged, err := objectChanged(e.ObjectOld, e.ObjectNew)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Errorf(\"failed to check if object %q changed. %v\", object.GetName(), err)\n\t\t\t\t}\n\t\t\t\treturn objectChanged\n\t\t\t}\n\n\t\t\treturn false\n\t\t},\n\t\tGenericFunc: func(e event.GenericEvent) bool {\n\t\t\treturn false\n\t\t},\n\t}\n}\n\n\/\/ isValidEvent analyses the diff between two objects events and determines\n\/\/ if we should reconcile that event or not\n\/\/ The goal is to avoid double-reconcile as much as possible\nfunc isValidEvent(patch []byte) bool {\n\tpatchString := string(patch)\n\n\t\/\/ Seem a bit 'weak' but since we can't get a real struct of the object\n\t\/\/ (unless we use the unstructured package, but that over complicates things)\n\t\/\/ That's probably the most straightforward approach for now...\n\t\/\/\n\t\/\/ The downscale only shows a \"deletionTimestamp\" which is not appropriate to catch\n\tif strings.Contains(patchString, \"Created new replica set\") {\n\t\tlogger.Debug(\"don't reconcile on replicaset addition\")\n\t\treturn false\n\t}\n\n\t\/\/ It looks like there is a diff\n\t\/\/ if the status changed, we do nothing\n\tvar p map[string]interface{}\n\tjson.Unmarshal(patch, &p)\n\tdelete(p, \"status\")\n\tif len(p) == 0 {\n\t\treturn false\n\t}\n\n\tlogger.Infof(\"will reconcile based on patch %s\", patchString)\n\treturn true\n}\n<commit_msg>ceph: change verbose info log to debug in controller<commit_after>\/*\nCopyright 2020 The Rook Authors. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n\thttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage controller\n\nimport (\n\t\"encoding\/json\"\n\t\"strings\"\n\n\t\"github.com\/banzaicloud\/k8s-objectmatcher\/patch\"\n\t\"github.com\/google\/go-cmp\/cmp\"\n\t\"github.com\/pkg\/errors\"\n\tcephv1 \"github.com\/rook\/rook\/pkg\/apis\/ceph.rook.io\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/api\/meta\"\n\t\"k8s.io\/apimachinery\/pkg\/api\/resource\"\n\t\"k8s.io\/apimachinery\/pkg\/runtime\"\n\t\"sigs.k8s.io\/controller-runtime\/pkg\/event\"\n\t\"sigs.k8s.io\/controller-runtime\/pkg\/predicate\"\n)\n\n\/\/ WatchControllerPredicate is a special update filter for update events\n\/\/ do not reconcile if the the status changes, this avoids a reconcile storm loop\n\/\/\n\/\/ returning 'true' means triggering a reconciliation\n\/\/ returning 'false' means do NOT trigger a reconciliation\nfunc WatchControllerPredicate() predicate.Funcs {\n\treturn predicate.Funcs{\n\t\tCreateFunc: func(e event.CreateEvent) bool {\n\t\t\tlogger.Debug(\"create event from the parent object\")\n\t\t\treturn true\n\t\t},\n\t\tDeleteFunc: func(e event.DeleteEvent) bool {\n\t\t\tlogger.Debug(\"delete event from the parent object\")\n\t\t\treturn true\n\t\t},\n\t\tUpdateFunc: func(e event.UpdateEvent) bool {\n\t\t\tlogger.Debug(\"update event from the parent object\")\n\t\t\t\/\/ resource.Quantity has non-exportable fields, so we use its comparator method\n\t\t\tresourceQtyComparer := cmp.Comparer(func(x, y resource.Quantity) bool { return x.Cmp(y) == 0 })\n\n\t\t\tswitch objOld := e.ObjectOld.(type) {\n\t\t\tcase *cephv1.CephObjectStore:\n\t\t\t\tobjNew := e.ObjectNew.(*cephv1.CephObjectStore)\n\t\t\t\tlogger.Debug(\"update event from the parent object CephObjectStore\")\n\t\t\t\tdiff := cmp.Diff(objOld.Spec, objNew.Spec, resourceQtyComparer)\n\t\t\t\tif diff != \"\" ||\n\t\t\t\t\tobjOld.GetDeletionTimestamp() != objNew.GetDeletionTimestamp() ||\n\t\t\t\t\tobjOld.GetGeneration() != objNew.GetGeneration() {\n\t\t\t\t\t\/\/ Checking if diff is not empty so we don't print it when the CR gets deleted\n\t\t\t\t\tif diff != \"\" {\n\t\t\t\t\t\tlogger.Infof(\"CR has changed for %q. diff=%s\", objNew.Name, diff)\n\t\t\t\t\t}\n\t\t\t\t\treturn true\n\t\t\t\t}\n\n\t\t\tcase *cephv1.CephObjectStoreUser:\n\t\t\t\tobjNew := e.ObjectNew.(*cephv1.CephObjectStoreUser)\n\t\t\t\tlogger.Debug(\"update event from the parent object CephObjectStoreUser\")\n\t\t\t\tdiff := cmp.Diff(objOld.Spec, objNew.Spec, resourceQtyComparer)\n\t\t\t\tif diff != \"\" ||\n\t\t\t\t\tobjOld.GetDeletionTimestamp() != objNew.GetDeletionTimestamp() ||\n\t\t\t\t\tobjOld.GetGeneration() != objNew.GetGeneration() {\n\t\t\t\t\t\/\/ Checking if diff is not empty so we don't print it when the CR gets deleted\n\t\t\t\t\tif diff != \"\" {\n\t\t\t\t\t\tlogger.Infof(\"CR has changed for %q. diff=%s\", objNew.Name, diff)\n\t\t\t\t\t}\n\t\t\t\t\treturn true\n\t\t\t\t}\n\n\t\t\tcase *cephv1.CephBlockPool:\n\t\t\t\tobjNew := e.ObjectNew.(*cephv1.CephBlockPool)\n\t\t\t\tlogger.Debug(\"update event from the parent object CephBlockPool\")\n\t\t\t\tdiff := cmp.Diff(objOld.Spec, objNew.Spec, resourceQtyComparer)\n\t\t\t\tif diff != \"\" ||\n\t\t\t\t\tobjOld.GetDeletionTimestamp() != objNew.GetDeletionTimestamp() ||\n\t\t\t\t\tobjOld.GetGeneration() != objNew.GetGeneration() {\n\t\t\t\t\t\/\/ Checking if diff is not empty so we don't print it when the CR gets deleted\n\t\t\t\t\tif diff != \"\" {\n\t\t\t\t\t\tlogger.Infof(\"CR has changed for %q. diff=%s\", objNew.Name, diff)\n\t\t\t\t\t}\n\t\t\t\t\treturn true\n\t\t\t\t}\n\n\t\t\tcase *cephv1.CephFilesystem:\n\t\t\t\tobjNew := e.ObjectNew.(*cephv1.CephFilesystem)\n\t\t\t\tlogger.Debug(\"update event from the parent object CephFilesystem\")\n\t\t\t\tdiff := cmp.Diff(objOld.Spec, objNew.Spec, resourceQtyComparer)\n\t\t\t\tif diff != \"\" ||\n\t\t\t\t\tobjOld.GetDeletionTimestamp() != objNew.GetDeletionTimestamp() ||\n\t\t\t\t\tobjOld.GetGeneration() != objNew.GetGeneration() {\n\t\t\t\t\t\/\/ Checking if diff is not empty so we don't print it when the CR gets deleted\n\t\t\t\t\tif diff != \"\" {\n\t\t\t\t\t\tlogger.Infof(\"CR has changed for %q. diff=%s\", objNew.Name, diff)\n\t\t\t\t\t}\n\t\t\t\t\treturn true\n\t\t\t\t}\n\n\t\t\tcase *cephv1.CephNFS:\n\t\t\t\tobjNew := e.ObjectNew.(*cephv1.CephNFS)\n\t\t\t\tlogger.Debug(\"update event from the parent object CephNFS\")\n\t\t\t\tdiff := cmp.Diff(objOld.Spec, objNew.Spec, resourceQtyComparer)\n\t\t\t\tif diff != \"\" ||\n\t\t\t\t\tobjOld.GetDeletionTimestamp() != objNew.GetDeletionTimestamp() ||\n\t\t\t\t\tobjOld.GetGeneration() != objNew.GetGeneration() {\n\t\t\t\t\t\/\/ Checking if diff is not empty so we don't print it when the CR gets deleted\n\t\t\t\t\tif diff != \"\" {\n\t\t\t\t\t\tlogger.Infof(\"CR has changed for %q. diff=%s\", objNew.Name, diff)\n\t\t\t\t\t}\n\t\t\t\t\treturn true\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tlogger.Debug(\"wont update unknown object\")\n\t\t\treturn false\n\t\t},\n\t\tGenericFunc: func(e event.GenericEvent) bool {\n\t\t\treturn false\n\t\t},\n\t}\n}\n\n\/\/ objectChanged checks whether the object has been updated\nfunc objectChanged(oldObj, newObj runtime.Object) (bool, error) {\n\tvar doReconcile bool\n\told := oldObj.DeepCopyObject()\n\tnew := newObj.DeepCopyObject()\n\n\t\/\/ Set resource version\n\taccessor := meta.NewAccessor()\n\tcurrentResourceVersion, err := accessor.ResourceVersion(old)\n\tif err == nil {\n\t\taccessor.SetResourceVersion(new, currentResourceVersion)\n\t}\n\n\t\/\/ Calculate diff between old and new object\n\tdiff, err := patch.DefaultPatchMaker.Calculate(old, new)\n\tif err != nil {\n\t\tdoReconcile = true\n\t\treturn doReconcile, errors.Wrap(err, \"failed to calculate object diff\")\n\t} else if diff.IsEmpty() {\n\t\treturn doReconcile, nil\n\t}\n\n\treturn isValidEvent(diff.Patch), nil\n}\n\n\/\/ WatchPredicateForNonCRDObject is a special filter for create events\n\/\/ It only applies to non-CRD objects, meaning, for instance a cephv1.CephBlockPool{}\n\/\/ object will not have this filter\n\/\/ Only for objects like &v1.Secret{} etc...\n\/\/\n\/\/ We return 'false' on a create event so we don't overstep with the main watcher on cephv1.CephBlockPool{}\n\/\/ This avoids a double reconcile when the secret gets deleted.\nfunc WatchPredicateForNonCRDObject(owner runtime.Object, scheme *runtime.Scheme) predicate.Funcs {\n\t\/\/ Initialize the Owner Matcher, which is the main controller object: e.g. cephv1.CephBlockPool{}\n\townerMatcher := NewOwnerReferenceMatcher(owner, scheme)\n\n\treturn predicate.Funcs{\n\t\tCreateFunc: func(e event.CreateEvent) bool {\n\t\t\treturn false\n\t\t},\n\t\tDeleteFunc: func(e event.DeleteEvent) bool {\n\t\t\tmatch, object, err := ownerMatcher.Match(e.Object)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorf(\"failed to check if object kind %q matched. %v\", e.Object.GetObjectKind(), err)\n\t\t\t}\n\t\t\tif match {\n\t\t\t\tlogger.Debugf(\"object %q matched on delete\", object.GetName())\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\tlogger.Debugf(\"object %q did not match on delete\", object.GetName())\n\t\t\treturn false\n\t\t},\n\t\tUpdateFunc: func(e event.UpdateEvent) bool {\n\t\t\tmatch, object, err := ownerMatcher.Match(e.ObjectNew)\n\t\t\tif err != nil {\n\t\t\t\tlogger.Errorf(\"failed to check if object matched. %v\", err)\n\t\t\t}\n\t\t\tif match {\n\t\t\t\tlogger.Debugf(\"object %q matched on update\", object.GetName())\n\t\t\t\tobjectChanged, err := objectChanged(e.ObjectOld, e.ObjectNew)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Errorf(\"failed to check if object %q changed. %v\", object.GetName(), err)\n\t\t\t\t}\n\t\t\t\treturn objectChanged\n\t\t\t}\n\n\t\t\treturn false\n\t\t},\n\t\tGenericFunc: func(e event.GenericEvent) bool {\n\t\t\treturn false\n\t\t},\n\t}\n}\n\n\/\/ isValidEvent analyses the diff between two objects events and determines\n\/\/ if we should reconcile that event or not\n\/\/ The goal is to avoid double-reconcile as much as possible\nfunc isValidEvent(patch []byte) bool {\n\tpatchString := string(patch)\n\n\t\/\/ Seem a bit 'weak' but since we can't get a real struct of the object\n\t\/\/ (unless we use the unstructured package, but that over complicates things)\n\t\/\/ That's probably the most straightforward approach for now...\n\t\/\/\n\t\/\/ The downscale only shows a \"deletionTimestamp\" which is not appropriate to catch\n\tif strings.Contains(patchString, \"Created new replica set\") {\n\t\tlogger.Debug(\"don't reconcile on replicaset addition\")\n\t\treturn false\n\t}\n\n\t\/\/ It looks like there is a diff\n\t\/\/ if the status changed, we do nothing\n\tvar p map[string]interface{}\n\tjson.Unmarshal(patch, &p)\n\tdelete(p, \"status\")\n\tif len(p) == 0 {\n\t\treturn false\n\t}\n\n\tlogger.Debugf(\"will reconcile based on patch %s\", patchString)\n\treturn true\n}\n<|endoftext|>"}
{"text":"<commit_before>package lib\n\nimport (\n\t\"crypto\/tls\"\n\t\"fmt\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ Client is the API client that performs all operations\n\/\/ against a docker server.\ntype Client struct {\n\t\/\/ proto holds the client protocol i.e. unix.\n\tproto string\n\t\/\/ addr holds the client address.\n\taddr string\n\t\/\/ basePath holds the path to prepend to the requests\n\tbasePath string\n\t\/\/ scheme holds the scheme of the client i.e. https.\n\tscheme string\n\t\/\/ tlsConfig holds the tls configuration to use in hijacked requests.\n\ttlsConfig *tls.Config\n\t\/\/ httpClient holds the client transport instance. Exported to keep the old code running.\n\thttpClient *http.Client\n\t\/\/ version of the server to talk to.\n\tversion string\n\t\/\/ custom http headers configured by users\n\tcustomHTTPHeaders map[string]string\n}\n\n\/\/ NewEnvClient initializes a new API client based on environment variables.\n\/\/ Use DOCKER_HOST to set the url to the docker server.\n\/\/ Use DOCKER_API_VERSION to set the version of the API to reach, leave empty for latest.\n\/\/ Use DOCKER_CERT_PATH to load the tls certificates from.\nfunc NewEnvClient() (*Client, error) {\n\tvar transport *http.Transport\n\tif dockerCertPath := os.Getenv(\"DOCKER_CERT_PATH\"); dockerCertPath != \"\" {\n\t\ttlsc := &tls.Config{}\n\n\t\tcert, err := tls.LoadX509KeyPair(filepath.Join(dockerCertPath, \"cert.pem\"), filepath.Join(dockerCertPath, \"key.pem\"))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Error loading x509 key pair: %s\", err)\n\t\t}\n\n\t\ttlsc.Certificates = append(tlsc.Certificates, cert)\n\t\ttlsc.InsecureSkipVerify = os.Getenv(\"DOCKER_TLS_VERIFY\") == \"\"\n\t\ttransport = &http.Transport{\n\t\t\tTLSClientConfig: tlsc,\n\t\t}\n\t}\n\n\treturn NewClient(os.Getenv(\"DOCKER_HOST\"), os.Getenv(\"DOCKER_API_VERSION\"), transport, nil)\n}\n\n\/\/ NewClient initializes a new API client for the given host and API version.\n\/\/ It won't send any version information if the version number is empty.\n\/\/ It uses the transport to create a new http client.\n\/\/ It also initializes the custom http headers to add to each request.\nfunc NewClient(host string, version string, transport *http.Transport, httpHeaders map[string]string) (*Client, error) {\n\tvar (\n\t\tbasePath       string\n\t\ttlsConfig      *tls.Config\n\t\tscheme         = \"http\"\n\t\tprotoAddrParts = strings.SplitN(host, \":\/\/\", 2)\n\t\tproto, addr    = protoAddrParts[0], protoAddrParts[1]\n\t)\n\n\tif proto == \"tcp\" {\n\t\tparsed, err := url.Parse(\"tcp:\/\/\" + addr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\taddr = parsed.Host\n\t\tbasePath = parsed.Path\n\t}\n\n\ttransport = configureTransport(transport, proto, addr)\n\tif transport.TLSClientConfig != nil {\n\t\tscheme = \"https\"\n\t}\n\n\treturn &Client{\n\t\tproto:             proto,\n\t\taddr:              addr,\n\t\tbasePath:          basePath,\n\t\tscheme:            scheme,\n\t\ttlsConfig:         tlsConfig,\n\t\thttpClient:        &http.Client{Transport: transport},\n\t\tversion:           version,\n\t\tcustomHTTPHeaders: httpHeaders,\n\t}, nil\n}\n\n\/\/ getAPIPath returns the versioned request path to call the api.\n\/\/ It appends the query parameters to the path if they are not empty.\nfunc (cli *Client) getAPIPath(p string, query url.Values) string {\n\tvar apiPath string\n\tif cli.version != \"\" {\n\t\tv := strings.TrimPrefix(cli.version, \"v\")\n\t\tapiPath = fmt.Sprintf(\"%s\/v%s%s\", cli.basePath, v, p)\n\t} else {\n\t\tapiPath = fmt.Sprintf(\"%s%s\", cli.basePath, p)\n\t}\n\tif len(query) > 0 {\n\t\tapiPath += \"?\" + query.Encode()\n\t}\n\treturn apiPath\n}\n\n\/\/ ClientVersion returns the version string associated with this\n\/\/ instance of the Client. Note that this value can be changed\n\/\/ via the DOCKER_API_VERSION env var.\nfunc (cli *Client) ClientVersion() string {\n\treturn cli.version\n}\n\nfunc configureTransport(tr *http.Transport, proto, addr string) *http.Transport {\n\tif tr == nil {\n\t\ttr = &http.Transport{}\n\t}\n\n\t\/\/ Why 32? See https:\/\/github.com\/docker\/docker\/pull\/8035.\n\ttimeout := 32 * time.Second\n\tif proto == \"unix\" {\n\t\t\/\/ No need for compression in local communications.\n\t\ttr.DisableCompression = true\n\t\ttr.Dial = func(_, _ string) (net.Conn, error) {\n\t\t\treturn net.DialTimeout(proto, addr, timeout)\n\t\t}\n\t} else {\n\t\ttr.Proxy = http.ProxyFromEnvironment\n\t\ttr.Dial = (&net.Dialer{Timeout: timeout}).Dial\n\t}\n\n\treturn tr\n}\n<commit_msg>Add godoc comment about client tls verification.<commit_after>package lib\n\nimport (\n\t\"crypto\/tls\"\n\t\"fmt\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ Client is the API client that performs all operations\n\/\/ against a docker server.\ntype Client struct {\n\t\/\/ proto holds the client protocol i.e. unix.\n\tproto string\n\t\/\/ addr holds the client address.\n\taddr string\n\t\/\/ basePath holds the path to prepend to the requests\n\tbasePath string\n\t\/\/ scheme holds the scheme of the client i.e. https.\n\tscheme string\n\t\/\/ tlsConfig holds the tls configuration to use in hijacked requests.\n\ttlsConfig *tls.Config\n\t\/\/ httpClient holds the client transport instance. Exported to keep the old code running.\n\thttpClient *http.Client\n\t\/\/ version of the server to talk to.\n\tversion string\n\t\/\/ custom http headers configured by users\n\tcustomHTTPHeaders map[string]string\n}\n\n\/\/ NewEnvClient initializes a new API client based on environment variables.\n\/\/ Use DOCKER_HOST to set the url to the docker server.\n\/\/ Use DOCKER_API_VERSION to set the version of the API to reach, leave empty for latest.\n\/\/ Use DOCKER_CERT_PATH to load the tls certificates from.\n\/\/ Use DOCKER_TLS_VERIFY to enable or disable TLS verification, off by default.\nfunc NewEnvClient() (*Client, error) {\n\tvar transport *http.Transport\n\tif dockerCertPath := os.Getenv(\"DOCKER_CERT_PATH\"); dockerCertPath != \"\" {\n\t\ttlsc := &tls.Config{}\n\n\t\tcert, err := tls.LoadX509KeyPair(filepath.Join(dockerCertPath, \"cert.pem\"), filepath.Join(dockerCertPath, \"key.pem\"))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Error loading x509 key pair: %s\", err)\n\t\t}\n\n\t\ttlsc.Certificates = append(tlsc.Certificates, cert)\n\t\ttlsc.InsecureSkipVerify = os.Getenv(\"DOCKER_TLS_VERIFY\") == \"\"\n\t\ttransport = &http.Transport{\n\t\t\tTLSClientConfig: tlsc,\n\t\t}\n\t}\n\n\treturn NewClient(os.Getenv(\"DOCKER_HOST\"), os.Getenv(\"DOCKER_API_VERSION\"), transport, nil)\n}\n\n\/\/ NewClient initializes a new API client for the given host and API version.\n\/\/ It won't send any version information if the version number is empty.\n\/\/ It uses the transport to create a new http client.\n\/\/ It also initializes the custom http headers to add to each request.\nfunc NewClient(host string, version string, transport *http.Transport, httpHeaders map[string]string) (*Client, error) {\n\tvar (\n\t\tbasePath       string\n\t\ttlsConfig      *tls.Config\n\t\tscheme         = \"http\"\n\t\tprotoAddrParts = strings.SplitN(host, \":\/\/\", 2)\n\t\tproto, addr    = protoAddrParts[0], protoAddrParts[1]\n\t)\n\n\tif proto == \"tcp\" {\n\t\tparsed, err := url.Parse(\"tcp:\/\/\" + addr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\taddr = parsed.Host\n\t\tbasePath = parsed.Path\n\t}\n\n\ttransport = configureTransport(transport, proto, addr)\n\tif transport.TLSClientConfig != nil {\n\t\tscheme = \"https\"\n\t}\n\n\treturn &Client{\n\t\tproto:             proto,\n\t\taddr:              addr,\n\t\tbasePath:          basePath,\n\t\tscheme:            scheme,\n\t\ttlsConfig:         tlsConfig,\n\t\thttpClient:        &http.Client{Transport: transport},\n\t\tversion:           version,\n\t\tcustomHTTPHeaders: httpHeaders,\n\t}, nil\n}\n\n\/\/ getAPIPath returns the versioned request path to call the api.\n\/\/ It appends the query parameters to the path if they are not empty.\nfunc (cli *Client) getAPIPath(p string, query url.Values) string {\n\tvar apiPath string\n\tif cli.version != \"\" {\n\t\tv := strings.TrimPrefix(cli.version, \"v\")\n\t\tapiPath = fmt.Sprintf(\"%s\/v%s%s\", cli.basePath, v, p)\n\t} else {\n\t\tapiPath = fmt.Sprintf(\"%s%s\", cli.basePath, p)\n\t}\n\tif len(query) > 0 {\n\t\tapiPath += \"?\" + query.Encode()\n\t}\n\treturn apiPath\n}\n\n\/\/ ClientVersion returns the version string associated with this\n\/\/ instance of the Client. Note that this value can be changed\n\/\/ via the DOCKER_API_VERSION env var.\nfunc (cli *Client) ClientVersion() string {\n\treturn cli.version\n}\n\nfunc configureTransport(tr *http.Transport, proto, addr string) *http.Transport {\n\tif tr == nil {\n\t\ttr = &http.Transport{}\n\t}\n\n\t\/\/ Why 32? See https:\/\/github.com\/docker\/docker\/pull\/8035.\n\ttimeout := 32 * time.Second\n\tif proto == \"unix\" {\n\t\t\/\/ No need for compression in local communications.\n\t\ttr.DisableCompression = true\n\t\ttr.Dial = func(_, _ string) (net.Conn, error) {\n\t\t\treturn net.DialTimeout(proto, addr, timeout)\n\t\t}\n\t} else {\n\t\ttr.Proxy = http.ProxyFromEnvironment\n\t\ttr.Dial = (&net.Dialer{Timeout: timeout}).Dial\n\t}\n\n\treturn tr\n}\n<|endoftext|>"}
{"text":"<commit_before>package engi\n\nimport (\n\/\/ \"log\"\n)\n\ntype Spritesheet struct {\n\ttexture               *Texture\n\tCellWidth, CellHeight int\n\tcache                 map[int]*Region\n}\n\nfunc (s Spritesheet) Cell(i int) *Region {\n\ts.cache[i] = getRegionOfSpriteSheet(s.texture, 16, i)\n\treturn s.cache[i]\n}\n\nfunc (s Spritesheet) Width() float32 {\n\treturn s.texture.Width() \/ float32(s.CellWidth)\n}\n\nfunc (s Spritesheet) Height() float32 {\n\treturn s.texture.Height() \/ float32(s.CellHeight)\n}\n\nfunc NewSpritesheet(filename string, cellsize int) *Spritesheet {\n\treturn &Spritesheet{texture: Files.Image(filename), CellWidth: cellsize, CellHeight: cellsize, cache: make(map[int]*Region)}\n}\n\ntype AnimationComponent struct {\n\tIndex  int\n\tRate   float32\n\tChange float32\n\tTick   float32\n\tS      *Spritesheet\n}\n\nfunc (ac AnimationComponent) Name() string {\n\treturn \"AnimationComponent\"\n}\n\ntype AnimationSystem struct {\n\t*System\n}\n\nfunc (a *AnimationSystem) New() {\n\ta.System = &System{}\n}\n\nfunc (a AnimationSystem) Name() string {\n\treturn \"AnimationSystem\"\n}\n\nfunc (a *AnimationSystem) Update(e *Entity, dt float32) {\n\tvar (\n\t\tac *AnimationComponent\n\t\tr  *RenderComponent\n\t)\n\n\tif !e.GetComponent(&ac) || !e.GetComponent(&r) {\n\t\treturn\n\t}\n\n\tac.Change += dt\n\tif ac.Change >= ac.Rate {\n\t\tac.Index += 1\n\t\tif ac.Index >= int(ac.S.Width()*ac.S.Height()) {\n\t\t\tac.Index = 0\n\t\t}\n\t\tac.Change = 0\n\t\tr.Display = ac.S.Cell(ac.Index)\n\t}\n}\n<commit_msg>Added\/implemented a cache for spritesheets<commit_after>package engi\n\ntype Spritesheet struct {\n\ttexture               *Texture\n\tCellWidth, CellHeight int\n\tcache                 map[int]*Region\n}\n\nfunc (s Spritesheet) Cell(i int) *Region {\n\tif r := s.cache[i]; r != nil {\n\t\treturn r\n\t}\n\ts.cache[i] = getRegionOfSpriteSheet(s.texture, 16, i)\n\treturn s.cache[i]\n}\n\nfunc (s Spritesheet) Width() float32 {\n\treturn s.texture.Width() \/ float32(s.CellWidth)\n}\n\nfunc (s Spritesheet) Height() float32 {\n\treturn s.texture.Height() \/ float32(s.CellHeight)\n}\n\nfunc NewSpritesheet(filename string, cellsize int) *Spritesheet {\n\treturn &Spritesheet{texture: Files.Image(filename), CellWidth: cellsize, CellHeight: cellsize, cache: make(map[int]*Region)}\n}\n\ntype AnimationComponent struct {\n\tIndex  int\n\tRate   float32\n\tChange float32\n\tTick   float32\n\tS      *Spritesheet\n}\n\nfunc (ac AnimationComponent) Name() string {\n\treturn \"AnimationComponent\"\n}\n\ntype AnimationSystem struct {\n\t*System\n}\n\nfunc (a *AnimationSystem) New() {\n\ta.System = &System{}\n}\n\nfunc (a AnimationSystem) Name() string {\n\treturn \"AnimationSystem\"\n}\n\nfunc (a *AnimationSystem) Update(e *Entity, dt float32) {\n\tvar (\n\t\tac *AnimationComponent\n\t\tr  *RenderComponent\n\t)\n\n\tif !e.GetComponent(&ac) || !e.GetComponent(&r) {\n\t\treturn\n\t}\n\n\tac.Change += dt\n\tif ac.Change >= ac.Rate {\n\t\tac.Index += 1\n\t\tif ac.Index >= int(ac.S.Width()*ac.S.Height()) {\n\t\t\tac.Index = 0\n\t\t}\n\t\tac.Change = 0\n\t\tr.Display = ac.S.Cell(ac.Index)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2020 The Vitess Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage semantics\n\nimport (\n\t\"vitess.io\/vitess\/go\/mysql\"\n\tvtrpcpb \"vitess.io\/vitess\/go\/vt\/proto\/vtrpc\"\n\t\"vitess.io\/vitess\/go\/vt\/sqlparser\"\n\t\"vitess.io\/vitess\/go\/vt\/vterrors\"\n)\n\ntype (\n\t\/\/ analyzer is a struct to work with analyzing the query.\n\tanalyzer struct {\n\t\tTables []table\n\n\t\tscopes   []*scope\n\t\texprDeps map[sqlparser.Expr]TableSet\n\t\terr      error\n\t}\n)\n\n\/\/ newAnalyzer create the semantic analyzer\nfunc newAnalyzer() *analyzer {\n\treturn &analyzer{\n\t\texprDeps: map[sqlparser.Expr]TableSet{},\n\t}\n}\n\n\/\/ analyzeDown pushes new scopes when we encounter sub queries,\n\/\/ and resolves the table a column is using\nfunc (a *analyzer) analyzeDown(cursor *sqlparser.Cursor) bool {\n\tcurrent := a.currentScope()\n\tn := cursor.Node()\n\tswitch node := n.(type) {\n\tcase *sqlparser.Select:\n\t\ta.push(newScope(current))\n\t\tif err := a.analyzeTableExprs(node.From); err != nil {\n\t\t\ta.err = err\n\t\t\treturn false\n\t\t}\n\tcase *sqlparser.TableExprs:\n\t\t\/\/ this has already been visited when we encountered the SELECT struct\n\t\treturn false\n\n\t\/\/ we don't need to push new scope for sub queries since we do that for SELECT and UNION\n\n\tcase *sqlparser.Union:\n\t\ta.push(newScope(current))\n\tcase *sqlparser.ColName:\n\t\tt, err := a.resolveColumn(node, current)\n\t\tif err != nil {\n\t\t\ta.err = err\n\t\t}\n\t\ta.exprDeps[node] = t\n\t}\n\treturn a.shouldContinue()\n}\n\nfunc (a *analyzer) resolveColumn(colName *sqlparser.ColName, current *scope) (TableSet, error) {\n\tvar t table\n\tvar err error\n\tif colName.Qualifier.IsEmpty() {\n\t\tt, err = a.resolveUnQualifiedColumn(current)\n\t} else {\n\t\tt, err = a.resolveQualifiedColumn(current, colName)\n\t}\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn a.tableSetFor(t), nil\n}\n\nfunc (a *analyzer) analyzeTableExprs(tablExprs sqlparser.TableExprs) error {\n\tfor _, tableExpr := range tablExprs {\n\t\tif err := a.analyzeTableExpr(tableExpr); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (a *analyzer) analyzeTableExpr(tableExpr sqlparser.TableExpr) error {\n\tswitch table := tableExpr.(type) {\n\tcase *sqlparser.AliasedTableExpr:\n\t\treturn a.bindTable(table, table.Expr)\n\tcase *sqlparser.JoinTableExpr:\n\t\tif err := a.analyzeTableExpr(table.LeftExpr); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := a.analyzeTableExpr(table.RightExpr); err != nil {\n\t\t\treturn err\n\t\t}\n\tcase *sqlparser.ParenTableExpr:\n\t\treturn a.analyzeTableExprs(table.Exprs)\n\t}\n\treturn nil\n}\n\n\/\/ resolveQualifiedColumn handles `tabl.col` expressions\nfunc (a *analyzer) resolveQualifiedColumn(current *scope, expr *sqlparser.ColName) (table, error) {\n\tqualifier := expr.Qualifier.Name.String()\n\n\tfor current != nil {\n\t\ttableExpr, found := current.tables[qualifier]\n\t\tif found {\n\t\t\treturn tableExpr, nil\n\t\t}\n\t\tcurrent = current.parent\n\t}\n\n\treturn nil, mysql.NewSQLError(mysql.ERBadFieldError, mysql.SSBadFieldError, \"Unknown table referenced by '%s'\", sqlparser.String(expr))\n}\n\n\/\/ resolveUnQualifiedColumn\nfunc (a *analyzer) resolveUnQualifiedColumn(current *scope) (table, error) {\n\tif len(current.tables) == 1 {\n\t\tfor _, tableExpr := range current.tables {\n\t\t\treturn tableExpr, nil\n\t\t}\n\t}\n\treturn nil, vterrors.Errorf(vtrpcpb.Code_UNIMPLEMENTED, \"todo - figure out which table this column belongs to\")\n}\n\nfunc (a *analyzer) tableSetFor(t table) TableSet {\n\tfor i, t2 := range a.Tables {\n\t\tif t == t2 {\n\t\t\treturn TableSet(1 << i)\n\t\t}\n\t}\n\tpanic(\"unknown table\")\n}\n\nfunc (a *analyzer) bindTable(alias *sqlparser.AliasedTableExpr, expr sqlparser.SimpleTableExpr) error {\n\tswitch t := expr.(type) {\n\tcase *sqlparser.DerivedTable:\n\t\ta.push(newScope(nil))\n\t\tif err := a.analyze(t.Select); err != nil {\n\t\t\treturn err\n\t\t}\n\t\ta.popScope()\n\t\tscope := a.currentScope()\n\t\treturn scope.addTable(alias.As.String(), alias)\n\tcase sqlparser.TableName:\n\t\tscope := a.currentScope()\n\t\ta.Tables = append(a.Tables, alias)\n\t\tif alias.As.IsEmpty() {\n\t\t\treturn scope.addTable(t.Name.String(), alias)\n\t\t}\n\t\treturn scope.addTable(alias.As.String(), alias)\n\t}\n\treturn nil\n}\n\nfunc (a *analyzer) analyze(statement sqlparser.Statement) error {\n\t_ = sqlparser.Rewrite(statement, a.analyzeDown, a.analyzeUp)\n\n\treturn a.err\n}\n\nfunc (a *analyzer) analyzeUp(cursor *sqlparser.Cursor) bool {\n\tswitch cursor.Node().(type) {\n\tcase *sqlparser.Union, *sqlparser.Select:\n\t\ta.popScope()\n\t}\n\treturn true\n}\n\nfunc (a *analyzer) shouldContinue() bool {\n\treturn a.err == nil\n}\n\nfunc (a *analyzer) push(s *scope) {\n\ta.scopes = append(a.scopes, s)\n}\n\nfunc (a *analyzer) popScope() {\n\tl := len(a.scopes) - 1\n\ta.scopes = a.scopes[:l]\n}\n\nfunc (a *analyzer) currentScope() *scope {\n\tsize := len(a.scopes)\n\tif size == 0 {\n\t\treturn nil\n\t}\n\treturn a.scopes[size-1]\n}\n<commit_msg>fail semantic analyzer for queries that are not supported yet<commit_after>\/*\nCopyright 2020 The Vitess Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage semantics\n\nimport (\n\t\"vitess.io\/vitess\/go\/mysql\"\n\tvtrpcpb \"vitess.io\/vitess\/go\/vt\/proto\/vtrpc\"\n\t\"vitess.io\/vitess\/go\/vt\/sqlparser\"\n\t\"vitess.io\/vitess\/go\/vt\/vterrors\"\n)\n\ntype (\n\t\/\/ analyzer is a struct to work with analyzing the query.\n\tanalyzer struct {\n\t\tTables []table\n\n\t\tscopes   []*scope\n\t\texprDeps map[sqlparser.Expr]TableSet\n\t\terr      error\n\t}\n)\n\n\/\/ newAnalyzer create the semantic analyzer\nfunc newAnalyzer() *analyzer {\n\treturn &analyzer{\n\t\texprDeps: map[sqlparser.Expr]TableSet{},\n\t}\n}\n\n\/\/ analyzeDown pushes new scopes when we encounter sub queries,\n\/\/ and resolves the table a column is using\nfunc (a *analyzer) analyzeDown(cursor *sqlparser.Cursor) bool {\n\tcurrent := a.currentScope()\n\tn := cursor.Node()\n\tswitch node := n.(type) {\n\tcase *sqlparser.Select:\n\t\ta.push(newScope(current))\n\t\tif err := a.analyzeTableExprs(node.From); err != nil {\n\t\t\ta.err = err\n\t\t\treturn false\n\t\t}\n\tcase *sqlparser.DerivedTable, *sqlparser.Subquery:\n\t\ta.err = vterrors.Errorf(vtrpcpb.Code_UNIMPLEMENTED, \"%T not supported\", node)\n\tcase *sqlparser.TableExprs:\n\t\t\/\/ this has already been visited when we encountered the SELECT struct\n\t\treturn false\n\n\t\/\/ we don't need to push new scope for sub queries since we do that for SELECT and UNION\n\n\tcase *sqlparser.Union:\n\t\ta.push(newScope(current))\n\tcase *sqlparser.ColName:\n\t\tt, err := a.resolveColumn(node, current)\n\t\tif err != nil {\n\t\t\ta.err = err\n\t\t}\n\t\ta.exprDeps[node] = t\n\t}\n\treturn a.shouldContinue()\n}\n\nfunc (a *analyzer) resolveColumn(colName *sqlparser.ColName, current *scope) (TableSet, error) {\n\tvar t table\n\tvar err error\n\tif colName.Qualifier.IsEmpty() {\n\t\tt, err = a.resolveUnQualifiedColumn(current)\n\t} else {\n\t\tt, err = a.resolveQualifiedColumn(current, colName)\n\t}\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn a.tableSetFor(t), nil\n}\n\nfunc (a *analyzer) analyzeTableExprs(tablExprs sqlparser.TableExprs) error {\n\tfor _, tableExpr := range tablExprs {\n\t\tif err := a.analyzeTableExpr(tableExpr); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (a *analyzer) analyzeTableExpr(tableExpr sqlparser.TableExpr) error {\n\tswitch table := tableExpr.(type) {\n\tcase *sqlparser.AliasedTableExpr:\n\t\treturn a.bindTable(table, table.Expr)\n\tcase *sqlparser.JoinTableExpr:\n\t\tif table.Join != sqlparser.NormalJoinType {\n\t\t\treturn vterrors.Errorf(vtrpcpb.Code_UNIMPLEMENTED, \"Join type not supported: %s\", table.Join.ToString())\n\t\t}\n\t\tif err := a.analyzeTableExpr(table.LeftExpr); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := a.analyzeTableExpr(table.RightExpr); err != nil {\n\t\t\treturn err\n\t\t}\n\tcase *sqlparser.ParenTableExpr:\n\t\treturn a.analyzeTableExprs(table.Exprs)\n\t}\n\treturn nil\n}\n\n\/\/ resolveQualifiedColumn handles `tabl.col` expressions\nfunc (a *analyzer) resolveQualifiedColumn(current *scope, expr *sqlparser.ColName) (table, error) {\n\tqualifier := expr.Qualifier.Name.String()\n\n\tfor current != nil {\n\t\ttableExpr, found := current.tables[qualifier]\n\t\tif found {\n\t\t\treturn tableExpr, nil\n\t\t}\n\t\tcurrent = current.parent\n\t}\n\n\treturn nil, mysql.NewSQLError(mysql.ERBadFieldError, mysql.SSBadFieldError, \"Unknown table referenced by '%s'\", sqlparser.String(expr))\n}\n\n\/\/ resolveUnQualifiedColumn\nfunc (a *analyzer) resolveUnQualifiedColumn(current *scope) (table, error) {\n\tif len(current.tables) == 1 {\n\t\tfor _, tableExpr := range current.tables {\n\t\t\treturn tableExpr, nil\n\t\t}\n\t}\n\treturn nil, vterrors.Errorf(vtrpcpb.Code_UNIMPLEMENTED, \"todo - figure out which table this column belongs to\")\n}\n\nfunc (a *analyzer) tableSetFor(t table) TableSet {\n\tfor i, t2 := range a.Tables {\n\t\tif t == t2 {\n\t\t\treturn TableSet(1 << i)\n\t\t}\n\t}\n\tpanic(\"unknown table\")\n}\n\nfunc (a *analyzer) bindTable(alias *sqlparser.AliasedTableExpr, expr sqlparser.SimpleTableExpr) error {\n\tswitch t := expr.(type) {\n\tcase *sqlparser.DerivedTable:\n\t\ta.push(newScope(nil))\n\t\tif err := a.analyze(t.Select); err != nil {\n\t\t\treturn err\n\t\t}\n\t\ta.popScope()\n\t\tscope := a.currentScope()\n\t\treturn scope.addTable(alias.As.String(), alias)\n\tcase sqlparser.TableName:\n\t\tscope := a.currentScope()\n\t\ta.Tables = append(a.Tables, alias)\n\t\tif alias.As.IsEmpty() {\n\t\t\treturn scope.addTable(t.Name.String(), alias)\n\t\t}\n\t\treturn scope.addTable(alias.As.String(), alias)\n\t}\n\treturn nil\n}\n\nfunc (a *analyzer) analyze(statement sqlparser.Statement) error {\n\t_ = sqlparser.Rewrite(statement, a.analyzeDown, a.analyzeUp)\n\n\treturn a.err\n}\n\nfunc (a *analyzer) analyzeUp(cursor *sqlparser.Cursor) bool {\n\tswitch cursor.Node().(type) {\n\tcase *sqlparser.Union, *sqlparser.Select:\n\t\ta.popScope()\n\t}\n\treturn true\n}\n\nfunc (a *analyzer) shouldContinue() bool {\n\treturn a.err == nil\n}\n\nfunc (a *analyzer) push(s *scope) {\n\ta.scopes = append(a.scopes, s)\n}\n\nfunc (a *analyzer) popScope() {\n\tl := len(a.scopes) - 1\n\ta.scopes = a.scopes[:l]\n}\n\nfunc (a *analyzer) currentScope() *scope {\n\tsize := len(a.scopes)\n\tif size == 0 {\n\t\treturn nil\n\t}\n\treturn a.scopes[size-1]\n}\n<|endoftext|>"}
{"text":"<commit_before>package net_test\n\nimport (\n\t\"errors\"\n\t\"strings\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\n\t. \"github.com\/cloudfoundry\/bosh-agent\/platform\/net\"\n\tfakearp \"github.com\/cloudfoundry\/bosh-agent\/platform\/net\/arp\/fakes\"\n\tfakenet \"github.com\/cloudfoundry\/bosh-agent\/platform\/net\/fakes\"\n\tboship \"github.com\/cloudfoundry\/bosh-agent\/platform\/net\/ip\"\n\tfakeip \"github.com\/cloudfoundry\/bosh-agent\/platform\/net\/ip\/fakes\"\n\t\"github.com\/cloudfoundry\/bosh-agent\/platform\/net\/netfakes\"\n\tboshsettings \"github.com\/cloudfoundry\/bosh-agent\/settings\"\n\tboshlog \"github.com\/cloudfoundry\/bosh-utils\/logger\"\n\tfakesys \"github.com\/cloudfoundry\/bosh-utils\/system\/fakes\"\n)\n\nvar _ = Describe(\"UbuntuNetManager (IPv6)\", func() {\n\tvar (\n\t\tfs                            *fakesys.FakeFileSystem\n\t\tcmdRunner                     *fakesys.FakeCmdRunner\n\t\tipResolver                    *fakeip.FakeResolver\n\t\taddressBroadcaster            *fakearp.FakeAddressBroadcaster\n\t\tinterfaceAddrsProvider        *fakeip.FakeInterfaceAddressesProvider\n\t\tkernelIPv6                    *fakenet.FakeKernelIPv6\n\t\tnetManager                    UbuntuNetManager\n\t\tinterfaceConfigurationCreator InterfaceConfigurationCreator\n\t\tfakeMACAddressDetector        *netfakes.FakeMACAddressDetector\n\t)\n\n\tstubInterfaces := func(physicalInterfaces map[string]boshsettings.Network) {\n\t\taddresses := map[string]string{}\n\t\tfor iface, networkSettings := range physicalInterfaces {\n\t\t\taddresses[networkSettings.Mac] = iface\n\t\t}\n\n\t\tfakeMACAddressDetector.DetectMacAddressesReturns(addresses, nil)\n\t}\n\n\tBeforeEach(func() {\n\t\tfs = fakesys.NewFakeFileSystem()\n\t\tcmdRunner = fakesys.NewFakeCmdRunner()\n\t\tipResolver = &fakeip.FakeResolver{}\n\t\tlogger := boshlog.NewLogger(boshlog.LevelNone)\n\t\tfakeMACAddressDetector = &netfakes.FakeMACAddressDetector{}\n\t\tinterfaceConfigurationCreator = NewInterfaceConfigurationCreator(logger)\n\t\taddressBroadcaster = &fakearp.FakeAddressBroadcaster{}\n\t\tinterfaceAddrsProvider = &fakeip.FakeInterfaceAddressesProvider{}\n\t\tinterfaceAddrsValidator := boship.NewInterfaceAddressesValidator(interfaceAddrsProvider)\n\t\tdnsValidator := NewDNSValidator(fs)\n\t\tkernelIPv6 = &fakenet.FakeKernelIPv6{}\n\t\tnetManager = NewUbuntuNetManager(\n\t\t\tfs,\n\t\t\tcmdRunner,\n\t\t\tipResolver,\n\t\t\tfakeMACAddressDetector,\n\t\t\tinterfaceConfigurationCreator,\n\t\t\tinterfaceAddrsValidator,\n\t\t\tdnsValidator,\n\t\t\taddressBroadcaster,\n\t\t\tkernelIPv6,\n\t\t\tlogger,\n\t\t).(UbuntuNetManager)\n\t})\n\n\tscrubMultipleLines := func(in string) string {\n\t\treturn strings.Replace(in, \"\\n\\n\\n\", \"\\n\\n\", -1)\n\t}\n\n\tDescribe(\"SetupNetworking\", func() {\n\t\tBeforeEach(func() {\n\t\t\terr := fs.WriteFileString(\"\/etc\/resolv.conf\", \"nameserver 8.8.8.8\\nnameserver 9.9.9.9\")\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\terr = fs.WriteFileString(\"\/boot\/grub\/grub.conf\", \"\")\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\tinterfaceAddrsProvider.GetInterfaceAddresses = []boship.InterfaceAddress{\n\t\t\t\tboship.NewSimpleInterfaceAddress(\"ethstatic1\", \"2601:646:100:e8e8::103\"),\n\t\t\t\tboship.NewSimpleInterfaceAddress(\"ethstatic2\", \"1.2.3.4\"),\n\t\t\t\tboship.NewSimpleInterfaceAddress(\"ethstatic3\", \"2601:646:100:eeee::10\"),\n\t\t\t}\n\t\t})\n\n\t\tIt(\"enables IPv6 if there are any IPv6 addresses\", func() {\n\t\t\tstatic1Net := boshsettings.Network{\n\t\t\t\tType:    \"manual\",\n\t\t\t\tIP:      \"2601:646:100:e8e8::103\",\n\t\t\t\tNetmask: \"ffff:ffff:ffff:ffff:0000:0000:0000:0000\",\n\t\t\t\tGateway: \"2601:646:100:e8e8::\",\n\t\t\t\tDefault: []string{\"gateway\", \"dns\"},\n\t\t\t\tDNS:     []string{\"8.8.8.8\", \"9.9.9.9\"},\n\t\t\t\tMac:     \"mac1\",\n\t\t\t}\n\n\t\t\tstubInterfaces(map[string]boshsettings.Network{\n\t\t\t\t\"ethstatic1\": static1Net,\n\t\t\t})\n\n\t\t\terr := netManager.SetupNetworking(boshsettings.Networks{\"net1\": static1Net}, nil)\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\tExpect(kernelIPv6.Enabled).To(BeTrue())\n\t\t})\n\n\t\tIt(\"returns error if enabling IPv6 in kernel fails\", func() {\n\t\t\tstatic1Net := boshsettings.Network{\n\t\t\t\tType:    \"manual\",\n\t\t\t\tIP:      \"2601:646:100:e8e8::103\",\n\t\t\t\tNetmask: \"ffff:ffff:ffff:ffff:0000:0000:0000:0000\",\n\t\t\t\tGateway: \"2601:646:100:e8e8::\",\n\t\t\t\tDefault: []string{\"gateway\", \"dns\"},\n\t\t\t\tDNS:     []string{\"8.8.8.8\", \"9.9.9.9\"},\n\t\t\t\tMac:     \"mac1\",\n\t\t\t}\n\n\t\t\tstubInterfaces(map[string]boshsettings.Network{\n\t\t\t\t\"ethstatic1\": static1Net,\n\t\t\t})\n\n\t\t\tkernelIPv6.EnableErr = errors.New(\"fake-err\")\n\n\t\t\terr := netManager.SetupNetworking(boshsettings.Networks{\"net1\": static1Net}, nil)\n\t\t\tExpect(err).To(HaveOccurred())\n\t\t\tExpect(err.Error()).To(ContainSubstring(\"fake-err\"))\n\t\t})\n\n\t\tIt(\"does not enable IPv6 if there aren't any IPv6 addresses\", func() {\n\t\t\tstatic1Net := boshsettings.Network{\n\t\t\t\tType:    \"manual\",\n\t\t\t\tIP:      \"1.2.3.4\",\n\t\t\t\tDefault: nil,\n\t\t\t\tNetmask: \"255.255.255.0\",\n\t\t\t\tGateway: \"3.4.5.6\",\n\t\t\t\tMac:     \"mac2\",\n\t\t\t}\n\n\t\t\tstubInterfaces(map[string]boshsettings.Network{\n\t\t\t\t\"ethstatic2\": static1Net,\n\t\t\t})\n\n\t\t\terr := netManager.SetupNetworking(boshsettings.Networks{\"net1\": static1Net}, nil)\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\tExpect(kernelIPv6.Enabled).To(BeFalse())\n\t\t})\n\n\t\tIt(\"writes \/etc\/network\/interfaces with static inet6 configuration when manual network is used\", func() {\n\t\t\tstatic1Net := boshsettings.Network{\n\t\t\t\tType:    \"manual\",\n\t\t\t\tIP:      \"2601:646:100:e8e8::103\",\n\t\t\t\tNetmask: \"ffff:ffff:ffff:ffff:0000:0000:0000:0000\",\n\t\t\t\tGateway: \"2601:646:100:e8e8::\",\n\t\t\t\tDefault: []string{\"gateway\", \"dns\"},\n\t\t\t\tDNS:     []string{\"8.8.8.8\", \"9.9.9.9\"},\n\t\t\t\tMac:     \"mac1\",\n\t\t\t}\n\t\t\tstatic2Net := boshsettings.Network{\n\t\t\t\tType:    \"manual\",\n\t\t\t\tIP:      \"1.2.3.4\",\n\t\t\t\tDefault: nil,\n\t\t\t\tNetmask: \"255.255.255.0\",\n\t\t\t\tGateway: \"3.4.5.6\",\n\t\t\t\tMac:     \"mac2\",\n\t\t\t}\n\t\t\tstatic3Net := boshsettings.Network{\n\t\t\t\tType:    \"manual\",\n\t\t\t\tIP:      \"2601:646:100:eeee::10\",\n\t\t\t\tNetmask: \"ffff:ffff:ffff:ffff:ffff:0000:0000:0000\",\n\t\t\t\tGateway: \"2601:646:100:eeee::\",\n\t\t\t\tDefault: []string{},\n\t\t\t\tDNS:     []string{\"8.8.8.8\", \"9.9.9.9\"},\n\t\t\t\tMac:     \"mac3\",\n\t\t\t}\n\n\t\t\tstubInterfaces(map[string]boshsettings.Network{\n\t\t\t\t\"ethstatic1\": static1Net,\n\t\t\t\t\"ethstatic2\": static2Net,\n\t\t\t\t\"ethstatic3\": static3Net,\n\t\t\t})\n\n\t\t\terr := netManager.SetupNetworking(boshsettings.Networks{\n\t\t\t\t\"net1\": static1Net,\n\t\t\t\t\"net2\": static2Net,\n\t\t\t\t\"net3\": static3Net,\n\t\t\t}, nil)\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\tnetworkConfig := fs.GetFileTestStat(\"\/etc\/network\/interfaces\")\n\t\t\tExpect(networkConfig).ToNot(BeNil())\n\t\t\tExpect(scrubMultipleLines(networkConfig.StringContents())).To(Equal(`# Generated by bosh-agent\nauto lo\niface lo inet loopback\n\nauto ethstatic1\niface ethstatic1 inet6 static\n    address 2601:646:100:e8e8::103\n    netmask 64\n    gateway 2601:646:100:e8e8::\n\nauto ethstatic2\niface ethstatic2 inet static\n    address 1.2.3.4\n    network 1.2.3.0\n    netmask 255.255.255.0\n\nauto ethstatic3\niface ethstatic3 inet6 static\n    address 2601:646:100:eeee::10\n    netmask 80\n\naccept_ra 1\ndns-nameservers 8.8.8.8 9.9.9.9`))\n\t\t})\n\n\t\tIt(\"configures postup routes for static network\", func() {\n\t\t\tstatic1Net := boshsettings.Network{\n\t\t\t\tType:    \"manual\",\n\t\t\t\tIP:      \"2601:646:100:e8e8::103\",\n\t\t\t\tNetmask: \"ffff:ffff:ffff:ffff:0000:0000:0000:0000\",\n\t\t\t\tGateway: \"2601:646:100:e8e8::\",\n\t\t\t\tDefault: []string{\"gateway\", \"dns\"},\n\t\t\t\tDNS:     []string{\"8.8.8.8\", \"9.9.9.9\"},\n\t\t\t\tMac:     \"mac1\",\n\t\t\t\tRoutes: []boshsettings.Route{\n\t\t\t\t\tboshsettings.Route{\n\t\t\t\t\t\tDestination: \"2001:db8:1234::\",\n\t\t\t\t\t\tGateway:     \"2601:646:100:e8e8::\",\n\t\t\t\t\t\tNetmask:     \"ffff:ffff:ffff:0000:0000:0000:0000:0000\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tstubInterfaces(map[string]boshsettings.Network{\n\t\t\t\t\"ethstatic1\": static1Net,\n\t\t\t})\n\n\t\t\terr := netManager.SetupNetworking(boshsettings.Networks{\n\t\t\t\t\"net1\": static1Net,\n\t\t\t}, nil)\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\tnetworkConfig := fs.GetFileTestStat(\"\/etc\/network\/interfaces\")\n\t\t\tExpect(networkConfig).ToNot(BeNil())\n\t\t\tExpect(scrubMultipleLines(networkConfig.StringContents())).To(Equal(`# Generated by bosh-agent\nauto lo\niface lo inet loopback\n\nauto ethstatic1\niface ethstatic1 inet6 static\n    address 2601:646:100:e8e8::103\n    netmask 64\n    gateway 2601:646:100:e8e8::\n    post-up route -A inet6 add -net 2001:db8:1234:: netmask ffff:ffff:ffff:0000:0000:0000:0000:0000 gw 2601:646:100:e8e8::\n\naccept_ra 1\ndns-nameservers 8.8.8.8 9.9.9.9`))\n\t\t})\n\t})\n})\n<commit_msg>Remove another (last?) mention of grub.conf<commit_after>package net_test\n\nimport (\n\t\"errors\"\n\t\"strings\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\n\t. \"github.com\/cloudfoundry\/bosh-agent\/platform\/net\"\n\tfakearp \"github.com\/cloudfoundry\/bosh-agent\/platform\/net\/arp\/fakes\"\n\tfakenet \"github.com\/cloudfoundry\/bosh-agent\/platform\/net\/fakes\"\n\tboship \"github.com\/cloudfoundry\/bosh-agent\/platform\/net\/ip\"\n\tfakeip \"github.com\/cloudfoundry\/bosh-agent\/platform\/net\/ip\/fakes\"\n\t\"github.com\/cloudfoundry\/bosh-agent\/platform\/net\/netfakes\"\n\tboshsettings \"github.com\/cloudfoundry\/bosh-agent\/settings\"\n\tboshlog \"github.com\/cloudfoundry\/bosh-utils\/logger\"\n\tfakesys \"github.com\/cloudfoundry\/bosh-utils\/system\/fakes\"\n)\n\nvar _ = Describe(\"UbuntuNetManager (IPv6)\", func() {\n\tvar (\n\t\tfs                            *fakesys.FakeFileSystem\n\t\tcmdRunner                     *fakesys.FakeCmdRunner\n\t\tipResolver                    *fakeip.FakeResolver\n\t\taddressBroadcaster            *fakearp.FakeAddressBroadcaster\n\t\tinterfaceAddrsProvider        *fakeip.FakeInterfaceAddressesProvider\n\t\tkernelIPv6                    *fakenet.FakeKernelIPv6\n\t\tnetManager                    UbuntuNetManager\n\t\tinterfaceConfigurationCreator InterfaceConfigurationCreator\n\t\tfakeMACAddressDetector        *netfakes.FakeMACAddressDetector\n\t)\n\n\tstubInterfaces := func(physicalInterfaces map[string]boshsettings.Network) {\n\t\taddresses := map[string]string{}\n\t\tfor iface, networkSettings := range physicalInterfaces {\n\t\t\taddresses[networkSettings.Mac] = iface\n\t\t}\n\n\t\tfakeMACAddressDetector.DetectMacAddressesReturns(addresses, nil)\n\t}\n\n\tBeforeEach(func() {\n\t\tfs = fakesys.NewFakeFileSystem()\n\t\tcmdRunner = fakesys.NewFakeCmdRunner()\n\t\tipResolver = &fakeip.FakeResolver{}\n\t\tlogger := boshlog.NewLogger(boshlog.LevelNone)\n\t\tfakeMACAddressDetector = &netfakes.FakeMACAddressDetector{}\n\t\tinterfaceConfigurationCreator = NewInterfaceConfigurationCreator(logger)\n\t\taddressBroadcaster = &fakearp.FakeAddressBroadcaster{}\n\t\tinterfaceAddrsProvider = &fakeip.FakeInterfaceAddressesProvider{}\n\t\tinterfaceAddrsValidator := boship.NewInterfaceAddressesValidator(interfaceAddrsProvider)\n\t\tdnsValidator := NewDNSValidator(fs)\n\t\tkernelIPv6 = &fakenet.FakeKernelIPv6{}\n\t\tnetManager = NewUbuntuNetManager(\n\t\t\tfs,\n\t\t\tcmdRunner,\n\t\t\tipResolver,\n\t\t\tfakeMACAddressDetector,\n\t\t\tinterfaceConfigurationCreator,\n\t\t\tinterfaceAddrsValidator,\n\t\t\tdnsValidator,\n\t\t\taddressBroadcaster,\n\t\t\tkernelIPv6,\n\t\t\tlogger,\n\t\t).(UbuntuNetManager)\n\t})\n\n\tscrubMultipleLines := func(in string) string {\n\t\treturn strings.Replace(in, \"\\n\\n\\n\", \"\\n\\n\", -1)\n\t}\n\n\tDescribe(\"SetupNetworking\", func() {\n\t\tBeforeEach(func() {\n\t\t\terr := fs.WriteFileString(\"\/etc\/resolv.conf\", \"nameserver 8.8.8.8\\nnameserver 9.9.9.9\")\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\terr = fs.WriteFileString(\"\/boot\/grub\/grub.cnf\", \"\")\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\tinterfaceAddrsProvider.GetInterfaceAddresses = []boship.InterfaceAddress{\n\t\t\t\tboship.NewSimpleInterfaceAddress(\"ethstatic1\", \"2601:646:100:e8e8::103\"),\n\t\t\t\tboship.NewSimpleInterfaceAddress(\"ethstatic2\", \"1.2.3.4\"),\n\t\t\t\tboship.NewSimpleInterfaceAddress(\"ethstatic3\", \"2601:646:100:eeee::10\"),\n\t\t\t}\n\t\t})\n\n\t\tIt(\"enables IPv6 if there are any IPv6 addresses\", func() {\n\t\t\tstatic1Net := boshsettings.Network{\n\t\t\t\tType:    \"manual\",\n\t\t\t\tIP:      \"2601:646:100:e8e8::103\",\n\t\t\t\tNetmask: \"ffff:ffff:ffff:ffff:0000:0000:0000:0000\",\n\t\t\t\tGateway: \"2601:646:100:e8e8::\",\n\t\t\t\tDefault: []string{\"gateway\", \"dns\"},\n\t\t\t\tDNS:     []string{\"8.8.8.8\", \"9.9.9.9\"},\n\t\t\t\tMac:     \"mac1\",\n\t\t\t}\n\n\t\t\tstubInterfaces(map[string]boshsettings.Network{\n\t\t\t\t\"ethstatic1\": static1Net,\n\t\t\t})\n\n\t\t\terr := netManager.SetupNetworking(boshsettings.Networks{\"net1\": static1Net}, nil)\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\tExpect(kernelIPv6.Enabled).To(BeTrue())\n\t\t})\n\n\t\tIt(\"returns error if enabling IPv6 in kernel fails\", func() {\n\t\t\tstatic1Net := boshsettings.Network{\n\t\t\t\tType:    \"manual\",\n\t\t\t\tIP:      \"2601:646:100:e8e8::103\",\n\t\t\t\tNetmask: \"ffff:ffff:ffff:ffff:0000:0000:0000:0000\",\n\t\t\t\tGateway: \"2601:646:100:e8e8::\",\n\t\t\t\tDefault: []string{\"gateway\", \"dns\"},\n\t\t\t\tDNS:     []string{\"8.8.8.8\", \"9.9.9.9\"},\n\t\t\t\tMac:     \"mac1\",\n\t\t\t}\n\n\t\t\tstubInterfaces(map[string]boshsettings.Network{\n\t\t\t\t\"ethstatic1\": static1Net,\n\t\t\t})\n\n\t\t\tkernelIPv6.EnableErr = errors.New(\"fake-err\")\n\n\t\t\terr := netManager.SetupNetworking(boshsettings.Networks{\"net1\": static1Net}, nil)\n\t\t\tExpect(err).To(HaveOccurred())\n\t\t\tExpect(err.Error()).To(ContainSubstring(\"fake-err\"))\n\t\t})\n\n\t\tIt(\"does not enable IPv6 if there aren't any IPv6 addresses\", func() {\n\t\t\tstatic1Net := boshsettings.Network{\n\t\t\t\tType:    \"manual\",\n\t\t\t\tIP:      \"1.2.3.4\",\n\t\t\t\tDefault: nil,\n\t\t\t\tNetmask: \"255.255.255.0\",\n\t\t\t\tGateway: \"3.4.5.6\",\n\t\t\t\tMac:     \"mac2\",\n\t\t\t}\n\n\t\t\tstubInterfaces(map[string]boshsettings.Network{\n\t\t\t\t\"ethstatic2\": static1Net,\n\t\t\t})\n\n\t\t\terr := netManager.SetupNetworking(boshsettings.Networks{\"net1\": static1Net}, nil)\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\tExpect(kernelIPv6.Enabled).To(BeFalse())\n\t\t})\n\n\t\tIt(\"writes \/etc\/network\/interfaces with static inet6 configuration when manual network is used\", func() {\n\t\t\tstatic1Net := boshsettings.Network{\n\t\t\t\tType:    \"manual\",\n\t\t\t\tIP:      \"2601:646:100:e8e8::103\",\n\t\t\t\tNetmask: \"ffff:ffff:ffff:ffff:0000:0000:0000:0000\",\n\t\t\t\tGateway: \"2601:646:100:e8e8::\",\n\t\t\t\tDefault: []string{\"gateway\", \"dns\"},\n\t\t\t\tDNS:     []string{\"8.8.8.8\", \"9.9.9.9\"},\n\t\t\t\tMac:     \"mac1\",\n\t\t\t}\n\t\t\tstatic2Net := boshsettings.Network{\n\t\t\t\tType:    \"manual\",\n\t\t\t\tIP:      \"1.2.3.4\",\n\t\t\t\tDefault: nil,\n\t\t\t\tNetmask: \"255.255.255.0\",\n\t\t\t\tGateway: \"3.4.5.6\",\n\t\t\t\tMac:     \"mac2\",\n\t\t\t}\n\t\t\tstatic3Net := boshsettings.Network{\n\t\t\t\tType:    \"manual\",\n\t\t\t\tIP:      \"2601:646:100:eeee::10\",\n\t\t\t\tNetmask: \"ffff:ffff:ffff:ffff:ffff:0000:0000:0000\",\n\t\t\t\tGateway: \"2601:646:100:eeee::\",\n\t\t\t\tDefault: []string{},\n\t\t\t\tDNS:     []string{\"8.8.8.8\", \"9.9.9.9\"},\n\t\t\t\tMac:     \"mac3\",\n\t\t\t}\n\n\t\t\tstubInterfaces(map[string]boshsettings.Network{\n\t\t\t\t\"ethstatic1\": static1Net,\n\t\t\t\t\"ethstatic2\": static2Net,\n\t\t\t\t\"ethstatic3\": static3Net,\n\t\t\t})\n\n\t\t\terr := netManager.SetupNetworking(boshsettings.Networks{\n\t\t\t\t\"net1\": static1Net,\n\t\t\t\t\"net2\": static2Net,\n\t\t\t\t\"net3\": static3Net,\n\t\t\t}, nil)\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\tnetworkConfig := fs.GetFileTestStat(\"\/etc\/network\/interfaces\")\n\t\t\tExpect(networkConfig).ToNot(BeNil())\n\t\t\tExpect(scrubMultipleLines(networkConfig.StringContents())).To(Equal(`# Generated by bosh-agent\nauto lo\niface lo inet loopback\n\nauto ethstatic1\niface ethstatic1 inet6 static\n    address 2601:646:100:e8e8::103\n    netmask 64\n    gateway 2601:646:100:e8e8::\n\nauto ethstatic2\niface ethstatic2 inet static\n    address 1.2.3.4\n    network 1.2.3.0\n    netmask 255.255.255.0\n\nauto ethstatic3\niface ethstatic3 inet6 static\n    address 2601:646:100:eeee::10\n    netmask 80\n\naccept_ra 1\ndns-nameservers 8.8.8.8 9.9.9.9`))\n\t\t})\n\n\t\tIt(\"configures postup routes for static network\", func() {\n\t\t\tstatic1Net := boshsettings.Network{\n\t\t\t\tType:    \"manual\",\n\t\t\t\tIP:      \"2601:646:100:e8e8::103\",\n\t\t\t\tNetmask: \"ffff:ffff:ffff:ffff:0000:0000:0000:0000\",\n\t\t\t\tGateway: \"2601:646:100:e8e8::\",\n\t\t\t\tDefault: []string{\"gateway\", \"dns\"},\n\t\t\t\tDNS:     []string{\"8.8.8.8\", \"9.9.9.9\"},\n\t\t\t\tMac:     \"mac1\",\n\t\t\t\tRoutes: []boshsettings.Route{\n\t\t\t\t\tboshsettings.Route{\n\t\t\t\t\t\tDestination: \"2001:db8:1234::\",\n\t\t\t\t\t\tGateway:     \"2601:646:100:e8e8::\",\n\t\t\t\t\t\tNetmask:     \"ffff:ffff:ffff:0000:0000:0000:0000:0000\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tstubInterfaces(map[string]boshsettings.Network{\n\t\t\t\t\"ethstatic1\": static1Net,\n\t\t\t})\n\n\t\t\terr := netManager.SetupNetworking(boshsettings.Networks{\n\t\t\t\t\"net1\": static1Net,\n\t\t\t}, nil)\n\t\t\tExpect(err).ToNot(HaveOccurred())\n\n\t\t\tnetworkConfig := fs.GetFileTestStat(\"\/etc\/network\/interfaces\")\n\t\t\tExpect(networkConfig).ToNot(BeNil())\n\t\t\tExpect(scrubMultipleLines(networkConfig.StringContents())).To(Equal(`# Generated by bosh-agent\nauto lo\niface lo inet loopback\n\nauto ethstatic1\niface ethstatic1 inet6 static\n    address 2601:646:100:e8e8::103\n    netmask 64\n    gateway 2601:646:100:e8e8::\n    post-up route -A inet6 add -net 2001:db8:1234:: netmask ffff:ffff:ffff:0000:0000:0000:0000:0000 gw 2601:646:100:e8e8::\n\naccept_ra 1\ndns-nameservers 8.8.8.8 9.9.9.9`))\n\t\t})\n\t})\n})\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"reflect\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/spf13\/cobra\"\n\t\"helm.sh\/helm\/v3\/pkg\/action\"\n\t\"helm.sh\/helm\/v3\/pkg\/chartutil\"\n\t\"helm.sh\/helm\/v3\/pkg\/release\"\n\t\"sigs.k8s.io\/yaml\"\n)\n\nvar editHelp = `\nThis command return the values of given helm release in a text editor, and redploy the chart with the edited values.\n`\n\ntype editCmd struct {\n\trelease                    string\n\tout                        io.Writer\n\tcfg                        *action.Configuration\n\tallValues                  bool\n\teditor                     string\n\ttimeout                    time.Duration\n\twait                       bool\n\trevision                   int\n\tdisableDefaultIntersection bool\n}\n\nfunc newEditCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {\n\n\tedit := &editCmd{\n\t\tout: out}\n\n\tcmd := &cobra.Command{\n\t\tUse:   \"edit [flags] RELEASE\",\n\t\tShort: fmt.Sprintf(\"edit a release\"),\n\t\tLong:  editHelp,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tedit.cfg = cfg\n\t\t\tedit.editor = os.ExpandEnv(edit.editor)\n\t\t\tif len(args) != 1 {\n\t\t\t\treturn fmt.Errorf(\"This command neeeds 1 argument: release name\")\n\t\t\t}\n\t\t\tedit.release = args[0]\n\t\t\treturn edit.run()\n\t\t},\n\t}\n\tf := cmd.Flags()\n\tf.BoolVarP(&edit.allValues, \"all\", \"a\", false, \"edit all (computed) vals\")\n\tf.IntVar(&edit.revision, \"revision\", 0, \"edit the current chart with values from old revision\")\n\tf.DurationVar(&edit.timeout, \"timeout\", 300*time.Second, \"time to wait for any individual Kubernetes operation (like Jobs for hooks)\")\n\tf.BoolVar(&edit.wait, \"wait\", false, \"if set, will wait until all Pods, PVCs, Services, and minimum number of Pods of a Deployment are in a ready state before marking the release as successful. It will wait for as long as --timeout\")\n\tf.StringVarP(&edit.editor, \"editor\", \"e\", \"$EDITOR\", \"name of the editor\")\n\tf.BoolVarP(&edit.disableDefaultIntersection, \"disable-default-intersection\", \"m\", false, \"If set, user supplied values that are the same as default values won't be \\\"removed\\\" from user supplied values (careful using with -a, setting both of this params won't \\\"merge\\\" the values and all values will become user supplied values)\")\n\n\treturn cmd\n}\n\nfunc (e *editCmd) vals(rel *release.Release) (map[string]interface{}, error) {\n\tvalues := action.NewGetValues(e.cfg)\n\tvalues.AllValues = e.allValues\n\tvalues.Version = e.revision\n\treturn values.Run(rel.Name)\n}\n\nfunc (e *editCmd) getDefaultsIntersection(overridesMap map[string]interface{}, defaultMap map[string]interface{}) map[string]interface{} {\n\tnewMap := map[string]interface{}{}\n\tfor key, value := range overridesMap {\n\t\tif _, ok := defaultMap[key]; ok {\n\t\t\tif !reflect.DeepEqual(value, defaultMap[key]) {\n\t\t\t\tinnerMap, ok2 := value.(map[string]interface{})\n\t\t\t\tinnerMapDefault, ok2Default := defaultMap[key].(map[string]interface{})\n\t\t\t\tif ok2 && ok2Default {\n\t\t\t\t\tnewMap[key] = e.getDefaultsIntersection(innerMap, innerMapDefault)\n\t\t\t\t} else {\n\t\t\t\t\tnewMap[key] = value\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tnewMap[key] = value\n\t\t}\n\t}\n\treturn newMap\n}\n\nfunc (e *editCmd) run() error {\n\n\tgetRelease := action.NewGet(e.cfg)\n\t\/\/ getRelease.Version = 0\n\tres, err := getRelease.Run(e.release)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttmpfile, err := ioutil.TempFile(os.TempDir(), fmt.Sprintf(\"helm-edit-%s\", res.Name))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer os.Remove(tmpfile.Name())\n\n\tvalsMap, err := e.vals(res)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvals, _ := yaml.Marshal(valsMap)\n\t_, err = tmpfile.Write(vals)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := tmpfile.Close(); err != nil {\n\t\treturn err\n\t}\n\n\teditor := strings.Split(e.editor, \" \")\n\n\tcmd := exec.Command(editor[0], append(editor[1:], tmpfile.Name())...)\n\tcmd.Stdin = os.Stdin\n\tcmd.Stdout = e.out\n\tcmd.Stderr = e.out\n\tif err := cmd.Run(); err != nil {\n\t\treturn err\n\t}\n\n\tnewValues, err := chartutil.ReadValuesFile(tmpfile.Name())\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar userSuppliedVal map[string]interface{}\n\tif e.disableDefaultIntersection {\n\t\tuserSuppliedVal = newValues.AsMap()\n\t} else {\n\t\tuserSuppliedVal = e.getDefaultsIntersection(newValues.AsMap(), res.Chart.Values)\n\t}\n\n\tnewValuesString, err := newValues.YAML()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif string(vals) != newValuesString {\n\t\tupgrade := action.NewUpgrade(e.cfg)\n\t\tupgrade.Wait = e.wait\n\t\tupgrade.Timeout = e.timeout\n\t\tres, err := upgrade.Run(\n\t\t\tres.Name,\n\t\t\tres.Chart,\n\t\t\tuserSuppliedVal)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfmt.Fprintf(e.out, \"Release %q has been edited. Happy Helming!\\n%s\", e.release, res.Info.Notes)\n\n\t\t\/\/ TODO: print the status like status command does\n\t} else {\n\t\tfmt.Fprintln(e.out, \"Edit cancelled, no changes made!\")\n\t}\n\n\treturn nil\n}\n<commit_msg>don't use Sprintf for Short<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"reflect\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/spf13\/cobra\"\n\t\"helm.sh\/helm\/v3\/pkg\/action\"\n\t\"helm.sh\/helm\/v3\/pkg\/chartutil\"\n\t\"helm.sh\/helm\/v3\/pkg\/release\"\n\t\"sigs.k8s.io\/yaml\"\n)\n\nvar editHelp = `\nThis command return the values of given helm release in a text editor, and redploy the chart with the edited values.\n`\n\ntype editCmd struct {\n\trelease                    string\n\tout                        io.Writer\n\tcfg                        *action.Configuration\n\tallValues                  bool\n\teditor                     string\n\ttimeout                    time.Duration\n\twait                       bool\n\trevision                   int\n\tdisableDefaultIntersection bool\n}\n\nfunc newEditCmd(cfg *action.Configuration, out io.Writer) *cobra.Command {\n\n\tedit := &editCmd{\n\t\tout: out}\n\n\tcmd := &cobra.Command{\n\t\tUse:   \"edit [flags] RELEASE\",\n\t\tShort: \"edit a release\",\n\t\tLong:  editHelp,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tedit.cfg = cfg\n\t\t\tedit.editor = os.ExpandEnv(edit.editor)\n\t\t\tif len(args) != 1 {\n\t\t\t\treturn fmt.Errorf(\"This command neeeds 1 argument: release name\")\n\t\t\t}\n\t\t\tedit.release = args[0]\n\t\t\treturn edit.run()\n\t\t},\n\t}\n\tf := cmd.Flags()\n\tf.BoolVarP(&edit.allValues, \"all\", \"a\", false, \"edit all (computed) vals\")\n\tf.IntVar(&edit.revision, \"revision\", 0, \"edit the current chart with values from old revision\")\n\tf.DurationVar(&edit.timeout, \"timeout\", 300*time.Second, \"time to wait for any individual Kubernetes operation (like Jobs for hooks)\")\n\tf.BoolVar(&edit.wait, \"wait\", false, \"if set, will wait until all Pods, PVCs, Services, and minimum number of Pods of a Deployment are in a ready state before marking the release as successful. It will wait for as long as --timeout\")\n\tf.StringVarP(&edit.editor, \"editor\", \"e\", \"$EDITOR\", \"name of the editor\")\n\tf.BoolVarP(&edit.disableDefaultIntersection, \"disable-default-intersection\", \"m\", false, \"If set, user supplied values that are the same as default values won't be \\\"removed\\\" from user supplied values (careful using with -a, setting both of this params won't \\\"merge\\\" the values and all values will become user supplied values)\")\n\n\treturn cmd\n}\n\nfunc (e *editCmd) vals(rel *release.Release) (map[string]interface{}, error) {\n\tvalues := action.NewGetValues(e.cfg)\n\tvalues.AllValues = e.allValues\n\tvalues.Version = e.revision\n\treturn values.Run(rel.Name)\n}\n\nfunc (e *editCmd) getDefaultsIntersection(overridesMap map[string]interface{}, defaultMap map[string]interface{}) map[string]interface{} {\n\tnewMap := map[string]interface{}{}\n\tfor key, value := range overridesMap {\n\t\tif _, ok := defaultMap[key]; ok {\n\t\t\tif !reflect.DeepEqual(value, defaultMap[key]) {\n\t\t\t\tinnerMap, ok2 := value.(map[string]interface{})\n\t\t\t\tinnerMapDefault, ok2Default := defaultMap[key].(map[string]interface{})\n\t\t\t\tif ok2 && ok2Default {\n\t\t\t\t\tnewMap[key] = e.getDefaultsIntersection(innerMap, innerMapDefault)\n\t\t\t\t} else {\n\t\t\t\t\tnewMap[key] = value\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tnewMap[key] = value\n\t\t}\n\t}\n\treturn newMap\n}\n\nfunc (e *editCmd) run() error {\n\n\tgetRelease := action.NewGet(e.cfg)\n\t\/\/ getRelease.Version = 0\n\tres, err := getRelease.Run(e.release)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttmpfile, err := ioutil.TempFile(os.TempDir(), fmt.Sprintf(\"helm-edit-%s\", res.Name))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer os.Remove(tmpfile.Name())\n\n\tvalsMap, err := e.vals(res)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvals, _ := yaml.Marshal(valsMap)\n\t_, err = tmpfile.Write(vals)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := tmpfile.Close(); err != nil {\n\t\treturn err\n\t}\n\n\teditor := strings.Split(e.editor, \" \")\n\n\tcmd := exec.Command(editor[0], append(editor[1:], tmpfile.Name())...)\n\tcmd.Stdin = os.Stdin\n\tcmd.Stdout = e.out\n\tcmd.Stderr = e.out\n\tif err := cmd.Run(); err != nil {\n\t\treturn err\n\t}\n\n\tnewValues, err := chartutil.ReadValuesFile(tmpfile.Name())\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar userSuppliedVal map[string]interface{}\n\tif e.disableDefaultIntersection {\n\t\tuserSuppliedVal = newValues.AsMap()\n\t} else {\n\t\tuserSuppliedVal = e.getDefaultsIntersection(newValues.AsMap(), res.Chart.Values)\n\t}\n\n\tnewValuesString, err := newValues.YAML()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif string(vals) != newValuesString {\n\t\tupgrade := action.NewUpgrade(e.cfg)\n\t\tupgrade.Wait = e.wait\n\t\tupgrade.Timeout = e.timeout\n\t\tres, err := upgrade.Run(\n\t\t\tres.Name,\n\t\t\tres.Chart,\n\t\t\tuserSuppliedVal)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfmt.Fprintf(e.out, \"Release %q has been edited. Happy Helming!\\n%s\", e.release, res.Info.Notes)\n\n\t\t\/\/ TODO: print the status like status command does\n\t} else {\n\t\tfmt.Fprintln(e.out, \"Edit cancelled, no changes made!\")\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package jettison_test\n\nimport (\n\t\"errors\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t\"github.com\/pivotal-golang\/lager\/lagertest\"\n\n\t\"github.com\/cloudfoundry-incubator\/garden\"\n\tgfakes \"github.com\/cloudfoundry-incubator\/garden\/fakes\"\n\n\t. \"github.com\/concourse\/jettison\"\n)\n\nvar _ = Describe(\"Drainer\", func() {\n\tvar (\n\t\tdrainer *Drainer\n\t\tlogger  *lagertest.TestLogger\n\n\t\tfakeGardenClient *gfakes.FakeClient\n\t)\n\n\tBeforeEach(func() {\n\t\tlogger = lagertest.NewTestLogger(\"drainer\")\n\t\tfakeGardenClient = new(gfakes.FakeClient)\n\t})\n\n\tJustBeforeEach(func() {\n\t\tdrainer = NewDrainer(logger, fakeGardenClient)\n\t})\n\n\tContext(\"when there are containers to clean up\", func() {\n\t\tvar (\n\t\t\tcontainerA *gfakes.FakeContainer\n\t\t\tcontainerB *gfakes.FakeContainer\n\t\t)\n\n\t\tBeforeEach(func() {\n\t\t\tcontainerA = new(gfakes.FakeContainer)\n\t\t\tcontainerA.HandleReturns(\"container-a\")\n\n\t\t\tcontainerB = new(gfakes.FakeContainer)\n\t\t\tcontainerB.HandleReturns(\"container-b\")\n\n\t\t\tfakeGardenClient.ContainersReturns([]garden.Container{containerA, containerB}, nil)\n\t\t})\n\n\t\tIt(\"cleans up ephemeral containers\", func() {\n\t\t\terr := drainer.Drain()\n\t\t\tΩ(err).ShouldNot(HaveOccurred())\n\n\t\t\tBy(\"querying for ephemeral containers\", func() {\n\t\t\t\tΩ(fakeGardenClient.ContainersCallCount()).Should(Equal(1))\n\t\t\t\tqueriedProperties := fakeGardenClient.ContainersArgsForCall(0)\n\n\t\t\t\tΩ(queriedProperties).Should(HaveKeyWithValue(\"concourse:ephemeral\", \"true\"))\n\t\t\t})\n\n\t\t\tBy(\"taking each of the returned containers and destroying it\", func() {\n\t\t\t\tΩ(fakeGardenClient.DestroyCallCount()).Should(Equal(2))\n\n\t\t\t\tdestroyedHandle := fakeGardenClient.DestroyArgsForCall(0)\n\t\t\t\tΩ(destroyedHandle).Should(Equal(\"container-a\"))\n\n\t\t\t\tdestroyedHandle = fakeGardenClient.DestroyArgsForCall(1)\n\t\t\t\tΩ(destroyedHandle).Should(Equal(\"container-b\"))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when one of the containers fails to delete\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\tfakeGardenClient.DestroyStub = func(handle string) error {\n\t\t\t\t\tif handle == containerA.Handle() {\n\t\t\t\t\t\treturn errors.New(\"container a cannot be destroyed at this time\")\n\t\t\t\t\t}\n\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t})\n\n\t\t\tIt(\"keeps on goin' but returns a composite error\", func() {\n\t\t\t\terr := drainer.Drain()\n\t\t\t\tΩ(err).Should(HaveOccurred())\n\n\t\t\t\tΩ(fakeGardenClient.DestroyCallCount()).Should(Equal(2))\n\t\t\t})\n\t\t})\n\t})\n\n\tContext(\"when garden returns an error\", func() {\n\t\tdisaster := errors.New(\"oh no\")\n\n\t\tBeforeEach(func() {\n\t\t\tfakeGardenClient.ContainersReturns(nil, disaster)\n\t\t})\n\n\t\tIt(\"re-returns that error\", func() {\n\t\t\terr := drainer.Drain()\n\t\t\tΩ(err).Should(MatchError(disaster))\n\t\t})\n\t})\n})\n<commit_msg>change omega to Expect (and other similar changes)<commit_after>package jettison_test\n\nimport (\n\t\"errors\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n\t\"github.com\/pivotal-golang\/lager\/lagertest\"\n\n\t\"github.com\/cloudfoundry-incubator\/garden\"\n\tgfakes \"github.com\/cloudfoundry-incubator\/garden\/fakes\"\n\n\t. \"github.com\/concourse\/jettison\"\n)\n\nvar _ = Describe(\"Drainer\", func() {\n\tvar (\n\t\tdrainer *Drainer\n\t\tlogger  *lagertest.TestLogger\n\n\t\tfakeGardenClient *gfakes.FakeClient\n\t)\n\n\tBeforeEach(func() {\n\t\tlogger = lagertest.NewTestLogger(\"drainer\")\n\t\tfakeGardenClient = new(gfakes.FakeClient)\n\t})\n\n\tJustBeforeEach(func() {\n\t\tdrainer = NewDrainer(logger, fakeGardenClient)\n\t})\n\n\tContext(\"when there are containers to clean up\", func() {\n\t\tvar (\n\t\t\tcontainerA *gfakes.FakeContainer\n\t\t\tcontainerB *gfakes.FakeContainer\n\t\t)\n\n\t\tBeforeEach(func() {\n\t\t\tcontainerA = new(gfakes.FakeContainer)\n\t\t\tcontainerA.HandleReturns(\"container-a\")\n\n\t\t\tcontainerB = new(gfakes.FakeContainer)\n\t\t\tcontainerB.HandleReturns(\"container-b\")\n\n\t\t\tfakeGardenClient.ContainersReturns([]garden.Container{containerA, containerB}, nil)\n\t\t})\n\n\t\tIt(\"cleans up ephemeral containers\", func() {\n\t\t\terr := drainer.Drain()\n\t\t\tExpect(err).NotTo(HaveOccurred())\n\n\t\t\tBy(\"querying for ephemeral containers\", func() {\n\t\t\t\tExpect(fakeGardenClient.ContainersCallCount()).To(Equal(1))\n\t\t\t\tqueriedProperties := fakeGardenClient.ContainersArgsForCall(0)\n\n\t\t\t\tExpect(queriedProperties).To(HaveKeyWithValue(\"concourse:ephemeral\", \"true\"))\n\t\t\t})\n\n\t\t\tBy(\"taking each of the returned containers and destroying it\", func() {\n\t\t\t\tExpect(fakeGardenClient.DestroyCallCount()).To(Equal(2))\n\n\t\t\t\tdestroyedHandle := fakeGardenClient.DestroyArgsForCall(0)\n\t\t\t\tExpect(destroyedHandle).To(Equal(\"container-a\"))\n\n\t\t\t\tdestroyedHandle = fakeGardenClient.DestroyArgsForCall(1)\n\t\t\t\tExpect(destroyedHandle).To(Equal(\"container-b\"))\n\t\t\t})\n\t\t})\n\n\t\tContext(\"when one of the containers fails to delete\", func() {\n\t\t\tBeforeEach(func() {\n\t\t\t\tfakeGardenClient.DestroyStub = func(handle string) error {\n\t\t\t\t\tif handle == containerA.Handle() {\n\t\t\t\t\t\treturn errors.New(\"container a cannot be destroyed at this time\")\n\t\t\t\t\t}\n\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t})\n\n\t\t\tIt(\"keeps on goin' but returns a composite error\", func() {\n\t\t\t\terr := drainer.Drain()\n\t\t\t\tExpect(err).To(HaveOccurred())\n\n\t\t\t\tExpect(fakeGardenClient.DestroyCallCount()).To(Equal(2))\n\t\t\t})\n\t\t})\n\t})\n\n\tContext(\"when garden returns an error\", func() {\n\t\tdisaster := errors.New(\"oh no\")\n\n\t\tBeforeEach(func() {\n\t\t\tfakeGardenClient.ContainersReturns(nil, disaster)\n\t\t})\n\n\t\tIt(\"re-returns that error\", func() {\n\t\t\terr := drainer.Drain()\n\t\t\tExpect(err).To(MatchError(disaster))\n\t\t})\n\t})\n})\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright The Helm Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage chartutil\n\nimport (\n\t\"archive\/tar\"\n\t\"compress\/gzip\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"time\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"sigs.k8s.io\/yaml\"\n\n\t\"helm.sh\/helm\/v3\/pkg\/chart\"\n)\n\nvar headerBytes = []byte(\"+aHR0cHM6Ly95b3V0dS5iZS96OVV6MWljandyTQo=\")\n\n\/\/ SaveDir saves a chart as files in a directory.\nfunc SaveDir(c *chart.Chart, dest string) error {\n\t\/\/ Create the chart directory\n\toutdir := filepath.Join(dest, c.Name())\n\tif fi, err := os.Stat(outdir); err == nil && !fi.IsDir() {\n\t\treturn errors.Errorf(\"file %s already exists and is not a directory\", outdir)\n\t}\n\tif err := os.MkdirAll(outdir, 0755); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Save the chart file.\n\tif err := SaveChartfile(filepath.Join(outdir, ChartfileName), c.Metadata); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Save values.yaml\n\tfor _, f := range c.Raw {\n\t\tif f.Name == ValuesfileName {\n\t\t\tvf := filepath.Join(outdir, ValuesfileName)\n\t\t\tif err := writeFile(vf, f.Data); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Save values.schema.json if it exists\n\tif c.Schema != nil {\n\t\tfilename := filepath.Join(outdir, SchemafileName)\n\t\tif err := writeFile(filename, c.Schema); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Save templates and files\n\tfor _, o := range [][]*chart.File{c.Templates, c.Files} {\n\t\tfor _, f := range o {\n\t\t\tn := filepath.Join(outdir, f.Name)\n\t\t\tif err := writeFile(n, f.Data); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Save dependencies\n\tbase := filepath.Join(outdir, ChartsDir)\n\tfor _, dep := range c.Dependencies() {\n\t\t\/\/ Here, we write each dependency as a tar file.\n\t\tif _, err := Save(dep, base); err != nil {\n\t\t\treturn errors.Wrapf(err, \"saving %s\", dep.ChartFullPath())\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ Save creates an archived chart to the given directory.\n\/\/\n\/\/ This takes an existing chart and a destination directory.\n\/\/\n\/\/ If the directory is \/foo, and the chart is named bar, with version 1.0.0, this\n\/\/ will generate \/foo\/bar-1.0.0.tgz.\n\/\/\n\/\/ This returns the absolute path to the chart archive file.\nfunc Save(c *chart.Chart, outDir string) (string, error) {\n\tif err := c.Validate(); err != nil {\n\t\treturn \"\", errors.Wrap(err, \"chart validation\")\n\t}\n\n\tfilename := fmt.Sprintf(\"%s-%s.tgz\", c.Name(), c.Metadata.Version)\n\tfilename = filepath.Join(outDir, filename)\n\tif stat, err := os.Stat(filepath.Dir(filename)); os.IsNotExist(err) {\n\t\tif err := os.MkdirAll(filepath.Dir(filename), 0755); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t} else if !stat.IsDir() {\n\t\treturn \"\", errors.Errorf(\"is not a directory: %s\", filepath.Dir(filename))\n\t}\n\n\tf, err := os.Create(filename)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t\/\/ Wrap in gzip writer\n\tzipper := gzip.NewWriter(f)\n\tzipper.Header.Extra = headerBytes\n\tzipper.Header.Comment = \"Helm\"\n\n\t\/\/ Wrap in tar writer\n\ttwriter := tar.NewWriter(zipper)\n\trollback := false\n\tdefer func() {\n\t\ttwriter.Close()\n\t\tzipper.Close()\n\t\tf.Close()\n\t\tif rollback {\n\t\t\tos.Remove(filename)\n\t\t}\n\t}()\n\n\tif err := writeTarContents(twriter, c, \"\"); err != nil {\n\t\trollback = true\n\t\treturn filename, err\n\t}\n\treturn filename, nil\n}\n\nfunc writeTarContents(out *tar.Writer, c *chart.Chart, prefix string) error {\n\tbase := filepath.Join(prefix, c.Name())\n\n\t\/\/ Pull out the dependencies of a v1 Chart, since there's no way\n\t\/\/ to tell the serializer to skip a field for just this use case\n\tsavedDependencies := c.Metadata.Dependencies\n\tif c.Metadata.APIVersion == chart.APIVersionV1 {\n\t\tc.Metadata.Dependencies = nil\n\t}\n\t\/\/ Save Chart.yaml\n\tcdata, err := yaml.Marshal(c.Metadata)\n\tif c.Metadata.APIVersion == chart.APIVersionV1 {\n\t\tc.Metadata.Dependencies = savedDependencies\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := writeToTar(out, filepath.Join(base, ChartfileName), cdata); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Save Chart.lock\n\t\/\/ TODO: remove the APIVersion check when APIVersionV1 is not used anymore\n\tif c.Metadata.APIVersion == chart.APIVersionV2 {\n\t\tif c.Lock != nil {\n\t\t\tldata, err := yaml.Marshal(c.Lock)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := writeToTar(out, filepath.Join(base, \"Chart.lock\"), ldata); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Save values.yaml\n\tfor _, f := range c.Raw {\n\t\tif f.Name == ValuesfileName {\n\t\t\tif err := writeToTar(out, filepath.Join(base, ValuesfileName), f.Data); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Save values.schema.json if it exists\n\tif c.Schema != nil {\n\t\tif !json.Valid(c.Schema) {\n\t\t\treturn errors.New(\"Invalid JSON in \" + SchemafileName)\n\t\t}\n\t\tif err := writeToTar(out, filepath.Join(base, SchemafileName), c.Schema); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Save templates\n\tfor _, f := range c.Templates {\n\t\tn := filepath.Join(base, f.Name)\n\t\tif err := writeToTar(out, n, f.Data); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Save files\n\tfor _, f := range c.Files {\n\t\tn := filepath.Join(base, f.Name)\n\t\tif err := writeToTar(out, n, f.Data); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Save dependencies\n\tfor _, dep := range c.Dependencies() {\n\t\tif err := writeTarContents(out, dep, filepath.Join(base, ChartsDir)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ writeToTar writes a single file to a tar archive.\nfunc writeToTar(out *tar.Writer, name string, body []byte) error {\n\t\/\/ TODO: Do we need to create dummy parent directory names if none exist?\n\th := &tar.Header{\n\t\tName:    name,\n\t\tMode:    0644,\n\t\tSize:    int64(len(body)),\n\t\tModTime: time.Now(),\n\t}\n\tif err := out.WriteHeader(h); err != nil {\n\t\treturn err\n\t}\n\t_, err := out.Write(body)\n\treturn err\n}\n<commit_msg>Fixing issue where archives created on windows have broken paths<commit_after>\/*\nCopyright The Helm Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage chartutil\n\nimport (\n\t\"archive\/tar\"\n\t\"compress\/gzip\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"time\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"sigs.k8s.io\/yaml\"\n\n\t\"helm.sh\/helm\/v3\/pkg\/chart\"\n)\n\nvar headerBytes = []byte(\"+aHR0cHM6Ly95b3V0dS5iZS96OVV6MWljandyTQo=\")\n\n\/\/ SaveDir saves a chart as files in a directory.\nfunc SaveDir(c *chart.Chart, dest string) error {\n\t\/\/ Create the chart directory\n\toutdir := filepath.Join(dest, c.Name())\n\tif fi, err := os.Stat(outdir); err == nil && !fi.IsDir() {\n\t\treturn errors.Errorf(\"file %s already exists and is not a directory\", outdir)\n\t}\n\tif err := os.MkdirAll(outdir, 0755); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Save the chart file.\n\tif err := SaveChartfile(filepath.Join(outdir, ChartfileName), c.Metadata); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Save values.yaml\n\tfor _, f := range c.Raw {\n\t\tif f.Name == ValuesfileName {\n\t\t\tvf := filepath.Join(outdir, ValuesfileName)\n\t\t\tif err := writeFile(vf, f.Data); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Save values.schema.json if it exists\n\tif c.Schema != nil {\n\t\tfilename := filepath.Join(outdir, SchemafileName)\n\t\tif err := writeFile(filename, c.Schema); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Save templates and files\n\tfor _, o := range [][]*chart.File{c.Templates, c.Files} {\n\t\tfor _, f := range o {\n\t\t\tn := filepath.Join(outdir, f.Name)\n\t\t\tif err := writeFile(n, f.Data); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Save dependencies\n\tbase := filepath.Join(outdir, ChartsDir)\n\tfor _, dep := range c.Dependencies() {\n\t\t\/\/ Here, we write each dependency as a tar file.\n\t\tif _, err := Save(dep, base); err != nil {\n\t\t\treturn errors.Wrapf(err, \"saving %s\", dep.ChartFullPath())\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ Save creates an archived chart to the given directory.\n\/\/\n\/\/ This takes an existing chart and a destination directory.\n\/\/\n\/\/ If the directory is \/foo, and the chart is named bar, with version 1.0.0, this\n\/\/ will generate \/foo\/bar-1.0.0.tgz.\n\/\/\n\/\/ This returns the absolute path to the chart archive file.\nfunc Save(c *chart.Chart, outDir string) (string, error) {\n\tif err := c.Validate(); err != nil {\n\t\treturn \"\", errors.Wrap(err, \"chart validation\")\n\t}\n\n\tfilename := fmt.Sprintf(\"%s-%s.tgz\", c.Name(), c.Metadata.Version)\n\tfilename = filepath.Join(outDir, filename)\n\tif stat, err := os.Stat(filepath.Dir(filename)); os.IsNotExist(err) {\n\t\tif err := os.MkdirAll(filepath.Dir(filename), 0755); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t} else if !stat.IsDir() {\n\t\treturn \"\", errors.Errorf(\"is not a directory: %s\", filepath.Dir(filename))\n\t}\n\n\tf, err := os.Create(filename)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t\/\/ Wrap in gzip writer\n\tzipper := gzip.NewWriter(f)\n\tzipper.Header.Extra = headerBytes\n\tzipper.Header.Comment = \"Helm\"\n\n\t\/\/ Wrap in tar writer\n\ttwriter := tar.NewWriter(zipper)\n\trollback := false\n\tdefer func() {\n\t\ttwriter.Close()\n\t\tzipper.Close()\n\t\tf.Close()\n\t\tif rollback {\n\t\t\tos.Remove(filename)\n\t\t}\n\t}()\n\n\tif err := writeTarContents(twriter, c, \"\"); err != nil {\n\t\trollback = true\n\t\treturn filename, err\n\t}\n\treturn filename, nil\n}\n\nfunc writeTarContents(out *tar.Writer, c *chart.Chart, prefix string) error {\n\tbase := filepath.Join(prefix, c.Name())\n\n\t\/\/ Pull out the dependencies of a v1 Chart, since there's no way\n\t\/\/ to tell the serializer to skip a field for just this use case\n\tsavedDependencies := c.Metadata.Dependencies\n\tif c.Metadata.APIVersion == chart.APIVersionV1 {\n\t\tc.Metadata.Dependencies = nil\n\t}\n\t\/\/ Save Chart.yaml\n\tcdata, err := yaml.Marshal(c.Metadata)\n\tif c.Metadata.APIVersion == chart.APIVersionV1 {\n\t\tc.Metadata.Dependencies = savedDependencies\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := writeToTar(out, filepath.Join(base, ChartfileName), cdata); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Save Chart.lock\n\t\/\/ TODO: remove the APIVersion check when APIVersionV1 is not used anymore\n\tif c.Metadata.APIVersion == chart.APIVersionV2 {\n\t\tif c.Lock != nil {\n\t\t\tldata, err := yaml.Marshal(c.Lock)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := writeToTar(out, filepath.Join(base, \"Chart.lock\"), ldata); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Save values.yaml\n\tfor _, f := range c.Raw {\n\t\tif f.Name == ValuesfileName {\n\t\t\tif err := writeToTar(out, filepath.Join(base, ValuesfileName), f.Data); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Save values.schema.json if it exists\n\tif c.Schema != nil {\n\t\tif !json.Valid(c.Schema) {\n\t\t\treturn errors.New(\"Invalid JSON in \" + SchemafileName)\n\t\t}\n\t\tif err := writeToTar(out, filepath.Join(base, SchemafileName), c.Schema); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Save templates\n\tfor _, f := range c.Templates {\n\t\tn := filepath.Join(base, f.Name)\n\t\tif err := writeToTar(out, n, f.Data); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Save files\n\tfor _, f := range c.Files {\n\t\tn := filepath.Join(base, f.Name)\n\t\tif err := writeToTar(out, n, f.Data); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Save dependencies\n\tfor _, dep := range c.Dependencies() {\n\t\tif err := writeTarContents(out, dep, filepath.Join(base, ChartsDir)); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ writeToTar writes a single file to a tar archive.\nfunc writeToTar(out *tar.Writer, name string, body []byte) error {\n\t\/\/ TODO: Do we need to create dummy parent directory names if none exist?\n\th := &tar.Header{\n\t\tName:    filepath.ToSlash(name),\n\t\tMode:    0644,\n\t\tSize:    int64(len(body)),\n\t\tModTime: time.Now(),\n\t}\n\tif err := out.WriteHeader(h); err != nil {\n\t\treturn err\n\t}\n\t_, err := out.Write(body)\n\treturn err\n}\n<|endoftext|>"}
{"text":"<commit_before>package types\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/mitsuse\/matrix-go\/mutable\/dense\"\n)\n\nfunc TestIsZerosMutableDense(t *testing.T) {\n\tm, _ := dense.New(4, 3)(\n\t\t0, 0, 0,\n\t\t0, 0, 0,\n\t\t0, 0, 0,\n\t\t0, 0, 0,\n\t)\n\n\tif isZeros := IsZeros(m); !isZeros {\n\t\tt.Error(\"This matrix should be zeros.\")\n\t\tt.Fatalf(\"# matrix = %+v\", m)\n\t}\n}\n\nfunc TestIsNotZerosMutableDense(t *testing.T) {\n\tm, _ := dense.New(4, 3)(\n\t\t0, 1, 2,\n\t\t4, 5, 0,\n\t\t2, 3, 4,\n\t\t0, 1, 2,\n\t)\n\n\tif isZeros := IsZeros(m); isZeros {\n\t\tt.Error(\"This matrix should not be zeros.\")\n\t\tt.Fatalf(\"# matrix = %+v\", m)\n\t}\n}\n\nfunc TestIsSquareMutableDense(t *testing.T) {\n\tm, _ := dense.New(4, 4)(\n\t\t0, 1, 2, 3,\n\t\t4, 5, 0, 1,\n\t\t2, 3, 4, 5,\n\t\t0, 1, 2, 3,\n\t)\n\n\tif isSquare := IsSquare(m); !isSquare {\n\t\tt.Error(\"This matrix should be square.\")\n\t\tt.Fatalf(\"# matrix = %+v\", m)\n\t}\n}\n\nfunc TestIsNotSquareMutableDense(t *testing.T) {\n\tm, _ := dense.New(4, 3)(\n\t\t0, 1, 2,\n\t\t4, 5, 0,\n\t\t2, 3, 4,\n\t\t0, 1, 2,\n\t)\n\n\tif isSquare := IsSquare(m); isSquare {\n\t\tt.Error(\"This matrix should not be square.\")\n\t\tt.Fatalf(\"# matrix = %+v\", m)\n\t}\n}\n\nfunc TestIsDiagonalMutableDense(t *testing.T) {\n\tm, _ := dense.New(4, 4)(\n\t\t2, 0, 0, 0,\n\t\t0, 4, 0, 0,\n\t\t0, 0, 1, 0,\n\t\t0, 0, 0, 0,\n\t)\n\n\tif isDiagonal := IsDiagonal(m); !isDiagonal {\n\t\tt.Error(\"This matrix should be diagonal.\")\n\t\tt.Fatalf(\"# matrix = %+v\", m)\n\t}\n}\n\nfunc TestIsNotDiagonalMutableDense(t *testing.T) {\n\tm, _ := dense.New(4, 4)(\n\t\t0, 1, 1, 1,\n\t\t1, 0, 1, 1,\n\t\t1, 1, 0, 1,\n\t\t1, 1, 1, 0,\n\t)\n\n\tif isDiagonal := IsDiagonal(m); isDiagonal {\n\t\tt.Error(\"This matrix should not be diagonal.\")\n\t\tt.Fatalf(\"# matrix = %+v\", m)\n\t}\n}\n\nfunc TestIsNotDiagonalNonSquareMutableDense(t *testing.T) {\n\tm, _ := dense.New(4, 3)(\n\t\t2, 0, 0,\n\t\t0, 4, 0,\n\t\t0, 0, 1,\n\t\t0, 0, 0,\n\t)\n\n\tif isDiagonal := IsDiagonal(m); isDiagonal {\n\t\tt.Error(\"This matrix should not be diagonal.\")\n\t\tt.Fatalf(\"# matrix = %+v\", m)\n\t}\n}\n\nfunc TestIsIdentityMutableDense(t *testing.T) {\n\tm, _ := dense.New(4, 4)(\n\t\t1, 0, 0, 0,\n\t\t0, 1, 0, 0,\n\t\t0, 0, 1, 0,\n\t\t0, 0, 0, 1,\n\t)\n\n\tif isIdentity := IsIdentity(m); !isIdentity {\n\t\tt.Error(\"This matrix should be identity.\")\n\t\tt.Fatalf(\"# matrix = %+v\", m)\n\t}\n}\n\nfunc TestIsNotIdentityMutableDense(t *testing.T) {\n\tm, _ := dense.New(4, 4)(\n\t\t2, 0, 0, 0,\n\t\t0, 1, 0, 0,\n\t\t0, 0, 1, 0,\n\t\t0, 0, 0, 1,\n\t)\n\n\tif isIdentity := IsIdentity(m); isIdentity {\n\t\tt.Error(\"This matrix should not be identity.\")\n\t\tt.Fatalf(\"# matrix = %+v\", m)\n\t}\n}\n\nfunc TestIsNotIdentityNonSquareMutableDense(t *testing.T) {\n\tm, _ := dense.New(4, 3)(\n\t\t1, 0, 0,\n\t\t0, 1, 0,\n\t\t0, 0, 1,\n\t\t0, 0, 0,\n\t)\n\n\tif isIdentity := IsIdentity(m); isIdentity {\n\t\tt.Error(\"This matrix should not be identity.\")\n\t\tt.Fatalf(\"# matrix = %+v\", m)\n\t}\n}\n\nfunc TestIsScalarMutableDense(t *testing.T) {\n\tm, _ := dense.New(4, 4)(\n\t\t7, 0, 0, 0,\n\t\t0, 7, 0, 0,\n\t\t0, 0, 7, 0,\n\t\t0, 0, 0, 7,\n\t)\n\n\tif isScalar := IsScalar(m); !isScalar {\n\t\tt.Error(\"This matrix should be scalar.\")\n\t\tt.Fatalf(\"# matrix = %+v\", m)\n\t}\n}\n\nfunc TestIsNotScalarMutableDense(t *testing.T) {\n\tm, _ := dense.New(4, 4)(\n\t\t7, 0, 0, 0,\n\t\t0, 7, 0, 0,\n\t\t0, 0, 7, 0,\n\t\t0, 0, 0, 6,\n\t)\n\n\tif isScalar := IsScalar(m); isScalar {\n\t\tt.Error(\"This matrix should not be scalar.\")\n\t\tt.Fatalf(\"# matrix = %+v\", m)\n\t}\n}\n\nfunc TestIsNotScalarNonSquareMutableDense(t *testing.T) {\n\tm, _ := dense.New(4, 3)(\n\t\t7, 0, 0,\n\t\t0, 7, 0,\n\t\t0, 0, 7,\n\t\t0, 0, 0,\n\t)\n\n\tif isScalar := IsScalar(m); isScalar {\n\t\tt.Error(\"This matrix should not be scalar.\")\n\t\tt.Fatalf(\"# matrix = %+v\", m)\n\t}\n}\n<commit_msg>Panic when the initialization of a dense matrix failed.<commit_after>package types\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/mitsuse\/matrix-go\/mutable\/dense\"\n)\n\nfunc TestIsZerosMutableDense(t *testing.T) {\n\tm := dense.New(4, 3)(\n\t\t0, 0, 0,\n\t\t0, 0, 0,\n\t\t0, 0, 0,\n\t\t0, 0, 0,\n\t)\n\n\tif isZeros := IsZeros(m); !isZeros {\n\t\tt.Error(\"This matrix should be zeros.\")\n\t\tt.Fatalf(\"# matrix = %+v\", m)\n\t}\n}\n\nfunc TestIsNotZerosMutableDense(t *testing.T) {\n\tm := dense.New(4, 3)(\n\t\t0, 1, 2,\n\t\t4, 5, 0,\n\t\t2, 3, 4,\n\t\t0, 1, 2,\n\t)\n\n\tif isZeros := IsZeros(m); isZeros {\n\t\tt.Error(\"This matrix should not be zeros.\")\n\t\tt.Fatalf(\"# matrix = %+v\", m)\n\t}\n}\n\nfunc TestIsSquareMutableDense(t *testing.T) {\n\tm := dense.New(4, 4)(\n\t\t0, 1, 2, 3,\n\t\t4, 5, 0, 1,\n\t\t2, 3, 4, 5,\n\t\t0, 1, 2, 3,\n\t)\n\n\tif isSquare := IsSquare(m); !isSquare {\n\t\tt.Error(\"This matrix should be square.\")\n\t\tt.Fatalf(\"# matrix = %+v\", m)\n\t}\n}\n\nfunc TestIsNotSquareMutableDense(t *testing.T) {\n\tm := dense.New(4, 3)(\n\t\t0, 1, 2,\n\t\t4, 5, 0,\n\t\t2, 3, 4,\n\t\t0, 1, 2,\n\t)\n\n\tif isSquare := IsSquare(m); isSquare {\n\t\tt.Error(\"This matrix should not be square.\")\n\t\tt.Fatalf(\"# matrix = %+v\", m)\n\t}\n}\n\nfunc TestIsDiagonalMutableDense(t *testing.T) {\n\tm := dense.New(4, 4)(\n\t\t2, 0, 0, 0,\n\t\t0, 4, 0, 0,\n\t\t0, 0, 1, 0,\n\t\t0, 0, 0, 0,\n\t)\n\n\tif isDiagonal := IsDiagonal(m); !isDiagonal {\n\t\tt.Error(\"This matrix should be diagonal.\")\n\t\tt.Fatalf(\"# matrix = %+v\", m)\n\t}\n}\n\nfunc TestIsNotDiagonalMutableDense(t *testing.T) {\n\tm := dense.New(4, 4)(\n\t\t0, 1, 1, 1,\n\t\t1, 0, 1, 1,\n\t\t1, 1, 0, 1,\n\t\t1, 1, 1, 0,\n\t)\n\n\tif isDiagonal := IsDiagonal(m); isDiagonal {\n\t\tt.Error(\"This matrix should not be diagonal.\")\n\t\tt.Fatalf(\"# matrix = %+v\", m)\n\t}\n}\n\nfunc TestIsNotDiagonalNonSquareMutableDense(t *testing.T) {\n\tm := dense.New(4, 3)(\n\t\t2, 0, 0,\n\t\t0, 4, 0,\n\t\t0, 0, 1,\n\t\t0, 0, 0,\n\t)\n\n\tif isDiagonal := IsDiagonal(m); isDiagonal {\n\t\tt.Error(\"This matrix should not be diagonal.\")\n\t\tt.Fatalf(\"# matrix = %+v\", m)\n\t}\n}\n\nfunc TestIsIdentityMutableDense(t *testing.T) {\n\tm := dense.New(4, 4)(\n\t\t1, 0, 0, 0,\n\t\t0, 1, 0, 0,\n\t\t0, 0, 1, 0,\n\t\t0, 0, 0, 1,\n\t)\n\n\tif isIdentity := IsIdentity(m); !isIdentity {\n\t\tt.Error(\"This matrix should be identity.\")\n\t\tt.Fatalf(\"# matrix = %+v\", m)\n\t}\n}\n\nfunc TestIsNotIdentityMutableDense(t *testing.T) {\n\tm := dense.New(4, 4)(\n\t\t2, 0, 0, 0,\n\t\t0, 1, 0, 0,\n\t\t0, 0, 1, 0,\n\t\t0, 0, 0, 1,\n\t)\n\n\tif isIdentity := IsIdentity(m); isIdentity {\n\t\tt.Error(\"This matrix should not be identity.\")\n\t\tt.Fatalf(\"# matrix = %+v\", m)\n\t}\n}\n\nfunc TestIsNotIdentityNonSquareMutableDense(t *testing.T) {\n\tm := dense.New(4, 3)(\n\t\t1, 0, 0,\n\t\t0, 1, 0,\n\t\t0, 0, 1,\n\t\t0, 0, 0,\n\t)\n\n\tif isIdentity := IsIdentity(m); isIdentity {\n\t\tt.Error(\"This matrix should not be identity.\")\n\t\tt.Fatalf(\"# matrix = %+v\", m)\n\t}\n}\n\nfunc TestIsScalarMutableDense(t *testing.T) {\n\tm := dense.New(4, 4)(\n\t\t7, 0, 0, 0,\n\t\t0, 7, 0, 0,\n\t\t0, 0, 7, 0,\n\t\t0, 0, 0, 7,\n\t)\n\n\tif isScalar := IsScalar(m); !isScalar {\n\t\tt.Error(\"This matrix should be scalar.\")\n\t\tt.Fatalf(\"# matrix = %+v\", m)\n\t}\n}\n\nfunc TestIsNotScalarMutableDense(t *testing.T) {\n\tm := dense.New(4, 4)(\n\t\t7, 0, 0, 0,\n\t\t0, 7, 0, 0,\n\t\t0, 0, 7, 0,\n\t\t0, 0, 0, 6,\n\t)\n\n\tif isScalar := IsScalar(m); isScalar {\n\t\tt.Error(\"This matrix should not be scalar.\")\n\t\tt.Fatalf(\"# matrix = %+v\", m)\n\t}\n}\n\nfunc TestIsNotScalarNonSquareMutableDense(t *testing.T) {\n\tm := dense.New(4, 3)(\n\t\t7, 0, 0,\n\t\t0, 7, 0,\n\t\t0, 0, 7,\n\t\t0, 0, 0,\n\t)\n\n\tif isScalar := IsScalar(m); isScalar {\n\t\tt.Error(\"This matrix should not be scalar.\")\n\t\tt.Fatalf(\"# matrix = %+v\", m)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2019 The Vitess Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage tabletserver\n\nimport (\n\t\"fmt\"\n\t\"html\/template\"\n\t\"sort\"\n\t\"sync\"\n\t\"time\"\n\n\t\"golang.org\/x\/net\/context\"\n\t\"vitess.io\/vitess\/go\/vt\/callinfo\"\n)\n\n\/\/ QueryDetail is a simple wrapper for Query, Context and a killable conn.\ntype QueryDetail struct {\n\tctx    context.Context\n\tconn   killable\n\tconnID int64\n\tstart  time.Time\n}\n\ntype killable interface {\n\tCurrent() string\n\tID() int64\n\tKill(message string, elapsed time.Duration) error\n}\n\n\/\/ NewQueryDetail creates a new QueryDetail\nfunc NewQueryDetail(ctx context.Context, conn killable) *QueryDetail {\n\treturn &QueryDetail{ctx: ctx, conn: conn, connID: conn.ID(), start: time.Now()}\n}\n\n\/\/ QueryList holds a thread safe list of QueryDetails\ntype QueryList struct {\n\tmu           sync.Mutex\n\tqueryDetails map[int64]*QueryDetail\n}\n\n\/\/ NewQueryList creates a new QueryList\nfunc NewQueryList() *QueryList {\n\treturn &QueryList{queryDetails: make(map[int64]*QueryDetail)}\n}\n\n\/\/ Add adds a QueryDetail to QueryList\nfunc (ql *QueryList) Add(qd *QueryDetail) {\n\tql.mu.Lock()\n\tdefer ql.mu.Unlock()\n\tql.queryDetails[qd.connID] = qd\n}\n\n\/\/ Remove removes a QueryDetail from QueryList\nfunc (ql *QueryList) Remove(qd *QueryDetail) {\n\tql.mu.Lock()\n\tdefer ql.mu.Unlock()\n\tdelete(ql.queryDetails, qd.connID)\n}\n\n\/\/ Terminate updates the query status and kills the connection\nfunc (ql *QueryList) Terminate(connID int64) error {\n\tql.mu.Lock()\n\tdefer ql.mu.Unlock()\n\tqd := ql.queryDetails[connID]\n\tif qd == nil {\n\t\treturn fmt.Errorf(\"query %v not found; %+v\", connID, ql)\n\t}\n\tqd.conn.Kill(\"QueryList.Terminate()\", time.Since(qd.start))\n\treturn nil\n}\n\n\/\/ TerminateAll terminates all queries and kills the MySQL connections\nfunc (ql *QueryList) TerminateAll() {\n\tql.mu.Lock()\n\tdefer ql.mu.Unlock()\n\tfor _, qd := range ql.queryDetails {\n\t\tqd.conn.Kill(\"QueryList.TerminateAll()\", time.Since(qd.start))\n\t}\n}\n\n\/\/ QueryDetailzRow is used for rendering QueryDetail in a template\ntype QueryDetailzRow struct {\n\tQuery             string\n\tContextHTML       template.HTML\n\tStart             time.Time\n\tDuration          time.Duration\n\tConnID            int64\n\tState             string\n\tShowTerminateLink bool\n}\n\ntype byStartTime []QueryDetailzRow\n\nfunc (a byStartTime) Len() int           { return len(a) }\nfunc (a byStartTime) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }\nfunc (a byStartTime) Less(i, j int) bool { return a[i].Start.Before(a[j].Start) }\n\n\/\/ GetQueryzRows returns a list of QueryDetailzRow sorted by start time\nfunc (ql *QueryList) GetQueryzRows() []QueryDetailzRow {\n\tql.mu.Lock()\n\trows := []QueryDetailzRow{}\n\tfor _, qd := range ql.queryDetails {\n\t\trow := QueryDetailzRow{\n\t\t\tQuery:       qd.conn.Current(),\n\t\t\tContextHTML: callinfo.HTMLFromContext(qd.ctx),\n\t\t\tStart:       qd.start,\n\t\t\tDuration:    time.Since(qd.start),\n\t\t\tConnID:      qd.connID,\n\t\t}\n\t\trows = append(rows, row)\n\t}\n\tql.mu.Unlock()\n\tsort.Sort(byStartTime(rows))\n\treturn rows\n}\n<commit_msg>vttablet: query redaction support<commit_after>\/*\nCopyright 2019 The Vitess Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage tabletserver\n\nimport (\n\t\"fmt\"\n\t\"html\/template\"\n\t\"sort\"\n\t\"sync\"\n\t\"time\"\n\n\t\"golang.org\/x\/net\/context\"\n\t\"vitess.io\/vitess\/go\/streamlog\"\n\t\"vitess.io\/vitess\/go\/vt\/callinfo\"\n\t\"vitess.io\/vitess\/go\/vt\/sqlparser\"\n)\n\n\/\/ QueryDetail is a simple wrapper for Query, Context and a killable conn.\ntype QueryDetail struct {\n\tctx    context.Context\n\tconn   killable\n\tconnID int64\n\tstart  time.Time\n}\n\ntype killable interface {\n\tCurrent() string\n\tID() int64\n\tKill(message string, elapsed time.Duration) error\n}\n\n\/\/ NewQueryDetail creates a new QueryDetail\nfunc NewQueryDetail(ctx context.Context, conn killable) *QueryDetail {\n\treturn &QueryDetail{ctx: ctx, conn: conn, connID: conn.ID(), start: time.Now()}\n}\n\n\/\/ QueryList holds a thread safe list of QueryDetails\ntype QueryList struct {\n\tmu           sync.Mutex\n\tqueryDetails map[int64]*QueryDetail\n}\n\n\/\/ NewQueryList creates a new QueryList\nfunc NewQueryList() *QueryList {\n\treturn &QueryList{queryDetails: make(map[int64]*QueryDetail)}\n}\n\n\/\/ Add adds a QueryDetail to QueryList\nfunc (ql *QueryList) Add(qd *QueryDetail) {\n\tql.mu.Lock()\n\tdefer ql.mu.Unlock()\n\tql.queryDetails[qd.connID] = qd\n}\n\n\/\/ Remove removes a QueryDetail from QueryList\nfunc (ql *QueryList) Remove(qd *QueryDetail) {\n\tql.mu.Lock()\n\tdefer ql.mu.Unlock()\n\tdelete(ql.queryDetails, qd.connID)\n}\n\n\/\/ Terminate updates the query status and kills the connection\nfunc (ql *QueryList) Terminate(connID int64) error {\n\tql.mu.Lock()\n\tdefer ql.mu.Unlock()\n\tqd := ql.queryDetails[connID]\n\tif qd == nil {\n\t\treturn fmt.Errorf(\"query %v not found; %+v\", connID, ql)\n\t}\n\tqd.conn.Kill(\"QueryList.Terminate()\", time.Since(qd.start))\n\treturn nil\n}\n\n\/\/ TerminateAll terminates all queries and kills the MySQL connections\nfunc (ql *QueryList) TerminateAll() {\n\tql.mu.Lock()\n\tdefer ql.mu.Unlock()\n\tfor _, qd := range ql.queryDetails {\n\t\tqd.conn.Kill(\"QueryList.TerminateAll()\", time.Since(qd.start))\n\t}\n}\n\n\/\/ QueryDetailzRow is used for rendering QueryDetail in a template\ntype QueryDetailzRow struct {\n\tQuery             string\n\tContextHTML       template.HTML\n\tStart             time.Time\n\tDuration          time.Duration\n\tConnID            int64\n\tState             string\n\tShowTerminateLink bool\n}\n\ntype byStartTime []QueryDetailzRow\n\nfunc (a byStartTime) Len() int           { return len(a) }\nfunc (a byStartTime) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }\nfunc (a byStartTime) Less(i, j int) bool { return a[i].Start.Before(a[j].Start) }\n\n\/\/ GetQueryzRows returns a list of QueryDetailzRow sorted by start time\nfunc (ql *QueryList) GetQueryzRows() []QueryDetailzRow {\n\tql.mu.Lock()\n\trows := []QueryDetailzRow{}\n\tfor _, qd := range ql.queryDetails {\n\t\tquery := qd.conn.Current()\n\t\tif *streamlog.RedactDebugUIQueries {\n\t\t\tquery, _ = sqlparser.RedactSQLQuery(query)\n\t\t}\n\t\trow := QueryDetailzRow{\n\t\t\tQuery:       query,\n\t\t\tContextHTML: callinfo.HTMLFromContext(qd.ctx),\n\t\t\tStart:       qd.start,\n\t\t\tDuration:    time.Since(qd.start),\n\t\t\tConnID:      qd.connID,\n\t\t}\n\t\trows = append(rows, row)\n\t}\n\tql.mu.Unlock()\n\tsort.Sort(byStartTime(rows))\n\treturn rows\n}\n<|endoftext|>"}
{"text":"<commit_before>package api\n\nimport (\n\t\"encoding\/json\"\n\t\"net\/http\"\n\n\t\"github.com\/netlify\/gotrue\/models\"\n)\n\n\/\/ adminUserParams are used to handle admin requests that relate to user accounts\n\/\/ The User field is used for sub-user authentication and the others are used in the Update\/Create endpoints\n\/\/\n\/\/ To create a new user the request would look like:\n\/\/     {\"email\": \"email@provider.com\", \"password\": \"password\"}\n\/\/\n\/\/ And to authenticate as another user as an administrator you would send:\n\/\/     {\"user\": {\"email\": \"email@provider.com\", \"aud\": \"myaudience\"}}\ntype adminTargetUser struct {\n\tAud   string `json:\"aud\"`\n\tEmail string `json:\"email\"`\n\tID    string `json:\"id\"`\n}\n\ntype adminUserParams struct {\n\tRole     string                 `json:\"role\"`\n\tEmail    string                 `json:\"email\"`\n\tPassword string                 `json:\"password\"`\n\tConfirm  bool                   `json:\"confirm\"`\n\tData     map[string]interface{} `json:\"data\"`\n\tUser     adminTargetUser        `json:\"user\"`\n}\n\nfunc (api *API) getAdminParams(r *http.Request) (*adminUserParams, error) {\n\tparams := adminUserParams{}\n\terr := json.NewDecoder(r.Body).Decode(&params)\n\tif err != nil {\n\t\treturn nil, badRequestError(\"Could not decode admin user params: %v\", err)\n\t}\n\treturn &params, nil\n}\n\n\/\/ Returns the the target user\nfunc (api *API) getAdminTargetUser(instanceID string, params *adminUserParams) (*models.User, error) {\n\tuser, err := api.db.FindUserByEmailAndAudience(instanceID, params.User.Email, params.User.Aud)\n\tif err != nil {\n\t\tif models.IsNotFoundError(err) {\n\t\t\tif user, err = api.db.FindUserByID(params.User.ID); err != nil {\n\t\t\t\tif models.IsNotFoundError(err) {\n\t\t\t\t\treturn nil, badRequestError(\"Unable to find user by email: %s and id: %s in audience: %s\", params.User.Email, params.User.ID, params.User.Aud)\n\t\t\t\t}\n\t\t\t\treturn nil, internalServerError(\"Database error finding user\").WithInternalError(err)\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil, internalServerError(\"Database error finding user\").WithInternalError(err)\n\t\t}\n\t}\n\n\treturn user, nil\n}\n\n\/\/ adminUsers responds with a list of all users in a given audience\nfunc (api *API) adminUsers(w http.ResponseWriter, r *http.Request) error {\n\tctx := r.Context()\n\tinstanceID := getInstanceID(ctx)\n\taud := api.requestAud(ctx, r)\n\tusers, err := api.db.FindUsersInAudience(instanceID, aud)\n\tif err != nil {\n\t\treturn internalServerError(\"Database error finding users\").WithInternalError(err)\n\t}\n\n\treturn sendJSON(w, http.StatusOK, map[string]interface{}{\n\t\t\"users\": users,\n\t\t\"aud\":   aud,\n\t})\n}\n\n\/\/ adminUserGet returns information about a single user\nfunc (api *API) adminUserGet(w http.ResponseWriter, r *http.Request) error {\n\tinstanceID := getInstanceID(r.Context())\n\tparams := &adminUserParams{\n\t\tUser: adminTargetUser{\n\t\t\tID:    r.FormValue(\"id\"),\n\t\t\tEmail: r.FormValue(\"email\"),\n\t\t\tAud:   r.FormValue(\"aud\"),\n\t\t},\n\t}\n\tuser, err := api.getAdminTargetUser(instanceID, params)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn sendJSON(w, http.StatusOK, user)\n}\n\n\/\/ adminUserUpdate updates a single user object\nfunc (api *API) adminUserUpdate(w http.ResponseWriter, r *http.Request) error {\n\tinstanceID := getInstanceID(r.Context())\n\tparams, err := api.getAdminParams(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\tuser, err := api.getAdminTargetUser(instanceID, params)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif params.Role != \"\" {\n\t\tuser.SetRole(params.Role)\n\t}\n\n\tif params.Confirm {\n\t\tuser.Confirm()\n\t}\n\n\tif params.Password != \"\" {\n\t\tuser.EncryptPassword(params.Password)\n\t}\n\n\tif params.Email != \"\" {\n\t\tuser.Email = params.Email\n\t}\n\n\tif err := api.db.UpdateUser(user); err != nil {\n\t\treturn internalServerError(\"Error updating user\").WithInternalError(err)\n\t}\n\n\treturn sendJSON(w, http.StatusOK, user)\n}\n\n\/\/ adminUserCreate creates a new user based on the provided data\nfunc (api *API) adminUserCreate(w http.ResponseWriter, r *http.Request) error {\n\tctx := r.Context()\n\tinstanceID := getInstanceID(ctx)\n\tparams, err := api.getAdminParams(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmailer := getMailer(ctx)\n\tif err := mailer.ValidateEmail(params.Email); err != nil {\n\t\treturn badRequestError(\"Invalid email address: %s\", params.Email).WithInternalError(err)\n\t}\n\n\taud := api.requestAud(ctx, r)\n\tif params.User.Aud != \"\" {\n\t\taud = params.User.Aud\n\t}\n\n\tif exists, err := api.db.IsDuplicatedEmail(instanceID, params.Email, aud); err != nil {\n\t\treturn internalServerError(\"Database error checking email\").WithInternalError(err)\n\t} else if exists {\n\t\treturn unprocessableEntityError(\"Email address already registered by another user\")\n\t}\n\n\tuser, err := models.NewUser(instanceID, params.Email, params.Password, aud, params.Data)\n\tif err != nil {\n\t\treturn internalServerError(\"Error creating user\").WithInternalError(err)\n\t}\n\n\tconfig := getConfig(ctx)\n\tif params.Role != \"\" {\n\t\tuser.SetRole(params.Role)\n\t} else {\n\t\tuser.SetRole(config.JWT.DefaultGroupName)\n\t}\n\n\tif params.Confirm {\n\t\tuser.Confirm()\n\t}\n\n\tif err = api.db.CreateUser(user); err != nil {\n\t\treturn internalServerError(\"Database error creating new user\").WithInternalError(err)\n\t}\n\n\treturn sendJSON(w, http.StatusOK, user)\n}\n\n\/\/ adminUserDelete delete a user\nfunc (api *API) adminUserDelete(w http.ResponseWriter, r *http.Request) error {\n\tinstanceID := getInstanceID(r.Context())\n\tparams, err := api.getAdminParams(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\tuser, err := api.getAdminTargetUser(instanceID, params)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := api.db.DeleteUser(user); err != nil {\n\t\treturn internalServerError(\"Database error deleting user\").WithInternalError(err)\n\t}\n\n\treturn sendJSON(w, http.StatusOK, map[string]interface{}{})\n}\n<commit_msg>Preload audience from the request before getting a user.<commit_after>package api\n\nimport (\n\t\"encoding\/json\"\n\t\"net\/http\"\n\n\t\"github.com\/netlify\/gotrue\/models\"\n)\n\n\/\/ adminUserParams are used to handle admin requests that relate to user accounts\n\/\/ The User field is used for sub-user authentication and the others are used in the Update\/Create endpoints\n\/\/\n\/\/ To create a new user the request would look like:\n\/\/     {\"email\": \"email@provider.com\", \"password\": \"password\"}\n\/\/\n\/\/ And to authenticate as another user as an administrator you would send:\n\/\/     {\"user\": {\"email\": \"email@provider.com\", \"aud\": \"myaudience\"}}\ntype adminTargetUser struct {\n\tAud   string `json:\"aud\"`\n\tEmail string `json:\"email\"`\n\tID    string `json:\"id\"`\n}\n\ntype adminUserParams struct {\n\tRole     string                 `json:\"role\"`\n\tEmail    string                 `json:\"email\"`\n\tPassword string                 `json:\"password\"`\n\tConfirm  bool                   `json:\"confirm\"`\n\tData     map[string]interface{} `json:\"data\"`\n\tUser     adminTargetUser        `json:\"user\"`\n}\n\nfunc (api *API) getAdminParams(r *http.Request) (*adminUserParams, error) {\n\tparams := adminUserParams{}\n\terr := json.NewDecoder(r.Body).Decode(&params)\n\tif err != nil {\n\t\treturn nil, badRequestError(\"Could not decode admin user params: %v\", err)\n\t}\n\treturn &params, nil\n}\n\n\/\/ Returns the the target user\nfunc (api *API) getAdminTargetUser(instanceID string, params *adminUserParams) (*models.User, error) {\n\tuser, err := api.db.FindUserByEmailAndAudience(instanceID, params.User.Email, params.User.Aud)\n\tif err != nil {\n\t\tif models.IsNotFoundError(err) {\n\t\t\tif user, err = api.db.FindUserByID(params.User.ID); err != nil {\n\t\t\t\tif models.IsNotFoundError(err) {\n\t\t\t\t\treturn nil, badRequestError(\"Unable to find user by email: %s and id: %s in audience: %s\", params.User.Email, params.User.ID, params.User.Aud)\n\t\t\t\t}\n\t\t\t\treturn nil, internalServerError(\"Database error finding user\").WithInternalError(err)\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil, internalServerError(\"Database error finding user\").WithInternalError(err)\n\t\t}\n\t}\n\n\treturn user, nil\n}\n\n\/\/ adminUsers responds with a list of all users in a given audience\nfunc (api *API) adminUsers(w http.ResponseWriter, r *http.Request) error {\n\tctx := r.Context()\n\tinstanceID := getInstanceID(ctx)\n\taud := api.requestAud(ctx, r)\n\tusers, err := api.db.FindUsersInAudience(instanceID, aud)\n\tif err != nil {\n\t\treturn internalServerError(\"Database error finding users\").WithInternalError(err)\n\t}\n\n\treturn sendJSON(w, http.StatusOK, map[string]interface{}{\n\t\t\"users\": users,\n\t\t\"aud\":   aud,\n\t})\n}\n\n\/\/ adminUserGet returns information about a single user\nfunc (api *API) adminUserGet(w http.ResponseWriter, r *http.Request) error {\n\tctx := r.Context()\n\tinstanceID := getInstanceID(r.Context())\n\n\taud := r.FormValue(\"aud\")\n\tif aud == \"\" {\n\t\taud = api.requestAud(ctx, r)\n\t}\n\n\tparams := &adminUserParams{\n\t\tUser: adminTargetUser{\n\t\t\tID:    r.FormValue(\"id\"),\n\t\t\tEmail: r.FormValue(\"email\"),\n\t\t\tAud:   aud,\n\t\t},\n\t}\n\tuser, err := api.getAdminTargetUser(instanceID, params)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn sendJSON(w, http.StatusOK, user)\n}\n\n\/\/ adminUserUpdate updates a single user object\nfunc (api *API) adminUserUpdate(w http.ResponseWriter, r *http.Request) error {\n\tinstanceID := getInstanceID(r.Context())\n\tparams, err := api.getAdminParams(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\tuser, err := api.getAdminTargetUser(instanceID, params)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif params.Role != \"\" {\n\t\tuser.SetRole(params.Role)\n\t}\n\n\tif params.Confirm {\n\t\tuser.Confirm()\n\t}\n\n\tif params.Password != \"\" {\n\t\tuser.EncryptPassword(params.Password)\n\t}\n\n\tif params.Email != \"\" {\n\t\tuser.Email = params.Email\n\t}\n\n\tif err := api.db.UpdateUser(user); err != nil {\n\t\treturn internalServerError(\"Error updating user\").WithInternalError(err)\n\t}\n\n\treturn sendJSON(w, http.StatusOK, user)\n}\n\n\/\/ adminUserCreate creates a new user based on the provided data\nfunc (api *API) adminUserCreate(w http.ResponseWriter, r *http.Request) error {\n\tctx := r.Context()\n\tinstanceID := getInstanceID(ctx)\n\tparams, err := api.getAdminParams(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmailer := getMailer(ctx)\n\tif err := mailer.ValidateEmail(params.Email); err != nil {\n\t\treturn badRequestError(\"Invalid email address: %s\", params.Email).WithInternalError(err)\n\t}\n\n\taud := api.requestAud(ctx, r)\n\tif params.User.Aud != \"\" {\n\t\taud = params.User.Aud\n\t}\n\n\tif exists, err := api.db.IsDuplicatedEmail(instanceID, params.Email, aud); err != nil {\n\t\treturn internalServerError(\"Database error checking email\").WithInternalError(err)\n\t} else if exists {\n\t\treturn unprocessableEntityError(\"Email address already registered by another user\")\n\t}\n\n\tuser, err := models.NewUser(instanceID, params.Email, params.Password, aud, params.Data)\n\tif err != nil {\n\t\treturn internalServerError(\"Error creating user\").WithInternalError(err)\n\t}\n\n\tconfig := getConfig(ctx)\n\tif params.Role != \"\" {\n\t\tuser.SetRole(params.Role)\n\t} else {\n\t\tuser.SetRole(config.JWT.DefaultGroupName)\n\t}\n\n\tif params.Confirm {\n\t\tuser.Confirm()\n\t}\n\n\tif err = api.db.CreateUser(user); err != nil {\n\t\treturn internalServerError(\"Database error creating new user\").WithInternalError(err)\n\t}\n\n\treturn sendJSON(w, http.StatusOK, user)\n}\n\n\/\/ adminUserDelete delete a user\nfunc (api *API) adminUserDelete(w http.ResponseWriter, r *http.Request) error {\n\tinstanceID := getInstanceID(r.Context())\n\tparams, err := api.getAdminParams(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\tuser, err := api.getAdminTargetUser(instanceID, params)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := api.db.DeleteUser(user); err != nil {\n\t\treturn internalServerError(\"Database error deleting user\").WithInternalError(err)\n\t}\n\n\treturn sendJSON(w, http.StatusOK, map[string]interface{}{})\n}\n<|endoftext|>"}
{"text":"<commit_before>package carto\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"runtime\"\n\n\t\"sync\"\n\n\t\"github.com\/mathuin\/gdal\"\n\t\"github.com\/mathuin\/terroir\/world\"\n)\n\n\/\/ JMT: convert to XZ, biome value, and list 0->n of points\ntype Column struct {\n\txz     world.XZ\n\tbiome  string\n\tblocks []string\n}\n\nfunc (r Region) genFeatures(in chan Feature) {\n\tds, err := gdal.Open(r.mapfile, gdal.ReadOnly)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif Debug {\n\t\tdatasetInfo(ds, \"genFeatures Input\")\n\t}\n\tinx := ds.RasterXSize()\n\tiny := ds.RasterYSize()\n\tsrs := gdal.CreateSpatialReference(ds.Projection())\n\tbufferLen := inx * iny\n\n\tlcarr := make([]int16, bufferLen)\n\tlcBand := ds.RasterBand(Landcover)\n\tlcrerr := lcBand.IO(gdal.Read, 0, 0, inx, iny, lcarr, inx, iny, 0, 0)\n\tif notnil(lcrerr) {\n\t\tpanic(lcrerr)\n\t}\n\n\t\/\/ shapefile driver\n\toutdrv := gdal.OGRDriverByName(\"Memory\")\n\toutDS, ok := outdrv.Create(\"out\", nil)\n\tif !ok {\n\t\tpanic(fmt.Errorf(\"OGR Driver Create Fail\"))\n\t}\n\toutLayer := outDS.CreateLayer(\"polygons\", srs, gdal.GT_Polygon, nil)\n\n\t\/\/ field definition\n\toutField := gdal.CreateFieldDefinition(\"lc\", gdal.FT_Integer)\n\toutLayer.CreateField(outField, false)\n\tfield := 0\n\n\t\/\/ options!\n\toptions := []string{}\n\n\t\/\/ do it!\n\terr = lcBand.Polygonize(lcBand, outLayer, field, options, gdal.DummyProgress, nil)\n\tif notnil(err) {\n\t\tpanic(err)\n\t}\n\n\t\/\/ iterate over features\n\tfc, ok := outLayer.FeatureCount(true)\n\tif !ok {\n\t\tpanic(fmt.Errorf(\"outLayer.FeatureCount NOT OK\"))\n\t}\n\tif Debug {\n\t\tlog.Print(\"outLayer.FeatureCount(true): \", fc)\n\t}\n\toutLayer.ResetReading()\n\tfor i := 0; i < fc; i++ {\n\t\tin <- Feature{outLayer.NextFeature()}\n\t}\n\tclose(in)\n}\n\nfunc (r *Region) BuildWorld() (*world.World, error) {\n\tw := world.MakeWorld(r.name)\n\tw.SetRandomSeed(0)\n\t\/\/ JMT: need a sane storage location for files\n\tw.SetSaveDir(\".\")\n\tspawnpt := world.MakePoint(0, 0, 0)\n\n\tin := make(chan Feature)\n\tout := make(chan Column)\n\n\tvar wg sync.WaitGroup\n\n\tnumWorkers := runtime.NumCPU()\n\t\/\/ if Debug {\n\t\/\/ \tlog.Print(\"debug mode - only starting one worker\")\n\t\/\/ \tnumWorkers = 1\n\t\/\/ }\n\n\tfor i := 0; i < numWorkers; i++ {\n\t\twg.Add(1)\n\t\tgo func(i int) {\n\t\t\tdefer wg.Done()\n\t\t\tr.processFeatures(in, out, i)\n\t\t}(i)\n\t}\n\tgo func() { wg.Wait(); close(out) }()\n\tgo r.genFeatures(in)\n\n\tcolumncount := 0\n\tfor column := range out {\n\t\tcolumncount++\n\n\t\tb, ok := world.Biome[column.biome]\n\t\tif !ok {\n\t\t\terr := fmt.Errorf(\"biome %s not in world.Biome\", column.biome)\n\t\t\tpanic(err)\n\t\t}\n\t\tw.SetBiome(column.xz, byte(b))\n\n\t\tfor k, v := range column.blocks {\n\t\t\tpt := world.Point{X: column.xz.X, Y: int32(k), Z: column.xz.Z}\n\t\t\tb, err := world.BlockNamed(v)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tw.SetBlock(pt, b)\n\t\t}\n\n\t\ttopBlock := world.Point{X: column.xz.X, Y: int32(len(column.blocks)), Z: column.xz.Z}\n\n\t\tif topBlock.Y > spawnpt.Y {\n\t\t\tif Debug {\n\t\t\t\tlog.Printf(\"new spawn: %s\", topBlock)\n\t\t\t}\n\t\t\tspawnpt = topBlock\n\t\t}\n\n\t\t\/\/ JMT: naive lighting here\n\t\tw.SetSkyLight(topBlock, 15)\n\t}\n\n\tw.SetSpawn(spawnpt)\n\n\treturn &w, nil\n}\n\nvar Arrind2Debug = false\n\nfunc arrind2(x int32, y int32, inx int32, iny int32, gti [6]int32) (int32, error) {\n\tif Arrind2Debug {\n\t\tlog.Printf(\"x: %d, y: %d, inx: %d\", x, y, inx)\n\t\tlog.Printf(\"0: %d, 1: %d, 2: %d, 3: %d, 4: %d, 5: %d\",\n\t\t\tgti[0], gti[1], gti[2], gti[3], gti[4], gti[5])\n\t\tlog.Printf(\"x-0: %d, y-3: %d\", x-gti[0], y-gti[3])\n\t\tlog.Printf(\"x-0\/1: %d, y-3\/5: %d\", (x-gti[0])\/gti[1], (y-gti[3])\/gti[5])\n\t}\n\trealx := (x - gti[0]) \/ gti[1]\n\tif realx < 0 {\n\t\treturn 0, fmt.Errorf(\"realx %d < 0\", realx)\n\t}\n\tif realx > inx {\n\t\treturn 0, fmt.Errorf(\"realx %d >= inx %d\", realx, inx)\n\t}\n\trealy := (y-gti[3])\/gti[5] - 1\n\tif realy < 0 {\n\t\treturn 0, fmt.Errorf(\"realx %d < 0\", realx)\n\t}\n\tif realy > iny {\n\t\treturn 0, fmt.Errorf(\"realy %d > iny %d\", realy, iny)\n\t}\n\treturn realx + realy*inx, nil\n}\n\nfunc (r *Region) processFeatures(in chan Feature, out chan Column, i int) {\n\tds, err := gdal.Open(r.mapfile, gdal.ReadOnly)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif Debug && i == 0 {\n\t\tdatasetInfo(ds, \"processFeatures\")\n\t}\n\tinx := ds.RasterXSize()\n\tiny := ds.RasterYSize()\n\tbufferLen := inx * iny\n\n\tlcarr := make([]int16, bufferLen)\n\tlcBand := ds.RasterBand(Landcover)\n\tlcrerr := lcBand.IO(gdal.Read, 0, 0, inx, iny, lcarr, inx, iny, 0, 0)\n\tif notnil(lcrerr) {\n\t\tpanic(lcrerr)\n\t}\n\n\televarr := make([]int16, bufferLen)\n\televBand := ds.RasterBand(Elevation)\n\televrerr := elevBand.IO(gdal.Read, 0, 0, inx, iny, elevarr, inx, iny, 0, 0)\n\tif notnil(elevrerr) {\n\t\tpanic(elevrerr)\n\t}\n\n\tbathyarr := make([]int16, bufferLen)\n\tbathyBand := ds.RasterBand(Bathy)\n\tbathyrerr := bathyBand.IO(gdal.Read, 0, 0, inx, iny, bathyarr, inx, iny, 0, 0)\n\tif notnil(bathyrerr) {\n\t\tpanic(bathyrerr)\n\t}\n\n\tcrustarr := make([]int16, bufferLen)\n\tcrustBand := ds.RasterBand(Crust)\n\tcrustrerr := crustBand.IO(gdal.Read, 0, 0, inx, iny, crustarr, inx, iny, 0, 0)\n\tif notnil(crustrerr) {\n\t\tpanic(crustrerr)\n\t}\n\n\tprocessed := 0\n\n\t\/\/ first pass at memoize\n\t\/\/ memo := make(map[string]Column)\n\n\tfor f := range in {\n\t\tprocessed++\n\n\t\thead := fmt.Sprintf(\"%d: feature #%d\", i, processed)\n\n\t\t\/\/ if Debug {\n\t\t\/\/ \tlog.Printf(\"%s begins\", head)\n\t\t\/\/ }\n\t\tpts := f.Points(ds, head)\n\t\tif len(pts) == 0 {\n\t\t\tlog.Printf(\"%s: No points in geometry!\", head)\n\t\t\tlog.Print(\"SCRATCH ONE FEATURE\")\n\t\t\tcontinue\n\t\t}\n\n\t\tlc := f.LCValue()\n\t\tswitch lc {\n\t\tcase 11:\n\t\t\t\/\/ \"open water\"\n\t\t\tfor _, pt := range pts {\n\t\t\t\telev := elevarr[pt.index]\n\t\t\t\tbathy := bathyarr[pt.index]\n\t\t\t\tcrust := crustarr[pt.index]\n\n\t\t\t\t\/\/ key := fmt.Sprintf(\"%d|%d|%d|%d\", lc, elev, bathy, crust)\n\t\t\t\t\/\/ if col, ok := memo[key]; ok {\n\t\t\t\t\/\/ \tout <- col\n\t\t\t\t\/\/ \tcontinue\n\t\t\t\t\/\/ }\n\n\t\t\t\tcol := Column{}\n\t\t\t\tcol.xz = pt.xz\n\n\t\t\t\tif int(bathy) <= r.maxdepth-1 {\n\t\t\t\t\tcol.biome = \"Deep Ocean\"\n\t\t\t\t} else {\n\t\t\t\t\tcol.biome = \"Ocean\"\n\t\t\t\t}\n\n\t\t\t\tblocks := make([]string, elev)\n\n\t\t\t\tfor y := int16(0); y < elev; y++ {\n\t\t\t\t\tif y == 0 {\n\t\t\t\t\t\tblocks[y] = \"Bedrock\"\n\t\t\t\t\t} else if y < (elev - bathy - crust) {\n\t\t\t\t\t\tblocks[y] = \"Stone\"\n\t\t\t\t\t} else if y < (elev - bathy) {\n\t\t\t\t\t\tblocks[y] = \"Gravel\"\n\t\t\t\t\t} else {\n\t\t\t\t\t\tblocks[y] = \"Water\"\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcol.blocks = blocks\n\t\t\t\t\/\/ memo[key] = col\n\t\t\t\tout <- col\n\t\t\t}\n\t\tdefault:\n\t\t\t\/\/ anything else\n\t\t\tfor _, pt := range pts {\n\t\t\t\telev := elevarr[pt.index]\n\t\t\t\t\/\/ bathy := bathyarr[pt.index]\n\t\t\t\tcrust := crustarr[pt.index]\n\n\t\t\t\t\/\/ key := fmt.Sprintf(\"%d|%d|%d|%d\", lc, elev, bathy, crust)\n\t\t\t\t\/\/ if col, ok := memo[key]; ok {\n\t\t\t\t\/\/ \tout <- col\n\t\t\t\t\/\/ \tcontinue\n\t\t\t\t\/\/ }\n\n\t\t\t\tcol := Column{}\n\t\t\t\tcol.xz = pt.xz\n\t\t\t\tcol.biome = \"Plains\"\n\n\t\t\t\tblocks := make([]string, elev)\n\n\t\t\t\tfor y := int16(0); y < elev; y++ {\n\t\t\t\t\tif y == 0 {\n\t\t\t\t\t\tblocks[y] = \"Bedrock\"\n\t\t\t\t\t} else if y < (elev - crust - 1) {\n\t\t\t\t\t\tblocks[y] = \"Stone\"\n\t\t\t\t\t} else if y < elev-1 {\n\t\t\t\t\t\tblocks[y] = \"Dirt\"\n\t\t\t\t\t} else {\n\t\t\t\t\t\tblocks[y] = \"Grass Block\"\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcol.blocks = blocks\n\t\t\t\t\/\/ memo[key] = col\n\t\t\t\tout <- col\n\t\t\t}\n\t\t}\n\t}\n}\n\ntype Feature struct {\n\tgdal.Feature\n}\n\n\/\/ returns true if the feature is valid\nfunc (f Feature) isValid() bool {\n\treturn f.Geometry().IsValid()\n}\n\n\/\/ returns the landcover value\nfunc (f Feature) LCValue() int {\n\t\/\/ field 0 is the only field here\n\treturn f.FieldAsInteger(0)\n}\n\n\/\/ generates list of points and sends them to a channel\nfunc (f Feature) genPoints(in chan world.XZ, gti [6]int32) {\n\tg := f.Geometry()\n\te := g.Envelope()\n\teminx := int32(e.MinX())\n\teminy := int32(e.MinY())\n\temaxx := int32(e.MaxX())\n\temaxy := int32(e.MaxY())\n\n\tfor y := eminy; y < emaxy; y -= gti[5] {\n\t\tfor x := eminx; x < emaxx; x += gti[1] {\n\t\t\tin <- world.XZ{X: x, Z: y}\n\t\t}\n\t}\n\tclose(in)\n}\n\ntype XZIndex struct {\n\txz    world.XZ\n\tindex int32\n}\n\nfunc (f Feature) Points(ds gdal.Dataset, head string) []XZIndex {\n\tinx := ds.RasterXSize()\n\tiny := ds.RasterYSize()\n\tgt := ds.GeoTransform()\n\tsrs := gdal.CreateSpatialReference(ds.Projection())\n\n\tlcarr := make([]int16, inx*iny)\n\tlcBand := ds.RasterBand(Landcover)\n\tlcrerr := lcBand.IO(gdal.Read, 0, 0, inx, iny, lcarr, inx, iny, 0, 0)\n\tif notnil(lcrerr) {\n\t\tpanic(lcrerr)\n\t}\n\n\tvar gti [6]int32\n\tfor i, v := range gt {\n\t\tgti[i] = int32(v)\n\t}\n\n\tin := make(chan world.XZ)\n\tout := make(chan XZIndex)\n\n\tvar wg sync.WaitGroup\n\n\tnumWorkers := runtime.NumCPU()\n\n\tfor i := 0; i < numWorkers; i++ {\n\t\twg.Add(1)\n\t\tgo func(i int) {\n\t\t\tdefer wg.Done()\n\t\t\tppHead := fmt.Sprintf(\"%s %d\", head, i)\n\t\t\tf.processPoints(in, out, inx, iny, gti, srs, lcarr, ppHead)\n\t\t}(i)\n\t}\n\tgo func() { wg.Wait(); close(out) }()\n\tgo f.genPoints(in, gti)\n\n\tpts := []XZIndex{}\n\tptcount := 0\n\tfor pt := range out {\n\t\tif Debug {\n\t\t\tif ptcount > 1 && ptcount%10000 == 0 {\n\t\t\t\tlog.Printf(\"%s: %d columns\", head, ptcount)\n\t\t\t}\n\t\t}\n\t\tptcount++\n\t\tpts = append(pts, pt)\n\t}\n\treturn pts\n}\n\nfunc (f Feature) processPoints(in chan world.XZ, out chan XZIndex, inx int, iny int, gti [6]int32, srs gdal.SpatialReference, lcarr []int16, ppHead string) {\n\tg := f.Geometry()\n\n\tlc := f.LCValue()\n\n\tfor xz := range in {\n\t\tindex, aerr := arrind2(xz.X, xz.Z, int32(inx), int32(iny), gti)\n\t\t\/\/ JMT: arrind returns nil if coordinates are invalid\n\t\tif aerr != nil {\n\t\t\tlog.Printf(\"%s: aerr was not nil: %s\", ppHead, aerr.Error())\n\t\t\tcontinue\n\t\t}\n\t\tif lcarr[index] != int16(lc) {\n\t\t\tcontinue\n\t\t}\n\t\twkt := fmt.Sprintf(\"POINT (%f %f)\", float64(xz.X)+0.5*float64(gti[1]), float64(xz.Z)-0.5*float64(gti[5]))\n\t\tpt, err := gdal.CreateFromWKT(wkt, srs)\n\t\tif notnil(err) {\n\t\t\tlog.Printf(\"%s: gdal.CreateFromWKT() error: %s\", ppHead, err.Error())\n\t\t\tcontinue\n\t\t}\n\t\tif g.Contains(pt) {\n\t\t\tout <- XZIndex{xz: world.XZ{X: xz.X \/ gti[1], Z: xz.Z \/ gti[5]}, index: index}\n\t\t}\n\t}\n}\n<commit_msg>Moved transformation to a better place.<commit_after>package carto\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"runtime\"\n\n\t\"sync\"\n\n\t\"github.com\/mathuin\/gdal\"\n\t\"github.com\/mathuin\/terroir\/world\"\n)\n\n\/\/ JMT: convert to XZ, biome value, and list 0->n of points\ntype Column struct {\n\txz     world.XZ\n\tbiome  string\n\tblocks []string\n}\n\nfunc (r Region) genFeatures(in chan Feature) {\n\tds, err := gdal.Open(r.mapfile, gdal.ReadOnly)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif Debug {\n\t\tdatasetInfo(ds, \"genFeatures Input\")\n\t}\n\tinx := ds.RasterXSize()\n\tiny := ds.RasterYSize()\n\tsrs := gdal.CreateSpatialReference(ds.Projection())\n\tbufferLen := inx * iny\n\n\tlcarr := make([]int16, bufferLen)\n\tlcBand := ds.RasterBand(Landcover)\n\tlcrerr := lcBand.IO(gdal.Read, 0, 0, inx, iny, lcarr, inx, iny, 0, 0)\n\tif notnil(lcrerr) {\n\t\tpanic(lcrerr)\n\t}\n\n\t\/\/ shapefile driver\n\toutdrv := gdal.OGRDriverByName(\"Memory\")\n\toutDS, ok := outdrv.Create(\"out\", nil)\n\tif !ok {\n\t\tpanic(fmt.Errorf(\"OGR Driver Create Fail\"))\n\t}\n\toutLayer := outDS.CreateLayer(\"polygons\", srs, gdal.GT_Polygon, nil)\n\n\t\/\/ field definition\n\toutField := gdal.CreateFieldDefinition(\"lc\", gdal.FT_Integer)\n\toutLayer.CreateField(outField, false)\n\tfield := 0\n\n\t\/\/ options!\n\toptions := []string{}\n\n\t\/\/ do it!\n\terr = lcBand.Polygonize(lcBand, outLayer, field, options, gdal.DummyProgress, nil)\n\tif notnil(err) {\n\t\tpanic(err)\n\t}\n\n\t\/\/ iterate over features\n\tfc, ok := outLayer.FeatureCount(true)\n\tif !ok {\n\t\tpanic(fmt.Errorf(\"outLayer.FeatureCount NOT OK\"))\n\t}\n\tif Debug {\n\t\tlog.Print(\"outLayer.FeatureCount(true): \", fc)\n\t}\n\toutLayer.ResetReading()\n\tfor i := 0; i < fc; i++ {\n\t\tin <- Feature{outLayer.NextFeature()}\n\t}\n\tclose(in)\n}\n\nfunc (r *Region) BuildWorld() (*world.World, error) {\n\tw := world.MakeWorld(r.name)\n\tw.SetRandomSeed(0)\n\t\/\/ JMT: need a sane storage location for files\n\tw.SetSaveDir(\".\")\n\tspawnpt := world.MakePoint(0, 0, 0)\n\n\tin := make(chan Feature)\n\tout := make(chan Column)\n\n\tvar wg sync.WaitGroup\n\n\tnumWorkers := runtime.NumCPU()\n\t\/\/ if Debug {\n\t\/\/ \tlog.Print(\"debug mode - only starting one worker\")\n\t\/\/ \tnumWorkers = 1\n\t\/\/ }\n\n\tfor i := 0; i < numWorkers; i++ {\n\t\twg.Add(1)\n\t\tgo func(i int) {\n\t\t\tdefer wg.Done()\n\t\t\tr.processFeatures(in, out, i)\n\t\t}(i)\n\t}\n\tgo func() { wg.Wait(); close(out) }()\n\tgo r.genFeatures(in)\n\n\tcolumncount := 0\n\tfor column := range out {\n\t\tcolumncount++\n\n\t\tb, ok := world.Biome[column.biome]\n\t\tif !ok {\n\t\t\terr := fmt.Errorf(\"biome %s not in world.Biome\", column.biome)\n\t\t\tpanic(err)\n\t\t}\n\t\tw.SetBiome(column.xz, byte(b))\n\n\t\tfor k, v := range column.blocks {\n\t\t\tpt := world.Point{X: column.xz.X, Y: int32(k), Z: column.xz.Z}\n\t\t\tb, err := world.BlockNamed(v)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tw.SetBlock(pt, b)\n\t\t}\n\n\t\ttopBlock := world.Point{X: column.xz.X, Y: int32(len(column.blocks)), Z: column.xz.Z}\n\n\t\tif topBlock.Y > spawnpt.Y {\n\t\t\tif Debug {\n\t\t\t\tlog.Printf(\"new spawn: %s\", topBlock)\n\t\t\t}\n\t\t\tspawnpt = topBlock\n\t\t}\n\n\t\t\/\/ JMT: naive lighting here\n\t\tw.SetSkyLight(topBlock, 15)\n\t}\n\n\tw.SetSpawn(spawnpt)\n\n\treturn &w, nil\n}\n\nvar Arrind2Debug = false\n\nfunc arrind2(x int32, y int32, inx int32, iny int32, gti [6]int32) (int32, error) {\n\tif Arrind2Debug {\n\t\tlog.Printf(\"x: %d, y: %d, inx: %d\", x, y, inx)\n\t\tlog.Printf(\"0: %d, 1: %d, 2: %d, 3: %d, 4: %d, 5: %d\",\n\t\t\tgti[0], gti[1], gti[2], gti[3], gti[4], gti[5])\n\t\tlog.Printf(\"x-0: %d, y-3: %d\", x-gti[0], y-gti[3])\n\t\tlog.Printf(\"x-0\/1: %d, y-3\/5: %d\", (x-gti[0])\/gti[1], (y-gti[3])\/gti[5])\n\t}\n\trealx := (x - gti[0]) \/ gti[1]\n\tif realx < 0 {\n\t\treturn 0, fmt.Errorf(\"realx %d < 0\", realx)\n\t}\n\tif realx > inx {\n\t\treturn 0, fmt.Errorf(\"realx %d >= inx %d\", realx, inx)\n\t}\n\trealy := (y-gti[3])\/gti[5] - 1\n\tif realy < 0 {\n\t\treturn 0, fmt.Errorf(\"realx %d < 0\", realx)\n\t}\n\tif realy > iny {\n\t\treturn 0, fmt.Errorf(\"realy %d > iny %d\", realy, iny)\n\t}\n\treturn realx + realy*inx, nil\n}\n\nfunc (r *Region) processFeatures(in chan Feature, out chan Column, i int) {\n\tds, err := gdal.Open(r.mapfile, gdal.ReadOnly)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif Debug && i == 0 {\n\t\tdatasetInfo(ds, \"processFeatures\")\n\t}\n\tinx := ds.RasterXSize()\n\tiny := ds.RasterYSize()\n\tbufferLen := inx * iny\n\n\tlcarr := make([]int16, bufferLen)\n\tlcBand := ds.RasterBand(Landcover)\n\tlcrerr := lcBand.IO(gdal.Read, 0, 0, inx, iny, lcarr, inx, iny, 0, 0)\n\tif notnil(lcrerr) {\n\t\tpanic(lcrerr)\n\t}\n\n\televarr := make([]int16, bufferLen)\n\televBand := ds.RasterBand(Elevation)\n\televrerr := elevBand.IO(gdal.Read, 0, 0, inx, iny, elevarr, inx, iny, 0, 0)\n\tif notnil(elevrerr) {\n\t\tpanic(elevrerr)\n\t}\n\n\tbathyarr := make([]int16, bufferLen)\n\tbathyBand := ds.RasterBand(Bathy)\n\tbathyrerr := bathyBand.IO(gdal.Read, 0, 0, inx, iny, bathyarr, inx, iny, 0, 0)\n\tif notnil(bathyrerr) {\n\t\tpanic(bathyrerr)\n\t}\n\n\tcrustarr := make([]int16, bufferLen)\n\tcrustBand := ds.RasterBand(Crust)\n\tcrustrerr := crustBand.IO(gdal.Read, 0, 0, inx, iny, crustarr, inx, iny, 0, 0)\n\tif notnil(crustrerr) {\n\t\tpanic(crustrerr)\n\t}\n\n\tprocessed := 0\n\n\t\/\/ first pass at memoize\n\t\/\/ memo := make(map[string]Column)\n\n\tfor f := range in {\n\t\tprocessed++\n\n\t\thead := fmt.Sprintf(\"%d: feature #%d\", i, processed)\n\n\t\t\/\/ if Debug {\n\t\t\/\/ \tlog.Printf(\"%s begins\", head)\n\t\t\/\/ }\n\t\tpts := f.Points(ds, head)\n\t\tif len(pts) == 0 {\n\t\t\tlog.Printf(\"%s: No points in geometry!\", head)\n\t\t\tlog.Print(\"SCRATCH ONE FEATURE\")\n\t\t\tcontinue\n\t\t}\n\n\t\tlc := f.LCValue()\n\t\tswitch lc {\n\t\tcase 11:\n\t\t\t\/\/ \"open water\"\n\t\t\tfor _, pt := range pts {\n\t\t\t\telev := elevarr[pt.index]\n\t\t\t\tbathy := bathyarr[pt.index]\n\t\t\t\tcrust := crustarr[pt.index]\n\n\t\t\t\t\/\/ key := fmt.Sprintf(\"%d|%d|%d|%d\", lc, elev, bathy, crust)\n\t\t\t\t\/\/ if col, ok := memo[key]; ok {\n\t\t\t\t\/\/ \tout <- col\n\t\t\t\t\/\/ \tcontinue\n\t\t\t\t\/\/ }\n\n\t\t\t\tcol := Column{}\n\t\t\t\tcol.xz = pt.xz\n\n\t\t\t\tif int(bathy) <= r.maxdepth-1 {\n\t\t\t\t\tcol.biome = \"Deep Ocean\"\n\t\t\t\t} else {\n\t\t\t\t\tcol.biome = \"Ocean\"\n\t\t\t\t}\n\n\t\t\t\tblocks := make([]string, elev)\n\n\t\t\t\tfor y := int16(0); y < elev; y++ {\n\t\t\t\t\tif y == 0 {\n\t\t\t\t\t\tblocks[y] = \"Bedrock\"\n\t\t\t\t\t} else if y < (elev - bathy - crust) {\n\t\t\t\t\t\tblocks[y] = \"Stone\"\n\t\t\t\t\t} else if y < (elev - bathy) {\n\t\t\t\t\t\tblocks[y] = \"Gravel\"\n\t\t\t\t\t} else {\n\t\t\t\t\t\tblocks[y] = \"Water\"\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcol.blocks = blocks\n\t\t\t\t\/\/ memo[key] = col\n\t\t\t\tout <- col\n\t\t\t}\n\t\tdefault:\n\t\t\t\/\/ anything else\n\t\t\tfor _, pt := range pts {\n\t\t\t\telev := elevarr[pt.index]\n\t\t\t\t\/\/ bathy := bathyarr[pt.index]\n\t\t\t\tcrust := crustarr[pt.index]\n\n\t\t\t\t\/\/ key := fmt.Sprintf(\"%d|%d|%d|%d\", lc, elev, bathy, crust)\n\t\t\t\t\/\/ if col, ok := memo[key]; ok {\n\t\t\t\t\/\/ \tout <- col\n\t\t\t\t\/\/ \tcontinue\n\t\t\t\t\/\/ }\n\n\t\t\t\tcol := Column{}\n\t\t\t\tcol.xz = pt.xz\n\t\t\t\tcol.biome = \"Plains\"\n\n\t\t\t\tblocks := make([]string, elev)\n\n\t\t\t\tfor y := int16(0); y < elev; y++ {\n\t\t\t\t\tif y == 0 {\n\t\t\t\t\t\tblocks[y] = \"Bedrock\"\n\t\t\t\t\t} else if y < (elev - crust - 1) {\n\t\t\t\t\t\tblocks[y] = \"Stone\"\n\t\t\t\t\t} else if y < elev-1 {\n\t\t\t\t\t\tblocks[y] = \"Dirt\"\n\t\t\t\t\t} else {\n\t\t\t\t\t\tblocks[y] = \"Grass Block\"\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcol.blocks = blocks\n\t\t\t\t\/\/ memo[key] = col\n\t\t\t\tout <- col\n\t\t\t}\n\t\t}\n\t}\n}\n\ntype Feature struct {\n\tgdal.Feature\n}\n\n\/\/ returns true if the feature is valid\nfunc (f Feature) isValid() bool {\n\treturn f.Geometry().IsValid()\n}\n\n\/\/ returns the landcover value\nfunc (f Feature) LCValue() int {\n\t\/\/ field 0 is the only field here\n\treturn f.FieldAsInteger(0)\n}\n\n\/\/ generates list of points and sends them to a channel\nfunc (f Feature) genPoints(in chan world.XZ, gti [6]int32) {\n\tg := f.Geometry()\n\te := g.Envelope()\n\teminx := int32(e.MinX())\n\teminy := int32(e.MinY())\n\temaxx := int32(e.MaxX())\n\temaxy := int32(e.MaxY())\n\n\tfor y := eminy; y < emaxy; y -= gti[5] {\n\t\tfor x := eminx; x < emaxx; x += gti[1] {\n\t\t\tin <- world.XZ{X: x, Z: y}\n\t\t}\n\t}\n\tclose(in)\n}\n\ntype XZIndex struct {\n\txz    world.XZ\n\tindex int32\n}\n\nfunc makeXZIndex(xz world.XZ, index int32, gti [6]int32) XZIndex {\n\treturn XZIndex{xz: world.XZ{X: xz.X \/ gti[1], Z: xz.Z \/ gti[5]}, index: index}\n}\n\nfunc (f Feature) Points(ds gdal.Dataset, head string) []XZIndex {\n\tinx := ds.RasterXSize()\n\tiny := ds.RasterYSize()\n\tgt := ds.GeoTransform()\n\tsrs := gdal.CreateSpatialReference(ds.Projection())\n\n\tlcarr := make([]int16, inx*iny)\n\tlcBand := ds.RasterBand(Landcover)\n\tlcrerr := lcBand.IO(gdal.Read, 0, 0, inx, iny, lcarr, inx, iny, 0, 0)\n\tif notnil(lcrerr) {\n\t\tpanic(lcrerr)\n\t}\n\n\tvar gti [6]int32\n\tfor i, v := range gt {\n\t\tgti[i] = int32(v)\n\t}\n\n\tin := make(chan world.XZ)\n\tout := make(chan XZIndex)\n\n\tvar wg sync.WaitGroup\n\n\tnumWorkers := runtime.NumCPU()\n\n\tfor i := 0; i < numWorkers; i++ {\n\t\twg.Add(1)\n\t\tgo func(i int) {\n\t\t\tdefer wg.Done()\n\t\t\tppHead := fmt.Sprintf(\"%s %d\", head, i)\n\t\t\tf.processPoints(in, out, inx, iny, gti, srs, lcarr, ppHead)\n\t\t}(i)\n\t}\n\tgo func() { wg.Wait(); close(out) }()\n\tgo f.genPoints(in, gti)\n\n\tpts := []XZIndex{}\n\tptcount := 0\n\tfor pt := range out {\n\t\tif Debug {\n\t\t\tif ptcount > 1 && ptcount%10000 == 0 {\n\t\t\t\tlog.Printf(\"%s: %d columns\", head, ptcount)\n\t\t\t}\n\t\t}\n\t\tptcount++\n\t\tpts = append(pts, pt)\n\t}\n\treturn pts\n}\n\nfunc (f Feature) processPoints(in chan world.XZ, out chan XZIndex, inx int, iny int, gti [6]int32, srs gdal.SpatialReference, lcarr []int16, ppHead string) {\n\tg := f.Geometry()\n\n\tlc := f.LCValue()\n\n\tfor xz := range in {\n\t\tindex, aerr := arrind2(xz.X, xz.Z, int32(inx), int32(iny), gti)\n\t\t\/\/ JMT: arrind returns nil if coordinates are invalid\n\t\tif aerr != nil {\n\t\t\tlog.Printf(\"%s: aerr was not nil: %s\", ppHead, aerr.Error())\n\t\t\tcontinue\n\t\t}\n\t\tif lcarr[index] != int16(lc) {\n\t\t\tcontinue\n\t\t}\n\t\twkt := fmt.Sprintf(\"POINT (%f %f)\", float64(xz.X)+0.5*float64(gti[1]), float64(xz.Z)-0.5*float64(gti[5]))\n\t\tpt, err := gdal.CreateFromWKT(wkt, srs)\n\t\tif notnil(err) {\n\t\t\tlog.Printf(\"%s: gdal.CreateFromWKT() error: %s\", ppHead, err.Error())\n\t\t\tcontinue\n\t\t}\n\t\tif g.Contains(pt) {\n\t\t\tout <- makeXZIndex(xz, index, gti)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>93af6b32-2e55-11e5-9284-b827eb9e62be<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Liu Dong <ddliuhb@gmail.com>.\n\/\/ Licensed under the MIT license.\n\npackage spider\n\nimport (\n    \"time\"\n    \/\/ \"fmt\"\n    \"sync\"\n    \"log\"\n)\n\nconst defaultConcurrency = 3\n\nconst (\n    ON_START = iota\n    ON_STOP = iota\n)\n\ntype Listener func(*Spider, *Task)\n\n\/\/ Create a spider.\nfunc NewSpider() *Spider {\n    spider := &Spider {\n    }\n\n    spider.prepare()\n    return spider\n}\n\ntype Spider struct {\n    Concurrency int\n    pipes []Pipe\n    tasks []*Task\n    events map[int][]Listener\n    Stats map[Status]uint64\n    IsPaused bool\n    IsStopped bool\n    IsDebug bool\n    m sync.Mutex\n    statsLock sync.Mutex\n}\n\n\/\/ Chain a pipe.\nfunc (this *Spider) Pipe(pipe Pipe) *Spider {\n    this.pipes = append(this.pipes, pipe)\n\n    return this\n} \n\n\/\/ Initialize the spider objects.\nfunc (this *Spider) prepare() {\n    this.events = make(map[int][]Listener)\n    this.Stats = make(map[Status]uint64)\n    this.Stats[PENDING] = 0\n    this.Stats[WORKING] = 0\n    this.Stats[FAILED] = 0\n    this.Stats[IGNORED] = 0\n    this.Stats[DONE] = 0\n}\n\n\/\/ Run spider forever, and accept a quit channel to close it.\n\/\/ \n\/\/ Loop through the task list and run each of them with the help of a buffered channel.\nfunc (this *Spider) RunForever(quit chan bool) {\n    this.IsStopped = false\n    this.IsPaused = false\n    log.Println(\"[INFO] Spider started\")\n\n    if this.Concurrency <= 0 {\n        this.Concurrency = defaultConcurrency\n    }\n\n    chs := make(chan bool, this.Concurrency)\n\n    for {\n        select {\n        case <- quit:\n            break\n        default:\n            \/\/ do nothing\n        }\n\n        if this.IsStopped {\n            break\n        }\n\n        if this.IsPaused {\n            time.Sleep(10 * time.Millisecond)\n            continue\n        }\n\n        this.m.Lock()\n        if len(this.tasks) > 0 {\n            task := this.tasks[len(this.tasks) - 1]\n            this.tasks = this.tasks[:len(this.tasks) - 1]\n\n            this.m.Unlock()\n            chs <- true\n            go func() {\n                this.do(task)\n                <-chs\n            }()\n        } else {\n            this.m.Unlock()\n\n            \/\/ there is nothing to do, sleep for 10 ms\n            time.Sleep(10 * time.Millisecond)\n        }\n    }\n}\n\n\/\/ Run spider and stop when complete.\nfunc (this *Spider) Run() {\n    quit := make(chan bool)\n    go this.RunForever(quit)\n\n    \/\/ check finish\n    for {\n        \/\/ if all tasks are finished, we can go out of the loop\n        if this.IsFinished() {\n            quit <- true\n            log.Println(\"[INFO] Spider finished\")\n            break\n        } else {\n            time.Sleep(10 * time.Millisecond)\n        }\n    }\n}\n\n\/\/ Run spider and start a RPC server\nfunc (this *Spider) RunAndServe(listen string) error {\n    quit := make(chan bool)\n    go this.RunForever(quit)\n\n    return StartRPCServer(this, listen)\n}\n\n\/\/ Run a single task (should never panic)\nfunc (this *Spider) do(task *Task) {\n    defer func() {\n        \/\/ error occured\n        if r := recover(); r != nil {\n            this.FailTask(task, r)\n            return\n        }\n\n        if !task.IsEnded() {\n            this.DoneTask(task)\n        }\n    }()\n\n    this.StartTask(task)\n\n    Series(this.pipes...)(this, task)\n}\n\nfunc (this *Spider) Pause() {\n    this.IsPaused = true\n}\n\nfunc (this *Spider) Resume() {\n    this.IsPaused = false\n}\n\nfunc (this *Spider) Stop() {\n    this.IsStopped = true\n}\n\n\/\/ Check if all tasks have been processed.\nfunc (this *Spider) IsFinished() bool {\n    return this.Stats[PENDING] == 0 && this.Stats[WORKING] == 0\n}\n\n\/\/ Add tasks from uri.\nfunc (this *Spider) AddUri(uris ...string) *Spider {\n    for _, uri := range uris {\n        this.AddTask(NewTask(uri))\n    }\n\n    return this\n}\n\n\/\/ Add a task to queue\nfunc (this *Spider) AddTask(task *Task) *Spider {\n    task.Spider = this\n    this.m.Lock()\n    this.tasks = append(this.tasks, task)\n    this.m.Unlock()\n\n    this.statsLock.Lock()\n    this.Stats[PENDING]++\n    this.statsLock.Unlock()\n\n    return this\n}\n\n\/\/ Mark a task as failed.\nfunc (this *Spider) FailTask(task *Task, reason interface{}) {\n    task.Status = FAILED\n\n    this.statsLock.Lock()\n    this.Stats[FAILED]++\n    this.Stats[WORKING]--\n    this.statsLock.Unlock()\n\n    log.Println(\"[WARN] Task failed: \", task.Uri, \"\\t\", reason)\n}\n\n\/\/ Mark a task as done.\nfunc (this *Spider) DoneTask(task *Task) {\n    task.Status = DONE\n    this.statsLock.Lock()\n    this.Stats[DONE]++\n    this.Stats[WORKING]--\n    this.statsLock.Unlock()\n\n    if this.IsDebug {\n        log.Println(\"[DEBUG] Task done: \", task.Uri)\n    }\n}\n\n\/\/ Mark a task as ignored.\nfunc (this *Spider) IgnoreTask(task *Task, reason interface{}) {\n    task.Status = IGNORED\n\n    this.statsLock.Lock()\n    this.Stats[IGNORED]++\n    this.Stats[WORKING]--\n    this.statsLock.Unlock()\n\n    if this.IsDebug {\n        log.Println(\"[DEBUG] Task ignored: \", task.Uri, \"\\t\", reason)\n    }\n}\n\n\/\/ Mark a task as started.\nfunc (this *Spider) StartTask(task *Task) {\n    task.Status = WORKING\n\n    this.statsLock.Lock()\n    this.Stats[WORKING]++\n    this.Stats[PENDING]--\n    this.statsLock.Unlock()\n\n    if this.IsDebug {\n        log.Println(\"[DEBUG] Task started: \", task.Uri)\n    }\n}\n\n\/\/ Register events\nfunc (this *Spider) On(e int, f Listener) *Spider {\n    this.events[e] = append(this.events[e], f)\n\n    return this\n}\n\n\/\/ Trigger an event\nfunc (this *Spider) Trigger(e int, t *Task) {\n    if events, ok := this.events[e]; ok {\n        for _, e := range events {\n            e(this, t)\n        }\n    }\n}<commit_msg>fix memory leak<commit_after>\/\/ Copyright 2015 Liu Dong <ddliuhb@gmail.com>.\n\/\/ Licensed under the MIT license.\n\npackage spider\n\nimport (\n    \"time\"\n    \/\/ \"fmt\"\n    \"sync\"\n    \"log\"\n)\n\nconst defaultConcurrency = 3\n\nconst (\n    ON_START = iota\n    ON_STOP = iota\n)\n\ntype Listener func(*Spider, *Task)\n\n\/\/ Create a spider.\nfunc NewSpider() *Spider {\n    spider := &Spider {\n    }\n\n    spider.prepare()\n    return spider\n}\n\ntype Spider struct {\n    Concurrency int\n    pipes []Pipe\n    tasks []*Task\n    events map[int][]Listener\n    Stats map[Status]uint64\n    IsPaused bool\n    IsStopped bool\n    IsDebug bool\n    m sync.Mutex\n    statsLock sync.Mutex\n}\n\n\/\/ Chain a pipe.\nfunc (this *Spider) Pipe(pipe Pipe) *Spider {\n    this.pipes = append(this.pipes, pipe)\n\n    return this\n} \n\n\/\/ Initialize the spider objects.\nfunc (this *Spider) prepare() {\n    this.events = make(map[int][]Listener)\n    this.Stats = make(map[Status]uint64)\n    this.Stats[PENDING] = 0\n    this.Stats[WORKING] = 0\n    this.Stats[FAILED] = 0\n    this.Stats[IGNORED] = 0\n    this.Stats[DONE] = 0\n}\n\n\/\/ Run spider forever, and accept a quit channel to close it.\n\/\/ \n\/\/ Loop through the task list and run each of them with the help of a buffered channel.\nfunc (this *Spider) RunForever(quit chan bool) {\n    this.IsStopped = false\n    this.IsPaused = false\n    log.Println(\"[INFO] Spider started\")\n\n    if this.Concurrency <= 0 {\n        this.Concurrency = defaultConcurrency\n    }\n\n    chs := make(chan bool, this.Concurrency)\n\n    for {\n        select {\n        case <- quit:\n            break\n        default:\n            \/\/ do nothing\n        }\n\n        if this.IsStopped {\n            break\n        }\n\n        if this.IsPaused {\n            time.Sleep(10 * time.Millisecond)\n            continue\n        }\n\n        this.m.Lock()\n        if len(this.tasks) > 0 {\n            task := this.tasks[len(this.tasks) - 1]\n            this.tasks = this.tasks[:len(this.tasks) - 1]\n\n            this.m.Unlock()\n            chs <- true\n            go func() {\n                this.do(task)\n                <-chs\n            }()\n        } else {\n            this.m.Unlock()\n\n            \/\/ there is nothing to do, sleep for 10 ms\n            time.Sleep(10 * time.Millisecond)\n        }\n    }\n}\n\n\/\/ Run spider and stop when complete.\nfunc (this *Spider) Run() {\n    quit := make(chan bool)\n    go this.RunForever(quit)\n\n    \/\/ check finish\n    for {\n        \/\/ if all tasks are finished, we can go out of the loop\n        if this.IsFinished() {\n            quit <- true\n            log.Println(\"[INFO] Spider finished\")\n            break\n        } else {\n            time.Sleep(10 * time.Millisecond)\n        }\n    }\n}\n\n\/\/ Run spider and start a RPC server\nfunc (this *Spider) RunAndServe(listen string) error {\n    quit := make(chan bool)\n    go this.RunForever(quit)\n\n    return StartRPCServer(this, listen)\n}\n\n\/\/ Run a single task (should never panic)\nfunc (this *Spider) do(task *Task) {\n    defer func() {\n        \/\/ error occured\n        if r := recover(); r != nil {\n            this.FailTask(task, r)\n        } else if !task.IsEnded() {\n            this.DoneTask(task)\n        }\n\n        \/\/ cleanup\n        task.Parent = nil\n        task.Data = nil\n    }()\n\n    this.StartTask(task)\n\n    Series(this.pipes...)(this, task)\n}\n\nfunc (this *Spider) Pause() {\n    this.IsPaused = true\n}\n\nfunc (this *Spider) Resume() {\n    this.IsPaused = false\n}\n\nfunc (this *Spider) Stop() {\n    this.IsStopped = true\n}\n\n\/\/ Check if all tasks have been processed.\nfunc (this *Spider) IsFinished() bool {\n    return this.Stats[PENDING] == 0 && this.Stats[WORKING] == 0\n}\n\n\/\/ Add tasks from uri.\nfunc (this *Spider) AddUri(uris ...string) *Spider {\n    for _, uri := range uris {\n        this.AddTask(NewTask(uri))\n    }\n\n    return this\n}\n\n\/\/ Add a task to queue\nfunc (this *Spider) AddTask(task *Task) *Spider {\n    task.Spider = this\n    this.m.Lock()\n    this.tasks = append(this.tasks, task)\n    this.m.Unlock()\n\n    this.statsLock.Lock()\n    this.Stats[PENDING]++\n    this.statsLock.Unlock()\n\n    return this\n}\n\n\/\/ Mark a task as failed.\nfunc (this *Spider) FailTask(task *Task, reason interface{}) {\n    task.Status = FAILED\n\n    this.statsLock.Lock()\n    this.Stats[FAILED]++\n    this.Stats[WORKING]--\n    this.statsLock.Unlock()\n\n    log.Println(\"[WARN] Task failed: \", task.Uri, \"\\t\", reason)\n}\n\n\/\/ Mark a task as done.\nfunc (this *Spider) DoneTask(task *Task) {\n    task.Status = DONE\n    this.statsLock.Lock()\n    this.Stats[DONE]++\n    this.Stats[WORKING]--\n    this.statsLock.Unlock()\n\n    if this.IsDebug {\n        log.Println(\"[DEBUG] Task done: \", task.Uri)\n    }\n}\n\n\/\/ Mark a task as ignored.\nfunc (this *Spider) IgnoreTask(task *Task, reason interface{}) {\n    task.Status = IGNORED\n\n    this.statsLock.Lock()\n    this.Stats[IGNORED]++\n    this.Stats[WORKING]--\n    this.statsLock.Unlock()\n\n    if this.IsDebug {\n        log.Println(\"[DEBUG] Task ignored: \", task.Uri, \"\\t\", reason)\n    }\n}\n\n\/\/ Mark a task as started.\nfunc (this *Spider) StartTask(task *Task) {\n    task.Status = WORKING\n\n    this.statsLock.Lock()\n    this.Stats[WORKING]++\n    this.Stats[PENDING]--\n    this.statsLock.Unlock()\n\n    if this.IsDebug {\n        log.Println(\"[DEBUG] Task started: \", task.Uri)\n    }\n}\n\n\/\/ Register events\nfunc (this *Spider) On(e int, f Listener) *Spider {\n    this.events[e] = append(this.events[e], f)\n\n    return this\n}\n\n\/\/ Trigger an event\nfunc (this *Spider) Trigger(e int, t *Task) {\n    if events, ok := this.events[e]; ok {\n        for _, e := range events {\n            e(this, t)\n        }\n    }\n}<|endoftext|>"}
{"text":"<commit_before>package cli\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"os\/signal\"\n\t\"strings\"\n\t\"syscall\"\n\n\t\"github.com\/spf13\/cobra\"\n\n\t\"github.com\/datawire\/telepresence2\/pkg\/client\"\n\tmanager \"github.com\/datawire\/telepresence2\/pkg\/rpc\"\n\t\"github.com\/datawire\/telepresence2\/pkg\/rpc\/connector\"\n)\n\n\/\/ runner contains all parameters needed in order to run an intercepted command.\ntype runner struct {\n\tconnector.ConnectRequest\n\tmanager.CreateInterceptRequest\n\tDNS             string\n\tFallback        string\n\tRemoveIntercept string\n\tList            bool\n\tNoWait          bool\n\tQuit            bool\n\tStatus          bool\n\tVersion         bool\n}\n\n\/\/ run will ensure that an intercept is in place and then execute the command given by args[0]\n\/\/ and the arguments starting at args[1:].\nfunc (p *runner) run(cmd *cobra.Command, args []string) error {\n\tswitch {\n\tcase p.List:\n\t\treturn listIntercepts(cmd, []string{})\n\tcase p.Quit:\n\t\treturn quit(cmd, []string{})\n\tcase p.Status:\n\t\treturn status(cmd, []string{})\n\tcase p.RemoveIntercept != \"\":\n\t\treturn removeIntercept(cmd, []string{p.RemoveIntercept})\n\tcase p.Version:\n\t\treturn printVersion(cmd, []string{})\n\t}\n\n\tdoWithResource := func(context string) error {\n\t\tswitch {\n\t\tcase p.NoWait:\n\t\t\treturn nil\n\t\tcase len(args) == 0:\n\t\t\treturn p.startSubshell(cmd, context)\n\t\tdefault:\n\t\t\treturn start(args[0], args[1:], true, cmd.InOrStdin(), cmd.OutOrStdout(), cmd.ErrOrStderr())\n\t\t}\n\t}\n\n\tif p.CreateInterceptRequest.InterceptSpec.Name != \"\" {\n\t\tif err := prepareIntercept(&p.CreateInterceptRequest); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn p.runWithIntercept(cmd, func(is *interceptState) error { return doWithResource(is.cs.info.ClusterContext) })\n\t}\n\treturn p.runWithConnector(cmd, func(cs *connectorState) error { return doWithResource(cs.info.ClusterContext) })\n}\n\nfunc (p *runner) startSubshell(cmd *cobra.Command, ctx string) error {\n\texe := os.Getenv(\"SHELL\")\n\tvar envArg string\n\tvar args []string\n\tif strings.HasSuffix(exe, \"\/zsh\") {\n\t\t\/\/ TODO: Find a way to alter zsh prompt. Not sure it's possible since the option\n\t\t\/\/  prompt_subst must be set for prompt substitution to take place. The only way\n\t\t\/\/  to set it is from files being sourced when the command starts. If that is\n\t\t\/\/  enabled (and it really should be, it's very common), then the PS1 passed from\n\t\t\/\/  here is overwritten.\n\t\texe = \"\/bin\/bash\"\n\t}\n\tenvArg = fmt.Sprintf(`PROMPT_COMMAND=export PS1=\"@%s $PS1\";unset PROMPT_COMMAND`, ctx)\n\targs = []string{\"-i\"}\n\tout := cmd.OutOrStdout()\n\tfmt.Fprintf(out, \"Starting a %s subshell\\n\", exe)\n\treturn start(exe, args, true, cmd.InOrStdin(), out, cmd.ErrOrStderr(), envArg)\n}\n\nfunc (p *runner) runWithDaemon(cmd *cobra.Command, f func(ds *daemonState) error) error {\n\tds, err := newDaemonState(cmd, p.DNS, p.Fallback)\n\tif err != nil && err != errDaemonIsNotRunning {\n\t\treturn err\n\t}\n\treturn client.WithEnsuredState(ds, p.NoWait, func() error { return f(ds) })\n}\n\nfunc (p *runner) runWithConnector(cmd *cobra.Command, f func(cs *connectorState) error) error {\n\treturn p.runWithDaemon(cmd, func(ds *daemonState) error {\n\t\tp.InterceptEnabled = true\n\t\tcs, err := newConnectorState(ds.grpc, &p.ConnectRequest, cmd)\n\t\tif err != nil && err != errConnectorIsNotRunning {\n\t\t\treturn err\n\t\t}\n\t\treturn client.WithEnsuredState(cs, p.NoWait, func() error { return f(cs) })\n\t})\n}\n\nfunc (p *runner) runWithIntercept(cmd *cobra.Command, f func(is *interceptState) error) error {\n\treturn p.runWithConnector(cmd, func(cs *connectorState) error {\n\t\tis := newInterceptState(cs, &p.CreateInterceptRequest, cmd)\n\t\treturn client.WithEnsuredState(is, p.NoWait, func() error { return f(is) })\n\t})\n}\n\nfunc runAsRoot(exe string, args []string) error {\n\tif os.Geteuid() != 0 {\n\t\tif err := exec.Command(\"sudo\", \"-n\", \"true\").Run(); err != nil {\n\t\t\tfmt.Printf(\"Need root privileges to run %q\\n\", client.ShellString(exe, args))\n\t\t\tif err = exec.Command(\"sudo\", \"true\").Run(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\targs = append([]string{\"-n\", \"-E\", exe}, args...)\n\t\texe = \"sudo\"\n\t}\n\treturn start(exe, args, false, nil, nil, nil)\n}\n\nfunc start(exe string, args []string, wait bool, stdin io.Reader, stdout, stderr io.Writer, env ...string) error {\n\tcmd := exec.Command(exe, args...)\n\tcmd.Stdout = stdout\n\tcmd.Stderr = stderr\n\tcmd.Stdin = stdin\n\tif len(env) > 0 {\n\t\tcmd.Env = append(os.Environ(), env...)\n\t}\n\tif !wait {\n\t\t\/\/ Process must live in a process group of its own to prevent\n\t\t\/\/ getting affected by <ctrl-c> in the terminal\n\t\tcmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}\n\t}\n\n\tvar err error\n\tif err = cmd.Start(); err != nil {\n\t\treturn fmt.Errorf(\"%s: %v\", client.ShellString(exe, args), err)\n\t}\n\tif !wait {\n\t\t_ = cmd.Process.Release()\n\t\treturn nil\n\t}\n\n\t\/\/ Ensure that SIGINT and SIGTERM are propagated to the child process\n\tsigCh := make(chan os.Signal, 1)\n\tsignal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)\n\tgo func() {\n\t\tsig := <-sigCh\n\t\tif sig == nil {\n\t\t\treturn\n\t\t}\n\t\t_ = cmd.Process.Signal(sig)\n\t}()\n\ts, err := cmd.Process.Wait()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%s: %v\", client.ShellString(exe, args), err)\n\t}\n\n\tsigCh <- nil\n\texitCode := s.ExitCode()\n\tif exitCode != 0 {\n\t\treturn fmt.Errorf(\"%s %s: exited with %d\", exe, strings.Join(args, \" \"), exitCode)\n\t}\n\treturn nil\n}\n<commit_msg>Remove code that attempts to change prompt for subshell<commit_after>package cli\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"os\/signal\"\n\t\"strings\"\n\t\"syscall\"\n\n\t\"github.com\/spf13\/cobra\"\n\n\t\"github.com\/datawire\/telepresence2\/pkg\/client\"\n\tmanager \"github.com\/datawire\/telepresence2\/pkg\/rpc\"\n\t\"github.com\/datawire\/telepresence2\/pkg\/rpc\/connector\"\n)\n\n\/\/ runner contains all parameters needed in order to run an intercepted command.\ntype runner struct {\n\tconnector.ConnectRequest\n\tmanager.CreateInterceptRequest\n\tDNS             string\n\tFallback        string\n\tRemoveIntercept string\n\tList            bool\n\tNoWait          bool\n\tQuit            bool\n\tStatus          bool\n\tVersion         bool\n}\n\n\/\/ run will ensure that an intercept is in place and then execute the command given by args[0]\n\/\/ and the arguments starting at args[1:].\nfunc (p *runner) run(cmd *cobra.Command, args []string) error {\n\tswitch {\n\tcase p.List:\n\t\treturn listIntercepts(cmd, []string{})\n\tcase p.Quit:\n\t\treturn quit(cmd, []string{})\n\tcase p.Status:\n\t\treturn status(cmd, []string{})\n\tcase p.RemoveIntercept != \"\":\n\t\treturn removeIntercept(cmd, []string{p.RemoveIntercept})\n\tcase p.Version:\n\t\treturn printVersion(cmd, []string{})\n\t}\n\n\tdoWithResource := func(context string) error {\n\t\tswitch {\n\t\tcase p.NoWait:\n\t\t\treturn nil\n\t\tcase len(args) == 0:\n\t\t\treturn p.startSubshell(cmd, context)\n\t\tdefault:\n\t\t\treturn start(args[0], args[1:], true, cmd.InOrStdin(), cmd.OutOrStdout(), cmd.ErrOrStderr())\n\t\t}\n\t}\n\n\tif p.CreateInterceptRequest.InterceptSpec.Name != \"\" {\n\t\tif err := prepareIntercept(&p.CreateInterceptRequest); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn p.runWithIntercept(cmd, func(is *interceptState) error { return doWithResource(is.cs.info.ClusterContext) })\n\t}\n\treturn p.runWithConnector(cmd, func(cs *connectorState) error { return doWithResource(cs.info.ClusterContext) })\n}\n\nfunc (p *runner) startSubshell(cmd *cobra.Command, ctx string) error {\n\texe := os.Getenv(\"SHELL\")\n\tout := cmd.OutOrStdout()\n\tfmt.Fprintf(out, \"Starting a %s subshell\\n\", exe)\n\treturn start(exe, []string{\"i\"}, true, cmd.InOrStdin(), out, cmd.ErrOrStderr())\n}\n\nfunc (p *runner) runWithDaemon(cmd *cobra.Command, f func(ds *daemonState) error) error {\n\tds, err := newDaemonState(cmd, p.DNS, p.Fallback)\n\tif err != nil && err != errDaemonIsNotRunning {\n\t\treturn err\n\t}\n\treturn client.WithEnsuredState(ds, p.NoWait, func() error { return f(ds) })\n}\n\nfunc (p *runner) runWithConnector(cmd *cobra.Command, f func(cs *connectorState) error) error {\n\treturn p.runWithDaemon(cmd, func(ds *daemonState) error {\n\t\tp.InterceptEnabled = true\n\t\tcs, err := newConnectorState(ds.grpc, &p.ConnectRequest, cmd)\n\t\tif err != nil && err != errConnectorIsNotRunning {\n\t\t\treturn err\n\t\t}\n\t\treturn client.WithEnsuredState(cs, p.NoWait, func() error { return f(cs) })\n\t})\n}\n\nfunc (p *runner) runWithIntercept(cmd *cobra.Command, f func(is *interceptState) error) error {\n\treturn p.runWithConnector(cmd, func(cs *connectorState) error {\n\t\tis := newInterceptState(cs, &p.CreateInterceptRequest, cmd)\n\t\treturn client.WithEnsuredState(is, p.NoWait, func() error { return f(is) })\n\t})\n}\n\nfunc runAsRoot(exe string, args []string) error {\n\tif os.Geteuid() != 0 {\n\t\tif err := exec.Command(\"sudo\", \"-n\", \"true\").Run(); err != nil {\n\t\t\tfmt.Printf(\"Need root privileges to run %q\\n\", client.ShellString(exe, args))\n\t\t\tif err = exec.Command(\"sudo\", \"true\").Run(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\targs = append([]string{\"-n\", \"-E\", exe}, args...)\n\t\texe = \"sudo\"\n\t}\n\treturn start(exe, args, false, nil, nil, nil)\n}\n\nfunc start(exe string, args []string, wait bool, stdin io.Reader, stdout, stderr io.Writer, env ...string) error {\n\tcmd := exec.Command(exe, args...)\n\tcmd.Stdout = stdout\n\tcmd.Stderr = stderr\n\tcmd.Stdin = stdin\n\tif len(env) > 0 {\n\t\tcmd.Env = append(os.Environ(), env...)\n\t}\n\tif !wait {\n\t\t\/\/ Process must live in a process group of its own to prevent\n\t\t\/\/ getting affected by <ctrl-c> in the terminal\n\t\tcmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}\n\t}\n\n\tvar err error\n\tif err = cmd.Start(); err != nil {\n\t\treturn fmt.Errorf(\"%s: %v\", client.ShellString(exe, args), err)\n\t}\n\tif !wait {\n\t\t_ = cmd.Process.Release()\n\t\treturn nil\n\t}\n\n\t\/\/ Ensure that SIGINT and SIGTERM are propagated to the child process\n\tsigCh := make(chan os.Signal, 1)\n\tsignal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)\n\tgo func() {\n\t\tsig := <-sigCh\n\t\tif sig == nil {\n\t\t\treturn\n\t\t}\n\t\t_ = cmd.Process.Signal(sig)\n\t}()\n\ts, err := cmd.Process.Wait()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%s: %v\", client.ShellString(exe, args), err)\n\t}\n\n\tsigCh <- nil\n\texitCode := s.ExitCode()\n\tif exitCode != 0 {\n\t\treturn fmt.Errorf(\"%s %s: exited with %d\", exe, strings.Join(args, \" \"), exitCode)\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package network\n\nimport (\n\t\"github.com\/name5566\/leaf\/log\"\n\t\"net\"\n\t\"sync\"\n)\n\ntype TCPServer struct {\n\tAddr            string\n\tMaxConnNum      int\n\tPendingWriteNum int\n\tNewAgent        func(*TCPConn) Agent\n\tln              net.Listener\n\tconns           ConnSet\n\tmutexConns      sync.Mutex\n\twg              sync.WaitGroup\n\tcloseFlag       bool\n\n\t\/\/ msg parser\n\tLenMsgLen    int\n\tMinMsgLen    uint32\n\tMaxMsgLen    uint32\n\tLittleEndian bool\n\tmsgParser    *MsgParser\n}\n\nfunc (server *TCPServer) Start() {\n\tserver.init()\n\tgo server.run()\n}\n\nfunc (server *TCPServer) init() {\n\tln, err := net.Listen(\"tcp\", server.Addr)\n\tif err != nil {\n\t\tlog.Fatal(\"%v\", err)\n\t}\n\n\tif server.MaxConnNum <= 0 {\n\t\tserver.MaxConnNum = 100\n\t\tlog.Release(\"invalid MaxConnNum, reset to %v\", server.MaxConnNum)\n\t}\n\tif server.PendingWriteNum <= 0 {\n\t\tserver.PendingWriteNum = 100\n\t\tlog.Release(\"invalid PendingWriteNum, reset to %v\", server.PendingWriteNum)\n\t}\n\tif server.NewAgent == nil {\n\t\tlog.Fatal(\"NewAgent must not be nil\")\n\t}\n\n\tserver.ln = ln\n\tserver.conns = make(ConnSet)\n\tserver.closeFlag = false\n\n\t\/\/ msg parser\n\tmsgParser := NewMsgParser()\n\tmsgParser.SetMsgLen(server.LenMsgLen, server.MinMsgLen, server.MaxMsgLen)\n\tmsgParser.SetByteOrder(server.LittleEndian)\n\tserver.msgParser = msgParser\n}\n\nfunc (server *TCPServer) run() {\n\tfor {\n\t\tconn, err := server.ln.Accept()\n\t\tif err != nil {\n\t\t\tif server.closeFlag {\n\t\t\t\treturn\n\t\t\t} else {\n\t\t\t\tlog.Error(\"accept error: %v\", err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tserver.mutexConns.Lock()\n\t\tif len(server.conns) >= server.MaxConnNum {\n\t\t\tserver.mutexConns.Unlock()\n\t\t\tconn.Close()\n\t\t\tlog.Debug(\"too many connections\")\n\t\t\tcontinue\n\t\t}\n\t\tserver.conns[conn] = struct{}{}\n\t\tserver.mutexConns.Unlock()\n\n\t\tserver.wg.Add(1)\n\n\t\ttcpConn := newTCPConn(conn, server.PendingWriteNum, server.msgParser)\n\t\tagent := server.NewAgent(tcpConn)\n\t\tgo func() {\n\t\t\tagent.Run()\n\n\t\t\t\/\/ cleanup\n\t\t\ttcpConn.Close()\n\t\t\tserver.mutexConns.Lock()\n\t\t\tdelete(server.conns, conn)\n\t\t\tserver.mutexConns.Unlock()\n\t\t\tagent.OnClose()\n\n\t\t\tserver.wg.Done()\n\t\t}()\n\t}\n}\n\nfunc (server *TCPServer) Close() {\n\tserver.closeFlag = true\n\tserver.ln.Close()\n\n\tserver.mutexConns.Lock()\n\tfor conn := range server.conns {\n\t\tconn.Close()\n\t}\n\tserver.conns = make(ConnSet)\n\tserver.mutexConns.Unlock()\n\n\tserver.wg.Wait()\n}\n<commit_msg>bug fix on Accept<commit_after>package network\n\nimport (\n\t\"github.com\/name5566\/leaf\/log\"\n\t\"net\"\n\t\"sync\"\n)\n\ntype TCPServer struct {\n\tAddr            string\n\tMaxConnNum      int\n\tPendingWriteNum int\n\tNewAgent        func(*TCPConn) Agent\n\tln              net.Listener\n\tconns           ConnSet\n\tmutexConns      sync.Mutex\n\twg              sync.WaitGroup\n\n\t\/\/ msg parser\n\tLenMsgLen    int\n\tMinMsgLen    uint32\n\tMaxMsgLen    uint32\n\tLittleEndian bool\n\tmsgParser    *MsgParser\n}\n\nfunc (server *TCPServer) Start() {\n\tserver.init()\n\tgo server.run()\n}\n\nfunc (server *TCPServer) init() {\n\tln, err := net.Listen(\"tcp\", server.Addr)\n\tif err != nil {\n\t\tlog.Fatal(\"%v\", err)\n\t}\n\n\tif server.MaxConnNum <= 0 {\n\t\tserver.MaxConnNum = 100\n\t\tlog.Release(\"invalid MaxConnNum, reset to %v\", server.MaxConnNum)\n\t}\n\tif server.PendingWriteNum <= 0 {\n\t\tserver.PendingWriteNum = 100\n\t\tlog.Release(\"invalid PendingWriteNum, reset to %v\", server.PendingWriteNum)\n\t}\n\tif server.NewAgent == nil {\n\t\tlog.Fatal(\"NewAgent must not be nil\")\n\t}\n\n\tserver.ln = ln\n\tserver.conns = make(ConnSet)\n\n\t\/\/ msg parser\n\tmsgParser := NewMsgParser()\n\tmsgParser.SetMsgLen(server.LenMsgLen, server.MinMsgLen, server.MaxMsgLen)\n\tmsgParser.SetByteOrder(server.LittleEndian)\n\tserver.msgParser = msgParser\n}\n\nfunc (server *TCPServer) run() {\n\tfor {\n\t\tconn, err := server.ln.Accept()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tserver.mutexConns.Lock()\n\t\tif len(server.conns) >= server.MaxConnNum {\n\t\t\tserver.mutexConns.Unlock()\n\t\t\tconn.Close()\n\t\t\tlog.Debug(\"too many connections\")\n\t\t\tcontinue\n\t\t}\n\t\tserver.conns[conn] = struct{}{}\n\t\tserver.mutexConns.Unlock()\n\n\t\tserver.wg.Add(1)\n\n\t\ttcpConn := newTCPConn(conn, server.PendingWriteNum, server.msgParser)\n\t\tagent := server.NewAgent(tcpConn)\n\t\tgo func() {\n\t\t\tagent.Run()\n\n\t\t\t\/\/ cleanup\n\t\t\ttcpConn.Close()\n\t\t\tserver.mutexConns.Lock()\n\t\t\tdelete(server.conns, conn)\n\t\t\tserver.mutexConns.Unlock()\n\t\t\tagent.OnClose()\n\n\t\t\tserver.wg.Done()\n\t\t}()\n\t}\n}\n\nfunc (server *TCPServer) Close() {\n\tserver.ln.Close()\n\n\tserver.mutexConns.Lock()\n\tfor conn := range server.conns {\n\t\tconn.Close()\n\t}\n\tserver.conns = make(ConnSet)\n\tserver.mutexConns.Unlock()\n\n\tserver.wg.Wait()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ File: taorpc.go\n\/\/ Author: Kevin Walsh <kwalsh@holycross.edu>\n\/\/ Description: Support for RPC from hosted program to host Tao.\n\/\/\n\/\/ Copyright (c) 2013, Google Inc.  All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage tao\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"math\"\n\t\"net\/rpc\"\n\t\"strings\"\n\n\t\"code.google.com\/p\/goprotobuf\/proto\"\n\n\t\"cloudproxy\/util\"\n\t\"cloudproxy\/util\/protorpc\"\n)\n\nvar opRPCName = map[string]string{\n\t\"Tao.GetRandomBytes\":  \"TAO_RPC_GET_RANDOM_BYTES\",\n\t\"Tao.Seal\":            \"TAO_RPC_SEAL\",\n\t\"Tao.Unseal\":          \"TAO_RPC_UNSEAL\",\n\t\"Tao.Attest\":          \"TAO_RPC_ATTEST\",\n\t\"Tao.GetTaoName\":      \"TAO_RPC_GET_TAO_NAME\",\n\t\"Tao.ExtendTaoName\":   \"TAO_RPC_EXTEND_TAO_NAME\",\n\t\"Tao.GetSharedSecret\": \"TAO_RPC_GET_SHARED_SECRET\",\n}\n\nvar opGoName = make(map[string]string)\n\nfunc init() {\n\tfor goName, rpcName := range opRPCName {\n\t\topGoName[rpcName] = goName\n\t}\n}\n\n\/\/ Convert string \"Tao.FooBar\" into integer TaoRPCOperation_TAO_RPC_FOO_BAR.\nfunc goToRPC(m string) (TaoRPCOperation, error) {\n\top := TaoRPCOperation(TaoRPCOperation_value[opRPCName[m]])\n\tif op == TaoRPCOperation(0) {\n\t\treturn op, protorpc.ErrBadRequestType\n\t}\n\treturn op, nil\n}\n\n\/\/ Convert integer TaoRPCOperation_TAO_RPC_FOO_BAR into string \"Tao.FooBar\".\nfunc rpcToGo(op TaoRPCOperation) (string, error) {\n\ts := opGoName[TaoRPCOperation_name[int32(op)]]\n\tif s == \"\" {\n\t\treturn \"\", protorpc.ErrBadRequestType\n\t}\n\treturn s, nil\n}\n\ntype taoMux struct{}\n\nfunc (taoMux) SetRequestHeader(req proto.Message, servicemethod string, seq uint64) error {\n\tm, ok := req.(*TaoRPCRequest)\n\tif !ok || m == nil {\n\t\treturn protorpc.ErrBadRequestType\n\t}\n\trpc, err := goToRPC(servicemethod)\n\tif err != nil {\n\t\treturn err\n\t}\n\tm.Rpc = &rpc\n\tm.Seq = &seq\n\treturn nil\n}\n\nfunc (taoMux) SetResponseHeader(req proto.Message, servicemethod string, seq uint64) error {\n\tm, ok := req.(*TaoRPCResponse)\n\tif !ok || m == nil {\n\t\treturn protorpc.ErrBadResponseType\n\t}\n\trpc, err := goToRPC(servicemethod)\n\tif err != nil {\n\t\treturn err\n\t}\n\tm.Rpc = &rpc\n\tm.Seq = &seq\n\treturn nil\n}\n\nfunc (taoMux) GetServiceMethod(number uint64) (string, error) {\n\treturn rpcToGo(TaoRPCOperation(int32(number)))\n}\n\n\/\/ TaoRPC sends requests between this hosted program and the host Tao.\ntype TaoRPC struct {\n\trpc *rpc.Client\n}\n\nfunc DeserializeTaoRPC(s string) (*TaoRPC, error) {\n\tif s == \"\" {\n\t\treturn nil, errors.New(\"taorpc: missing host Tao spec\" +\n\t\t\t\" (ensure $\" + HostTaoEnvVar + \" is set)\")\n\t}\n\tr := strings.TrimPrefix(s, \"tao::TaoRPC+\")\n\tif r == s {\n\t\treturn nil, errors.New(\"taorpc: unrecognized $\" + HostTaoEnvVar + \" string \" + s)\n\t}\n\tms, err := util.DeserializeFDMessageStream(r)\n\tif err != nil {\n\t\treturn nil, errors.New(\"taorpc: unrecognized $\" + HostTaoEnvVar + \" string \" + s +\n\t\t\t\" (\" + err.Error() + \")\")\n\t}\n\treturn &TaoRPC{protorpc.NewClient(ms, taoMux{})}, nil\n}\n\ntype expectedResponse int\n\nconst (\n\twantNothing                  = 0\n\twantData    expectedResponse = 1 << iota\n\twantPolicy\n)\n\nvar ErrMalformedResponse = errors.New(\"taorpc: malformed response\")\n\nfunc (t *TaoRPC) call(method string, r *TaoRPCRequest, e expectedResponse) (data []byte, policy string, err error) {\n\ts := new(TaoRPCResponse)\n\terr = t.rpc.Call(method, r, s)\n\tif err != nil {\n\t\treturn\n\t}\n\tif s.Error != nil {\n\t\terr = errors.New(*s.Error)\n\t\treturn\n\t}\n\tif (s.Data != nil) != (e&wantData != 0) ||\n\t\t(s.Policy != nil) != (e&wantPolicy != 0) {\n\t\terr = ErrMalformedResponse\n\t\treturn\n\t}\n\tif s.Data != nil {\n\t\tdata = s.Data\n\t}\n\tif s.Policy != nil {\n\t\tpolicy = *s.Policy\n\t}\n\treturn\n}\n\nfunc (t *TaoRPC) GetTaoName() (string, error) {\n\tr := &TaoRPCRequest{}\n\tdata, _, err := t.call(\"Tao.GetTaoName\", r, wantData)\n\treturn string(data), err\n}\n\nfunc (t *TaoRPC) ExtendTaoName(subprin string) error {\n\tr := &TaoRPCRequest{Data: []byte(subprin)}\n\t_, _, err := t.call(\"Tao.ExtendTaoName\", r, wantNothing)\n\treturn err\n}\n\ntype taoRandReader TaoRPC\n\nfunc (t *taoRandReader) Read(p []byte) (n int, err error) {\n\tbytes, err := (*TaoRPC)(t).GetRandomBytes(len(p))\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tcopy(p, bytes)\n\treturn len(p), nil\n}\n\n\/\/ TODO(kwalsh) Can Rand be made generic, or does it need to be defined for the\n\/\/ concrete type TaoRPC?\nfunc (t *TaoRPC) Rand() io.Reader {\n\treturn (*taoRandReader)(t)\n}\n\nfunc (t *TaoRPC) GetRandomBytes(n int) ([]byte, error) {\n\tif n > math.MaxUint32 {\n\t\treturn nil, errors.New(\"taorpc: request for too many random bytes\")\n\t}\n\tr := &TaoRPCRequest{Size: proto.Int32(int32(n))}\n\tbytes, _, err := t.call(\"Tao.GetRandomBytes\", r, wantData)\n\treturn bytes, err\n}\n\nfunc (t *TaoRPC) GetSharedSecret(n int, policy string) ([]byte, error) {\n\tif n > math.MaxUint32 {\n\t\treturn nil, errors.New(\"taorpc: request for too many secret bytes\")\n\t}\n\tr := &TaoRPCRequest{Size: proto.Int32(int32(n)), Policy: proto.String(policy)}\n\tbytes, _, err := t.call(\"Tao.GetSharedSecret\", r, wantData)\n\treturn bytes, err\n}\n\nfunc (t *TaoRPC) Attest(stmt *Statement) (*Attestation, error) {\n\tdata, err := proto.Marshal(stmt)\n\tif _, ok := err.(*proto.RequiredNotSetError); err != nil && !ok {\n\t\treturn nil, err\n\t}\n\tr := &TaoRPCRequest{Data: data}\n\tbytes, _, err := t.call(\"Tao.Attest\", r, wantData)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar a Attestation\n\terr = proto.Unmarshal(bytes, &a)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &a, nil\n}\n\nfunc (t *TaoRPC) Seal(data []byte, policy string) (sealed []byte, err error) {\n\tr := &TaoRPCRequest{Data: data, Policy: proto.String(policy)}\n\tsealed, _, err = t.call(\"Tao.Seal\", r, wantData)\n\treturn\n}\n\nfunc (t *TaoRPC) Unseal(sealed []byte) (data []byte, policy string, err error) {\n\tr := &TaoRPCRequest{Data: sealed}\n\tdata, policy, err = t.call(\"Tao.Unseal\", r, wantData|wantPolicy)\n\treturn\n}\n<commit_msg>taorpc: missing type on const<commit_after>\/\/ File: taorpc.go\n\/\/ Author: Kevin Walsh <kwalsh@holycross.edu>\n\/\/ Description: Support for RPC from hosted program to host Tao.\n\/\/\n\/\/ Copyright (c) 2013, Google Inc.  All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage tao\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"math\"\n\t\"net\/rpc\"\n\t\"strings\"\n\n\t\"code.google.com\/p\/goprotobuf\/proto\"\n\n\t\"cloudproxy\/util\"\n\t\"cloudproxy\/util\/protorpc\"\n)\n\nvar opRPCName = map[string]string{\n\t\"Tao.GetRandomBytes\":  \"TAO_RPC_GET_RANDOM_BYTES\",\n\t\"Tao.Seal\":            \"TAO_RPC_SEAL\",\n\t\"Tao.Unseal\":          \"TAO_RPC_UNSEAL\",\n\t\"Tao.Attest\":          \"TAO_RPC_ATTEST\",\n\t\"Tao.GetTaoName\":      \"TAO_RPC_GET_TAO_NAME\",\n\t\"Tao.ExtendTaoName\":   \"TAO_RPC_EXTEND_TAO_NAME\",\n\t\"Tao.GetSharedSecret\": \"TAO_RPC_GET_SHARED_SECRET\",\n}\n\nvar opGoName = make(map[string]string)\n\nfunc init() {\n\tfor goName, rpcName := range opRPCName {\n\t\topGoName[rpcName] = goName\n\t}\n}\n\n\/\/ Convert string \"Tao.FooBar\" into integer TaoRPCOperation_TAO_RPC_FOO_BAR.\nfunc goToRPC(m string) (TaoRPCOperation, error) {\n\top := TaoRPCOperation(TaoRPCOperation_value[opRPCName[m]])\n\tif op == TaoRPCOperation(0) {\n\t\treturn op, protorpc.ErrBadRequestType\n\t}\n\treturn op, nil\n}\n\n\/\/ Convert integer TaoRPCOperation_TAO_RPC_FOO_BAR into string \"Tao.FooBar\".\nfunc rpcToGo(op TaoRPCOperation) (string, error) {\n\ts := opGoName[TaoRPCOperation_name[int32(op)]]\n\tif s == \"\" {\n\t\treturn \"\", protorpc.ErrBadRequestType\n\t}\n\treturn s, nil\n}\n\ntype taoMux struct{}\n\nfunc (taoMux) SetRequestHeader(req proto.Message, servicemethod string, seq uint64) error {\n\tm, ok := req.(*TaoRPCRequest)\n\tif !ok || m == nil {\n\t\treturn protorpc.ErrBadRequestType\n\t}\n\trpc, err := goToRPC(servicemethod)\n\tif err != nil {\n\t\treturn err\n\t}\n\tm.Rpc = &rpc\n\tm.Seq = &seq\n\treturn nil\n}\n\nfunc (taoMux) SetResponseHeader(req proto.Message, servicemethod string, seq uint64) error {\n\tm, ok := req.(*TaoRPCResponse)\n\tif !ok || m == nil {\n\t\treturn protorpc.ErrBadResponseType\n\t}\n\trpc, err := goToRPC(servicemethod)\n\tif err != nil {\n\t\treturn err\n\t}\n\tm.Rpc = &rpc\n\tm.Seq = &seq\n\treturn nil\n}\n\nfunc (taoMux) GetServiceMethod(number uint64) (string, error) {\n\treturn rpcToGo(TaoRPCOperation(int32(number)))\n}\n\n\/\/ TaoRPC sends requests between this hosted program and the host Tao.\ntype TaoRPC struct {\n\trpc *rpc.Client\n}\n\nfunc DeserializeTaoRPC(s string) (*TaoRPC, error) {\n\tif s == \"\" {\n\t\treturn nil, errors.New(\"taorpc: missing host Tao spec\" +\n\t\t\t\" (ensure $\" + HostTaoEnvVar + \" is set)\")\n\t}\n\tr := strings.TrimPrefix(s, \"tao::TaoRPC+\")\n\tif r == s {\n\t\treturn nil, errors.New(\"taorpc: unrecognized $\" + HostTaoEnvVar + \" string \" + s)\n\t}\n\tms, err := util.DeserializeFDMessageStream(r)\n\tif err != nil {\n\t\treturn nil, errors.New(\"taorpc: unrecognized $\" + HostTaoEnvVar + \" string \" + s +\n\t\t\t\" (\" + err.Error() + \")\")\n\t}\n\treturn &TaoRPC{protorpc.NewClient(ms, taoMux{})}, nil\n}\n\ntype expectedResponse int\n\nconst (\n\twantNothing expectedResponse = 0\n\twantData    expectedResponse = 1 << iota\n\twantPolicy\n)\n\nvar ErrMalformedResponse = errors.New(\"taorpc: malformed response\")\n\nfunc (t *TaoRPC) call(method string, r *TaoRPCRequest, e expectedResponse) (data []byte, policy string, err error) {\n\ts := new(TaoRPCResponse)\n\terr = t.rpc.Call(method, r, s)\n\tif err != nil {\n\t\treturn\n\t}\n\tif s.Error != nil {\n\t\terr = errors.New(*s.Error)\n\t\treturn\n\t}\n\tif (s.Data != nil) != (e&wantData != 0) ||\n\t\t(s.Policy != nil) != (e&wantPolicy != 0) {\n\t\terr = ErrMalformedResponse\n\t\treturn\n\t}\n\tif s.Data != nil {\n\t\tdata = s.Data\n\t}\n\tif s.Policy != nil {\n\t\tpolicy = *s.Policy\n\t}\n\treturn\n}\n\nfunc (t *TaoRPC) GetTaoName() (string, error) {\n\tr := &TaoRPCRequest{}\n\tdata, _, err := t.call(\"Tao.GetTaoName\", r, wantData)\n\treturn string(data), err\n}\n\nfunc (t *TaoRPC) ExtendTaoName(subprin string) error {\n\tr := &TaoRPCRequest{Data: []byte(subprin)}\n\t_, _, err := t.call(\"Tao.ExtendTaoName\", r, wantNothing)\n\treturn err\n}\n\ntype taoRandReader TaoRPC\n\nfunc (t *taoRandReader) Read(p []byte) (n int, err error) {\n\tbytes, err := (*TaoRPC)(t).GetRandomBytes(len(p))\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tcopy(p, bytes)\n\treturn len(p), nil\n}\n\n\/\/ TODO(kwalsh) Can Rand be made generic, or does it need to be defined for the\n\/\/ concrete type TaoRPC?\nfunc (t *TaoRPC) Rand() io.Reader {\n\treturn (*taoRandReader)(t)\n}\n\nfunc (t *TaoRPC) GetRandomBytes(n int) ([]byte, error) {\n\tif n > math.MaxUint32 {\n\t\treturn nil, errors.New(\"taorpc: request for too many random bytes\")\n\t}\n\tr := &TaoRPCRequest{Size: proto.Int32(int32(n))}\n\tbytes, _, err := t.call(\"Tao.GetRandomBytes\", r, wantData)\n\treturn bytes, err\n}\n\nfunc (t *TaoRPC) GetSharedSecret(n int, policy string) ([]byte, error) {\n\tif n > math.MaxUint32 {\n\t\treturn nil, errors.New(\"taorpc: request for too many secret bytes\")\n\t}\n\tr := &TaoRPCRequest{Size: proto.Int32(int32(n)), Policy: proto.String(policy)}\n\tbytes, _, err := t.call(\"Tao.GetSharedSecret\", r, wantData)\n\treturn bytes, err\n}\n\nfunc (t *TaoRPC) Attest(stmt *Statement) (*Attestation, error) {\n\tdata, err := proto.Marshal(stmt)\n\tif _, ok := err.(*proto.RequiredNotSetError); err != nil && !ok {\n\t\treturn nil, err\n\t}\n\tr := &TaoRPCRequest{Data: data}\n\tbytes, _, err := t.call(\"Tao.Attest\", r, wantData)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar a Attestation\n\terr = proto.Unmarshal(bytes, &a)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &a, nil\n}\n\nfunc (t *TaoRPC) Seal(data []byte, policy string) (sealed []byte, err error) {\n\tr := &TaoRPCRequest{Data: data, Policy: proto.String(policy)}\n\tsealed, _, err = t.call(\"Tao.Seal\", r, wantData)\n\treturn\n}\n\nfunc (t *TaoRPC) Unseal(sealed []byte) (data []byte, policy string, err error) {\n\tr := &TaoRPCRequest{Data: sealed}\n\tdata, policy, err = t.call(\"Tao.Unseal\", r, wantData|wantPolicy)\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>e4354e54-2e56-11e5-9284-b827eb9e62be<commit_after><|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"flag\"\n\t\"gopkg.in\/fsnotify.v1\"\n\t\"io\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"sync\"\n)\n\nfunc main() {\n\td, err := os.Getwd()\n\tif err != nil {\n\t\td = \".\/\"\n\t}\n\n\tport := flag.String(\"http\", \":8081\", \"the listening port\")\n\tdir := flag.String(\"dir\", d, \"the working folder\")\n\tflag.Parse()\n\n\tcompiler := filepath.Join(*dir, \"compiler.jar\")\n\t_, err = os.Stat(compiler)\n\tcompilerMissing := os.IsNotExist(err)\n\n\tjsDir := filepath.Join(*dir, \"src\")\n\t_, err = os.Stat(jsDir)\n\tjsDirMissing := os.IsNotExist(err)\n\n\tlock := sync.Mutex{}\n\n\tif compilerMissing {\n\t\tlog.Println(\"Not found 'compiler.jar', please download it here: http:\/\/dl.google.com\/closure-compiler\/compiler-latest.zip\")\n\t} else if jsDirMissing {\n\t\tlog.Println(\"Not found 'src' dir\")\n\t} else {\n\t\twatcher, err := fsnotify.NewWatcher()\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tdefer watcher.Close()\n\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase event := <-watcher.Events:\n\t\t\t\t\t\/\/ call compile only for script change\n\t\t\t\t\tif event.Op != fsnotify.Chmod && event.Op != fsnotify.Rename {\n\t\t\t\t\t\tif ext := filepath.Ext(event.Name); ext != \".js\" && ext != \".json\" {\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tlock.Lock()\n\t\t\t\t\t\tlog.Println(\"Compiling script...\")\n\t\t\t\t\t\terr := compileScript(compiler, jsDir)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tlog.Println(\"Error compiling script:\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlog.Println(\"Done!\")\n\t\t\t\t\t\tlock.Unlock()\n\t\t\t\t\t}\n\t\t\t\tcase err := <-watcher.Errors:\n\t\t\t\t\tlog.Println(\"watcher error:\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\n\t\t\/\/ watch all sub-dir\n\t\terr = filepath.Walk(jsDir, func(path string, info os.FileInfo, err error) error {\n\t\t\tif info.IsDir() {\n\t\t\t\terr := watcher.Add(path)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\n\tlock.Lock()\n\terr = compileScript(compiler, jsDir)\n\tif err != nil {\n\t\tlog.Println(\"Error compiling script:\", err)\n\t} else {\n\t\tlog.Println(\"Compiling script at\", jsDir)\n\t}\n\tlock.Unlock()\n\n\tlog.Println(\"Serving client at http:\/\/localhost\" + *port)\n\tpanic(http.ListenAndServe(*port, http.FileServer(http.Dir(*dir))))\n}\n\nfunc compileScript(compiler, jsDir string) error {\n\targs := []string{\"-jar\", compiler, \"--language_in\", \"ECMASCRIPT5\"}\n\terr := filepath.Walk(filepath.Join(jsDir, \"app\"), func(path string, info os.FileInfo, err error) error {\n\t\tif filepath.Ext(path) == \".js\" {\n\t\t\targs = append(args, \"--js\", path)\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmd := exec.Command(\"java\", args...)\n\tvar out bytes.Buffer\n\tcmd.Stdout = &out\n\tvar er bytes.Buffer\n\tcmd.Stderr = &er\n\terr = cmd.Run()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ merge with lib file\n\tlibs := []string{}\n\tfilepath.Walk(filepath.Join(jsDir, \"lib\"), func(path string, info os.FileInfo, err error) error {\n\t\tif filepath.Ext(path) == \".js\" {\n\t\t\tlibs = append(libs, path)\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf, err := os.OpenFile(filepath.Join(jsDir, \"..\/js\/app.min.js\"), os.O_WRONLY, 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\tfor _, l := range libs {\n\t\tf2, err := os.Open(l)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error when open lib file:\", err)\n\t\t\tcontinue\n\t\t}\n\t\tdefer f2.Close()\n\n\t\t_, err = io.Copy(f, f2)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error when copy lib file content:\", err)\n\t\t} else {\n\t\t\tf.Write([]byte{10, 13})\n\t\t}\n\t}\n\n\t_, err = io.Copy(f, &out)\n\n\treturn err\n}\n<commit_msg>add debug flag<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"flag\"\n\t\"gopkg.in\/fsnotify.v1\"\n\t\"io\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"sync\"\n)\n\nfunc main() {\n\td, err := os.Getwd()\n\tif err != nil {\n\t\td = \".\/\"\n\t}\n\n\tport := flag.String(\"http\", \":8081\", \"the listening port\")\n\tdir := flag.String(\"dir\", d, \"the working folder\")\n\tdebug := flag.Bool(\"debug\", false, \"enable\/disable debuging mode\")\n\tflag.Parse()\n\n\tcompiler := filepath.Join(*dir, \"compiler.jar\")\n\t_, err = os.Stat(compiler)\n\tcompilerMissing := os.IsNotExist(err)\n\n\tjsDir := filepath.Join(*dir, \"src\")\n\t_, err = os.Stat(jsDir)\n\tjsDirMissing := os.IsNotExist(err)\n\n\tlock := sync.Mutex{}\n\n\tif compilerMissing {\n\t\tlog.Println(\"Not found 'compiler.jar', please download it here: http:\/\/dl.google.com\/closure-compiler\/compiler-latest.zip\")\n\t} else if jsDirMissing {\n\t\tlog.Println(\"Not found 'src' dir\")\n\t} else {\n\t\twatcher, err := fsnotify.NewWatcher()\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tdefer watcher.Close()\n\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase event := <-watcher.Events:\n\t\t\t\t\t\/\/ call compile only for script change\n\t\t\t\t\tif event.Op != fsnotify.Chmod && event.Op != fsnotify.Rename {\n\t\t\t\t\t\tif ext := filepath.Ext(event.Name); ext != \".js\" && ext != \".json\" {\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tlock.Lock()\n\t\t\t\t\t\tlog.Println(\"Compiling script...\")\n\t\t\t\t\t\terr := compileScript(compiler, jsDir, *debug)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tlog.Println(\"Error compiling script:\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlog.Println(\"Done!\")\n\t\t\t\t\t\tlock.Unlock()\n\t\t\t\t\t}\n\t\t\t\tcase err := <-watcher.Errors:\n\t\t\t\t\tlog.Println(\"watcher error:\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\n\t\t\/\/ watch all sub-dir\n\t\terr = filepath.Walk(jsDir, func(path string, info os.FileInfo, err error) error {\n\t\t\tif info.IsDir() {\n\t\t\t\terr := watcher.Add(path)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n\n\tlock.Lock()\n\terr = compileScript(compiler, jsDir, *debug)\n\tif err != nil {\n\t\tlog.Println(\"Error compiling script:\", err)\n\t} else {\n\t\tlog.Println(\"Compiling script at\", jsDir)\n\t}\n\tlock.Unlock()\n\n\tlog.Println(\"Serving client at http:\/\/localhost\" + *port)\n\tpanic(http.ListenAndServe(*port, http.FileServer(http.Dir(*dir))))\n}\n\nfunc compileScript(compiler, jsDir string, debug bool) error {\n\targs := []string{\"-jar\", compiler, \"--language_in\", \"ECMASCRIPT5\"}\n\tif debug {\n\t\targs = []string{\"-jar\", compiler, \"--language_in\", \"ECMASCRIPT5\", \"--formatting\", \"PRETTY_PRINT\", \"--compilation_level\", \"SIMPLE\"}\n\t}\n\terr := filepath.Walk(filepath.Join(jsDir, \"app\"), func(path string, info os.FileInfo, err error) error {\n\t\tif filepath.Ext(path) == \".js\" {\n\t\t\targs = append(args, \"--js\", path)\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmd := exec.Command(\"java\", args...)\n\tvar out bytes.Buffer\n\tcmd.Stdout = &out\n\tvar er bytes.Buffer\n\tcmd.Stderr = &er\n\terr = cmd.Run()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ merge with lib file\n\tlibs := []string{}\n\tfilepath.Walk(filepath.Join(jsDir, \"lib\"), func(path string, info os.FileInfo, err error) error {\n\t\tif filepath.Ext(path) == \".js\" {\n\t\t\tlibs = append(libs, path)\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf, err := os.OpenFile(filepath.Join(jsDir, \"..\/js\/app.min.js\"), os.O_WRONLY, 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\tfor _, l := range libs {\n\t\tf2, err := os.Open(l)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error when open lib file:\", err)\n\t\t\tcontinue\n\t\t}\n\t\tdefer f2.Close()\n\n\t\t_, err = io.Copy(f, f2)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error when copy lib file content:\", err)\n\t\t} else {\n\t\t\tf.Write([]byte{10, 13})\n\t\t}\n\t}\n\n\t_, err = io.Copy(f, &out)\n\n\treturn err\n}\n<|endoftext|>"}
{"text":"<commit_before>package ergo\n\ntype Ergo struct {\n\t*Route\n}\n\nfunc New(path string) *Ergo {\n\treturn &Ergo{\n\t\tRoute: NewRoute(path),\n\t}\n}\n\nfunc (e *Ergo) Schemes(s ...string) *Ergo {\n\tschemes(e, s)\n\treturn e\n}\n\nfunc (e *Ergo) Consumes(mimes ...string) *Ergo {\n\tconsumes(e, mimes)\n\treturn e\n}\n\nfunc (e *Ergo) Produces(mimes ...string) *Ergo {\n\tproduces(e, mimes)\n\treturn e\n}\n\nfunc (e *Ergo) Params(params ...*Param) *Ergo {\n\taddParams(e, params...)\n\treturn e\n}\n\nfunc (e *Ergo) ResetParams(params ...*Param) *Ergo {\n\te.setParamsSlice(params...)\n\treturn e\n}\n\nfunc (e *Ergo) SetParams(params map[string]*Param) *Ergo {\n\te.setParams(params)\n\treturn e\n}\n\nfunc (e *Ergo) IgnoreParams(params ...string) *Ergo {\n\tignoreParams(e, params...)\n\treturn e\n}\n\nfunc (e *Ergo) IgnoreParamsBut(params ...string) *Ergo {\n\tignoreParamsBut(e, params...)\n\treturn e\n}\n\n<commit_msg>NotFoundHandler setter for Ergo<commit_after>package ergo\n\ntype Ergo struct {\n\t*Route\n}\n\nfunc New(path string) *Ergo {\n\treturn &Ergo{\n\t\tRoute: NewRoute(path),\n\t}\n}\n\nfunc (e *Ergo) Schemes(s ...string) *Ergo {\n\tschemes(e, s)\n\treturn e\n}\n\nfunc (e *Ergo) Consumes(mimes ...string) *Ergo {\n\tconsumes(e, mimes)\n\treturn e\n}\n\nfunc (e *Ergo) Produces(mimes ...string) *Ergo {\n\tproduces(e, mimes)\n\treturn e\n}\n\nfunc (e *Ergo) Params(params ...*Param) *Ergo {\n\taddParams(e, params...)\n\treturn e\n}\n\nfunc (e *Ergo) ResetParams(params ...*Param) *Ergo {\n\te.setParamsSlice(params...)\n\treturn e\n}\n\nfunc (e *Ergo) SetParams(params map[string]*Param) *Ergo {\n\te.setParams(params)\n\treturn e\n}\n\nfunc (e *Ergo) IgnoreParams(params ...string) *Ergo {\n\tignoreParams(e, params...)\n\treturn e\n}\n\nfunc (e *Ergo) IgnoreParamsBut(params ...string) *Ergo {\n\tignoreParamsBut(e, params...)\n\treturn e\n}\n\nfunc (e *Ergo) NotFoundHandler(h Handler) *Ergo {\n\te.Route.notFoundHandler = h\n\treturn e\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016-2018 Authors of Cilium\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage kvstore\n\nimport (\n\t\"encoding\/base64\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/cilium\/cilium\/pkg\/backoff\"\n\t\"github.com\/cilium\/cilium\/pkg\/controller\"\n\t\"github.com\/cilium\/cilium\/pkg\/logging\/logfields\"\n\n\tconsulAPI \"github.com\/hashicorp\/consul\/api\"\n\t\"github.com\/sirupsen\/logrus\"\n)\n\nconst (\n\tconsulName = \"consul\"\n\n\t\/\/ optAddress is the string representing the key mapping to the value of the\n\t\/\/ address for Consul.\n\toptAddress = \"consul.address\"\n\n\t\/\/ maxLockRetries is the number of retries attempted when acquiring a lock\n\tmaxLockRetries = 10\n)\n\ntype consulModule struct {\n\topts   backendOptions\n\tconfig *consulAPI.Config\n}\n\nvar (\n\t\/\/consulDummyAddress can be overwritten from test invokers using ldflags\n\tconsulDummyAddress = \"127.0.0.1:8501\"\n\n\tmodule = &consulModule{\n\t\topts: backendOptions{\n\t\t\toptAddress: &backendOption{\n\t\t\t\tdescription: \"Addresses of consul cluster\",\n\t\t\t},\n\t\t},\n\t}\n)\n\nfunc init() {\n\t\/\/ register consul module for use\n\tregisterBackend(consulName, module)\n}\n\nfunc (c *consulModule) createInstance() backendModule {\n\tcpy := *module\n\treturn &cpy\n}\n\nfunc (c *consulModule) getName() string {\n\treturn consulName\n}\n\nfunc (c *consulModule) setConfigDummy() {\n\tc.config = consulAPI.DefaultConfig()\n\tc.config.Address = consulDummyAddress\n}\n\nfunc (c *consulModule) setConfig(opts map[string]string) error {\n\treturn setOpts(opts, c.opts)\n}\n\nfunc (c *consulModule) getConfig() map[string]string {\n\treturn getOpts(c.opts)\n}\n\nfunc (c *consulModule) newClient() (BackendOperations, error) {\n\tif c.config == nil {\n\t\tconsulAddr, ok := c.opts[optAddress]\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"invalid consul configuration, please specify %s option\", optAddress)\n\t\t}\n\n\t\taddr := consulAddr.value\n\t\tconsulSplitAddr := strings.Split(addr, \":\/\/\")\n\t\tif len(consulSplitAddr) == 2 {\n\t\t\taddr = consulSplitAddr[1]\n\t\t} else if len(consulSplitAddr) == 1 {\n\t\t\taddr = consulSplitAddr[0]\n\t\t}\n\n\t\tc.config = consulAPI.DefaultConfig()\n\t\tc.config.Address = addr\n\t}\n\n\tclient, err := newConsulClient(c.config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn client, nil\n}\n\nvar (\n\tmaxRetries = 30\n)\n\ntype consulClient struct {\n\t*consulAPI.Client\n\tlease       string\n\tcontrollers *controller.Manager\n}\n\nfunc newConsulClient(config *consulAPI.Config) (BackendOperations, error) {\n\tvar (\n\t\tc   *consulAPI.Client\n\t\terr error\n\t)\n\tif config != nil {\n\t\tc, err = consulAPI.NewClient(config)\n\t} else {\n\t\tc, err = consulAPI.NewClient(consulAPI.DefaultConfig())\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tboff := backoff.Exponential{Min: time.Duration(100) * time.Millisecond}\n\tlog.Info(\"Waiting for consul to elect a leader\")\n\n\tfor i := 0; i < maxRetries; i++ {\n\t\tvar leader string\n\t\tleader, err = c.Status().Leader()\n\n\t\tif err == nil {\n\t\t\tif leader != \"\" {\n\t\t\t\t\/\/ happy path\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\terr = errors.New(\"timeout while waiting for leader to be elected\")\n\t\t\t}\n\t\t}\n\n\t\tboff.Wait()\n\t}\n\n\tif err != nil {\n\t\tlog.WithError(err).Fatal(\"Unable to contact consul server\")\n\t}\n\n\tentry := &consulAPI.SessionEntry{\n\t\tTTL:      fmt.Sprintf(\"%ds\", int(LeaseTTL.Seconds())),\n\t\tBehavior: consulAPI.SessionBehaviorDelete,\n\t}\n\n\tlease, _, err := c.Session().Create(entry, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to create default lease: %s\", err)\n\t}\n\n\tclient := &consulClient{\n\t\tClient:      c,\n\t\tlease:       lease,\n\t\tcontrollers: controller.NewManager(),\n\t}\n\n\tclient.controllers.UpdateController(fmt.Sprintf(\"consul-lease-keepalive-%p\", c),\n\t\tcontroller.ControllerParams{\n\t\t\tDoFunc: func() error {\n\t\t\t\t_, _, err := c.Session().Renew(lease, nil)\n\t\t\t\treturn err\n\t\t\t},\n\t\t\tRunInterval: KeepAliveInterval,\n\t\t},\n\t)\n\n\treturn client, nil\n}\n\nfunc (c *consulClient) LockPath(path string) (kvLocker, error) {\n\tlockKey, err := c.LockOpts(&consulAPI.LockOptions{Key: getLockPath(path)})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor retries := 0; retries < maxLockRetries; retries++ {\n\t\tch, err := lockKey.Lock(nil)\n\t\tswitch {\n\t\tcase err != nil:\n\t\t\treturn nil, err\n\t\tcase ch == nil && err == nil:\n\t\t\tTrace(\"Acquiring lock timed out, retrying\", nil, logrus.Fields{fieldKey: path, logfields.Attempt: retries})\n\t\tdefault:\n\t\t\treturn lockKey, err\n\t\t}\n\t}\n\n\treturn nil, fmt.Errorf(\"maximum retries (%d) reached\", maxLockRetries)\n}\n\n\/\/ Watch starts watching for changes in a prefix\nfunc (c *consulClient) Watch(w *Watcher) {\n\t\/\/ Last known state of all KVPairs matching the prefix\n\tlocalState := map[string]consulAPI.KVPair{}\n\tnextIndex := uint64(0)\n\n\tqo := consulAPI.QueryOptions{\n\t\tWaitTime: time.Second,\n\t}\n\n\tfor {\n\t\t\/\/ Initialize sleep time to a millisecond as we don't\n\t\t\/\/ want to sleep in between successful watch cycles\n\t\tsleepTime := 1 * time.Millisecond\n\n\t\tqo.WaitIndex = nextIndex\n\t\tpairs, q, err := c.KV().List(w.prefix, &qo)\n\t\tif err != nil {\n\t\t\tsleepTime = 5 * time.Second\n\t\t\tTrace(\"List of Watch failed\", err, logrus.Fields{fieldPrefix: w.prefix, fieldWatcher: w.name})\n\t\t}\n\n\t\tif q != nil {\n\t\t\tnextIndex = q.LastIndex\n\t\t}\n\n\t\t\/\/ timeout while watching for changes, re-schedule\n\t\tif qo.WaitIndex != 0 && (q == nil || q.LastIndex == qo.WaitIndex) {\n\t\t\tgoto wait\n\t\t}\n\n\t\tfor _, newPair := range pairs {\n\t\t\toldPair, ok := localState[newPair.Key]\n\n\t\t\t\/\/ Keys reported for the first time must be new\n\t\t\tif !ok {\n\t\t\t\tif newPair.CreateIndex != newPair.ModifyIndex {\n\t\t\t\t\tlog.Debugf(\"consul: Previously unknown key %s received with CreateIndex(%d) != ModifyIndex(%d)\",\n\t\t\t\t\t\tnewPair.Key, newPair.CreateIndex, newPair.ModifyIndex)\n\t\t\t\t}\n\n\t\t\t\tw.Events <- KeyValueEvent{\n\t\t\t\t\tTyp:   EventTypeCreate,\n\t\t\t\t\tKey:   newPair.Key,\n\t\t\t\t\tValue: newPair.Value,\n\t\t\t\t}\n\t\t\t} else if oldPair.ModifyIndex != newPair.ModifyIndex {\n\t\t\t\tw.Events <- KeyValueEvent{\n\t\t\t\t\tTyp:   EventTypeModify,\n\t\t\t\t\tKey:   newPair.Key,\n\t\t\t\t\tValue: newPair.Value,\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ Everything left on localState will be assumed to\n\t\t\t\/\/ have been deleted, therefore remove all keys in\n\t\t\t\/\/ localState that still exist in the kvstore\n\t\t\tdelete(localState, newPair.Key)\n\t\t}\n\n\t\tfor k, deletedPair := range localState {\n\t\t\tw.Events <- KeyValueEvent{\n\t\t\t\tTyp:   EventTypeDelete,\n\t\t\t\tKey:   deletedPair.Key,\n\t\t\t\tValue: deletedPair.Value,\n\t\t\t}\n\t\t\tdelete(localState, k)\n\t\t}\n\n\t\tfor _, newPair := range pairs {\n\t\t\tlocalState[newPair.Key] = *newPair\n\n\t\t}\n\n\t\t\/\/ Initial list operation has been completed, signal this\n\t\tif qo.WaitIndex == 0 {\n\t\t\tw.Events <- KeyValueEvent{Typ: EventTypeListDone}\n\t\t}\n\n\twait:\n\t\tselect {\n\t\tcase <-time.After(sleepTime):\n\t\tcase <-w.stopWatch:\n\t\t\tclose(w.Events)\n\t\t\tw.stopWait.Done()\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (c *consulClient) Status() (string, error) {\n\tleader, err := c.Client.Status().Leader()\n\treturn \"Consul: \" + leader, err\n}\n\nfunc (c *consulClient) DeletePrefix(path string) error {\n\tincreaseMetric(path, metricDelete, \"DeletePrefix\")\n\t_, err := c.Client.KV().DeleteTree(path, nil)\n\treturn err\n}\n\n\/\/ Set sets value of key\nfunc (c *consulClient) Set(key string, value []byte) error {\n\tincreaseMetric(key, metricSet, \"Set\")\n\t_, err := c.KV().Put(&consulAPI.KVPair{Key: key, Value: value}, nil)\n\treturn err\n}\n\n\/\/ Delete deletes a key\nfunc (c *consulClient) Delete(key string) error {\n\tincreaseMetric(key, metricDelete, \"Delete\")\n\t_, err := c.KV().Delete(key, nil)\n\treturn err\n}\n\n\/\/ Get returns value of key\nfunc (c *consulClient) Get(key string) ([]byte, error) {\n\tincreaseMetric(key, metricRead, \"Get\")\n\tpair, _, err := c.KV().Get(key, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif pair == nil {\n\t\treturn nil, nil\n\t}\n\treturn pair.Value, nil\n}\n\n\/\/ GetPrefix returns the first key which matches the prefix\nfunc (c *consulClient) GetPrefix(prefix string) ([]byte, error) {\n\tincreaseMetric(prefix, metricRead, \"GetPrefix\")\n\tpairs, _, err := c.KV().List(prefix, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(pairs) == 0 {\n\t\treturn nil, nil\n\t}\n\n\treturn pairs[0].Value, nil\n}\n\n\/\/ Update creates or updates a key with the value\nfunc (c *consulClient) Update(key string, value []byte, lease bool) error {\n\tincreaseMetric(key, metricSet, \"Update\")\n\tk := &consulAPI.KVPair{Key: key, Value: value}\n\n\tif lease {\n\t\tk.Session = c.lease\n\t}\n\n\t_, err := c.KV().Put(k, nil)\n\treturn err\n}\n\n\/\/ CreateOnly creates a key with the value and will fail if the key already exists\nfunc (c *consulClient) CreateOnly(key string, value []byte, lease bool) error {\n\tincreaseMetric(key, metricSet, \"CreateOnly\")\n\tk := &consulAPI.KVPair{\n\t\tKey:         key,\n\t\tValue:       value,\n\t\tCreateIndex: 0,\n\t}\n\n\tif lease {\n\t\tk.Session = c.lease\n\t}\n\n\tsuccess, _, err := c.KV().CAS(k, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to compare-and-swap: %s\", err)\n\t}\n\tif !success {\n\t\treturn fmt.Errorf(\"compare-and-swap unsuccessful\")\n\t}\n\n\treturn nil\n}\n\n\/\/ CreateIfExists creates a key with the value only if key condKey exists\nfunc (c *consulClient) CreateIfExists(condKey, key string, value []byte, lease bool) error {\n\t\/\/ Consul does not support transactions which would allow to check for\n\t\/\/ the presence of a conditional key if the key is not the key being\n\t\/\/ manipulated\n\t\/\/\n\t\/\/ Lock the conditional key to serialize all CreateIfExists() calls\n\n\tincreaseMetric(key, metricSet, \"CreateIfExists\")\n\tl, err := LockPath(condKey)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to lock condKey for CreateIfExists: %s\", err)\n\t}\n\n\tdefer l.Unlock()\n\n\t\/\/ Create the key if it does not exist\n\tif err := c.CreateOnly(key, value, lease); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Consul does not support transactions which would allow to check for\n\t\/\/ the presence of another key\n\tmasterKey, err := c.Get(condKey)\n\tif err != nil || masterKey == nil {\n\t\tc.Delete(key)\n\t\treturn fmt.Errorf(\"conditional key not present\")\n\t}\n\n\treturn nil\n}\n\n\/\/ ListPrefix returns a map of matching keys\nfunc (c *consulClient) ListPrefix(prefix string) (KeyValuePairs, error) {\n\tincreaseMetric(prefix, metricRead, \"ListPrefix\")\n\tpairs, _, err := c.KV().List(prefix, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tp := KeyValuePairs(make(map[string][]byte, len(pairs)))\n\tfor i := 0; i < len(pairs); i++ {\n\t\tp[pairs[i].Key] = pairs[i].Value\n\t}\n\n\treturn p, nil\n}\n\n\/\/ Close closes the consul session\nfunc (c *consulClient) Close() {\n\tif c.controllers != nil {\n\t\tc.controllers.RemoveAll()\n\t}\n\tif c.lease != \"\" {\n\t\tc.Session().Destroy(c.lease, nil)\n\t}\n}\n\n\/\/ GetCapabilities returns the capabilities of the backend\nfunc (c *consulClient) GetCapabilities() Capabilities {\n\treturn Capabilities(0)\n}\n\n\/\/ Encode encodes a binary slice into a character set that the backend supports\nfunc (c *consulClient) Encode(in []byte) string {\n\treturn base64.URLEncoding.EncodeToString([]byte(in))\n}\n\n\/\/ Decode decodes a key previously encoded back into the original binary slice\nfunc (c *consulClient) Decode(in string) ([]byte, error) {\n\treturn base64.URLEncoding.DecodeString(in)\n}\n\n\/\/ ListAndWatch implements the BackendOperations.ListAndWatch using consul\nfunc (c *consulClient) ListAndWatch(name, prefix string, chanSize int) *Watcher {\n\tw := newWatcher(name, prefix, chanSize)\n\n\tlog.WithField(fieldWatcher, w).Debug(\"Starting watcher...\")\n\n\tgo c.Watch(w)\n\n\treturn w\n}\n<commit_msg>consul: add support for TLS option<commit_after>\/\/ Copyright 2016-2018 Authors of Cilium\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage kvstore\n\nimport (\n\t\"encoding\/base64\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"time\"\n\n\t\"github.com\/cilium\/cilium\/pkg\/backoff\"\n\t\"github.com\/cilium\/cilium\/pkg\/controller\"\n\t\"github.com\/cilium\/cilium\/pkg\/logging\/logfields\"\n\n\tconsulAPI \"github.com\/hashicorp\/consul\/api\"\n\t\"github.com\/sirupsen\/logrus\"\n\t\"gopkg.in\/yaml.v2\"\n)\n\nconst (\n\tconsulName = \"consul\"\n\n\t\/\/ optAddress is the string representing the key mapping to the value of the\n\t\/\/ address for Consul.\n\toptAddress         = \"consul.address\"\n\tconsulOptionConfig = \"consul.tlsconfig\"\n\n\t\/\/ maxLockRetries is the number of retries attempted when acquiring a lock\n\tmaxLockRetries = 10\n)\n\ntype consulModule struct {\n\topts   backendOptions\n\tconfig *consulAPI.Config\n}\n\nvar (\n\t\/\/consulDummyAddress can be overwritten from test invokers using ldflags\n\tconsulDummyAddress = \"127.0.0.1:8501\"\n\n\tmodule = &consulModule{\n\t\topts: backendOptions{\n\t\t\toptAddress: &backendOption{\n\t\t\t\tdescription: \"Addresses of consul cluster\",\n\t\t\t},\n\t\t\tconsulOptionConfig: &backendOption{\n\t\t\t\tdescription: \"Path to consul tls configuration file\",\n\t\t\t},\n\t\t},\n\t}\n)\n\nfunc init() {\n\t\/\/ register consul module for use\n\tregisterBackend(consulName, module)\n}\n\nfunc (c *consulModule) createInstance() backendModule {\n\tcpy := *module\n\treturn &cpy\n}\n\nfunc (c *consulModule) getName() string {\n\treturn consulName\n}\n\nfunc (c *consulModule) setConfigDummy() {\n\tc.config = consulAPI.DefaultConfig()\n\tc.config.Address = consulDummyAddress\n}\n\nfunc (c *consulModule) setConfig(opts map[string]string) error {\n\treturn setOpts(opts, c.opts)\n}\n\nfunc (c *consulModule) getConfig() map[string]string {\n\treturn getOpts(c.opts)\n}\n\nfunc (c *consulModule) newClient() (BackendOperations, error) {\n\tif c.config == nil {\n\t\tconsulAddr, consulAddrSet := c.opts[optAddress]\n\t\tconfigPathOpt, configPathOptSet := c.opts[consulOptionConfig]\n\t\tif !consulAddrSet {\n\t\t\treturn nil, fmt.Errorf(\"invalid consul configuration, please specify %s option\", optAddress)\n\t\t}\n\n\t\tif consulAddr.value == \"\" {\n\t\t\treturn nil, fmt.Errorf(\"invalid consul configuration, please specify %s option\", optAddress)\n\t\t}\n\n\t\taddr := consulAddr.value\n\t\tc.config = consulAPI.DefaultConfig()\n\t\tif configPathOptSet && configPathOpt.value != \"\" {\n\t\t\tb, err := ioutil.ReadFile(configPathOpt.value)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"unable to read consul tls configuration file %s: %s\", configPathOpt.value, err)\n\t\t\t}\n\t\t\tyc := consulAPI.TLSConfig{}\n\t\t\terr = yaml.Unmarshal(b, &yc)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"invalid consul tls configuration in %s: %s\", configPathOpt.value, err)\n\t\t\t}\n\t\t\tc.config.TLSConfig = yc\n\t\t}\n\n\t\tc.config.Address = addr\n\n\t}\n\tclient, err := newConsulClient(c.config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn client, nil\n}\n\nvar (\n\tmaxRetries = 30\n)\n\ntype consulClient struct {\n\t*consulAPI.Client\n\tlease       string\n\tcontrollers *controller.Manager\n}\n\nfunc newConsulClient(config *consulAPI.Config) (BackendOperations, error) {\n\tvar (\n\t\tc   *consulAPI.Client\n\t\terr error\n\t)\n\tif config != nil {\n\t\tc, err = consulAPI.NewClient(config)\n\t} else {\n\t\tc, err = consulAPI.NewClient(consulAPI.DefaultConfig())\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tboff := backoff.Exponential{Min: time.Duration(100) * time.Millisecond}\n\tlog.Info(\"Waiting for consul to elect a leader\")\n\n\tfor i := 0; i < maxRetries; i++ {\n\t\tvar leader string\n\t\tleader, err = c.Status().Leader()\n\n\t\tif err == nil {\n\t\t\tif leader != \"\" {\n\t\t\t\t\/\/ happy path\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\terr = errors.New(\"timeout while waiting for leader to be elected\")\n\t\t\t}\n\t\t}\n\n\t\tboff.Wait()\n\t}\n\n\tif err != nil {\n\t\tlog.WithError(err).Fatal(\"Unable to contact consul server\")\n\t}\n\n\tentry := &consulAPI.SessionEntry{\n\t\tTTL:      fmt.Sprintf(\"%ds\", int(LeaseTTL.Seconds())),\n\t\tBehavior: consulAPI.SessionBehaviorDelete,\n\t}\n\n\tlease, _, err := c.Session().Create(entry, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to create default lease: %s\", err)\n\t}\n\n\tclient := &consulClient{\n\t\tClient:      c,\n\t\tlease:       lease,\n\t\tcontrollers: controller.NewManager(),\n\t}\n\n\tclient.controllers.UpdateController(fmt.Sprintf(\"consul-lease-keepalive-%p\", c),\n\t\tcontroller.ControllerParams{\n\t\t\tDoFunc: func() error {\n\t\t\t\t_, _, err := c.Session().Renew(lease, nil)\n\t\t\t\treturn err\n\t\t\t},\n\t\t\tRunInterval: KeepAliveInterval,\n\t\t},\n\t)\n\n\treturn client, nil\n}\n\nfunc (c *consulClient) LockPath(path string) (kvLocker, error) {\n\tlockKey, err := c.LockOpts(&consulAPI.LockOptions{Key: getLockPath(path)})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor retries := 0; retries < maxLockRetries; retries++ {\n\t\tch, err := lockKey.Lock(nil)\n\t\tswitch {\n\t\tcase err != nil:\n\t\t\treturn nil, err\n\t\tcase ch == nil && err == nil:\n\t\t\tTrace(\"Acquiring lock timed out, retrying\", nil, logrus.Fields{fieldKey: path, logfields.Attempt: retries})\n\t\tdefault:\n\t\t\treturn lockKey, err\n\t\t}\n\t}\n\n\treturn nil, fmt.Errorf(\"maximum retries (%d) reached\", maxLockRetries)\n}\n\n\/\/ Watch starts watching for changes in a prefix\nfunc (c *consulClient) Watch(w *Watcher) {\n\t\/\/ Last known state of all KVPairs matching the prefix\n\tlocalState := map[string]consulAPI.KVPair{}\n\tnextIndex := uint64(0)\n\n\tqo := consulAPI.QueryOptions{\n\t\tWaitTime: time.Second,\n\t}\n\n\tfor {\n\t\t\/\/ Initialize sleep time to a millisecond as we don't\n\t\t\/\/ want to sleep in between successful watch cycles\n\t\tsleepTime := 1 * time.Millisecond\n\n\t\tqo.WaitIndex = nextIndex\n\t\tpairs, q, err := c.KV().List(w.prefix, &qo)\n\t\tif err != nil {\n\t\t\tsleepTime = 5 * time.Second\n\t\t\tTrace(\"List of Watch failed\", err, logrus.Fields{fieldPrefix: w.prefix, fieldWatcher: w.name})\n\t\t}\n\n\t\tif q != nil {\n\t\t\tnextIndex = q.LastIndex\n\t\t}\n\n\t\t\/\/ timeout while watching for changes, re-schedule\n\t\tif qo.WaitIndex != 0 && (q == nil || q.LastIndex == qo.WaitIndex) {\n\t\t\tgoto wait\n\t\t}\n\n\t\tfor _, newPair := range pairs {\n\t\t\toldPair, ok := localState[newPair.Key]\n\n\t\t\t\/\/ Keys reported for the first time must be new\n\t\t\tif !ok {\n\t\t\t\tif newPair.CreateIndex != newPair.ModifyIndex {\n\t\t\t\t\tlog.Debugf(\"consul: Previously unknown key %s received with CreateIndex(%d) != ModifyIndex(%d)\",\n\t\t\t\t\t\tnewPair.Key, newPair.CreateIndex, newPair.ModifyIndex)\n\t\t\t\t}\n\n\t\t\t\tw.Events <- KeyValueEvent{\n\t\t\t\t\tTyp:   EventTypeCreate,\n\t\t\t\t\tKey:   newPair.Key,\n\t\t\t\t\tValue: newPair.Value,\n\t\t\t\t}\n\t\t\t} else if oldPair.ModifyIndex != newPair.ModifyIndex {\n\t\t\t\tw.Events <- KeyValueEvent{\n\t\t\t\t\tTyp:   EventTypeModify,\n\t\t\t\t\tKey:   newPair.Key,\n\t\t\t\t\tValue: newPair.Value,\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ Everything left on localState will be assumed to\n\t\t\t\/\/ have been deleted, therefore remove all keys in\n\t\t\t\/\/ localState that still exist in the kvstore\n\t\t\tdelete(localState, newPair.Key)\n\t\t}\n\n\t\tfor k, deletedPair := range localState {\n\t\t\tw.Events <- KeyValueEvent{\n\t\t\t\tTyp:   EventTypeDelete,\n\t\t\t\tKey:   deletedPair.Key,\n\t\t\t\tValue: deletedPair.Value,\n\t\t\t}\n\t\t\tdelete(localState, k)\n\t\t}\n\n\t\tfor _, newPair := range pairs {\n\t\t\tlocalState[newPair.Key] = *newPair\n\n\t\t}\n\n\t\t\/\/ Initial list operation has been completed, signal this\n\t\tif qo.WaitIndex == 0 {\n\t\t\tw.Events <- KeyValueEvent{Typ: EventTypeListDone}\n\t\t}\n\n\twait:\n\t\tselect {\n\t\tcase <-time.After(sleepTime):\n\t\tcase <-w.stopWatch:\n\t\t\tclose(w.Events)\n\t\t\tw.stopWait.Done()\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (c *consulClient) Status() (string, error) {\n\tleader, err := c.Client.Status().Leader()\n\treturn \"Consul: \" + leader, err\n}\n\nfunc (c *consulClient) DeletePrefix(path string) error {\n\tincreaseMetric(path, metricDelete, \"DeletePrefix\")\n\t_, err := c.Client.KV().DeleteTree(path, nil)\n\treturn err\n}\n\n\/\/ Set sets value of key\nfunc (c *consulClient) Set(key string, value []byte) error {\n\tincreaseMetric(key, metricSet, \"Set\")\n\t_, err := c.KV().Put(&consulAPI.KVPair{Key: key, Value: value}, nil)\n\treturn err\n}\n\n\/\/ Delete deletes a key\nfunc (c *consulClient) Delete(key string) error {\n\tincreaseMetric(key, metricDelete, \"Delete\")\n\t_, err := c.KV().Delete(key, nil)\n\treturn err\n}\n\n\/\/ Get returns value of key\nfunc (c *consulClient) Get(key string) ([]byte, error) {\n\tincreaseMetric(key, metricRead, \"Get\")\n\tpair, _, err := c.KV().Get(key, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif pair == nil {\n\t\treturn nil, nil\n\t}\n\treturn pair.Value, nil\n}\n\n\/\/ GetPrefix returns the first key which matches the prefix\nfunc (c *consulClient) GetPrefix(prefix string) ([]byte, error) {\n\tincreaseMetric(prefix, metricRead, \"GetPrefix\")\n\tpairs, _, err := c.KV().List(prefix, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(pairs) == 0 {\n\t\treturn nil, nil\n\t}\n\n\treturn pairs[0].Value, nil\n}\n\n\/\/ Update creates or updates a key with the value\nfunc (c *consulClient) Update(key string, value []byte, lease bool) error {\n\tincreaseMetric(key, metricSet, \"Update\")\n\tk := &consulAPI.KVPair{Key: key, Value: value}\n\n\tif lease {\n\t\tk.Session = c.lease\n\t}\n\n\t_, err := c.KV().Put(k, nil)\n\treturn err\n}\n\n\/\/ CreateOnly creates a key with the value and will fail if the key already exists\nfunc (c *consulClient) CreateOnly(key string, value []byte, lease bool) error {\n\tincreaseMetric(key, metricSet, \"CreateOnly\")\n\tk := &consulAPI.KVPair{\n\t\tKey:         key,\n\t\tValue:       value,\n\t\tCreateIndex: 0,\n\t}\n\n\tif lease {\n\t\tk.Session = c.lease\n\t}\n\n\tsuccess, _, err := c.KV().CAS(k, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to compare-and-swap: %s\", err)\n\t}\n\tif !success {\n\t\treturn fmt.Errorf(\"compare-and-swap unsuccessful\")\n\t}\n\n\treturn nil\n}\n\n\/\/ CreateIfExists creates a key with the value only if key condKey exists\nfunc (c *consulClient) CreateIfExists(condKey, key string, value []byte, lease bool) error {\n\t\/\/ Consul does not support transactions which would allow to check for\n\t\/\/ the presence of a conditional key if the key is not the key being\n\t\/\/ manipulated\n\t\/\/\n\t\/\/ Lock the conditional key to serialize all CreateIfExists() calls\n\n\tincreaseMetric(key, metricSet, \"CreateIfExists\")\n\tl, err := LockPath(condKey)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to lock condKey for CreateIfExists: %s\", err)\n\t}\n\n\tdefer l.Unlock()\n\n\t\/\/ Create the key if it does not exist\n\tif err := c.CreateOnly(key, value, lease); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Consul does not support transactions which would allow to check for\n\t\/\/ the presence of another key\n\tmasterKey, err := c.Get(condKey)\n\tif err != nil || masterKey == nil {\n\t\tc.Delete(key)\n\t\treturn fmt.Errorf(\"conditional key not present\")\n\t}\n\n\treturn nil\n}\n\n\/\/ ListPrefix returns a map of matching keys\nfunc (c *consulClient) ListPrefix(prefix string) (KeyValuePairs, error) {\n\tincreaseMetric(prefix, metricRead, \"ListPrefix\")\n\tpairs, _, err := c.KV().List(prefix, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tp := KeyValuePairs(make(map[string][]byte, len(pairs)))\n\tfor i := 0; i < len(pairs); i++ {\n\t\tp[pairs[i].Key] = pairs[i].Value\n\t}\n\n\treturn p, nil\n}\n\n\/\/ Close closes the consul session\nfunc (c *consulClient) Close() {\n\tif c.controllers != nil {\n\t\tc.controllers.RemoveAll()\n\t}\n\tif c.lease != \"\" {\n\t\tc.Session().Destroy(c.lease, nil)\n\t}\n}\n\n\/\/ GetCapabilities returns the capabilities of the backend\nfunc (c *consulClient) GetCapabilities() Capabilities {\n\treturn Capabilities(0)\n}\n\n\/\/ Encode encodes a binary slice into a character set that the backend supports\nfunc (c *consulClient) Encode(in []byte) string {\n\treturn base64.URLEncoding.EncodeToString([]byte(in))\n}\n\n\/\/ Decode decodes a key previously encoded back into the original binary slice\nfunc (c *consulClient) Decode(in string) ([]byte, error) {\n\treturn base64.URLEncoding.DecodeString(in)\n}\n\n\/\/ ListAndWatch implements the BackendOperations.ListAndWatch using consul\nfunc (c *consulClient) ListAndWatch(name, prefix string, chanSize int) *Watcher {\n\tw := newWatcher(name, prefix, chanSize)\n\n\tlog.WithField(fieldWatcher, w).Debug(\"Starting watcher...\")\n\n\tgo c.Watch(w)\n\n\treturn w\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>ea51a752-2e55-11e5-9284-b827eb9e62be<commit_after><|endoftext|>"}
{"text":"<commit_before>package client\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/mobingilabs\/mocli\/client\/timeout\"\n\t\"github.com\/mobingilabs\/mocli\/pkg\/cli\/confmap\"\n\t\"github.com\/mobingilabs\/mocli\/pkg\/credentials\"\n\td \"github.com\/mobingilabs\/mocli\/pkg\/debug\"\n\t\"github.com\/spf13\/viper\"\n)\n\ntype setreq struct {\n\tvalues *url.Values           \/\/ when not nil, we populate raw query\n\theader *http.Header          \/\/ when not nil, we add to headers\n\tbasic  *credentials.UserPass \/\/ when not nil, we set basic auth\n}\n\ntype Client struct {\n\tclient *http.Client \/\/ our http client\n\tconfig *Config      \/\/ client configuration(s)\n}\n\nfunc NewClient(cnf *Config) *Client {\n\treturn &Client{\n\t\tclient: &http.Client{},\n\t\tconfig: cnf,\n\t}\n}\n\nfunc (c *Client) GetTagDigest(path string) (string, error) {\n\tvar digest string\n\thdrs := &http.Header{\n\t\t\"Authorization\": {\"Bearer \" + c.config.AccessToken},\n\t\t\"Accept\":        {\"application\/vnd.docker.distribution.manifest.v2+json\"},\n\t}\n\n\th, err := c.hdr(path, &setreq{header: hdrs})\n\tif err != nil {\n\t\treturn digest, err\n\t}\n\n\tfor name, hdr := range h {\n\t\tif name == \"Etag\" {\n\t\t\tdigest = hdr[0]\n\t\t\tdigest = strings.TrimSuffix(strings.TrimPrefix(digest, \"\\\"\"), \"\\\"\")\n\t\t}\n\t}\n\n\tif digest == \"\" {\n\t\treturn digest, fmt.Errorf(\"digest not found\")\n\t}\n\n\treturn digest, nil\n}\n\nfunc (c *Client) GetAccessToken(pl []byte) (string, error) {\n\tvar (\n\t\ttoken string\n\t\tm     map[string]interface{}\n\t)\n\n\thdrs := &http.Header{\"Content-Type\": {\"application\/json\"}}\n\tbody, err := c.post(\"\/access_token\", &setreq{header: hdrs}, pl)\n\tif err != nil {\n\t\treturn token, err\n\t}\n\n\tif err = json.Unmarshal(body, &m); err != nil {\n\t\treturn token, err\n\t}\n\n\tt, found := m[\"access_token\"]\n\tif !found {\n\t\treturn token, fmt.Errorf(\"cannot find access token\")\n\t}\n\n\ttoken = fmt.Sprintf(\"%s\", t)\n\treturn token, nil\n}\n\nfunc (c *Client) BasicAuthGet(path, user, pass string, v *url.Values) ([]byte, error) {\n\treturn c.get(\n\t\tpath,\n\t\t&setreq{\n\t\t\tvalues: v,\n\t\t\tbasic: &credentials.UserPass{\n\t\t\t\tUsername: user,\n\t\t\t\tPassword: pass,\n\t\t\t},\n\t\t},\n\t)\n}\n\nfunc (c *Client) AuthGet(path string) ([]byte, error) {\n\tah := c.authHdr()\n\treturn c.get(path, &setreq{header: &ah})\n}\n\nfunc (c *Client) AuthPost(path string, pl []byte) ([]byte, error) {\n\tah := c.authHdr()\n\tah.Add(\"Content-Type\", \"application\/json\")\n\treturn c.post(path, &setreq{header: &ah}, pl)\n}\n\nfunc (c *Client) AuthPut(path string, pl []byte) ([]byte, error) {\n\tah := c.authHdr()\n\tah.Add(\"Content-Type\", \"application\/json\")\n\treturn c.put(path, &setreq{header: &ah}, pl)\n}\n\nfunc (c *Client) AuthDel(path string) ([]byte, error) {\n\tah := c.authHdr()\n\treturn c.del(path, &setreq{header: &ah})\n}\n\nfunc (c *Client) url() string {\n\treturn c.config.RootUrl + \"\/\" + c.config.ApiVersion\n}\n\nfunc (c *Client) hdr(path string, p *setreq) (http.Header, error) {\n\treq, err := http.NewRequest(http.MethodGet, c.url()+path, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar cancel context.CancelFunc\n\treq, cancel = c.initReq(req, p)\n\tdefer cancel()\n\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer resp.Body.Close()\n\tverboseResponse(resp)\n\tret := resp.Header\n\treturn ret, nil\n}\n\nfunc (c *Client) get(path string, p *setreq) ([]byte, error) {\n\treq, err := http.NewRequest(http.MethodGet, c.url()+path, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar cancel context.CancelFunc\n\treq, cancel = c.initReq(req, p)\n\treturn c.send(req, cancel)\n}\n\nfunc (c *Client) post(path string, p *setreq, pl []byte) ([]byte, error) {\n\treq, err := http.NewRequest(http.MethodPost, c.url()+path, bytes.NewBuffer(pl))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar cancel context.CancelFunc\n\treq, cancel = c.initReq(req, p)\n\treturn c.send(req, cancel)\n}\n\nfunc (c *Client) put(path string, p *setreq, pl []byte) ([]byte, error) {\n\treq, err := http.NewRequest(http.MethodPut, c.url()+path, bytes.NewBuffer(pl))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar cancel context.CancelFunc\n\treq, cancel = c.initReq(req, p)\n\treturn c.send(req, cancel)\n}\n\nfunc (c *Client) del(path string, p *setreq) ([]byte, error) {\n\treq, err := http.NewRequest(http.MethodDelete, c.url()+path, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar cancel context.CancelFunc\n\treq, cancel = c.initReq(req, p)\n\treturn c.send(req, cancel)\n}\n\nfunc (c *Client) send(r *http.Request, cancel context.CancelFunc) ([]byte, error) {\n\tif cancel != nil {\n\t\tdefer cancel()\n\t}\n\n\tresp, err := c.client.Do(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer resp.Body.Close()\n\tverboseResponse(resp)\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tre := respError(resp, body)\n\tif re != \"\" {\n\t\treturn body, fmt.Errorf(re)\n\t}\n\n\treturn body, nil\n}\n\nfunc (c *Client) authHdr() http.Header {\n\treturn http.Header{\"Authorization\": {\"Bearer \" + c.config.AccessToken}}\n}\n\nfunc (c *Client) initReq(r *http.Request, p *setreq) (*http.Request, context.CancelFunc) {\n\tctx, cancel := context.WithTimeout(r.Context(), time.Second*time.Duration(timeout.Timeout))\n\tr = r.WithContext(ctx)\n\n\tif p.header != nil {\n\t\tfor name, hdr := range *p.header {\n\t\t\tr.Header.Add(name, hdr[0])\n\t\t}\n\t}\n\n\tif p.values != nil {\n\t\tvalues := *p.values\n\t\tr.URL.RawQuery = values.Encode()\n\t}\n\n\tif p.basic != nil {\n\t\tr.SetBasicAuth(p.basic.Username, p.basic.Password)\n\t}\n\n\tc.verboseRequest(r)\n\treturn r, cancel\n}\n\nfunc (c *Client) verboseRequest(r *http.Request) {\n\tif viper.GetBool(confmap.ConfigKey(\"verbose\")) {\n\t\td.Info(\"[URL]\", r.URL.String())\n\t\td.Info(\"[METHOD]\", r.Method)\n\t\tfor n, h := range r.Header {\n\t\t\td.Info(fmt.Sprintf(\"[REQUEST] %s: %s\", n, h))\n\t\t}\n\t}\n}\n\nfunc verboseResponse(r *http.Response) {\n\tif viper.GetBool(confmap.ConfigKey(\"verbose\")) {\n\t\tfor n, h := range r.Header {\n\t\t\td.Info(fmt.Sprintf(\"[RESPONSE] %s: %s\", n, h))\n\t\t}\n\n\t\td.Info(\"[STATUS]\", r.Status)\n\t}\n}\n\nfunc respError(r *http.Response, b []byte) string {\n\tvar (\n\t\terrcnt int\n\t\tm      map[string]interface{}\n\t\tserr   string\n\t\tcem    string\n\t)\n\n\terr := json.Unmarshal(b, &m)\n\tif err != nil {\n\t\t\/\/ considered success; our expected error format\n\t\t\/\/ is marshallable to 'm'\n\t\treturn serr\n\t}\n\n\tif !d.IsHttpSuccess(r.StatusCode) {\n\t\tserr = serr + \"[\" + r.Status + \"]\"\n\t}\n\n\t\/\/ these three should be present to be considered error\n\tif c, found := m[\"code\"]; found {\n\t\tcem = cem + \"[\" + fmt.Sprintf(\"%s\", c) + \"]\"\n\t\terrcnt += 1\n\t}\n\n\tif e, found := m[\"error\"]; found {\n\t\tcem = cem + fmt.Sprintf(\" %s:\", e)\n\t\terrcnt += 1\n\t}\n\n\tif s, found := m[\"message\"]; found {\n\t\tcem = cem + fmt.Sprintf(\" %s\", s)\n\t\terrcnt += 1\n\t}\n\n\tif errcnt == 3 {\n\t\tserr = serr + cem\n\t}\n\n\treturn serr\n}\n<commit_msg>Include http response in main http send func.<commit_after>package client\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/mobingilabs\/mocli\/client\/timeout\"\n\t\"github.com\/mobingilabs\/mocli\/pkg\/cli\/confmap\"\n\t\"github.com\/mobingilabs\/mocli\/pkg\/credentials\"\n\td \"github.com\/mobingilabs\/mocli\/pkg\/debug\"\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/spf13\/viper\"\n)\n\ntype setreq struct {\n\tvalues *url.Values           \/\/ when not nil, we populate raw query\n\theader *http.Header          \/\/ when not nil, we add to headers\n\tbasic  *credentials.UserPass \/\/ when not nil, we set basic auth\n}\n\ntype Client struct {\n\tclient *http.Client \/\/ our http client\n\tconfig *Config      \/\/ client configuration(s)\n}\n\nfunc NewClient(cnf *Config) *Client {\n\treturn &Client{\n\t\tclient: &http.Client{},\n\t\tconfig: cnf,\n\t}\n}\n\nfunc (c *Client) GetTagDigest(path string) (string, error) {\n\tvar digest string\n\thdrs := &http.Header{\n\t\t\"Authorization\": {\"Bearer \" + c.config.AccessToken},\n\t\t\"Accept\":        {\"application\/vnd.docker.distribution.manifest.v2+json\"},\n\t}\n\n\th, err := c.hdr(path, &setreq{header: hdrs})\n\tif err != nil {\n\t\treturn digest, err\n\t}\n\n\tfor name, hdr := range h {\n\t\tif name == \"Etag\" {\n\t\t\tdigest = hdr[0]\n\t\t\tdigest = strings.TrimSuffix(strings.TrimPrefix(digest, \"\\\"\"), \"\\\"\")\n\t\t}\n\t}\n\n\tif digest == \"\" {\n\t\treturn digest, fmt.Errorf(\"digest not found\")\n\t}\n\n\treturn digest, nil\n}\n\nfunc (c *Client) GetAccessToken(pl []byte) (string, error) {\n\tvar (\n\t\ttoken string\n\t\tm     map[string]interface{}\n\t)\n\n\thdrs := &http.Header{\"Content-Type\": {\"application\/json\"}}\n\t_, body, err := c.post(\"\/access_token\", &setreq{header: hdrs}, pl)\n\tif err != nil {\n\t\treturn token, err\n\t}\n\n\tif err = json.Unmarshal(body, &m); err != nil {\n\t\treturn token, err\n\t}\n\n\tt, found := m[\"access_token\"]\n\tif !found {\n\t\treturn token, fmt.Errorf(\"cannot find access token\")\n\t}\n\n\ttoken = fmt.Sprintf(\"%s\", t)\n\treturn token, nil\n}\n\nfunc (c *Client) BasicAuthGet(path, user, pass string, v *url.Values) ([]byte, error) {\n\t_, body, err := c.get(\n\t\tpath,\n\t\t&setreq{\n\t\t\tvalues: v,\n\t\t\tbasic: &credentials.UserPass{\n\t\t\t\tUsername: user,\n\t\t\t\tPassword: pass,\n\t\t\t},\n\t\t},\n\t)\n\n\treturn body, err\n}\n\nfunc (c *Client) AuthGet(path string) ([]byte, error) {\n\tah := c.authHdr()\n\t_, body, err := c.get(path, &setreq{header: &ah})\n\treturn body, err\n}\n\nfunc (c *Client) AuthPost(path string, pl []byte) ([]byte, error) {\n\tah := c.authHdr()\n\tah.Add(\"Content-Type\", \"application\/json\")\n\t_, body, err := c.post(path, &setreq{header: &ah}, pl)\n\treturn body, err\n}\n\nfunc (c *Client) AuthPut(path string, pl []byte) ([]byte, error) {\n\tah := c.authHdr()\n\tah.Add(\"Content-Type\", \"application\/json\")\n\t_, body, err := c.put(path, &setreq{header: &ah}, pl)\n\treturn body, err\n}\n\nfunc (c *Client) AuthDel(path string) ([]byte, error) {\n\tah := c.authHdr()\n\t_, body, err := c.del(path, &setreq{header: &ah})\n\treturn body, err\n}\n\nfunc (c *Client) url() string {\n\treturn c.config.RootUrl + \"\/\" + c.config.ApiVersion\n}\n\nfunc (c *Client) hdr(path string, p *setreq) (http.Header, error) {\n\treq, err := http.NewRequest(http.MethodGet, c.url()+path, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar cancel context.CancelFunc\n\treq, cancel = c.initReq(req, p)\n\tdefer cancel()\n\n\tresp, err := c.client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer resp.Body.Close()\n\tverboseResponse(resp)\n\tret := resp.Header\n\treturn ret, nil\n}\n\nfunc (c *Client) get(path string, p *setreq) (*http.Response, []byte, error) {\n\treq, err := http.NewRequest(http.MethodGet, c.url()+path, nil)\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"new request failed\")\n\t}\n\n\tvar cancel context.CancelFunc\n\treq, cancel = c.initReq(req, p)\n\treturn c.send(req, cancel)\n}\n\nfunc (c *Client) post(path string, p *setreq, pl []byte) (*http.Response, []byte, error) {\n\treq, err := http.NewRequest(http.MethodPost, c.url()+path, bytes.NewBuffer(pl))\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"new request failed\")\n\t}\n\n\tvar cancel context.CancelFunc\n\treq, cancel = c.initReq(req, p)\n\treturn c.send(req, cancel)\n}\n\nfunc (c *Client) put(path string, p *setreq, pl []byte) (*http.Response, []byte, error) {\n\treq, err := http.NewRequest(http.MethodPut, c.url()+path, bytes.NewBuffer(pl))\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"new request failed\")\n\t}\n\n\tvar cancel context.CancelFunc\n\treq, cancel = c.initReq(req, p)\n\treturn c.send(req, cancel)\n}\n\nfunc (c *Client) del(path string, p *setreq) (*http.Response, []byte, error) {\n\treq, err := http.NewRequest(http.MethodDelete, c.url()+path, nil)\n\tif err != nil {\n\t\treturn nil, nil, errors.Wrap(err, \"new request failed\")\n\t}\n\n\tvar cancel context.CancelFunc\n\treq, cancel = c.initReq(req, p)\n\treturn c.send(req, cancel)\n}\n\nfunc (c *Client) send(r *http.Request, cancel context.CancelFunc) (*http.Response, []byte, error) {\n\tif cancel != nil {\n\t\tdefer cancel()\n\t}\n\n\tresp, err := c.client.Do(r)\n\tif err != nil {\n\t\treturn resp, nil, errors.Wrap(err, \"do failed\")\n\t}\n\n\tdefer resp.Body.Close()\n\tverboseResponse(resp)\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn resp, nil, errors.Wrap(err, \"read body failed\")\n\t}\n\n\tre := respError(resp, body)\n\tif re != \"\" {\n\t\treturn resp, body, fmt.Errorf(re)\n\t}\n\n\treturn resp, body, nil\n}\n\nfunc (c *Client) authHdr() http.Header {\n\treturn http.Header{\"Authorization\": {\"Bearer \" + c.config.AccessToken}}\n}\n\nfunc (c *Client) initReq(r *http.Request, p *setreq) (*http.Request, context.CancelFunc) {\n\tctx, cancel := context.WithTimeout(r.Context(), time.Second*time.Duration(timeout.Timeout))\n\tr = r.WithContext(ctx)\n\n\tif p.header != nil {\n\t\tfor name, hdr := range *p.header {\n\t\t\tr.Header.Add(name, hdr[0])\n\t\t}\n\t}\n\n\tif p.values != nil {\n\t\tvalues := *p.values\n\t\tr.URL.RawQuery = values.Encode()\n\t}\n\n\tif p.basic != nil {\n\t\tr.SetBasicAuth(p.basic.Username, p.basic.Password)\n\t}\n\n\tc.verboseRequest(r)\n\treturn r, cancel\n}\n\nfunc (c *Client) verboseRequest(r *http.Request) {\n\tif viper.GetBool(confmap.ConfigKey(\"verbose\")) {\n\t\td.Info(\"[URL]\", r.URL.String())\n\t\td.Info(\"[METHOD]\", r.Method)\n\t\tfor n, h := range r.Header {\n\t\t\td.Info(fmt.Sprintf(\"[REQUEST] %s: %s\", n, h))\n\t\t}\n\t}\n}\n\nfunc verboseResponse(r *http.Response) {\n\tif viper.GetBool(confmap.ConfigKey(\"verbose\")) {\n\t\tfor n, h := range r.Header {\n\t\t\td.Info(fmt.Sprintf(\"[RESPONSE] %s: %s\", n, h))\n\t\t}\n\n\t\td.Info(\"[STATUS]\", r.Status)\n\t}\n}\n\nfunc respError(r *http.Response, b []byte) string {\n\tvar (\n\t\terrcnt int\n\t\tm      map[string]interface{}\n\t\tserr   string\n\t\tcem    string\n\t)\n\n\terr := json.Unmarshal(b, &m)\n\tif err != nil {\n\t\t\/\/ considered success; our expected error format\n\t\t\/\/ is marshallable to 'm'\n\t\treturn serr\n\t}\n\n\tif !d.IsHttpSuccess(r.StatusCode) {\n\t\tserr = serr + \"[\" + r.Status + \"]\"\n\t}\n\n\t\/\/ these three should be present to be considered error\n\tif c, found := m[\"code\"]; found {\n\t\tcem = cem + \"[\" + fmt.Sprintf(\"%s\", c) + \"]\"\n\t\terrcnt += 1\n\t}\n\n\tif e, found := m[\"error\"]; found {\n\t\tcem = cem + fmt.Sprintf(\" %s:\", e)\n\t\terrcnt += 1\n\t}\n\n\tif s, found := m[\"message\"]; found {\n\t\tcem = cem + fmt.Sprintf(\" %s\", s)\n\t\terrcnt += 1\n\t}\n\n\tif errcnt == 3 {\n\t\tserr = serr + cem\n\t}\n\n\treturn serr\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright The OpenTelemetry Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage ottl \/\/ import \"github.com\/open-telemetry\/opentelemetry-collector-contrib\/pkg\/ottl\"\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"strings\"\n)\n\ntype PathExpressionParser[K any] func(*Path) (GetSetter[K], error)\n\ntype EnumParser func(*EnumSymbol) (*Enum, error)\n\ntype Enum int64\n\nfunc (p *Parser[K]) newFunctionCall(inv invocation) (ExprFunc[K], error) {\n\tif f, ok := p.functions[inv.Function]; ok {\n\t\targs, err := p.buildArgs(inv, reflect.TypeOf(f))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturnVals := reflect.ValueOf(f).Call(args)\n\n\t\tif returnVals[1].IsNil() {\n\t\t\terr = nil\n\t\t} else {\n\t\t\terr = returnVals[1].Interface().(error)\n\t\t}\n\n\t\treturn returnVals[0].Interface().(ExprFunc[K]), err\n\t}\n\treturn nil, fmt.Errorf(\"undefined function %v\", inv.Function)\n}\n\nfunc (p *Parser[K]) buildArgs(inv invocation, fType reflect.Type) ([]reflect.Value, error) {\n\tvar args []reflect.Value\n\t\/\/ Some function arguments may be intended to take values from the calling processor\n\t\/\/ instead of being passed by the caller of the OTTL function, so we have to keep\n\t\/\/ track of the index of the argument passed within the DSL.\n\t\/\/ e.g. TelemetrySettings, which is provided by the processor to the OTTL Parser struct.\n\tDSLArgumentIndex := 0\n\tfor i := 0; i < fType.NumIn(); i++ {\n\t\targType := fType.In(i)\n\n\t\tswitch argType.Kind() {\n\t\tcase reflect.Slice:\n\t\t\terr := p.buildSliceArg(inv, argType, i, &args)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\t\/\/ Slice arguments must be the final argument in an invocation.\n\t\t\treturn args, nil\n\t\tdefault:\n\t\t\tisInternalArg := p.buildInternalArg(argType, &args)\n\n\t\t\tif isInternalArg {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif DSLArgumentIndex >= len(inv.Arguments) {\n\t\t\t\treturn nil, fmt.Errorf(\"not enough arguments for function %v\", inv.Function)\n\t\t\t}\n\n\t\t\targDef := inv.Arguments[DSLArgumentIndex]\n\t\t\terr := p.buildArg(argDef, argType, DSLArgumentIndex, &args)\n\t\t\tDSLArgumentIndex++\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(inv.Arguments) > DSLArgumentIndex {\n\t\treturn nil, fmt.Errorf(\"too many arguments for function %v\", inv.Function)\n\t}\n\n\treturn args, nil\n}\n\nfunc (p *Parser[K]) buildSliceArg(inv invocation, argType reflect.Type, startingIndex int, args *[]reflect.Value) error {\n\tname := argType.Elem().Name()\n\tswitch {\n\tcase name == reflect.String.String():\n\t\tvar arg []string\n\t\tfor j := startingIndex; j < len(inv.Arguments); j++ {\n\t\t\tif inv.Arguments[j].String == nil {\n\t\t\t\treturn fmt.Errorf(\"invalid argument for slice parameter at position %v, must be a string\", j)\n\t\t\t}\n\t\t\targ = append(arg, *inv.Arguments[j].String)\n\t\t}\n\t\t*args = append(*args, reflect.ValueOf(arg))\n\tcase name == reflect.Float64.String():\n\t\tvar arg []float64\n\t\tfor j := startingIndex; j < len(inv.Arguments); j++ {\n\t\t\tif inv.Arguments[j].Float == nil {\n\t\t\t\treturn fmt.Errorf(\"invalid argument for slice parameter at position %v, must be a float\", j)\n\t\t\t}\n\t\t\targ = append(arg, *inv.Arguments[j].Float)\n\t\t}\n\t\t*args = append(*args, reflect.ValueOf(arg))\n\tcase name == reflect.Int64.String():\n\t\tvar arg []int64\n\t\tfor j := startingIndex; j < len(inv.Arguments); j++ {\n\t\t\tif inv.Arguments[j].Int == nil {\n\t\t\t\treturn fmt.Errorf(\"invalid argument for slice parameter at position %v, must be an int\", j)\n\t\t\t}\n\t\t\targ = append(arg, *inv.Arguments[j].Int)\n\t\t}\n\t\t*args = append(*args, reflect.ValueOf(arg))\n\tcase name == reflect.Uint8.String():\n\t\tif inv.Arguments[startingIndex].Bytes == nil {\n\t\t\treturn fmt.Errorf(\"invalid argument for slice parameter at position %v, must be a byte slice literal\", startingIndex)\n\t\t}\n\t\t*args = append(*args, reflect.ValueOf(([]byte)(*inv.Arguments[startingIndex].Bytes)))\n\tcase strings.HasPrefix(name, \"Getter\"):\n\t\tvar arg []Getter[K]\n\t\tfor j := startingIndex; j < len(inv.Arguments); j++ {\n\t\t\tval, err := p.newGetter(inv.Arguments[j])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\targ = append(arg, val)\n\t\t}\n\t\t*args = append(*args, reflect.ValueOf(arg))\n\tdefault:\n\t\treturn fmt.Errorf(\"unsupported slice type '%s' for function '%v'\", argType.Elem().Name(), inv.Function)\n\t}\n\treturn nil\n}\n\n\/\/ Handle interfaces that can be passed as arguments to OTTL function invocations.\nfunc (p *Parser[K]) buildArg(argDef value, argType reflect.Type, index int, args *[]reflect.Value) error {\n\tname := argType.Name()\n\tswitch {\n\tcase strings.HasPrefix(name, \"Setter\"):\n\t\tfallthrough\n\tcase strings.HasPrefix(name, \"GetSetter\"):\n\t\targ, err := p.pathParser(argDef.Path)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"invalid argument at position %v %w\", index, err)\n\t\t}\n\t\t*args = append(*args, reflect.ValueOf(arg))\n\tcase strings.HasPrefix(name, \"Getter\"):\n\t\targ, err := p.newGetter(argDef)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"invalid argument at position %v %w\", index, err)\n\t\t}\n\t\t*args = append(*args, reflect.ValueOf(arg))\n\tcase name == \"Enum\":\n\t\targ, err := p.enumParser(argDef.Enum)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"invalid argument at position %v must be an Enum\", index)\n\t\t}\n\t\t*args = append(*args, reflect.ValueOf(*arg))\n\tcase name == \"string\":\n\t\tif argDef.String == nil {\n\t\t\treturn fmt.Errorf(\"invalid argument at position %v, must be an string\", index)\n\t\t}\n\t\t*args = append(*args, reflect.ValueOf(*argDef.String))\n\tcase name == \"float64\":\n\t\tif argDef.Float == nil {\n\t\t\treturn fmt.Errorf(\"invalid argument at position %v, must be an float\", index)\n\t\t}\n\t\t*args = append(*args, reflect.ValueOf(*argDef.Float))\n\tcase name == \"int64\":\n\t\tif argDef.Int == nil {\n\t\t\treturn fmt.Errorf(\"invalid argument at position %v, must be an int\", index)\n\t\t}\n\t\t*args = append(*args, reflect.ValueOf(*argDef.Int))\n\tcase name == \"bool\":\n\t\tif argDef.Bool == nil {\n\t\t\treturn fmt.Errorf(\"invalid argument at position %v, must be a bool\", index)\n\t\t}\n\t\t*args = append(*args, reflect.ValueOf(bool(*argDef.Bool)))\n\tdefault:\n\t\treturn errors.New(\"unsupported argument type\")\n\t}\n\treturn nil\n}\n\n\/\/ Handle interfaces that can be declared as parameters to a OTTL function, but will\n\/\/ never be called in an invocation. Returns whether the arg is an internal arg.\nfunc (p *Parser[K]) buildInternalArg(argType reflect.Type, args *[]reflect.Value) bool {\n\tswitch argType.Name() {\n\tcase \"TelemetrySettings\":\n\t\t*args = append(*args, reflect.ValueOf(p.telemetrySettings))\n\tdefault:\n\t\treturn false\n\t}\n\n\treturn true\n}\n<commit_msg>[chore] pkg\/ottl check for condition first (#14614)<commit_after>\/\/ Copyright The OpenTelemetry Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/      http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage ottl \/\/ import \"github.com\/open-telemetry\/opentelemetry-collector-contrib\/pkg\/ottl\"\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"strings\"\n)\n\ntype PathExpressionParser[K any] func(*Path) (GetSetter[K], error)\n\ntype EnumParser func(*EnumSymbol) (*Enum, error)\n\ntype Enum int64\n\nfunc (p *Parser[K]) newFunctionCall(inv invocation) (ExprFunc[K], error) {\n\tf, ok := p.functions[inv.Function]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"undefined function %v\", inv.Function)\n\t}\n\targs, err := p.buildArgs(inv, reflect.TypeOf(f))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturnVals := reflect.ValueOf(f).Call(args)\n\n\tif returnVals[1].IsNil() {\n\t\terr = nil\n\t} else {\n\t\terr = returnVals[1].Interface().(error)\n\t}\n\n\treturn returnVals[0].Interface().(ExprFunc[K]), err\n}\n\nfunc (p *Parser[K]) buildArgs(inv invocation, fType reflect.Type) ([]reflect.Value, error) {\n\tvar args []reflect.Value\n\t\/\/ Some function arguments may be intended to take values from the calling processor\n\t\/\/ instead of being passed by the caller of the OTTL function, so we have to keep\n\t\/\/ track of the index of the argument passed within the DSL.\n\t\/\/ e.g. TelemetrySettings, which is provided by the processor to the OTTL Parser struct.\n\tDSLArgumentIndex := 0\n\tfor i := 0; i < fType.NumIn(); i++ {\n\t\targType := fType.In(i)\n\n\t\tswitch argType.Kind() {\n\t\tcase reflect.Slice:\n\t\t\terr := p.buildSliceArg(inv, argType, i, &args)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\t\/\/ Slice arguments must be the final argument in an invocation.\n\t\t\treturn args, nil\n\t\tdefault:\n\t\t\tisInternalArg := p.buildInternalArg(argType, &args)\n\n\t\t\tif isInternalArg {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif DSLArgumentIndex >= len(inv.Arguments) {\n\t\t\t\treturn nil, fmt.Errorf(\"not enough arguments for function %v\", inv.Function)\n\t\t\t}\n\n\t\t\targDef := inv.Arguments[DSLArgumentIndex]\n\t\t\terr := p.buildArg(argDef, argType, DSLArgumentIndex, &args)\n\t\t\tDSLArgumentIndex++\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(inv.Arguments) > DSLArgumentIndex {\n\t\treturn nil, fmt.Errorf(\"too many arguments for function %v\", inv.Function)\n\t}\n\n\treturn args, nil\n}\n\nfunc (p *Parser[K]) buildSliceArg(inv invocation, argType reflect.Type, startingIndex int, args *[]reflect.Value) error {\n\tname := argType.Elem().Name()\n\tswitch {\n\tcase name == reflect.String.String():\n\t\tvar arg []string\n\t\tfor j := startingIndex; j < len(inv.Arguments); j++ {\n\t\t\tif inv.Arguments[j].String == nil {\n\t\t\t\treturn fmt.Errorf(\"invalid argument for slice parameter at position %v, must be a string\", j)\n\t\t\t}\n\t\t\targ = append(arg, *inv.Arguments[j].String)\n\t\t}\n\t\t*args = append(*args, reflect.ValueOf(arg))\n\tcase name == reflect.Float64.String():\n\t\tvar arg []float64\n\t\tfor j := startingIndex; j < len(inv.Arguments); j++ {\n\t\t\tif inv.Arguments[j].Float == nil {\n\t\t\t\treturn fmt.Errorf(\"invalid argument for slice parameter at position %v, must be a float\", j)\n\t\t\t}\n\t\t\targ = append(arg, *inv.Arguments[j].Float)\n\t\t}\n\t\t*args = append(*args, reflect.ValueOf(arg))\n\tcase name == reflect.Int64.String():\n\t\tvar arg []int64\n\t\tfor j := startingIndex; j < len(inv.Arguments); j++ {\n\t\t\tif inv.Arguments[j].Int == nil {\n\t\t\t\treturn fmt.Errorf(\"invalid argument for slice parameter at position %v, must be an int\", j)\n\t\t\t}\n\t\t\targ = append(arg, *inv.Arguments[j].Int)\n\t\t}\n\t\t*args = append(*args, reflect.ValueOf(arg))\n\tcase name == reflect.Uint8.String():\n\t\tif inv.Arguments[startingIndex].Bytes == nil {\n\t\t\treturn fmt.Errorf(\"invalid argument for slice parameter at position %v, must be a byte slice literal\", startingIndex)\n\t\t}\n\t\t*args = append(*args, reflect.ValueOf(([]byte)(*inv.Arguments[startingIndex].Bytes)))\n\tcase strings.HasPrefix(name, \"Getter\"):\n\t\tvar arg []Getter[K]\n\t\tfor j := startingIndex; j < len(inv.Arguments); j++ {\n\t\t\tval, err := p.newGetter(inv.Arguments[j])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\targ = append(arg, val)\n\t\t}\n\t\t*args = append(*args, reflect.ValueOf(arg))\n\tdefault:\n\t\treturn fmt.Errorf(\"unsupported slice type '%s' for function '%v'\", argType.Elem().Name(), inv.Function)\n\t}\n\treturn nil\n}\n\n\/\/ Handle interfaces that can be passed as arguments to OTTL function invocations.\nfunc (p *Parser[K]) buildArg(argDef value, argType reflect.Type, index int, args *[]reflect.Value) error {\n\tname := argType.Name()\n\tswitch {\n\tcase strings.HasPrefix(name, \"Setter\"):\n\t\tfallthrough\n\tcase strings.HasPrefix(name, \"GetSetter\"):\n\t\targ, err := p.pathParser(argDef.Path)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"invalid argument at position %v %w\", index, err)\n\t\t}\n\t\t*args = append(*args, reflect.ValueOf(arg))\n\tcase strings.HasPrefix(name, \"Getter\"):\n\t\targ, err := p.newGetter(argDef)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"invalid argument at position %v %w\", index, err)\n\t\t}\n\t\t*args = append(*args, reflect.ValueOf(arg))\n\tcase name == \"Enum\":\n\t\targ, err := p.enumParser(argDef.Enum)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"invalid argument at position %v must be an Enum\", index)\n\t\t}\n\t\t*args = append(*args, reflect.ValueOf(*arg))\n\tcase name == \"string\":\n\t\tif argDef.String == nil {\n\t\t\treturn fmt.Errorf(\"invalid argument at position %v, must be an string\", index)\n\t\t}\n\t\t*args = append(*args, reflect.ValueOf(*argDef.String))\n\tcase name == \"float64\":\n\t\tif argDef.Float == nil {\n\t\t\treturn fmt.Errorf(\"invalid argument at position %v, must be an float\", index)\n\t\t}\n\t\t*args = append(*args, reflect.ValueOf(*argDef.Float))\n\tcase name == \"int64\":\n\t\tif argDef.Int == nil {\n\t\t\treturn fmt.Errorf(\"invalid argument at position %v, must be an int\", index)\n\t\t}\n\t\t*args = append(*args, reflect.ValueOf(*argDef.Int))\n\tcase name == \"bool\":\n\t\tif argDef.Bool == nil {\n\t\t\treturn fmt.Errorf(\"invalid argument at position %v, must be a bool\", index)\n\t\t}\n\t\t*args = append(*args, reflect.ValueOf(bool(*argDef.Bool)))\n\tdefault:\n\t\treturn errors.New(\"unsupported argument type\")\n\t}\n\treturn nil\n}\n\n\/\/ Handle interfaces that can be declared as parameters to a OTTL function, but will\n\/\/ never be called in an invocation. Returns whether the arg is an internal arg.\nfunc (p *Parser[K]) buildInternalArg(argType reflect.Type, args *[]reflect.Value) bool {\n\tswitch argType.Name() {\n\tcase \"TelemetrySettings\":\n\t\t*args = append(*args, reflect.ValueOf(p.telemetrySettings))\n\tdefault:\n\t\treturn false\n\t}\n\n\treturn true\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2017 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage schemaconv\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"path\"\n\t\"strings\"\n\n\t\"k8s.io\/kube-openapi\/pkg\/util\/proto\"\n\t\"sigs.k8s.io\/structured-merge-diff\/schema\"\n)\n\n\/\/ ToSchema converts openapi definitions into a schema suitable for structured\n\/\/ merge (i.e. kubectl apply v2).\nfunc ToSchema(models proto.Models) (*schema.Schema, error) {\n\tc := convert{\n\t\tinput:  models,\n\t\toutput: &schema.Schema{},\n\t}\n\tif err := c.convertAll(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c.output, nil\n}\n\ntype convert struct {\n\tinput  proto.Models\n\toutput *schema.Schema\n\n\tcurrentName   string\n\tcurrent       *schema.Atom\n\terrorMessages []string\n}\n\nfunc (c *convert) push(name string, a *schema.Atom) *convert {\n\treturn &convert{\n\t\tinput:       c.input,\n\t\toutput:      c.output,\n\t\tcurrentName: name,\n\t\tcurrent:     a,\n\t}\n}\n\nfunc (c *convert) top() *schema.Atom { return c.current }\n\nfunc (c *convert) pop(c2 *convert) {\n\tc.errorMessages = append(c.errorMessages, c2.errorMessages...)\n}\n\nfunc (c *convert) convertAll() error {\n\tfor _, name := range c.input.ListModels() {\n\t\tmodel := c.input.LookupModel(name)\n\t\tc.insertTypeDef(name, model)\n\t}\n\tif len(c.errorMessages) > 0 {\n\t\treturn errors.New(strings.Join(c.errorMessages, \"\\n\"))\n\t}\n\treturn nil\n}\n\nfunc (c *convert) reportError(format string, args ...interface{}) {\n\tc.errorMessages = append(c.errorMessages,\n\t\tc.currentName+\": \"+fmt.Sprintf(format, args...),\n\t)\n}\n\nfunc (c *convert) insertTypeDef(name string, model proto.Schema) {\n\tdef := schema.TypeDef{\n\t\tName: name,\n\t}\n\tc2 := c.push(name, &def.Atom)\n\tmodel.Accept(c2)\n\tc.pop(c2)\n\tif def.Atom == (schema.Atom{}) {\n\t\t\/\/ This could happen if there were a top-level reference.\n\t\treturn\n\t}\n\tc.output.Types = append(c.output.Types, def)\n}\n\nfunc (c *convert) makeRef(model proto.Schema) schema.TypeRef {\n\tvar tr schema.TypeRef\n\tif r, ok := model.(*proto.Ref); ok {\n\t\t\/\/ reference a named type\n\t\t_, n := path.Split(r.Reference())\n\t\ttr.NamedType = &n\n\t} else {\n\t\t\/\/ compute the type inline\n\t\tc2 := c.push(\"inlined in \"+c.currentName, &tr.Inlined)\n\t\tmodel.Accept(c2)\n\t\tc.pop(c2)\n\n\t\tif tr == (schema.TypeRef{}) {\n\t\t\t\/\/ emit warning?\n\t\t\ttr.Inlined.Untyped = &schema.Untyped{}\n\t\t}\n\t}\n\treturn tr\n}\n\nfunc (c *convert) VisitKind(k *proto.Kind) {\n\ta := c.top()\n\ta.Struct = &schema.Struct{}\n\tfor _, name := range k.FieldOrder {\n\t\tmember := k.Fields[name]\n\t\ttr := c.makeRef(member)\n\t\ta.Struct.Fields = append(a.Struct.Fields, schema.StructField{\n\t\t\tName: name,\n\t\t\tType: tr,\n\t\t})\n\t}\n\n\t\/\/ TODO: Get element relationship when we start adding it to the spec.\n}\n\nfunc toStringSlice(o interface{}) (out []string, ok bool) {\n\tswitch t := o.(type) {\n\tcase []interface{}:\n\t\tfor _, v := range t {\n\t\t\tswitch vt := v.(type) {\n\t\t\tcase string:\n\t\t\t\tout = append(out, vt)\n\t\t\t}\n\t\t}\n\t\treturn out, true\n\t}\n\treturn nil, false\n}\n\nfunc (c *convert) VisitArray(a *proto.Array) {\n\tatom := c.top()\n\tatom.List = &schema.List{\n\t\tElementRelationship: schema.Atomic,\n\t}\n\tl := atom.List\n\tl.ElementType = c.makeRef(a.SubType)\n\n\text := a.GetExtensions()\n\n\tif val, ok := ext[\"x-kubernetes-list-type\"]; ok {\n\t\tif val == \"atomic\" {\n\t\t\tl.ElementRelationship = schema.Atomic\n\t\t} else if val == \"set\" {\n\t\t\tl.ElementRelationship = schema.Associative\n\t\t} else if val == \"map\" {\n\t\t\tl.ElementRelationship = schema.Associative\n\t\t\tif keys, ok := ext[\"x-kubernetes-list-map-keys\"]; ok {\n\t\t\t\tif keyNames, ok := toStringSlice(keys); ok {\n\t\t\t\t\tl.Keys = keyNames\n\t\t\t\t} else {\n\t\t\t\t\tc.reportError(\"uninterpreted map keys: %#v\", keys)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tc.reportError(\"missing map keys\")\n\t\t\t}\n\t\t} else {\n\t\t\tc.reportError(\"unknown list type %v\", val)\n\t\t\tl.ElementRelationship = schema.Atomic\n\t\t}\n\t} else if val, ok := ext[\"x-kubernetes-patch-strategy\"]; ok {\n\t\tif val == \"merge\" || val == \"merge,retainKeys\" {\n\t\t\tl.ElementRelationship = schema.Associative\n\t\t\tif key, ok := ext[\"x-kubernetes-patch-merge-key\"]; ok {\n\t\t\t\tif keyName, ok := key.(string); ok {\n\t\t\t\t\tl.Keys = []string{keyName}\n\t\t\t\t} else {\n\t\t\t\t\tc.reportError(\"uninterpreted merge key: %#v\", key)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t\/\/ It's not an error for this to be absent, it\n\t\t\t\t\/\/ means it's a set.\n\t\t\t}\n\t\t} else if val == \"retainKeys\" {\n\t\t} else {\n\t\t\tc.reportError(\"unknown patch strategy %v\", val)\n\t\t\tl.ElementRelationship = schema.Atomic\n\t\t}\n\t}\n}\n\nfunc (c *convert) VisitMap(m *proto.Map) {\n\ta := c.top()\n\ta.Map = &schema.Map{}\n\ta.Map.ElementType = c.makeRef(m.SubType)\n\n\t\/\/ TODO: Get element relationship when we start putting it into the\n\t\/\/ spec.\n}\n\nfunc (c *convert) VisitPrimitive(p *proto.Primitive) {\n\ta := c.top()\n\tptr := func(s schema.Scalar) *schema.Scalar { return &s }\n\tswitch p.Type {\n\tcase proto.Integer:\n\t\ta.Scalar = ptr(schema.Numeric)\n\tcase proto.Number:\n\t\ta.Scalar = ptr(schema.Numeric)\n\tcase proto.String:\n\t\tif p.Format == \"int-or-string\" {\n\t\t\ta.Untyped = &schema.Untyped{}\n\t\t} else {\n\t\t\ta.Scalar = ptr(schema.String)\n\t\t}\n\tcase proto.Boolean:\n\t\ta.Scalar = ptr(schema.Boolean)\n\tdefault:\n\t\ta.Untyped = &schema.Untyped{}\n\t}\n}\n\nfunc (c *convert) VisitArbitrary(a *proto.Arbitrary) {\n\tc.top().Untyped = &schema.Untyped{}\n}\n\nfunc (c *convert) VisitReference(proto.Reference) {\n\t\/\/ Do nothing, we handle references specially\n}\n<commit_msg>handle more string formats<commit_after>\/*\nCopyright 2017 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage schemaconv\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"path\"\n\t\"strings\"\n\n\t\"k8s.io\/kube-openapi\/pkg\/util\/proto\"\n\t\"sigs.k8s.io\/structured-merge-diff\/schema\"\n)\n\n\/\/ ToSchema converts openapi definitions into a schema suitable for structured\n\/\/ merge (i.e. kubectl apply v2).\nfunc ToSchema(models proto.Models) (*schema.Schema, error) {\n\tc := convert{\n\t\tinput:  models,\n\t\toutput: &schema.Schema{},\n\t}\n\tif err := c.convertAll(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn c.output, nil\n}\n\ntype convert struct {\n\tinput  proto.Models\n\toutput *schema.Schema\n\n\tcurrentName   string\n\tcurrent       *schema.Atom\n\terrorMessages []string\n}\n\nfunc (c *convert) push(name string, a *schema.Atom) *convert {\n\treturn &convert{\n\t\tinput:       c.input,\n\t\toutput:      c.output,\n\t\tcurrentName: name,\n\t\tcurrent:     a,\n\t}\n}\n\nfunc (c *convert) top() *schema.Atom { return c.current }\n\nfunc (c *convert) pop(c2 *convert) {\n\tc.errorMessages = append(c.errorMessages, c2.errorMessages...)\n}\n\nfunc (c *convert) convertAll() error {\n\tfor _, name := range c.input.ListModels() {\n\t\tmodel := c.input.LookupModel(name)\n\t\tc.insertTypeDef(name, model)\n\t}\n\tif len(c.errorMessages) > 0 {\n\t\treturn errors.New(strings.Join(c.errorMessages, \"\\n\"))\n\t}\n\treturn nil\n}\n\nfunc (c *convert) reportError(format string, args ...interface{}) {\n\tc.errorMessages = append(c.errorMessages,\n\t\tc.currentName+\": \"+fmt.Sprintf(format, args...),\n\t)\n}\n\nfunc (c *convert) insertTypeDef(name string, model proto.Schema) {\n\tdef := schema.TypeDef{\n\t\tName: name,\n\t}\n\tc2 := c.push(name, &def.Atom)\n\tmodel.Accept(c2)\n\tc.pop(c2)\n\tif def.Atom == (schema.Atom{}) {\n\t\t\/\/ This could happen if there were a top-level reference.\n\t\treturn\n\t}\n\tc.output.Types = append(c.output.Types, def)\n}\n\nfunc (c *convert) makeRef(model proto.Schema) schema.TypeRef {\n\tvar tr schema.TypeRef\n\tif r, ok := model.(*proto.Ref); ok {\n\t\t\/\/ reference a named type\n\t\t_, n := path.Split(r.Reference())\n\t\ttr.NamedType = &n\n\t} else {\n\t\t\/\/ compute the type inline\n\t\tc2 := c.push(\"inlined in \"+c.currentName, &tr.Inlined)\n\t\tmodel.Accept(c2)\n\t\tc.pop(c2)\n\n\t\tif tr == (schema.TypeRef{}) {\n\t\t\t\/\/ emit warning?\n\t\t\ttr.Inlined.Untyped = &schema.Untyped{}\n\t\t}\n\t}\n\treturn tr\n}\n\nfunc (c *convert) VisitKind(k *proto.Kind) {\n\ta := c.top()\n\ta.Struct = &schema.Struct{}\n\tfor _, name := range k.FieldOrder {\n\t\tmember := k.Fields[name]\n\t\ttr := c.makeRef(member)\n\t\ta.Struct.Fields = append(a.Struct.Fields, schema.StructField{\n\t\t\tName: name,\n\t\t\tType: tr,\n\t\t})\n\t}\n\n\t\/\/ TODO: Get element relationship when we start adding it to the spec.\n}\n\nfunc toStringSlice(o interface{}) (out []string, ok bool) {\n\tswitch t := o.(type) {\n\tcase []interface{}:\n\t\tfor _, v := range t {\n\t\t\tswitch vt := v.(type) {\n\t\t\tcase string:\n\t\t\t\tout = append(out, vt)\n\t\t\t}\n\t\t}\n\t\treturn out, true\n\t}\n\treturn nil, false\n}\n\nfunc (c *convert) VisitArray(a *proto.Array) {\n\tatom := c.top()\n\tatom.List = &schema.List{\n\t\tElementRelationship: schema.Atomic,\n\t}\n\tl := atom.List\n\tl.ElementType = c.makeRef(a.SubType)\n\n\text := a.GetExtensions()\n\n\tif val, ok := ext[\"x-kubernetes-list-type\"]; ok {\n\t\tif val == \"atomic\" {\n\t\t\tl.ElementRelationship = schema.Atomic\n\t\t} else if val == \"set\" {\n\t\t\tl.ElementRelationship = schema.Associative\n\t\t} else if val == \"map\" {\n\t\t\tl.ElementRelationship = schema.Associative\n\t\t\tif keys, ok := ext[\"x-kubernetes-list-map-keys\"]; ok {\n\t\t\t\tif keyNames, ok := toStringSlice(keys); ok {\n\t\t\t\t\tl.Keys = keyNames\n\t\t\t\t} else {\n\t\t\t\t\tc.reportError(\"uninterpreted map keys: %#v\", keys)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tc.reportError(\"missing map keys\")\n\t\t\t}\n\t\t} else {\n\t\t\tc.reportError(\"unknown list type %v\", val)\n\t\t\tl.ElementRelationship = schema.Atomic\n\t\t}\n\t} else if val, ok := ext[\"x-kubernetes-patch-strategy\"]; ok {\n\t\tif val == \"merge\" || val == \"merge,retainKeys\" {\n\t\t\tl.ElementRelationship = schema.Associative\n\t\t\tif key, ok := ext[\"x-kubernetes-patch-merge-key\"]; ok {\n\t\t\t\tif keyName, ok := key.(string); ok {\n\t\t\t\t\tl.Keys = []string{keyName}\n\t\t\t\t} else {\n\t\t\t\t\tc.reportError(\"uninterpreted merge key: %#v\", key)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t\/\/ It's not an error for this to be absent, it\n\t\t\t\t\/\/ means it's a set.\n\t\t\t}\n\t\t} else if val == \"retainKeys\" {\n\t\t} else {\n\t\t\tc.reportError(\"unknown patch strategy %v\", val)\n\t\t\tl.ElementRelationship = schema.Atomic\n\t\t}\n\t}\n}\n\nfunc (c *convert) VisitMap(m *proto.Map) {\n\ta := c.top()\n\ta.Map = &schema.Map{}\n\ta.Map.ElementType = c.makeRef(m.SubType)\n\n\t\/\/ TODO: Get element relationship when we start putting it into the\n\t\/\/ spec.\n}\n\nfunc (c *convert) VisitPrimitive(p *proto.Primitive) {\n\ta := c.top()\n\tptr := func(s schema.Scalar) *schema.Scalar { return &s }\n\tswitch p.Type {\n\tcase proto.Integer:\n\t\ta.Scalar = ptr(schema.Numeric)\n\tcase proto.Number:\n\t\ta.Scalar = ptr(schema.Numeric)\n\tcase proto.String:\n\t\tswitch p.Format {\n\t\tcase \"\":\n\t\t\ta.Scalar = ptr(schema.String)\n\t\tcase \"byte\":\n\t\t\t\/\/ byte really means []byte and is encoded as a string.\n\t\t\ta.Scalar = ptr(schema.String)\n\t\tcase \"int-or-string\":\n\t\t\ta.Untyped = &schema.Untyped{}\n\t\tcase \"date-time\":\n\t\t\ta.Untyped = &schema.Untyped{}\n\t\tdefault:\n\t\t\ta.Untyped = &schema.Untyped{}\n\t\t}\n\tcase proto.Boolean:\n\t\ta.Scalar = ptr(schema.Boolean)\n\tdefault:\n\t\ta.Untyped = &schema.Untyped{}\n\t}\n}\n\nfunc (c *convert) VisitArbitrary(a *proto.Arbitrary) {\n\tc.top().Untyped = &schema.Untyped{}\n}\n\nfunc (c *convert) VisitReference(proto.Reference) {\n\t\/\/ Do nothing, we handle references specially\n}\n<|endoftext|>"}
{"text":"<commit_before>package source\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/url\"\n\t\"path\"\n\t\"regexp\"\n)\n\nvar (\n\thookbotGithostRe = regexp.MustCompile(\"^\/sub\/([^\/]+)\/repo\/([^\/]+)\/([^\/]+)\" +\n\t\t\"\/branch\/([^\/#]+)(?:#(.*))?$\")\n\thookbotDockerPullSub = regexp.MustCompile(\"^\/sub\/docker-pull\/(.*)\/tag\/([^\/]+)$\")\n)\n\nfunc GetSourceFromHookbot(hookbotURLStr string) (string, ImageSource, error) {\n\n\thookbotURL, err := url.Parse(hookbotURLStr)\n\tif err != nil {\n\t\treturn \"\", nil, fmt.Errorf(\"Hookbot URL %q does not parse: %v\",\n\t\t\thookbotURLStr, err)\n\t}\n\n\tswitch {\n\tcase hookbotGithostRe.MatchString(PathWithFragment(hookbotURL)):\n\t\treturn NewGitHostSource(hookbotURL)\n\n\tcase hookbotDockerPullSub.MatchString(hookbotURL.Path):\n\t\treturn NewDockerPullSource(hookbotURL)\n\t}\n\n\treturn \"\", nil, fmt.Errorf(\"Unrecogized hookbot URL %q\", hookbotURL.Path)\n}\n\n\/\/ Represent the path as \/foo or \/foo#bar if #bar is specified.\nfunc PathWithFragment(u *url.URL) string {\n\tpathWithFragment := u.Path\n\tif u.Fragment != \"\" {\n\t\tpathWithFragment += \"#\" + u.Fragment\n\t}\n\treturn pathWithFragment\n}\n\nfunc NewGitHostSource(hookbotURL *url.URL) (string, ImageSource, error) {\n\n\tgroups := hookbotGithostRe.FindStringSubmatch(PathWithFragment(hookbotURL))\n\thost, user, repository, branch := groups[1], groups[2], groups[3], groups[4]\n\timageRoot := groups[5]\n\n\timageSource := &GitHostSource{\n\t\tHost:          host,\n\t\tUser:          user,\n\t\tRepository:    repository,\n\t\tInitialBranch: branch,\n\t\tImageRoot:     imageRoot,\n\t}\n\n\tlog.Printf(\"Hookbot monitoring %v@%v via %v (imageroot %q)\",\n\t\trepository, branch, hookbotURL.Host, imageRoot)\n\n\treturn repository, imageSource, nil\n}\n\nfunc NewDockerPullSource(hookbotURL *url.URL) (string, ImageSource, error) {\n\n\tgroups := hookbotDockerPullSub.FindStringSubmatch(hookbotURL.Path)\n\trepository, tag := groups[1], groups[2]\n\n\timageSource := &DockerPullSource{\n\t\tRepository: repository,\n\t\tTag:        tag,\n\t}\n\n\tlog.Printf(\"Hookbot monitoring %v@%v via %v\",\n\t\trepository, tag, hookbotURL.Host)\n\n\tcontainerName := path.Base(repository)\n\treturn containerName, imageSource, nil\n}\n<commit_msg>Add \/sub\/hanoverd\/cwd hookbot mode for building from local URL<commit_after>package source\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/url\"\n\t\"path\"\n\t\"regexp\"\n)\n\nvar (\n\thookbotGithostRe = regexp.MustCompile(\"^\/sub\/([^\/]+)\/repo\/([^\/]+)\/([^\/]+)\" +\n\t\t\"\/branch\/([^\/#]+)(?:#(.*))?$\")\n\thookbotDockerPullSub = regexp.MustCompile(\"^\/sub\/docker-pull\/(.*)\/tag\/([^\/]+)$\")\n\thookbotCwdRe         = regexp.MustCompile(\"^\/sub\/hanoverd\/cwd$\")\n)\n\nfunc GetSourceFromHookbot(hookbotURLStr string) (string, ImageSource, error) {\n\n\thookbotURL, err := url.Parse(hookbotURLStr)\n\tif err != nil {\n\t\treturn \"\", nil, fmt.Errorf(\"Hookbot URL %q does not parse: %v\",\n\t\t\thookbotURLStr, err)\n\t}\n\n\tswitch {\n\tcase hookbotGithostRe.MatchString(PathWithFragment(hookbotURL)):\n\t\treturn NewGitHostSource(hookbotURL)\n\n\tcase hookbotDockerPullSub.MatchString(hookbotURL.Path):\n\t\treturn NewDockerPullSource(hookbotURL)\n\n\tcase hookbotCwdRe.MatchString(hookbotURL.Path):\n\t\treturn \"cwd\", &CwdSource{}, nil\n\t}\n\n\treturn \"\", nil, fmt.Errorf(\"Unrecogized hookbot URL %q\", hookbotURL.Path)\n}\n\n\/\/ Represent the path as \/foo or \/foo#bar if #bar is specified.\nfunc PathWithFragment(u *url.URL) string {\n\tpathWithFragment := u.Path\n\tif u.Fragment != \"\" {\n\t\tpathWithFragment += \"#\" + u.Fragment\n\t}\n\treturn pathWithFragment\n}\n\nfunc NewGitHostSource(hookbotURL *url.URL) (string, ImageSource, error) {\n\n\tgroups := hookbotGithostRe.FindStringSubmatch(PathWithFragment(hookbotURL))\n\thost, user, repository, branch := groups[1], groups[2], groups[3], groups[4]\n\timageRoot := groups[5]\n\n\timageSource := &GitHostSource{\n\t\tHost:          host,\n\t\tUser:          user,\n\t\tRepository:    repository,\n\t\tInitialBranch: branch,\n\t\tImageRoot:     imageRoot,\n\t}\n\n\tlog.Printf(\"Hookbot monitoring %v@%v via %v (imageroot %q)\",\n\t\trepository, branch, hookbotURL.Host, imageRoot)\n\n\treturn repository, imageSource, nil\n}\n\nfunc NewDockerPullSource(hookbotURL *url.URL) (string, ImageSource, error) {\n\n\tgroups := hookbotDockerPullSub.FindStringSubmatch(hookbotURL.Path)\n\trepository, tag := groups[1], groups[2]\n\n\timageSource := &DockerPullSource{\n\t\tRepository: repository,\n\t\tTag:        tag,\n\t}\n\n\tlog.Printf(\"Hookbot monitoring %v@%v via %v\",\n\t\trepository, tag, hookbotURL.Host)\n\n\tcontainerName := path.Base(repository)\n\treturn containerName, imageSource, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright The Helm Authors.\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage strvals\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"sigs.k8s.io\/yaml\"\n)\n\n\/\/ ErrNotList indicates that a non-list was treated as a list.\nvar ErrNotList = errors.New(\"not a list\")\n\n\/\/ ToYAML takes a string of arguments and converts to a YAML document.\nfunc ToYAML(s string) (string, error) {\n\tm, err := Parse(s)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\td, err := yaml.Marshal(m)\n\treturn strings.TrimSuffix(string(d), \"\\n\"), err\n}\n\n\/\/ Parse parses a set line.\n\/\/\n\/\/ A set line is of the form name1=value1,name2=value2\nfunc Parse(s string) (map[string]interface{}, error) {\n\tvals := map[string]interface{}{}\n\tscanner := bytes.NewBufferString(s)\n\tt := newParser(scanner, vals, false)\n\terr := t.parse()\n\treturn vals, err\n}\n\n\/\/ ParseString parses a set line and forces a string value.\n\/\/\n\/\/ A set line is of the form name1=value1,name2=value2\nfunc ParseString(s string) (map[string]interface{}, error) {\n\tvals := map[string]interface{}{}\n\tscanner := bytes.NewBufferString(s)\n\tt := newParser(scanner, vals, true)\n\terr := t.parse()\n\treturn vals, err\n}\n\n\/\/ ParseInto parses a strvals line and merges the result into dest.\n\/\/\n\/\/ If the strval string has a key that exists in dest, it overwrites the\n\/\/ dest version.\nfunc ParseInto(s string, dest map[string]interface{}) error {\n\tscanner := bytes.NewBufferString(s)\n\tt := newParser(scanner, dest, false)\n\treturn t.parse()\n}\n\n\/\/ ParseFile parses a set line, but its final value is loaded from the file at the path specified by the original value.\n\/\/\n\/\/ A set line is of the form name1=path1,name2=path2\n\/\/\n\/\/ When the files at path1 and path2 contained \"val1\" and \"val2\" respectively, the set line is consumed as\n\/\/ name1=val1,name2=val2\nfunc ParseFile(s string, reader RunesValueReader) (map[string]interface{}, error) {\n\tvals := map[string]interface{}{}\n\tscanner := bytes.NewBufferString(s)\n\tt := newFileParser(scanner, vals, reader)\n\terr := t.parse()\n\treturn vals, err\n}\n\n\/\/ ParseIntoString parses a strvals line and merges the result into dest.\n\/\/\n\/\/ This method always returns a string as the value.\nfunc ParseIntoString(s string, dest map[string]interface{}) error {\n\tscanner := bytes.NewBufferString(s)\n\tt := newParser(scanner, dest, true)\n\treturn t.parse()\n}\n\n\/\/ ParseIntoFile parses a filevals line and merges the result into dest.\n\/\/\n\/\/ This method always returns a string as the value.\nfunc ParseIntoFile(s string, dest map[string]interface{}, reader RunesValueReader) error {\n\tscanner := bytes.NewBufferString(s)\n\tt := newFileParser(scanner, dest, reader)\n\treturn t.parse()\n}\n\n\/\/ RunesValueReader is a function that takes the given value (a slice of runes)\n\/\/ and returns the parsed value\ntype RunesValueReader func([]rune) (interface{}, error)\n\n\/\/ parser is a simple parser that takes a strvals line and parses it into a\n\/\/ map representation.\n\/\/\n\/\/ where sc is the source of the original data being parsed\n\/\/ where data is the final parsed data from the parses with correct types\ntype parser struct {\n\tsc     *bytes.Buffer\n\tdata   map[string]interface{}\n\treader RunesValueReader\n}\n\nfunc newParser(sc *bytes.Buffer, data map[string]interface{}, stringBool bool) *parser {\n\tstringConverter := func(rs []rune) (interface{}, error) {\n\t\treturn typedVal(rs, stringBool), nil\n\t}\n\treturn &parser{sc: sc, data: data, reader: stringConverter}\n}\n\nfunc newFileParser(sc *bytes.Buffer, data map[string]interface{}, reader RunesValueReader) *parser {\n\treturn &parser{sc: sc, data: data, reader: reader}\n}\n\nfunc (t *parser) parse() error {\n\tfor {\n\t\terr := t.key(t.data)\n\t\tif err == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif err == io.EOF {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n}\n\nfunc runeSet(r []rune) map[rune]bool {\n\ts := make(map[rune]bool, len(r))\n\tfor _, rr := range r {\n\t\ts[rr] = true\n\t}\n\treturn s\n}\n\nfunc (t *parser) key(data map[string]interface{}) error {\n\tstop := runeSet([]rune{'=', '[', ',', '.'})\n\tfor {\n\t\tswitch k, last, err := runesUntil(t.sc, stop); {\n\t\tcase err != nil:\n\t\t\tif len(k) == 0 {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn errors.Errorf(\"key %q has no value\", string(k))\n\t\t\t\/\/set(data, string(k), \"\")\n\t\t\t\/\/return err\n\t\tcase last == '[':\n\t\t\t\/\/ We are in a list index context, so we need to set an index.\n\t\t\ti, err := t.keyIndex()\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"error parsing index\")\n\t\t\t}\n\t\t\tkk := string(k)\n\t\t\t\/\/ Find or create target list\n\t\t\tlist := []interface{}{}\n\t\t\tif _, ok := data[kk]; ok {\n\t\t\t\tlist = data[kk].([]interface{})\n\t\t\t}\n\n\t\t\t\/\/ Now we need to get the value after the ].\n\t\t\tlist, err = t.listItem(list, i)\n\t\t\tset(data, kk, list)\n\t\t\treturn err\n\t\tcase last == '=':\n\t\t\t\/\/End of key. Consume =, Get value.\n\t\t\t\/\/ FIXME: Get value list first\n\t\t\tvl, e := t.valList()\n\t\t\tswitch e {\n\t\t\tcase nil:\n\t\t\t\tset(data, string(k), vl)\n\t\t\t\treturn nil\n\t\t\tcase io.EOF:\n\t\t\t\tset(data, string(k), \"\")\n\t\t\t\treturn e\n\t\t\tcase ErrNotList:\n\t\t\t\trs, e := t.val()\n\t\t\t\tif e != nil && e != io.EOF {\n\t\t\t\t\treturn e\n\t\t\t\t}\n\t\t\t\tv, e := t.reader(rs)\n\t\t\t\tset(data, string(k), v)\n\t\t\t\treturn e\n\t\t\tdefault:\n\t\t\t\treturn e\n\t\t\t}\n\n\t\tcase last == ',':\n\t\t\t\/\/ No value given. Set the value to empty string. Return error.\n\t\t\tset(data, string(k), \"\")\n\t\t\treturn errors.Errorf(\"key %q has no value (cannot end with ,)\", string(k))\n\t\tcase last == '.':\n\t\t\t\/\/ First, create or find the target map.\n\t\t\tinner := map[string]interface{}{}\n\t\t\tif _, ok := data[string(k)]; ok {\n\t\t\t\tinner = data[string(k)].(map[string]interface{})\n\t\t\t}\n\n\t\t\t\/\/ Recurse\n\t\t\te := t.key(inner)\n\t\t\tif len(inner) == 0 {\n\t\t\t\treturn errors.Errorf(\"key map %q has no value\", string(k))\n\t\t\t}\n\t\t\tset(data, string(k), inner)\n\t\t\treturn e\n\t\t}\n\t}\n}\n\nfunc set(data map[string]interface{}, key string, val interface{}) {\n\t\/\/ If key is empty, don't set it.\n\tif len(key) == 0 {\n\t\treturn\n\t}\n\tdata[key] = val\n}\n\nfunc setIndex(list []interface{}, index int, val interface{}) ([]interface{}, error) {\n\tif index < 0 {\n\t\treturn list, fmt.Errorf(\"negative %d index not allowed\", index)\n\t}\n\tif len(list) <= index {\n\t\tnewlist := make([]interface{}, index+1)\n\t\tcopy(newlist, list)\n\t\tlist = newlist\n\t}\n\tlist[index] = val\n\treturn list, nil\n}\n\nfunc (t *parser) keyIndex() (int, error) {\n\t\/\/ First, get the key.\n\tstop := runeSet([]rune{']'})\n\tv, _, err := runesUntil(t.sc, stop)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\t\/\/ v should be the index\n\treturn strconv.Atoi(string(v))\n\n}\nfunc (t *parser) listItem(list []interface{}, i int) ([]interface{}, error) {\n\tif i < 0 {\n\t\treturn list, fmt.Errorf(\"negative %d index not allowed\", i)\n\t}\n\tstop := runeSet([]rune{'[', '.', '='})\n\tswitch k, last, err := runesUntil(t.sc, stop); {\n\tcase len(k) > 0:\n\t\treturn list, errors.Errorf(\"unexpected data at end of array index: %q\", k)\n\tcase err != nil:\n\t\treturn list, err\n\tcase last == '=':\n\t\tvl, e := t.valList()\n\t\tswitch e {\n\t\tcase nil:\n\t\t\treturn setIndex(list, i, vl)\n\t\tcase io.EOF:\n\t\t\treturn setIndex(list, i, \"\")\n\t\tcase ErrNotList:\n\t\t\trs, e := t.val()\n\t\t\tif e != nil && e != io.EOF {\n\t\t\t\treturn list, e\n\t\t\t}\n\t\t\tv, e := t.reader(rs)\n\t\t\tif e != nil {\n\t\t\t\treturn list, e\n\t\t\t}\n\t\t\treturn setIndex(list, i, v)\n\t\tdefault:\n\t\t\treturn list, e\n\t\t}\n\tcase last == '[':\n\t\t\/\/ now we have a nested list. Read the index and handle.\n\t\ti, err := t.keyIndex()\n\t\tif err != nil {\n\t\t\treturn list, errors.Wrap(err, \"error parsing index\")\n\t\t}\n\t\t\/\/ Now we need to get the value after the ].\n\t\tlist2, err := t.listItem(list, i)\n\t\tif err != nil {\n\t\t\treturn list, err\n\t\t}\n\t\treturn setIndex(list, i, list2)\n\tcase last == '.':\n\t\t\/\/ We have a nested object. Send to t.key\n\t\tinner := map[string]interface{}{}\n\t\tif len(list) > i {\n\t\t\tvar ok bool\n\t\t\tinner, ok = list[i].(map[string]interface{})\n\t\t\tif !ok {\n\t\t\t\t\/\/ We have indices out of order. Initialize empty value.\n\t\t\t\tlist[i] = map[string]interface{}{}\n\t\t\t\tinner = list[i].(map[string]interface{})\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Recurse\n\t\te := t.key(inner)\n\t\tif e != nil {\n\t\t\treturn list, e\n\t\t}\n\t\treturn setIndex(list, i, inner)\n\tdefault:\n\t\treturn nil, errors.Errorf(\"parse error: unexpected token %v\", last)\n\t}\n}\n\nfunc (t *parser) val() ([]rune, error) {\n\tstop := runeSet([]rune{','})\n\tv, _, err := runesUntil(t.sc, stop)\n\treturn v, err\n}\n\nfunc (t *parser) valList() ([]interface{}, error) {\n\tr, _, e := t.sc.ReadRune()\n\tif e != nil {\n\t\treturn []interface{}{}, e\n\t}\n\n\tif r != '{' {\n\t\tt.sc.UnreadRune()\n\t\treturn []interface{}{}, ErrNotList\n\t}\n\n\tlist := []interface{}{}\n\tstop := runeSet([]rune{',', '}'})\n\tfor {\n\t\tswitch rs, last, err := runesUntil(t.sc, stop); {\n\t\tcase err != nil:\n\t\t\tif err == io.EOF {\n\t\t\t\terr = errors.New(\"list must terminate with '}'\")\n\t\t\t}\n\t\t\treturn list, err\n\t\tcase last == '}':\n\t\t\t\/\/ If this is followed by ',', consume it.\n\t\t\tif r, _, e := t.sc.ReadRune(); e == nil && r != ',' {\n\t\t\t\tt.sc.UnreadRune()\n\t\t\t}\n\t\t\tv, e := t.reader(rs)\n\t\t\tlist = append(list, v)\n\t\t\treturn list, e\n\t\tcase last == ',':\n\t\t\tv, e := t.reader(rs)\n\t\t\tif e != nil {\n\t\t\t\treturn list, e\n\t\t\t}\n\t\t\tlist = append(list, v)\n\t\t}\n\t}\n}\n\nfunc runesUntil(in io.RuneReader, stop map[rune]bool) ([]rune, rune, error) {\n\tv := []rune{}\n\tfor {\n\t\tswitch r, _, e := in.ReadRune(); {\n\t\tcase e != nil:\n\t\t\treturn v, r, e\n\t\tcase inMap(r, stop):\n\t\t\treturn v, r, nil\n\t\tcase r == '\\\\':\n\t\t\tnext, _, e := in.ReadRune()\n\t\t\tif e != nil {\n\t\t\t\treturn v, next, e\n\t\t\t}\n\t\t\tv = append(v, next)\n\t\tdefault:\n\t\t\tv = append(v, r)\n\t\t}\n\t}\n}\n\nfunc inMap(k rune, m map[rune]bool) bool {\n\t_, ok := m[k]\n\treturn ok\n}\n\nfunc typedVal(v []rune, st bool) interface{} {\n\tval := string(v)\n\n\tif st {\n\t\treturn val\n\t}\n\n\tif strings.EqualFold(val, \"true\") {\n\t\treturn true\n\t}\n\n\tif strings.EqualFold(val, \"false\") {\n\t\treturn false\n\t}\n\n\tif strings.EqualFold(val, \"null\") {\n\t\treturn nil\n\t}\n\n\tif strings.EqualFold(val, \"0\") {\n\t\treturn int64(0)\n\t}\n\n\t\/\/ If this value does not start with zero, try parsing it to an int\n\tif len(val) != 0 && val[0] != '0' {\n\t\tif iv, err := strconv.ParseInt(val, 10, 64); err == nil {\n\t\t\treturn iv\n\t\t}\n\t}\n\n\treturn val\n}\n<commit_msg>Recovering from panic that can occur with make<commit_after>\/*\nCopyright The Helm Authors.\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage strvals\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"sigs.k8s.io\/yaml\"\n)\n\n\/\/ ErrNotList indicates that a non-list was treated as a list.\nvar ErrNotList = errors.New(\"not a list\")\n\n\/\/ ToYAML takes a string of arguments and converts to a YAML document.\nfunc ToYAML(s string) (string, error) {\n\tm, err := Parse(s)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\td, err := yaml.Marshal(m)\n\treturn strings.TrimSuffix(string(d), \"\\n\"), err\n}\n\n\/\/ Parse parses a set line.\n\/\/\n\/\/ A set line is of the form name1=value1,name2=value2\nfunc Parse(s string) (map[string]interface{}, error) {\n\tvals := map[string]interface{}{}\n\tscanner := bytes.NewBufferString(s)\n\tt := newParser(scanner, vals, false)\n\terr := t.parse()\n\treturn vals, err\n}\n\n\/\/ ParseString parses a set line and forces a string value.\n\/\/\n\/\/ A set line is of the form name1=value1,name2=value2\nfunc ParseString(s string) (map[string]interface{}, error) {\n\tvals := map[string]interface{}{}\n\tscanner := bytes.NewBufferString(s)\n\tt := newParser(scanner, vals, true)\n\terr := t.parse()\n\treturn vals, err\n}\n\n\/\/ ParseInto parses a strvals line and merges the result into dest.\n\/\/\n\/\/ If the strval string has a key that exists in dest, it overwrites the\n\/\/ dest version.\nfunc ParseInto(s string, dest map[string]interface{}) error {\n\tscanner := bytes.NewBufferString(s)\n\tt := newParser(scanner, dest, false)\n\treturn t.parse()\n}\n\n\/\/ ParseFile parses a set line, but its final value is loaded from the file at the path specified by the original value.\n\/\/\n\/\/ A set line is of the form name1=path1,name2=path2\n\/\/\n\/\/ When the files at path1 and path2 contained \"val1\" and \"val2\" respectively, the set line is consumed as\n\/\/ name1=val1,name2=val2\nfunc ParseFile(s string, reader RunesValueReader) (map[string]interface{}, error) {\n\tvals := map[string]interface{}{}\n\tscanner := bytes.NewBufferString(s)\n\tt := newFileParser(scanner, vals, reader)\n\terr := t.parse()\n\treturn vals, err\n}\n\n\/\/ ParseIntoString parses a strvals line and merges the result into dest.\n\/\/\n\/\/ This method always returns a string as the value.\nfunc ParseIntoString(s string, dest map[string]interface{}) error {\n\tscanner := bytes.NewBufferString(s)\n\tt := newParser(scanner, dest, true)\n\treturn t.parse()\n}\n\n\/\/ ParseIntoFile parses a filevals line and merges the result into dest.\n\/\/\n\/\/ This method always returns a string as the value.\nfunc ParseIntoFile(s string, dest map[string]interface{}, reader RunesValueReader) error {\n\tscanner := bytes.NewBufferString(s)\n\tt := newFileParser(scanner, dest, reader)\n\treturn t.parse()\n}\n\n\/\/ RunesValueReader is a function that takes the given value (a slice of runes)\n\/\/ and returns the parsed value\ntype RunesValueReader func([]rune) (interface{}, error)\n\n\/\/ parser is a simple parser that takes a strvals line and parses it into a\n\/\/ map representation.\n\/\/\n\/\/ where sc is the source of the original data being parsed\n\/\/ where data is the final parsed data from the parses with correct types\ntype parser struct {\n\tsc     *bytes.Buffer\n\tdata   map[string]interface{}\n\treader RunesValueReader\n}\n\nfunc newParser(sc *bytes.Buffer, data map[string]interface{}, stringBool bool) *parser {\n\tstringConverter := func(rs []rune) (interface{}, error) {\n\t\treturn typedVal(rs, stringBool), nil\n\t}\n\treturn &parser{sc: sc, data: data, reader: stringConverter}\n}\n\nfunc newFileParser(sc *bytes.Buffer, data map[string]interface{}, reader RunesValueReader) *parser {\n\treturn &parser{sc: sc, data: data, reader: reader}\n}\n\nfunc (t *parser) parse() error {\n\tfor {\n\t\terr := t.key(t.data)\n\t\tif err == nil {\n\t\t\tcontinue\n\t\t}\n\t\tif err == io.EOF {\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n}\n\nfunc runeSet(r []rune) map[rune]bool {\n\ts := make(map[rune]bool, len(r))\n\tfor _, rr := range r {\n\t\ts[rr] = true\n\t}\n\treturn s\n}\n\nfunc (t *parser) key(data map[string]interface{}) error {\n\tstop := runeSet([]rune{'=', '[', ',', '.'})\n\tfor {\n\t\tswitch k, last, err := runesUntil(t.sc, stop); {\n\t\tcase err != nil:\n\t\t\tif len(k) == 0 {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn errors.Errorf(\"key %q has no value\", string(k))\n\t\t\t\/\/set(data, string(k), \"\")\n\t\t\t\/\/return err\n\t\tcase last == '[':\n\t\t\t\/\/ We are in a list index context, so we need to set an index.\n\t\t\ti, err := t.keyIndex()\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"error parsing index\")\n\t\t\t}\n\t\t\tkk := string(k)\n\t\t\t\/\/ Find or create target list\n\t\t\tlist := []interface{}{}\n\t\t\tif _, ok := data[kk]; ok {\n\t\t\t\tlist = data[kk].([]interface{})\n\t\t\t}\n\n\t\t\t\/\/ Now we need to get the value after the ].\n\t\t\tlist, err = t.listItem(list, i)\n\t\t\tset(data, kk, list)\n\t\t\treturn err\n\t\tcase last == '=':\n\t\t\t\/\/End of key. Consume =, Get value.\n\t\t\t\/\/ FIXME: Get value list first\n\t\t\tvl, e := t.valList()\n\t\t\tswitch e {\n\t\t\tcase nil:\n\t\t\t\tset(data, string(k), vl)\n\t\t\t\treturn nil\n\t\t\tcase io.EOF:\n\t\t\t\tset(data, string(k), \"\")\n\t\t\t\treturn e\n\t\t\tcase ErrNotList:\n\t\t\t\trs, e := t.val()\n\t\t\t\tif e != nil && e != io.EOF {\n\t\t\t\t\treturn e\n\t\t\t\t}\n\t\t\t\tv, e := t.reader(rs)\n\t\t\t\tset(data, string(k), v)\n\t\t\t\treturn e\n\t\t\tdefault:\n\t\t\t\treturn e\n\t\t\t}\n\n\t\tcase last == ',':\n\t\t\t\/\/ No value given. Set the value to empty string. Return error.\n\t\t\tset(data, string(k), \"\")\n\t\t\treturn errors.Errorf(\"key %q has no value (cannot end with ,)\", string(k))\n\t\tcase last == '.':\n\t\t\t\/\/ First, create or find the target map.\n\t\t\tinner := map[string]interface{}{}\n\t\t\tif _, ok := data[string(k)]; ok {\n\t\t\t\tinner = data[string(k)].(map[string]interface{})\n\t\t\t}\n\n\t\t\t\/\/ Recurse\n\t\t\te := t.key(inner)\n\t\t\tif len(inner) == 0 {\n\t\t\t\treturn errors.Errorf(\"key map %q has no value\", string(k))\n\t\t\t}\n\t\t\tset(data, string(k), inner)\n\t\t\treturn e\n\t\t}\n\t}\n}\n\nfunc set(data map[string]interface{}, key string, val interface{}) {\n\t\/\/ If key is empty, don't set it.\n\tif len(key) == 0 {\n\t\treturn\n\t}\n\tdata[key] = val\n}\n\nfunc setIndex(list []interface{}, index int, val interface{}) (l2 []interface{}, err error) {\n\t\/\/ There are possible index values that are out of range on a target system\n\t\/\/ causing a panic. This will catch the panic and return an error instead.\n\t\/\/ The value of the index that causes a panic varies from system to system.\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\terr = fmt.Errorf(\"error processing index %d: %s\", index, r)\n\t\t}\n\t}()\n\n\tif index < 0 {\n\t\treturn list, fmt.Errorf(\"negative %d index not allowed\", index)\n\t}\n\tif len(list) <= index {\n\t\tnewlist := make([]interface{}, index+1)\n\t\tcopy(newlist, list)\n\t\tlist = newlist\n\t}\n\tlist[index] = val\n\treturn list, nil\n}\n\nfunc (t *parser) keyIndex() (int, error) {\n\t\/\/ First, get the key.\n\tstop := runeSet([]rune{']'})\n\tv, _, err := runesUntil(t.sc, stop)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\t\/\/ v should be the index\n\treturn strconv.Atoi(string(v))\n\n}\nfunc (t *parser) listItem(list []interface{}, i int) ([]interface{}, error) {\n\tif i < 0 {\n\t\treturn list, fmt.Errorf(\"negative %d index not allowed\", i)\n\t}\n\tstop := runeSet([]rune{'[', '.', '='})\n\tswitch k, last, err := runesUntil(t.sc, stop); {\n\tcase len(k) > 0:\n\t\treturn list, errors.Errorf(\"unexpected data at end of array index: %q\", k)\n\tcase err != nil:\n\t\treturn list, err\n\tcase last == '=':\n\t\tvl, e := t.valList()\n\t\tswitch e {\n\t\tcase nil:\n\t\t\treturn setIndex(list, i, vl)\n\t\tcase io.EOF:\n\t\t\treturn setIndex(list, i, \"\")\n\t\tcase ErrNotList:\n\t\t\trs, e := t.val()\n\t\t\tif e != nil && e != io.EOF {\n\t\t\t\treturn list, e\n\t\t\t}\n\t\t\tv, e := t.reader(rs)\n\t\t\tif e != nil {\n\t\t\t\treturn list, e\n\t\t\t}\n\t\t\treturn setIndex(list, i, v)\n\t\tdefault:\n\t\t\treturn list, e\n\t\t}\n\tcase last == '[':\n\t\t\/\/ now we have a nested list. Read the index and handle.\n\t\ti, err := t.keyIndex()\n\t\tif err != nil {\n\t\t\treturn list, errors.Wrap(err, \"error parsing index\")\n\t\t}\n\t\t\/\/ Now we need to get the value after the ].\n\t\tlist2, err := t.listItem(list, i)\n\t\tif err != nil {\n\t\t\treturn list, err\n\t\t}\n\t\treturn setIndex(list, i, list2)\n\tcase last == '.':\n\t\t\/\/ We have a nested object. Send to t.key\n\t\tinner := map[string]interface{}{}\n\t\tif len(list) > i {\n\t\t\tvar ok bool\n\t\t\tinner, ok = list[i].(map[string]interface{})\n\t\t\tif !ok {\n\t\t\t\t\/\/ We have indices out of order. Initialize empty value.\n\t\t\t\tlist[i] = map[string]interface{}{}\n\t\t\t\tinner = list[i].(map[string]interface{})\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Recurse\n\t\te := t.key(inner)\n\t\tif e != nil {\n\t\t\treturn list, e\n\t\t}\n\t\treturn setIndex(list, i, inner)\n\tdefault:\n\t\treturn nil, errors.Errorf(\"parse error: unexpected token %v\", last)\n\t}\n}\n\nfunc (t *parser) val() ([]rune, error) {\n\tstop := runeSet([]rune{','})\n\tv, _, err := runesUntil(t.sc, stop)\n\treturn v, err\n}\n\nfunc (t *parser) valList() ([]interface{}, error) {\n\tr, _, e := t.sc.ReadRune()\n\tif e != nil {\n\t\treturn []interface{}{}, e\n\t}\n\n\tif r != '{' {\n\t\tt.sc.UnreadRune()\n\t\treturn []interface{}{}, ErrNotList\n\t}\n\n\tlist := []interface{}{}\n\tstop := runeSet([]rune{',', '}'})\n\tfor {\n\t\tswitch rs, last, err := runesUntil(t.sc, stop); {\n\t\tcase err != nil:\n\t\t\tif err == io.EOF {\n\t\t\t\terr = errors.New(\"list must terminate with '}'\")\n\t\t\t}\n\t\t\treturn list, err\n\t\tcase last == '}':\n\t\t\t\/\/ If this is followed by ',', consume it.\n\t\t\tif r, _, e := t.sc.ReadRune(); e == nil && r != ',' {\n\t\t\t\tt.sc.UnreadRune()\n\t\t\t}\n\t\t\tv, e := t.reader(rs)\n\t\t\tlist = append(list, v)\n\t\t\treturn list, e\n\t\tcase last == ',':\n\t\t\tv, e := t.reader(rs)\n\t\t\tif e != nil {\n\t\t\t\treturn list, e\n\t\t\t}\n\t\t\tlist = append(list, v)\n\t\t}\n\t}\n}\n\nfunc runesUntil(in io.RuneReader, stop map[rune]bool) ([]rune, rune, error) {\n\tv := []rune{}\n\tfor {\n\t\tswitch r, _, e := in.ReadRune(); {\n\t\tcase e != nil:\n\t\t\treturn v, r, e\n\t\tcase inMap(r, stop):\n\t\t\treturn v, r, nil\n\t\tcase r == '\\\\':\n\t\t\tnext, _, e := in.ReadRune()\n\t\t\tif e != nil {\n\t\t\t\treturn v, next, e\n\t\t\t}\n\t\t\tv = append(v, next)\n\t\tdefault:\n\t\t\tv = append(v, r)\n\t\t}\n\t}\n}\n\nfunc inMap(k rune, m map[rune]bool) bool {\n\t_, ok := m[k]\n\treturn ok\n}\n\nfunc typedVal(v []rune, st bool) interface{} {\n\tval := string(v)\n\n\tif st {\n\t\treturn val\n\t}\n\n\tif strings.EqualFold(val, \"true\") {\n\t\treturn true\n\t}\n\n\tif strings.EqualFold(val, \"false\") {\n\t\treturn false\n\t}\n\n\tif strings.EqualFold(val, \"null\") {\n\t\treturn nil\n\t}\n\n\tif strings.EqualFold(val, \"0\") {\n\t\treturn int64(0)\n\t}\n\n\t\/\/ If this value does not start with zero, try parsing it to an int\n\tif len(val) != 0 && val[0] != '0' {\n\t\tif iv, err := strconv.ParseInt(val, 10, 64); err == nil {\n\t\t\treturn iv\n\t\t}\n\t}\n\n\treturn val\n}\n<|endoftext|>"}
{"text":"<commit_before>package test\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\/exec\"\n\t\"time\"\n)\n\nconst (\n\tetcdChkTimes = 10\n\tetcdChkDelay = time.Second\n)\n\nfunc init() {\n\tRegisterService(Etcd, func() Service {\n\t\treturn &etcdService{}\n\t})\n}\n\ntype etcdService struct {\n\tports   []int\n\tworkDir string\n\tcmd     *exec.Cmd\n}\n\nfunc (s *etcdService) Start() (int, error) {\n\t\/\/ perform default check\n\tif err := CheckExecutable(\"etcd\"); err != nil {\n\t\treturn 0, err\n\t}\n\n\t\/\/ booking 2 ports\n\tvar err error\n\ts.ports, err = BookPorts(2)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"fail to book ports, err:%v\", err)\n\t}\n\n\t\/\/ prepare tmp dir\n\ts.workDir, err = ioutil.TempDir(\"\", \"etcd-test\")\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"fail to prepare tmp dir, err:%v\", err)\n\t}\n\n\ts.cmd = exec.Command(\n\t\t\"etcd\",\n\t\tfmt.Sprintf(\"-bind-addr=0.0.0.0:%d\", s.ports[0]),\n\t\tfmt.Sprintf(\"-peer-bind-addr=0.0.0.0:%d\", s.ports[1]),\n\t\tfmt.Sprintf(\"-data-dir=%s\", s.workDir),\n\t\tfmt.Sprintf(\"-name=m%d\", s.ports[0]),\n\t)\n\tif err := s.cmd.Start(); err != nil {\n\t\treturn 0, err\n\t}\n\n\tfor i := 0; i < etcdChkTimes; i++ {\n\t\ttime.Sleep(etcdChkDelay)\n\t\tif CheckListening(s.ports[0]) {\n\t\t\treturn s.ports[0], nil\n\t\t}\n\t}\n\t\/\/ only need region server thrift port\n\treturn 0, fmt.Errorf(\"fail to start etcd\")\n}\n\nfunc (s *etcdService) Stop() error {\n\t\/\/ close process\n\treturn s.cmd.Process.Kill()\n}\n<commit_msg>Adopt commands for etcd 3.x<commit_after>package test\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\/exec\"\n\t\"time\"\n)\n\nconst (\n\tetcdChkTimes = 10\n\tetcdChkDelay = time.Second\n)\n\nfunc init() {\n\tRegisterService(Etcd, func() Service {\n\t\treturn &etcdService{}\n\t})\n}\n\ntype etcdService struct {\n\tports   []int\n\tworkDir string\n\tcmd     *exec.Cmd\n}\n\nfunc (s *etcdService) Start() (int, error) {\n\t\/\/ perform default check\n\tif err := CheckExecutable(\"etcd\"); err != nil {\n\t\treturn 0, err\n\t}\n\n\t\/\/ booking 2 ports\n\tvar err error\n\ts.ports, err = BookPorts(2)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"fail to book ports, err:%v\", err)\n\t}\n\n\t\/\/ prepare tmp dir\n\ts.workDir, err = ioutil.TempDir(\"\", \"etcd-test\")\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"fail to prepare tmp dir, err:%v\", err)\n\t}\n\n\ts.cmd = exec.Command(\n\t\t\"etcd\",\n\t\tfmt.Sprintf(\"--listen-client-urls=http:\/\/0.0.0.0:%d\", s.ports[0]),\n\t\tfmt.Sprintf(\"--advertise-client-urls=http:\/\/0.0.0.0:%d\", s.ports[0]),\n\t\tfmt.Sprintf(\"-data-dir=%s\", s.workDir),\n\t\tfmt.Sprintf(\"-name=m%d\", s.ports[0]),\n\t)\n\tif err := s.cmd.Start(); err != nil {\n\t\treturn 0, err\n\t}\n\n\tfor i := 0; i < etcdChkTimes; i++ {\n\t\ttime.Sleep(etcdChkDelay)\n\t\tif CheckListening(s.ports[0]) {\n\t\t\treturn s.ports[0], nil\n\t\t}\n\t}\n\t\/\/ only need region server thrift port\n\treturn 0, fmt.Errorf(\"fail to start etcd\")\n}\n\nfunc (s *etcdService) Stop() error {\n\t\/\/ close process\n\tif err := s.cmd.Process.Kill(); err != nil {\n\t\treturn err\n\t}\n\ttime.Sleep(time.Second)\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2014 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage wait\n\nimport (\n\t\"errors\"\n\t\"math\/rand\"\n\t\"time\"\n\n\t\"k8s.io\/apimachinery\/pkg\/util\/runtime\"\n)\n\n\/\/ For any test of the style:\n\/\/   ...\n\/\/   <- time.After(timeout):\n\/\/      t.Errorf(\"Timed out\")\n\/\/ The value for timeout should effectively be \"forever.\" Obviously we don't want our tests to truly lock up forever, but 30s\n\/\/ is long enough that it is effectively forever for the things that can slow down a run on a heavily contended machine\n\/\/ (GC, seeks, etc), but not so long as to make a developer ctrl-c a test run if they do happen to break that test.\nvar ForeverTestTimeout = time.Second * 30\n\n\/\/ NeverStop may be passed to Until to make it never stop.\nvar NeverStop <-chan struct{} = make(chan struct{})\n\n\/\/ Forever calls f every period for ever.\n\/\/\n\/\/ Forever is syntactic sugar on top of Until.\nfunc Forever(f func(), period time.Duration) {\n\tUntil(f, period, NeverStop)\n}\n\n\/\/ Until loops until stop channel is closed, running f every period.\n\/\/\n\/\/ Until is syntactic sugar on top of JitterUntil with zero jitter factor and\n\/\/ with sliding = true (which means the timer for period starts after the f\n\/\/ completes).\nfunc Until(f func(), period time.Duration, stopCh <-chan struct{}) {\n\tJitterUntil(f, period, 0.0, true, stopCh)\n}\n\n\/\/ NonSlidingUntil loops until stop channel is closed, running f every\n\/\/ period.\n\/\/\n\/\/ NonSlidingUntil is syntactic sugar on top of JitterUntil with zero jitter\n\/\/ factor, with sliding = false (meaning the timer for period starts at the same\n\/\/ time as the function starts).\nfunc NonSlidingUntil(f func(), period time.Duration, stopCh <-chan struct{}) {\n\tJitterUntil(f, period, 0.0, false, stopCh)\n}\n\n\/\/ JitterUntil loops until stop channel is closed, running f every period.\n\/\/\n\/\/ If jitterFactor is positive, the period is jittered before every run of f.\n\/\/ If jitterFactor is not positive, the period is unchanged and not jittered.\n\/\/\n\/\/ If sliding is true, the period is computed after f runs. If it is false then\n\/\/ period includes the runtime for f.\n\/\/\n\/\/ Close stopCh to stop. f may not be invoked if stop channel is already\n\/\/ closed. Pass NeverStop to if you don't want it stop.\nfunc JitterUntil(f func(), period time.Duration, jitterFactor float64, sliding bool, stopCh <-chan struct{}) {\n\tvar t *time.Timer\n\tvar sawTimeout bool\n\n\tfor {\n\t\tselect {\n\t\tcase <-stopCh:\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\n\t\tjitteredPeriod := period\n\t\tif jitterFactor > 0.0 {\n\t\t\tjitteredPeriod = Jitter(period, jitterFactor)\n\t\t}\n\n\t\tif !sliding {\n\t\t\tt = resetOrReuseTimer(t, jitteredPeriod, sawTimeout)\n\t\t}\n\n\t\tfunc() {\n\t\t\tdefer runtime.HandleCrash()\n\t\t\tf()\n\t\t}()\n\n\t\tif sliding {\n\t\t\tt = resetOrReuseTimer(t, jitteredPeriod, sawTimeout)\n\t\t}\n\n\t\t\/\/ NOTE: b\/c there is no priority selection in golang\n\t\t\/\/ it is possible for this to race, meaning we could\n\t\t\/\/ trigger t.C and stopCh, and t.C select falls through.\n\t\t\/\/ In order to mitigate we re-check stopCh at the beginning\n\t\t\/\/ of every loop to prevent extra executions of f().\n\t\tselect {\n\t\tcase <-stopCh:\n\t\t\treturn\n\t\tcase <-t.C:\n\t\t\tsawTimeout = true\n\t\t}\n\t}\n}\n\n\/\/ Jitter returns a time.Duration between duration and duration + maxFactor *\n\/\/ duration.\n\/\/\n\/\/ This allows clients to avoid converging on periodic behavior. If maxFactor\n\/\/ is 0.0, a suggested default value will be chosen.\nfunc Jitter(duration time.Duration, maxFactor float64) time.Duration {\n\tif maxFactor <= 0.0 {\n\t\tmaxFactor = 1.0\n\t}\n\twait := duration + time.Duration(rand.Float64()*maxFactor*float64(duration))\n\treturn wait\n}\n\n\/\/ ErrWaitTimeout is returned when the condition exited without success.\nvar ErrWaitTimeout = errors.New(\"timed out waiting for the condition\")\n\n\/\/ ConditionFunc returns true if the condition is satisfied, or an error\n\/\/ if the loop should be aborted.\ntype ConditionFunc func() (done bool, err error)\n\n\/\/ Backoff holds parameters applied to a Backoff function.\ntype Backoff struct {\n\tDuration time.Duration \/\/ the base duration\n\tFactor   float64       \/\/ Duration is multiplied by factor each iteration\n\tJitter   float64       \/\/ The amount of jitter applied each iteration\n\tSteps    int           \/\/ Exit with error after this many steps\n}\n\n\/\/ ExponentialBackoff repeats a condition check with exponential backoff.\n\/\/\n\/\/ It checks the condition up to Steps times, increasing the wait by multiplying\n\/\/ the previous duration by Factor.\n\/\/\n\/\/ If Jitter is greater than zero, a random amount of each duration is added\n\/\/ (between duration and duration*(1+jitter)).\n\/\/\n\/\/ If the condition never returns true, ErrWaitTimeout is returned. All other\n\/\/ errors terminate immediately.\nfunc ExponentialBackoff(backoff Backoff, condition ConditionFunc) error {\n\tduration := backoff.Duration\n\tfor i := 0; i < backoff.Steps; i++ {\n\t\tif i != 0 {\n\t\t\tadjusted := duration\n\t\t\tif backoff.Jitter > 0.0 {\n\t\t\t\tadjusted = Jitter(duration, backoff.Jitter)\n\t\t\t}\n\t\t\ttime.Sleep(adjusted)\n\t\t\tduration = time.Duration(float64(duration) * backoff.Factor)\n\t\t}\n\t\tif ok, err := condition(); err != nil || ok {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn ErrWaitTimeout\n}\n\n\/\/ Poll tries a condition func until it returns true, an error, or the timeout\n\/\/ is reached.\n\/\/\n\/\/ Poll always waits the interval before the run of 'condition'.\n\/\/ 'condition' will always be invoked at least once.\n\/\/\n\/\/ Some intervals may be missed if the condition takes too long or the time\n\/\/ window is too short.\n\/\/\n\/\/ If you want to Poll something forever, see PollInfinite.\nfunc Poll(interval, timeout time.Duration, condition ConditionFunc) error {\n\treturn pollInternal(poller(interval, timeout), condition)\n}\n\nfunc pollInternal(wait WaitFunc, condition ConditionFunc) error {\n\tdone := make(chan struct{})\n\tdefer close(done)\n\treturn WaitFor(wait, condition, done)\n}\n\n\/\/ PollImmediate tries a condition func until it returns true, an error, or the timeout\n\/\/ is reached.\n\/\/\n\/\/ Poll always checks 'condition' before waiting for the interval. 'condition'\n\/\/ will always be invoked at least once.\n\/\/\n\/\/ Some intervals may be missed if the condition takes too long or the time\n\/\/ window is too short.\n\/\/\n\/\/ If you want to Poll something forever, see PollInfinite.\nfunc PollImmediate(interval, timeout time.Duration, condition ConditionFunc) error {\n\treturn pollImmediateInternal(poller(interval, timeout), condition)\n}\n\nfunc pollImmediateInternal(wait WaitFunc, condition ConditionFunc) error {\n\tdone, err := condition()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif done {\n\t\treturn nil\n\t}\n\treturn pollInternal(wait, condition)\n}\n\n\/\/ PollInfinite tries a condition func until it returns true or an error\n\/\/\n\/\/ PollInfinite always waits the interval before the run of 'condition'.\n\/\/\n\/\/ Some intervals may be missed if the condition takes too long or the time\n\/\/ window is too short.\nfunc PollInfinite(interval time.Duration, condition ConditionFunc) error {\n\tdone := make(chan struct{})\n\tdefer close(done)\n\treturn PollUntil(interval, condition, done)\n}\n\n\/\/ PollImmediateInfinite tries a condition func until it returns true or an error\n\/\/\n\/\/ PollImmediateInfinite runs the 'condition' before waiting for the interval.\n\/\/\n\/\/ Some intervals may be missed if the condition takes too long or the time\n\/\/ window is too short.\nfunc PollImmediateInfinite(interval time.Duration, condition ConditionFunc) error {\n\tdone, err := condition()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif done {\n\t\treturn nil\n\t}\n\treturn PollInfinite(interval, condition)\n}\n\n\/\/ PollUntil tries a condition func until it returns true, an error or stopCh is\n\/\/ closed.\n\/\/\n\/\/ PolUntil always waits interval before the first run of 'condition'.\n\/\/ 'condition' will always be invoked at least once.\nfunc PollUntil(interval time.Duration, condition ConditionFunc, stopCh <-chan struct{}) error {\n\treturn WaitFor(poller(interval, 0), condition, stopCh)\n}\n\n\/\/ WaitFunc creates a channel that receives an item every time a test\n\/\/ should be executed and is closed when the last test should be invoked.\ntype WaitFunc func(done <-chan struct{}) <-chan struct{}\n\n\/\/ WaitFor continually checks 'fn' as driven by 'wait'.\n\/\/\n\/\/ WaitFor gets a channel from 'wait()'', and then invokes 'fn' once for every value\n\/\/ placed on the channel and once more when the channel is closed.\n\/\/\n\/\/ If 'fn' returns an error the loop ends and that error is returned, and if\n\/\/ 'fn' returns true the loop ends and nil is returned.\n\/\/\n\/\/ ErrWaitTimeout will be returned if the channel is closed without fn ever\n\/\/ returning true.\nfunc WaitFor(wait WaitFunc, fn ConditionFunc, done <-chan struct{}) error {\n\tc := wait(done)\n\tfor {\n\t\t_, open := <-c\n\t\tok, err := fn()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif ok {\n\t\t\treturn nil\n\t\t}\n\t\tif !open {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn ErrWaitTimeout\n}\n\n\/\/ poller returns a WaitFunc that will send to the channel every interval until\n\/\/ timeout has elapsed and then closes the channel.\n\/\/\n\/\/ Over very short intervals you may receive no ticks before the channel is\n\/\/ closed. A timeout of 0 is interpreted as an infinity.\n\/\/\n\/\/ Output ticks are not buffered. If the channel is not ready to receive an\n\/\/ item, the tick is skipped.\nfunc poller(interval, timeout time.Duration) WaitFunc {\n\treturn WaitFunc(func(done <-chan struct{}) <-chan struct{} {\n\t\tch := make(chan struct{})\n\n\t\tgo func() {\n\t\t\tdefer close(ch)\n\n\t\t\ttick := time.NewTicker(interval)\n\t\t\tdefer tick.Stop()\n\n\t\t\tvar after <-chan time.Time\n\t\t\tif timeout != 0 {\n\t\t\t\t\/\/ time.After is more convenient, but it\n\t\t\t\t\/\/ potentially leaves timers around much longer\n\t\t\t\t\/\/ than necessary if we exit early.\n\t\t\t\ttimer := time.NewTimer(timeout)\n\t\t\t\tafter = timer.C\n\t\t\t\tdefer timer.Stop()\n\t\t\t}\n\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase <-tick.C:\n\t\t\t\t\t\/\/ If the consumer isn't ready for this signal drop it and\n\t\t\t\t\t\/\/ check the other channels.\n\t\t\t\t\tselect {\n\t\t\t\t\tcase ch <- struct{}{}:\n\t\t\t\t\tdefault:\n\t\t\t\t\t}\n\t\t\t\tcase <-after:\n\t\t\t\t\treturn\n\t\t\t\tcase <-done:\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\n\t\treturn ch\n\t})\n}\n\n\/\/ resetOrReuseTimer avoids allocating a new timer if one is already in use.\n\/\/ Not safe for multiple threads.\nfunc resetOrReuseTimer(t *time.Timer, d time.Duration, sawTimeout bool) *time.Timer {\n\tif t == nil {\n\t\treturn time.NewTimer(d)\n\t}\n\tif !t.Stop() && !sawTimeout {\n\t\t<-t.C\n\t}\n\tt.Reset(d)\n\treturn t\n}\n<commit_msg>Shared Informer Run blocks until all goroutines finish<commit_after>\/*\nCopyright 2014 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage wait\n\nimport (\n\t\"errors\"\n\t\"math\/rand\"\n\t\"sync\"\n\t\"time\"\n\n\t\"k8s.io\/apimachinery\/pkg\/util\/runtime\"\n)\n\n\/\/ For any test of the style:\n\/\/   ...\n\/\/   <- time.After(timeout):\n\/\/      t.Errorf(\"Timed out\")\n\/\/ The value for timeout should effectively be \"forever.\" Obviously we don't want our tests to truly lock up forever, but 30s\n\/\/ is long enough that it is effectively forever for the things that can slow down a run on a heavily contended machine\n\/\/ (GC, seeks, etc), but not so long as to make a developer ctrl-c a test run if they do happen to break that test.\nvar ForeverTestTimeout = time.Second * 30\n\n\/\/ NeverStop may be passed to Until to make it never stop.\nvar NeverStop <-chan struct{} = make(chan struct{})\n\n\/\/ StartUntil starts f in a new goroutine and calls done once f has finished.\nfunc StartUntil(stopCh <-chan struct{}, wg *sync.WaitGroup, f func(stopCh <-chan struct{})) {\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tf(stopCh)\n\t}()\n}\n\n\/\/ Forever calls f every period for ever.\n\/\/\n\/\/ Forever is syntactic sugar on top of Until.\nfunc Forever(f func(), period time.Duration) {\n\tUntil(f, period, NeverStop)\n}\n\n\/\/ Until loops until stop channel is closed, running f every period.\n\/\/\n\/\/ Until is syntactic sugar on top of JitterUntil with zero jitter factor and\n\/\/ with sliding = true (which means the timer for period starts after the f\n\/\/ completes).\nfunc Until(f func(), period time.Duration, stopCh <-chan struct{}) {\n\tJitterUntil(f, period, 0.0, true, stopCh)\n}\n\n\/\/ NonSlidingUntil loops until stop channel is closed, running f every\n\/\/ period.\n\/\/\n\/\/ NonSlidingUntil is syntactic sugar on top of JitterUntil with zero jitter\n\/\/ factor, with sliding = false (meaning the timer for period starts at the same\n\/\/ time as the function starts).\nfunc NonSlidingUntil(f func(), period time.Duration, stopCh <-chan struct{}) {\n\tJitterUntil(f, period, 0.0, false, stopCh)\n}\n\n\/\/ JitterUntil loops until stop channel is closed, running f every period.\n\/\/\n\/\/ If jitterFactor is positive, the period is jittered before every run of f.\n\/\/ If jitterFactor is not positive, the period is unchanged and not jittered.\n\/\/\n\/\/ If sliding is true, the period is computed after f runs. If it is false then\n\/\/ period includes the runtime for f.\n\/\/\n\/\/ Close stopCh to stop. f may not be invoked if stop channel is already\n\/\/ closed. Pass NeverStop to if you don't want it stop.\nfunc JitterUntil(f func(), period time.Duration, jitterFactor float64, sliding bool, stopCh <-chan struct{}) {\n\tvar t *time.Timer\n\tvar sawTimeout bool\n\n\tfor {\n\t\tselect {\n\t\tcase <-stopCh:\n\t\t\treturn\n\t\tdefault:\n\t\t}\n\n\t\tjitteredPeriod := period\n\t\tif jitterFactor > 0.0 {\n\t\t\tjitteredPeriod = Jitter(period, jitterFactor)\n\t\t}\n\n\t\tif !sliding {\n\t\t\tt = resetOrReuseTimer(t, jitteredPeriod, sawTimeout)\n\t\t}\n\n\t\tfunc() {\n\t\t\tdefer runtime.HandleCrash()\n\t\t\tf()\n\t\t}()\n\n\t\tif sliding {\n\t\t\tt = resetOrReuseTimer(t, jitteredPeriod, sawTimeout)\n\t\t}\n\n\t\t\/\/ NOTE: b\/c there is no priority selection in golang\n\t\t\/\/ it is possible for this to race, meaning we could\n\t\t\/\/ trigger t.C and stopCh, and t.C select falls through.\n\t\t\/\/ In order to mitigate we re-check stopCh at the beginning\n\t\t\/\/ of every loop to prevent extra executions of f().\n\t\tselect {\n\t\tcase <-stopCh:\n\t\t\treturn\n\t\tcase <-t.C:\n\t\t\tsawTimeout = true\n\t\t}\n\t}\n}\n\n\/\/ Jitter returns a time.Duration between duration and duration + maxFactor *\n\/\/ duration.\n\/\/\n\/\/ This allows clients to avoid converging on periodic behavior. If maxFactor\n\/\/ is 0.0, a suggested default value will be chosen.\nfunc Jitter(duration time.Duration, maxFactor float64) time.Duration {\n\tif maxFactor <= 0.0 {\n\t\tmaxFactor = 1.0\n\t}\n\twait := duration + time.Duration(rand.Float64()*maxFactor*float64(duration))\n\treturn wait\n}\n\n\/\/ ErrWaitTimeout is returned when the condition exited without success.\nvar ErrWaitTimeout = errors.New(\"timed out waiting for the condition\")\n\n\/\/ ConditionFunc returns true if the condition is satisfied, or an error\n\/\/ if the loop should be aborted.\ntype ConditionFunc func() (done bool, err error)\n\n\/\/ Backoff holds parameters applied to a Backoff function.\ntype Backoff struct {\n\tDuration time.Duration \/\/ the base duration\n\tFactor   float64       \/\/ Duration is multiplied by factor each iteration\n\tJitter   float64       \/\/ The amount of jitter applied each iteration\n\tSteps    int           \/\/ Exit with error after this many steps\n}\n\n\/\/ ExponentialBackoff repeats a condition check with exponential backoff.\n\/\/\n\/\/ It checks the condition up to Steps times, increasing the wait by multiplying\n\/\/ the previous duration by Factor.\n\/\/\n\/\/ If Jitter is greater than zero, a random amount of each duration is added\n\/\/ (between duration and duration*(1+jitter)).\n\/\/\n\/\/ If the condition never returns true, ErrWaitTimeout is returned. All other\n\/\/ errors terminate immediately.\nfunc ExponentialBackoff(backoff Backoff, condition ConditionFunc) error {\n\tduration := backoff.Duration\n\tfor i := 0; i < backoff.Steps; i++ {\n\t\tif i != 0 {\n\t\t\tadjusted := duration\n\t\t\tif backoff.Jitter > 0.0 {\n\t\t\t\tadjusted = Jitter(duration, backoff.Jitter)\n\t\t\t}\n\t\t\ttime.Sleep(adjusted)\n\t\t\tduration = time.Duration(float64(duration) * backoff.Factor)\n\t\t}\n\t\tif ok, err := condition(); err != nil || ok {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn ErrWaitTimeout\n}\n\n\/\/ Poll tries a condition func until it returns true, an error, or the timeout\n\/\/ is reached.\n\/\/\n\/\/ Poll always waits the interval before the run of 'condition'.\n\/\/ 'condition' will always be invoked at least once.\n\/\/\n\/\/ Some intervals may be missed if the condition takes too long or the time\n\/\/ window is too short.\n\/\/\n\/\/ If you want to Poll something forever, see PollInfinite.\nfunc Poll(interval, timeout time.Duration, condition ConditionFunc) error {\n\treturn pollInternal(poller(interval, timeout), condition)\n}\n\nfunc pollInternal(wait WaitFunc, condition ConditionFunc) error {\n\tdone := make(chan struct{})\n\tdefer close(done)\n\treturn WaitFor(wait, condition, done)\n}\n\n\/\/ PollImmediate tries a condition func until it returns true, an error, or the timeout\n\/\/ is reached.\n\/\/\n\/\/ Poll always checks 'condition' before waiting for the interval. 'condition'\n\/\/ will always be invoked at least once.\n\/\/\n\/\/ Some intervals may be missed if the condition takes too long or the time\n\/\/ window is too short.\n\/\/\n\/\/ If you want to Poll something forever, see PollInfinite.\nfunc PollImmediate(interval, timeout time.Duration, condition ConditionFunc) error {\n\treturn pollImmediateInternal(poller(interval, timeout), condition)\n}\n\nfunc pollImmediateInternal(wait WaitFunc, condition ConditionFunc) error {\n\tdone, err := condition()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif done {\n\t\treturn nil\n\t}\n\treturn pollInternal(wait, condition)\n}\n\n\/\/ PollInfinite tries a condition func until it returns true or an error\n\/\/\n\/\/ PollInfinite always waits the interval before the run of 'condition'.\n\/\/\n\/\/ Some intervals may be missed if the condition takes too long or the time\n\/\/ window is too short.\nfunc PollInfinite(interval time.Duration, condition ConditionFunc) error {\n\tdone := make(chan struct{})\n\tdefer close(done)\n\treturn PollUntil(interval, condition, done)\n}\n\n\/\/ PollImmediateInfinite tries a condition func until it returns true or an error\n\/\/\n\/\/ PollImmediateInfinite runs the 'condition' before waiting for the interval.\n\/\/\n\/\/ Some intervals may be missed if the condition takes too long or the time\n\/\/ window is too short.\nfunc PollImmediateInfinite(interval time.Duration, condition ConditionFunc) error {\n\tdone, err := condition()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif done {\n\t\treturn nil\n\t}\n\treturn PollInfinite(interval, condition)\n}\n\n\/\/ PollUntil tries a condition func until it returns true, an error or stopCh is\n\/\/ closed.\n\/\/\n\/\/ PolUntil always waits interval before the first run of 'condition'.\n\/\/ 'condition' will always be invoked at least once.\nfunc PollUntil(interval time.Duration, condition ConditionFunc, stopCh <-chan struct{}) error {\n\treturn WaitFor(poller(interval, 0), condition, stopCh)\n}\n\n\/\/ WaitFunc creates a channel that receives an item every time a test\n\/\/ should be executed and is closed when the last test should be invoked.\ntype WaitFunc func(done <-chan struct{}) <-chan struct{}\n\n\/\/ WaitFor continually checks 'fn' as driven by 'wait'.\n\/\/\n\/\/ WaitFor gets a channel from 'wait()'', and then invokes 'fn' once for every value\n\/\/ placed on the channel and once more when the channel is closed.\n\/\/\n\/\/ If 'fn' returns an error the loop ends and that error is returned, and if\n\/\/ 'fn' returns true the loop ends and nil is returned.\n\/\/\n\/\/ ErrWaitTimeout will be returned if the channel is closed without fn ever\n\/\/ returning true.\nfunc WaitFor(wait WaitFunc, fn ConditionFunc, done <-chan struct{}) error {\n\tc := wait(done)\n\tfor {\n\t\t_, open := <-c\n\t\tok, err := fn()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif ok {\n\t\t\treturn nil\n\t\t}\n\t\tif !open {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn ErrWaitTimeout\n}\n\n\/\/ poller returns a WaitFunc that will send to the channel every interval until\n\/\/ timeout has elapsed and then closes the channel.\n\/\/\n\/\/ Over very short intervals you may receive no ticks before the channel is\n\/\/ closed. A timeout of 0 is interpreted as an infinity.\n\/\/\n\/\/ Output ticks are not buffered. If the channel is not ready to receive an\n\/\/ item, the tick is skipped.\nfunc poller(interval, timeout time.Duration) WaitFunc {\n\treturn WaitFunc(func(done <-chan struct{}) <-chan struct{} {\n\t\tch := make(chan struct{})\n\n\t\tgo func() {\n\t\t\tdefer close(ch)\n\n\t\t\ttick := time.NewTicker(interval)\n\t\t\tdefer tick.Stop()\n\n\t\t\tvar after <-chan time.Time\n\t\t\tif timeout != 0 {\n\t\t\t\t\/\/ time.After is more convenient, but it\n\t\t\t\t\/\/ potentially leaves timers around much longer\n\t\t\t\t\/\/ than necessary if we exit early.\n\t\t\t\ttimer := time.NewTimer(timeout)\n\t\t\t\tafter = timer.C\n\t\t\t\tdefer timer.Stop()\n\t\t\t}\n\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase <-tick.C:\n\t\t\t\t\t\/\/ If the consumer isn't ready for this signal drop it and\n\t\t\t\t\t\/\/ check the other channels.\n\t\t\t\t\tselect {\n\t\t\t\t\tcase ch <- struct{}{}:\n\t\t\t\t\tdefault:\n\t\t\t\t\t}\n\t\t\t\tcase <-after:\n\t\t\t\t\treturn\n\t\t\t\tcase <-done:\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\n\t\treturn ch\n\t})\n}\n\n\/\/ resetOrReuseTimer avoids allocating a new timer if one is already in use.\n\/\/ Not safe for multiple threads.\nfunc resetOrReuseTimer(t *time.Timer, d time.Duration, sawTimeout bool) *time.Timer {\n\tif t == nil {\n\t\treturn time.NewTimer(d)\n\t}\n\tif !t.Stop() && !sawTimeout {\n\t\t<-t.C\n\t}\n\tt.Reset(d)\n\treturn t\n}\n<|endoftext|>"}
{"text":"<commit_before>package mail\n\nimport (\n\t\"crypto\/rand\"\n\t\"encoding\/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net\/mail\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\t\"unicode\/utf8\"\n\n\t\"github.com\/emersion\/go-message\"\n)\n\nconst dateLayout = \"Mon, 02 Jan 2006 15:04:05 -0700\"\n\ntype headerParser struct {\n\ts string\n}\n\nfunc (p *headerParser) len() int {\n\treturn len(p.s)\n}\n\nfunc (p *headerParser) empty() bool {\n\treturn p.len() == 0\n}\n\nfunc (p *headerParser) peek() byte {\n\treturn p.s[0]\n}\n\nfunc (p *headerParser) consume(c byte) bool {\n\tif p.empty() || p.peek() != c {\n\t\treturn false\n\t}\n\tp.s = p.s[1:]\n\treturn true\n}\n\n\/\/ skipSpace skips the leading space and tab characters.\nfunc (p *headerParser) skipSpace() {\n\tp.s = strings.TrimLeft(p.s, \" \\t\")\n}\n\n\/\/ skipCFWS skips CFWS as defined in RFC5322. It returns false if the CFWS is\n\/\/ malformed.\nfunc (p *headerParser) skipCFWS() bool {\n\tp.skipSpace()\n\n\tfor {\n\t\tif !p.consume('(') {\n\t\t\tbreak\n\t\t}\n\n\t\tif _, ok := p.consumeComment(); !ok {\n\t\t\treturn false\n\t\t}\n\n\t\tp.skipSpace()\n\t}\n\n\treturn true\n}\n\nfunc (p *headerParser) consumeComment() (string, bool) {\n\t\/\/ '(' already consumed.\n\tdepth := 1\n\n\tvar comment string\n\tfor {\n\t\tif p.empty() || depth == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\tif p.peek() == '\\\\' && p.len() > 1 {\n\t\t\tp.s = p.s[1:]\n\t\t} else if p.peek() == '(' {\n\t\t\tdepth++\n\t\t} else if p.peek() == ')' {\n\t\t\tdepth--\n\t\t}\n\n\t\tif depth > 0 {\n\t\t\tcomment += p.s[:1]\n\t\t}\n\n\t\tp.s = p.s[1:]\n\t}\n\n\treturn comment, depth == 0\n}\n\nfunc (p *headerParser) parseAtomText(dot bool) (string, error) {\n\ti := 0\n\tfor {\n\t\tr, size := utf8.DecodeRuneInString(p.s[i:])\n\t\tif size == 1 && r == utf8.RuneError {\n\t\t\treturn \"\", fmt.Errorf(\"mail: invalid UTF-8 in atom-text: %q\", p.s)\n\t\t} else if size == 0 || !isAtext(r, dot) {\n\t\t\tbreak\n\t\t}\n\t\ti += size\n\t}\n\tif i == 0 {\n\t\treturn \"\", errors.New(\"mail: invalid string\")\n\t}\n\n\tvar atom string\n\tatom, p.s = p.s[:i], p.s[i:]\n\treturn atom, nil\n}\n\nfunc isAtext(r rune, dot bool) bool {\n\tswitch r {\n\tcase '.':\n\t\treturn dot\n\t\/\/ RFC 5322 3.2.3 specials\n\tcase '(', ')', '[', ']', ';', '@', '\\\\', ',':\n\t\treturn false\n\tcase '<', '>', '\"', ':':\n\t\treturn false\n\t}\n\treturn isVchar(r)\n}\n\n\/\/ isVchar reports whether r is an RFC 5322 VCHAR character.\nfunc isVchar(r rune) bool {\n\t\/\/ Visible (printing) characters\n\treturn '!' <= r && r <= '~' || isMultibyte(r)\n}\n\n\/\/ isMultibyte reports whether r is a multi-byte UTF-8 character\n\/\/ as supported by RFC 6532\nfunc isMultibyte(r rune) bool {\n\treturn r >= utf8.RuneSelf\n}\n\nfunc (p *headerParser) parseNoFoldLiteral() (string, error) {\n\tif !p.consume('[') {\n\t\treturn \"\", errors.New(\"mail: missing '[' in no-fold-literal\")\n\t}\n\n\ti := 0\n\tfor {\n\t\tr, size := utf8.DecodeRuneInString(p.s[i:])\n\t\tif size == 1 && r == utf8.RuneError {\n\t\t\treturn \"\", fmt.Errorf(\"mail: invalid UTF-8 in no-fold-literal: %q\", p.s)\n\t\t} else if size == 0 || !isDtext(r) {\n\t\t\tbreak\n\t\t}\n\t\ti += size\n\t}\n\tvar lit string\n\tlit, p.s = p.s[:i], p.s[i:]\n\n\tif !p.consume(']') {\n\t\treturn \"\", errors.New(\"mail: missing ']' in no-fold-literal\")\n\t}\n\treturn \"[\" + lit + \"]\", nil\n}\n\nfunc isDtext(r rune) bool {\n\tswitch r {\n\tcase '[', ']', '\\\\':\n\t\treturn false\n\t}\n\treturn isVchar(r)\n}\n\nfunc (p *headerParser) parseMsgID() (string, error) {\n\tif !p.skipCFWS() {\n\t\treturn \"\", errors.New(\"mail: malformed parenthetical comment\")\n\t}\n\n\tif !p.consume('<') {\n\t\treturn \"\", errors.New(\"mail: missing '<' in msg-id\")\n\t}\n\n\tleft, err := p.parseAtomText(true)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif !p.consume('@') {\n\t\treturn \"\", errors.New(\"mail: missing '@' in msg-id\")\n\t}\n\n\tvar right string\n\tif !p.empty() && p.peek() == '[' {\n\t\t\/\/ no-fold-literal\n\t\tright, err = p.parseNoFoldLiteral()\n\t} else {\n\t\tright, err = p.parseAtomText(true)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\tif !p.consume('>') {\n\t\treturn \"\", errors.New(\"mail: missing '>' in msg-id\")\n\t}\n\n\tif !p.skipCFWS() {\n\t\treturn \"\", errors.New(\"mail: malformed parenthetical comment\")\n\t}\n\n\treturn left + \"@\" + right, nil\n}\n\n\/\/ A Header is a mail header.\ntype Header struct {\n\tmessage.Header\n}\n\n\/\/ HeaderFromMap creates a header from a map of header fields.\n\/\/\n\/\/ This function is provided for interoperability with the standard library.\n\/\/ If possible, ReadHeader should be used instead to avoid loosing information.\n\/\/ The map representation looses the ordering of the fields, the capitalization\n\/\/ of the header keys, and the whitespace of the original header.\nfunc HeaderFromMap(m map[string][]string) Header {\n\treturn Header{message.HeaderFromMap(m)}\n}\n\n\/\/ AddressList parses the named header field as a list of addresses. If the\n\/\/ header field is missing, it returns nil.\n\/\/\n\/\/ This can be used on From, Sender, Reply-To, To, Cc and Bcc header fields.\nfunc (h *Header) AddressList(key string) ([]*Address, error) {\n\tv := h.Get(key)\n\tif v == \"\" {\n\t\treturn nil, nil\n\t}\n\treturn ParseAddressList(v)\n}\n\n\/\/ SetAddressList formats the named header field to the provided list of\n\/\/ addresses.\n\/\/\n\/\/ This can be used on From, Sender, Reply-To, To, Cc and Bcc header fields.\nfunc (h *Header) SetAddressList(key string, addrs []*Address) {\n\tif len(addrs) > 0 {\n\t\th.Set(key, formatAddressList(addrs))\n\t} else {\n\t\th.Del(key)\n\t}\n}\n\n\/\/ Date parses the Date header field.\nfunc (h *Header) Date() (time.Time, error) {\n\treturn mail.ParseDate(h.Get(\"Date\"))\n}\n\n\/\/ SetDate formats the Date header field.\nfunc (h *Header) SetDate(t time.Time) {\n\th.Set(\"Date\", t.Format(dateLayout))\n}\n\n\/\/ Subject parses the Subject header field. If there is an error, the raw field\n\/\/ value is returned alongside the error.\nfunc (h *Header) Subject() (string, error) {\n\treturn h.Text(\"Subject\")\n}\n\n\/\/ SetSubject formats the Subject header field.\nfunc (h *Header) SetSubject(s string) {\n\th.SetText(\"Subject\", s)\n}\n\n\/\/ MessageID parses the Message-ID field. It returns the message identifier,\n\/\/ without the angle brackets. If the message doesn't have a Message-ID header\n\/\/ field, it returns an empty string.\nfunc (h *Header) MessageID() (string, error) {\n\tv := h.Get(\"Message-Id\")\n\tif v == \"\" {\n\t\treturn \"\", nil\n\t}\n\n\tp := headerParser{v}\n\treturn p.parseMsgID()\n}\n\n\/\/ MsgIDList parses a list of message identifiers. It returns message\n\/\/ identifiers without angle brackets. If the header field is missing, it\n\/\/ returns nil.\n\/\/\n\/\/ This can be used on In-Reply-To and References header fields.\nfunc (h *Header) MsgIDList(key string) ([]string, error) {\n\tv := h.Get(key)\n\tif v == \"\" {\n\t\treturn nil, nil\n\t}\n\n\tp := headerParser{v}\n\tvar l []string\n\tfor !p.empty() {\n\t\tmsgID, err := p.parseMsgID()\n\t\tif err != nil {\n\t\t\treturn l, err\n\t\t}\n\t\tl = append(l, msgID)\n\t}\n\n\treturn l, nil\n}\n\n\/\/ GenerateMessageID generates an RFC 2822-compliant Message-Id based on the\n\/\/ informational draft \"Recommendations for generating Message IDs\", for lack\n\/\/ of a better authoritative source.\nfunc (h *Header) GenerateMessageID() error {\n\tnow := uint64(time.Now().UnixNano())\n\n\tnonceByte := make([]byte, 8)\n\tif _, err := rand.Read(nonceByte); err != nil {\n\t\treturn err\n\t}\n\tnonce := binary.BigEndian.Uint64(nonceByte)\n\n\thostname, err := os.Hostname()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmsgID := fmt.Sprintf(\"%s.%s@%s\", base36(now), base36(nonce), hostname)\n\th.SetMessageID(msgID)\n\treturn nil\n}\n\nfunc base36(input uint64) string {\n\treturn strings.ToUpper(strconv.FormatUint(input, 36))\n}\n\n\/\/ SetMessageID sets the Message-ID field. id is the message identifier,\n\/\/ without the angle brackets.\nfunc (h *Header) SetMessageID(id string) {\n\th.Set(\"Message-Id\", \"<\"+id+\">\")\n}\n\n\/\/ SetMsgIDList formats a list of message identifiers. Message identifiers\n\/\/ don't include angle brackets.\n\/\/\n\/\/ This can be used on In-Reply-To and References header fields.\nfunc (h *Header) SetMsgIDList(key string, l []string) {\n\tif len(l) > 0 {\n\t\th.Set(key, \"<\"+strings.Join(l, \"> <\")+\">\")\n\t} else {\n\t\th.Del(key)\n\t}\n}\n\n\/\/ Copy creates a stand-alone copy of the header.\nfunc (h *Header) Copy() Header {\n\treturn Header{h.Header.Copy()}\n}\n<commit_msg>Add function to set Message-ID hostname manually<commit_after>package mail\n\nimport (\n\t\"crypto\/rand\"\n\t\"encoding\/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net\/mail\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\t\"unicode\/utf8\"\n\n\t\"github.com\/emersion\/go-message\"\n)\n\nconst dateLayout = \"Mon, 02 Jan 2006 15:04:05 -0700\"\n\ntype headerParser struct {\n\ts string\n}\n\nfunc (p *headerParser) len() int {\n\treturn len(p.s)\n}\n\nfunc (p *headerParser) empty() bool {\n\treturn p.len() == 0\n}\n\nfunc (p *headerParser) peek() byte {\n\treturn p.s[0]\n}\n\nfunc (p *headerParser) consume(c byte) bool {\n\tif p.empty() || p.peek() != c {\n\t\treturn false\n\t}\n\tp.s = p.s[1:]\n\treturn true\n}\n\n\/\/ skipSpace skips the leading space and tab characters.\nfunc (p *headerParser) skipSpace() {\n\tp.s = strings.TrimLeft(p.s, \" \\t\")\n}\n\n\/\/ skipCFWS skips CFWS as defined in RFC5322. It returns false if the CFWS is\n\/\/ malformed.\nfunc (p *headerParser) skipCFWS() bool {\n\tp.skipSpace()\n\n\tfor {\n\t\tif !p.consume('(') {\n\t\t\tbreak\n\t\t}\n\n\t\tif _, ok := p.consumeComment(); !ok {\n\t\t\treturn false\n\t\t}\n\n\t\tp.skipSpace()\n\t}\n\n\treturn true\n}\n\nfunc (p *headerParser) consumeComment() (string, bool) {\n\t\/\/ '(' already consumed.\n\tdepth := 1\n\n\tvar comment string\n\tfor {\n\t\tif p.empty() || depth == 0 {\n\t\t\tbreak\n\t\t}\n\n\t\tif p.peek() == '\\\\' && p.len() > 1 {\n\t\t\tp.s = p.s[1:]\n\t\t} else if p.peek() == '(' {\n\t\t\tdepth++\n\t\t} else if p.peek() == ')' {\n\t\t\tdepth--\n\t\t}\n\n\t\tif depth > 0 {\n\t\t\tcomment += p.s[:1]\n\t\t}\n\n\t\tp.s = p.s[1:]\n\t}\n\n\treturn comment, depth == 0\n}\n\nfunc (p *headerParser) parseAtomText(dot bool) (string, error) {\n\ti := 0\n\tfor {\n\t\tr, size := utf8.DecodeRuneInString(p.s[i:])\n\t\tif size == 1 && r == utf8.RuneError {\n\t\t\treturn \"\", fmt.Errorf(\"mail: invalid UTF-8 in atom-text: %q\", p.s)\n\t\t} else if size == 0 || !isAtext(r, dot) {\n\t\t\tbreak\n\t\t}\n\t\ti += size\n\t}\n\tif i == 0 {\n\t\treturn \"\", errors.New(\"mail: invalid string\")\n\t}\n\n\tvar atom string\n\tatom, p.s = p.s[:i], p.s[i:]\n\treturn atom, nil\n}\n\nfunc isAtext(r rune, dot bool) bool {\n\tswitch r {\n\tcase '.':\n\t\treturn dot\n\t\/\/ RFC 5322 3.2.3 specials\n\tcase '(', ')', '[', ']', ';', '@', '\\\\', ',':\n\t\treturn false\n\tcase '<', '>', '\"', ':':\n\t\treturn false\n\t}\n\treturn isVchar(r)\n}\n\n\/\/ isVchar reports whether r is an RFC 5322 VCHAR character.\nfunc isVchar(r rune) bool {\n\t\/\/ Visible (printing) characters\n\treturn '!' <= r && r <= '~' || isMultibyte(r)\n}\n\n\/\/ isMultibyte reports whether r is a multi-byte UTF-8 character\n\/\/ as supported by RFC 6532\nfunc isMultibyte(r rune) bool {\n\treturn r >= utf8.RuneSelf\n}\n\nfunc (p *headerParser) parseNoFoldLiteral() (string, error) {\n\tif !p.consume('[') {\n\t\treturn \"\", errors.New(\"mail: missing '[' in no-fold-literal\")\n\t}\n\n\ti := 0\n\tfor {\n\t\tr, size := utf8.DecodeRuneInString(p.s[i:])\n\t\tif size == 1 && r == utf8.RuneError {\n\t\t\treturn \"\", fmt.Errorf(\"mail: invalid UTF-8 in no-fold-literal: %q\", p.s)\n\t\t} else if size == 0 || !isDtext(r) {\n\t\t\tbreak\n\t\t}\n\t\ti += size\n\t}\n\tvar lit string\n\tlit, p.s = p.s[:i], p.s[i:]\n\n\tif !p.consume(']') {\n\t\treturn \"\", errors.New(\"mail: missing ']' in no-fold-literal\")\n\t}\n\treturn \"[\" + lit + \"]\", nil\n}\n\nfunc isDtext(r rune) bool {\n\tswitch r {\n\tcase '[', ']', '\\\\':\n\t\treturn false\n\t}\n\treturn isVchar(r)\n}\n\nfunc (p *headerParser) parseMsgID() (string, error) {\n\tif !p.skipCFWS() {\n\t\treturn \"\", errors.New(\"mail: malformed parenthetical comment\")\n\t}\n\n\tif !p.consume('<') {\n\t\treturn \"\", errors.New(\"mail: missing '<' in msg-id\")\n\t}\n\n\tleft, err := p.parseAtomText(true)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif !p.consume('@') {\n\t\treturn \"\", errors.New(\"mail: missing '@' in msg-id\")\n\t}\n\n\tvar right string\n\tif !p.empty() && p.peek() == '[' {\n\t\t\/\/ no-fold-literal\n\t\tright, err = p.parseNoFoldLiteral()\n\t} else {\n\t\tright, err = p.parseAtomText(true)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\tif !p.consume('>') {\n\t\treturn \"\", errors.New(\"mail: missing '>' in msg-id\")\n\t}\n\n\tif !p.skipCFWS() {\n\t\treturn \"\", errors.New(\"mail: malformed parenthetical comment\")\n\t}\n\n\treturn left + \"@\" + right, nil\n}\n\n\/\/ A Header is a mail header.\ntype Header struct {\n\tmessage.Header\n}\n\n\/\/ HeaderFromMap creates a header from a map of header fields.\n\/\/\n\/\/ This function is provided for interoperability with the standard library.\n\/\/ If possible, ReadHeader should be used instead to avoid loosing information.\n\/\/ The map representation looses the ordering of the fields, the capitalization\n\/\/ of the header keys, and the whitespace of the original header.\nfunc HeaderFromMap(m map[string][]string) Header {\n\treturn Header{message.HeaderFromMap(m)}\n}\n\n\/\/ AddressList parses the named header field as a list of addresses. If the\n\/\/ header field is missing, it returns nil.\n\/\/\n\/\/ This can be used on From, Sender, Reply-To, To, Cc and Bcc header fields.\nfunc (h *Header) AddressList(key string) ([]*Address, error) {\n\tv := h.Get(key)\n\tif v == \"\" {\n\t\treturn nil, nil\n\t}\n\treturn ParseAddressList(v)\n}\n\n\/\/ SetAddressList formats the named header field to the provided list of\n\/\/ addresses.\n\/\/\n\/\/ This can be used on From, Sender, Reply-To, To, Cc and Bcc header fields.\nfunc (h *Header) SetAddressList(key string, addrs []*Address) {\n\tif len(addrs) > 0 {\n\t\th.Set(key, formatAddressList(addrs))\n\t} else {\n\t\th.Del(key)\n\t}\n}\n\n\/\/ Date parses the Date header field.\nfunc (h *Header) Date() (time.Time, error) {\n\treturn mail.ParseDate(h.Get(\"Date\"))\n}\n\n\/\/ SetDate formats the Date header field.\nfunc (h *Header) SetDate(t time.Time) {\n\th.Set(\"Date\", t.Format(dateLayout))\n}\n\n\/\/ Subject parses the Subject header field. If there is an error, the raw field\n\/\/ value is returned alongside the error.\nfunc (h *Header) Subject() (string, error) {\n\treturn h.Text(\"Subject\")\n}\n\n\/\/ SetSubject formats the Subject header field.\nfunc (h *Header) SetSubject(s string) {\n\th.SetText(\"Subject\", s)\n}\n\n\/\/ MessageID parses the Message-ID field. It returns the message identifier,\n\/\/ without the angle brackets. If the message doesn't have a Message-ID header\n\/\/ field, it returns an empty string.\nfunc (h *Header) MessageID() (string, error) {\n\tv := h.Get(\"Message-Id\")\n\tif v == \"\" {\n\t\treturn \"\", nil\n\t}\n\n\tp := headerParser{v}\n\treturn p.parseMsgID()\n}\n\n\/\/ MsgIDList parses a list of message identifiers. It returns message\n\/\/ identifiers without angle brackets. If the header field is missing, it\n\/\/ returns nil.\n\/\/\n\/\/ This can be used on In-Reply-To and References header fields.\nfunc (h *Header) MsgIDList(key string) ([]string, error) {\n\tv := h.Get(key)\n\tif v == \"\" {\n\t\treturn nil, nil\n\t}\n\n\tp := headerParser{v}\n\tvar l []string\n\tfor !p.empty() {\n\t\tmsgID, err := p.parseMsgID()\n\t\tif err != nil {\n\t\t\treturn l, err\n\t\t}\n\t\tl = append(l, msgID)\n\t}\n\n\treturn l, nil\n}\n\n\/\/ GenerateMessageID wraps GenerateMessageIDWithHostname and therefore uses the\n\/\/ hostname of the local machine. This is done to not break existing software.\n\/\/ Wherever possible better use GenerateMessageIDWithHostname, because the local\n\/\/ hostname of a machine tends to not be unique nor a FQDN which especially\n\/\/ brings problems with spam filters.\nfunc (h *Header) GenerateMessageID() error {\n\tvar err error\n\thostname, err := os.Hostname()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn h.GenerateMessageIDWithHostname(hostname)\n}\n\n\/\/ GenerateMessageIDWithHostname generates an RFC 2822-compliant Message-Id\n\/\/ based on the informational draft \"Recommendations for generating Message\n\/\/ IDs\", it takes an hostname as argument, so that software using this library\n\/\/ could use a hostname they know to be unique\nfunc (h *Header) GenerateMessageIDWithHostname(hostname string) error {\n\tnow := uint64(time.Now().UnixNano())\n\n\tnonceByte := make([]byte, 8)\n\tif _, err := rand.Read(nonceByte); err != nil {\n\t\treturn err\n\t}\n\tnonce := binary.BigEndian.Uint64(nonceByte)\n\n\tmsgID := fmt.Sprintf(\"%s.%s@%s\", base36(now), base36(nonce), hostname)\n\th.SetMessageID(msgID)\n\treturn nil\n}\n\nfunc base36(input uint64) string {\n\treturn strings.ToUpper(strconv.FormatUint(input, 36))\n}\n\n\/\/ SetMessageID sets the Message-ID field. id is the message identifier,\n\/\/ without the angle brackets.\nfunc (h *Header) SetMessageID(id string) {\n\th.Set(\"Message-Id\", \"<\"+id+\">\")\n}\n\n\/\/ SetMsgIDList formats a list of message identifiers. Message identifiers\n\/\/ don't include angle brackets.\n\/\/\n\/\/ This can be used on In-Reply-To and References header fields.\nfunc (h *Header) SetMsgIDList(key string, l []string) {\n\tif len(l) > 0 {\n\t\th.Set(key, \"<\"+strings.Join(l, \"> <\")+\">\")\n\t} else {\n\t\th.Del(key)\n\t}\n}\n\n\/\/ Copy creates a stand-alone copy of the header.\nfunc (h *Header) Copy() Header {\n\treturn Header{h.Header.Copy()}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t. \"fmt\"\n\t\"polydawn.net\/dockctrl\/confl\"\n\t\"polydawn.net\/dockctrl\/crocker\"\n)\n\n\/*\n\tHelps run anything that requires a docker connection.\n\tHandles creation & cleanup in one place.\n\tDocker daemon config is determined by looking around the cwd.\n*\/\nfunc WithDocker(fn func(*crocker.Dock, *confl.ConfigLoad) error) error {\n\t\/\/Load configuration, then find or start a docker\n\tsettings := confl.NewConfigLoad(\".\")\n\tdock := crocker.NewDock(\".\/dock\")\n\n\t\/\/Announce the docker\n\tif dock.IsChildProcess() {\n\t\tPrintln(\"Started a docker in\", dock.Dir())\n\t} else {\n\t\tPrintln(\"Connecting to docker\", dock.Dir())\n\t}\n\n\t\/\/Run the closure, kill the docker if needed, and return any errors.\n\terr := fn(dock, settings)\n\tdock.Slay()\n\treturn err\n}\n\n\/\/Helper function: maps a TrionConfig struct to crocker function.\n\/\/Kinda ugly; this situation may improve once our config shenanigans solidifies a bit.\nfunc Launch(dock *crocker.Dock, config crocker.ContainerConfig) *crocker.Container {\n\treturn crocker.Launch(dock, config.Image, config.Command, config.Attach, config.Privileged, config.Folder, config.DNS, config.Mounts, config.Ports, config.Environment)\n}\n<commit_msg>Use a parent's dock folder if found.<commit_after>package main\n\nimport (\n\t. \"fmt\"\n\t\"polydawn.net\/dockctrl\/confl\"\n\t\"polydawn.net\/dockctrl\/crocker\"\n)\n\n\/*\n\tHelps run anything that requires a docker connection.\n\tHandles creation & cleanup in one place.\n\tDocker daemon config is determined by looking around the cwd.\n*\/\nfunc WithDocker(fn func(*crocker.Dock, *confl.ConfigLoad) error) error {\n\t\/\/Load configuration, then find or start a docker\n\tsettings := confl.NewConfigLoad(\".\")\n\tdock := crocker.NewDock(settings.Dock)\n\n\t\/\/Announce the docker\n\tif dock.IsChildProcess() {\n\t\tPrintln(\"Started a docker in\", dock.Dir())\n\t} else {\n\t\tPrintln(\"Connecting to docker\", dock.Dir())\n\t}\n\n\t\/\/Run the closure, kill the docker if needed, and return any errors.\n\terr := fn(dock, settings)\n\tdock.Slay()\n\treturn err\n}\n\n\/\/Helper function: maps a TrionConfig struct to crocker function.\n\/\/Kinda ugly; this situation may improve once our config shenanigans solidifies a bit.\nfunc Launch(dock *crocker.Dock, config crocker.ContainerConfig) *crocker.Container {\n\treturn crocker.Launch(dock, config.Image, config.Command, config.Attach, config.Privileged, config.Folder, config.DNS, config.Mounts, config.Ports, config.Environment)\n}\n<|endoftext|>"}
{"text":"<commit_before>package command\n\nimport (\n\t\"os\"\n\t\"os\/signal\"\n\n\t\"github.com\/codegangsta\/cli\"\n\t\"github.com\/dnaeon\/gru\/minion\"\n)\n\nfunc NewServeCommand() cli.Command {\n\tcmd := cli.Command{\n\t\tName:   \"serve\",\n\t\tUsage:  \"start minion\",\n\t\tAction: execServeCommand,\n\t\tFlags: []cli.Flag{\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"name\",\n\t\t\t\tUsage: \"set minion name\",\n\t\t\t\tValue: \"\",\n\t\t\t},\n\t\t},\n\t}\n\n\treturn cmd\n}\n\n\/\/ Executes the \"serve\" command\nfunc execServeCommand(c *cli.Context) {\n\tname, err := os.Hostname()\n\tif err != nil {\n\t\tdisplayError(err, 1)\n\t}\n\n\tnameFlag := c.String(\"name\")\n\tif nameFlag != \"\" {\n\t\tname = nameFlag\n\t}\n\n\tcfg := etcdConfigFromFlags(c)\n\tm := minion.NewEtcdMinion(name, cfg)\n\n\t\/\/ Channel on which the shutdown signal is sent\n\tquit := make(chan os.Signal, 1)\n\tsignal.Notify(quit, os.Interrupt)\n\n\t\/\/ Start minion\n\tif err != m.Serve() {\n\t\tdisplayError(err, 1)\n\t}\n\n\t\/\/ Block until a shutdown signal is received\n\t<-quit\n\tm.Stop()\n}\n<commit_msg>gructl: fix typo in error handling when starting the minion<commit_after>package command\n\nimport (\n\t\"os\"\n\t\"os\/signal\"\n\n\t\"github.com\/codegangsta\/cli\"\n\t\"github.com\/dnaeon\/gru\/minion\"\n)\n\nfunc NewServeCommand() cli.Command {\n\tcmd := cli.Command{\n\t\tName:   \"serve\",\n\t\tUsage:  \"start minion\",\n\t\tAction: execServeCommand,\n\t\tFlags: []cli.Flag{\n\t\t\tcli.StringFlag{\n\t\t\t\tName: \"name\",\n\t\t\t\tUsage: \"set minion name\",\n\t\t\t\tValue: \"\",\n\t\t\t},\n\t\t},\n\t}\n\n\treturn cmd\n}\n\n\/\/ Executes the \"serve\" command\nfunc execServeCommand(c *cli.Context) {\n\tname, err := os.Hostname()\n\tif err != nil {\n\t\tdisplayError(err, 1)\n\t}\n\n\tnameFlag := c.String(\"name\")\n\tif nameFlag != \"\" {\n\t\tname = nameFlag\n\t}\n\n\tcfg := etcdConfigFromFlags(c)\n\tm := minion.NewEtcdMinion(name, cfg)\n\n\t\/\/ Channel on which the shutdown signal is sent\n\tquit := make(chan os.Signal, 1)\n\tsignal.Notify(quit, os.Interrupt)\n\n\t\/\/ Start minion\n\terr = m.Serve()\n\tif err != nil {\n\t\tdisplayError(err, 1)\n\t}\n\n\t\/\/ Block until a shutdown signal is received\n\t<-quit\n\tm.Stop()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build linux\n\npackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/opencontainers\/runc\/libcontainer\"\n\t\"github.com\/opencontainers\/runc\/libcontainer\/utils\"\n\t\"github.com\/opencontainers\/runtime-spec\/specs-go\"\n\t\"github.com\/urfave\/cli\"\n)\n\nvar execCommand = cli.Command{\n\tName:  \"exec\",\n\tUsage: \"execute new process inside the container\",\n\tArgsUsage: `<container-id> <container command> [command options]\n\nWhere \"<container-id>\" is the name for the instance of the container and\n\"<container command>\" is the command to be executed in the container.\n\nEXAMPLE:\nFor example, if the container is configured to run the linux ps command the\nfollowing will output a list of processes running in the container:\n\n       # runc exec <container-id> ps`,\n\tFlags: []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName:  \"console-socket\",\n\t\t\tUsage: \"path to an AF_UNIX socket which will receive a file descriptor referencing the master end of the console's pseudoterminal\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:  \"cwd\",\n\t\t\tUsage: \"current working directory in the container\",\n\t\t},\n\t\tcli.StringSliceFlag{\n\t\t\tName:  \"env, e\",\n\t\t\tUsage: \"set environment variables\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"tty, t\",\n\t\t\tUsage: \"allocate a pseudo-TTY\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:  \"user, u\",\n\t\t\tUsage: \"UID (format: <uid>[:<gid>])\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:  \"process, p\",\n\t\t\tUsage: \"path to the process.json\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"detach,d\",\n\t\t\tUsage: \"detach from the container's process\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:  \"pid-file\",\n\t\t\tValue: \"\",\n\t\t\tUsage: \"specify the file to write the process id to\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:  \"process-label\",\n\t\t\tUsage: \"set the asm process label for the process commonly used with selinux\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:  \"apparmor\",\n\t\t\tUsage: \"set the apparmor profile for the process\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"no-new-privs\",\n\t\t\tUsage: \"set the no new privileges value for the process\",\n\t\t},\n\t\tcli.StringSliceFlag{\n\t\t\tName:  \"cap, c\",\n\t\t\tValue: &cli.StringSlice{},\n\t\t\tUsage: \"add a capability to the bounding set for the process\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:   \"no-subreaper\",\n\t\t\tUsage:  \"disable the use of the subreaper used to reap reparented processes\",\n\t\t\tHidden: true,\n\t\t},\n\t},\n\tAction: func(context *cli.Context) error {\n\t\tif err := checkArgs(context, 2, minArgs); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif os.Geteuid() != 0 {\n\t\t\treturn fmt.Errorf(\"runc should be run as root\")\n\t\t}\n\t\tif err := revisePidFile(context); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tstatus, err := execProcess(context)\n\t\tif err == nil {\n\t\t\tos.Exit(status)\n\t\t}\n\t\treturn fmt.Errorf(\"exec failed: %v\", err)\n\t},\n\tSkipArgReorder: true,\n}\n\nfunc execProcess(context *cli.Context) (int, error) {\n\tcontainer, err := getContainer(context)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\tstatus, err := container.Status()\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\tif status == libcontainer.Stopped {\n\t\treturn -1, fmt.Errorf(\"cannot exec a container that has run and stopped\")\n\t}\n\tpath := context.String(\"process\")\n\tif path == \"\" && len(context.Args()) == 1 {\n\t\treturn -1, fmt.Errorf(\"process args cannot be empty\")\n\t}\n\tdetach := context.Bool(\"detach\")\n\tstate, err := container.State()\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\tbundle := utils.SearchLabels(state.Config.Labels, \"bundle\")\n\tp, err := getProcess(context, bundle)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\tr := &runner{\n\t\tenableSubreaper: false,\n\t\tshouldDestroy:   false,\n\t\tcontainer:       container,\n\t\tconsoleSocket:   context.String(\"console-socket\"),\n\t\tdetach:          detach,\n\t\tpidFile:         context.String(\"pid-file\"),\n\t}\n\treturn r.run(p)\n}\n\nfunc getProcess(context *cli.Context, bundle string) (*specs.Process, error) {\n\tif path := context.String(\"process\"); path != \"\" {\n\t\tf, err := os.Open(path)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer f.Close()\n\t\tvar p specs.Process\n\t\tif err := json.NewDecoder(f).Decode(&p); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn &p, validateProcessSpec(&p)\n\t}\n\t\/\/ process via cli flags\n\tif err := os.Chdir(bundle); err != nil {\n\t\treturn nil, err\n\t}\n\tspec, err := loadSpec(specConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tp := spec.Process\n\tp.Args = context.Args()[1:]\n\t\/\/ override the cwd, if passed\n\tif context.String(\"cwd\") != \"\" {\n\t\tp.Cwd = context.String(\"cwd\")\n\t}\n\tif ap := context.String(\"apparmor\"); ap != \"\" {\n\t\tp.ApparmorProfile = ap\n\t}\n\tif l := context.String(\"process-label\"); l != \"\" {\n\t\tp.SelinuxLabel = l\n\t}\n\tif caps := context.StringSlice(\"cap\"); len(caps) > 0 {\n\t\tp.Capabilities = caps\n\t}\n\t\/\/ append the passed env variables\n\tp.Env = append(p.Env, context.StringSlice(\"env\")...)\n\n\t\/\/ set the tty\n\tif context.IsSet(\"tty\") {\n\t\tp.Terminal = context.Bool(\"tty\")\n\t}\n\tif context.IsSet(\"no-new-privs\") {\n\t\tp.NoNewPrivileges = context.Bool(\"no-new-privs\")\n\t}\n\t\/\/ override the user, if passed\n\tif context.String(\"user\") != \"\" {\n\t\tu := strings.SplitN(context.String(\"user\"), \":\", 2)\n\t\tif len(u) > 1 {\n\t\t\tgid, err := strconv.Atoi(u[1])\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"parsing %s as int for gid failed: %v\", u[1], err)\n\t\t\t}\n\t\t\tp.User.GID = uint32(gid)\n\t\t}\n\t\tuid, err := strconv.Atoi(u[0])\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"parsing %s as int for uid failed: %v\", u[0], err)\n\t\t}\n\t\tp.User.UID = uint32(uid)\n\t}\n\treturn &p, nil\n}\n<commit_msg>Fix regression of exec command<commit_after>\/\/ +build linux\n\npackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/opencontainers\/runc\/libcontainer\"\n\t\"github.com\/opencontainers\/runc\/libcontainer\/utils\"\n\t\"github.com\/opencontainers\/runtime-spec\/specs-go\"\n\t\"github.com\/urfave\/cli\"\n)\n\nvar execCommand = cli.Command{\n\tName:  \"exec\",\n\tUsage: \"execute new process inside the container\",\n\tArgsUsage: `<container-id> <command> [command options]  || -p process.json <container-id>\n\nWhere \"<container-id>\" is the name for the instance of the container and\n\"<command>\" is the command to be executed in the container.\n\"<command>\" can't be empty unless a \"-p\" flag provided.\n\nEXAMPLE:\nFor example, if the container is configured to run the linux ps command the\nfollowing will output a list of processes running in the container:\n\n       # runc exec <container-id> ps`,\n\tFlags: []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName:  \"console-socket\",\n\t\t\tUsage: \"path to an AF_UNIX socket which will receive a file descriptor referencing the master end of the console's pseudoterminal\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:  \"cwd\",\n\t\t\tUsage: \"current working directory in the container\",\n\t\t},\n\t\tcli.StringSliceFlag{\n\t\t\tName:  \"env, e\",\n\t\t\tUsage: \"set environment variables\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"tty, t\",\n\t\t\tUsage: \"allocate a pseudo-TTY\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:  \"user, u\",\n\t\t\tUsage: \"UID (format: <uid>[:<gid>])\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:  \"process, p\",\n\t\t\tUsage: \"path to the process.json\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"detach,d\",\n\t\t\tUsage: \"detach from the container's process\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:  \"pid-file\",\n\t\t\tValue: \"\",\n\t\t\tUsage: \"specify the file to write the process id to\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:  \"process-label\",\n\t\t\tUsage: \"set the asm process label for the process commonly used with selinux\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName:  \"apparmor\",\n\t\t\tUsage: \"set the apparmor profile for the process\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:  \"no-new-privs\",\n\t\t\tUsage: \"set the no new privileges value for the process\",\n\t\t},\n\t\tcli.StringSliceFlag{\n\t\t\tName:  \"cap, c\",\n\t\t\tValue: &cli.StringSlice{},\n\t\t\tUsage: \"add a capability to the bounding set for the process\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName:   \"no-subreaper\",\n\t\t\tUsage:  \"disable the use of the subreaper used to reap reparented processes\",\n\t\t\tHidden: true,\n\t\t},\n\t},\n\tAction: func(context *cli.Context) error {\n\t\tif err := checkArgs(context, 1, minArgs); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif os.Geteuid() != 0 {\n\t\t\treturn fmt.Errorf(\"runc should be run as root\")\n\t\t}\n\t\tif err := revisePidFile(context); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tstatus, err := execProcess(context)\n\t\tif err == nil {\n\t\t\tos.Exit(status)\n\t\t}\n\t\treturn fmt.Errorf(\"exec failed: %v\", err)\n\t},\n\tSkipArgReorder: true,\n}\n\nfunc execProcess(context *cli.Context) (int, error) {\n\tcontainer, err := getContainer(context)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\tstatus, err := container.Status()\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\tif status == libcontainer.Stopped {\n\t\treturn -1, fmt.Errorf(\"cannot exec a container that has run and stopped\")\n\t}\n\tpath := context.String(\"process\")\n\tif path == \"\" && len(context.Args()) == 1 {\n\t\treturn -1, fmt.Errorf(\"process args cannot be empty\")\n\t}\n\tdetach := context.Bool(\"detach\")\n\tstate, err := container.State()\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\tbundle := utils.SearchLabels(state.Config.Labels, \"bundle\")\n\tp, err := getProcess(context, bundle)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\tr := &runner{\n\t\tenableSubreaper: false,\n\t\tshouldDestroy:   false,\n\t\tcontainer:       container,\n\t\tconsoleSocket:   context.String(\"console-socket\"),\n\t\tdetach:          detach,\n\t\tpidFile:         context.String(\"pid-file\"),\n\t}\n\treturn r.run(p)\n}\n\nfunc getProcess(context *cli.Context, bundle string) (*specs.Process, error) {\n\tif path := context.String(\"process\"); path != \"\" {\n\t\tf, err := os.Open(path)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer f.Close()\n\t\tvar p specs.Process\n\t\tif err := json.NewDecoder(f).Decode(&p); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn &p, validateProcessSpec(&p)\n\t}\n\t\/\/ process via cli flags\n\tif err := os.Chdir(bundle); err != nil {\n\t\treturn nil, err\n\t}\n\tspec, err := loadSpec(specConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tp := spec.Process\n\tp.Args = context.Args()[1:]\n\t\/\/ override the cwd, if passed\n\tif context.String(\"cwd\") != \"\" {\n\t\tp.Cwd = context.String(\"cwd\")\n\t}\n\tif ap := context.String(\"apparmor\"); ap != \"\" {\n\t\tp.ApparmorProfile = ap\n\t}\n\tif l := context.String(\"process-label\"); l != \"\" {\n\t\tp.SelinuxLabel = l\n\t}\n\tif caps := context.StringSlice(\"cap\"); len(caps) > 0 {\n\t\tp.Capabilities = caps\n\t}\n\t\/\/ append the passed env variables\n\tp.Env = append(p.Env, context.StringSlice(\"env\")...)\n\n\t\/\/ set the tty\n\tif context.IsSet(\"tty\") {\n\t\tp.Terminal = context.Bool(\"tty\")\n\t}\n\tif context.IsSet(\"no-new-privs\") {\n\t\tp.NoNewPrivileges = context.Bool(\"no-new-privs\")\n\t}\n\t\/\/ override the user, if passed\n\tif context.String(\"user\") != \"\" {\n\t\tu := strings.SplitN(context.String(\"user\"), \":\", 2)\n\t\tif len(u) > 1 {\n\t\t\tgid, err := strconv.Atoi(u[1])\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"parsing %s as int for gid failed: %v\", u[1], err)\n\t\t\t}\n\t\t\tp.User.GID = uint32(gid)\n\t\t}\n\t\tuid, err := strconv.Atoi(u[0])\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"parsing %s as int for uid failed: %v\", u[0], err)\n\t\t}\n\t\tp.User.UID = uint32(uid)\n\t}\n\treturn &p, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"runtime\"\n\t\"strings\"\n)\n\nvar cmdBase = []string{\"sh\", \"-c\"}\n\nfunc init() {\n\tif runtime.GOOS == \"windows\" {\n\t\tcmdBase = []string{\"cmd\", \"\/c\"}\n\t}\n}\n\n\/\/ Exec fillin\nfunc Exec() error {\n\tif len(os.Args) >= 2 {\n\t\tswitch os.Args[1] {\n\t\tcase \"-v\", \"version\", \"-version\", \"--version\":\n\t\t\tprintVersion()\n\t\t\treturn nil\n\t\tcase \"-h\", \"help\", \"-help\", \"--help\":\n\t\t\tprintHelp()\n\t\t\treturn nil\n\t\t}\n\t}\n\tsh, err := exec.LookPath(cmdBase[0])\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfigDir := \"~\/.config\/fillin\"\n\tif dir := os.Getenv(\"FILLIN_CONFIG_DIR\"); dir != \"\" {\n\t\tconfigDir = dir\n\t}\n\tcmd, err := Run(configDir, os.Args[1:], nil, bufio.NewWriter(os.Stdout))\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := syscallExec(sh, append(cmdBase, cmd), os.Environ()); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc printVersion() {\n\tfmt.Printf(\"%s version %s\\n\", name, version)\n}\n\nfunc printHelp() {\n\tfmt.Printf(strings.Replace(`NAME:\n   $NAME - %s\n\nUSAGE:\n   $NAME command...\n\nEXAMPLES:\n   $NAME echo {{message}} # in bash\/zsh shell\n   $NAME echo [[message]] # in fish shell\n   $NAME psql -h {{psql:hostname}} -U {{psql:username}} -d {{psql:dbname}}\n   $NAME curl {{example-api:base-url}}\/api\/1\/example\/info -H 'Authorization: Bearer {{example-api:access-token}}'\n\nVERSION:\n   %s\n\nAUTHOR:\n   %s\n`, \"$NAME\", name, -1), description, version, author)\n}\n<commit_msg>use printf argument indices instead of strings.Replace<commit_after>package main\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"runtime\"\n)\n\nvar cmdBase = []string{\"sh\", \"-c\"}\n\nfunc init() {\n\tif runtime.GOOS == \"windows\" {\n\t\tcmdBase = []string{\"cmd\", \"\/c\"}\n\t}\n}\n\n\/\/ Exec fillin\nfunc Exec() error {\n\tif len(os.Args) >= 2 {\n\t\tswitch os.Args[1] {\n\t\tcase \"-v\", \"version\", \"-version\", \"--version\":\n\t\t\tprintVersion()\n\t\t\treturn nil\n\t\tcase \"-h\", \"help\", \"-help\", \"--help\":\n\t\t\tprintHelp()\n\t\t\treturn nil\n\t\t}\n\t}\n\tsh, err := exec.LookPath(cmdBase[0])\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfigDir := \"~\/.config\/fillin\"\n\tif dir := os.Getenv(\"FILLIN_CONFIG_DIR\"); dir != \"\" {\n\t\tconfigDir = dir\n\t}\n\tcmd, err := Run(configDir, os.Args[1:], nil, bufio.NewWriter(os.Stdout))\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := syscallExec(sh, append(cmdBase, cmd), os.Environ()); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc printVersion() {\n\tfmt.Printf(\"%s version %s\\n\", name, version)\n}\n\nfunc printHelp() {\n\tfmt.Printf(`NAME:\n   %[1]s - %[2]s\n\nUSAGE:\n   %[1]s command...\n\nEXAMPLES:\n   %[1]s echo {{message}} # in bash\/zsh shell\n   %[1]s echo [[message]] # in fish shell\n   %[1]s psql -h {{psql:hostname}} -U {{psql:username}} -d {{psql:dbname}}\n   %[1]s curl {{example-api:base-url}}\/api\/1\/example\/info -H 'Authorization: Bearer {{example-api:access-token}}'\n\nVERSION:\n   %[3]s\n\nAUTHOR:\n   %[4]s\n`, name, description, version, author)\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>nbdsetup<commit_after>\/\/ Copyright (C) 2014 Andreas Klauer <Andreas.Klauer@metamorpher.de>\n\/\/ License: GPL\n\n\/\/ nbdsetup is an alternative to losetup using network block devices.\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com\/frostschutz\/nbd\"\n)\n\nfunc main() {\n\tfile := flag.String(\"file\", \"\", \"regular file or block device\")\n\tflag.Parse()\n\tfmt.Printf(\"Using %s\\n\", *file)\n\tdevice, err := os.Open(*file)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\tstat, _ := device.Stat()\n\tnbd.Create(device, stat.Size())\n}\n\n\/\/ End of file.\n<|endoftext|>"}
{"text":"<commit_before>package torus\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"os\"\n\t\"sync\"\n\t\"time\"\n\n\t\"golang.org\/x\/net\/context\"\n\n\t\"github.com\/coreos\/pkg\/capnslog\"\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n\n\t\"github.com\/coreos\/torus\/models\"\n)\n\nvar (\n\tpromOpenINodes = prometheus.NewGaugeVec(prometheus.GaugeOpts{\n\t\tName: \"torus_server_open_inodes\",\n\t\tHelp: \"Number of open inodes reported on last update to mds\",\n\t}, []string{\"volume\"})\n\tpromOpenFiles = prometheus.NewGaugeVec(prometheus.GaugeOpts{\n\t\tName: \"torus_server_open_files\",\n\t\tHelp: \"Number of open files\",\n\t}, []string{\"volume\"})\n\tpromFileSyncs = prometheus.NewCounterVec(prometheus.CounterOpts{\n\t\tName: \"torus_server_file_syncs\",\n\t\tHelp: \"Number of times a file has been synced on this server\",\n\t}, []string{\"volume\"})\n\tpromFileChangedSyncs = prometheus.NewCounterVec(prometheus.CounterOpts{\n\t\tName: \"torus_server_file_changed_syncs\",\n\t\tHelp: \"Number of times a file has been synced on this server, and the file has changed underneath it\",\n\t}, []string{\"volume\"})\n\tpromFileWrittenBytes = prometheus.NewCounterVec(prometheus.CounterOpts{\n\t\tName: \"torus_server_file_written_bytes\",\n\t\tHelp: \"Number of bytes written to a file on this server\",\n\t}, []string{\"volume\"})\n\tpromFileBlockRead = prometheus.NewHistogram(prometheus.HistogramOpts{\n\t\tName:    \"torus_server_file_block_read_us\",\n\t\tHelp:    \"Histogram of ms taken to read a block through the layers and into the file abstraction\",\n\t\tBuckets: prometheus.ExponentialBuckets(50.0, 2, 20),\n\t})\n\tpromFileBlockWrite = prometheus.NewHistogram(prometheus.HistogramOpts{\n\t\tName:    \"torus_server_file_block_write_us\",\n\t\tHelp:    \"Histogram of ms taken to write a block through the layers and into the file abstraction\",\n\t\tBuckets: prometheus.ExponentialBuckets(50.0, 2, 20),\n\t})\n)\n\nfunc init() {\n\tprometheus.MustRegister(promOpenINodes)\n\tprometheus.MustRegister(promOpenFiles)\n\tprometheus.MustRegister(promFileSyncs)\n\tprometheus.MustRegister(promFileChangedSyncs)\n\tprometheus.MustRegister(promFileWrittenBytes)\n\tprometheus.MustRegister(promFileBlockRead)\n\tprometheus.MustRegister(promFileBlockWrite)\n}\n\ntype File struct {\n\t\/\/ globals\n\tmut      sync.RWMutex\n\tsrv      *Server\n\tblkSize  int64\n\toffset   int64\n\tReadOnly bool\n\n\t\/\/ file metadata\n\tvolume   *models.Volume\n\tinode    *models.INode\n\tblocks   Blockset\n\treplaces uint64\n\tchanged  map[string]bool\n\tcache    fileCache\n\n\twriteINodeRef INodeRef\n\twriteOpen     bool\n}\n\nfunc (f *File) WriteOpen() bool {\n\treturn f.writeOpen\n}\n\nfunc (f *File) Replaces() uint64 {\n\treturn f.replaces\n}\n\nfunc (s *Server) CreateFile(volume *models.Volume, inode *models.INode, blocks Blockset) (*File, error) {\n\tmd := s.MDS.GlobalMetadata()\n\tclog.Tracef(\"Creating File For Inode %d:%d\", inode.Volume, inode.INode)\n\treturn &File{\n\t\tvolume:  volume,\n\t\tinode:   inode,\n\t\tsrv:     s,\n\t\tblocks:  blocks,\n\t\tblkSize: int64(md.BlockSize),\n\t\tcache:   newSingleBlockCache(blocks, md.BlockSize),\n\t}, nil\n}\n\nfunc (f *File) openWrite() error {\n\tif f.ReadOnly {\n\t\treturn ErrLocked\n\t}\n\tif f.writeOpen {\n\t\treturn nil\n\t}\n\tvid := VolumeID(f.volume.Id)\n\tnewINode, err := f.srv.MDS.CommitINodeIndex(vid)\n\tif err != nil {\n\t\treturn err\n\t}\n\tf.writeINodeRef = NewINodeRef(VolumeID(vid), newINode)\n\tif f.inode != nil {\n\t\tf.replaces = f.inode.INode\n\t\tf.inode.INode = uint64(newINode)\n\t}\n\tf.writeOpen = true\n\tf.cache.newINode(f.writeINodeRef)\n\treturn nil\n}\n\nfunc (f *File) writeToBlock(i, from, to int, data []byte) (int, error) {\n\treturn f.cache.writeToBlock(f.getContext(), i, from, to, data)\n}\n\nfunc (f *File) getContext() context.Context {\n\treturn f.srv.getContext()\n}\n\nfunc (f *File) Write(b []byte) (n int, err error) {\n\tn, err = f.WriteAt(b, f.offset)\n\tf.offset += int64(n)\n\treturn\n}\n\nfunc (f *File) WriteAt(b []byte, off int64) (n int, err error) {\n\tf.mut.Lock()\n\tdefer f.mut.Unlock()\n\terr = f.openWrite()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tif clog.LevelAt(capnslog.TRACE) {\n\t\tclog.Trace(\"begin write: offset \", off, \" size \", len(b))\n\t}\n\ttoWrite := len(b)\n\n\tdefer func() {\n\t\tif off > int64(f.inode.Filesize) {\n\t\t\tclog.Tracef(\"updating filesize: %d\", off)\n\t\t\tf.inode.Filesize = uint64(off)\n\t\t}\n\t}()\n\n\t\/\/ Write the front matter, which may dangle from a byte offset\n\tblkIndex := int(off \/ f.blkSize)\n\n\tif f.blocks.Length()+1 < blkIndex {\n\t\tif clog.LevelAt(capnslog.DEBUG) {\n\t\t\tclog.Debug(\"begin write: offset \", off, \" size \", len(b))\n\t\t\tclog.Debug(\"end of file \", f.blocks.Length(), \" blkIndex \", blkIndex)\n\t\t}\n\t\tpromFileWrittenBytes.WithLabelValues(f.volume.Name).Add(float64(n))\n\t\terr := f.Truncate(off)\n\t\tif err != nil {\n\t\t\treturn n, err\n\t\t}\n\t\t\/\/return n, errors.New(\"Can't write past the end of a file\")\n\t}\n\n\tblkOff := off - int64(int(f.blkSize)*blkIndex)\n\tif blkOff != 0 {\n\t\tfrontlen := int(f.blkSize - blkOff)\n\t\tif frontlen > toWrite {\n\t\t\tfrontlen = toWrite\n\t\t}\n\t\twrote, err := f.writeToBlock(blkIndex, int(blkOff), int(blkOff)+frontlen, b[:frontlen])\n\t\tclog.Tracef(\"head writing block at index %d, inoderef %s\", blkIndex, f.writeINodeRef)\n\t\tif err != nil {\n\t\t\treturn n, err\n\t\t} else if wrote != frontlen {\n\t\t\tpromFileWrittenBytes.WithLabelValues(f.volume.Name).Add(float64(n))\n\t\t\treturn n, errors.New(\"Couldn't write all of the first block at the offset\")\n\t\t}\n\t\tb = b[frontlen:]\n\t\tn += wrote\n\t\toff += int64(wrote)\n\t}\n\n\ttoWrite = len(b)\n\tif toWrite == 0 {\n\t\t\/\/ We're done\n\t\tpromFileWrittenBytes.WithLabelValues(f.volume.Name).Add(float64(n))\n\t\treturn n, nil\n\t}\n\n\t\/\/ Bulk Write! We'd rather be here.\n\tif off%f.blkSize != 0 {\n\t\tpanic(\"Offset not equal to a block boundary\")\n\t}\n\n\tfor toWrite >= int(f.blkSize) {\n\t\tblkIndex := int(off \/ f.blkSize)\n\t\tif clog.LevelAt(capnslog.TRACE) {\n\t\t\tclog.Tracef(\"bulk writing block at index %d, inoderef %s\", blkIndex, f.writeINodeRef)\n\t\t}\n\t\tstart := time.Now()\n\t\terr = f.blocks.PutBlock(f.getContext(), f.writeINodeRef, blkIndex, b[:f.blkSize])\n\t\tif err != nil {\n\t\t\tpromFileWrittenBytes.WithLabelValues(f.volume.Name).Add(float64(n))\n\t\t\treturn n, err\n\t\t}\n\t\tdelta := time.Now().Sub(start)\n\t\tpromFileBlockWrite.Observe(float64(delta.Nanoseconds()) \/ 1000)\n\t\tb = b[f.blkSize:]\n\t\tn += int(f.blkSize)\n\t\toff += int64(f.blkSize)\n\t\ttoWrite = len(b)\n\t}\n\n\tif toWrite == 0 {\n\t\t\/\/ We're done\n\t\tpromFileWrittenBytes.WithLabelValues(f.volume.Name).Add(float64(n))\n\t\treturn n, nil\n\t}\n\n\t\/\/ Trailing matter. This sucks too.\n\tif off%f.blkSize != 0 {\n\t\tpanic(\"Offset not equal to a block boundary after bulk\")\n\t}\n\tblkIndex = int(off \/ f.blkSize)\n\twrote, err := f.writeToBlock(blkIndex, 0, toWrite, b)\n\tif clog.LevelAt(capnslog.TRACE) {\n\t\tclog.Tracef(\"tail writing block at index %d, inoderef %s\", blkIndex, f.writeINodeRef)\n\t}\n\tif err != nil {\n\t\tpromFileWrittenBytes.WithLabelValues(f.volume.Name).Add(float64(n))\n\t\treturn n, err\n\t} else if wrote != toWrite {\n\t\tpromFileWrittenBytes.WithLabelValues(f.volume.Name).Add(float64(n))\n\t\treturn n, errors.New(\"Couldn't write all of the last block\")\n\t}\n\tn += wrote\n\toff += int64(wrote)\n\tpromFileWrittenBytes.WithLabelValues(f.volume.Name).Add(float64(n))\n\treturn n, nil\n}\n\nfunc (f *File) Read(b []byte) (n int, err error) {\n\tn, err = f.ReadAt(b, f.offset)\n\tf.offset += int64(n)\n\treturn\n}\n\nfunc (f *File) ReadAt(b []byte, off int64) (n int, ferr error) {\n\tf.mut.RLock()\n\tdefer f.mut.RUnlock()\n\ttoRead := len(b)\n\tif clog.LevelAt(capnslog.TRACE) {\n\t\tclog.Tracef(\"begin read @ %x of size %d\", off, toRead)\n\t}\n\tn = 0\n\tif int64(toRead)+off > int64(f.inode.Filesize) {\n\t\ttoRead = int(int64(f.inode.Filesize) - off)\n\t\tferr = io.EOF\n\t\tclog.Tracef(\"read is longer than file\")\n\t}\n\tfor toRead > n {\n\t\tblkIndex := int(off \/ f.blkSize)\n\t\tblkOff := off - int64(int(f.blkSize)*blkIndex)\n\t\tif clog.LevelAt(capnslog.TRACE) {\n\t\t\tclog.Tracef(\"getting block index %d\", blkIndex)\n\t\t}\n\t\tblk, err := f.cache.getBlock(f.getContext(), blkIndex)\n\t\tif err != nil {\n\t\t\treturn n, err\n\t\t}\n\t\tthisRead := f.blkSize - blkOff\n\t\tif int64(toRead-n) < thisRead {\n\t\t\tthisRead = int64(toRead - n)\n\t\t}\n\t\tcount := copy(b[n:], blk[blkOff:blkOff+thisRead])\n\t\tn += count\n\t\toff += int64(count)\n\t}\n\tif toRead != n {\n\t\t\/\/panic(\"Read more than n bytes?\")\n\t}\n\treturn n, ferr\n}\n\nfunc (f *File) Seek(offset int64, whence int) (int64, error) {\n\t\/\/ TODO(mischief): validate offset\n\tswitch whence {\n\tcase os.SEEK_SET:\n\t\tf.offset = offset\n\tcase os.SEEK_CUR:\n\t\tf.offset += offset\n\tcase os.SEEK_END:\n\t\t\/\/f.offset = int64(f.inode.Filesize) - offset\n\t\tfallthrough\n\tdefault:\n\t\treturn 0, errors.New(\"invalid whence\")\n\t}\n\n\treturn offset, nil\n}\n\nfunc (f *File) Close() error {\n\tif f == nil {\n\t\treturn ErrInvalid\n\t}\n\tpromOpenFiles.WithLabelValues(f.volume.Name).Dec()\n\treturn nil\n}\n\nfunc (f *File) Truncate(size int64) error {\n\terr := f.openWrite()\n\tif err != nil {\n\t\treturn err\n\t}\n\tnBlocks := (size \/ f.blkSize)\n\tif size%f.blkSize != 0 {\n\t\tnBlocks++\n\t}\n\tclog.Tracef(\"truncate to %d %d\", size, nBlocks)\n\tf.blocks.Truncate(int(nBlocks), uint64(f.blkSize))\n\tf.inode.Filesize = uint64(size)\n\treturn nil\n}\n\n\/\/ Trim zeroes data in the middle of a file.\nfunc (f *File) Trim(offset, length int64) error {\n\tclog.Debugf(\"trimming %d %d\", offset, length)\n\terr := f.openWrite()\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/ find the block edges\n\tblkFrom := offset \/ f.blkSize\n\tif offset%f.blkSize != 0 {\n\t\tblkFrom += 1\n\t}\n\tblkTo := (offset + length) \/ f.blkSize\n\treturn f.blocks.Trim(int(blkFrom), int(blkTo))\n}\n\nfunc (f *File) SyncAllWrites() (INodeRef, error) {\n\terr := f.SyncBlocks()\n\tif err != nil {\n\t\treturn ZeroINode(), err\n\t}\n\treturn f.SyncINode(f.getContext())\n}\n\nfunc (f *File) SyncINode(ctx context.Context) (INodeRef, error) {\n\tref := f.writeINodeRef\n\tblkdata, err := MarshalBlocksetToProto(f.blocks)\n\tif err != nil {\n\t\tclog.Error(\"sync: couldn't marshal proto\")\n\t\treturn ZeroINode(), err\n\t}\n\tf.inode.Blocks = blkdata\n\tif f.inode.Volume != f.volume.Id {\n\t\tpanic(\"mismatched volume and inode volume\")\n\t}\n\terr = f.srv.INodes.WriteINode(ctx, ref, f.inode)\n\tif err != nil {\n\t\treturn ZeroINode(), err\n\t}\n\tf.writeOpen = false\n\treturn ref, nil\n}\n\nfunc (f *File) SyncBlocks() error {\n\terr := f.cache.sync(f.getContext())\n\tif err != nil {\n\t\tclog.Error(\"sync: couldn't sync block\")\n\t\treturn err\n\t}\n\treturn f.srv.Blocks.Flush()\n}\n\nfunc (f *File) Size() uint64 {\n\treturn f.inode.Filesize\n}\n<commit_msg>file: tiny: output read offset with decimal number same as write<commit_after>package torus\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"os\"\n\t\"sync\"\n\t\"time\"\n\n\t\"golang.org\/x\/net\/context\"\n\n\t\"github.com\/coreos\/pkg\/capnslog\"\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n\n\t\"github.com\/coreos\/torus\/models\"\n)\n\nvar (\n\tpromOpenINodes = prometheus.NewGaugeVec(prometheus.GaugeOpts{\n\t\tName: \"torus_server_open_inodes\",\n\t\tHelp: \"Number of open inodes reported on last update to mds\",\n\t}, []string{\"volume\"})\n\tpromOpenFiles = prometheus.NewGaugeVec(prometheus.GaugeOpts{\n\t\tName: \"torus_server_open_files\",\n\t\tHelp: \"Number of open files\",\n\t}, []string{\"volume\"})\n\tpromFileSyncs = prometheus.NewCounterVec(prometheus.CounterOpts{\n\t\tName: \"torus_server_file_syncs\",\n\t\tHelp: \"Number of times a file has been synced on this server\",\n\t}, []string{\"volume\"})\n\tpromFileChangedSyncs = prometheus.NewCounterVec(prometheus.CounterOpts{\n\t\tName: \"torus_server_file_changed_syncs\",\n\t\tHelp: \"Number of times a file has been synced on this server, and the file has changed underneath it\",\n\t}, []string{\"volume\"})\n\tpromFileWrittenBytes = prometheus.NewCounterVec(prometheus.CounterOpts{\n\t\tName: \"torus_server_file_written_bytes\",\n\t\tHelp: \"Number of bytes written to a file on this server\",\n\t}, []string{\"volume\"})\n\tpromFileBlockRead = prometheus.NewHistogram(prometheus.HistogramOpts{\n\t\tName:    \"torus_server_file_block_read_us\",\n\t\tHelp:    \"Histogram of ms taken to read a block through the layers and into the file abstraction\",\n\t\tBuckets: prometheus.ExponentialBuckets(50.0, 2, 20),\n\t})\n\tpromFileBlockWrite = prometheus.NewHistogram(prometheus.HistogramOpts{\n\t\tName:    \"torus_server_file_block_write_us\",\n\t\tHelp:    \"Histogram of ms taken to write a block through the layers and into the file abstraction\",\n\t\tBuckets: prometheus.ExponentialBuckets(50.0, 2, 20),\n\t})\n)\n\nfunc init() {\n\tprometheus.MustRegister(promOpenINodes)\n\tprometheus.MustRegister(promOpenFiles)\n\tprometheus.MustRegister(promFileSyncs)\n\tprometheus.MustRegister(promFileChangedSyncs)\n\tprometheus.MustRegister(promFileWrittenBytes)\n\tprometheus.MustRegister(promFileBlockRead)\n\tprometheus.MustRegister(promFileBlockWrite)\n}\n\ntype File struct {\n\t\/\/ globals\n\tmut      sync.RWMutex\n\tsrv      *Server\n\tblkSize  int64\n\toffset   int64\n\tReadOnly bool\n\n\t\/\/ file metadata\n\tvolume   *models.Volume\n\tinode    *models.INode\n\tblocks   Blockset\n\treplaces uint64\n\tchanged  map[string]bool\n\tcache    fileCache\n\n\twriteINodeRef INodeRef\n\twriteOpen     bool\n}\n\nfunc (f *File) WriteOpen() bool {\n\treturn f.writeOpen\n}\n\nfunc (f *File) Replaces() uint64 {\n\treturn f.replaces\n}\n\nfunc (s *Server) CreateFile(volume *models.Volume, inode *models.INode, blocks Blockset) (*File, error) {\n\tmd := s.MDS.GlobalMetadata()\n\tclog.Tracef(\"Creating File For Inode %d:%d\", inode.Volume, inode.INode)\n\treturn &File{\n\t\tvolume:  volume,\n\t\tinode:   inode,\n\t\tsrv:     s,\n\t\tblocks:  blocks,\n\t\tblkSize: int64(md.BlockSize),\n\t\tcache:   newSingleBlockCache(blocks, md.BlockSize),\n\t}, nil\n}\n\nfunc (f *File) openWrite() error {\n\tif f.ReadOnly {\n\t\treturn ErrLocked\n\t}\n\tif f.writeOpen {\n\t\treturn nil\n\t}\n\tvid := VolumeID(f.volume.Id)\n\tnewINode, err := f.srv.MDS.CommitINodeIndex(vid)\n\tif err != nil {\n\t\treturn err\n\t}\n\tf.writeINodeRef = NewINodeRef(VolumeID(vid), newINode)\n\tif f.inode != nil {\n\t\tf.replaces = f.inode.INode\n\t\tf.inode.INode = uint64(newINode)\n\t}\n\tf.writeOpen = true\n\tf.cache.newINode(f.writeINodeRef)\n\treturn nil\n}\n\nfunc (f *File) writeToBlock(i, from, to int, data []byte) (int, error) {\n\treturn f.cache.writeToBlock(f.getContext(), i, from, to, data)\n}\n\nfunc (f *File) getContext() context.Context {\n\treturn f.srv.getContext()\n}\n\nfunc (f *File) Write(b []byte) (n int, err error) {\n\tn, err = f.WriteAt(b, f.offset)\n\tf.offset += int64(n)\n\treturn\n}\n\nfunc (f *File) WriteAt(b []byte, off int64) (n int, err error) {\n\tf.mut.Lock()\n\tdefer f.mut.Unlock()\n\terr = f.openWrite()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tif clog.LevelAt(capnslog.TRACE) {\n\t\tclog.Trace(\"begin write: offset \", off, \" size \", len(b))\n\t}\n\ttoWrite := len(b)\n\n\tdefer func() {\n\t\tif off > int64(f.inode.Filesize) {\n\t\t\tclog.Tracef(\"updating filesize: %d\", off)\n\t\t\tf.inode.Filesize = uint64(off)\n\t\t}\n\t}()\n\n\t\/\/ Write the front matter, which may dangle from a byte offset\n\tblkIndex := int(off \/ f.blkSize)\n\n\tif f.blocks.Length()+1 < blkIndex {\n\t\tif clog.LevelAt(capnslog.DEBUG) {\n\t\t\tclog.Debug(\"begin write: offset \", off, \" size \", len(b))\n\t\t\tclog.Debug(\"end of file \", f.blocks.Length(), \" blkIndex \", blkIndex)\n\t\t}\n\t\tpromFileWrittenBytes.WithLabelValues(f.volume.Name).Add(float64(n))\n\t\terr := f.Truncate(off)\n\t\tif err != nil {\n\t\t\treturn n, err\n\t\t}\n\t\t\/\/return n, errors.New(\"Can't write past the end of a file\")\n\t}\n\n\tblkOff := off - int64(int(f.blkSize)*blkIndex)\n\tif blkOff != 0 {\n\t\tfrontlen := int(f.blkSize - blkOff)\n\t\tif frontlen > toWrite {\n\t\t\tfrontlen = toWrite\n\t\t}\n\t\twrote, err := f.writeToBlock(blkIndex, int(blkOff), int(blkOff)+frontlen, b[:frontlen])\n\t\tclog.Tracef(\"head writing block at index %d, inoderef %s\", blkIndex, f.writeINodeRef)\n\t\tif err != nil {\n\t\t\treturn n, err\n\t\t} else if wrote != frontlen {\n\t\t\tpromFileWrittenBytes.WithLabelValues(f.volume.Name).Add(float64(n))\n\t\t\treturn n, errors.New(\"Couldn't write all of the first block at the offset\")\n\t\t}\n\t\tb = b[frontlen:]\n\t\tn += wrote\n\t\toff += int64(wrote)\n\t}\n\n\ttoWrite = len(b)\n\tif toWrite == 0 {\n\t\t\/\/ We're done\n\t\tpromFileWrittenBytes.WithLabelValues(f.volume.Name).Add(float64(n))\n\t\treturn n, nil\n\t}\n\n\t\/\/ Bulk Write! We'd rather be here.\n\tif off%f.blkSize != 0 {\n\t\tpanic(\"Offset not equal to a block boundary\")\n\t}\n\n\tfor toWrite >= int(f.blkSize) {\n\t\tblkIndex := int(off \/ f.blkSize)\n\t\tif clog.LevelAt(capnslog.TRACE) {\n\t\t\tclog.Tracef(\"bulk writing block at index %d, inoderef %s\", blkIndex, f.writeINodeRef)\n\t\t}\n\t\tstart := time.Now()\n\t\terr = f.blocks.PutBlock(f.getContext(), f.writeINodeRef, blkIndex, b[:f.blkSize])\n\t\tif err != nil {\n\t\t\tpromFileWrittenBytes.WithLabelValues(f.volume.Name).Add(float64(n))\n\t\t\treturn n, err\n\t\t}\n\t\tdelta := time.Now().Sub(start)\n\t\tpromFileBlockWrite.Observe(float64(delta.Nanoseconds()) \/ 1000)\n\t\tb = b[f.blkSize:]\n\t\tn += int(f.blkSize)\n\t\toff += int64(f.blkSize)\n\t\ttoWrite = len(b)\n\t}\n\n\tif toWrite == 0 {\n\t\t\/\/ We're done\n\t\tpromFileWrittenBytes.WithLabelValues(f.volume.Name).Add(float64(n))\n\t\treturn n, nil\n\t}\n\n\t\/\/ Trailing matter. This sucks too.\n\tif off%f.blkSize != 0 {\n\t\tpanic(\"Offset not equal to a block boundary after bulk\")\n\t}\n\tblkIndex = int(off \/ f.blkSize)\n\twrote, err := f.writeToBlock(blkIndex, 0, toWrite, b)\n\tif clog.LevelAt(capnslog.TRACE) {\n\t\tclog.Tracef(\"tail writing block at index %d, inoderef %s\", blkIndex, f.writeINodeRef)\n\t}\n\tif err != nil {\n\t\tpromFileWrittenBytes.WithLabelValues(f.volume.Name).Add(float64(n))\n\t\treturn n, err\n\t} else if wrote != toWrite {\n\t\tpromFileWrittenBytes.WithLabelValues(f.volume.Name).Add(float64(n))\n\t\treturn n, errors.New(\"Couldn't write all of the last block\")\n\t}\n\tn += wrote\n\toff += int64(wrote)\n\tpromFileWrittenBytes.WithLabelValues(f.volume.Name).Add(float64(n))\n\treturn n, nil\n}\n\nfunc (f *File) Read(b []byte) (n int, err error) {\n\tn, err = f.ReadAt(b, f.offset)\n\tf.offset += int64(n)\n\treturn\n}\n\nfunc (f *File) ReadAt(b []byte, off int64) (n int, ferr error) {\n\tf.mut.RLock()\n\tdefer f.mut.RUnlock()\n\ttoRead := len(b)\n\tif clog.LevelAt(capnslog.TRACE) {\n\t\tclog.Trace(\"begin read: offset \", off, \" size \", toRead)\n\t}\n\tn = 0\n\tif int64(toRead)+off > int64(f.inode.Filesize) {\n\t\ttoRead = int(int64(f.inode.Filesize) - off)\n\t\tferr = io.EOF\n\t\tclog.Tracef(\"read is longer than file\")\n\t}\n\tfor toRead > n {\n\t\tblkIndex := int(off \/ f.blkSize)\n\t\tblkOff := off - int64(int(f.blkSize)*blkIndex)\n\t\tif clog.LevelAt(capnslog.TRACE) {\n\t\t\tclog.Tracef(\"getting block index %d\", blkIndex)\n\t\t}\n\t\tblk, err := f.cache.getBlock(f.getContext(), blkIndex)\n\t\tif err != nil {\n\t\t\treturn n, err\n\t\t}\n\t\tthisRead := f.blkSize - blkOff\n\t\tif int64(toRead-n) < thisRead {\n\t\t\tthisRead = int64(toRead - n)\n\t\t}\n\t\tcount := copy(b[n:], blk[blkOff:blkOff+thisRead])\n\t\tn += count\n\t\toff += int64(count)\n\t}\n\tif toRead != n {\n\t\t\/\/panic(\"Read more than n bytes?\")\n\t}\n\treturn n, ferr\n}\n\nfunc (f *File) Seek(offset int64, whence int) (int64, error) {\n\t\/\/ TODO(mischief): validate offset\n\tswitch whence {\n\tcase os.SEEK_SET:\n\t\tf.offset = offset\n\tcase os.SEEK_CUR:\n\t\tf.offset += offset\n\tcase os.SEEK_END:\n\t\t\/\/f.offset = int64(f.inode.Filesize) - offset\n\t\tfallthrough\n\tdefault:\n\t\treturn 0, errors.New(\"invalid whence\")\n\t}\n\n\treturn offset, nil\n}\n\nfunc (f *File) Close() error {\n\tif f == nil {\n\t\treturn ErrInvalid\n\t}\n\tpromOpenFiles.WithLabelValues(f.volume.Name).Dec()\n\treturn nil\n}\n\nfunc (f *File) Truncate(size int64) error {\n\terr := f.openWrite()\n\tif err != nil {\n\t\treturn err\n\t}\n\tnBlocks := (size \/ f.blkSize)\n\tif size%f.blkSize != 0 {\n\t\tnBlocks++\n\t}\n\tclog.Tracef(\"truncate to %d %d\", size, nBlocks)\n\tf.blocks.Truncate(int(nBlocks), uint64(f.blkSize))\n\tf.inode.Filesize = uint64(size)\n\treturn nil\n}\n\n\/\/ Trim zeroes data in the middle of a file.\nfunc (f *File) Trim(offset, length int64) error {\n\tclog.Debugf(\"trimming %d %d\", offset, length)\n\terr := f.openWrite()\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/ find the block edges\n\tblkFrom := offset \/ f.blkSize\n\tif offset%f.blkSize != 0 {\n\t\tblkFrom += 1\n\t}\n\tblkTo := (offset + length) \/ f.blkSize\n\treturn f.blocks.Trim(int(blkFrom), int(blkTo))\n}\n\nfunc (f *File) SyncAllWrites() (INodeRef, error) {\n\terr := f.SyncBlocks()\n\tif err != nil {\n\t\treturn ZeroINode(), err\n\t}\n\treturn f.SyncINode(f.getContext())\n}\n\nfunc (f *File) SyncINode(ctx context.Context) (INodeRef, error) {\n\tref := f.writeINodeRef\n\tblkdata, err := MarshalBlocksetToProto(f.blocks)\n\tif err != nil {\n\t\tclog.Error(\"sync: couldn't marshal proto\")\n\t\treturn ZeroINode(), err\n\t}\n\tf.inode.Blocks = blkdata\n\tif f.inode.Volume != f.volume.Id {\n\t\tpanic(\"mismatched volume and inode volume\")\n\t}\n\terr = f.srv.INodes.WriteINode(ctx, ref, f.inode)\n\tif err != nil {\n\t\treturn ZeroINode(), err\n\t}\n\tf.writeOpen = false\n\treturn ref, nil\n}\n\nfunc (f *File) SyncBlocks() error {\n\terr := f.cache.sync(f.getContext())\n\tif err != nil {\n\t\tclog.Error(\"sync: couldn't sync block\")\n\t\treturn err\n\t}\n\treturn f.srv.Blocks.Flush()\n}\n\nfunc (f *File) Size() uint64 {\n\treturn f.inode.Filesize\n}\n<|endoftext|>"}
{"text":"<commit_before>package amsutil\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"mime\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/recruit-tech\/go-ams\"\n)\n\nconst (\n\tuploadPolicyName       = \"UploadPolicy\"\n\tuploadDurationInMinute = 440.0\n)\n\nfunc UploadFile(ctx context.Context, client *ams.Client, file *os.File) (*ams.Asset, error) {\n\tif client == nil {\n\t\treturn nil, errors.New(\"client missing\")\n\t}\n\tif file == nil {\n\t\treturn nil, errors.New(\"file missing\")\n\t}\n\n\tstat, err := file.Stat()\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"upload file stat read failed\")\n\t}\n\n\t_, filename := path.Split(file.Name())\n\tmimeType := mime.TypeByExtension(path.Ext(filename))\n\tif !strings.HasPrefix(mimeType, \"video\/\") {\n\t\treturn nil, errors.Errorf(\"invalid file type. expected video\/*, actual '%s'\", mimeType)\n\t}\n\n\tasset, err := client.CreateAsset(ctx, filename)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"create asset failed. name='%s'\", filename)\n\t}\n\n\tassetFile, err := client.CreateAssetFile(ctx, asset.ID, filename, mimeType)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"create asset file failed. assetID='%s'\", asset.ID)\n\t}\n\n\taccessPolicy, err := client.CreateAccessPolicy(ctx, uploadPolicyName, uploadDurationInMinute, ams.PermissionWrite)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"create access policy failed\")\n\t}\n\tdefer client.DeleteAccessPolicy(ctx, accessPolicy.ID)\n\n\tstartTime := time.Now().Add(-5 * time.Minute)\n\tlocator, err := client.CreateLocator(ctx, accessPolicy.ID, asset.ID, startTime, ams.LocatorSAS)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"create locator failed\")\n\t}\n\tdefer client.DeleteLocator(ctx, locator.ID)\n\n\tuploadURL, err := locator.ToUploadURL(filename)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"upload url build failed. name='%s'\", uploadURL.String())\n\t}\n\n\tblockList, err := client.PutBlob(ctx, uploadURL, file)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"put blob failed\")\n\t}\n\n\tif err := client.PutBlockList(ctx, uploadURL, blockList); err != nil {\n\t\treturn nil, errors.Wrap(err, \"put block list failed\")\n\t}\n\n\tassetFile.ContentFileSize = fmt.Sprint(stat.Size())\n\tif err := client.UpdateAssetFile(ctx, assetFile); err != nil {\n\t\treturn nil, errors.Wrap(err, \"update asset file failed\")\n\t}\n\n\treturn asset, nil\n}\n<commit_msg>feat: use blob<commit_after>package amsutil\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"mime\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/recruit-tech\/go-ams\"\n)\n\nconst (\n\tuploadPolicyName       = \"UploadPolicy\"\n\tuploadDurationInMinute = 440.0\n)\n\nfunc UploadFile(ctx context.Context, client *ams.Client, file *os.File) (*ams.Asset, error) {\n\tif client == nil {\n\t\treturn nil, errors.New(\"client missing\")\n\t}\n\tif file == nil {\n\t\treturn nil, errors.New(\"file missing\")\n\t}\n\n\tblob, err := ams.NewFileBlob(file)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"blob construct failed\")\n\t}\n\n\t_, filename := path.Split(file.Name())\n\tmimeType := mime.TypeByExtension(path.Ext(filename))\n\tif !strings.HasPrefix(mimeType, \"video\/\") {\n\t\treturn nil, errors.Errorf(\"invalid file type. expected video\/*, actual '%s'\", mimeType)\n\t}\n\n\tasset, err := client.CreateAsset(ctx, filename)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"create asset failed. name='%s'\", filename)\n\t}\n\n\tassetFile, err := client.CreateAssetFile(ctx, asset.ID, filename, mimeType)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"create asset file failed. assetID='%s'\", asset.ID)\n\t}\n\n\taccessPolicy, err := client.CreateAccessPolicy(ctx, uploadPolicyName, uploadDurationInMinute, ams.PermissionWrite)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"create access policy failed\")\n\t}\n\tdefer client.DeleteAccessPolicy(ctx, accessPolicy.ID)\n\n\tstartTime := time.Now().Add(-5 * time.Minute)\n\tlocator, err := client.CreateLocator(ctx, accessPolicy.ID, asset.ID, startTime, ams.LocatorSAS)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"create locator failed\")\n\t}\n\tdefer client.DeleteLocator(ctx, locator.ID)\n\n\tuploadURL, err := locator.ToUploadURL(filename)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"upload url build failed. name='%s'\", uploadURL.String())\n\t}\n\n\tvar blockList []string\n\tblockID := \"block-id-01\"\n\tif err := client.PutBlob(ctx, uploadURL, blob, blockID); err != nil {\n\t\treturn nil, errors.Wrap(err, \"put blob failed\")\n\t}\n\tblockList = append(blockList, blockID)\n\tif err := client.PutBlockList(ctx, uploadURL, blockList); err != nil {\n\t\treturn nil, errors.Wrap(err, \"put block list failed\")\n\t}\n\n\tassetFile.ContentFileSize = fmt.Sprint(blob.Size())\n\tif err := client.UpdateAssetFile(ctx, assetFile); err != nil {\n\t\treturn nil, errors.Wrap(err, \"update asset file failed\")\n\t}\n\n\treturn asset, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package libp2ptls\n\nimport (\n\tmrand \"math\/rand\"\n\t\"testing\"\n\n\t. \"github.com\/onsi\/ginkgo\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\nfunc TestLibp2pTLS(t *testing.T) {\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"libp2p TLS Suite\")\n}\n\nvar _ = BeforeSuite(func() {\n\tmrand.Seed(GinkgoRandomSeed())\n})\n<commit_msg>remove the Ginkgo test suite<commit_after><|endoftext|>"}
{"text":"<commit_before>\/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *  http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\npackage cli\n\nimport (\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com\/spf13\/cobra\"\n\t\"mynewt.apache.org\/newt\/newt\/interfaces\"\n\t\"mynewt.apache.org\/newt\/newt\/newtutil\"\n\t\"mynewt.apache.org\/newt\/newt\/pkg\"\n\t\"mynewt.apache.org\/newt\/newt\/project\"\n\t\"mynewt.apache.org\/newt\/util\"\n)\n\nvar NewTypeStr = \"pkg\"\n\nfunc pkgNewCmd(cmd *cobra.Command, args []string) {\n\tNewTypeStr = strings.ToUpper(NewTypeStr)\n\n\tpw := project.NewPackageWriter()\n\tif err := pw.ConfigurePackage(NewTypeStr, args[0]); err != nil {\n\t\tNewtUsage(cmd, err)\n\t}\n\tif err := pw.WritePackage(); err != nil {\n\t\tNewtUsage(cmd, err)\n\t}\n}\n\nfunc pkgMoveCmd(cmd *cobra.Command, args []string) {\n\tif len(args) != 2 {\n\t\tNewtUsage(cmd, util.NewNewtError(\"Exactly two arguments required to pkg move\"))\n\t}\n\n\tsrcLoc := args[0]\n\tdstLoc := args[1]\n\n\tproj := TryGetProject()\n\tinterfaces.SetProject(proj)\n\n\twd, err := os.Getwd()\n\tif err != nil {\n\t\tNewtUsage(cmd, util.ChildNewtError(err))\n\t}\n\n\tif err := os.Chdir(proj.Path() + \"\/\"); err != nil {\n\t\tNewtUsage(cmd, util.ChildNewtError(err))\n\t}\n\n\t\/* Find source package, defaulting search to the local project if no\n\t * repository descriptor is found.\n\t *\/\n\tsrcRepoName, srcName, err := newtutil.ParsePackageString(srcLoc)\n\tif err != nil {\n\t\tos.Chdir(wd)\n\t\tNewtUsage(cmd, err)\n\t}\n\n\tsrcRepo := proj.LocalRepo()\n\tif srcRepoName != \"\" {\n\t\tsrcRepo = proj.FindRepo(srcRepoName)\n\t}\n\n\tsrcPkg, err := proj.ResolvePackage(srcRepo, srcName)\n\tif err != nil {\n\t\tos.Chdir(wd)\n\t\tNewtUsage(cmd, err)\n\t}\n\n\t\/* Resolve the destination package to a physical location, and then\n\t * move the source package to that location.\n\t * dstLoc is assumed to be in the format \"@repo\/pkg\/loc\"\n\t *\/\n\trepoName, pkgName, err := newtutil.ParsePackageString(dstLoc)\n\tif err != nil {\n\t\tos.Chdir(wd)\n\t\tNewtUsage(cmd, err)\n\t}\n\n\tdstPath := proj.Path() + \"\/\"\n\trepo := proj.LocalRepo()\n\tif repoName != \"\" {\n\t\tdstPath += \"repos\/\" + repoName + \"\/\"\n\t\trepo = proj.FindRepo(repoName)\n\t\tif repo == nil {\n\t\t\tos.Chdir(wd)\n\t\t\tNewtUsage(cmd, util.NewNewtError(\"Destination repo \"+\n\t\t\t\trepoName+\" does not exist\"))\n\t\t}\n\t}\n\tdstPath += pkgName + \"\/\"\n\n\tif util.NodeExist(dstPath) {\n\t\tos.Chdir(wd)\n\t\tNewtUsage(cmd, util.NewNewtError(\"Cannot overwrite existing package, \"+\n\t\t\t\"use pkg delete first\"))\n\t}\n\n\tutil.StatusMessage(util.VERBOSITY_DEFAULT, \"Moving package %s to %s\\n\",\n\t\tsrcLoc, dstLoc)\n\n\tif err := util.MoveDir(srcPkg.BasePath(), dstPath); err != nil {\n\t\tos.Chdir(wd)\n\t\tNewtUsage(cmd, err)\n\t}\n\n\t\/* Replace the package name in the pkg.yml file *\/\n\tpkgData, err := ioutil.ReadFile(dstPath + \"\/pkg.yml\")\n\tif err != nil {\n\t\tos.Chdir(wd)\n\t\tNewtUsage(cmd, err)\n\t}\n\n\tre := regexp.MustCompile(regexp.QuoteMeta(srcName))\n\tres := re.ReplaceAllString(string(pkgData), pkgName)\n\n\tif err := ioutil.WriteFile(dstPath+\"\/pkg.yml\", []byte(res), 0666); err != nil {\n\t\tNewtUsage(cmd, util.ChildNewtError(err))\n\t}\n\n\t\/* If the last element of the package path changes, rename the include\n\t * directory.\n\t *\/\n\tif path.Base(pkgName) != path.Base(srcPkg.Name()) {\n\t\tutil.MoveDir(dstPath+\"\/include\/\"+path.Base(srcPkg.Name()),\n\t\t\tdstPath+\"\/include\/\"+path.Base(pkgName))\n\t}\n\n\tos.Chdir(wd)\n}\n\nfunc pkgRemoveCmd(cmd *cobra.Command, args []string) {\n\tif len(args) != 1 {\n\t\tNewtUsage(cmd, util.NewNewtError(\"Must specify a package name to delete\"))\n\t}\n\n\tproj := TryGetProject()\n\tinterfaces.SetProject(proj)\n\n\twd, err := os.Getwd()\n\tif err != nil {\n\t\tNewtUsage(cmd, util.ChildNewtError(err))\n\t}\n\n\tif err := os.Chdir(proj.Path() + \"\/\"); err != nil {\n\t\tNewtUsage(cmd, util.ChildNewtError(err))\n\t}\n\t\/* Resolve package, and get path from package to ensure we're being asked\n\t * to remove a valid path.\n\t *\/\n\trepoName, pkgName, err := newtutil.ParsePackageString(args[0])\n\tif err != nil {\n\t\tos.Chdir(wd)\n\t\tNewtUsage(cmd, err)\n\t}\n\n\trepo := proj.LocalRepo()\n\tif repoName != \"\" {\n\t\trepo = proj.FindRepo(repoName)\n\t\tif repo == nil {\n\t\t\tos.Chdir(wd)\n\t\t\tNewtUsage(cmd, util.NewNewtError(\"Destination repo \"+\n\t\t\t\trepoName+\" does not exist\"))\n\t\t}\n\t}\n\n\tpkg, err := pkg.LoadLocalPackage(repo, pkgName)\n\tif err != nil {\n\t\tos.Chdir(wd)\n\t\tNewtUsage(cmd, err)\n\t}\n\n\tutil.StatusMessage(util.VERBOSITY_DEFAULT, \"Removing package %s\\n\",\n\t\targs[0])\n\n\tif err := os.RemoveAll(pkg.BasePath()); err != nil {\n\t\tos.Chdir(wd)\n\t\tNewtUsage(cmd, util.ChildNewtError(err))\n\t}\n\n\tos.Chdir(wd)\n}\n\nfunc AddPackageCommands(cmd *cobra.Command) {\n\t\/* Add the base package command, on top of which other commands are\n\t * keyed\n\t *\/\n\tpkgHelpText := \"Commands for creating and manipulating packages\"\n\tpkgHelpEx := \"  newt pkg new --type=pkg libs\/mylib\"\n\n\tpkgCmd := &cobra.Command{\n\t\tUse:     \"pkg\",\n\t\tShort:   \"Create and manage packages in the current workspace\",\n\t\tLong:    pkgHelpText,\n\t\tExample: pkgHelpEx,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmd.Help()\n\t\t},\n\t}\n\n\tcmd.AddCommand(pkgCmd)\n\n\t\/* Package new command, create a new package *\/\n\tnewCmdHelpText := \"\"\n\tnewCmdHelpEx := \"\"\n\n\tnewCmd := &cobra.Command{\n\t\tUse:     \"new\",\n\t\tShort:   \"Create a new package, from a template\",\n\t\tLong:    newCmdHelpText,\n\t\tExample: newCmdHelpEx,\n\t\tRun:     pkgNewCmd,\n\t}\n\n\tnewCmd.PersistentFlags().StringVarP(&NewTypeStr, \"type\", \"t\",\n\t\t\"pkg\", \"Type of package to create: pkg, bsp, sdk.  Default pkg.\")\n\n\tpkgCmd.AddCommand(newCmd)\n\n\tmoveCmdHelpText := \"\"\n\tmoveCmdHelpEx := \"\"\n\n\tmoveCmd := &cobra.Command{\n\t\tUse:     \"move\",\n\t\tShort:   \"Move a package from one location to another\",\n\t\tLong:    moveCmdHelpText,\n\t\tExample: moveCmdHelpEx,\n\t\tRun:     pkgMoveCmd,\n\t}\n\n\tpkgCmd.AddCommand(moveCmd)\n\n\tremoveCmdHelpText := \"\"\n\tremoveCmdHelpEx := \"\"\n\n\tremoveCmd := &cobra.Command{\n\t\tUse:     \"remove\",\n\t\tShort:   \"Remove a package\",\n\t\tLong:    removeCmdHelpText,\n\t\tExample: removeCmdHelpEx,\n\t\tRun:     pkgRemoveCmd,\n\t}\n\n\tpkgCmd.AddCommand(removeCmd)\n}\n<commit_msg>use defer to exit function instead of calling os.Chdir() in exit path<commit_after>\/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements.  See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership.  The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License.  You may obtain a copy of the License at\n *\n *  http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied.  See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\npackage cli\n\nimport (\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com\/spf13\/cobra\"\n\t\"mynewt.apache.org\/newt\/newt\/interfaces\"\n\t\"mynewt.apache.org\/newt\/newt\/newtutil\"\n\t\"mynewt.apache.org\/newt\/newt\/pkg\"\n\t\"mynewt.apache.org\/newt\/newt\/project\"\n\t\"mynewt.apache.org\/newt\/util\"\n)\n\nvar NewTypeStr = \"pkg\"\n\nfunc pkgNewCmd(cmd *cobra.Command, args []string) {\n\tNewTypeStr = strings.ToUpper(NewTypeStr)\n\n\tpw := project.NewPackageWriter()\n\tif err := pw.ConfigurePackage(NewTypeStr, args[0]); err != nil {\n\t\tNewtUsage(cmd, err)\n\t}\n\tif err := pw.WritePackage(); err != nil {\n\t\tNewtUsage(cmd, err)\n\t}\n}\n\nfunc pkgMoveCmd(cmd *cobra.Command, args []string) {\n\tif len(args) != 2 {\n\t\tNewtUsage(cmd, util.NewNewtError(\"Exactly two arguments required to pkg move\"))\n\t}\n\n\tsrcLoc := args[0]\n\tdstLoc := args[1]\n\n\tproj := TryGetProject()\n\tinterfaces.SetProject(proj)\n\n\twd, err := os.Getwd()\n\tif err != nil {\n\t\tNewtUsage(cmd, util.ChildNewtError(err))\n\t}\n\tdefer os.Chdir(wd)\n\n\tif err := os.Chdir(proj.Path() + \"\/\"); err != nil {\n\t\tNewtUsage(cmd, util.ChildNewtError(err))\n\t}\n\n\t\/* Find source package, defaulting search to the local project if no\n\t * repository descriptor is found.\n\t *\/\n\tsrcRepoName, srcName, err := newtutil.ParsePackageString(srcLoc)\n\tif err != nil {\n\t\tNewtUsage(cmd, err)\n\t}\n\n\tsrcRepo := proj.LocalRepo()\n\tif srcRepoName != \"\" {\n\t\tsrcRepo = proj.FindRepo(srcRepoName)\n\t}\n\n\tsrcPkg, err := proj.ResolvePackage(srcRepo, srcName)\n\tif err != nil {\n\t\tNewtUsage(cmd, err)\n\t}\n\n\t\/* Resolve the destination package to a physical location, and then\n\t * move the source package to that location.\n\t * dstLoc is assumed to be in the format \"@repo\/pkg\/loc\"\n\t *\/\n\trepoName, pkgName, err := newtutil.ParsePackageString(dstLoc)\n\tif err != nil {\n\t\tNewtUsage(cmd, err)\n\t}\n\n\tdstPath := proj.Path() + \"\/\"\n\trepo := proj.LocalRepo()\n\tif repoName != \"\" {\n\t\tdstPath += \"repos\/\" + repoName + \"\/\"\n\t\trepo = proj.FindRepo(repoName)\n\t\tif repo == nil {\n\t\t\tNewtUsage(cmd, util.NewNewtError(\"Destination repo \"+\n\t\t\t\trepoName+\" does not exist\"))\n\t\t}\n\t}\n\tdstPath += pkgName + \"\/\"\n\n\tif util.NodeExist(dstPath) {\n\t\tNewtUsage(cmd, util.NewNewtError(\"Cannot overwrite existing package, \"+\n\t\t\t\"use pkg delete first\"))\n\t}\n\n\tutil.StatusMessage(util.VERBOSITY_DEFAULT, \"Moving package %s to %s\\n\",\n\t\tsrcLoc, dstLoc)\n\n\tif err := util.MoveDir(srcPkg.BasePath(), dstPath); err != nil {\n\t\tNewtUsage(cmd, err)\n\t}\n\n\t\/* Replace the package name in the pkg.yml file *\/\n\tpkgData, err := ioutil.ReadFile(dstPath + \"\/pkg.yml\")\n\tif err != nil {\n\t\tNewtUsage(cmd, err)\n\t}\n\n\tre := regexp.MustCompile(regexp.QuoteMeta(srcName))\n\tres := re.ReplaceAllString(string(pkgData), pkgName)\n\n\tif err := ioutil.WriteFile(dstPath+\"\/pkg.yml\", []byte(res), 0666); err != nil {\n\t\tNewtUsage(cmd, util.ChildNewtError(err))\n\t}\n\n\t\/* If the last element of the package path changes, rename the include\n\t * directory.\n\t *\/\n\tif path.Base(pkgName) != path.Base(srcPkg.Name()) {\n\t\tutil.MoveDir(dstPath+\"\/include\/\"+path.Base(srcPkg.Name()),\n\t\t\tdstPath+\"\/include\/\"+path.Base(pkgName))\n\t}\n}\n\nfunc pkgRemoveCmd(cmd *cobra.Command, args []string) {\n\tif len(args) != 1 {\n\t\tNewtUsage(cmd, util.NewNewtError(\"Must specify a package name to delete\"))\n\t}\n\n\tproj := TryGetProject()\n\tinterfaces.SetProject(proj)\n\n\twd, err := os.Getwd()\n\tif err != nil {\n\t\tNewtUsage(cmd, util.ChildNewtError(err))\n\t}\n\tdefer os.Chdir(wd)\n\n\tif err := os.Chdir(proj.Path() + \"\/\"); err != nil {\n\t\tNewtUsage(cmd, util.ChildNewtError(err))\n\t}\n\t\/* Resolve package, and get path from package to ensure we're being asked\n\t * to remove a valid path.\n\t *\/\n\trepoName, pkgName, err := newtutil.ParsePackageString(args[0])\n\tif err != nil {\n\t\tos.Chdir(wd)\n\t\tNewtUsage(cmd, err)\n\t}\n\n\trepo := proj.LocalRepo()\n\tif repoName != \"\" {\n\t\trepo = proj.FindRepo(repoName)\n\t\tif repo == nil {\n\t\t\tos.Chdir(wd)\n\t\t\tNewtUsage(cmd, util.NewNewtError(\"Destination repo \"+\n\t\t\t\trepoName+\" does not exist\"))\n\t\t}\n\t}\n\n\tpkg, err := pkg.LoadLocalPackage(repo, pkgName)\n\tif err != nil {\n\t\tos.Chdir(wd)\n\t\tNewtUsage(cmd, err)\n\t}\n\n\tutil.StatusMessage(util.VERBOSITY_DEFAULT, \"Removing package %s\\n\",\n\t\targs[0])\n\n\tif err := os.RemoveAll(pkg.BasePath()); err != nil {\n\t\tos.Chdir(wd)\n\t\tNewtUsage(cmd, util.ChildNewtError(err))\n\t}\n\n\tos.Chdir(wd)\n}\n\nfunc AddPackageCommands(cmd *cobra.Command) {\n\t\/* Add the base package command, on top of which other commands are\n\t * keyed\n\t *\/\n\tpkgHelpText := \"Commands for creating and manipulating packages\"\n\tpkgHelpEx := \"  newt pkg new --type=pkg libs\/mylib\"\n\n\tpkgCmd := &cobra.Command{\n\t\tUse:     \"pkg\",\n\t\tShort:   \"Create and manage packages in the current workspace\",\n\t\tLong:    pkgHelpText,\n\t\tExample: pkgHelpEx,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmd.Help()\n\t\t},\n\t}\n\n\tcmd.AddCommand(pkgCmd)\n\n\t\/* Package new command, create a new package *\/\n\tnewCmdHelpText := \"\"\n\tnewCmdHelpEx := \"\"\n\n\tnewCmd := &cobra.Command{\n\t\tUse:     \"new\",\n\t\tShort:   \"Create a new package, from a template\",\n\t\tLong:    newCmdHelpText,\n\t\tExample: newCmdHelpEx,\n\t\tRun:     pkgNewCmd,\n\t}\n\n\tnewCmd.PersistentFlags().StringVarP(&NewTypeStr, \"type\", \"t\",\n\t\t\"pkg\", \"Type of package to create: pkg, bsp, sdk.  Default pkg.\")\n\n\tpkgCmd.AddCommand(newCmd)\n\n\tmoveCmdHelpText := \"\"\n\tmoveCmdHelpEx := \"\"\n\n\tmoveCmd := &cobra.Command{\n\t\tUse:     \"move\",\n\t\tShort:   \"Move a package from one location to another\",\n\t\tLong:    moveCmdHelpText,\n\t\tExample: moveCmdHelpEx,\n\t\tRun:     pkgMoveCmd,\n\t}\n\n\tpkgCmd.AddCommand(moveCmd)\n\n\tremoveCmdHelpText := \"\"\n\tremoveCmdHelpEx := \"\"\n\n\tremoveCmd := &cobra.Command{\n\t\tUse:     \"remove\",\n\t\tShort:   \"Remove a package\",\n\t\tLong:    removeCmdHelpText,\n\t\tExample: removeCmdHelpEx,\n\t\tRun:     pkgRemoveCmd,\n\t}\n\n\tpkgCmd.AddCommand(removeCmd)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\n<commit_msg>modified main<commit_after>package main\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\tpbd \"github.com\/brotherlogic\/discovery\/proto\"\n\tpb \"github.com\/brotherlogic\/gobuildmaster\/proto\"\n\t\"golang.org\/x\/net\/context\"\n\t\"google.golang.org\/grpc\/codes\"\n\t\"google.golang.org\/grpc\/status\"\n)\n\nfunc (s *Server) updateWorld(ctx context.Context, server *pbd.RegistryEntry) ([]string, error) {\n\tjobs, err := s.getter.getJobs(ctx, server)\n\tif err != nil {\n\t\treturn []string{}, err\n\t}\n\n\tslaveMap := []string{}\n\tfor _, job := range jobs {\n\t\tslaveMap = append(slaveMap, job.GetJob().GetName())\n\t}\n\n\treturn slaveMap, nil\n}\n\nfunc (s *Server) adjustWorld(ctx context.Context) error {\n\tslaves, err := s.getter.getSlaves()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar ourSlave *pbd.RegistryEntry\n\tfor _, slave := range slaves.GetServices() {\n\t\tif slave.Identifier == s.Registry.Identifier {\n\t\t\tourSlave = slave\n\t\t}\n\t}\n\tif ourSlave == nil {\n\t\treturn fmt.Errorf(\"Cannot locate local gbs from %v\", slaves)\n\t}\n\n\tif len(slaves.GetServices()) == 0 {\n\t\treturn fmt.Errorf(\"Unable to locate any slaves\")\n\t}\n\n\tjobCount := make(map[string]int)\n\tourjobs := make(map[string]bool)\n\tfor _, server := range slaves.GetServices() {\n\t\tslaves, err := s.updateWorld(ctx, server)\n\t\tif err != nil {\n\t\t\ts.Log(fmt.Sprintf(\"Unable to reach %v -> %v\", server, err))\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, j := range slaves {\n\t\t\tjobCount[j]++\n\t\t\tif server.Identifier == s.Registry.Identifier {\n\t\t\t\tourjobs[j] = true\n\t\t\t}\n\t\t}\n\t}\n\n\tlocalConfig, err := s.getter.getConfig(ctx, ourSlave)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, intent := range s.config.Nintents {\n\t\ttime.Sleep(time.Second * 2)\n\t\tif !ourjobs[intent.GetJob().GetName()] {\n\t\t\tallmatch := true\n\t\t\tfor _, req := range intent.GetJob().GetRequirements() {\n\t\t\t\tlocalmatch := false\n\t\t\t\tfor _, r := range localConfig {\n\t\t\t\t\tif r.Category == req.Category && r.Properties == req.Properties {\n\t\t\t\t\t\tlocalmatch = true\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif !localmatch {\n\t\t\t\t\tallmatch = false\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif allmatch {\n\t\t\t\terr := s.check(ctx, intent, jobCount, ourSlave)\n\t\t\t\ts.Log(fmt.Sprintf(\"Running %v -> %v\", intent.GetJob().GetName(), err))\n\t\t\t\tcode := status.Convert(err).Code()\n\t\t\t\tif code != codes.OK && code != codes.FailedPrecondition {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\ts.Log(fmt.Sprintf(\"Missing requirements for %v\", intent.GetJob().GetName()))\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (s *Server) check(ctx context.Context, i *pb.NIntent, counts map[string]int, ls *pbd.RegistryEntry) error {\n\terr := s.registerJob(ctx, i)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif i.Redundancy == pb.Redundancy_GLOBAL {\n\t\treturn s.runJob(ctx, i.GetJob(), ls)\n\t}\n\n\tif i.Redundancy == pb.Redundancy_REDUNDANT {\n\t\tif counts[i.GetJob().GetName()] < 3 {\n\t\t\treturn s.runJob(ctx, i.GetJob(), ls)\n\t\t}\n\t}\n\n\tif counts[i.GetJob().GetName()] < int(i.Count) {\n\t\treturn s.runJob(ctx, i.GetJob(), ls)\n\t}\n\n\treturn nil\n}\n<commit_msg>Simplify<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\tpbd \"github.com\/brotherlogic\/discovery\/proto\"\n\tpb \"github.com\/brotherlogic\/gobuildmaster\/proto\"\n\t\"golang.org\/x\/net\/context\"\n\t\"google.golang.org\/grpc\/codes\"\n\t\"google.golang.org\/grpc\/status\"\n)\n\nfunc (s *Server) updateWorld(ctx context.Context, server *pbd.RegistryEntry) ([]string, error) {\n\tjobs, err := s.getter.getJobs(ctx, server)\n\tif err != nil {\n\t\treturn []string{}, err\n\t}\n\n\tslaveMap := []string{}\n\tfor _, job := range jobs {\n\t\tslaveMap = append(slaveMap, job.GetJob().GetName())\n\t}\n\n\treturn slaveMap, nil\n}\n\nfunc (s *Server) adjustWorld(ctx context.Context) error {\n\tslaves, err := s.getter.getSlaves()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar ourSlave *pbd.RegistryEntry\n\tfor _, slave := range slaves.GetServices() {\n\t\tif slave.Identifier == s.Registry.Identifier {\n\t\t\tourSlave = slave\n\t\t}\n\t}\n\tif ourSlave == nil {\n\t\treturn fmt.Errorf(\"Cannot locate local gbs from %v\", slaves)\n\t}\n\n\tif len(slaves.GetServices()) == 0 {\n\t\treturn fmt.Errorf(\"Unable to locate any slaves\")\n\t}\n\n\tjobCount := make(map[string]int)\n\tourjobs := make(map[string]bool)\n\tfor _, server := range slaves.GetServices() {\n\t\tslaves, err := s.updateWorld(ctx, server)\n\t\tif err != nil {\n\t\t\ts.Log(fmt.Sprintf(\"Unable to reach %v -> %v\", server, err))\n\t\t\tcontinue\n\t\t}\n\n\t\tfor _, j := range slaves {\n\t\t\tjobCount[j]++\n\t\t\tif server.Identifier == s.Registry.Identifier {\n\t\t\t\tourjobs[j] = true\n\t\t\t}\n\t\t}\n\t}\n\n\tlocalConfig, err := s.getter.getConfig(ctx, ourSlave)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, intent := range s.config.Nintents {\n\t\ttime.Sleep(time.Second * 2)\n\t\tif !ourjobs[intent.GetJob().GetName()] {\n\t\t\tallmatch := true\n\t\t\tfor _, req := range intent.GetJob().GetRequirements() {\n\t\t\t\tlocalmatch := false\n\t\t\t\tfor _, r := range localConfig {\n\t\t\t\t\tif r.Category == req.Category && r.Properties == req.Properties {\n\t\t\t\t\t\tlocalmatch = true\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif !localmatch {\n\t\t\t\t\tallmatch = false\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif allmatch {\n\t\t\t\terr := s.check(ctx, intent, jobCount, ourSlave)\n\t\t\t\ts.Log(fmt.Sprintf(\"Running %v -> %v\", intent.GetJob().GetName(), err))\n\t\t\t\tcode := status.Convert(err).Code()\n\t\t\t\tif code != codes.OK && code != codes.FailedPrecondition {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\ts.Log(fmt.Sprintf(\"Missing requirements for %v\", intent.GetJob().GetName()))\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (s *Server) check(ctx context.Context, i *pb.NIntent, counts map[string]int, ls *pbd.RegistryEntry) error {\n\terr := s.registerJob(ctx, i)\n\tcode := status.Convert(err).Code()\n\tif code != codes.OK && code != codes.NotFound {\n\t\treturn err\n\t}\n\n\tif i.Redundancy == pb.Redundancy_GLOBAL {\n\t\treturn s.runJob(ctx, i.GetJob(), ls)\n\t}\n\n\tif i.Redundancy == pb.Redundancy_REDUNDANT {\n\t\tif counts[i.GetJob().GetName()] < 3 {\n\t\t\treturn s.runJob(ctx, i.GetJob(), ls)\n\t\t}\n\t}\n\n\tif counts[i.GetJob().GetName()] < int(i.Count) {\n\t\treturn s.runJob(ctx, i.GetJob(), ls)\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2019 The Jetstack cert-manager contributors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage flags\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\tflag \"github.com\/spf13\/pflag\"\n\t\"os\/exec\"\n\n\tlogf \"github.com\/jetstack\/cert-manager\/hack\/release\/pkg\/log\"\n\t\"github.com\/jetstack\/cert-manager\/hack\/release\/pkg\/util\"\n)\n\nvar (\n\tDefault = &Global{}\n\n\tlog = logf.Log.WithName(\"global\")\n)\n\ntype Global struct {\n\t\/\/ Path to the root of the cert-manager repository\n\tRepoRoot string\n\n\t\/\/ DockerRepo is the docker repository used to store release images\n\tDockerRepo string\n\n\t\/\/ UpstreamRepoURL is the URL of the git repo used to check for tags\n\tUpstreamRepoURL string\n\n\t\/\/ AppVersion is the version tag to use for this release\n\tAppVersion string\n\n\t\/\/ GitState contains the state of the git working tree.\n\tGitState string\n\n\t\/\/ GitCommitRef is the current git commit hash being built\n\tGitCommitRef string\n\n\tGitPath string\n\n\t\/\/ Path to the cert-manager Helm chart.\n\t\/\/ This is defined as a global as the manifests plugin also needs\n\t\/\/ access to this flag\n\tChartPath string\n}\n\nconst defaultDockerRepo = \"quay.io\/jetstack\"\n\nfunc (g *Global) AddFlags(fs *flag.FlagSet) {\n\tfs.StringVar(&g.RepoRoot, \"repo-root\", \"\", \"path to the root of the cert-manager repository\")\n\tfs.StringVar(&g.DockerRepo, \"docker-repo\", defaultDockerRepo, \"the docker repository that images will be tagged with\")\n\tfs.StringVar(&g.AppVersion, \"app-version\", \"\", \"app version to use when building and generating manifests. Defaults to 'git describe --tags --abbrev=0 --exact-match'\")\n\tfs.StringVar(&g.UpstreamRepoURL, \"git.upstream-repo-url\", \"https:\/\/github.com\/jetstack\/cert-manager.git\", \"the URL of the git repo used to check for tags when generating --app-version\")\n\tfs.StringVar(&g.GitState, \"git.state\", \"\", \"the state of the git working tree. if set and not 'clean', this will be appended to the app-version during builds\")\n\tfs.StringVar(&g.GitCommitRef, \"git.commit-ref\", \"\", \"the git commit ref of this build. Defaults to 'git rev-parse --short HEAD'\")\n\tfs.StringVar(&g.GitPath, \"git.path\", \"git\", \"path to the git binary to use\")\n\tfs.StringVar(&g.ChartPath, \"chart.path\", \"deploy\/charts\/cert-manager\", \"the path to the cert-manager helm chart, relative to the repo root\")\n}\n\nfunc (g *Global) Validate() []error {\n\tvar errs []error\n\n\tif g.UpstreamRepoURL == \"\" {\n\t\terrs = append(errs, fmt.Errorf(\"--git.upstream-repo-url must be specified\"))\n\t}\n\n\treturn errs\n}\n\nfunc (g *Global) Complete() error {\n\tlog = log.WithName(\"default-flags\")\n\n\tif g.DockerRepo == \"\" {\n\t\tlog := log.WithValues(\"flag\", \"docker-repo\")\n\t\tg.DockerRepo = defaultDockerRepo\n\t\tlog.Info(\"set default value\", \"value\", g.DockerRepo)\n\t}\n\n\tif g.RepoRoot == \"\" {\n\t\tlog := log.WithValues(\"flag\", \"repo-root\")\n\t\tif bwd := os.Getenv(\"BUILD_WORKSPACE_DIRECTORY\"); bwd != \"\" {\n\t\t\tg.RepoRoot = bwd\n\t\t} else {\n\t\t\tdir, err := os.Getwd()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error determining repo root: %v\", err)\n\t\t\t}\n\t\t\tg.RepoRoot = dir\n\t\t}\n\n\t\tlog.Info(\"set default value\", \"value\", g.RepoRoot)\n\t}\n\n\tif g.AppVersion == \"\" {\n\t\tlog := log.WithValues(\"flag\", \"app-version\")\n\n\t\tlog.V(logf.LogLevelDebug).Info(\"fetching upstream git repo tags\")\n\t\t_, err := g.gitOutput(\"fetch\", \"--tags\")\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error fetching tags: %v\", err)\n\t\t}\n\n\t\tlog.V(logf.LogLevelDebug).Info(\"finding tags that match the current commit ref\")\n\t\tg.AppVersion, err = g.gitOutput(\"describe\", \"--tags\", \"--abbrev=0\", \"--exact-match\")\n\t\tif err != nil {\n\t\t\tlog.Error(err, \"failed to determine tag for current git ref\/HEAD\")\n\t\t\tg.AppVersion = \"\"\n\t\t}\n\n\t\tif g.AppVersion == \"\" {\n\t\t\t\/\/ default to 'canary' if no tags point to the current ref\n\t\t\tg.AppVersion = \"canary\"\n\t\t}\n\n\t\tlog.WithValues(\"value\", g.AppVersion).Info(\"set default value\")\n\t}\n\n\tif g.GitCommitRef == \"\" {\n\t\tlog := log.WithValues(\"flag\", \"git.commit-ref\")\n\n\t\tlog.V(logf.LogLevelDebug).Info(\"parsing current git commit ref\")\n\t\tvar err error\n\t\tg.GitCommitRef, err = g.gitOutput(\"rev-parse\", \"--short\", \"HEAD\")\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error getting current commit ref: %v\", err)\n\t\t}\n\n\t\tlog.WithValues(\"value\", g.GitCommitRef).Info(\"set default value\")\n\t}\n\n\tif g.GitState == \"\" {\n\t\tlog := log.WithValues(\"flag\", \"git.commit-state\")\n\n\t\tlog.V(logf.LogLevelDebug).Info(\"evaluating current git working tree dirty status\")\n\t\tchanges, err := g.gitOutput(\"status\", \"--porcelain\")\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error checking git status: %v\", err)\n\t\t}\n\n\t\tif len(changes) == 0 {\n\t\t\tg.GitState = \"clean\"\n\t\t} else {\n\t\t\tg.GitState = \"dirty\"\n\t\t}\n\n\t\tlog.WithValues(\"value\", g.GitState).Info(\"set default value\")\n\t}\n\n\treturn nil\n}\n\nfunc (g *Global) gitOutput(args ...string) (string, error) {\n\tcmd := exec.Command(g.GitPath, args...)\n\tb, err := util.RunPrintCombined(log, cmd)\n\treturn strings.TrimSpace(string(b)), err\n}\n<commit_msg>Chdir to repo root<commit_after>\/*\nCopyright 2019 The Jetstack cert-manager contributors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage flags\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\tflag \"github.com\/spf13\/pflag\"\n\t\"os\/exec\"\n\n\tlogf \"github.com\/jetstack\/cert-manager\/hack\/release\/pkg\/log\"\n\t\"github.com\/jetstack\/cert-manager\/hack\/release\/pkg\/util\"\n)\n\nvar (\n\tDefault = &Global{}\n\n\tlog = logf.Log.WithName(\"global\")\n)\n\ntype Global struct {\n\t\/\/ Path to the root of the cert-manager repository\n\tRepoRoot string\n\n\t\/\/ DockerRepo is the docker repository used to store release images\n\tDockerRepo string\n\n\t\/\/ UpstreamRepoURL is the URL of the git repo used to check for tags\n\tUpstreamRepoURL string\n\n\t\/\/ AppVersion is the version tag to use for this release\n\tAppVersion string\n\n\t\/\/ GitState contains the state of the git working tree.\n\tGitState string\n\n\t\/\/ GitCommitRef is the current git commit hash being built\n\tGitCommitRef string\n\n\tGitPath string\n\n\t\/\/ Path to the cert-manager Helm chart.\n\t\/\/ This is defined as a global as the manifests plugin also needs\n\t\/\/ access to this flag\n\tChartPath string\n}\n\nconst defaultDockerRepo = \"quay.io\/jetstack\"\n\nfunc (g *Global) AddFlags(fs *flag.FlagSet) {\n\tfs.StringVar(&g.RepoRoot, \"repo-root\", \"\", \"path to the root of the cert-manager repository\")\n\tfs.StringVar(&g.DockerRepo, \"docker-repo\", defaultDockerRepo, \"the docker repository that images will be tagged with\")\n\tfs.StringVar(&g.AppVersion, \"app-version\", \"\", \"app version to use when building and generating manifests. Defaults to 'git describe --tags --abbrev=0 --exact-match'\")\n\tfs.StringVar(&g.UpstreamRepoURL, \"git.upstream-repo-url\", \"https:\/\/github.com\/jetstack\/cert-manager.git\", \"the URL of the git repo used to check for tags when generating --app-version\")\n\tfs.StringVar(&g.GitState, \"git.state\", \"\", \"the state of the git working tree. if set and not 'clean', this will be appended to the app-version during builds\")\n\tfs.StringVar(&g.GitCommitRef, \"git.commit-ref\", \"\", \"the git commit ref of this build. Defaults to 'git rev-parse --short HEAD'\")\n\tfs.StringVar(&g.GitPath, \"git.path\", \"git\", \"path to the git binary to use\")\n\tfs.StringVar(&g.ChartPath, \"chart.path\", \"deploy\/charts\/cert-manager\", \"the path to the cert-manager helm chart, relative to the repo root\")\n}\n\nfunc (g *Global) Validate() []error {\n\tvar errs []error\n\n\tif g.UpstreamRepoURL == \"\" {\n\t\terrs = append(errs, fmt.Errorf(\"--git.upstream-repo-url must be specified\"))\n\t}\n\n\treturn errs\n}\n\nfunc (g *Global) Complete() error {\n\tlog = log.WithName(\"default-flags\")\n\n\tif g.DockerRepo == \"\" {\n\t\tlog := log.WithValues(\"flag\", \"docker-repo\")\n\t\tg.DockerRepo = defaultDockerRepo\n\t\tlog.Info(\"set default value\", \"value\", g.DockerRepo)\n\t}\n\n\tif g.RepoRoot == \"\" {\n\t\tlog := log.WithValues(\"flag\", \"repo-root\")\n\t\tif bwd := os.Getenv(\"BUILD_WORKSPACE_DIRECTORY\"); bwd != \"\" {\n\t\t\tg.RepoRoot = bwd\n\t\t} else {\n\t\t\tdir, err := os.Getwd()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"error determining repo root: %v\", err)\n\t\t\t}\n\t\t\tg.RepoRoot = dir\n\t\t}\n\n\t\tlog.Info(\"set default value\", \"value\", g.RepoRoot)\n\t}\n\tif err := os.Chdir(g.RepoRoot); err != nil {\n\t\treturn fmt.Errorf(\"error changing directory to --repo-root=%q: %v\", g.RepoRoot, err)\n\t}\n\n\tif g.AppVersion == \"\" {\n\t\tlog := log.WithValues(\"flag\", \"app-version\")\n\n\t\tlog.V(logf.LogLevelDebug).Info(\"fetching upstream git repo tags\")\n\t\t_, err := g.gitOutput(\"fetch\", \"--tags\")\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error fetching tags: %v\", err)\n\t\t}\n\n\t\tlog.V(logf.LogLevelDebug).Info(\"finding tags that match the current commit ref\")\n\t\tg.AppVersion, err = g.gitOutput(\"describe\", \"--tags\", \"--abbrev=0\", \"--exact-match\")\n\t\tif err != nil {\n\t\t\tlog.Error(err, \"failed to determine tag for current git ref\/HEAD\")\n\t\t\tg.AppVersion = \"\"\n\t\t}\n\n\t\tif g.AppVersion == \"\" {\n\t\t\t\/\/ default to 'canary' if no tags point to the current ref\n\t\t\tg.AppVersion = \"canary\"\n\t\t}\n\n\t\tlog.WithValues(\"value\", g.AppVersion).Info(\"set default value\")\n\t}\n\n\tif g.GitCommitRef == \"\" {\n\t\tlog := log.WithValues(\"flag\", \"git.commit-ref\")\n\n\t\tlog.V(logf.LogLevelDebug).Info(\"parsing current git commit ref\")\n\t\tvar err error\n\t\tg.GitCommitRef, err = g.gitOutput(\"rev-parse\", \"--short\", \"HEAD\")\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error getting current commit ref: %v\", err)\n\t\t}\n\n\t\tlog.WithValues(\"value\", g.GitCommitRef).Info(\"set default value\")\n\t}\n\n\tif g.GitState == \"\" {\n\t\tlog := log.WithValues(\"flag\", \"git.commit-state\")\n\n\t\tlog.V(logf.LogLevelDebug).Info(\"evaluating current git working tree dirty status\")\n\t\tchanges, err := g.gitOutput(\"status\", \"--porcelain\")\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error checking git status: %v\", err)\n\t\t}\n\n\t\tif len(changes) == 0 {\n\t\t\tg.GitState = \"clean\"\n\t\t} else {\n\t\t\tg.GitState = \"dirty\"\n\t\t}\n\n\t\tlog.WithValues(\"value\", g.GitState).Info(\"set default value\")\n\t}\n\n\treturn nil\n}\n\nfunc (g *Global) gitOutput(args ...string) (string, error) {\n\tcmd := exec.Command(g.GitPath, args...)\n\tb, err := util.RunPrintCombined(log, cmd)\n\treturn strings.TrimSpace(string(b)), err\n}\n<|endoftext|>"}
{"text":"<commit_before>package cmap\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"sync\"\n)\n\nconst defaultShardCount = 32\n\nconst bufferSize = 64\n\n\/\/ A \"thread\" safe map of type uint16:Anything.\n\/\/ To avoid lock bottlenecks this map is dived to several (shardCount) map shards.\ntype ConcurrentMap struct {\n\tshards []*ConcurrentMapShared\n\tcount  int\n}\n\n\/\/ A \"thread\" safe uint16 to anything map.\ntype ConcurrentMapShared struct {\n\titems map[uint16]interface{}\n\tmux   *sync.RWMutex\n}\n\n\/\/ Creates a new concurrent map.\nfunc New(shardCount int) (*ConcurrentMap, error) {\n\tif shardCount < 1 {\n\t\treturn nil, errors.New(\"invalid shard count: less than 1\")\n\t}\n\n\tshards := make([]*ConcurrentMapShared, shardCount)\n\n\tfor i := 0; i < shardCount; i++ {\n\t\tshards[i] = &ConcurrentMapShared{\n\t\t\titems: make(map[uint16]interface{}),\n\t\t\tmux:   &sync.RWMutex{},\n\t\t}\n\t}\n\n\treturn &ConcurrentMap{\n\t\tshards: shards,\n\t\tcount:  shardCount,\n\t}, nil\n}\n\nfunc NewDefault() *ConcurrentMap {\n\tm, err := New(defaultShardCount)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn m\n}\n\n\/\/ Returns shard under given key\nfunc (m *ConcurrentMap) getShard(key uint16) *ConcurrentMapShared {\n\treturn m.shards[m.getShardIndex(key)]\n}\n\nfunc (m *ConcurrentMap) getShardIndex(key uint16) uint16 {\n\treturn key % uint16(m.count)\n}\n\nfunc (m *ConcurrentMap) sortShardsTuples(data map[uint16]interface{}) map[uint16][]Tuple {\n\tshardsTuples := map[uint16][]Tuple{}\n\n\tfor key, value := range data {\n\t\tshardIndex := m.getShardIndex(key)\n\n\t\tif shardTuples, ok := shardsTuples[shardIndex]; ok {\n\t\t\tshardsTuples[shardIndex] = append(shardTuples, Tuple{\n\t\t\t\tKey: key,\n\t\t\t\tVal: value,\n\t\t\t})\n\t\t} else {\n\t\t\tshardsTuples[shardIndex] = make([]Tuple, 0, bufferSize)\n\t\t\tshardsTuples[shardIndex] = append(shardsTuples[shardIndex], Tuple{\n\t\t\t\tKey: key,\n\t\t\t\tVal: value,\n\t\t\t})\n\t\t}\n\t}\n\n\treturn shardsTuples\n}\n\nfunc (m *ConcurrentMap) sortShardsKeys(keys []uint16) map[uint16][]uint16 {\n\tshardsKeys := map[uint16][]uint16{}\n\n\tfor _, key := range keys {\n\t\tshardIndex := m.getShardIndex(key)\n\n\t\tif shardTuples, ok := shardsKeys[shardIndex]; ok {\n\t\t\tshardsKeys[shardIndex] = append(shardTuples, key)\n\t\t} else {\n\t\t\tshardsKeys[shardIndex] = make([]uint16, 0, bufferSize)\n\t\t\tshardsKeys[shardIndex] = append(shardsKeys[shardIndex], key)\n\t\t}\n\t}\n\n\treturn shardsKeys\n}\n\nfunc (m *ConcurrentMap) MSet(data map[uint16]interface{}) {\n\tshardsTuples := m.sortShardsTuples(data)\n\n\tfor shardIndex, tuples := range shardsTuples {\n\t\tshard := m.shards[shardIndex]\n\t\tshard.mux.Lock()\n\t\tfor _, tuple := range tuples {\n\t\t\tshard.items[tuple.Key] = tuple.Val\n\t\t}\n\t\tshard.mux.Unlock()\n\t}\n}\n\nfunc (m *ConcurrentMap) MSetIfAbsent(data map[uint16]interface{}) bool {\n\tshardsTuples := m.sortShardsTuples(data)\n\trollbackKeys := make([]uint16, 0, bufferSize)\n\n\tfor shardIndex, tuples := range shardsTuples {\n\t\tshard := m.shards[shardIndex]\n\t\tshard.mux.Lock()\n\t\tfor _, tuple := range tuples {\n\t\t\tif _, ok := shard.items[tuple.Key]; !ok {\n\t\t\t\tshard.items[tuple.Key] = tuple.Val\n\t\t\t\trollbackKeys = append(rollbackKeys, tuple.Key)\n\t\t\t} else {\n\t\t\t\tshard.mux.Unlock()\n\n\t\t\t\t\/\/ Rollback\n\t\t\t\tm.MRemove(rollbackKeys)\n\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\tshard.mux.Unlock()\n\t}\n\n\treturn true\n}\n\n\/\/ Sets the given value under the specified key.\nfunc (m *ConcurrentMap) Set(key uint16, value interface{}) {\n\t\/\/ Get map shard.\n\tshard := m.getShard(key)\n\tshard.mux.Lock()\n\tshard.items[key] = value\n\tshard.mux.Unlock()\n}\n\n\/\/ Callback to return new element to be inserted into the map\n\/\/ It is called while lock is held, therefore it MUST NOT\n\/\/ try to access other keys in same map, as it can lead to deadlock since\n\/\/ Go sync.RWLock is not reentrant\ntype UpsertCb func(exist bool, valueInMap interface{}, newValue interface{}) interface{}\n\n\/\/ Insert or Update - updates existing element or inserts a new one using UpsertCb\nfunc (m *ConcurrentMap) Upsert(key uint16, value interface{}, cb UpsertCb) (res interface{}) {\n\tshard := m.getShard(key)\n\tshard.mux.Lock()\n\tv, ok := shard.items[key]\n\tres = cb(ok, v, value)\n\tshard.items[key] = res\n\tshard.mux.Unlock()\n\treturn res\n}\n\n\/\/ Sets the given value under the specified key if no value was associated with it.\nfunc (m *ConcurrentMap) SetIfAbsent(key uint16, value interface{}) bool {\n\t\/\/ Get map shard.\n\tshard := m.getShard(key)\n\tshard.mux.Lock()\n\t_, ok := shard.items[key]\n\tif !ok {\n\t\tshard.items[key] = value\n\t}\n\tshard.mux.Unlock()\n\treturn !ok\n}\n\n\/\/ Retrieves an element from map under given key.\nfunc (m *ConcurrentMap) Get(key uint16) (interface{}, bool) {\n\t\/\/ Get shard\n\tshard := m.getShard(key)\n\tshard.mux.RLock()\n\t\/\/ Get item from shard.\n\tval, ok := shard.items[key]\n\tshard.mux.RUnlock()\n\treturn val, ok\n}\n\n\/\/ Returns the number of elements within the map.\nfunc (m *ConcurrentMap) Count() int {\n\tcount := 0\n\tfor i := 0; i < m.count; i++ {\n\t\tshard := m.shards[i]\n\t\tshard.mux.RLock()\n\t\tcount += len(shard.items)\n\t\tshard.mux.RUnlock()\n\t}\n\treturn count\n}\n\n\/\/ Looks up an item under specified key\nfunc (m *ConcurrentMap) Has(key uint16) bool {\n\t\/\/ Get shard\n\tshard := m.getShard(key)\n\tshard.mux.RLock()\n\t\/\/ See if element is within shard.\n\t_, ok := shard.items[key]\n\tshard.mux.RUnlock()\n\treturn ok\n}\n\n\/\/ Removes an element from the map.\nfunc (m *ConcurrentMap) Remove(key uint16) {\n\t\/\/ Try to get shard.\n\tshard := m.getShard(key)\n\tshard.mux.Lock()\n\tdelete(shard.items, key)\n\tshard.mux.Unlock()\n}\n\nfunc (m *ConcurrentMap) MRemove(keys []uint16) {\n\tshardsKeys := m.sortShardsKeys(keys)\n\n\tfor shardIndex, keys := range shardsKeys {\n\t\tshard := m.shards[shardIndex]\n\t\tshard.mux.Lock()\n\t\tfor _, key := range keys {\n\t\t\tdelete(shard.items, key)\n\t\t}\n\t\tshard.mux.Unlock()\n\t}\n}\n\n\/\/ RemoveCb is a callback executed in a map.RemoveCb() call, while Lock is held\n\/\/ If returns true, the element will be removed from the map\ntype RemoveCb func(key uint16, v interface{}, exists bool) bool\n\n\/\/ RemoveCb locks the shard containing the key, retrieves its current value and calls the callback with those params\n\/\/ If callback returns true and element exists, it will remove it from the map\n\/\/ Returns the value returned by the callback (even if element was not present in the map)\nfunc (m *ConcurrentMap) RemoveCb(key uint16, cb RemoveCb) bool {\n\t\/\/ Try to get shard.\n\tshard := m.getShard(key)\n\tshard.mux.Lock()\n\tv, ok := shard.items[key]\n\tremove := cb(key, v, ok)\n\tif remove && ok {\n\t\tdelete(shard.items, key)\n\t}\n\tshard.mux.Unlock()\n\treturn remove\n}\n\n\/\/ Removes an element from the map and returns it\nfunc (m *ConcurrentMap) Pop(key uint16) (v interface{}, exists bool) {\n\t\/\/ Try to get shard.\n\tshard := m.getShard(key)\n\tshard.mux.Lock()\n\tv, exists = shard.items[key]\n\tdelete(shard.items, key)\n\tshard.mux.Unlock()\n\treturn v, exists\n}\n\n\/\/ Checks if map is empty.\nfunc (m *ConcurrentMap) IsEmpty() bool {\n\treturn m.Count() == 0\n}\n\n\/\/ Used by the Iter & IterBuffered functions to wrap two variables together over a channel,\ntype Tuple struct {\n\tKey uint16\n\tVal interface{}\n}\n\n\/\/ Returns an iterator which could be used in a for range loop.\n\/\/\n\/\/ Deprecated: using IterBuffered() will get a better performence\nfunc (m *ConcurrentMap) Iter() <-chan Tuple {\n\tchans := snapshot(m)\n\tch := make(chan Tuple)\n\tgo fanIn(chans, ch)\n\treturn ch\n}\n\n\/\/ Returns a buffered iterator which could be used in a for range loop.\nfunc (m *ConcurrentMap) IterBuffered() <-chan Tuple {\n\tchans := snapshot(m)\n\ttotal := 0\n\tfor _, c := range chans {\n\t\ttotal += cap(c)\n\t}\n\tch := make(chan Tuple, total)\n\tgo fanIn(chans, ch)\n\treturn ch\n}\n\n\/\/ Returns a array of channels that contains elements in each shard,\n\/\/ which likely takes a snapshot of `m`.\n\/\/ It returns once the size of each buffered channel is determined,\n\/\/ before all the channels are populated using goroutines.\nfunc snapshot(m *ConcurrentMap) (chans []chan Tuple) {\n\tchans = make([]chan Tuple, m.count)\n\twg := sync.WaitGroup{}\n\twg.Add(m.count)\n\t\/\/ Foreach shard.\n\tfor index, shard := range m.shards {\n\t\tgo func(index int, shard *ConcurrentMapShared) {\n\t\t\t\/\/ Foreach key, value pair.\n\t\t\tshard.mux.RLock()\n\t\t\tchans[index] = make(chan Tuple, len(shard.items))\n\t\t\twg.Done()\n\t\t\tfor key, val := range shard.items {\n\t\t\t\tchans[index] <- Tuple{key, val}\n\t\t\t}\n\t\t\tshard.mux.RUnlock()\n\t\t\tclose(chans[index])\n\t\t}(index, shard)\n\t}\n\twg.Wait()\n\treturn chans\n}\n\n\/\/ fanIn reads elements from channels `chans` into channel `out`\nfunc fanIn(chans []chan Tuple, out chan Tuple) {\n\twg := sync.WaitGroup{}\n\twg.Add(len(chans))\n\tfor _, ch := range chans {\n\t\tgo func(ch chan Tuple) {\n\t\t\tfor t := range ch {\n\t\t\t\tout <- t\n\t\t\t}\n\t\t\twg.Done()\n\t\t}(ch)\n\t}\n\twg.Wait()\n\tclose(out)\n}\n\n\/\/ Returns all items as map[uint16]interface{}\nfunc (m *ConcurrentMap) Items() map[uint16]interface{} {\n\ttmp := make(map[uint16]interface{})\n\n\t\/\/ Insert items to temporary map.\n\tfor item := range m.IterBuffered() {\n\t\ttmp[item.Key] = item.Val\n\t}\n\n\treturn tmp\n}\n\n\/\/ Iterator callback,called for every key,value found in\n\/\/ maps. RLock is held for all calls for a given shard\n\/\/ therefore callback sess consistent view of a shard,\n\/\/ but not across the shards\ntype IterCb func(key uint16, v interface{})\n\n\/\/ Callback based iterator, cheapest way to read\n\/\/ all elements in a map.\nfunc (m *ConcurrentMap) IterCb(fn IterCb) {\n\tfor idx := range m.shards {\n\t\tshard := m.shards[idx]\n\t\tshard.mux.RLock()\n\t\tfor key, value := range shard.items {\n\t\t\tfn(key, value)\n\t\t}\n\t\tshard.mux.RUnlock()\n\t}\n}\n\n\/\/ Return all keys as []uint16\nfunc (m *ConcurrentMap) Keys() []uint16 {\n\tcount := m.Count()\n\tch := make(chan uint16, count)\n\tgo func() {\n\t\t\/\/ Foreach shard.\n\t\twg := sync.WaitGroup{}\n\t\twg.Add(m.count)\n\t\tfor _, shard := range m.shards {\n\t\t\tgo func(shard *ConcurrentMapShared) {\n\t\t\t\t\/\/ Foreach key, value pair.\n\t\t\t\tshard.mux.RLock()\n\t\t\t\tfor key := range shard.items {\n\t\t\t\t\tch <- key\n\t\t\t\t}\n\t\t\t\tshard.mux.RUnlock()\n\t\t\t\twg.Done()\n\t\t\t}(shard)\n\t\t}\n\t\twg.Wait()\n\t\tclose(ch)\n\t}()\n\n\t\/\/ Generate keys\n\tkeys := make([]uint16, 0, count)\n\tfor k := range ch {\n\t\tkeys = append(keys, k)\n\t}\n\treturn keys\n}\n\n\/\/Reviles ConcurrentMap \"private\" variables to json marshal.\nfunc (m *ConcurrentMap) MarshalJSON() ([]byte, error) {\n\t\/\/ Create a temporary map, which will hold all item spread across shards.\n\ttmp := make(map[uint16]interface{})\n\n\t\/\/ Insert items to temporary map.\n\tfor item := range m.IterBuffered() {\n\t\ttmp[item.Key] = item.Val\n\t}\n\treturn json.Marshal(tmp)\n}\n\n\/\/ Concurrent map uses Interface{} as its value, therefor JSON Unmarshal\n\/\/ will probably won't know which to type to unmarshal into, in such case\n\/\/ we'll end up with a value of type map[uint16]interface{}, In most cases this isn't\n\/\/ out value type, this is why we've decided to remove this functionality.\n\n\/\/ func (m *ConcurrentMap) UnmarshalJSON(b []byte) (err error) {\n\/\/ \t\/\/ Reverse process of Marshal.\n\n\/\/ \ttmp := make(map[uint16]interface{})\n\n\/\/ \t\/\/ Unmarshal into a single map.\n\/\/ \tif err := json.Unmarshal(b, &tmp); err != nil {\n\/\/ \t\treturn nil\n\/\/ \t}\n\n\/\/ \t\/\/ foreach key,value pair in temporary map insert into our concurrent map.\n\/\/ \tfor key, val := range tmp {\n\/\/ \t\tm.Set(key, val)\n\/\/ \t}\n\/\/ \treturn nil\n\/\/ }\n<commit_msg>CMap: Fix shard sorting methods<commit_after>package cmap\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"sync\"\n)\n\nconst defaultShardCount = 32\n\nconst bufferSize = 64\n\n\/\/ A \"thread\" safe map of type uint16:Anything.\n\/\/ To avoid lock bottlenecks this map is dived to several (shardCount) map shards.\ntype ConcurrentMap struct {\n\tshards []*ConcurrentMapShared\n\tcount  int\n}\n\n\/\/ A \"thread\" safe uint16 to anything map.\ntype ConcurrentMapShared struct {\n\titems map[uint16]interface{}\n\tmux   *sync.RWMutex\n}\n\n\/\/ Creates a new concurrent map.\nfunc New(shardCount int) (*ConcurrentMap, error) {\n\tif shardCount < 1 {\n\t\treturn nil, errors.New(\"invalid shard count: less than 1\")\n\t}\n\n\tshards := make([]*ConcurrentMapShared, shardCount)\n\n\tfor i := 0; i < shardCount; i++ {\n\t\tshards[i] = &ConcurrentMapShared{\n\t\t\titems: make(map[uint16]interface{}),\n\t\t\tmux:   &sync.RWMutex{},\n\t\t}\n\t}\n\n\treturn &ConcurrentMap{\n\t\tshards: shards,\n\t\tcount:  shardCount,\n\t}, nil\n}\n\nfunc NewDefault() *ConcurrentMap {\n\tm, err := New(defaultShardCount)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn m\n}\n\n\/\/ Returns shard under given key\nfunc (m *ConcurrentMap) getShard(key uint16) *ConcurrentMapShared {\n\treturn m.shards[m.getShardIndex(key)]\n}\n\nfunc (m *ConcurrentMap) getShardIndex(key uint16) uint16 {\n\treturn key % uint16(m.count)\n}\n\nfunc (m *ConcurrentMap) sortShardsTuples(data map[uint16]interface{}) map[uint16][]Tuple {\n\tshardsTuples := map[uint16][]Tuple{}\n\n\tfor key, value := range data {\n\t\tshardIndex := m.getShardIndex(key)\n\n\t\tif _, ok := shardsTuples[shardIndex]; !ok {\n\t\t\tshardsTuples[shardIndex] = make([]Tuple, 0, bufferSize)\n\t\t}\n\n\t\tshardsTuples[shardIndex] = append(shardsTuples[shardIndex], Tuple{\n\t\t\tKey: key,\n\t\t\tVal: value,\n\t\t})\n\t}\n\n\treturn shardsTuples\n}\n\nfunc (m *ConcurrentMap) sortShardsKeys(keys []uint16) map[uint16][]uint16 {\n\tshardsKeys := map[uint16][]uint16{}\n\n\tfor _, key := range keys {\n\t\tshardIndex := m.getShardIndex(key)\n\n\t\tif _, ok := shardsKeys[shardIndex]; !ok {\n\t\t\tshardsKeys[shardIndex] = make([]uint16, 0, bufferSize)\n\t\t}\n\n\t\tshardsKeys[shardIndex] = append(shardsKeys[shardIndex], key)\n\t}\n\n\treturn shardsKeys\n}\n\nfunc (m *ConcurrentMap) MSet(data map[uint16]interface{}) {\n\tshardsTuples := m.sortShardsTuples(data)\n\n\tfor shardIndex, tuples := range shardsTuples {\n\t\tshard := m.shards[shardIndex]\n\t\tshard.mux.Lock()\n\t\tfor _, tuple := range tuples {\n\t\t\tshard.items[tuple.Key] = tuple.Val\n\t\t}\n\t\tshard.mux.Unlock()\n\t}\n}\n\nfunc (m *ConcurrentMap) MSetIfAbsent(data map[uint16]interface{}) bool {\n\tshardsTuples := m.sortShardsTuples(data)\n\trollbackKeys := make([]uint16, 0, bufferSize)\n\n\tfor shardIndex, tuples := range shardsTuples {\n\t\tshard := m.shards[shardIndex]\n\t\tshard.mux.Lock()\n\t\tfor _, tuple := range tuples {\n\t\t\tif _, ok := shard.items[tuple.Key]; !ok {\n\t\t\t\tshard.items[tuple.Key] = tuple.Val\n\t\t\t\trollbackKeys = append(rollbackKeys, tuple.Key)\n\t\t\t} else {\n\t\t\t\tshard.mux.Unlock()\n\n\t\t\t\t\/\/ Rollback\n\t\t\t\tm.MRemove(rollbackKeys)\n\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\tshard.mux.Unlock()\n\t}\n\n\treturn true\n}\n\n\/\/ Sets the given value under the specified key.\nfunc (m *ConcurrentMap) Set(key uint16, value interface{}) {\n\t\/\/ Get map shard.\n\tshard := m.getShard(key)\n\tshard.mux.Lock()\n\tshard.items[key] = value\n\tshard.mux.Unlock()\n}\n\n\/\/ Callback to return new element to be inserted into the map\n\/\/ It is called while lock is held, therefore it MUST NOT\n\/\/ try to access other keys in same map, as it can lead to deadlock since\n\/\/ Go sync.RWLock is not reentrant\ntype UpsertCb func(exist bool, valueInMap interface{}, newValue interface{}) interface{}\n\n\/\/ Insert or Update - updates existing element or inserts a new one using UpsertCb\nfunc (m *ConcurrentMap) Upsert(key uint16, value interface{}, cb UpsertCb) (res interface{}) {\n\tshard := m.getShard(key)\n\tshard.mux.Lock()\n\tv, ok := shard.items[key]\n\tres = cb(ok, v, value)\n\tshard.items[key] = res\n\tshard.mux.Unlock()\n\treturn res\n}\n\n\/\/ Sets the given value under the specified key if no value was associated with it.\nfunc (m *ConcurrentMap) SetIfAbsent(key uint16, value interface{}) bool {\n\t\/\/ Get map shard.\n\tshard := m.getShard(key)\n\tshard.mux.Lock()\n\t_, ok := shard.items[key]\n\tif !ok {\n\t\tshard.items[key] = value\n\t}\n\tshard.mux.Unlock()\n\treturn !ok\n}\n\n\/\/ Retrieves an element from map under given key.\nfunc (m *ConcurrentMap) Get(key uint16) (interface{}, bool) {\n\t\/\/ Get shard\n\tshard := m.getShard(key)\n\tshard.mux.RLock()\n\t\/\/ Get item from shard.\n\tval, ok := shard.items[key]\n\tshard.mux.RUnlock()\n\treturn val, ok\n}\n\n\/\/ Returns the number of elements within the map.\nfunc (m *ConcurrentMap) Count() int {\n\tcount := 0\n\tfor i := 0; i < m.count; i++ {\n\t\tshard := m.shards[i]\n\t\tshard.mux.RLock()\n\t\tcount += len(shard.items)\n\t\tshard.mux.RUnlock()\n\t}\n\treturn count\n}\n\n\/\/ Looks up an item under specified key\nfunc (m *ConcurrentMap) Has(key uint16) bool {\n\t\/\/ Get shard\n\tshard := m.getShard(key)\n\tshard.mux.RLock()\n\t\/\/ See if element is within shard.\n\t_, ok := shard.items[key]\n\tshard.mux.RUnlock()\n\treturn ok\n}\n\n\/\/ Removes an element from the map.\nfunc (m *ConcurrentMap) Remove(key uint16) {\n\t\/\/ Try to get shard.\n\tshard := m.getShard(key)\n\tshard.mux.Lock()\n\tdelete(shard.items, key)\n\tshard.mux.Unlock()\n}\n\nfunc (m *ConcurrentMap) MRemove(keys []uint16) {\n\tshardsKeys := m.sortShardsKeys(keys)\n\n\tfor shardIndex, keys := range shardsKeys {\n\t\tshard := m.shards[shardIndex]\n\t\tshard.mux.Lock()\n\t\tfor _, key := range keys {\n\t\t\tdelete(shard.items, key)\n\t\t}\n\t\tshard.mux.Unlock()\n\t}\n}\n\n\/\/ RemoveCb is a callback executed in a map.RemoveCb() call, while Lock is held\n\/\/ If returns true, the element will be removed from the map\ntype RemoveCb func(key uint16, v interface{}, exists bool) bool\n\n\/\/ RemoveCb locks the shard containing the key, retrieves its current value and calls the callback with those params\n\/\/ If callback returns true and element exists, it will remove it from the map\n\/\/ Returns the value returned by the callback (even if element was not present in the map)\nfunc (m *ConcurrentMap) RemoveCb(key uint16, cb RemoveCb) bool {\n\t\/\/ Try to get shard.\n\tshard := m.getShard(key)\n\tshard.mux.Lock()\n\tv, ok := shard.items[key]\n\tremove := cb(key, v, ok)\n\tif remove && ok {\n\t\tdelete(shard.items, key)\n\t}\n\tshard.mux.Unlock()\n\treturn remove\n}\n\n\/\/ Removes an element from the map and returns it\nfunc (m *ConcurrentMap) Pop(key uint16) (v interface{}, exists bool) {\n\t\/\/ Try to get shard.\n\tshard := m.getShard(key)\n\tshard.mux.Lock()\n\tv, exists = shard.items[key]\n\tdelete(shard.items, key)\n\tshard.mux.Unlock()\n\treturn v, exists\n}\n\n\/\/ Checks if map is empty.\nfunc (m *ConcurrentMap) IsEmpty() bool {\n\treturn m.Count() == 0\n}\n\n\/\/ Used by the Iter & IterBuffered functions to wrap two variables together over a channel,\ntype Tuple struct {\n\tKey uint16\n\tVal interface{}\n}\n\n\/\/ Returns an iterator which could be used in a for range loop.\n\/\/\n\/\/ Deprecated: using IterBuffered() will get a better performence\nfunc (m *ConcurrentMap) Iter() <-chan Tuple {\n\tchans := snapshot(m)\n\tch := make(chan Tuple)\n\tgo fanIn(chans, ch)\n\treturn ch\n}\n\n\/\/ Returns a buffered iterator which could be used in a for range loop.\nfunc (m *ConcurrentMap) IterBuffered() <-chan Tuple {\n\tchans := snapshot(m)\n\ttotal := 0\n\tfor _, c := range chans {\n\t\ttotal += cap(c)\n\t}\n\tch := make(chan Tuple, total)\n\tgo fanIn(chans, ch)\n\treturn ch\n}\n\n\/\/ Returns a array of channels that contains elements in each shard,\n\/\/ which likely takes a snapshot of `m`.\n\/\/ It returns once the size of each buffered channel is determined,\n\/\/ before all the channels are populated using goroutines.\nfunc snapshot(m *ConcurrentMap) (chans []chan Tuple) {\n\tchans = make([]chan Tuple, m.count)\n\twg := sync.WaitGroup{}\n\twg.Add(m.count)\n\t\/\/ Foreach shard.\n\tfor index, shard := range m.shards {\n\t\tgo func(index int, shard *ConcurrentMapShared) {\n\t\t\t\/\/ Foreach key, value pair.\n\t\t\tshard.mux.RLock()\n\t\t\tchans[index] = make(chan Tuple, len(shard.items))\n\t\t\twg.Done()\n\t\t\tfor key, val := range shard.items {\n\t\t\t\tchans[index] <- Tuple{key, val}\n\t\t\t}\n\t\t\tshard.mux.RUnlock()\n\t\t\tclose(chans[index])\n\t\t}(index, shard)\n\t}\n\twg.Wait()\n\treturn chans\n}\n\n\/\/ fanIn reads elements from channels `chans` into channel `out`\nfunc fanIn(chans []chan Tuple, out chan Tuple) {\n\twg := sync.WaitGroup{}\n\twg.Add(len(chans))\n\tfor _, ch := range chans {\n\t\tgo func(ch chan Tuple) {\n\t\t\tfor t := range ch {\n\t\t\t\tout <- t\n\t\t\t}\n\t\t\twg.Done()\n\t\t}(ch)\n\t}\n\twg.Wait()\n\tclose(out)\n}\n\n\/\/ Returns all items as map[uint16]interface{}\nfunc (m *ConcurrentMap) Items() map[uint16]interface{} {\n\ttmp := make(map[uint16]interface{})\n\n\t\/\/ Insert items to temporary map.\n\tfor item := range m.IterBuffered() {\n\t\ttmp[item.Key] = item.Val\n\t}\n\n\treturn tmp\n}\n\n\/\/ Iterator callback,called for every key,value found in\n\/\/ maps. RLock is held for all calls for a given shard\n\/\/ therefore callback sess consistent view of a shard,\n\/\/ but not across the shards\ntype IterCb func(key uint16, v interface{})\n\n\/\/ Callback based iterator, cheapest way to read\n\/\/ all elements in a map.\nfunc (m *ConcurrentMap) IterCb(fn IterCb) {\n\tfor idx := range m.shards {\n\t\tshard := m.shards[idx]\n\t\tshard.mux.RLock()\n\t\tfor key, value := range shard.items {\n\t\t\tfn(key, value)\n\t\t}\n\t\tshard.mux.RUnlock()\n\t}\n}\n\n\/\/ Return all keys as []uint16\nfunc (m *ConcurrentMap) Keys() []uint16 {\n\tcount := m.Count()\n\tch := make(chan uint16, count)\n\tgo func() {\n\t\t\/\/ Foreach shard.\n\t\twg := sync.WaitGroup{}\n\t\twg.Add(m.count)\n\t\tfor _, shard := range m.shards {\n\t\t\tgo func(shard *ConcurrentMapShared) {\n\t\t\t\t\/\/ Foreach key, value pair.\n\t\t\t\tshard.mux.RLock()\n\t\t\t\tfor key := range shard.items {\n\t\t\t\t\tch <- key\n\t\t\t\t}\n\t\t\t\tshard.mux.RUnlock()\n\t\t\t\twg.Done()\n\t\t\t}(shard)\n\t\t}\n\t\twg.Wait()\n\t\tclose(ch)\n\t}()\n\n\t\/\/ Generate keys\n\tkeys := make([]uint16, 0, count)\n\tfor k := range ch {\n\t\tkeys = append(keys, k)\n\t}\n\treturn keys\n}\n\n\/\/Reviles ConcurrentMap \"private\" variables to json marshal.\nfunc (m *ConcurrentMap) MarshalJSON() ([]byte, error) {\n\t\/\/ Create a temporary map, which will hold all item spread across shards.\n\ttmp := make(map[uint16]interface{})\n\n\t\/\/ Insert items to temporary map.\n\tfor item := range m.IterBuffered() {\n\t\ttmp[item.Key] = item.Val\n\t}\n\treturn json.Marshal(tmp)\n}\n\n\/\/ Concurrent map uses Interface{} as its value, therefor JSON Unmarshal\n\/\/ will probably won't know which to type to unmarshal into, in such case\n\/\/ we'll end up with a value of type map[uint16]interface{}, In most cases this isn't\n\/\/ out value type, this is why we've decided to remove this functionality.\n\n\/\/ func (m *ConcurrentMap) UnmarshalJSON(b []byte) (err error) {\n\/\/ \t\/\/ Reverse process of Marshal.\n\n\/\/ \ttmp := make(map[uint16]interface{})\n\n\/\/ \t\/\/ Unmarshal into a single map.\n\/\/ \tif err := json.Unmarshal(b, &tmp); err != nil {\n\/\/ \t\treturn nil\n\/\/ \t}\n\n\/\/ \t\/\/ foreach key,value pair in temporary map insert into our concurrent map.\n\/\/ \tfor key, val := range tmp {\n\/\/ \t\tm.Set(key, val)\n\/\/ \t}\n\/\/ \treturn nil\n\/\/ }\n<|endoftext|>"}
{"text":"<commit_before>package common\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\n\/\/ LogFail is the failure log formatter\n\/\/ prints text to stderr and exits with status 1\nfunc LogFail(text string) {\n\tfmt.Fprintln(os.Stderr, fmt.Sprintf(\"FAILED: %s\", text))\n\tos.Exit(1)\n}\n\n\/\/ LogInfo1 is the info1 header formatter\nfunc LogInfo1(text string) {\n\tfmt.Fprintln(os.Stdout, fmt.Sprintf(\"-----> %s\", text))\n}\n\n\/\/ LogInfo1Quiet is the info1 header formatter (with quiet option)\nfunc LogInfo1Quiet(text string) {\n\tif os.Getenv(\"DOKKU_QUIET_OUTPUT\") != \"\" {\n\t\tLogInfo1(text)\n\t}\n}\n\n\/\/ LogInfo2 is the info2 header formatter\nfunc LogInfo2(text string) {\n\tfmt.Fprintln(os.Stdout, fmt.Sprintf(\"=====> %s\", text))\n}\n\n\/\/ LogInfo2Quiet is the info2 header formatter (with quiet option)\nfunc LogInfo2Quiet(text string) {\n\tif os.Getenv(\"DOKKU_QUIET_OUTPUT\") == \"\" {\n\t\tLogInfo2(text)\n\t}\n}\n\n\/\/ LogVerbose is the verbose log formatter\n\/\/ prints indented text to stdout\nfunc LogVerbose(text string) {\n\tfmt.Fprintln(os.Stdout, fmt.Sprintf(\"       %s\", text))\n}\n\n\/\/ LogVerboseQuiet is the verbose log formatter\n\/\/ prints indented text to stdout (with quiet option)\nfunc LogVerboseQuiet(text string) {\n\tif os.Getenv(\"DOKKU_QUIET_OUTPUT\") != \"\" {\n\t\tLogVerbose(text)\n\t}\n}\n\n\/\/ LogWarn is the warning log formatter\nfunc LogWarn(text string) {\n\tfmt.Fprintln(os.Stderr, fmt.Sprintf(\" !     %s\", text))\n}\n<commit_msg>fix: correct the DOKKU_QUIET_OUTPUT env var check for golang log methods<commit_after>package common\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\n\/\/ LogFail is the failure log formatter\n\/\/ prints text to stderr and exits with status 1\nfunc LogFail(text string) {\n\tfmt.Fprintln(os.Stderr, fmt.Sprintf(\"FAILED: %s\", text))\n\tos.Exit(1)\n}\n\n\/\/ LogInfo1 is the info1 header formatter\nfunc LogInfo1(text string) {\n\tfmt.Fprintln(os.Stdout, fmt.Sprintf(\"-----> %s\", text))\n}\n\n\/\/ LogInfo1Quiet is the info1 header formatter (with quiet option)\nfunc LogInfo1Quiet(text string) {\n\tif os.Getenv(\"DOKKU_QUIET_OUTPUT\") == \"\" {\n\t\tLogInfo1(text)\n\t}\n}\n\n\/\/ LogInfo2 is the info2 header formatter\nfunc LogInfo2(text string) {\n\tfmt.Fprintln(os.Stdout, fmt.Sprintf(\"=====> %s\", text))\n}\n\n\/\/ LogInfo2Quiet is the info2 header formatter (with quiet option)\nfunc LogInfo2Quiet(text string) {\n\tif os.Getenv(\"DOKKU_QUIET_OUTPUT\") == \"\" {\n\t\tLogInfo2(text)\n\t}\n}\n\n\/\/ LogVerbose is the verbose log formatter\n\/\/ prints indented text to stdout\nfunc LogVerbose(text string) {\n\tfmt.Fprintln(os.Stdout, fmt.Sprintf(\"       %s\", text))\n}\n\n\/\/ LogVerboseQuiet is the verbose log formatter\n\/\/ prints indented text to stdout (with quiet option)\nfunc LogVerboseQuiet(text string) {\n\tif os.Getenv(\"DOKKU_QUIET_OUTPUT\") == \"\" {\n\t\tLogVerbose(text)\n\t}\n}\n\n\/\/ LogWarn is the warning log formatter\nfunc LogWarn(text string) {\n\tfmt.Fprintln(os.Stderr, fmt.Sprintf(\" !     %s\", text))\n}\n<|endoftext|>"}
{"text":"<commit_before>package durafmt\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\nvar (\n\ttestStrings []struct {\n\t\ttest     string\n\t\texpected string\n\t}\n\ttestTimes []struct {\n\t\ttest     time.Duration\n\t\texpected string\n\t}\n)\n\n\/\/ TestParse for durafmt time.Duration conversion.\nfunc TestParse(t *testing.T) {\n\ttestTimes = []struct {\n\t\ttest     time.Duration\n\t\texpected string\n\t}{\n\t\t{1 * time.Second, \"1 second\"},\n\t\t{1 * time.Minute, \"1 minute\"},\n\t\t{2 * time.Second, \"2 seconds\"},\n\t\t{2 * time.Minute, \"2 minutes\"},\n\t\t{1 * time.Hour, \"1 hour\"},\n\t\t{2 * time.Hour, \"2 hours\"},\n\t\t{10 * time.Hour, \"10 hours\"},\n\t\t{24 * time.Hour, \"1 day\"},\n\t\t{48 * time.Hour, \"2 days\"},\n\t\t{120 * time.Hour, \"5 days\"},\n\t\t{168 * time.Hour, \"1 week\"},\n\t\t{672 * time.Hour, \"4 weeks\"},\n\t\t{8760 * time.Hour, \"1 year\"},\n\t\t{17520 * time.Hour, \"2 years\"},\n\t\t{-1 * time.Second, \"-1 second\"},\n\t\t{-10 * time.Second, \"-10 seconds\"},\n\t}\n\n\tfor _, table := range testTimes {\n\t\tresult := Parse(table.test).String()\n\t\tif result != table.expected {\n\t\t\tt.Errorf(\"Parse(%q).String() = %q. got %q, expected %q\",\n\t\t\t\ttable.test, result, result, table.expected)\n\t\t}\n\t}\n}\n\n\/\/ TestParseString for durafmt duration string conversion.\nfunc TestParseString(t *testing.T) {\n\ttestStrings = []struct {\n\t\ttest     string\n\t\texpected string\n\t}{\n\t\t{\"1s\", \"1 second\"},\n\t\t{\"1m\", \"1 minute\"},\n\t\t{\"2m\", \"2 minutes\"},\n\t\t{\"1h\", \"1 hour\"},\n\t\t{\"10h\", \"10 hours\"},\n\t\t{\"24h\", \"1 day\"},\n\t\t{\"48h\", \"2 days\"},\n\t\t{\"120h\", \"5 days\"},\n\t\t{\"168h\", \"1 week\"},\n\t\t{\"672h\", \"4 weeks\"},\n\t\t{\"8760h\", \"1 year\"},\n\t\t{\"17520h\", \"2 years\"},\n\t\t{\"1m0s\", \"1 minute\"},\n\t\t{\"1m2s\", \"1 minute 2 seconds\"},\n\t\t{\"3h4m5s\", \"3 hours 4 minutes 5 seconds\"},\n\t\t{\"0s\", \"0 seconds\"},\n\t\t{\"0m\", \"0 minutes\"},\n\t\t{\"0h\", \"0 hours\"},\n\t\t{\"0m2s\", \"2 seconds\"},\n\t\t{\"0m2m\", \"2 minutes\"},\n\t\t{\"0m2m3h\", \"3 hours 2 minutes\"},\n\t\t{\"0m2m34h\", \"1 day 10 hours 2 minutes\"},\n\t\t{\"-1s\", \"-1 second\"},\n\t\t{\"-1m\", \"-1 minute\"},\n\t\t{\"-2m\", \"-2 minutes\"},\n\t\t{\"-1h\", \"-1 hour\"},\n\t\t{\"-10h\", \"-10 hours\"},\n\t\t{\"-24h\", \"-1 day\"},\n\t\t{\"-48h\", \"-2 days\"},\n\t\t{\"-120h\", \"-5 days\"},\n\t\t{\"-168h\", \"-1 week\"},\n\t\t{\"-672h\", \"-4 weeks\"},\n\t\t{\"-8760h\", \"-1 year\"},\n\t\t{\"-1m0s\", \"-1 minute\"},\n\t\t{\"-0m2s\", \"-2 seconds\"},\n\t\t{\"-0m2m\", \"-2 minutes\"},\n\t\t{\"-0m2m3h\", \"-3 hours 2 minutes\"},\n\t\t{\"-0m2m34h\", \"-1 day 10 hours 2 minutes\"},\n\t\t{\"-0s\", \"-0 seconds\"},\n\t\t{\"-0m\", \"-0 minutes\"},\n\t\t{\"-0h\", \"-0 hours\"},\n\t}\n\n\tfor _, table := range testStrings {\n\t\td, err := ParseString(table.test)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"%q\", err)\n\t\t}\n\t\tresult := d.String()\n\t\tif result != table.expected {\n\t\t\tt.Errorf(\"d.String() = %q. got %q, expected %q\",\n\t\t\t\ttable.test, result, table.expected)\n\t\t}\n\t}\n}\n\n\/\/ TestInvalidDuration for invalid inputs.\nfunc TestInvalidDuration(t *testing.T) {\n\ttestStrings = []struct {\n\t\ttest     string\n\t\texpected string\n\t}{\n\t\t{\"1\", \"\"},\n\t\t{\"1d\", \"\"},\n\t\t{\"1w\", \"\"},\n\t\t{\"1wk\", \"\"},\n\t\t{\"1y\", \"\"},\n\t\t{\"\", \"\"},\n\t\t{\"m1\", \"\"},\n\t\t{\"1nmd\", \"\"},\n\t\t{\"0\", \"\"},\n\t\t{\"-0\", \"\"},\n\t}\n\n\tfor _, table := range testStrings {\n\t\t_, err := ParseString(table.test)\n\t\tif err == nil {\n\t\t\tt.Errorf(\"NewDurable(%q). got %q, expected %q\",\n\t\t\t\ttable.test, err, table.expected)\n\t\t}\n\t}\n}\n<commit_msg>test modified for millisecond<commit_after>package durafmt\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\nvar (\n\ttestStrings []struct {\n\t\ttest     string\n\t\texpected string\n\t}\n\ttestTimes []struct {\n\t\ttest     time.Duration\n\t\texpected string\n\t}\n)\n\n\/\/ TestParse for durafmt time.Duration conversion.\nfunc TestParse(t *testing.T) {\n\ttestTimes = []struct {\n\t\ttest     time.Duration\n\t\texpected string\n\t}{\n\t\t{1 * time.Second, \"1 second\"},\n\t\t{1 * time.Minute, \"1 minute\"},\n\t\t{2 * time.Second, \"2 seconds\"},\n\t\t{2 * time.Minute, \"2 minutes\"},\n\t\t{1 * time.Hour, \"1 hour\"},\n\t\t{2 * time.Hour, \"2 hours\"},\n\t\t{10 * time.Hour, \"10 hours\"},\n\t\t{24 * time.Hour, \"1 day\"},\n\t\t{48 * time.Hour, \"2 days\"},\n\t\t{120 * time.Hour, \"5 days\"},\n\t\t{168 * time.Hour, \"1 week\"},\n\t\t{672 * time.Hour, \"4 weeks\"},\n\t\t{8760 * time.Hour, \"1 year\"},\n\t\t{17520 * time.Hour, \"2 years\"},\n\t\t{-1 * time.Second, \"-1 second\"},\n\t\t{-10 * time.Second, \"-10 seconds\"},\n\t}\n\n\tfor _, table := range testTimes {\n\t\tresult := Parse(table.test).String()\n\t\tif result != table.expected {\n\t\t\tt.Errorf(\"Parse(%q).String() = %q. got %q, expected %q\",\n\t\t\t\ttable.test, result, result, table.expected)\n\t\t}\n\t}\n}\n\n\/\/ TestParseString for durafmt duration string conversion.\nfunc TestParseString(t *testing.T) {\n\ttestStrings = []struct {\n\t\ttest     string\n\t\texpected string\n\t}{\n\t\t{\"1s\", \"1 second\"},\n\t\t{\"1m\", \"1 minute\"},\n\t\t{\"2m\", \"2 minutes\"},\n\t\t{\"1h\", \"1 hour\"},\n\t\t{\"10h\", \"10 hours\"},\n\t\t{\"24h\", \"1 day\"},\n\t\t{\"48h\", \"2 days\"},\n\t\t{\"120h\", \"5 days\"},\n\t\t{\"168h\", \"1 week\"},\n\t\t{\"672h\", \"4 weeks\"},\n\t\t{\"8760h\", \"1 year\"},\n\t\t{\"17520h\", \"2 years\"},\n\t\t{\"1m0s\", \"1 minute\"},\n\t\t{\"1m2s\", \"1 minute 2 seconds\"},\n\t\t{\"3h4m5s\", \"3 hours 4 minutes 5 seconds\"},\n\t\t{\"0s\", \"0 seconds\"},\n\t\t{\"0m\", \"0 minutes0 milliseconds\"},\n\t\t{\"0h\", \"0 hours\"},\n\t\t{\"0m2s\", \"2 seconds\"},\n\t\t{\"0m2m\", \"2 minutes\"},\n\t\t{\"0m2m3h\", \"3 hours 2 minutes\"},\n\t\t{\"0m2m34h\", \"1 day 10 hours 2 minutes\"},\n\t\t{\"-1s\", \"-1 second\"},\n\t\t{\"-1m\", \"-1 minute\"},\n\t\t{\"-2m\", \"-2 minutes\"},\n\t\t{\"-1h\", \"-1 hour\"},\n\t\t{\"-10h\", \"-10 hours\"},\n\t\t{\"-24h\", \"-1 day\"},\n\t\t{\"-48h\", \"-2 days\"},\n\t\t{\"-120h\", \"-5 days\"},\n\t\t{\"-168h\", \"-1 week\"},\n\t\t{\"-672h\", \"-4 weeks\"},\n\t\t{\"-8760h\", \"-1 year\"},\n\t\t{\"-1m0s\", \"-1 minute\"},\n\t\t{\"-0m2s\", \"-2 seconds\"},\n\t\t{\"-0m2m\", \"-2 minutes\"},\n\t\t{\"-0m2m3h\", \"-3 hours 2 minutes\"},\n\t\t{\"-0m2m34h\", \"-1 day 10 hours 2 minutes\"},\n\t\t{\"-0s\", \"-0 seconds\"},\n\t\t{\"-0m\", \"-0 minutes0 milliseconds\"},\n\t\t{\"-0h\", \"-0 hours\"},\n\t}\n\n\tfor _, table := range testStrings {\n\t\td, err := ParseString(table.test)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"%q\", err)\n\t\t}\n\t\tresult := d.String()\n\t\tif result != table.expected {\n\t\t\tt.Errorf(\"d.String() = %q. got %q, expected %q\",\n\t\t\t\ttable.test, result, table.expected)\n\t\t}\n\t}\n}\n\n\/\/ TestInvalidDuration for invalid inputs.\nfunc TestInvalidDuration(t *testing.T) {\n\ttestStrings = []struct {\n\t\ttest     string\n\t\texpected string\n\t}{\n\t\t{\"1\", \"\"},\n\t\t{\"1d\", \"\"},\n\t\t{\"1w\", \"\"},\n\t\t{\"1wk\", \"\"},\n\t\t{\"1y\", \"\"},\n\t\t{\"\", \"\"},\n\t\t{\"m1\", \"\"},\n\t\t{\"1nmd\", \"\"},\n\t\t{\"0\", \"\"},\n\t\t{\"-0\", \"\"},\n\t}\n\n\tfor _, table := range testStrings {\n\t\t_, err := ParseString(table.test)\n\t\tif err == nil {\n\t\t\tt.Errorf(\"NewDurable(%q). got %q, expected %q\",\n\t\t\t\ttable.test, err, table.expected)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"image\"\n\t\"image\/color\"\n\t\"image\/draw\"\n\t\"os\"\n\t\"time\"\n\n\t. \"github.com\/eaburns\/quart\/geom\"\n\t\"github.com\/eaburns\/quart\/phys\"\n\n\t\"github.com\/skelterjohn\/go.wde\"\n)\n\nconst (\n\twidth  = 640\n\theight = 480\n\n\tspeed         = 5\n\tgravity       = -3\n\tstopThreshold = 1\n)\n\nvar (\n\tvel    Vector\n\tcircle = Circle{Center: Point{200, 200}, Radius: 50}\n\n\t\/\/ Sides is the set of polygon sides.\n\tsides = []Side{\n\t\t{{0, height - 1}, {0, 0}},\n\t\t{{0, 0}, {width - 1, 0}},\n\t\t{{width - 1, 0}, {width - 1, height - 1}},\n\t\t{{width - 1, height - 1}, {0, height - 1}},\n\t}\n\n\t\/\/ Click is the position of the latest mouse click.\n\tclick = Point{-1, -1}\n\n\t\/\/ Cursor is the current cursor position.\n\tcursor Point\n\n\t\/\/ Stopped is true if the circle has effectively stopped moving.\n\tstopped bool\n)\n\nfunc main() {\n\tgo mainLoop()\n\twde.Run()\n}\n\nfunc mainLoop() {\n\twin, err := wde.NewWindow(width, height)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\twin.SetTitle(\"geom test\")\n\twin.Show()\n\n\tdrawScene(win)\n\n\ttick := time.NewTicker(40 * time.Millisecond)\n\tfor {\n\t\tselect {\n\t\tcase ev, ok := <-win.EventChan():\n\t\t\tif !ok {\n\t\t\t\tos.Exit(0)\n\t\t\t}\n\t\t\tswitch ev := ev.(type) {\n\t\t\tcase wde.CloseEvent:\n\t\t\t\tos.Exit(0)\n\t\t\tcase wde.KeyTypedEvent:\n\t\t\t\tkeyTyped(ev)\n\t\t\tcase wde.KeyDownEvent:\n\t\t\t\tkeyDown(wde.KeyEvent(ev))\n\t\t\tcase wde.KeyUpEvent:\n\t\t\t\tkeyUp(wde.KeyEvent(ev))\n\t\t\tcase wde.MouseDraggedEvent:\n\t\t\t\tmouseMove(ev.MouseEvent)\n\t\t\tcase wde.MouseMovedEvent:\n\t\t\t\tmouseMove(ev.MouseEvent)\n\t\t\tcase wde.MouseDownEvent:\n\t\t\t\tmouseDown(wde.MouseButtonEvent(ev))\n\t\t\tcase wde.MouseUpEvent:\n\t\t\t\tmouseUp(wde.MouseButtonEvent(ev))\n\t\t\t}\n\n\t\tcase <-tick.C:\n\t\t\tif !stopped {\n\t\t\t\tstart := circle.Center\n\t\t\t\tcircle = phys.MoveCircle(circle, vel, sides)\n\t\t\t\tcircle = phys.MoveCircle(circle, Vector{0, gravity}, sides)\n\t\t\t\tdist := start.Minus(circle.Center).Magnitude()\n\t\t\t\tstopped = dist < stopThreshold\n\t\t\t}\n\t\t\tdrawScene(win)\n\t\t}\n\t}\n}\n\nfunc mouseMove(ev wde.MouseEvent) {\n\tcursor = Point{float64(ev.Where.X), float64(height - ev.Where.Y - 1)}\n}\n\nfunc mouseDown(ev wde.MouseButtonEvent) {\n\tswitch ev.Which {\n\tcase wde.LeftButton:\n\t\tclick = Point{float64(ev.Where.X), float64(height - ev.Where.Y - 1)}\n\t}\n}\n\nfunc mouseUp(ev wde.MouseButtonEvent) {\n\tswitch ev.Which {\n\tcase wde.LeftButton:\n\t\tsides = append(sides, Side{click, cursor})\n\t\tclick = Point{-1, -1}\n\t}\n}\n\nfunc keyTyped(ev wde.KeyTypedEvent) {\n\tswitch ev.Key {\n\tcase \"d\":\n\t\tif len(sides) > 4 {\n\t\t\tsides = sides[:len(sides)-1]\n\t\t}\n\t}\n}\n\nfunc keyDown(ev wde.KeyEvent) {\n\tswitch ev.Key {\n\tcase \"left_arrow\":\n\t\tvel[0] = -speed\n\tcase \"right_arrow\":\n\t\tvel[0] = speed\n\tcase \"up_arrow\":\n\t\tvel[1] = speed\n\tcase \"down_arrow\":\n\t\tvel[1] = -speed\n\t}\n\tstopped = false\n}\n\nfunc keyUp(ev wde.KeyEvent) {\n\tswitch ev.Key {\n\tcase \"left_arrow\", \"right_arrow\":\n\t\tvel[0] = 0\n\tcase \"up_arrow\", \"down_arrow\":\n\t\tvel[1] = 0\n\t}\n}\n\nfunc drawScene(win wde.Window) {\n\tclear(win)\n\tcv := ImageCanvas{win.Screen()}\n\n\tfor _, s := range sides {\n\t\ts.Draw(cv, color.Black)\n\t}\n\tcircle.Draw(cv, color.Black)\n\n\tif click[0] >= 0 {\n\t\tSide{click, cursor}.Draw(cv, color.RGBA{B: 255, A: 255})\n\t}\n\n\twin.FlushImage()\n}\n\nfunc clear(win wde.Window) {\n\timg := win.Screen()\n\tdraw.Draw(img, img.Bounds(), image.NewUniform(color.White), image.ZP, draw.Src)\n}\n<commit_msg>Only set stopped=true when velocity is zero.<commit_after>package main\n\nimport (\n\t\"image\"\n\t\"image\/color\"\n\t\"image\/draw\"\n\t\"os\"\n\t\"time\"\n\n\t. \"github.com\/eaburns\/quart\/geom\"\n\t\"github.com\/eaburns\/quart\/phys\"\n\n\t\"github.com\/skelterjohn\/go.wde\"\n)\n\nconst (\n\twidth  = 640\n\theight = 480\n\n\tspeed         = 5\n\tgravity       = -3\n\tstopThreshold = 1\n)\n\nvar (\n\tvel    Vector\n\tcircle = Circle{Center: Point{200, 200}, Radius: 50}\n\n\t\/\/ Sides is the set of polygon sides.\n\tsides = []Side{\n\t\t{{0, height - 1}, {0, 0}},\n\t\t{{0, 0}, {width - 1, 0}},\n\t\t{{width - 1, 0}, {width - 1, height - 1}},\n\t\t{{width - 1, height - 1}, {0, height - 1}},\n\t}\n\n\t\/\/ Click is the position of the latest mouse click.\n\tclick = Point{-1, -1}\n\n\t\/\/ Cursor is the current cursor position.\n\tcursor Point\n\n\t\/\/ Stopped is true if the circle has effectively stopped moving.\n\tstopped bool\n)\n\nfunc main() {\n\tgo mainLoop()\n\twde.Run()\n}\n\nfunc mainLoop() {\n\twin, err := wde.NewWindow(width, height)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\twin.SetTitle(\"geom test\")\n\twin.Show()\n\n\tdrawScene(win)\n\n\ttick := time.NewTicker(40 * time.Millisecond)\n\tfor {\n\t\tselect {\n\t\tcase ev, ok := <-win.EventChan():\n\t\t\tif !ok {\n\t\t\t\tos.Exit(0)\n\t\t\t}\n\t\t\tswitch ev := ev.(type) {\n\t\t\tcase wde.CloseEvent:\n\t\t\t\tos.Exit(0)\n\t\t\tcase wde.KeyTypedEvent:\n\t\t\t\tkeyTyped(ev)\n\t\t\tcase wde.KeyDownEvent:\n\t\t\t\tkeyDown(wde.KeyEvent(ev))\n\t\t\tcase wde.KeyUpEvent:\n\t\t\t\tkeyUp(wde.KeyEvent(ev))\n\t\t\tcase wde.MouseDraggedEvent:\n\t\t\t\tmouseMove(ev.MouseEvent)\n\t\t\tcase wde.MouseMovedEvent:\n\t\t\t\tmouseMove(ev.MouseEvent)\n\t\t\tcase wde.MouseDownEvent:\n\t\t\t\tmouseDown(wde.MouseButtonEvent(ev))\n\t\t\tcase wde.MouseUpEvent:\n\t\t\t\tmouseUp(wde.MouseButtonEvent(ev))\n\t\t\t}\n\n\t\tcase <-tick.C:\n\t\t\tif !stopped {\n\t\t\t\tstart := circle.Center\n\t\t\t\tcircle = phys.MoveCircle(circle, vel, sides)\n\t\t\t\tcircle = phys.MoveCircle(circle, Vector{0, gravity}, sides)\n\t\t\t\tdist := start.Minus(circle.Center).Magnitude()\n\t\t\t\tstopped = vel.Equals(Vector{}) && dist < stopThreshold\n\t\t\t}\n\t\t\tdrawScene(win)\n\t\t}\n\t}\n}\n\nfunc mouseMove(ev wde.MouseEvent) {\n\tcursor = Point{float64(ev.Where.X), float64(height - ev.Where.Y - 1)}\n}\n\nfunc mouseDown(ev wde.MouseButtonEvent) {\n\tswitch ev.Which {\n\tcase wde.LeftButton:\n\t\tclick = Point{float64(ev.Where.X), float64(height - ev.Where.Y - 1)}\n\t}\n}\n\nfunc mouseUp(ev wde.MouseButtonEvent) {\n\tswitch ev.Which {\n\tcase wde.LeftButton:\n\t\tsides = append(sides, Side{click, cursor})\n\t\tclick = Point{-1, -1}\n\t}\n}\n\nfunc keyTyped(ev wde.KeyTypedEvent) {\n\tswitch ev.Key {\n\tcase \"d\":\n\t\tif len(sides) > 4 {\n\t\t\tsides = sides[:len(sides)-1]\n\t\t}\n\t}\n}\n\nfunc keyDown(ev wde.KeyEvent) {\n\tswitch ev.Key {\n\tcase \"left_arrow\":\n\t\tvel[0] = -speed\n\tcase \"right_arrow\":\n\t\tvel[0] = speed\n\tcase \"up_arrow\":\n\t\tvel[1] = speed\n\tcase \"down_arrow\":\n\t\tvel[1] = -speed\n\t}\n\tstopped = false\n}\n\nfunc keyUp(ev wde.KeyEvent) {\n\tswitch ev.Key {\n\tcase \"left_arrow\", \"right_arrow\":\n\t\tvel[0] = 0\n\tcase \"up_arrow\", \"down_arrow\":\n\t\tvel[1] = 0\n\t}\n}\n\nfunc drawScene(win wde.Window) {\n\tclear(win)\n\tcv := ImageCanvas{win.Screen()}\n\n\tfor _, s := range sides {\n\t\ts.Draw(cv, color.Black)\n\t}\n\tcircle.Draw(cv, color.Black)\n\n\tif click[0] >= 0 {\n\t\tSide{click, cursor}.Draw(cv, color.RGBA{B: 255, A: 255})\n\t}\n\n\twin.FlushImage()\n}\n\nfunc clear(win wde.Window) {\n\timg := win.Screen()\n\tdraw.Draw(img, img.Bounds(), image.NewUniform(color.White), image.ZP, draw.Src)\n}\n<|endoftext|>"}
{"text":"<commit_before>package util\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"testing\"\n)\n\nvar (\n\tbs    = []byte{0, 11, 22, 33, 44, 55, 66, 77}\n\tbsBuf = bytes.NewReader(bs)\n\tn     = len(bs)\n)\n\nfunc TestReadBytes(t *testing.T) {\n\tbsReader := NewReader(bsBuf)\n\n\tread, err := bsReader.ReadBytes(n)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif n != len(read) {\n\t\tt.Errorf(\"Expecting to read: %v, got: %v\", n, read)\n\t}\n\tif !bytes.Equal(bs, read) {\n\t\tt.Error(\"Expecting: %v, got: %v\", bs, read)\n\t}\n\n\tfmt.Println(bsReader.buf.Buffered())\n\tif bsReader.buf.Buffered() != 0 {\n\t\tt.Errorf(\"Expecting buffered: %v, got: %v\", 0, bsReader.buf.Buffered())\n\t}\n}\n<commit_msg>Add test to Reader.ReadTillAndWithDelims<commit_after>package util\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n)\n\nvar (\n\tbs   = []byte{0, 11, 22, 33, 44, 55, 77, 88, 55, 66, 77, 88}\n\tbsRd = bytes.NewReader(bs)\n)\n\nfunc TestReadBytes(t *testing.T) {\n\tbsRd.Reset(bs)\n\tbsReader := NewReader(bsRd)\n\tn := 5 \/\/ Read 5 elements\n\n\tread, err := bsReader.ReadBytes(n)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif n != len(read) {\n\t\tt.Errorf(\"Expecting to read: %v, got: %v\", n, read)\n\t}\n\tif !bytes.Equal(bs[:n], read) {\n\t\tt.Error(\"Expecting: %v, got: %v\", bs[:n], len(read))\n\t}\n\n\tif bsReader.buf.Buffered() != len(bs)-n {\n\t\tt.Errorf(\"Expecting buffered: %v, got: %v\", len(bs)-n, bsReader.buf.Buffered())\n\t}\n}\n\nfunc TestReadTillAndWithDelims(t *testing.T) {\n\tbsRd.Reset(bs)\n\tbsReader := NewReader(bsRd)\n\tn := 10\n\tdelims := []byte{bs[n-2], bs[n-1]}\n\n\tread, err := bsReader.ReadTillAndWithDelims(delims)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tif n != len(read) {\n\t\tt.Errorf(\"Expecting to read: %v, got: %v\", n, len(read))\n\t}\n\tif !bytes.Equal(bs[:n], read) {\n\t\tt.Error(\"Expecting: %v, got: %v\", bs[:n], read)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nfunc main() {\n\tex1()\n\n}\n\nfunc ex1() {\n\tvar i interface{} = nil\n\tprintln(\"nil interface is nil?:\", i == nil) \/\/ true\n\tprintln(i)                                  \/\/ (0x0, 0x0)\n\n}\n<commit_msg>nilinterface: add ex2<commit_after>package main\n\nfunc main() {\n\n\tex1()\n\n\tex2()\n\n}\n\nfunc ex1() {\n\tvar i interface{} = nil\n\tprintln(\"ex1\")\n\tprintln(\"nil interface is nil?:\", i == nil) \/\/ true\n\tprintln(i)                                  \/\/ (0x0, 0x0)\n\tprintln()\n\n}\n\nfunc ex2() {\n\tvar v int = 10\n\tvar i interface{} = v\n\tprintln(\"ex2\")\n\tprintln(\"interface-to-value is nil?:\", i == nil) \/\/ false\n\tprintln(\"value address:\", &v)\n\tprintln(i)\n\tprintln()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2014 The Kubernetes Authors All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage scheduler\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"math\/rand\"\n\t\"sort\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/golang\/glog\"\n\t\"k8s.io\/kubernetes\/pkg\/api\"\n\t\"k8s.io\/kubernetes\/pkg\/util\"\n\t\"k8s.io\/kubernetes\/pkg\/util\/errors\"\n\t\"k8s.io\/kubernetes\/pkg\/util\/workqueue\"\n\t\"k8s.io\/kubernetes\/plugin\/pkg\/scheduler\/algorithm\"\n\t\"k8s.io\/kubernetes\/plugin\/pkg\/scheduler\/algorithm\/predicates\"\n\tschedulerapi \"k8s.io\/kubernetes\/plugin\/pkg\/scheduler\/api\"\n\t\"k8s.io\/kubernetes\/plugin\/pkg\/scheduler\/schedulercache\"\n)\n\ntype FailedPredicateMap map[string]string\n\ntype FitError struct {\n\tPod              *api.Pod\n\tFailedPredicates FailedPredicateMap\n}\n\nvar ErrNoNodesAvailable = fmt.Errorf(\"no nodes available to schedule pods\")\n\n\/\/ Error returns detailed information of why the pod failed to fit on each node\nfunc (f *FitError) Error() string {\n\tvar buf bytes.Buffer\n\tbuf.WriteString(fmt.Sprintf(\"pod (%s) failed to fit in any node\\n\", f.Pod.Name))\n\tfor node, predicate := range f.FailedPredicates {\n\t\treason := fmt.Sprintf(\"fit failure on node (%s): %s\\n\", node, predicate)\n\t\tbuf.WriteString(reason)\n\t}\n\treturn buf.String()\n}\n\ntype genericScheduler struct {\n\tcache         schedulercache.Cache\n\tpredicates    map[string]algorithm.FitPredicate\n\tprioritizers  []algorithm.PriorityConfig\n\textenders     []algorithm.SchedulerExtender\n\tpods          algorithm.PodLister\n\trandom        *rand.Rand\n\trandomLock    sync.Mutex\n\tlastNodeIndex uint64\n}\n\n\/\/ Schedule tries to schedule the given pod to one of node in the node list.\n\/\/ If it succeeds, it will return the name of the node.\n\/\/ If it fails, it will return a Fiterror error with reasons.\nfunc (g *genericScheduler) Schedule(pod *api.Pod, nodeLister algorithm.NodeLister) (string, error) {\n\tvar trace *util.Trace\n\tif pod != nil {\n\t\ttrace = util.NewTrace(fmt.Sprintf(\"Scheduling %s\/%s\", pod.Namespace, pod.Name))\n\t} else {\n\t\ttrace = util.NewTrace(\"Scheduling <nil> pod\")\n\t}\n\tdefer trace.LogIfLong(20 * time.Millisecond)\n\n\tnodes, err := nodeLister.List()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif len(nodes.Items) == 0 {\n\t\treturn \"\", ErrNoNodesAvailable\n\t}\n\n\t\/\/ Used for all fit and priority funcs.\n\tnodeNameToInfo, err := g.cache.GetNodeNameToInfoMap()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\ttrace.Step(\"Computing predicates\")\n\tfilteredNodes, failedPredicateMap, err := findNodesThatFit(pod, nodeNameToInfo, g.predicates, nodes, g.extenders)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif len(filteredNodes.Items) == 0 {\n\t\treturn \"\", &FitError{\n\t\t\tPod:              pod,\n\t\t\tFailedPredicates: failedPredicateMap,\n\t\t}\n\t}\n\n\ttrace.Step(\"Prioritizing\")\n\tpriorityList, err := PrioritizeNodes(pod, nodeNameToInfo, g.prioritizers, algorithm.FakeNodeLister(filteredNodes), g.extenders)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\ttrace.Step(\"Selecting host\")\n\treturn g.selectHost(priorityList)\n}\n\n\/\/ selectHost takes a prioritized list of nodes and then picks one\n\/\/ randomly from the nodes that had the highest score.\nfunc (g *genericScheduler) selectHost(priorityList schedulerapi.HostPriorityList) (string, error) {\n\tif len(priorityList) == 0 {\n\t\treturn \"\", fmt.Errorf(\"empty priorityList\")\n\t}\n\n\tsort.Sort(sort.Reverse(priorityList))\n\tmaxScore := priorityList[0].Score\n\tfirstAfterMaxScore := sort.Search(len(priorityList), func(i int) bool { return priorityList[i].Score < maxScore })\n\n\tg.randomLock.Lock()\n\tix := int(g.lastNodeIndex % uint64(firstAfterMaxScore))\n\tg.lastNodeIndex++\n\tg.randomLock.Unlock()\n\n\treturn priorityList[ix].Host, nil\n}\n\n\/\/ Filters the nodes to find the ones that fit based on the given predicate functions\n\/\/ Each node is passed through the predicate functions to determine if it is a fit\nfunc findNodesThatFit(pod *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, predicateFuncs map[string]algorithm.FitPredicate, nodes api.NodeList, extenders []algorithm.SchedulerExtender) (api.NodeList, FailedPredicateMap, error) {\n\tpredicateResultLock := sync.Mutex{}\n\tfiltered := []api.Node{}\n\tfailedPredicateMap := FailedPredicateMap{}\n\terrs := []error{}\n\n\tcheckNode := func(i int) {\n\t\tnodeName := nodes.Items[i].Name\n\t\tfits, failedPredicate, err := podFitsOnNode(pod, nodeNameToInfo[nodeName], predicateFuncs)\n\n\t\tpredicateResultLock.Lock()\n\t\tdefer predicateResultLock.Unlock()\n\t\tif err != nil {\n\t\t\terrs = append(errs, err)\n\t\t\treturn\n\t\t}\n\t\tif fits {\n\t\t\tfiltered = append(filtered, nodes.Items[i])\n\t\t} else {\n\t\t\tfailedPredicateMap[nodeName] = failedPredicate\n\t\t}\n\t}\n\tworkqueue.Parallelize(16, len(nodes.Items), checkNode)\n\tif len(errs) > 0 {\n\t\treturn api.NodeList{}, FailedPredicateMap{}, errors.NewAggregate(errs)\n\t}\n\n\tif len(filtered) > 0 && len(extenders) != 0 {\n\t\tfor _, extender := range extenders {\n\t\t\tfilteredList, err := extender.Filter(pod, &api.NodeList{Items: filtered})\n\t\t\tif err != nil {\n\t\t\t\treturn api.NodeList{}, FailedPredicateMap{}, err\n\t\t\t}\n\t\t\tfiltered = filteredList.Items\n\t\t\tif len(filtered) == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn api.NodeList{Items: filtered}, failedPredicateMap, nil\n}\n\n\/\/ Checks whether node with a given name and NodeInfo satisfies all predicateFuncs.\nfunc podFitsOnNode(pod *api.Pod, info *schedulercache.NodeInfo, predicateFuncs map[string]algorithm.FitPredicate) (bool, string, error) {\n\tfor _, predicate := range predicateFuncs {\n\t\tfit, err := predicate(pod, info)\n\t\tif err != nil {\n\t\t\tswitch e := err.(type) {\n\t\t\tcase *predicates.InsufficientResourceError:\n\t\t\t\tif fit {\n\t\t\t\t\terr := fmt.Errorf(\"got InsufficientResourceError: %v, but also fit='true' which is unexpected\", e)\n\t\t\t\t\treturn false, \"\", err\n\t\t\t\t}\n\t\t\tcase *predicates.PredicateFailureError:\n\t\t\t\tif fit {\n\t\t\t\t\terr := fmt.Errorf(\"got PredicateFailureError: %v, but also fit='true' which is unexpected\", e)\n\t\t\t\t\treturn false, \"\", err\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn false, \"\", err\n\t\t\t}\n\t\t}\n\t\tif !fit {\n\t\t\tif re, ok := err.(*predicates.InsufficientResourceError); ok {\n\t\t\t\treturn false, fmt.Sprintf(\"Insufficient %s\", re.ResourceName), nil\n\t\t\t}\n\t\t\tif re, ok := err.(*predicates.PredicateFailureError); ok {\n\t\t\t\treturn false, re.PredicateName, nil\n\t\t\t} else {\n\t\t\t\terr := fmt.Errorf(\"SchedulerPredicates failed due to %v, which is unexpected.\", err)\n\t\t\t\treturn false, \"\", err\n\t\t\t}\n\t\t}\n\t}\n\treturn true, \"\", nil\n}\n\n\/\/ Prioritizes the nodes by running the individual priority functions in parallel.\n\/\/ Each priority function is expected to set a score of 0-10\n\/\/ 0 is the lowest priority score (least preferred node) and 10 is the highest\n\/\/ Each priority function can also have its own weight\n\/\/ The node scores returned by the priority function are multiplied by the weights to get weighted scores\n\/\/ All scores are finally combined (added) to get the total weighted scores of all nodes\nfunc PrioritizeNodes(\n\tpod *api.Pod,\n\tnodeNameToInfo map[string]*schedulercache.NodeInfo,\n\tpriorityConfigs []algorithm.PriorityConfig,\n\tnodeLister algorithm.NodeLister,\n\textenders []algorithm.SchedulerExtender,\n) (schedulerapi.HostPriorityList, error) {\n\tresult := schedulerapi.HostPriorityList{}\n\n\t\/\/ If no priority configs are provided, then the EqualPriority function is applied\n\t\/\/ This is required to generate the priority list in the required format\n\tif len(priorityConfigs) == 0 && len(extenders) == 0 {\n\t\treturn EqualPriority(pod, nodeNameToInfo, nodeLister)\n\t}\n\n\tvar (\n\t\tmu             = sync.Mutex{}\n\t\twg             = sync.WaitGroup{}\n\t\tcombinedScores = map[string]int{}\n\t\terrs           []error\n\t)\n\n\tfor _, priorityConfig := range priorityConfigs {\n\t\t\/\/ skip the priority function if the weight is specified as 0\n\t\tif priorityConfig.Weight == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\twg.Add(1)\n\t\tgo func(config algorithm.PriorityConfig) {\n\t\t\tdefer wg.Done()\n\t\t\tweight := config.Weight\n\t\t\tpriorityFunc := config.Function\n\t\t\tprioritizedList, err := priorityFunc(pod, nodeNameToInfo, nodeLister)\n\n\t\t\tmu.Lock()\n\t\t\tdefer mu.Unlock()\n\t\t\tif err != nil {\n\t\t\t\terrs = append(errs, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfor i := range prioritizedList {\n\t\t\t\thost, score := prioritizedList[i].Host, prioritizedList[i].Score\n\t\t\t\tcombinedScores[host] += score * weight\n\t\t\t}\n\t\t}(priorityConfig)\n\t}\n\tif len(errs) != 0 {\n\t\treturn schedulerapi.HostPriorityList{}, errors.NewAggregate(errs)\n\t}\n\n\t\/\/ wait for all go routines to finish\n\twg.Wait()\n\n\tif len(extenders) != 0 && nodeLister != nil {\n\t\tnodes, err := nodeLister.List()\n\t\tif err != nil {\n\t\t\treturn schedulerapi.HostPriorityList{}, err\n\t\t}\n\t\tfor _, extender := range extenders {\n\t\t\twg.Add(1)\n\t\t\tgo func(ext algorithm.SchedulerExtender) {\n\t\t\t\tdefer wg.Done()\n\t\t\t\tprioritizedList, weight, err := ext.Prioritize(pod, &nodes)\n\t\t\t\tif err != nil {\n\t\t\t\t\t\/\/ Prioritization errors from extender can be ignored, let k8s\/other extenders determine the priorities\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tmu.Lock()\n\t\t\t\tfor i := range *prioritizedList {\n\t\t\t\t\thost, score := (*prioritizedList)[i].Host, (*prioritizedList)[i].Score\n\t\t\t\t\tcombinedScores[host] += score * weight\n\t\t\t\t}\n\t\t\t\tmu.Unlock()\n\t\t\t}(extender)\n\t\t}\n\t}\n\t\/\/ wait for all go routines to finish\n\twg.Wait()\n\n\tfor host, score := range combinedScores {\n\t\tglog.V(10).Infof(\"Host %s Score %d\", host, score)\n\t\tresult = append(result, schedulerapi.HostPriority{Host: host, Score: score})\n\t}\n\treturn result, nil\n}\n\n\/\/ EqualPriority is a prioritizer function that gives an equal weight of one to all nodes\nfunc EqualPriority(_ *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodeLister algorithm.NodeLister) (schedulerapi.HostPriorityList, error) {\n\tnodes, err := nodeLister.List()\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to list nodes: %v\", err)\n\t\treturn []schedulerapi.HostPriority{}, err\n\t}\n\n\tresult := []schedulerapi.HostPriority{}\n\tfor _, node := range nodes.Items {\n\t\tresult = append(result, schedulerapi.HostPriority{\n\t\t\tHost:  node.Name,\n\t\t\tScore: 1,\n\t\t})\n\t}\n\treturn result, nil\n}\n\nfunc NewGenericScheduler(cache schedulercache.Cache, predicates map[string]algorithm.FitPredicate, prioritizers []algorithm.PriorityConfig, extenders []algorithm.SchedulerExtender, random *rand.Rand) algorithm.ScheduleAlgorithm {\n\treturn &genericScheduler{\n\t\tcache:        cache,\n\t\tpredicates:   predicates,\n\t\tprioritizers: prioritizers,\n\t\textenders:    extenders,\n\t\trandom:       random,\n\t}\n}\n<commit_msg>Add the length detection of the \"predicateFuncs\" in generic_scheduler.go<commit_after>\/*\nCopyright 2014 The Kubernetes Authors All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage scheduler\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"math\/rand\"\n\t\"sort\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/golang\/glog\"\n\t\"k8s.io\/kubernetes\/pkg\/api\"\n\t\"k8s.io\/kubernetes\/pkg\/util\"\n\t\"k8s.io\/kubernetes\/pkg\/util\/errors\"\n\t\"k8s.io\/kubernetes\/pkg\/util\/workqueue\"\n\t\"k8s.io\/kubernetes\/plugin\/pkg\/scheduler\/algorithm\"\n\t\"k8s.io\/kubernetes\/plugin\/pkg\/scheduler\/algorithm\/predicates\"\n\tschedulerapi \"k8s.io\/kubernetes\/plugin\/pkg\/scheduler\/api\"\n\t\"k8s.io\/kubernetes\/plugin\/pkg\/scheduler\/schedulercache\"\n)\n\ntype FailedPredicateMap map[string]string\n\ntype FitError struct {\n\tPod              *api.Pod\n\tFailedPredicates FailedPredicateMap\n}\n\nvar ErrNoNodesAvailable = fmt.Errorf(\"no nodes available to schedule pods\")\n\n\/\/ Error returns detailed information of why the pod failed to fit on each node\nfunc (f *FitError) Error() string {\n\tvar buf bytes.Buffer\n\tbuf.WriteString(fmt.Sprintf(\"pod (%s) failed to fit in any node\\n\", f.Pod.Name))\n\tfor node, predicate := range f.FailedPredicates {\n\t\treason := fmt.Sprintf(\"fit failure on node (%s): %s\\n\", node, predicate)\n\t\tbuf.WriteString(reason)\n\t}\n\treturn buf.String()\n}\n\ntype genericScheduler struct {\n\tcache         schedulercache.Cache\n\tpredicates    map[string]algorithm.FitPredicate\n\tprioritizers  []algorithm.PriorityConfig\n\textenders     []algorithm.SchedulerExtender\n\tpods          algorithm.PodLister\n\trandom        *rand.Rand\n\trandomLock    sync.Mutex\n\tlastNodeIndex uint64\n}\n\n\/\/ Schedule tries to schedule the given pod to one of node in the node list.\n\/\/ If it succeeds, it will return the name of the node.\n\/\/ If it fails, it will return a Fiterror error with reasons.\nfunc (g *genericScheduler) Schedule(pod *api.Pod, nodeLister algorithm.NodeLister) (string, error) {\n\tvar trace *util.Trace\n\tif pod != nil {\n\t\ttrace = util.NewTrace(fmt.Sprintf(\"Scheduling %s\/%s\", pod.Namespace, pod.Name))\n\t} else {\n\t\ttrace = util.NewTrace(\"Scheduling <nil> pod\")\n\t}\n\tdefer trace.LogIfLong(20 * time.Millisecond)\n\n\tnodes, err := nodeLister.List()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif len(nodes.Items) == 0 {\n\t\treturn \"\", ErrNoNodesAvailable\n\t}\n\n\t\/\/ Used for all fit and priority funcs.\n\tnodeNameToInfo, err := g.cache.GetNodeNameToInfoMap()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\ttrace.Step(\"Computing predicates\")\n\tfilteredNodes, failedPredicateMap, err := findNodesThatFit(pod, nodeNameToInfo, g.predicates, nodes, g.extenders)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif len(filteredNodes.Items) == 0 {\n\t\treturn \"\", &FitError{\n\t\t\tPod:              pod,\n\t\t\tFailedPredicates: failedPredicateMap,\n\t\t}\n\t}\n\n\ttrace.Step(\"Prioritizing\")\n\tpriorityList, err := PrioritizeNodes(pod, nodeNameToInfo, g.prioritizers, algorithm.FakeNodeLister(filteredNodes), g.extenders)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\ttrace.Step(\"Selecting host\")\n\treturn g.selectHost(priorityList)\n}\n\n\/\/ selectHost takes a prioritized list of nodes and then picks one\n\/\/ randomly from the nodes that had the highest score.\nfunc (g *genericScheduler) selectHost(priorityList schedulerapi.HostPriorityList) (string, error) {\n\tif len(priorityList) == 0 {\n\t\treturn \"\", fmt.Errorf(\"empty priorityList\")\n\t}\n\n\tsort.Sort(sort.Reverse(priorityList))\n\tmaxScore := priorityList[0].Score\n\tfirstAfterMaxScore := sort.Search(len(priorityList), func(i int) bool { return priorityList[i].Score < maxScore })\n\n\tg.randomLock.Lock()\n\tix := int(g.lastNodeIndex % uint64(firstAfterMaxScore))\n\tg.lastNodeIndex++\n\tg.randomLock.Unlock()\n\n\treturn priorityList[ix].Host, nil\n}\n\n\/\/ Filters the nodes to find the ones that fit based on the given predicate functions\n\/\/ Each node is passed through the predicate functions to determine if it is a fit\nfunc findNodesThatFit(pod *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, predicateFuncs map[string]algorithm.FitPredicate, nodes api.NodeList, extenders []algorithm.SchedulerExtender) (api.NodeList, FailedPredicateMap, error) {\n\tfiltered := []api.Node{}\n\tfailedPredicateMap := FailedPredicateMap{}\n\n\tif len(predicateFuncs) == 0 {\n\t\tfiltered = nodes.Items\n\t} else {\n\t\tpredicateResultLock := sync.Mutex{}\n\t\terrs := []error{}\n\t\tcheckNode := func(i int) {\n\t\t\tnodeName := nodes.Items[i].Name\n\t\t\tfits, failedPredicate, err := podFitsOnNode(pod, nodeNameToInfo[nodeName], predicateFuncs)\n\t\n\t\t\tpredicateResultLock.Lock()\n\t\t\tdefer predicateResultLock.Unlock()\n\t\t\tif err != nil {\n\t\t\t\terrs = append(errs, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif fits {\n\t\t\t\tfiltered = append(filtered, nodes.Items[i])\n\t\t\t} else {\n\t\t\t\tfailedPredicateMap[nodeName] = failedPredicate\n\t\t\t}\n\t\t}\n\t\tworkqueue.Parallelize(16, len(nodes.Items), checkNode)\n\t\tif len(errs) > 0 {\n\t\t\treturn api.NodeList{}, FailedPredicateMap{}, errors.NewAggregate(errs)\n\t\t}\n\t}\n\n\tif len(filtered) > 0 && len(extenders) != 0 {\n\t\tfor _, extender := range extenders {\n\t\t\tfilteredList, err := extender.Filter(pod, &api.NodeList{Items: filtered})\n\t\t\tif err != nil {\n\t\t\t\treturn api.NodeList{}, FailedPredicateMap{}, err\n\t\t\t}\n\t\t\tfiltered = filteredList.Items\n\t\t\tif len(filtered) == 0 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn api.NodeList{Items: filtered}, failedPredicateMap, nil\n}\n\n\/\/ Checks whether node with a given name and NodeInfo satisfies all predicateFuncs.\nfunc podFitsOnNode(pod *api.Pod, info *schedulercache.NodeInfo, predicateFuncs map[string]algorithm.FitPredicate) (bool, string, error) {\n\tfor _, predicate := range predicateFuncs {\n\t\tfit, err := predicate(pod, info)\n\t\tif err != nil {\n\t\t\tswitch e := err.(type) {\n\t\t\tcase *predicates.InsufficientResourceError:\n\t\t\t\tif fit {\n\t\t\t\t\terr := fmt.Errorf(\"got InsufficientResourceError: %v, but also fit='true' which is unexpected\", e)\n\t\t\t\t\treturn false, \"\", err\n\t\t\t\t}\n\t\t\tcase *predicates.PredicateFailureError:\n\t\t\t\tif fit {\n\t\t\t\t\terr := fmt.Errorf(\"got PredicateFailureError: %v, but also fit='true' which is unexpected\", e)\n\t\t\t\t\treturn false, \"\", err\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\treturn false, \"\", err\n\t\t\t}\n\t\t}\n\t\tif !fit {\n\t\t\tif re, ok := err.(*predicates.InsufficientResourceError); ok {\n\t\t\t\treturn false, fmt.Sprintf(\"Insufficient %s\", re.ResourceName), nil\n\t\t\t}\n\t\t\tif re, ok := err.(*predicates.PredicateFailureError); ok {\n\t\t\t\treturn false, re.PredicateName, nil\n\t\t\t} else {\n\t\t\t\terr := fmt.Errorf(\"SchedulerPredicates failed due to %v, which is unexpected.\", err)\n\t\t\t\treturn false, \"\", err\n\t\t\t}\n\t\t}\n\t}\n\treturn true, \"\", nil\n}\n\n\/\/ Prioritizes the nodes by running the individual priority functions in parallel.\n\/\/ Each priority function is expected to set a score of 0-10\n\/\/ 0 is the lowest priority score (least preferred node) and 10 is the highest\n\/\/ Each priority function can also have its own weight\n\/\/ The node scores returned by the priority function are multiplied by the weights to get weighted scores\n\/\/ All scores are finally combined (added) to get the total weighted scores of all nodes\nfunc PrioritizeNodes(\n\tpod *api.Pod,\n\tnodeNameToInfo map[string]*schedulercache.NodeInfo,\n\tpriorityConfigs []algorithm.PriorityConfig,\n\tnodeLister algorithm.NodeLister,\n\textenders []algorithm.SchedulerExtender,\n) (schedulerapi.HostPriorityList, error) {\n\tresult := schedulerapi.HostPriorityList{}\n\n\t\/\/ If no priority configs are provided, then the EqualPriority function is applied\n\t\/\/ This is required to generate the priority list in the required format\n\tif len(priorityConfigs) == 0 && len(extenders) == 0 {\n\t\treturn EqualPriority(pod, nodeNameToInfo, nodeLister)\n\t}\n\n\tvar (\n\t\tmu             = sync.Mutex{}\n\t\twg             = sync.WaitGroup{}\n\t\tcombinedScores = map[string]int{}\n\t\terrs           []error\n\t)\n\n\tfor _, priorityConfig := range priorityConfigs {\n\t\t\/\/ skip the priority function if the weight is specified as 0\n\t\tif priorityConfig.Weight == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\twg.Add(1)\n\t\tgo func(config algorithm.PriorityConfig) {\n\t\t\tdefer wg.Done()\n\t\t\tweight := config.Weight\n\t\t\tpriorityFunc := config.Function\n\t\t\tprioritizedList, err := priorityFunc(pod, nodeNameToInfo, nodeLister)\n\n\t\t\tmu.Lock()\n\t\t\tdefer mu.Unlock()\n\t\t\tif err != nil {\n\t\t\t\terrs = append(errs, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfor i := range prioritizedList {\n\t\t\t\thost, score := prioritizedList[i].Host, prioritizedList[i].Score\n\t\t\t\tcombinedScores[host] += score * weight\n\t\t\t}\n\t\t}(priorityConfig)\n\t}\n\tif len(errs) != 0 {\n\t\treturn schedulerapi.HostPriorityList{}, errors.NewAggregate(errs)\n\t}\n\n\t\/\/ wait for all go routines to finish\n\twg.Wait()\n\n\tif len(extenders) != 0 && nodeLister != nil {\n\t\tnodes, err := nodeLister.List()\n\t\tif err != nil {\n\t\t\treturn schedulerapi.HostPriorityList{}, err\n\t\t}\n\t\tfor _, extender := range extenders {\n\t\t\twg.Add(1)\n\t\t\tgo func(ext algorithm.SchedulerExtender) {\n\t\t\t\tdefer wg.Done()\n\t\t\t\tprioritizedList, weight, err := ext.Prioritize(pod, &nodes)\n\t\t\t\tif err != nil {\n\t\t\t\t\t\/\/ Prioritization errors from extender can be ignored, let k8s\/other extenders determine the priorities\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tmu.Lock()\n\t\t\t\tfor i := range *prioritizedList {\n\t\t\t\t\thost, score := (*prioritizedList)[i].Host, (*prioritizedList)[i].Score\n\t\t\t\t\tcombinedScores[host] += score * weight\n\t\t\t\t}\n\t\t\t\tmu.Unlock()\n\t\t\t}(extender)\n\t\t}\n\t}\n\t\/\/ wait for all go routines to finish\n\twg.Wait()\n\n\tfor host, score := range combinedScores {\n\t\tglog.V(10).Infof(\"Host %s Score %d\", host, score)\n\t\tresult = append(result, schedulerapi.HostPriority{Host: host, Score: score})\n\t}\n\treturn result, nil\n}\n\n\/\/ EqualPriority is a prioritizer function that gives an equal weight of one to all nodes\nfunc EqualPriority(_ *api.Pod, nodeNameToInfo map[string]*schedulercache.NodeInfo, nodeLister algorithm.NodeLister) (schedulerapi.HostPriorityList, error) {\n\tnodes, err := nodeLister.List()\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to list nodes: %v\", err)\n\t\treturn []schedulerapi.HostPriority{}, err\n\t}\n\n\tresult := []schedulerapi.HostPriority{}\n\tfor _, node := range nodes.Items {\n\t\tresult = append(result, schedulerapi.HostPriority{\n\t\t\tHost:  node.Name,\n\t\t\tScore: 1,\n\t\t})\n\t}\n\treturn result, nil\n}\n\nfunc NewGenericScheduler(cache schedulercache.Cache, predicates map[string]algorithm.FitPredicate, prioritizers []algorithm.PriorityConfig, extenders []algorithm.SchedulerExtender, random *rand.Rand) algorithm.ScheduleAlgorithm {\n\treturn &genericScheduler{\n\t\tcache:        cache,\n\t\tpredicates:   predicates,\n\t\tprioritizers: prioritizers,\n\t\textenders:    extenders,\n\t\trandom:       random,\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 CodeIgnition. All rights reserved.\n\/\/ Use of this source code is governed by a BSD\n\/\/ license that can be found in the LICENSE file.\n\npackage policy\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\t\"time\"\n\n\t\"golang.org\/x\/net\/context\"\n)\n\nfunc fakePolicyHandler(ctx context.Context, p Policy) (<-chan Event, error) {\n\tfoo, ok := p.M[\"foo\"]\n\tif !ok {\n\t\treturn nil, errors.New(`\"foo\" key missing in fake policy`)\n\t}\n\tbar, ok := p.M[\"bar\"]\n\tif !ok {\n\t\treturn nil, errors.New(`\"bar\" key missing in fake policy`)\n\t}\n\tout := make(chan Event)\n\tgo func() {\n\t\tout <- Event{\n\t\t\tTime:   time.Now(),\n\t\t\tPolicy: p,\n\t\t\tData: map[string]interface{}{\n\t\t\t\t\"foo\": foo,\n\t\t\t\t\"bar\": bar,\n\t\t\t},\n\t\t}\n\t\tout <- Event{\n\t\t\tTime:   time.Now(),\n\t\t\tPolicy: p,\n\t\t\tData: map[string]interface{}{\n\t\t\t\t\"foo\": foo,\n\t\t\t\t\"bar\": bar,\n\t\t\t},\n\t\t}\n\t\tclose(out)\n\t}()\n\treturn out, nil\n}\n\nfunc TestNewHandler(t *testing.T) {\n\terr := NewHandler(\"\", fakePolicyHandler)\n\tif err == nil {\n\t\tt.Fatal(errors.New(\"NewHandler should return an error when the type is empty\"))\n\t}\n\terr = NewHandler(\"fake\", fakePolicyHandler)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestValid(t *testing.T) {\n\tp := Policy{\n\t\tName: \"\",\n\t}\n\tif err := p.Valid(); err == nil {\n\t\tt.Error(`want error \"policy name can't be empty\" got nil`)\n\t}\n\tp = Policy{\n\t\tName: \"dummy\",\n\t\tType: \"unknownDummyType\",\n\t}\n\tif err := p.Valid(); err == nil {\n\t\tt.Error(`want error \"policy type unknown\" got nil`)\n\t}\n}\n\nfunc TestExecute(t *testing.T) {\n\tp := Policy{\n\t\tName: \"dummy\",\n\t\tType: \"fake\",\n\t\tM: map[string]string{\n\t\t\t\"foo\": \"foo_value\",\n\t\t\t\"bar\": \"bar_value\",\n\t\t},\n\t}\n\tout, err := p.Execute(context.TODO())\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tvar count int\n\tfor evt := range out {\n\t\tcount++\n\t\tif evt.Data[\"foo\"] != \"foo_value\" {\n\t\t\tt.Errorf(`want evt.Data[\"foo\"] = %s; got %s`, \"foo\", evt.Data[\"foo\"])\n\t\t}\n\t\tif evt.Data[\"bar\"] != \"bar_value\" {\n\t\t\tt.Errorf(`want evt.Data[\"bar\"] = %s; got %s`, \"bar\", evt.Data[\"bar\"])\n\t\t}\n\t}\n\tif count != 2 {\n\t\tt.Errorf(`expected %d events; got %d events`, 2, count)\n\t}\n}\n<commit_msg>policy: test stopping policy execution using context cancel<commit_after>\/\/ Copyright 2015 CodeIgnition. All rights reserved.\n\/\/ Use of this source code is governed by a BSD\n\/\/ license that can be found in the LICENSE file.\n\npackage policy\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\t\"time\"\n\n\t\"golang.org\/x\/net\/context\"\n)\n\nfunc fakePolicyHandler(ctx context.Context, p Policy) (<-chan Event, error) {\n\tfoo, ok := p.M[\"foo\"]\n\tif !ok {\n\t\treturn nil, errors.New(`\"foo\" key missing in fake policy`)\n\t}\n\tinterval, ok := p.M[\"interval\"]\n\tif !ok {\n\t\treturn nil, errors.New(`\"interval\" key missing in fake policy`)\n\t}\n\td, err := time.ParseDuration(interval)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ This check is here to ensure time.Ticker(d) doesn't panic\n\tif d <= 0 {\n\t\treturn nil, errors.New(\"frequency must be a positive quantity\")\n\t}\n\n\tout := make(chan Event)\n\tgo func() {\n\t\tt := time.NewTicker(d)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\tt.Stop()\n\t\t\t\tclose(out)\n\t\t\t\treturn\n\t\t\tcase <-t.C:\n\t\t\t\tout <- Event{\n\t\t\t\t\tTime:   time.Now(),\n\t\t\t\t\tPolicy: p,\n\t\t\t\t\tData: map[string]interface{}{\n\t\t\t\t\t\t\"foo\": foo,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\treturn out, nil\n}\n\nfunc TestNewHandler(t *testing.T) {\n\terr := NewHandler(\"\", fakePolicyHandler)\n\tif err == nil {\n\t\tt.Fatal(errors.New(\"NewHandler should return an error when the type is empty\"))\n\t}\n\terr = NewHandler(\"fake\", fakePolicyHandler)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n}\n\nfunc TestValid(t *testing.T) {\n\tp := Policy{\n\t\tName: \"\",\n\t}\n\tif err := p.Valid(); err == nil {\n\t\tt.Error(`want error \"policy name can't be empty\" got nil`)\n\t}\n\tp = Policy{\n\t\tName: \"dummy\",\n\t\tType: \"unknownDummyType\",\n\t}\n\tif err := p.Valid(); err == nil {\n\t\tt.Error(`want error \"policy type unknown\" got nil`)\n\t}\n}\n\nfunc TestExecute(t *testing.T) {\n\tp := Policy{\n\t\tName: \"dummy\",\n\t\tType: \"fake\",\n\t\tM: map[string]string{\n\t\t\t\"foo\":      \"foo_value\",\n\t\t\t\"interval\": \"200ms\",\n\t\t},\n\t}\n\tctx, cancel := context.WithCancel(context.Background())\n\tout, err := p.Execute(ctx)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\tgo func() {\n\t\ttime.Sleep(1 * time.Second)\n\t\tcancel()\n\t}()\n\n\tvar count int\n\t\/\/ Here, we are also able to test whether out is being\n\t\/\/ closed when cancel() is called. If out is not closed,\n\t\/\/ this test should have been running forever.\n\tfor evt := range out {\n\t\tcount++\n\t\tif evt.Data[\"foo\"] != \"foo_value\" {\n\t\t\tt.Errorf(`want evt.Data[\"foo\"] = %s; got %s`, \"foo\", evt.Data[\"foo\"])\n\t\t}\n\t}\n\n\t\/\/ The interval for the dummy policy is 200ms.\n\t\/\/ We are calling cancel after 1 sec. Typically, we receive\n\t\/\/ 4 or 5 events in that duration.\n\tif count != 4 && count != 5 {\n\t\tt.Errorf(`want count to be either 4 or 5; got %d`, count)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright The Helm Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage action\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"syscall\"\n\n\t\"github.com\/Masterminds\/semver\/v3\"\n\t\"github.com\/pkg\/errors\"\n\t\"golang.org\/x\/crypto\/ssh\/terminal\"\n\n\t\"helm.sh\/helm\/v3\/pkg\/chart\"\n\t\"helm.sh\/helm\/v3\/pkg\/chart\/loader\"\n\t\"helm.sh\/helm\/v3\/pkg\/chartutil\"\n\t\"helm.sh\/helm\/v3\/pkg\/provenance\"\n)\n\n\/\/ Package is the action for packaging a chart.\n\/\/\n\/\/ It provides the implementation of 'helm package'.\ntype Package struct {\n\tSign             bool\n\tKey              string\n\tKeyring          string\n\tVersion          string\n\tAppVersion       string\n\tDestination      string\n\tDependencyUpdate bool\n\n\tRepositoryConfig string\n\tRepositoryCache  string\n}\n\n\/\/ NewPackage creates a new Package object with the given configuration.\nfunc NewPackage() *Package {\n\treturn &Package{}\n}\n\n\/\/ Run executes 'helm package' against the given chart and returns the path to the packaged chart.\nfunc (p *Package) Run(path string, vals map[string]interface{}) (string, error) {\n\tch, err := loader.LoadDir(path)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t\/\/ If version is set, modify the version.\n\tif p.Version != \"\" {\n\t\tif err := setVersion(ch, p.Version); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\tif p.AppVersion != \"\" {\n\t\tch.Metadata.AppVersion = p.AppVersion\n\t}\n\n\tif reqs := ch.Metadata.Dependencies; reqs != nil {\n\t\tif err := CheckDependencies(ch, reqs); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\tvar dest string\n\tif p.Destination == \".\" {\n\t\t\/\/ Save to the current working directory.\n\t\tdest, err = os.Getwd()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t} else {\n\t\t\/\/ Otherwise save to set destination\n\t\tdest = p.Destination\n\t}\n\n\tname, err := chartutil.Save(ch, dest)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"failed to save\")\n\t}\n\n\tif p.Sign {\n\t\terr = p.Clearsign(name)\n\t}\n\n\treturn name, err\n}\n\nfunc setVersion(ch *chart.Chart, ver string) error {\n\t\/\/ Verify that version is a Version, and error out if it is not.\n\tif _, err := semver.NewVersion(ver); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Set the version field on the chart.\n\tch.Metadata.Version = ver\n\treturn nil\n}\n\n\/\/ Clearsign signs a chart\nfunc (p *Package) Clearsign(filename string) error {\n\t\/\/ Load keyring\n\tsigner, err := provenance.NewFromKeyring(p.Keyring, p.Key)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := signer.DecryptKey(promptUser); err != nil {\n\t\treturn err\n\t}\n\n\tsig, err := signer.ClearSign(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn ioutil.WriteFile(filename+\".prov\", []byte(sig), 0644)\n}\n\n\/\/ promptUser implements provenance.PassphraseFetcher\nfunc promptUser(name string) ([]byte, error) {\n\tfmt.Printf(\"Password for key %q >  \", name)\n\tpw, err := terminal.ReadPassword(syscall.Stdin)\n\tfmt.Println()\n\treturn pw, err\n}\n<commit_msg>Fixing failing CI for windows<commit_after>\/*\nCopyright The Helm Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage action\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"syscall\"\n\n\t\"github.com\/Masterminds\/semver\/v3\"\n\t\"github.com\/pkg\/errors\"\n\t\"golang.org\/x\/crypto\/ssh\/terminal\"\n\n\t\"helm.sh\/helm\/v3\/pkg\/chart\"\n\t\"helm.sh\/helm\/v3\/pkg\/chart\/loader\"\n\t\"helm.sh\/helm\/v3\/pkg\/chartutil\"\n\t\"helm.sh\/helm\/v3\/pkg\/provenance\"\n)\n\n\/\/ Package is the action for packaging a chart.\n\/\/\n\/\/ It provides the implementation of 'helm package'.\ntype Package struct {\n\tSign             bool\n\tKey              string\n\tKeyring          string\n\tVersion          string\n\tAppVersion       string\n\tDestination      string\n\tDependencyUpdate bool\n\n\tRepositoryConfig string\n\tRepositoryCache  string\n}\n\n\/\/ NewPackage creates a new Package object with the given configuration.\nfunc NewPackage() *Package {\n\treturn &Package{}\n}\n\n\/\/ Run executes 'helm package' against the given chart and returns the path to the packaged chart.\nfunc (p *Package) Run(path string, vals map[string]interface{}) (string, error) {\n\tch, err := loader.LoadDir(path)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t\/\/ If version is set, modify the version.\n\tif p.Version != \"\" {\n\t\tif err := setVersion(ch, p.Version); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\tif p.AppVersion != \"\" {\n\t\tch.Metadata.AppVersion = p.AppVersion\n\t}\n\n\tif reqs := ch.Metadata.Dependencies; reqs != nil {\n\t\tif err := CheckDependencies(ch, reqs); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\tvar dest string\n\tif p.Destination == \".\" {\n\t\t\/\/ Save to the current working directory.\n\t\tdest, err = os.Getwd()\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t} else {\n\t\t\/\/ Otherwise save to set destination\n\t\tdest = p.Destination\n\t}\n\n\tname, err := chartutil.Save(ch, dest)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"failed to save\")\n\t}\n\n\tif p.Sign {\n\t\terr = p.Clearsign(name)\n\t}\n\n\treturn name, err\n}\n\nfunc setVersion(ch *chart.Chart, ver string) error {\n\t\/\/ Verify that version is a Version, and error out if it is not.\n\tif _, err := semver.NewVersion(ver); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Set the version field on the chart.\n\tch.Metadata.Version = ver\n\treturn nil\n}\n\n\/\/ Clearsign signs a chart\nfunc (p *Package) Clearsign(filename string) error {\n\t\/\/ Load keyring\n\tsigner, err := provenance.NewFromKeyring(p.Keyring, p.Key)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := signer.DecryptKey(promptUser); err != nil {\n\t\treturn err\n\t}\n\n\tsig, err := signer.ClearSign(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn ioutil.WriteFile(filename+\".prov\", []byte(sig), 0644)\n}\n\n\/\/ promptUser implements provenance.PassphraseFetcher\nfunc promptUser(name string) ([]byte, error) {\n\tfmt.Printf(\"Password for key %q >  \", name)\n\t\/\/ syscall.Stdin is not an int in all environments and needs to be coerced\n\t\/\/ into one there (e.g., Windows)\n\tpw, err := terminal.ReadPassword(int(syscall.Stdin))\n\tfmt.Println()\n\treturn pw, err\n}\n<|endoftext|>"}
{"text":"<commit_before>package api\n\nimport (\n\t\"context\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/go-chi\/chi\/middleware\"\n\t\"github.com\/go-kit\/kit\/log\"\n\t\"github.com\/go-kit\/kit\/log\/level\"\n\t\"github.com\/satori\/go.uuid\"\n)\n\ntype contextValue string\n\nconst contextReqID contextValue = \"request_id\"\n\n\/\/NewRequestID creates a middleware that passes X-Request-ID via contenxt or creates a new ID\nfunc NewRequestID(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\treqID := r.Header.Get(\"X-Request-ID\")\n\t\tif reqID == \"\" {\n\t\t\treqID = uuid.NewV4().String()\n\t\t}\n\n\t\tr = r.WithContext(context.WithValue(r.Context(), contextReqID, reqID))\n\n\t\tnext.ServeHTTP(w, r)\n\t})\n}\n\n\/\/GetRequestID returns the request ID from context.Context\nfunc GetRequestID(ctx context.Context) string {\n\tvalue := ctx.Value(contextReqID)\n\tif reqID, ok := value.(string); ok {\n\t\treturn reqID\n\t}\n\treturn \"\"\n}\n\n\/\/NewRequestLogger creates a middleware that logs all HTTP request information\nfunc NewRequestLogger(logger log.Logger) func(next http.Handler) http.Handler {\n\treturn func(next http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tstart := time.Now()\n\n\t\t\tww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)\n\t\t\tnext.ServeHTTP(ww, r)\n\n\t\t\tlevel.Debug(logger).Log(\n\t\t\t\t\"request\", GetRequestID(r.Context()),\n\t\t\t\t\"proto\", r.Proto,\n\t\t\t\t\"method\", r.Method,\n\t\t\t\t\"status\", ww.Status(),\n\t\t\t\t\"path\", r.URL.Path,\n\t\t\t\t\"duration\", time.Since(start),\n\t\t\t\t\"bytes\", ww.BytesWritten(),\n\t\t\t)\n\t\t})\n\t}\n}\n<commit_msg>Fix typo in pkg\/api\/request_id.go<commit_after>package api\n\nimport (\n\t\"context\"\n\t\"net\/http\"\n\t\"time\"\n\n\t\"github.com\/go-chi\/chi\/middleware\"\n\t\"github.com\/go-kit\/kit\/log\"\n\t\"github.com\/go-kit\/kit\/log\/level\"\n\t\"github.com\/satori\/go.uuid\"\n)\n\ntype contextValue string\n\nconst contextReqID contextValue = \"request_id\"\n\n\/\/NewRequestID creates a middleware that passes X-Request-ID via context or creates a new ID\nfunc NewRequestID(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\treqID := r.Header.Get(\"X-Request-ID\")\n\t\tif reqID == \"\" {\n\t\t\treqID = uuid.NewV4().String()\n\t\t}\n\n\t\tr = r.WithContext(context.WithValue(r.Context(), contextReqID, reqID))\n\n\t\tnext.ServeHTTP(w, r)\n\t})\n}\n\n\/\/GetRequestID returns the request ID from context.Context\nfunc GetRequestID(ctx context.Context) string {\n\tvalue := ctx.Value(contextReqID)\n\tif reqID, ok := value.(string); ok {\n\t\treturn reqID\n\t}\n\treturn \"\"\n}\n\n\/\/NewRequestLogger creates a middleware that logs all HTTP request information\nfunc NewRequestLogger(logger log.Logger) func(next http.Handler) http.Handler {\n\treturn func(next http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tstart := time.Now()\n\n\t\t\tww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)\n\t\t\tnext.ServeHTTP(ww, r)\n\n\t\t\tlevel.Debug(logger).Log(\n\t\t\t\t\"request\", GetRequestID(r.Context()),\n\t\t\t\t\"proto\", r.Proto,\n\t\t\t\t\"method\", r.Method,\n\t\t\t\t\"status\", ww.Status(),\n\t\t\t\t\"path\", r.URL.Path,\n\t\t\t\t\"duration\", time.Since(start),\n\t\t\t\t\"bytes\", ww.BytesWritten(),\n\t\t\t)\n\t\t})\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package api\n\nimport \"testing\"\n\nfunc TestVolumeListSet(t *testing.T) {\n\ttable := map[string][]VolumeSpec{\n\t\t\"\/test:\":             {{Source: \"\/test\", Destination: \".\"}},\n\t\t\"\/test:\/test\":        {{Source: \"\/test\", Destination: \"\/test\"}},\n\t\t\"\/test\/foo:\/etc\/ssl\": {{Source: \"\/test\/foo\", Destination: \"\/etc\/ssl\"}},\n\t\t\":\/foo\":              {{Source: \".\", Destination: \"\/foo\"}},\n\t\t\"\/foo\":               {{Source: \"\/foo\", Destination: \".\"}},\n\t\t\":\":                  {{Source: \".\", Destination: \".\"}},\n\t\t\"\/t est\/foo:\":        {{Source: \"\/t est\/foo\", Destination: \".\"}},\n\t\t`\"\/test\":\"\/foo\"`:     {{Source: \"\/test\", Destination: \"\/foo\"}},\n\t\t`'\/test':\"\/foo\"`:     {{Source: \"\/test\", Destination: \"\/foo\"}},\n\t\t`\"\/te\"st\":\"\/foo\"`:    {},\n\t\t\"\/test\/foo:\/ss;ss\":   {},\n\t\t\"\/test;foo:\/ssss\":    {},\n\t}\n\tfor v, expected := range table {\n\t\tgot := VolumeList{}\n\t\terr := got.Set(v)\n\t\tif len(expected) == 0 {\n\t\t\tif err == nil {\n\t\t\t\tt.Errorf(\"Expected error for %q, got %#v\", v, got)\n\t\t\t} else {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tif len(got) != len(expected) {\n\t\t\tt.Errorf(\"Expected %d injection in the list for %q, got %d\", len(expected), v, len(got))\n\t\t}\n\t\tfor _, exp := range expected {\n\t\t\tfound := false\n\t\t\tfor _, g := range got {\n\t\t\t\tif g.Source == exp.Source && g.Destination == exp.Destination {\n\t\t\t\t\tfound = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !found {\n\t\t\t\tt.Errorf(\"Expected %+v injection found in %#v list\", exp, got)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestEnvironmentSet(t *testing.T) {\n\ttable := map[string][]EnvironmentSpec{\n\t\t\"FOO=bar\":  {{Name: \"FOO\", Value: \"bar\"}},\n\t\t\"FOO=\":     {{Name: \"FOO\", Value: \"\"}},\n\t\t\"FOO\":      {},\n\t\t\"=\":        {},\n\t\t\"FOO=bar,\": {{Name: \"FOO\", Value: \"bar,\"}},\n\t\t\/\/ Users should get a deprecation warning in this case\n\t\t\/\/ TODO: Create fake glog interface to be able to verify this.\n\t\t\"FOO=bar,BAR=foo\": {{Name: \"FOO\", Value: \"bar,BAR=foo\"}},\n\t}\n\n\tfor v, expected := range table {\n\t\tgot := EnvironmentList{}\n\t\terr := got.Set(v)\n\t\tif len(expected) == 0 && err == nil {\n\t\t\tt.Errorf(\"Expected error for env %q\", v)\n\t\t\tcontinue\n\t\t}\n\t\tif len(expected) != len(got) {\n\t\t\tt.Errorf(\"got %d items, expected %d items in the list for %q\", len(got), len(expected), v)\n\t\t\tcontinue\n\t\t}\n\t\tfor _, exp := range expected {\n\t\t\tfound := false\n\t\t\tfor _, g := range got {\n\t\t\t\tif g.Name == exp.Name && g.Value == exp.Value {\n\t\t\t\t\tfound = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !found {\n\t\t\t\tt.Errorf(\"Expected %+v environment found in %#v list\", exp, got)\n\t\t\t}\n\t\t}\n\t}\n}\n<commit_msg>if found = true, add break is better<commit_after>package api\n\nimport \"testing\"\n\nfunc TestVolumeListSet(t *testing.T) {\n\ttable := map[string][]VolumeSpec{\n\t\t\"\/test:\":             {{Source: \"\/test\", Destination: \".\"}},\n\t\t\"\/test:\/test\":        {{Source: \"\/test\", Destination: \"\/test\"}},\n\t\t\"\/test\/foo:\/etc\/ssl\": {{Source: \"\/test\/foo\", Destination: \"\/etc\/ssl\"}},\n\t\t\":\/foo\":              {{Source: \".\", Destination: \"\/foo\"}},\n\t\t\"\/foo\":               {{Source: \"\/foo\", Destination: \".\"}},\n\t\t\":\":                  {{Source: \".\", Destination: \".\"}},\n\t\t\"\/t est\/foo:\":        {{Source: \"\/t est\/foo\", Destination: \".\"}},\n\t\t`\"\/test\":\"\/foo\"`:     {{Source: \"\/test\", Destination: \"\/foo\"}},\n\t\t`'\/test':\"\/foo\"`:     {{Source: \"\/test\", Destination: \"\/foo\"}},\n\t\t`\"\/te\"st\":\"\/foo\"`:    {},\n\t\t\"\/test\/foo:\/ss;ss\":   {},\n\t\t\"\/test;foo:\/ssss\":    {},\n\t}\n\tfor v, expected := range table {\n\t\tgot := VolumeList{}\n\t\terr := got.Set(v)\n\t\tif len(expected) == 0 {\n\t\t\tif err == nil {\n\t\t\t\tt.Errorf(\"Expected error for %q, got %#v\", v, got)\n\t\t\t} else {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tif len(got) != len(expected) {\n\t\t\tt.Errorf(\"Expected %d injection in the list for %q, got %d\", len(expected), v, len(got))\n\t\t}\n\t\tfor _, exp := range expected {\n\t\t\tfound := false\n\t\t\tfor _, g := range got {\n\t\t\t\tif g.Source == exp.Source && g.Destination == exp.Destination {\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\tt.Errorf(\"Expected %+v injection found in %#v list\", exp, got)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestEnvironmentSet(t *testing.T) {\n\ttable := map[string][]EnvironmentSpec{\n\t\t\"FOO=bar\":  {{Name: \"FOO\", Value: \"bar\"}},\n\t\t\"FOO=\":     {{Name: \"FOO\", Value: \"\"}},\n\t\t\"FOO\":      {},\n\t\t\"=\":        {},\n\t\t\"FOO=bar,\": {{Name: \"FOO\", Value: \"bar,\"}},\n\t\t\/\/ Users should get a deprecation warning in this case\n\t\t\/\/ TODO: Create fake glog interface to be able to verify this.\n\t\t\"FOO=bar,BAR=foo\": {{Name: \"FOO\", Value: \"bar,BAR=foo\"}},\n\t}\n\n\tfor v, expected := range table {\n\t\tgot := EnvironmentList{}\n\t\terr := got.Set(v)\n\t\tif len(expected) == 0 && err == nil {\n\t\t\tt.Errorf(\"Expected error for env %q\", v)\n\t\t\tcontinue\n\t\t}\n\t\tif len(expected) != len(got) {\n\t\t\tt.Errorf(\"got %d items, expected %d items in the list for %q\", len(got), len(expected), v)\n\t\t\tcontinue\n\t\t}\n\t\tfor _, exp := range expected {\n\t\t\tfound := false\n\t\t\tfor _, g := range got {\n\t\t\t\tif g.Name == exp.Name && g.Value == exp.Value {\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\tt.Errorf(\"Expected %+v environment found in %#v list\", exp, got)\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package utils\n\nimport (\n\t\"io\"\n\t\"net\/http\"\n\t\"net\/textproto\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\/\/ ServeContent replies to the request using the content in the provided\n\/\/ reader. The Content-Length and Content-Type headers are added with the\n\/\/ provided values.\nfunc ServeContent(w http.ResponseWriter, r *http.Request, contentType string, size int64, content io.Reader) {\n\th := w.Header()\n\tif size > 0 {\n\t\th.Set(\"Content-Length\", strconv.FormatInt(size, 10))\n\t}\n\tif contentType != \"\" {\n\t\th.Set(\"Content-Type\", contentType)\n\t}\n\tw.WriteHeader(http.StatusOK)\n\tif r.Method != \"HEAD\" {\n\t\tio.Copy(w, content)\n\t}\n}\n\n\/\/ CheckPreconditions evaluates request preconditions based only on the Etag\n\/\/ values.\nfunc CheckPreconditions(w http.ResponseWriter, r *http.Request, etag string) (done bool) {\n\tif etag != \"\" && !checkIfNoneMatch(w, r, etag) {\n\t\twriteNotModified(w)\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc checkIfNoneMatch(w http.ResponseWriter, r *http.Request, definedETag string) (match bool) {\n\tinm := r.Header.Get(\"If-None-Match\")\n\tif inm == \"\" {\n\t\treturn false\n\t}\n\tbuf := inm\n\tfor {\n\t\tbuf = textproto.TrimString(buf)\n\t\tif len(buf) == 0 {\n\t\t\tbreak\n\t\t}\n\t\tif buf[0] == ',' {\n\t\t\tbuf = buf[1:]\n\t\t}\n\t\tif buf[0] == '*' {\n\t\t\treturn false\n\t\t}\n\t\tetag, remain := scanETag(buf)\n\t\tif etag == \"\" {\n\t\t\tbreak\n\t\t}\n\t\tif etagWeakMatch(etag, definedETag) {\n\t\t\treturn false\n\t\t}\n\t\tbuf = remain\n\t}\n\treturn true\n}\n\n\/\/ etagWeakMatch reports whether a and b match using weak ETag comparison.\n\/\/ Assumes a and b are valid ETags.\nfunc etagWeakMatch(a, b string) bool {\n\treturn strings.TrimPrefix(a, \"W\/\") == strings.TrimPrefix(b, \"W\/\")\n}\n\n\/\/ etagStrongMatch reports whether a and b match using strong ETag comparison.\n\/\/ Assumes a and b are valid ETags.\nfunc etagStrongMatch(a, b string) bool {\n\treturn a == b && a != \"\" && a[0] == '\"'\n}\n\n\/\/ scanETag determines if a syntactically valid ETag is present at s. If so,\n\/\/ the ETag and remaining text after consuming ETag is returned. Otherwise,\n\/\/ it returns \"\", \"\".\nfunc scanETag(s string) (etag string, remain string) {\n\tstart := 0\n\tif len(s) >= 2 && s[0] == 'W' && s[1] == '\/' {\n\t\tstart = 2\n\t}\n\tif len(s[start:]) < 2 || s[start] != '\"' {\n\t\treturn \"\", \"\"\n\t}\n\t\/\/ ETag is either W\/\"text\" or \"text\".\n\t\/\/ See RFC 7232 2.3.\n\tfor i := start + 1; i < len(s); i++ {\n\t\tc := s[i]\n\t\tswitch {\n\t\t\/\/ Character values allowed in ETags.\n\t\tcase c == 0x21 || c >= 0x23 && c <= 0x7E || c >= 0x80:\n\t\tcase c == '\"':\n\t\t\treturn s[:i+1], s[i+1:]\n\t\tdefault:\n\t\t\treturn \"\", \"\"\n\t\t}\n\t}\n\treturn \"\", \"\"\n}\n\nfunc writeNotModified(w http.ResponseWriter) {\n\th := w.Header()\n\tdelete(h, \"Content-Type\")\n\tdelete(h, \"Content-Length\")\n\tw.WriteHeader(http.StatusNotModified)\n}\n<commit_msg>Keep content-type and content-length in unmodified response<commit_after>package utils\n\nimport (\n\t\"io\"\n\t\"net\/http\"\n\t\"net\/textproto\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\/\/ ServeContent replies to the request using the content in the provided\n\/\/ reader. The Content-Length and Content-Type headers are added with the\n\/\/ provided values.\nfunc ServeContent(w http.ResponseWriter, r *http.Request, contentType string, size int64, content io.Reader) {\n\th := w.Header()\n\tif size > 0 {\n\t\th.Set(\"Content-Length\", strconv.FormatInt(size, 10))\n\t}\n\tif contentType != \"\" {\n\t\th.Set(\"Content-Type\", contentType)\n\t}\n\tw.WriteHeader(http.StatusOK)\n\tif r.Method != \"HEAD\" {\n\t\tio.Copy(w, content)\n\t}\n}\n\n\/\/ CheckPreconditions evaluates request preconditions based only on the Etag\n\/\/ values.\nfunc CheckPreconditions(w http.ResponseWriter, r *http.Request, etag string) (done bool) {\n\tif etag != \"\" && !checkIfNoneMatch(w, r, etag) {\n\t\tw.WriteHeader(http.StatusNotModified)\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc checkIfNoneMatch(w http.ResponseWriter, r *http.Request, definedETag string) (match bool) {\n\tinm := r.Header.Get(\"If-None-Match\")\n\tif inm == \"\" {\n\t\treturn false\n\t}\n\tbuf := inm\n\tfor {\n\t\tbuf = textproto.TrimString(buf)\n\t\tif len(buf) == 0 {\n\t\t\tbreak\n\t\t}\n\t\tif buf[0] == ',' {\n\t\t\tbuf = buf[1:]\n\t\t}\n\t\tif buf[0] == '*' {\n\t\t\treturn false\n\t\t}\n\t\tetag, remain := scanETag(buf)\n\t\tif etag == \"\" {\n\t\t\tbreak\n\t\t}\n\t\tif etagWeakMatch(etag, definedETag) {\n\t\t\treturn false\n\t\t}\n\t\tbuf = remain\n\t}\n\treturn true\n}\n\n\/\/ etagWeakMatch reports whether a and b match using weak ETag comparison.\n\/\/ Assumes a and b are valid ETags.\nfunc etagWeakMatch(a, b string) bool {\n\treturn strings.TrimPrefix(a, \"W\/\") == strings.TrimPrefix(b, \"W\/\")\n}\n\n\/\/ etagStrongMatch reports whether a and b match using strong ETag comparison.\n\/\/ Assumes a and b are valid ETags.\nfunc etagStrongMatch(a, b string) bool {\n\treturn a == b && a != \"\" && a[0] == '\"'\n}\n\n\/\/ scanETag determines if a syntactically valid ETag is present at s. If so,\n\/\/ the ETag and remaining text after consuming ETag is returned. Otherwise,\n\/\/ it returns \"\", \"\".\nfunc scanETag(s string) (etag string, remain string) {\n\tstart := 0\n\tif len(s) >= 2 && s[0] == 'W' && s[1] == '\/' {\n\t\tstart = 2\n\t}\n\tif len(s[start:]) < 2 || s[start] != '\"' {\n\t\treturn \"\", \"\"\n\t}\n\t\/\/ ETag is either W\/\"text\" or \"text\".\n\t\/\/ See RFC 7232 2.3.\n\tfor i := start + 1; i < len(s); i++ {\n\t\tc := s[i]\n\t\tswitch {\n\t\t\/\/ Character values allowed in ETags.\n\t\tcase c == 0x21 || c >= 0x23 && c <= 0x7E || c >= 0x80:\n\t\tcase c == '\"':\n\t\t\treturn s[:i+1], s[i+1:]\n\t\tdefault:\n\t\t\treturn \"\", \"\"\n\t\t}\n\t}\n\treturn \"\", \"\"\n}\n<|endoftext|>"}
{"text":"<commit_before>package annotation\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com\/m-lab\/etl\/web100\"\n\n\t\"github.com\/m-lab\/etl\/metrics\"\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n)\n\nvar IPAnnotationEnabled = false\n\nfunc init() {\n\tgetFlagValues()\n}\n\nfunc getFlagValues() {\n\t\/\/ Check for ANNOTATE_IP = 'true'\n\tflag, ok := os.LookupEnv(\"ANNOTATE_IP\")\n\tif ok {\n\t\tIPAnnotationEnabled, _ = strconv.ParseBool(flag)\n\t\t\/\/ If parse fails, then ipAnn will be set to false.\n\t}\n}\n\n\/\/ EnableAnnotation is used only for testing.  Should be placed in whitebox _test file.\nfunc EnableAnnotation() {\n\tos.Setenv(\"ANNOTATE_IP\", \"True\")\n\tgetFlagValues()\n}\n\n\/\/ The GeolocationIP struct contains all the information needed for the\n\/\/ geolocation data that will be inserted into big query. The fiels are\n\/\/ capitalized for exporting, although the originals in the DB schema\n\/\/ are not.\ntype GeolocationIP struct {\n\tContinent_code string  `json:\"continent_code,string,omitempty\"` \/\/ Gives a shorthand for the continent\n\tCountry_code   string  `json:\"country_code,string,omitempty\"`   \/\/ Gives a shorthand for the country\n\tCountry_code3  string  `json:\"country_code3,string,omitempty\"`  \/\/ Gives a shorthand for the country\n\tCountry_name   string  `json:\"country_name,string,omitempty\"`   \/\/ Name of the country\n\tRegion         string  `json:\"region,string,omitempty\"`         \/\/ Region or State within the country\n\tMetro_code     int64   `json:\"metro_code,integer,omitempty\"`    \/\/ Metro code within the country\n\tCity           string  `json:\"city,string,omitempty\"`           \/\/ City within the region\n\tArea_code      int64   `json:\"area_code,integer,omitempty\"`     \/\/ Area code, similar to metro code\n\tPostal_code    string  `json:\"postal_code,string,omitempty\"`    \/\/ Postal code, again similar to metro\n\tLatitude       float64 `json:\"latitude,float\"`                  \/\/ Latitude\n\tLongitude      float64 `json:\"longitude,float\"`                 \/\/ Longitude\n\n}\n\n\/\/ The struct that will hold the IP\/ASN data when it gets added to the\n\/\/ schema. Currently empty and unused.\ntype IPASNData struct{}\n\n\/\/ The main struct for the geo metadata, which holds pointers to the\n\/\/ Geolocation data and the IP\/ASN data. This is what we parse the JSON\n\/\/ response from the annotator into.\ntype GeoData struct {\n\tGeo *GeolocationIP \/\/ Holds the geolocation data\n\tASN *IPASNData     \/\/ Holds the IP\/ASN data\n}\n\n\/\/ The RequestData schema is the schema for the json that we will send\n\/\/ down the pipe to the annotation service.\ntype RequestData struct {\n\tIP        string    \/\/ Holds the IP from an incoming request\n\tIPFormat  int       \/\/ Holds the ip format, 4 or 6\n\tTimestamp time.Time \/\/ Holds the timestamp from an incoming request\n}\n\n\/\/ AnnotatorURL holds the https address of the annotator.\n\/\/ TODO(gfr) See if there is a better way of determining\n\/\/ where to send the request (there almost certainly is)\nvar AnnotatorURL = \"https:\/\/annotator-dot-\" +\n\tos.Getenv(\"GCLOUD_PROJECT\") +\n\t\".appspot.com\"\n\n\/\/ BaseURL provides the base URL for single annotation requests\nvar BaseURL = AnnotatorURL + \"\/annotate?\"\n\n\/\/ BatchURL provides the base URL for batch annotation requests\nvar BatchURL = AnnotatorURL + \"\/batch_annotate\"\n\n\/\/ FetchGeoAnnotations takes a slice of strings\n\/\/ containing ip addresses, a timestamp, and a slice of pointers to\n\/\/ the GeolocationIP structs that correspond to the ip addresses. A\n\/\/ precondition assumed by this function is that both slices are the\n\/\/ same length. It will then make a call to the batch annotator, using\n\/\/ the ip addresses and the timestamp. Then, it uses that data to fill\n\/\/ in the structs pointed to by the slice of GeolocationIP pointers.\nfunc FetchGeoAnnotations(ips []string, timestamp time.Time, geoDest []*GeolocationIP) {\n\treqData := make([]RequestData, 0, len(ips))\n\tnormalized := make([]string, len(ips))\n\tfor i := range ips {\n\t\tif ips[i] == \"\" {\n\t\t\t\/\/ TODO(gfr) These should be warning, else we have error > request\n\t\t\tmetrics.AnnotationErrorCount.With(prometheus.\n\t\t\t\tLabels{\"source\": \"Empty IP Address!!!\"}).Inc()\n\t\t\tcontinue\n\t\t}\n\t\tvar err error\n\t\tnormalized[i], err = web100.NormalizeIPv6(ips[i])\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t\treqData = append(reqData, RequestData{normalized[i], 0, timestamp})\n\t}\n\tannotationData := GetBatchGeoData(BatchURL, reqData)\n\ttimeString := strconv.FormatInt(timestamp.Unix(), 36)\n\tfor i := range normalized {\n\t\tdata, ok := annotationData[normalized[i]+timeString]\n\t\tif !ok || data.Geo == nil {\n\t\t\t\/\/ TODO(gfr) These should be warning, else we have error > request\n\t\t\tmetrics.AnnotationErrorCount.With(prometheus.\n\t\t\t\tLabels{\"source\": \"Missing or empty data for IP Address!!!\"}).Inc()\n\t\t\tcontinue\n\t\t}\n\t\t*geoDest[i] = *data.Geo\n\t}\n}\n\n\/\/ GetAndInsertGeolocationIPStruct takes a NON-NIL pointer to a\n\/\/ pre-allocated GeolocationIP struct, an IP address, and a\n\/\/ timestamp. It will connect to the annotation service, get the\n\/\/ geo data, and insert the geo data into the reigion pointed to by\n\/\/ the GeolocationIP pointer.\nfunc GetAndInsertGeolocationIPStruct(geo *GeolocationIP, ip string, timestamp time.Time) {\n\turl := BaseURL + \"ip_addr=\" + url.QueryEscape(ip) +\n\t\t\"&since_epoch=\" + strconv.FormatInt(timestamp.Unix(), 10)\n\tannotationData := GetGeoData(url)\n\tif annotationData != nil && annotationData.Geo != nil {\n\t\t*geo = *annotationData.Geo\n\t}\n}\n\n\/\/ GetGeoData combines the functionality of QueryAnnotationService and\n\/\/ ParseJSONGeoDataResponse to query the annotator service and return\n\/\/ the corresponding GeoData if it can, or a nil pointer if it\n\/\/ encounters any error and cannot get the data for any reason\nfunc GetGeoData(url string) *GeoData {\n\t\/\/ Query the service and grab the response safely\n\tannotatorResponse, err := QueryAnnotationService(url)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn nil\n\t}\n\n\t\/\/ Safely parse the JSON response and pass it back to the caller\n\tgeoDataFromResponse, err := ParseJSONGeoDataResponse(annotatorResponse)\n\tif err != nil {\n\t\tmetrics.AnnotationErrorCount.With(prometheus.\n\t\t\tLabels{\"source\": \"Failed to parse JSON\"}).Inc()\n\t\tlog.Println(err)\n\t\treturn nil\n\t}\n\treturn geoDataFromResponse\n}\n\n\/\/ QueryAnnotationService will connect to the annotation service and\n\/\/ copy the body of a valid response to a byte slice and return it to a\n\/\/ user, returning an error if any occurs\nfunc QueryAnnotationService(url string) ([]byte, error) {\n\tmetrics.AnnotationRequestCount.Inc()\n\t\/\/ Make the actual request\n\tresp, err := http.Get(url)\n\n\t\/\/ Catch http errors\n\tif err != nil {\n\t\tmetrics.AnnotationErrorCount.\n\t\t\tWith(prometheus.Labels{\"source\": \"Request to Annotator failed\"}).Inc()\n\t\treturn nil, err\n\t}\n\n\t\/\/ Catch errors reported by the service\n\tif resp.StatusCode != http.StatusOK {\n\t\tmetrics.AnnotationErrorCount.\n\t\t\tWith(prometheus.Labels{\"source\": \"Webserver gave non-ok response\"}).Inc()\n\t\treturn nil, errors.New(\"URL:\" + url + \" gave response code \" + resp.Status)\n\t}\n\tdefer resp.Body.Close()\n\n\t\/\/ Copy response into a byte slice\n\treturn ioutil.ReadAll(resp.Body)\n}\n\n\/\/ ParseJSONGeoDataResponse takes a byte slice containing the test of\n\/\/ the JSON from the annotator service and parses it into a GeoData\n\/\/ struct, for easy manipulation. It returns a pointer to the struct on\n\/\/ success and an error if an error occurs.\nfunc ParseJSONGeoDataResponse(jsonBuffer []byte) (*GeoData, error) {\n\tparsedJSON := &GeoData{}\n\terr := json.Unmarshal(jsonBuffer, parsedJSON)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn parsedJSON, nil\n}\n\n\/\/ GetBatchGeoData combines the functionality of\n\/\/ BatchQueryAnnotationService and BatchParseJSONGeoDataResponse to\n\/\/ query the annotator service and return the corresponding map of\n\/\/ ip-timestamp strings to GeoData structs, or a nil map if it\n\/\/ encounters any error and cannot get the data for any reason\n\/\/ TODO - dedup common code in GetGeoData\nfunc GetBatchGeoData(url string, data []RequestData) map[string]GeoData {\n\t\/\/ Query the service and grab the response safely\n\tannotatorResponse, err := BatchQueryAnnotationService(url, data)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn nil\n\t}\n\n\t\/\/ Safely parse the JSON response and pass it back to the caller\n\tgeoDataFromResponse, err := BatchParseJSONGeoDataResponse(annotatorResponse)\n\tif err != nil {\n\t\tmetrics.AnnotationErrorCount.With(prometheus.\n\t\t\tLabels{\"source\": \"Failed to parse JSON\"}).Inc()\n\t\tlog.Println(err)\n\t\tlog.Printf(\"%+v\\n\", data)\n\t\treturn nil\n\t}\n\treturn geoDataFromResponse\n}\n\n\/\/ BatchQueryAnnotationService takes a url to POST the request to and\n\/\/ a slice of RequestDatas to be sent in the body in a JSON\n\/\/ format. It will copy the response into a []byte and return it to\n\/\/ the user, returning an error if any occurs\n\/\/ TODO(gfr) Should pass the annotator's request context through and use it here.\nfunc BatchQueryAnnotationService(url string, data []RequestData) ([]byte, error) {\n\tmetrics.AnnotationRequestCount.Inc()\n\n\tencodedData, err := json.Marshal(data)\n\tif err != nil {\n\t\tmetrics.AnnotationErrorCount.\n\t\t\tWith(prometheus.Labels{\"source\": \"Couldn't Marshal Data\"}).Inc()\n\t\treturn nil, err\n\t}\n\n\tvar netClient = &http.Client{\n\t\t\/\/ Median response time is < 10 msec, but 99th percentile is 0.6 seconds.\n\t\tTimeout: 2 * time.Second,\n\t}\n\n\t\/\/ Make the actual request\n\tresp, err := netClient.Post(url, \"raw\", bytes.NewReader(encodedData))\n\t\/\/ Catch http errors\n\tif err != nil {\n\t\tmetrics.AnnotationErrorCount.\n\t\t\tWith(prometheus.Labels{\"source\": err.Error()}).Inc()\n\t\treturn nil, err\n\t}\n\n\t\/\/ Catch errors reported by the service\n\tif resp.StatusCode != http.StatusOK {\n\t\tmetrics.AnnotationErrorCount.\n\t\t\tWith(prometheus.Labels{\"source\": http.StatusText(resp.StatusCode)}).Inc()\n\t\treturn nil, errors.New(\"URL:\" + url + \" gave response code \" + resp.Status)\n\t}\n\tdefer resp.Body.Close()\n\n\t\/\/ Copy response into a byte slice\n\treturn ioutil.ReadAll(resp.Body)\n}\n\n\/\/ BatchParseJSONGeoDataResponse takes a byte slice containing the\n\/\/ text of the JSON from the annoator service's batch request endpoint\n\/\/ and parses it into a map of strings to GeoData structs, for\n\/\/ easy manipulation. It returns a pointer to the struct on success\n\/\/ and an error if one occurs.\n\/\/ TODO - is there duplicate code with ParseJSON... ?\nfunc BatchParseJSONGeoDataResponse(jsonBuffer []byte) (map[string]GeoData, error) {\n\tparsedJSON := make(map[string]GeoData)\n\terr := json.Unmarshal(jsonBuffer, &parsedJSON)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn parsedJSON, nil\n}\n<commit_msg>PR fix<commit_after>package annotation\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com\/m-lab\/etl\/web100\"\n\n\t\"github.com\/m-lab\/etl\/metrics\"\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n)\n\nvar IPAnnotationEnabled = false\n\nfunc init() {\n\tgetFlagValues()\n}\n\nfunc getFlagValues() {\n\t\/\/ Check for ANNOTATE_IP = 'true'\n\tflag, ok := os.LookupEnv(\"ANNOTATE_IP\")\n\tif ok {\n\t\tIPAnnotationEnabled, _ = strconv.ParseBool(flag)\n\t\t\/\/ If parse fails, then ipAnn will be set to false.\n\t}\n}\n\n\/\/ EnableAnnotation is used only for testing.  Should be placed in whitebox _test file.\nfunc EnableAnnotation() {\n\tos.Setenv(\"ANNOTATE_IP\", \"True\")\n\tgetFlagValues()\n}\n\n\/\/ The GeolocationIP struct contains all the information needed for the\n\/\/ geolocation data that will be inserted into big query. The fiels are\n\/\/ capitalized for exporting, although the originals in the DB schema\n\/\/ are not.\ntype GeolocationIP struct {\n\tContinent_code string  `json:\"continent_code,string,omitempty\"` \/\/ Gives a shorthand for the continent\n\tCountry_code   string  `json:\"country_code,string,omitempty\"`   \/\/ Gives a shorthand for the country\n\tCountry_code3  string  `json:\"country_code3,string,omitempty\"`  \/\/ Gives a shorthand for the country\n\tCountry_name   string  `json:\"country_name,string,omitempty\"`   \/\/ Name of the country\n\tRegion         string  `json:\"region,string,omitempty\"`         \/\/ Region or State within the country\n\tMetro_code     int64   `json:\"metro_code,integer,omitempty\"`    \/\/ Metro code within the country\n\tCity           string  `json:\"city,string,omitempty\"`           \/\/ City within the region\n\tArea_code      int64   `json:\"area_code,integer,omitempty\"`     \/\/ Area code, similar to metro code\n\tPostal_code    string  `json:\"postal_code,string,omitempty\"`    \/\/ Postal code, again similar to metro\n\tLatitude       float64 `json:\"latitude,float\"`                  \/\/ Latitude\n\tLongitude      float64 `json:\"longitude,float\"`                 \/\/ Longitude\n\n}\n\n\/\/ The struct that will hold the IP\/ASN data when it gets added to the\n\/\/ schema. Currently empty and unused.\ntype IPASNData struct{}\n\n\/\/ The main struct for the geo metadata, which holds pointers to the\n\/\/ Geolocation data and the IP\/ASN data. This is what we parse the JSON\n\/\/ response from the annotator into.\ntype GeoData struct {\n\tGeo *GeolocationIP \/\/ Holds the geolocation data\n\tASN *IPASNData     \/\/ Holds the IP\/ASN data\n}\n\n\/\/ The RequestData schema is the schema for the json that we will send\n\/\/ down the pipe to the annotation service.\ntype RequestData struct {\n\tIP        string    \/\/ Holds the IP from an incoming request\n\tIPFormat  int       \/\/ Holds the ip format, 4 or 6\n\tTimestamp time.Time \/\/ Holds the timestamp from an incoming request\n}\n\n\/\/ AnnotatorURL holds the https address of the annotator.\n\/\/ TODO(gfr) See if there is a better way of determining\n\/\/ where to send the request (there almost certainly is)\nvar AnnotatorURL = \"https:\/\/annotator-dot-\" +\n\tos.Getenv(\"GCLOUD_PROJECT\") +\n\t\".appspot.com\"\n\n\/\/ BaseURL provides the base URL for single annotation requests\nvar BaseURL = AnnotatorURL + \"\/annotate?\"\n\n\/\/ BatchURL provides the base URL for batch annotation requests\nvar BatchURL = AnnotatorURL + \"\/batch_annotate\"\n\n\/\/ FetchGeoAnnotations takes a slice of strings\n\/\/ containing ip addresses, a timestamp, and a slice of pointers to\n\/\/ the GeolocationIP structs that correspond to the ip addresses. A\n\/\/ precondition assumed by this function is that both slices are the\n\/\/ same length. It will then make a call to the batch annotator, using\n\/\/ the ip addresses and the timestamp. Then, it uses that data to fill\n\/\/ in the structs pointed to by the slice of GeolocationIP pointers.\nfunc FetchGeoAnnotations(ips []string, timestamp time.Time, geoDest []*GeolocationIP) {\n\treqData := make([]RequestData, 0, len(ips))\n\tnormalized := make([]string, len(ips))\n\tfor i := range ips {\n\t\tif ips[i] == \"\" {\n\t\t\t\/\/ TODO(gfr) These should be warning, else we have error > request\n\t\t\tmetrics.AnnotationWarningCount.With(prometheus.\n\t\t\t\tLabels{\"source\": \"Empty IP Address!!!\"}).Inc()\n\t\t\tcontinue\n\t\t}\n\t\tvar err error\n\t\tnormalized[i], err = web100.NormalizeIPv6(ips[i])\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tmetrics.AnnotationWarningCount.With(prometheus.\n\t\t\t\tLabels{\"source\": \"NormalizeIPv6 Error\"}).Inc()\n\t\t}\n\t\treqData = append(reqData, RequestData{normalized[i], 0, timestamp})\n\t}\n\tannotationData := GetBatchGeoData(BatchURL, reqData)\n\ttimeString := strconv.FormatInt(timestamp.Unix(), 36)\n\tfor i := range normalized {\n\t\tdata, ok := annotationData[normalized[i]+timeString]\n\t\tif !ok || data.Geo == nil {\n\t\t\t\/\/ TODO(gfr) These should be warning, else we have error > request\n\t\t\tmetrics.AnnotationWarningCount.With(prometheus.\n\t\t\t\tLabels{\"source\": \"Missing or empty data for IP Address!!!\"}).Inc()\n\t\t\tcontinue\n\t\t}\n\t\t*geoDest[i] = *data.Geo\n\t}\n}\n\n\/\/ GetAndInsertGeolocationIPStruct takes a NON-NIL pointer to a\n\/\/ pre-allocated GeolocationIP struct, an IP address, and a\n\/\/ timestamp. It will connect to the annotation service, get the\n\/\/ geo data, and insert the geo data into the reigion pointed to by\n\/\/ the GeolocationIP pointer.\nfunc GetAndInsertGeolocationIPStruct(geo *GeolocationIP, ip string, timestamp time.Time) {\n\turl := BaseURL + \"ip_addr=\" + url.QueryEscape(ip) +\n\t\t\"&since_epoch=\" + strconv.FormatInt(timestamp.Unix(), 10)\n\tannotationData := GetGeoData(url)\n\tif annotationData != nil && annotationData.Geo != nil {\n\t\t*geo = *annotationData.Geo\n\t}\n}\n\n\/\/ GetGeoData combines the functionality of QueryAnnotationService and\n\/\/ ParseJSONGeoDataResponse to query the annotator service and return\n\/\/ the corresponding GeoData if it can, or a nil pointer if it\n\/\/ encounters any error and cannot get the data for any reason\nfunc GetGeoData(url string) *GeoData {\n\t\/\/ Query the service and grab the response safely\n\tannotatorResponse, err := QueryAnnotationService(url)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn nil\n\t}\n\n\t\/\/ Safely parse the JSON response and pass it back to the caller\n\tgeoDataFromResponse, err := ParseJSONGeoDataResponse(annotatorResponse)\n\tif err != nil {\n\t\tmetrics.AnnotationErrorCount.With(prometheus.\n\t\t\tLabels{\"source\": \"Failed to parse JSON\"}).Inc()\n\t\tlog.Println(err)\n\t\treturn nil\n\t}\n\treturn geoDataFromResponse\n}\n\n\/\/ QueryAnnotationService will connect to the annotation service and\n\/\/ copy the body of a valid response to a byte slice and return it to a\n\/\/ user, returning an error if any occurs\nfunc QueryAnnotationService(url string) ([]byte, error) {\n\tmetrics.AnnotationRequestCount.Inc()\n\t\/\/ Make the actual request\n\tresp, err := http.Get(url)\n\n\t\/\/ Catch http errors\n\tif err != nil {\n\t\tmetrics.AnnotationErrorCount.\n\t\t\tWith(prometheus.Labels{\"source\": \"Request to Annotator failed\"}).Inc()\n\t\treturn nil, err\n\t}\n\n\t\/\/ Catch errors reported by the service\n\tif resp.StatusCode != http.StatusOK {\n\t\tmetrics.AnnotationErrorCount.\n\t\t\tWith(prometheus.Labels{\"source\": \"Webserver gave non-ok response\"}).Inc()\n\t\treturn nil, errors.New(\"URL:\" + url + \" gave response code \" + resp.Status)\n\t}\n\tdefer resp.Body.Close()\n\n\t\/\/ Copy response into a byte slice\n\treturn ioutil.ReadAll(resp.Body)\n}\n\n\/\/ ParseJSONGeoDataResponse takes a byte slice containing the test of\n\/\/ the JSON from the annotator service and parses it into a GeoData\n\/\/ struct, for easy manipulation. It returns a pointer to the struct on\n\/\/ success and an error if an error occurs.\nfunc ParseJSONGeoDataResponse(jsonBuffer []byte) (*GeoData, error) {\n\tparsedJSON := &GeoData{}\n\terr := json.Unmarshal(jsonBuffer, parsedJSON)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn parsedJSON, nil\n}\n\n\/\/ GetBatchGeoData combines the functionality of\n\/\/ BatchQueryAnnotationService and BatchParseJSONGeoDataResponse to\n\/\/ query the annotator service and return the corresponding map of\n\/\/ ip-timestamp strings to GeoData structs, or a nil map if it\n\/\/ encounters any error and cannot get the data for any reason\n\/\/ TODO - dedup common code in GetGeoData\nfunc GetBatchGeoData(url string, data []RequestData) map[string]GeoData {\n\t\/\/ Query the service and grab the response safely\n\tannotatorResponse, err := BatchQueryAnnotationService(url, data)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn nil\n\t}\n\n\t\/\/ Safely parse the JSON response and pass it back to the caller\n\tgeoDataFromResponse, err := BatchParseJSONGeoDataResponse(annotatorResponse)\n\tif err != nil {\n\t\tmetrics.AnnotationErrorCount.With(prometheus.\n\t\t\tLabels{\"source\": \"Failed to parse JSON\"}).Inc()\n\t\tlog.Println(err)\n\t\tlog.Printf(\"%+v\\n\", data)\n\t\treturn nil\n\t}\n\treturn geoDataFromResponse\n}\n\n\/\/ BatchQueryAnnotationService takes a url to POST the request to and\n\/\/ a slice of RequestDatas to be sent in the body in a JSON\n\/\/ format. It will copy the response into a []byte and return it to\n\/\/ the user, returning an error if any occurs\n\/\/ TODO(gfr) Should pass the annotator's request context through and use it here.\nfunc BatchQueryAnnotationService(url string, data []RequestData) ([]byte, error) {\n\tmetrics.AnnotationRequestCount.Inc()\n\n\tencodedData, err := json.Marshal(data)\n\tif err != nil {\n\t\tmetrics.AnnotationErrorCount.\n\t\t\tWith(prometheus.Labels{\"source\": \"Couldn't Marshal Data\"}).Inc()\n\t\treturn nil, err\n\t}\n\n\tvar netClient = &http.Client{\n\t\t\/\/ Median response time is < 10 msec, but 99th percentile is 0.6 seconds.\n\t\tTimeout: 2 * time.Second,\n\t}\n\n\t\/\/ Make the actual request\n\tresp, err := netClient.Post(url, \"raw\", bytes.NewReader(encodedData))\n\t\/\/ Catch http errors\n\tif err != nil {\n\t\tmetrics.AnnotationErrorCount.\n\t\t\tWith(prometheus.Labels{\"source\": err.Error()}).Inc()\n\t\treturn nil, err\n\t}\n\n\t\/\/ Catch errors reported by the service\n\tif resp.StatusCode != http.StatusOK {\n\t\tmetrics.AnnotationErrorCount.\n\t\t\tWith(prometheus.Labels{\"source\": http.StatusText(resp.StatusCode)}).Inc()\n\t\treturn nil, errors.New(\"URL:\" + url + \" gave response code \" + resp.Status)\n\t}\n\tdefer resp.Body.Close()\n\n\t\/\/ Copy response into a byte slice\n\treturn ioutil.ReadAll(resp.Body)\n}\n\n\/\/ BatchParseJSONGeoDataResponse takes a byte slice containing the\n\/\/ text of the JSON from the annoator service's batch request endpoint\n\/\/ and parses it into a map of strings to GeoData structs, for\n\/\/ easy manipulation. It returns a pointer to the struct on success\n\/\/ and an error if one occurs.\n\/\/ TODO - is there duplicate code with ParseJSON... ?\nfunc BatchParseJSONGeoDataResponse(jsonBuffer []byte) (map[string]GeoData, error) {\n\tparsedJSON := make(map[string]GeoData)\n\terr := json.Unmarshal(jsonBuffer, &parsedJSON)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn parsedJSON, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package api\n\nimport (\n\t\"fmt\"\n\t\"github.com\/nais\/naisd\/api\/app\"\n\tv1 \"k8s.io\/api\/core\/v1\"\n\tk8sextensions \"k8s.io\/api\/extensions\/v1beta1\"\n\tk8smeta \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/intstr\"\n\t\"k8s.io\/client-go\/kubernetes\"\n)\n\nconst (\n\tdefaultRedisPort          = 6379\n\tdefaultRedisExporterPort  = 9121\n\tdefaultRedisExporterImage = \"oliver006\/redis_exporter:v1.0.3-alpine\"\n\tdefaultRedisImage         = \"redis:5-alpine\"\n)\n\ntype Redis struct {\n\tEnabled  bool\n\tImage    string\n\tLimits   ResourceList\n\tRequests ResourceList\n}\n\nfunc updateDefaultRedisValues(redis Redis) Redis {\n\tif redis.Image == \"\" {\n\t\tredis.Image = defaultRedisImage\n\t}\n\tif len(redis.Limits.Cpu) == 0 {\n\t\tredis.Limits.Cpu = \"100m\"\n\t}\n\tif len(redis.Limits.Memory) == 0 {\n\t\tredis.Limits.Memory = \"128Mi\"\n\t}\n\tif len(redis.Requests.Cpu) == 0 {\n\t\tredis.Requests.Cpu = \"100m\"\n\t}\n\tif len(redis.Requests.Memory) == 0 {\n\t\tredis.Requests.Memory = \"128Mi\"\n\t}\n\treturn redis\n}\n\nfunc createRedisPodSpec(redis Redis) v1.PodSpec {\n\treturn v1.PodSpec{\n\t\tContainers: []v1.Container{\n\t\t\t{\n\t\t\t\tName:  \"redis\",\n\t\t\t\tImage: redis.Image,\n\t\t\t\tResources: createResourceLimits(redis.Requests.Cpu, redis.Requests.Memory,\n\t\t\t\t\tredis.Limits.Cpu, redis.Limits.Memory),\n\t\t\t\tImagePullPolicy: v1.PullIfNotPresent,\n\t\t\t\tPorts: []v1.ContainerPort{\n\t\t\t\t\t{\n\t\t\t\t\t\tContainerPort: int32(defaultRedisPort),\n\t\t\t\t\t\tName:          DefaultPortName,\n\t\t\t\t\t\tProtocol:      v1.ProtocolTCP,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tName:  \"exporter\",\n\t\t\t\tImage: defaultRedisExporterImage,\n\t\t\t\tResources: createResourceLimits(\"100m\", \"100Mi\",\n\t\t\t\t\t\"100m\", \"100Mi\"),\n\t\t\t\tImagePullPolicy: v1.PullIfNotPresent,\n\t\t\t\tPorts: []v1.ContainerPort{\n\t\t\t\t\t{\n\t\t\t\t\t\tContainerPort: int32(defaultRedisExporterPort),\n\t\t\t\t\t\tName:          DefaultPortName,\n\t\t\t\t\t\tProtocol:      v1.ProtocolTCP,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc createRedisDeploymentSpec(resourceName string, spec app.Spec, redis Redis) k8sextensions.DeploymentSpec {\n\tobjectMeta := generateObjectMeta(spec)\n\tobjectMeta.Name = resourceName\n\tobjectMeta.Annotations = map[string]string{\n\t\t\"prometheus.io\/scrape\": \"true\",\n\t\t\"prometheus.io\/port\":   string(defaultRedisExporterPort),\n\t\t\"prometheus.io\/path\":   \"\/metrics\",\n\t}\n\n\treturn k8sextensions.DeploymentSpec{\n\t\tReplicas: int32p(1),\n\t\tSelector: &k8smeta.LabelSelector{\n\t\t\tMatchLabels: createPodSelector(spec),\n\t\t},\n\t\tStrategy: k8sextensions.DeploymentStrategy{\n\t\t\tType: k8sextensions.RecreateDeploymentStrategyType,\n\t\t},\n\t\tProgressDeadlineSeconds: int32p(300),\n\t\tRevisionHistoryLimit:    int32p(10),\n\t\tTemplate: v1.PodTemplateSpec{\n\t\t\tObjectMeta: objectMeta,\n\t\t\tSpec:       createRedisPodSpec(redis),\n\t\t},\n\t}\n}\n\nfunc createRedisDeploymentDef(resourceName string, spec app.Spec, redis Redis, existingDeployment *k8sextensions.Deployment) *k8sextensions.Deployment {\n\texistingDeployment.Spec = createRedisDeploymentSpec(resourceName, spec, redis)\n\treturn existingDeployment\n}\n\nfunc createOrUpdateRedisInstance(spec app.Spec, redis Redis, k8sClient kubernetes.Interface) (*k8sextensions.Deployment, error) {\n\tredisName := fmt.Sprintf(\"%s-redis\", spec.ResourceName())\n\texistingDeployment, err := getExistingDeployment(redisName, spec.Namespace, k8sClient)\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to get existing deployment: %s\", err)\n\t}\n\n\tdeploymentDef := createRedisDeploymentDef(redisName, spec, redis, existingDeployment)\n\n\treturn createOrUpdateDeploymentResource(deploymentDef, spec.Namespace, k8sClient)\n}\n\nfunc createRedisServiceDef(spec app.Spec) *v1.Service {\n\treturn &v1.Service{\n\t\tTypeMeta: k8smeta.TypeMeta{\n\t\t\tKind:       \"Service\",\n\t\t\tAPIVersion: \"v1\",\n\t\t},\n\t\tObjectMeta: generateObjectMeta(spec),\n\t\tSpec: v1.ServiceSpec{\n\t\t\tType:     v1.ServiceTypeClusterIP,\n\t\t\tSelector: createPodSelector(spec),\n\t\t\tPorts: []v1.ServicePort{\n\t\t\t\t{\n\t\t\t\t\tName:     DefaultPortName,\n\t\t\t\t\tProtocol: v1.ProtocolTCP,\n\t\t\t\t\tPort:     6379,\n\t\t\t\t\tTargetPort: intstr.IntOrString{\n\t\t\t\t\t\tType:   intstr.String,\n\t\t\t\t\t\tStrVal: DefaultPortName,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc createOrUpdateRedisService(spec app.Spec, k8sClient kubernetes.Interface) (*v1.Service, error) {\n\tredisName := fmt.Sprintf(\"%s-redis\", spec.ResourceName())\n\tservice, err := getExistingService(redisName, spec.Namespace, k8sClient)\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to get existing service: %s\", err)\n\t} else if service == nil {\n\t\tservice = createRedisServiceDef(spec)\n\t\tservice.Name = redisName\n\t}\n\n\tservice.ObjectMeta = addLabelsToObjectMeta(service.ObjectMeta, spec)\n\treturn createOrUpdateServiceResource(service, spec.Namespace, k8sClient)\n}\n<commit_msg>Riktig navn på deployment<commit_after>package api\n\nimport (\n\t\"fmt\"\n\t\"github.com\/nais\/naisd\/api\/app\"\n\tv1 \"k8s.io\/api\/core\/v1\"\n\tk8sextensions \"k8s.io\/api\/extensions\/v1beta1\"\n\tk8smeta \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/intstr\"\n\t\"k8s.io\/client-go\/kubernetes\"\n)\n\nconst (\n\tdefaultRedisPort          = 6379\n\tdefaultRedisExporterPort  = 9121\n\tdefaultRedisExporterImage = \"oliver006\/redis_exporter:v1.0.3-alpine\"\n\tdefaultRedisImage         = \"redis:5-alpine\"\n)\n\ntype Redis struct {\n\tEnabled  bool\n\tImage    string\n\tLimits   ResourceList\n\tRequests ResourceList\n}\n\nfunc updateDefaultRedisValues(redis Redis) Redis {\n\tif redis.Image == \"\" {\n\t\tredis.Image = defaultRedisImage\n\t}\n\tif len(redis.Limits.Cpu) == 0 {\n\t\tredis.Limits.Cpu = \"100m\"\n\t}\n\tif len(redis.Limits.Memory) == 0 {\n\t\tredis.Limits.Memory = \"128Mi\"\n\t}\n\tif len(redis.Requests.Cpu) == 0 {\n\t\tredis.Requests.Cpu = \"100m\"\n\t}\n\tif len(redis.Requests.Memory) == 0 {\n\t\tredis.Requests.Memory = \"128Mi\"\n\t}\n\treturn redis\n}\n\nfunc createRedisPodSpec(redis Redis) v1.PodSpec {\n\treturn v1.PodSpec{\n\t\tContainers: []v1.Container{\n\t\t\t{\n\t\t\t\tName:  \"redis\",\n\t\t\t\tImage: redis.Image,\n\t\t\t\tResources: createResourceLimits(redis.Requests.Cpu, redis.Requests.Memory,\n\t\t\t\t\tredis.Limits.Cpu, redis.Limits.Memory),\n\t\t\t\tImagePullPolicy: v1.PullIfNotPresent,\n\t\t\t\tPorts: []v1.ContainerPort{\n\t\t\t\t\t{\n\t\t\t\t\t\tContainerPort: int32(defaultRedisPort),\n\t\t\t\t\t\tName:          DefaultPortName,\n\t\t\t\t\t\tProtocol:      v1.ProtocolTCP,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tName:  \"exporter\",\n\t\t\t\tImage: defaultRedisExporterImage,\n\t\t\t\tResources: createResourceLimits(\"100m\", \"100Mi\",\n\t\t\t\t\t\"100m\", \"100Mi\"),\n\t\t\t\tImagePullPolicy: v1.PullIfNotPresent,\n\t\t\t\tPorts: []v1.ContainerPort{\n\t\t\t\t\t{\n\t\t\t\t\t\tContainerPort: int32(defaultRedisExporterPort),\n\t\t\t\t\t\tName:          DefaultPortName,\n\t\t\t\t\t\tProtocol:      v1.ProtocolTCP,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc createRedisDeploymentSpec(resourceName string, spec app.Spec, redis Redis) k8sextensions.DeploymentSpec {\n\tobjectMeta := generateObjectMeta(spec)\n\tobjectMeta.Name = resourceName\n\tobjectMeta.Annotations = map[string]string{\n\t\t\"prometheus.io\/scrape\": \"true\",\n\t\t\"prometheus.io\/port\":   string(defaultRedisExporterPort),\n\t\t\"prometheus.io\/path\":   \"\/metrics\",\n\t}\n\n\treturn k8sextensions.DeploymentSpec{\n\t\tReplicas: int32p(1),\n\t\tSelector: &k8smeta.LabelSelector{\n\t\t\tMatchLabels: createPodSelector(spec),\n\t\t},\n\t\tStrategy: k8sextensions.DeploymentStrategy{\n\t\t\tType: k8sextensions.RecreateDeploymentStrategyType,\n\t\t},\n\t\tProgressDeadlineSeconds: int32p(300),\n\t\tRevisionHistoryLimit:    int32p(10),\n\t\tTemplate: v1.PodTemplateSpec{\n\t\t\tObjectMeta: objectMeta,\n\t\t\tSpec:       createRedisPodSpec(redis),\n\t\t},\n\t}\n}\n\nfunc createRedisDeploymentDef(resourceName string, spec app.Spec, redis Redis, existingDeployment *k8sextensions.Deployment) *k8sextensions.Deployment {\n\texistingDeployment.Spec = createRedisDeploymentSpec(resourceName, spec, redis)\n\treturn existingDeployment\n}\n\nfunc createOrUpdateRedisInstance(spec app.Spec, redis Redis, k8sClient kubernetes.Interface) (*k8sextensions.Deployment, error) {\n\tredisName := fmt.Sprintf(\"%s-redis\", spec.ResourceName())\n\texistingDeployment, err := getExistingDeployment(redisName, spec.Namespace, k8sClient)\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to get existing deployment: %s\", err)\n\t}\n\n\tdeploymentDef := createRedisDeploymentDef(redisName, spec, redis, existingDeployment)\n\tdeploymentDef.Name = fmt.Sprintf(\"%s-redis\", spec.ResourceName())\n\n\treturn createOrUpdateDeploymentResource(deploymentDef, spec.Namespace, k8sClient)\n}\n\nfunc createRedisServiceDef(spec app.Spec) *v1.Service {\n\treturn &v1.Service{\n\t\tTypeMeta: k8smeta.TypeMeta{\n\t\t\tKind:       \"Service\",\n\t\t\tAPIVersion: \"v1\",\n\t\t},\n\t\tObjectMeta: generateObjectMeta(spec),\n\t\tSpec: v1.ServiceSpec{\n\t\t\tType:     v1.ServiceTypeClusterIP,\n\t\t\tSelector: createPodSelector(spec),\n\t\t\tPorts: []v1.ServicePort{\n\t\t\t\t{\n\t\t\t\t\tName:     DefaultPortName,\n\t\t\t\t\tProtocol: v1.ProtocolTCP,\n\t\t\t\t\tPort:     6379,\n\t\t\t\t\tTargetPort: intstr.IntOrString{\n\t\t\t\t\t\tType:   intstr.String,\n\t\t\t\t\t\tStrVal: DefaultPortName,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc createOrUpdateRedisService(spec app.Spec, k8sClient kubernetes.Interface) (*v1.Service, error) {\n\tredisName := fmt.Sprintf(\"%s-redis\", spec.ResourceName())\n\tservice, err := getExistingService(redisName, spec.Namespace, k8sClient)\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to get existing service: %s\", err)\n\t} else if service == nil {\n\t\tservice = createRedisServiceDef(spec)\n\t\tservice.Name = redisName\n\t}\n\n\tservice.ObjectMeta = addLabelsToObjectMeta(service.ObjectMeta, spec)\n\treturn createOrUpdateServiceResource(service, spec.Namespace, k8sClient)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/go:generate swagger generate spec\n\/\/ Package main GalAirCheck.\n\/\/\n\/\/ the purpose of this application is to provide an Galera Check application\n\/\/ that will show state of Galera Cluster in real Time\n\/\/\n\/\/ Terms Of Service:\n\/\/\n\/\/ there are no TOS at this moment, use at your own risk we take no responsibility\n\/\/\n\/\/     Schemes:\n\/\/     Host:\n\/\/     BasePath:\n\/\/     Version: 0.0.1\n\/\/     License: MIT http:\/\/opensource.org\/licenses\/MIT\n\/\/     Contact: Julien SENON <julien.senon@gmail.com>\npackage main\n\nimport (\n\t\"api\"\n\t\/\/ \"fmt\"\n\t\"github.com\/gorilla\/handlers\"\n\t\"github.com\/gorilla\/mux\"\n\t\"net\/http\"\n\t\"web\"\n)\n\n\/\/ TO FIX\n\nfunc main() {\n\tr := mux.NewRouter()\n\n\t\/\/ Remove CORS Header check to allow swagger and application on same host and port\n\theadersOk := handlers.AllowedHeaders([]string{\"X-Requested-With\", \"Content-Type\"})\n\t\/\/ To be changed\n\toriginsOk := handlers.AllowedOrigins([]string{\"*\"})\n\tmethodsOk := handlers.AllowedMethods([]string{\"GET\", \"HEAD\", \"POST\", \"PUT\", \"OPTIONS\", \"PATCH\"})\n\n\t\/\/ Web Part\n\tr.HandleFunc(\"\/index\", web.Index)\n\tr.HandleFunc(\"\/toto\", web.Toto)\n\n\tr.HandleFunc(\"\/login\", web.Login)\n\n\t\/\/ Static dir\n\tr.PathPrefix(\"\/\").Handler(http.StripPrefix(\"\/\", http.FileServer(http.Dir(\"templates\/static\/\"))))\n\n\t\/\/ Health Check\n\tr.HandleFunc(\"\/healthy\/am-i-up\", api.Statusamiup).Methods(\"GET\")\n\tr.HandleFunc(\"\/healthy\/about\", api.Statusabout).Methods(\"GET\")\n\n\thttp.ListenAndServe(\":9030\", handlers.CORS(originsOk, headersOk, methodsOk)(r))\n}\n<commit_msg>cleanning<commit_after>\/\/go:generate swagger generate spec\n\/\/ Package main GalAirCheck.\n\/\/\n\/\/ the purpose of this application is to provide an Galera Check application\n\/\/ that will show state of Galera Cluster in real Time\n\/\/\n\/\/ Terms Of Service:\n\/\/\n\/\/ there are no TOS at this moment, use at your own risk we take no responsibility\n\/\/\n\/\/     Schemes:\n\/\/     Host:\n\/\/     BasePath:\n\/\/     Version: 0.0.1\n\/\/     License: MIT http:\/\/opensource.org\/licenses\/MIT\n\/\/     Contact: Julien SENON <julien.senon@gmail.com>\npackage main\n\nimport (\n\t\"api\"\n\t\/\/ \"fmt\"\n\t\"github.com\/gorilla\/handlers\"\n\t\"github.com\/gorilla\/mux\"\n\t\"net\/http\"\n\t\"web\"\n)\n\n\/\/ TO FIX\n\nfunc main() {\n\tr := mux.NewRouter()\n\n\t\/\/ Remove CORS Header check to allow swagger and application on same host and port\n\theadersOk := handlers.AllowedHeaders([]string{\"X-Requested-With\", \"Content-Type\"})\n\t\/\/ To be changed\n\toriginsOk := handlers.AllowedOrigins([]string{\"*\"})\n\tmethodsOk := handlers.AllowedMethods([]string{\"GET\", \"HEAD\", \"POST\", \"PUT\", \"OPTIONS\", \"PATCH\"})\n\n\t\/\/ Web Part\n\tr.HandleFunc(\"\/index\", web.Index)\n\n\t\/\/ Static dir\n\tr.PathPrefix(\"\/\").Handler(http.StripPrefix(\"\/\", http.FileServer(http.Dir(\"templates\/static\/\"))))\n\n\t\/\/ Health Check\n\tr.HandleFunc(\"\/healthy\/am-i-up\", api.Statusamiup).Methods(\"GET\")\n\tr.HandleFunc(\"\/healthy\/about\", api.Statusabout).Methods(\"GET\")\n\n\thttp.ListenAndServe(\":9030\", handlers.CORS(originsOk, headersOk, methodsOk)(r))\n}\n<|endoftext|>"}
{"text":"<commit_before>package vault\n\nimport (\n\t\"io\/ioutil\"\n\t\"math\/rand\"\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n)\n\nvar (\n\tTEST_DIR = os.Getenv(\"GOPATH\") + \"\/src\/github.com\/ieee0824\/thor\/test\"\n)\n\nfunc init() {\n\trand.Seed(time.Now().UnixNano())\n}\n\nvar letterRunes = []rune(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\")\n\nfunc randStringRunes(n int) string {\n\tb := make([]rune, n)\n\tfor i := range b {\n\t\tb[i] = letterRunes[rand.Intn(len(letterRunes))]\n\t}\n\treturn string(b)\n}\n\nfunc TestIsSecret(t *testing.T) {\n\tplainTextPath := TEST_DIR + \"\/vaultTestFiles\/plain.json\"\n\tchipherTextPath := TEST_DIR + \"\/vaultTestFiles\/chipher.json\"\n\n\tplain, err := ioutil.ReadFile(plainTextPath)\n\tif err != nil {\n\t\tt.Error(err)\n\t} else if IsSecret(plain) {\n\t\tt.Errorf(\"The result is illegal. I want %v, but it is actually %v.\", false, IsSecret(plain))\n\t}\n\n\tchipher, err := ioutil.ReadFile(chipherTextPath)\n\tif err != nil {\n\t\tt.Error(err)\n\t} else if !IsSecret(chipher) {\n\t\tt.Errorf(\"The result is illegal. I want %v, but it is actually %v.\", true, IsSecret(chipher))\n\t}\n}\n\nfunc falsification(d []byte) []byte {\n\n\tfor i, v := range d {\n\t\tif i%2 == 0 {\n\t\t\td[i] <<= uint(rand.Int())\n\t\t} else {\n\t\t\td[i] >>= uint(rand.Int())\n\t\t}\n\t}\n\treturn d\n}\n\nfunc TestEncryption(t *testing.T) {\n\tvar randomStr = randStringRunes(65536)\n\tvar key = \"test\"\n\tvar invalidKey = \"johnDoe\"\n\n\tencrypter := NewString(randomStr)\n\n\tif err := encrypter.Encrypt(key); err != nil {\n\t\tt.Error(err)\n\t} else if string(encrypter.Chipher) == randomStr {\n\t\tt.Errorf(\"cipher text and plain text is match\")\n\t}\n\n\tif result, err := encrypter.Decrypt(key); err != nil {\n\t\tt.Error(err)\n\t} else if string(result) != randomStr {\n\t\tt.Errorf(\"cipher text and plain text is not match\")\n\t}\n\n\tif _, err := encrypter.Decrypt(invalidKey); err == nil {\n\t\tt.Errorf(\"There is no error with an invalid key.\")\n\t}\n\tencrypter.Chipher = falsification(encrypter.Chipher)\n\tif _, err := encrypter.Decrypt(key); err == nil {\n\t\tt.Errorf(\"Tampering is not detected.\")\n\t}\n\n}\n<commit_msg>データの破損検出<commit_after>package vault\n\nimport (\n\t\"io\/ioutil\"\n\t\"math\/rand\"\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n)\n\nvar (\n\tTEST_DIR = os.Getenv(\"GOPATH\") + \"\/src\/github.com\/ieee0824\/thor\/test\"\n)\n\nfunc init() {\n\trand.Seed(time.Now().UnixNano())\n}\n\nvar letterRunes = []rune(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\")\n\nfunc randStringRunes(n int) string {\n\tb := make([]rune, n)\n\tfor i := range b {\n\t\tb[i] = letterRunes[rand.Intn(len(letterRunes))]\n\t}\n\treturn string(b)\n}\n\nfunc TestIsSecret(t *testing.T) {\n\tplainTextPath := TEST_DIR + \"\/vaultTestFiles\/plain.json\"\n\tchipherTextPath := TEST_DIR + \"\/vaultTestFiles\/chipher.json\"\n\n\tplain, err := ioutil.ReadFile(plainTextPath)\n\tif err != nil {\n\t\tt.Error(err)\n\t} else if IsSecret(plain) {\n\t\tt.Errorf(\"The result is illegal. I want %v, but it is actually %v.\", false, IsSecret(plain))\n\t}\n\n\tchipher, err := ioutil.ReadFile(chipherTextPath)\n\tif err != nil {\n\t\tt.Error(err)\n\t} else if !IsSecret(chipher) {\n\t\tt.Errorf(\"The result is illegal. I want %v, but it is actually %v.\", true, IsSecret(chipher))\n\t}\n}\n\nfunc falsification(d []byte) []byte {\n\n\tfor i, v := range d {\n\t\tif i%2 == 0 {\n\t\t\td[i] = v << uint(rand.Int())\n\t\t} else {\n\t\t\td[i] = v >> uint(rand.Int())\n\t\t}\n\t}\n\treturn d\n}\n\nfunc TestEncryption(t *testing.T) {\n\tvar randomStr = randStringRunes(65536)\n\tvar key = \"test\"\n\tvar invalidKey = \"johnDoe\"\n\n\tencrypter := NewString(randomStr)\n\n\tif err := encrypter.Encrypt(key); err != nil {\n\t\tt.Error(err)\n\t} else if string(encrypter.Chipher) == randomStr {\n\t\tt.Errorf(\"cipher text and plain text is match\")\n\t}\n\n\tif result, err := encrypter.Decrypt(key); err != nil {\n\t\tt.Error(err)\n\t} else if string(result) != randomStr {\n\t\tt.Errorf(\"cipher text and plain text is not match\")\n\t}\n\n\tif _, err := encrypter.Decrypt(invalidKey); err == nil {\n\t\tt.Errorf(\"There is no error with an invalid key.\")\n\t}\n\tencrypter.Chipher = falsification(encrypter.Chipher)\n\tif _, err := encrypter.Decrypt(key); err == nil {\n\t\tt.Errorf(\"Tampering is not detected.\")\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package check\n\nimport (\n\t\"fmt\"\n\t\"plaid\/parser\"\n)\n\n\/\/ Scope tracks the symbol table and other data used during the check\ntype Scope struct {\n\tparent        *Scope\n\terrs          []error\n\tvariables     []string\n\tvalues        map[string]Type\n\tpendingReturn Type\n\tqueue         []struct {\n\t\tret  Type\n\t\texpr parser.FunctionExpr\n\t}\n}\n\nfunc (s *Scope) hasParent() bool {\n\treturn (s.parent != nil)\n}\n\n\/\/ Errors returns a list of errors detected during the check\nfunc (s *Scope) Errors() []error {\n\tif s.hasParent() {\n\t\treturn s.parent.Errors()\n\t}\n\n\treturn s.errs\n}\n\nfunc (s *Scope) addError(err error) {\n\tif s.hasParent() {\n\t\ts.parent.addError(err)\n\t} else {\n\t\ts.errs = append(s.errs, err)\n\t}\n}\n\nfunc (s *Scope) hasVariable(name string) bool {\n\t_, exists := s.values[name]\n\treturn exists\n}\n\nfunc (s *Scope) registerVariable(name string, typ Type) {\n\ts.variables = append(s.variables, name)\n\ts.values[name] = typ\n}\n\nfunc (s *Scope) getVariable(name string) Type {\n\treturn s.values[name]\n}\n\nfunc (s *Scope) hasPendingReturnType() bool {\n\treturn (s.pendingReturn != nil)\n}\n\nfunc (s *Scope) getPendingReturnType() Type {\n\treturn s.pendingReturn\n}\n\nfunc (s *Scope) setPendingReturnType(typ Type) {\n\ts.pendingReturn = typ\n}\n\nfunc (s *Scope) hasBodyQueue() bool {\n\treturn len(s.queue) > 0\n}\n\nfunc (s *Scope) enqueueBody(ret Type, expr parser.FunctionExpr) {\n\tbody := struct {\n\t\tret  Type\n\t\texpr parser.FunctionExpr\n\t}{ret, expr}\n\ts.queue = append(s.queue, body)\n}\n\nfunc (s *Scope) dequeueBody() (Type, parser.FunctionExpr) {\n\tbody := s.queue[0]\n\ts.queue = s.queue[1:]\n\treturn body.ret, body.expr\n}\n\nfunc (s *Scope) String() string {\n\tvar out string\n\tfor _, name := range s.variables {\n\t\tout += fmt.Sprintf(\"%s : %s\\n\", name, s.values[name])\n\t}\n\treturn out\n}\n\nfunc makeScope(parent *Scope, ret Type) *Scope {\n\treturn &Scope{\n\t\tparent,\n\t\t[]error{},\n\t\t[]string{},\n\t\tmake(map[string]Type),\n\t\tret,\n\t\t[]struct {\n\t\t\tret  Type\n\t\t\texpr parser.FunctionExpr\n\t\t}{},\n\t}\n}\n<commit_msg>if variable is not local, check parent scope<commit_after>package check\n\nimport (\n\t\"fmt\"\n\t\"plaid\/parser\"\n)\n\n\/\/ Scope tracks the symbol table and other data used during the check\ntype Scope struct {\n\tparent        *Scope\n\terrs          []error\n\tvariables     []string\n\tvalues        map[string]Type\n\tpendingReturn Type\n\tqueue         []struct {\n\t\tret  Type\n\t\texpr parser.FunctionExpr\n\t}\n}\n\nfunc (s *Scope) hasParent() bool {\n\treturn (s.parent != nil)\n}\n\n\/\/ Errors returns a list of errors detected during the check\nfunc (s *Scope) Errors() []error {\n\tif s.hasParent() {\n\t\treturn s.parent.Errors()\n\t}\n\n\treturn s.errs\n}\n\nfunc (s *Scope) addError(err error) {\n\tif s.hasParent() {\n\t\ts.parent.addError(err)\n\t} else {\n\t\ts.errs = append(s.errs, err)\n\t}\n}\n\nfunc (s *Scope) hasVariable(name string) bool {\n\t_, exists := s.values[name]\n\n\tif exists == false && s.hasParent() {\n\t\treturn s.parent.hasVariable(name)\n\t}\n\n\treturn exists\n}\n\nfunc (s *Scope) registerVariable(name string, typ Type) {\n\ts.variables = append(s.variables, name)\n\ts.values[name] = typ\n}\n\nfunc (s *Scope) getVariable(name string) Type {\n\treturn s.values[name]\n}\n\nfunc (s *Scope) hasPendingReturnType() bool {\n\treturn (s.pendingReturn != nil)\n}\n\nfunc (s *Scope) getPendingReturnType() Type {\n\treturn s.pendingReturn\n}\n\nfunc (s *Scope) setPendingReturnType(typ Type) {\n\ts.pendingReturn = typ\n}\n\nfunc (s *Scope) hasBodyQueue() bool {\n\treturn len(s.queue) > 0\n}\n\nfunc (s *Scope) enqueueBody(ret Type, expr parser.FunctionExpr) {\n\tbody := struct {\n\t\tret  Type\n\t\texpr parser.FunctionExpr\n\t}{ret, expr}\n\ts.queue = append(s.queue, body)\n}\n\nfunc (s *Scope) dequeueBody() (Type, parser.FunctionExpr) {\n\tbody := s.queue[0]\n\ts.queue = s.queue[1:]\n\treturn body.ret, body.expr\n}\n\nfunc (s *Scope) String() string {\n\tvar out string\n\tfor _, name := range s.variables {\n\t\tout += fmt.Sprintf(\"%s : %s\\n\", name, s.values[name])\n\t}\n\treturn out\n}\n\nfunc makeScope(parent *Scope, ret Type) *Scope {\n\treturn &Scope{\n\t\tparent,\n\t\t[]error{},\n\t\t[]string{},\n\t\tmake(map[string]Type),\n\t\tret,\n\t\t[]struct {\n\t\t\tret  Type\n\t\t\texpr parser.FunctionExpr\n\t\t}{},\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build gofig\n\npackage config\n\nimport (\n\t\"os\"\n\t\"runtime\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\tgofigCore \"github.com\/akutz\/gofig\"\n\tgofig \"github.com\/akutz\/gofig\/types\"\n\n\t\"github.com\/codedellemc\/libstorage\/api\/context\"\n\t\"github.com\/codedellemc\/libstorage\/api\/registry\"\n\t\"github.com\/codedellemc\/libstorage\/api\/types\"\n)\n\nconst (\n\tlogStdoutDesc = \"The file to which to log os.Stdout\"\n\tlogStderrDesc = \"The file to which to log os.Stderr\"\n)\n\nfunc init() {\n\tgofigCore.LogGetAndSet = false\n\tgofigCore.LogSecureKey = false\n\tgofigCore.LogFlattenEnvVars = false\n\n\tregistry.RegisterConfigReg(\n\t\t\"libStorage\",\n\t\tfunc(ctx types.Context, r gofig.ConfigRegistration) {\n\n\t\t\tpathConfig := context.MustPathConfig(ctx)\n\n\t\t\tvar lvl log.Level\n\t\t\tif types.Debug {\n\t\t\t\tlvl = log.DebugLevel\n\t\t\t} else {\n\t\t\t\tll, err := log.ParseLevel(os.Getenv(\"LIBSTORAGE_LOGGING_LEVEL\"))\n\t\t\t\tif err != nil {\n\t\t\t\t\tll = log.WarnLevel\n\t\t\t\t}\n\t\t\t\tlvl = ll\n\t\t\t}\n\n\t\t\trk := func(\n\t\t\t\tkeyType gofig.ConfigKeyTypes,\n\t\t\t\tdefaultVal interface{},\n\t\t\t\tdescription string,\n\t\t\t\tkeyVal types.ConfigKey,\n\t\t\t\targs ...interface{}) {\n\n\t\t\t\tif args == nil {\n\t\t\t\t\targs = []interface{}{keyVal}\n\t\t\t\t} else {\n\t\t\t\t\targs = append([]interface{}{keyVal}, args...)\n\t\t\t\t}\n\t\t\t\tr.Key(keyType, \"\", defaultVal, description, args...)\n\t\t\t}\n\n\t\t\tdefaultAEM := types.UnixEndpoint.String()\n\t\t\tdefaultStorageDriver := types.LibStorageDriverName\n\t\t\tdefaultLogLevel := lvl.String()\n\t\t\tdefaultClientType := types.IntegrationClient.String()\n\n\t\t\trk(gofig.String, \"\", \"\", types.ConfigHost)\n\t\t\trk(gofig.String, \"\", \"\", types.ConfigService)\n\t\t\trk(gofig.String, defaultAEM, \"\", types.ConfigServerAutoEndpointMode)\n\t\t\trk(gofig.String, runtime.GOOS, \"\", types.ConfigOSDriver)\n\t\t\trk(gofig.String, defaultStorageDriver, \"\",\n\t\t\t\ttypes.ConfigStorageDriver)\n\t\t\trk(gofig.String, defaultIntDriver, \"\",\n\t\t\t\ttypes.ConfigIntegrationDriver)\n\t\t\trk(gofig.String, defaultClientType, \"\", types.ConfigClientType)\n\t\t\trk(gofig.String, defaultLogLevel, \"\", types.ConfigLogLevel)\n\t\t\trk(gofig.String, \"\", logStdoutDesc, types.ConfigLogStderr)\n\t\t\trk(gofig.String, \"\", logStderrDesc, types.ConfigLogStdout)\n\t\t\trk(gofig.Bool, types.Debug, \"\", types.ConfigLogHTTPRequests)\n\t\t\trk(gofig.Bool, types.Debug, \"\", types.ConfigLogHTTPResponses)\n\t\t\trk(gofig.Bool, false, \"\", types.ConfigHTTPDisableKeepAlive)\n\t\t\trk(gofig.Int, 300, \"\", types.ConfigHTTPWriteTimeout)\n\t\t\trk(gofig.Int, 300, \"\", types.ConfigHTTPReadTimeout)\n\n\t\t\trk(gofig.String, pathConfig.LSX, \"\", types.ConfigExecutorPath)\n\n\t\t\trk(gofig.Bool, false, \"\", types.ConfigExecutorNoDownload)\n\t\t\trk(gofig.Bool, false, \"\", types.ConfigIgVolOpsMountPreempt)\n\t\t\trk(gofig.Bool, false, \"\", types.ConfigIgVolOpsCreateDisable)\n\t\t\trk(gofig.Bool, false, \"\", types.ConfigIgVolOpsRemoveDisable)\n\t\t\trk(gofig.Bool, false, \"\", types.ConfigIgVolOpsUnmountIgnoreUsed)\n\t\t\trk(gofig.Bool, true, \"\", types.ConfigIgVolOpsPathCacheEnabled)\n\t\t\trk(gofig.Bool, true, \"\", types.ConfigIgVolOpsPathCacheAsync)\n\t\t\trk(gofig.String, \"30m\", \"\", types.ConfigClientCacheInstanceID)\n\t\t\trk(gofig.String, \"30s\", \"\", types.ConfigDeviceAttachTimeout)\n\t\t\trk(gofig.Int, 0, \"\", types.ConfigDeviceScanType)\n\t\t\trk(gofig.Bool, false, \"\", types.ConfigEmbedded)\n\t\t\trk(gofig.String, \"1m\", \"\", types.ConfigServerTasksExeTimeout)\n\t\t\trk(gofig.String, \"0s\", \"\", types.ConfigServerTasksLogTimeout)\n\t\t\trk(gofig.Bool, false, \"\", types.ConfigServerParseRequestOpts)\n\n\t\t\t\/\/ tls config\n\t\t\trk(\n\t\t\t\tgofig.String,\n\t\t\t\tpathConfig.DefaultTLSCertFile,\n\t\t\t\t\"\",\n\t\t\t\ttypes.ConfigTLSCertFile)\n\t\t\trk(\n\t\t\t\tgofig.String,\n\t\t\t\tpathConfig.DefaultTLSKeyFile,\n\t\t\t\t\"\",\n\t\t\t\ttypes.ConfigTLSKeyFile)\n\t\t\trk(\n\t\t\t\tgofig.String,\n\t\t\t\tpathConfig.DefaultTLSTrustedRootsFile,\n\t\t\t\t\"\",\n\t\t\t\ttypes.ConfigTLSTrustedCertsFile)\n\t\t\trk(\n\t\t\t\tgofig.String,\n\t\t\t\tpathConfig.DefaultTLSKnownHosts,\n\t\t\t\t\"\",\n\t\t\t\ttypes.ConfigTLSKnownHosts)\n\t\t\trk(gofig.String, \"\", \"\", types.ConfigTLSServerName)\n\t\t\trk(gofig.Bool, false, \"\", types.ConfigTLSDisabled)\n\t\t\trk(gofig.Bool, false, \"\", types.ConfigTLSInsecure)\n\t\t\trk(gofig.Bool, false, \"\", types.ConfigTLSClientCertRequired)\n\n\t\t\t\/\/ auth config - client\n\t\t\trk(gofig.String, \"\", \"\", types.ConfigClientAuthToken)\n\n\t\t\t\/\/ auth config - server\n\t\t\trk(gofig.String, \"\", \"\", types.ConfigServerAuthKey)\n\t\t\trk(gofig.String, \"HS256\", \"\", types.ConfigServerAuthAlg)\n\t\t\trk(gofig.String, \"\", \"\", types.ConfigServerAuthAllow)\n\t\t\trk(gofig.String, \"\", \"\", types.ConfigServerAuthDeny)\n\t\t\trk(gofig.Bool, false, \"\", types.ConfigServerAuthDisabled)\n\t\t})\n}\n<commit_msg>TLS Boolean Property Fix<commit_after>\/\/ +build gofig\n\npackage config\n\nimport (\n\t\"os\"\n\t\"runtime\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\tgofigCore \"github.com\/akutz\/gofig\"\n\tgofig \"github.com\/akutz\/gofig\/types\"\n\n\t\"github.com\/codedellemc\/libstorage\/api\/context\"\n\t\"github.com\/codedellemc\/libstorage\/api\/registry\"\n\t\"github.com\/codedellemc\/libstorage\/api\/types\"\n)\n\nconst (\n\tlogStdoutDesc = \"The file to which to log os.Stdout\"\n\tlogStderrDesc = \"The file to which to log os.Stderr\"\n)\n\nfunc init() {\n\tgofigCore.LogGetAndSet = false\n\tgofigCore.LogSecureKey = false\n\tgofigCore.LogFlattenEnvVars = false\n\n\tregistry.RegisterConfigReg(\n\t\t\"libStorage\",\n\t\tfunc(ctx types.Context, r gofig.ConfigRegistration) {\n\n\t\t\tpathConfig := context.MustPathConfig(ctx)\n\n\t\t\tvar lvl log.Level\n\t\t\tif types.Debug {\n\t\t\t\tlvl = log.DebugLevel\n\t\t\t} else {\n\t\t\t\tll, err := log.ParseLevel(os.Getenv(\"LIBSTORAGE_LOGGING_LEVEL\"))\n\t\t\t\tif err != nil {\n\t\t\t\t\tll = log.WarnLevel\n\t\t\t\t}\n\t\t\t\tlvl = ll\n\t\t\t}\n\n\t\t\trk := func(\n\t\t\t\tkeyType gofig.ConfigKeyTypes,\n\t\t\t\tdefaultVal interface{},\n\t\t\t\tdescription string,\n\t\t\t\tkeyVal types.ConfigKey,\n\t\t\t\targs ...interface{}) {\n\n\t\t\t\tif args == nil {\n\t\t\t\t\targs = []interface{}{keyVal}\n\t\t\t\t} else {\n\t\t\t\t\targs = append([]interface{}{keyVal}, args...)\n\t\t\t\t}\n\t\t\t\tr.Key(keyType, \"\", defaultVal, description, args...)\n\t\t\t}\n\n\t\t\tdefaultAEM := types.UnixEndpoint.String()\n\t\t\tdefaultStorageDriver := types.LibStorageDriverName\n\t\t\tdefaultLogLevel := lvl.String()\n\t\t\tdefaultClientType := types.IntegrationClient.String()\n\n\t\t\trk(gofig.String, \"\", \"\", types.ConfigHost)\n\t\t\trk(gofig.String, \"\", \"\", types.ConfigService)\n\t\t\trk(gofig.String, defaultAEM, \"\", types.ConfigServerAutoEndpointMode)\n\t\t\trk(gofig.String, runtime.GOOS, \"\", types.ConfigOSDriver)\n\t\t\trk(gofig.String, defaultStorageDriver, \"\",\n\t\t\t\ttypes.ConfigStorageDriver)\n\t\t\trk(gofig.String, defaultIntDriver, \"\",\n\t\t\t\ttypes.ConfigIntegrationDriver)\n\t\t\trk(gofig.String, defaultClientType, \"\", types.ConfigClientType)\n\t\t\trk(gofig.String, defaultLogLevel, \"\", types.ConfigLogLevel)\n\t\t\trk(gofig.String, \"\", logStdoutDesc, types.ConfigLogStderr)\n\t\t\trk(gofig.String, \"\", logStderrDesc, types.ConfigLogStdout)\n\t\t\trk(gofig.Bool, types.Debug, \"\", types.ConfigLogHTTPRequests)\n\t\t\trk(gofig.Bool, types.Debug, \"\", types.ConfigLogHTTPResponses)\n\t\t\trk(gofig.Bool, false, \"\", types.ConfigHTTPDisableKeepAlive)\n\t\t\trk(gofig.Int, 300, \"\", types.ConfigHTTPWriteTimeout)\n\t\t\trk(gofig.Int, 300, \"\", types.ConfigHTTPReadTimeout)\n\n\t\t\trk(gofig.String, pathConfig.LSX, \"\", types.ConfigExecutorPath)\n\n\t\t\trk(gofig.Bool, false, \"\", types.ConfigExecutorNoDownload)\n\t\t\trk(gofig.Bool, false, \"\", types.ConfigIgVolOpsMountPreempt)\n\t\t\trk(gofig.Bool, false, \"\", types.ConfigIgVolOpsCreateDisable)\n\t\t\trk(gofig.Bool, false, \"\", types.ConfigIgVolOpsRemoveDisable)\n\t\t\trk(gofig.Bool, false, \"\", types.ConfigIgVolOpsUnmountIgnoreUsed)\n\t\t\trk(gofig.Bool, true, \"\", types.ConfigIgVolOpsPathCacheEnabled)\n\t\t\trk(gofig.Bool, true, \"\", types.ConfigIgVolOpsPathCacheAsync)\n\t\t\trk(gofig.String, \"30m\", \"\", types.ConfigClientCacheInstanceID)\n\t\t\trk(gofig.String, \"30s\", \"\", types.ConfigDeviceAttachTimeout)\n\t\t\trk(gofig.Int, 0, \"\", types.ConfigDeviceScanType)\n\t\t\trk(gofig.Bool, false, \"\", types.ConfigEmbedded)\n\t\t\trk(gofig.String, \"1m\", \"\", types.ConfigServerTasksExeTimeout)\n\t\t\trk(gofig.String, \"0s\", \"\", types.ConfigServerTasksLogTimeout)\n\t\t\trk(gofig.Bool, false, \"\", types.ConfigServerParseRequestOpts)\n\n\t\t\t\/\/ tls config\n\t\t\trk(\n\t\t\t\tgofig.String,\n\t\t\t\tpathConfig.DefaultTLSCertFile,\n\t\t\t\t\"\",\n\t\t\t\ttypes.ConfigTLSCertFile)\n\t\t\trk(\n\t\t\t\tgofig.String,\n\t\t\t\tpathConfig.DefaultTLSKeyFile,\n\t\t\t\t\"\",\n\t\t\t\ttypes.ConfigTLSKeyFile)\n\t\t\trk(\n\t\t\t\tgofig.String,\n\t\t\t\tpathConfig.DefaultTLSTrustedRootsFile,\n\t\t\t\t\"\",\n\t\t\t\ttypes.ConfigTLSTrustedCertsFile)\n\t\t\trk(\n\t\t\t\tgofig.String,\n\t\t\t\tpathConfig.DefaultTLSKnownHosts,\n\t\t\t\t\"\",\n\t\t\t\ttypes.ConfigTLSKnownHosts)\n\t\t\trk(gofig.String, \"\", \"\", types.ConfigTLSServerName)\n\t\t\trk(gofig.String, \"\", \"\", types.ConfigTLSDisabled)\n\t\t\trk(gofig.String, \"\", \"\", types.ConfigTLSInsecure)\n\t\t\trk(gofig.String, \"\", \"\", types.ConfigTLSClientCertRequired)\n\n\t\t\t\/\/ auth config - client\n\t\t\trk(gofig.String, \"\", \"\", types.ConfigClientAuthToken)\n\n\t\t\t\/\/ auth config - server\n\t\t\trk(gofig.String, \"\", \"\", types.ConfigServerAuthKey)\n\t\t\trk(gofig.String, \"HS256\", \"\", types.ConfigServerAuthAlg)\n\t\t\trk(gofig.String, \"\", \"\", types.ConfigServerAuthAllow)\n\t\t\trk(gofig.String, \"\", \"\", types.ConfigServerAuthDeny)\n\t\t\trk(gofig.Bool, false, \"\", types.ConfigServerAuthDisabled)\n\t\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Porgram: FfCvt\n\/\/ Purpose: ffmpeg convert wrapper tool\n\/\/ Authors: Tong Sun (c) 2015, All rights reserved\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/*\n\nTranscodes all episodes in the given directory and all of it's subdirectories\nusing ffmpeg.\n\nInitial version based (but also heavily hacked) on\nhttps:\/\/gist.github.com\/mmstick\/3182c1c8596c1f830c7e\nby Michael Murphy (mmstick)\n\n*\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Program start\n\npackage main\n\nimport (\n\t\"bytes\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Constant and data type\/structure definitions\n\nconst (\n\tSTATIC_PARAMS = \"me=star:subme=7:bframes=16:b-adapt=2:ref=16:rc-lookahead=60:max-merge=5:tu-intra-depth=4:tu-inter-depth=4\"\n)\n\n\/\/ Contains information about each episode\ntype Episode struct {\n\tname           string\n\tdirectory      string\n\toriginalSize   int64\n\ttranscodedSize int64\n\tsizeDifference int64\n\ttime           time.Duration\n\tstat           error\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Global variables definitions\n\nvar (\n\tsprintf = fmt.Sprintf\n)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Main\n\nfunc main() {\n\tflag.Usage = Usage\n\tflag.Parse()\n\n\t\/\/ One mandatory arguments, either -d or -f\n\tif len(Opts.Directory)+len(Opts.File) < 1 {\n\t\tUsage()\n\t}\n\n\tstartTime := time.Now()\n\tif Opts.Directory != \"\" {\n\t\ttranscodeEpisodes(scanEpisodes(scanDirectory(Opts.Directory), Opts.Directory))\n\t} else if Opts.File != \"\" {\n\t\toutputName := getOutputName(Opts.File)\n\t\tfmt.Printf(\"\\n== Transcoding: %s\\n\", Opts.File)\n\t\ttranscodeFile(Opts.File, outputName)\n\t}\n\tfmt.Printf(\"Transcoding completed in %s\\n\", time.Since(startTime))\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function definitions\n\n\/\/==========================================================================\n\/\/ Directory & Episodes handling\n\n\/\/ Transcodes all episodes in the episode list\nfunc transcodeEpisodes(episodeList *[]Episode) {\n\tfiles := len(*episodeList)\n\tfor index, ep := range *episodeList {\n\t\tep.transcodeEpisode(index+1, files)\n\t\tep.status()\n\t}\n}\n\n\/\/ Print the status of the transcoded episode\nfunc (episode Episode) status() {\n\tif episode.stat != nil {\n\t\tfmt.Println(\"Failed to transcode\", episode.name)\n\t} else {\n\t\tfmt.Println(\"Transcoded\", episode.name)\n\t\tfmt.Println(\"Original Size:\", episode.originalSize, \"MB\")\n\t\tfmt.Println(\"New Size:\", episode.transcodedSize, \"MB\")\n\t\tfmt.Println(\"Difference:\", episode.sizeDifference, \"MB\")\n\t\tfmt.Println(\"Time:\", episode.time)\n\t}\n}\n\n\/\/ Recurse through each subdirectory and adds each episode to the episode list\nfunc scanEpisodes(directoryList []os.FileInfo, directory string) *[]Episode {\n\tlist := []Episode{}\n\tfor _, file := range directoryList {\n\t\tif file.IsDir() {\n\t\t\trecurseDirectory(&directory, file.Name())\n\t\t} else {\n\t\t\tappendEpisode(&list, file, &directory)\n\t\t}\n\t}\n\treturn &list\n}\n\n\/\/ Returns a list of files in the current directory\nfunc scanDirectory(path string) []os.FileInfo {\n\tdirectory, _ := ioutil.ReadDir(path)\n\treturn directory\n}\n\n\/\/ If the file is a directory, recurse through the directory.\nfunc recurseDirectory(directory *string, filename string) {\n\tsubdirectory := sprintf(\"%s\/%s\", *directory, filename)\n\tscanEpisodes(scanDirectory(subdirectory), subdirectory)\n}\n\n\/\/ Append the current episode to the episode list, unless it's encoded already\nfunc appendEpisode(list *[]Episode, file os.FileInfo, directory *string) {\n\tfname := file.Name()\n\tif fname[len(fname)-5:] == \"_.mkv\" {\n\t\treturn\n\t}\n\n\t*list = append(*list, Episode{\n\t\tname:         fname,\n\t\tdirectory:    *directory,\n\t\toriginalSize: file.Size() \/ 1000000,\n\t})\n}\n\n\/\/==========================================================================\n\/\/ Transcode handling\n\n\/\/ Transcode the current episode\nfunc (ep Episode) transcodeEpisode(index, files int) {\n\tinputName := sprintf(\"%s\/%s\", ep.directory, ep.name)\n\toutputName := getOutputName(inputName)\n\tfmt.Printf(\"\\n== Transcoding [%d\/%d]: %s\\n\", index, files, ep.name)\n\tep.time, ep.stat = transcodeFile(inputName, outputName)\n\tep.transcodedSize = transcodeSize(outputName)\n\tep.sizeDifference = ep.originalSize - ep.transcodedSize\n}\n\nfunc transcodeFile(inputName, outputName string) (time.Duration, error) {\n\tstartTime := time.Now()\n\n\targs := encodeParametersV(encodeParametersA(\n\t\t[]string{\"-i\", inputName}))\n\targs = append(args, os.Args...)\n\targs = append(args, outputName)\n\tdebug(Opts.FFMpeg)\n\tdebug(strings.Join(args, \" \"))\n\n\tcmd := exec.Command(Opts.FFMpeg, args...)\n\tvar out bytes.Buffer\n\tcmd.Stdout = &out\n\terr := cmd.Run()\n\tif err != nil {\n\t\tlog.Printf(\"%s: Exec error - %s\", progname, err.Error())\n\t}\n\t\/\/fmt.Printf(\"\\n== Out:\\n%s\\n\", out.String())\n\ttime := time.Since(startTime)\n\treturn time, err\n}\n\n\/\/ Returns the encode parameters for Audio\nfunc encodeParametersA(args []string) []string {\n\tif Opts.AC {\n\t\targs = append(args, \"-c:a\", \"copy\")\n\t\treturn args\n\t}\n\treturn args\n}\n\n\/\/ Returns the encode parameters for Video\nfunc encodeParametersV(args []string) []string {\n\tif Opts.VC {\n\t\targs = append(args, \"-c:v\", \"copy\")\n\t\treturn args\n\t}\n\treturn args\n}\n\n\/\/ Returns the size of the newly transcoded episode, if it exists.\nfunc transcodeSize(transcodedEpisode string) int64 {\n\tfile, err := os.Open(transcodedEpisode)\n\tif err == nil {\n\t\tstat, _ := file.Stat()\n\t\treturn stat.Size() \/ 1000000\n\t} else {\n\t\tlog.Printf(\"%s: Open error - %s\", progname, err.Error())\n\t\treturn 0\n\t}\n}\n\n\/\/ Replaces the file extension from the input string with _.mkv\nfunc getOutputName(input string) string {\n\tfor index := len(input) - 1; index >= 0; index-- {\n\t\tif input[index] == '.' {\n\t\t\tinput = input[:index]\n\t\t}\n\t}\n\treturn input + \"_.mkv\"\n}\n\nfunc debug(input string) {\n\tif Opts.Debug == 0 {\n\t\treturn\n\t}\n\tprint(\"] \")\n\tprint(input)\n\tprint(\"\\n\")\n}\n<commit_msg>- [!] use flag.Args() instead to catch not all but the rest of non-flag arguments<commit_after>\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Porgram: FfCvt\n\/\/ Purpose: ffmpeg convert wrapper tool\n\/\/ Authors: Tong Sun (c) 2015, All rights reserved\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/*\n\nTranscodes all episodes in the given directory and all of it's subdirectories\nusing ffmpeg.\n\nInitial version based (but also heavily hacked) on\nhttps:\/\/gist.github.com\/mmstick\/3182c1c8596c1f830c7e\nby Michael Murphy (mmstick)\n\n*\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Program start\n\npackage main\n\nimport (\n\t\"bytes\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Constant and data type\/structure definitions\n\nconst (\n\tSTATIC_PARAMS = \"me=star:subme=7:bframes=16:b-adapt=2:ref=16:rc-lookahead=60:max-merge=5:tu-intra-depth=4:tu-inter-depth=4\"\n)\n\n\/\/ Contains information about each episode\ntype Episode struct {\n\tname           string\n\tdirectory      string\n\toriginalSize   int64\n\ttranscodedSize int64\n\tsizeDifference int64\n\ttime           time.Duration\n\tstat           error\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Global variables definitions\n\nvar (\n\tsprintf = fmt.Sprintf\n)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Main\n\nfunc main() {\n\tflag.Usage = Usage\n\tflag.Parse()\n\n\t\/\/ One mandatory arguments, either -d or -f\n\tif len(Opts.Directory)+len(Opts.File) < 1 {\n\t\tUsage()\n\t}\n\n\tstartTime := time.Now()\n\tif Opts.Directory != \"\" {\n\t\ttranscodeEpisodes(scanEpisodes(scanDirectory(Opts.Directory), Opts.Directory))\n\t} else if Opts.File != \"\" {\n\t\toutputName := getOutputName(Opts.File)\n\t\tfmt.Printf(\"\\n== Transcoding: %s\\n\", Opts.File)\n\t\ttranscodeFile(Opts.File, outputName)\n\t}\n\tfmt.Printf(\"Transcoding completed in %s\\n\", time.Since(startTime))\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Function definitions\n\n\/\/==========================================================================\n\/\/ Directory & Episodes handling\n\n\/\/ Transcodes all episodes in the episode list\nfunc transcodeEpisodes(episodeList *[]Episode) {\n\tfiles := len(*episodeList)\n\tfor index, ep := range *episodeList {\n\t\tep.transcodeEpisode(index+1, files)\n\t\tep.status()\n\t}\n}\n\n\/\/ Print the status of the transcoded episode\nfunc (episode Episode) status() {\n\tif episode.stat != nil {\n\t\tfmt.Println(\"Failed to transcode\", episode.name)\n\t} else {\n\t\tfmt.Println(\"Transcoded\", episode.name)\n\t\tfmt.Println(\"Original Size:\", episode.originalSize, \"MB\")\n\t\tfmt.Println(\"New Size:\", episode.transcodedSize, \"MB\")\n\t\tfmt.Println(\"Difference:\", episode.sizeDifference, \"MB\")\n\t\tfmt.Println(\"Time:\", episode.time)\n\t}\n}\n\n\/\/ Recurse through each subdirectory and adds each episode to the episode list\nfunc scanEpisodes(directoryList []os.FileInfo, directory string) *[]Episode {\n\tlist := []Episode{}\n\tfor _, file := range directoryList {\n\t\tif file.IsDir() {\n\t\t\trecurseDirectory(&directory, file.Name())\n\t\t} else {\n\t\t\tappendEpisode(&list, file, &directory)\n\t\t}\n\t}\n\treturn &list\n}\n\n\/\/ Returns a list of files in the current directory\nfunc scanDirectory(path string) []os.FileInfo {\n\tdirectory, _ := ioutil.ReadDir(path)\n\treturn directory\n}\n\n\/\/ If the file is a directory, recurse through the directory.\nfunc recurseDirectory(directory *string, filename string) {\n\tsubdirectory := sprintf(\"%s\/%s\", *directory, filename)\n\tscanEpisodes(scanDirectory(subdirectory), subdirectory)\n}\n\n\/\/ Append the current episode to the episode list, unless it's encoded already\nfunc appendEpisode(list *[]Episode, file os.FileInfo, directory *string) {\n\tfname := file.Name()\n\tif fname[len(fname)-5:] == \"_.mkv\" {\n\t\treturn\n\t}\n\n\t*list = append(*list, Episode{\n\t\tname:         fname,\n\t\tdirectory:    *directory,\n\t\toriginalSize: file.Size() \/ 1000000,\n\t})\n}\n\n\/\/==========================================================================\n\/\/ Transcode handling\n\n\/\/ Transcode the current episode\nfunc (ep Episode) transcodeEpisode(index, files int) {\n\tinputName := sprintf(\"%s\/%s\", ep.directory, ep.name)\n\toutputName := getOutputName(inputName)\n\tfmt.Printf(\"\\n== Transcoding [%d\/%d]: %s\\n\", index, files, ep.name)\n\tep.time, ep.stat = transcodeFile(inputName, outputName)\n\tep.transcodedSize = transcodeSize(outputName)\n\tep.sizeDifference = ep.originalSize - ep.transcodedSize\n}\n\nfunc transcodeFile(inputName, outputName string) (time.Duration, error) {\n\tstartTime := time.Now()\n\n\targs := encodeParametersV(encodeParametersA(\n\t\t[]string{\"-i\", inputName}))\n\targs = append(args, flag.Args()...)\n\targs = append(args, outputName)\n\tdebug(Opts.FFMpeg)\n\tdebug(strings.Join(args, \" \"))\n\n\tcmd := exec.Command(Opts.FFMpeg, args...)\n\tvar out bytes.Buffer\n\tcmd.Stdout = &out\n\terr := cmd.Run()\n\tif err != nil {\n\t\tlog.Printf(\"%s: Exec error - %s\", progname, err.Error())\n\t}\n\tfmt.Printf(\"\\n%s\\n\", out.String())\n\ttime := time.Since(startTime)\n\treturn time, err\n}\n\n\/\/ Returns the encode parameters for Audio\nfunc encodeParametersA(args []string) []string {\n\tif Opts.AC {\n\t\targs = append(args, \"-c:a\", \"copy\")\n\t\treturn args\n\t}\n\treturn args\n}\n\n\/\/ Returns the encode parameters for Video\nfunc encodeParametersV(args []string) []string {\n\tif Opts.VC {\n\t\targs = append(args, \"-c:v\", \"copy\")\n\t\treturn args\n\t}\n\treturn args\n}\n\n\/\/ Returns the size of the newly transcoded episode, if it exists.\nfunc transcodeSize(transcodedEpisode string) int64 {\n\tfile, err := os.Open(transcodedEpisode)\n\tif err == nil {\n\t\tstat, _ := file.Stat()\n\t\treturn stat.Size() \/ 1000000\n\t} else {\n\t\tlog.Printf(\"%s: Open error - %s\", progname, err.Error())\n\t\treturn 0\n\t}\n}\n\n\/\/ Replaces the file extension from the input string with _.mkv\nfunc getOutputName(input string) string {\n\tfor index := len(input) - 1; index >= 0; index-- {\n\t\tif input[index] == '.' {\n\t\t\tinput = input[:index]\n\t\t}\n\t}\n\treturn input + \"_.mkv\"\n}\n\nfunc debug(input string) {\n\tif Opts.Debug == 0 {\n\t\treturn\n\t}\n\tprint(\"] \")\n\tprint(input)\n\tprint(\"\\n\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package compress\n\nimport (\n\t\"archive\/tar\"\n\t\"archive\/zip\"\n\t\"compress\/gzip\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"runtime\"\n\n\t\"github.com\/klauspost\/pgzip\"\n\t\"github.com\/mitchellh\/packer\/common\"\n\t\"github.com\/mitchellh\/packer\/helper\/config\"\n\t\"github.com\/mitchellh\/packer\/packer\"\n\t\"github.com\/mitchellh\/packer\/template\/interpolate\"\n\t\"github.com\/pierrec\/lz4\"\n)\n\ntype Config struct {\n\tcommon.PackerConfig `mapstructure:\",squash\"`\n\n\t\/\/ Fields from config file\n\tOutputPath        string `mapstructure:\"output\"`\n\tCompressionLevel  int    `mapstructure:\"compression_level\"`\n\tKeepInputArtifact bool   `mapstructure:\"keep_input_artifact\"`\n\n\t\/\/ Derived fields\n\tArchive   string\n\tAlgorithm string\n\n\tctx *interpolate.Context\n}\n\ntype PostProcessor struct {\n\tconfig *Config\n}\n\nvar (\n\t\/\/ ErrInvalidCompressionLevel is returned when the compression level passed\n\t\/\/ to gzip is not in the expected range. See compress\/flate for details.\n\tErrInvalidCompressionLevel = fmt.Errorf(\n\t\t\"Invalid compression level. Expected an integer from -1 to 9.\")\n\n\tErrWrongInputCount = fmt.Errorf(\n\t\t\"Can only have 1 input file when not using tar\/zip\")\n\n\tfilenamePattern = regexp.MustCompile(`(?:\\.([a-z0-9]+))`)\n)\n\nfunc (p *PostProcessor) Configure(raws ...interface{}) error {\n\terr := config.Decode(&p.config, &config.DecodeOpts{\n\t\tInterpolate: true,\n\t\tInterpolateFilter: &interpolate.RenderFilter{\n\t\t\tExclude: []string{},\n\t\t},\n\t}, raws...)\n\n\terrs := new(packer.MultiError)\n\n\tif p.config.OutputPath == \"\" {\n\t\tp.config.OutputPath = \"packer_{{.BuildName}}_{{.Provider}}\"\n\t}\n\n\tif err = interpolate.Validate(p.config.OutputPath, p.config.ctx); err != nil {\n\t\terrs = packer.MultiErrorAppend(\n\t\t\terrs, fmt.Errorf(\"Error parsing target template: %s\", err))\n\t}\n\n\ttemplates := map[string]*string{\n\t\t\"output\": &p.config.OutputPath,\n\t}\n\n\tif p.config.CompressionLevel > pgzip.BestCompression {\n\t\tp.config.CompressionLevel = pgzip.BestCompression\n\t}\n\t\/\/ Technically 0 means \"don't compress\" but I don't know how to\n\t\/\/ differentiate between \"user entered zero\" and \"user entered nothing\".\n\t\/\/ Also, why bother creating a compressed file with zero compression?\n\tif p.config.CompressionLevel == -1 || p.config.CompressionLevel == 0 {\n\t\tp.config.CompressionLevel = pgzip.DefaultCompression\n\t}\n\n\tfor key, ptr := range templates {\n\t\tif *ptr == \"\" {\n\t\t\terrs = packer.MultiErrorAppend(\n\t\t\t\terrs, fmt.Errorf(\"%s must be set\", key))\n\t\t}\n\n\t\t*ptr, err = interpolate.Render(p.config.OutputPath, p.config.ctx)\n\t\tif err != nil {\n\t\t\terrs = packer.MultiErrorAppend(\n\t\t\t\terrs, fmt.Errorf(\"Error processing %s: %s\", key, err))\n\t\t}\n\t}\n\n\tp.config.detectFromFilename()\n\n\tif len(errs.Errors) > 0 {\n\t\treturn errs\n\t}\n\n\treturn nil\n\n}\n\nfunc (p *PostProcessor) PostProcess(ui packer.Ui, artifact packer.Artifact) (packer.Artifact, bool, error) {\n\n\ttarget := p.config.OutputPath\n\tkeep := p.config.KeepInputArtifact\n\tnewArtifact := &Artifact{Path: target}\n\n\toutputFile, err := os.Create(target)\n\tif err != nil {\n\t\treturn nil, false, fmt.Errorf(\n\t\t\t\"Unable to create archive %s: %s\", target, err)\n\t}\n\tdefer outputFile.Close()\n\n\t\/\/ Setup output interface. If we're using compression, output is a\n\t\/\/ compression writer. Otherwise it's just a file.\n\tvar output io.WriteCloser\n\tswitch p.config.Algorithm {\n\tcase \"lz4\":\n\t\tui.Say(fmt.Sprintf(\"Preparing lz4 compression for %s\", target))\n\t\toutput, err = makeLZ4Writer(outputFile, p.config.CompressionLevel)\n\t\tdefer output.Close()\n\tcase \"pgzip\":\n\t\tui.Say(fmt.Sprintf(\"Preparing gzip compression for %s\", target))\n\t\toutput, err = makePgzipWriter(outputFile, p.config.CompressionLevel)\n\t\tdefer output.Close()\n\tdefault:\n\t\toutput = outputFile\n\t}\n\n\tcompression := p.config.Algorithm\n\tif compression == \"\" {\n\t\tcompression = \"no\"\n\t}\n\n\t\/\/ Build an archive, if we're supposed to do that.\n\tswitch p.config.Archive {\n\tcase \"tar\":\n\t\tui.Say(fmt.Sprintf(\"Tarring %s with %s compression\", target, compression))\n\t\terr = createTarArchive(artifact.Files(), output)\n\t\tif err != nil {\n\t\t\treturn nil, keep, fmt.Errorf(\"Error creating tar: %s\", err)\n\t\t}\n\tcase \"zip\":\n\t\tui.Say(fmt.Sprintf(\"Zipping %s\", target))\n\t\terr = createZipArchive(artifact.Files(), output)\n\t\tif err != nil {\n\t\t\treturn nil, keep, fmt.Errorf(\"Error creating zip: %s\", err)\n\t\t}\n\tdefault:\n\t\tui.Say(fmt.Sprintf(\"Copying %s with %s compression\", target, compression))\n\t\t\/\/ Filename indicates no tarball (just compress) so we'll do an io.Copy\n\t\t\/\/ into our compressor.\n\t\tif len(artifact.Files()) != 1 {\n\t\t\treturn nil, keep, fmt.Errorf(\n\t\t\t\t\"Can only have 1 input file when not using tar\/zip. Found %d \"+\n\t\t\t\t\t\"files: %v\", len(artifact.Files()), artifact.Files())\n\t\t}\n\n\t\tsource, err := os.Open(artifact.Files()[0])\n\t\tif err != nil {\n\t\t\treturn nil, keep, fmt.Errorf(\n\t\t\t\t\"Failed to open source file %s for reading: %s\",\n\t\t\t\tartifact.Files()[0], err)\n\t\t}\n\t\tdefer source.Close()\n\n\t\tif _, err = io.Copy(output, source); err != nil {\n\t\t\treturn nil, keep, fmt.Errorf(\"Failed to compress %s: %s\",\n\t\t\t\tartifact.Files()[0], err)\n\t\t}\n\t}\n\n\tui.Say(fmt.Sprintf(\"Archive %s completed\", target))\n\n\treturn newArtifact, keep, nil\n}\n\nfunc (config *Config) detectFromFilename() {\n\n\textensions := map[string]string{\n\t\t\"tar\": \"tar\",\n\t\t\"zip\": \"zip\",\n\t\t\"gz\":  \"pgzip\",\n\t\t\"lz4\": \"lz4\",\n\t}\n\n\tresult := filenamePattern.FindAllStringSubmatch(config.OutputPath, -1)\n\n\t\/\/ No dots. Bail out with defaults.\n\tif len(result) == 0 {\n\t\tconfig.Algorithm = \"pgzip\"\n\t\tconfig.Archive = \"tar\"\n\t\treturn\n\t}\n\n\t\/\/ Parse the last two .groups, if they're there\n\tlastItem := result[len(result)-1][1]\n\tvar nextToLastItem string\n\tif len(result) == 1 {\n\t\tnextToLastItem = \"\"\n\t} else {\n\t\tnextToLastItem = result[len(result)-2][1]\n\t}\n\n\t\/\/ Should we make an archive? E.g. tar or zip?\n\tif nextToLastItem == \"tar\" {\n\t\tconfig.Archive = \"tar\"\n\t}\n\tif lastItem == \"zip\" || lastItem == \"tar\" {\n\t\tconfig.Archive = lastItem\n\t\t\/\/ Tar or zip is our final artifact. Bail out.\n\t\treturn\n\t}\n\n\t\/\/ Should we compress the artifact?\n\talgorithm, ok := extensions[lastItem]\n\tif ok {\n\t\tconfig.Algorithm = algorithm\n\t\t\/\/ We found our compression algorithm. Bail out.\n\t\treturn\n\t}\n\n\t\/\/ We didn't match a known compression format. Default to tar + pgzip\n\tconfig.Algorithm = \"pgzip\"\n\tconfig.Archive = \"tar\"\n\treturn\n}\n\nfunc makeLZ4Writer(output io.WriteCloser, compressionLevel int) (io.WriteCloser, error) {\n\tlzwriter := lz4.NewWriter(output)\n\tif compressionLevel > gzip.DefaultCompression {\n\t\tlzwriter.Header.HighCompression = true\n\t}\n\treturn lzwriter, nil\n}\n\nfunc makePgzipWriter(output io.WriteCloser, compressionLevel int) (io.WriteCloser, error) {\n\tgzipWriter, err := pgzip.NewWriterLevel(output, compressionLevel)\n\tif err != nil {\n\t\treturn nil, ErrInvalidCompressionLevel\n\t}\n\tgzipWriter.SetConcurrency(500000, runtime.GOMAXPROCS(-1))\n\treturn gzipWriter, nil\n}\n\nfunc createTarArchive(files []string, output io.WriteCloser) error {\n\tarchive := tar.NewWriter(output)\n\tdefer archive.Close()\n\n\tfor _, path := range files {\n\t\tfile, err := os.Open(path)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Unable to read file %s: %s\", path, err)\n\t\t}\n\t\tdefer file.Close()\n\n\t\tfi, err := file.Stat()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Unable to get fileinfo for %s: %s\", path, err)\n\t\t}\n\n\t\theader, err := tar.FileInfoHeader(fi, path)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to create tar header for %s: %s\", path, err)\n\t\t}\n\n\t\tif err := archive.WriteHeader(header); err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to write tar header for %s: %s\", path, err)\n\t\t}\n\n\t\tif _, err := io.Copy(archive, file); err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to copy %s data to archive: %s\", path, err)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc createZipArchive(files []string, output io.WriteCloser) error {\n\tarchive := zip.NewWriter(output)\n\tdefer archive.Close()\n\n\tfor _, path := range files {\n\t\tpath = filepath.ToSlash(path)\n\n\t\tsource, err := os.Open(path)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Unable to read file %s: %s\", path, err)\n\t\t}\n\t\tdefer source.Close()\n\n\t\ttarget, err := archive.Create(path)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to add zip header for %s: %s\", path, err)\n\t\t}\n\n\t\t_, err = io.Copy(target, source)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to copy %s data to archive: %s\", path, err)\n\t\t}\n\t}\n\treturn nil\n}\n<commit_msg>Tweaked some of the UI\/UX around GOMAXPROCS<commit_after>package compress\n\nimport (\n\t\"archive\/tar\"\n\t\"archive\/zip\"\n\t\"compress\/gzip\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"runtime\"\n\n\t\"github.com\/klauspost\/pgzip\"\n\t\"github.com\/mitchellh\/packer\/common\"\n\t\"github.com\/mitchellh\/packer\/helper\/config\"\n\t\"github.com\/mitchellh\/packer\/packer\"\n\t\"github.com\/mitchellh\/packer\/template\/interpolate\"\n\t\"github.com\/pierrec\/lz4\"\n)\n\ntype Config struct {\n\tcommon.PackerConfig `mapstructure:\",squash\"`\n\n\t\/\/ Fields from config file\n\tOutputPath        string `mapstructure:\"output\"`\n\tCompressionLevel  int    `mapstructure:\"compression_level\"`\n\tKeepInputArtifact bool   `mapstructure:\"keep_input_artifact\"`\n\n\t\/\/ Derived fields\n\tArchive   string\n\tAlgorithm string\n\n\tctx *interpolate.Context\n}\n\ntype PostProcessor struct {\n\tconfig *Config\n}\n\nvar (\n\t\/\/ ErrInvalidCompressionLevel is returned when the compression level passed\n\t\/\/ to gzip is not in the expected range. See compress\/flate for details.\n\tErrInvalidCompressionLevel = fmt.Errorf(\n\t\t\"Invalid compression level. Expected an integer from -1 to 9.\")\n\n\tErrWrongInputCount = fmt.Errorf(\n\t\t\"Can only have 1 input file when not using tar\/zip\")\n\n\tfilenamePattern = regexp.MustCompile(`(?:\\.([a-z0-9]+))`)\n)\n\nfunc (p *PostProcessor) Configure(raws ...interface{}) error {\n\terr := config.Decode(&p.config, &config.DecodeOpts{\n\t\tInterpolate: true,\n\t\tInterpolateFilter: &interpolate.RenderFilter{\n\t\t\tExclude: []string{},\n\t\t},\n\t}, raws...)\n\n\terrs := new(packer.MultiError)\n\n\t\/\/ If there is no explicit number of Go threads to use, then set it\n\tif os.Getenv(\"GOMAXPROCS\") == \"\" {\n\t\truntime.GOMAXPROCS(runtime.NumCPU())\n\t}\n\n\tif p.config.OutputPath == \"\" {\n\t\tp.config.OutputPath = \"packer_{{.BuildName}}_{{.Provider}}\"\n\t}\n\n\tif err = interpolate.Validate(p.config.OutputPath, p.config.ctx); err != nil {\n\t\terrs = packer.MultiErrorAppend(\n\t\t\terrs, fmt.Errorf(\"Error parsing target template: %s\", err))\n\t}\n\n\ttemplates := map[string]*string{\n\t\t\"output\": &p.config.OutputPath,\n\t}\n\n\tif p.config.CompressionLevel > pgzip.BestCompression {\n\t\tp.config.CompressionLevel = pgzip.BestCompression\n\t}\n\t\/\/ Technically 0 means \"don't compress\" but I don't know how to\n\t\/\/ differentiate between \"user entered zero\" and \"user entered nothing\".\n\t\/\/ Also, why bother creating a compressed file with zero compression?\n\tif p.config.CompressionLevel == -1 || p.config.CompressionLevel == 0 {\n\t\tp.config.CompressionLevel = pgzip.DefaultCompression\n\t}\n\n\tfor key, ptr := range templates {\n\t\tif *ptr == \"\" {\n\t\t\terrs = packer.MultiErrorAppend(\n\t\t\t\terrs, fmt.Errorf(\"%s must be set\", key))\n\t\t}\n\n\t\t*ptr, err = interpolate.Render(p.config.OutputPath, p.config.ctx)\n\t\tif err != nil {\n\t\t\terrs = packer.MultiErrorAppend(\n\t\t\t\terrs, fmt.Errorf(\"Error processing %s: %s\", key, err))\n\t\t}\n\t}\n\n\tp.config.detectFromFilename()\n\n\tif len(errs.Errors) > 0 {\n\t\treturn errs\n\t}\n\n\treturn nil\n\n}\n\nfunc (p *PostProcessor) PostProcess(ui packer.Ui, artifact packer.Artifact) (packer.Artifact, bool, error) {\n\n\ttarget := p.config.OutputPath\n\tkeep := p.config.KeepInputArtifact\n\tnewArtifact := &Artifact{Path: target}\n\n\toutputFile, err := os.Create(target)\n\tif err != nil {\n\t\treturn nil, false, fmt.Errorf(\n\t\t\t\"Unable to create archive %s: %s\", target, err)\n\t}\n\tdefer outputFile.Close()\n\n\t\/\/ Setup output interface. If we're using compression, output is a\n\t\/\/ compression writer. Otherwise it's just a file.\n\tvar output io.WriteCloser\n\tswitch p.config.Algorithm {\n\tcase \"lz4\":\n\t\tui.Say(fmt.Sprintf(\"Using lz4 compression with %d cores for %s\",\n\t\t\truntime.GOMAXPROCS(-1), target))\n\t\toutput, err = makeLZ4Writer(outputFile, p.config.CompressionLevel)\n\t\tdefer output.Close()\n\tcase \"pgzip\":\n\t\tui.Say(fmt.Sprintf(\"Using pgzip compression with %d cores for %s\",\n\t\t\truntime.GOMAXPROCS(-1), target))\n\t\toutput, err = makePgzipWriter(outputFile, p.config.CompressionLevel)\n\t\tdefer output.Close()\n\tdefault:\n\t\toutput = outputFile\n\t}\n\n\tcompression := p.config.Algorithm\n\tif compression == \"\" {\n\t\tcompression = \"no compression\"\n\t}\n\n\t\/\/ Build an archive, if we're supposed to do that.\n\tswitch p.config.Archive {\n\tcase \"tar\":\n\t\tui.Say(fmt.Sprintf(\"Tarring %s with %s\", target, compression))\n\t\terr = createTarArchive(artifact.Files(), output)\n\t\tif err != nil {\n\t\t\treturn nil, keep, fmt.Errorf(\"Error creating tar: %s\", err)\n\t\t}\n\tcase \"zip\":\n\t\tui.Say(fmt.Sprintf(\"Zipping %s\", target))\n\t\terr = createZipArchive(artifact.Files(), output)\n\t\tif err != nil {\n\t\t\treturn nil, keep, fmt.Errorf(\"Error creating zip: %s\", err)\n\t\t}\n\tdefault:\n\t\t\/\/ Filename indicates no tarball (just compress) so we'll do an io.Copy\n\t\t\/\/ into our compressor.\n\t\tif len(artifact.Files()) != 1 {\n\t\t\treturn nil, keep, fmt.Errorf(\n\t\t\t\t\"Can only have 1 input file when not using tar\/zip. Found %d \"+\n\t\t\t\t\t\"files: %v\", len(artifact.Files()), artifact.Files())\n\t\t}\n\t\tarchiveFile := artifact.Files()[0]\n\t\tui.Say(fmt.Sprintf(\"Archiving %s with %s\", archiveFile, compression))\n\n\t\tsource, err := os.Open(archiveFile)\n\t\tif err != nil {\n\t\t\treturn nil, keep, fmt.Errorf(\n\t\t\t\t\"Failed to open source file %s for reading: %s\",\n\t\t\t\tarchiveFile, err)\n\t\t}\n\t\tdefer source.Close()\n\n\t\tif _, err = io.Copy(output, source); err != nil {\n\t\t\treturn nil, keep, fmt.Errorf(\"Failed to compress %s: %s\",\n\t\t\t\tarchiveFile, err)\n\t\t}\n\t}\n\n\tui.Say(fmt.Sprintf(\"Archive %s completed\", target))\n\n\treturn newArtifact, keep, nil\n}\n\nfunc (config *Config) detectFromFilename() {\n\n\textensions := map[string]string{\n\t\t\"tar\": \"tar\",\n\t\t\"zip\": \"zip\",\n\t\t\"gz\":  \"pgzip\",\n\t\t\"lz4\": \"lz4\",\n\t}\n\n\tresult := filenamePattern.FindAllStringSubmatch(config.OutputPath, -1)\n\n\t\/\/ No dots. Bail out with defaults.\n\tif len(result) == 0 {\n\t\tconfig.Algorithm = \"pgzip\"\n\t\tconfig.Archive = \"tar\"\n\t\treturn\n\t}\n\n\t\/\/ Parse the last two .groups, if they're there\n\tlastItem := result[len(result)-1][1]\n\tvar nextToLastItem string\n\tif len(result) == 1 {\n\t\tnextToLastItem = \"\"\n\t} else {\n\t\tnextToLastItem = result[len(result)-2][1]\n\t}\n\n\t\/\/ Should we make an archive? E.g. tar or zip?\n\tif nextToLastItem == \"tar\" {\n\t\tconfig.Archive = \"tar\"\n\t}\n\tif lastItem == \"zip\" || lastItem == \"tar\" {\n\t\tconfig.Archive = lastItem\n\t\t\/\/ Tar or zip is our final artifact. Bail out.\n\t\treturn\n\t}\n\n\t\/\/ Should we compress the artifact?\n\talgorithm, ok := extensions[lastItem]\n\tif ok {\n\t\tconfig.Algorithm = algorithm\n\t\t\/\/ We found our compression algorithm. Bail out.\n\t\treturn\n\t}\n\n\t\/\/ We didn't match a known compression format. Default to tar + pgzip\n\tconfig.Algorithm = \"pgzip\"\n\tconfig.Archive = \"tar\"\n\treturn\n}\n\nfunc makeLZ4Writer(output io.WriteCloser, compressionLevel int) (io.WriteCloser, error) {\n\tlzwriter := lz4.NewWriter(output)\n\tif compressionLevel > gzip.DefaultCompression {\n\t\tlzwriter.Header.HighCompression = true\n\t}\n\treturn lzwriter, nil\n}\n\nfunc makePgzipWriter(output io.WriteCloser, compressionLevel int) (io.WriteCloser, error) {\n\tgzipWriter, err := pgzip.NewWriterLevel(output, compressionLevel)\n\tif err != nil {\n\t\treturn nil, ErrInvalidCompressionLevel\n\t}\n\tgzipWriter.SetConcurrency(500000, runtime.GOMAXPROCS(-1))\n\treturn gzipWriter, nil\n}\n\nfunc createTarArchive(files []string, output io.WriteCloser) error {\n\tarchive := tar.NewWriter(output)\n\tdefer archive.Close()\n\n\tfor _, path := range files {\n\t\tfile, err := os.Open(path)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Unable to read file %s: %s\", path, err)\n\t\t}\n\t\tdefer file.Close()\n\n\t\tfi, err := file.Stat()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Unable to get fileinfo for %s: %s\", path, err)\n\t\t}\n\n\t\theader, err := tar.FileInfoHeader(fi, path)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to create tar header for %s: %s\", path, err)\n\t\t}\n\n\t\tif err := archive.WriteHeader(header); err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to write tar header for %s: %s\", path, err)\n\t\t}\n\n\t\tif _, err := io.Copy(archive, file); err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to copy %s data to archive: %s\", path, err)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc createZipArchive(files []string, output io.WriteCloser) error {\n\tarchive := zip.NewWriter(output)\n\tdefer archive.Close()\n\n\tfor _, path := range files {\n\t\tpath = filepath.ToSlash(path)\n\n\t\tsource, err := os.Open(path)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Unable to read file %s: %s\", path, err)\n\t\t}\n\t\tdefer source.Close()\n\n\t\ttarget, err := archive.Create(path)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to add zip header for %s: %s\", path, err)\n\t\t}\n\n\t\t_, err = io.Copy(target, source)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to copy %s data to archive: %s\", path, err)\n\t\t}\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build kvdb_etcd\n\npackage etcd\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/btcsuite\/btcwallet\/walletdb\"\n\t\"github.com\/stretchr\/testify\/require\"\n)\n\nfunc TestReadCursorEmptyInterval(t *testing.T) {\n\tt.Parallel()\n\n\tf := NewEtcdTestFixture(t)\n\tdefer f.Cleanup()\n\n\tdb, err := newEtcdBackend(f.BackendConfig())\n\trequire.NoError(t, err)\n\n\terr = db.Update(func(tx walletdb.ReadWriteTx) error {\n\t\tb, err := tx.CreateTopLevelBucket([]byte(\"alma\"))\n\t\trequire.NoError(t, err)\n\t\trequire.NotNil(t, b)\n\n\t\treturn nil\n\t})\n\trequire.NoError(t, err)\n\n\terr = db.View(func(tx walletdb.ReadTx) error {\n\t\tb := tx.ReadBucket([]byte(\"alma\"))\n\t\trequire.NotNil(t, b)\n\n\t\tcursor := b.ReadCursor()\n\t\tk, v := cursor.First()\n\t\trequire.Nil(t, k)\n\t\trequire.Nil(t, v)\n\n\t\tk, v = cursor.Next()\n\t\trequire.Nil(t, k)\n\t\trequire.Nil(t, v)\n\n\t\tk, v = cursor.Last()\n\t\trequire.Nil(t, k)\n\t\trequire.Nil(t, v)\n\n\t\tk, v = cursor.Prev()\n\t\trequire.Nil(t, k)\n\t\trequire.Nil(t, v)\n\n\t\treturn nil\n\t})\n\trequire.NoError(t, err)\n}\n\nfunc TestReadCursorNonEmptyInterval(t *testing.T) {\n\tt.Parallel()\n\n\tf := NewEtcdTestFixture(t)\n\tdefer f.Cleanup()\n\n\tdb, err := newEtcdBackend(f.BackendConfig())\n\trequire.NoError(t, err)\n\n\ttestKeyValues := []KV{\n\t\t{\"b\", \"1\"},\n\t\t{\"c\", \"2\"},\n\t\t{\"da\", \"3\"},\n\t\t{\"e\", \"4\"},\n\t}\n\n\terr = db.Update(func(tx walletdb.ReadWriteTx) error {\n\t\tb, err := tx.CreateTopLevelBucket([]byte(\"alma\"))\n\t\trequire.NoError(t, err)\n\t\trequire.NotNil(t, b)\n\n\t\tfor _, kv := range testKeyValues {\n\t\t\trequire.NoError(t, b.Put([]byte(kv.key), []byte(kv.val)))\n\t\t}\n\t\treturn nil\n\t})\n\n\trequire.NoError(t, err)\n\n\terr = db.View(func(tx walletdb.ReadTx) error {\n\t\tb := tx.ReadBucket([]byte(\"alma\"))\n\t\trequire.NotNil(t, b)\n\n\t\t\/\/ Iterate from the front.\n\t\tvar kvs []KV\n\t\tcursor := b.ReadCursor()\n\t\tk, v := cursor.First()\n\n\t\tfor k != nil && v != nil {\n\t\t\tkvs = append(kvs, KV{string(k), string(v)})\n\t\t\tk, v = cursor.Next()\n\t\t}\n\t\trequire.Equal(t, testKeyValues, kvs)\n\n\t\t\/\/ Iterate from the back.\n\t\tkvs = []KV{}\n\t\tk, v = cursor.Last()\n\n\t\tfor k != nil && v != nil {\n\t\t\tkvs = append(kvs, KV{string(k), string(v)})\n\t\t\tk, v = cursor.Prev()\n\t\t}\n\t\trequire.Equal(t, reverseKVs(testKeyValues), kvs)\n\n\t\t\/\/ Random access\n\t\tperm := []int{3, 0, 2, 1}\n\t\tfor _, i := range perm {\n\t\t\tk, v := cursor.Seek([]byte(testKeyValues[i].key))\n\t\t\trequire.Equal(t, []byte(testKeyValues[i].key), k)\n\t\t\trequire.Equal(t, []byte(testKeyValues[i].val), v)\n\t\t}\n\n\t\t\/\/ Seek to nonexisting key.\n\t\tk, v = cursor.Seek(nil)\n\t\trequire.Nil(t, k)\n\t\trequire.Nil(t, v)\n\n\t\tk, v = cursor.Seek([]byte(\"x\"))\n\t\trequire.Nil(t, k)\n\t\trequire.Nil(t, v)\n\n\t\treturn nil\n\t})\n\n\trequire.NoError(t, err)\n}\n\nfunc TestReadWriteCursor(t *testing.T) {\n\tt.Parallel()\n\n\tf := NewEtcdTestFixture(t)\n\tdefer f.Cleanup()\n\n\tdb, err := newEtcdBackend(f.BackendConfig())\n\trequire.NoError(t, err)\n\n\ttestKeyValues := []KV{\n\t\t{\"b\", \"1\"},\n\t\t{\"c\", \"2\"},\n\t\t{\"da\", \"3\"},\n\t\t{\"e\", \"4\"},\n\t}\n\n\tcount := len(testKeyValues)\n\n\t\/\/ Pre-store the first half of the interval.\n\trequire.NoError(t, db.Update(func(tx walletdb.ReadWriteTx) error {\n\t\tb, err := tx.CreateTopLevelBucket([]byte(\"apple\"))\n\t\trequire.NoError(t, err)\n\t\trequire.NotNil(t, b)\n\n\t\tfor i := 0; i < count\/2; i++ {\n\t\t\terr = b.Put(\n\t\t\t\t[]byte(testKeyValues[i].key),\n\t\t\t\t[]byte(testKeyValues[i].val),\n\t\t\t)\n\t\t\trequire.NoError(t, err)\n\t\t}\n\t\treturn nil\n\t}))\n\n\terr = db.Update(func(tx walletdb.ReadWriteTx) error {\n\t\tb := tx.ReadWriteBucket([]byte(\"apple\"))\n\t\trequire.NotNil(t, b)\n\n\t\t\/\/ Store the second half of the interval.\n\t\tfor i := count \/ 2; i < count; i++ {\n\t\t\terr = b.Put(\n\t\t\t\t[]byte(testKeyValues[i].key),\n\t\t\t\t[]byte(testKeyValues[i].val),\n\t\t\t)\n\t\t\trequire.NoError(t, err)\n\t\t}\n\n\t\tcursor := b.ReadWriteCursor()\n\n\t\t\/\/ First on valid interval.\n\t\tfk, fv := cursor.First()\n\t\trequire.Equal(t, []byte(\"b\"), fk)\n\t\trequire.Equal(t, []byte(\"1\"), fv)\n\n\t\t\/\/ Prev(First()) = nil\n\t\tk, v := cursor.Prev()\n\t\trequire.Nil(t, k)\n\t\trequire.Nil(t, v)\n\n\t\t\/\/ Last on valid interval.\n\t\tlk, lv := cursor.Last()\n\t\trequire.Equal(t, []byte(\"e\"), lk)\n\t\trequire.Equal(t, []byte(\"4\"), lv)\n\n\t\t\/\/ Next(Last()) = nil\n\t\tk, v = cursor.Next()\n\t\trequire.Nil(t, k)\n\t\trequire.Nil(t, v)\n\n\t\t\/\/ Delete first item, then add an item before the\n\t\t\/\/ deleted one. Check that First\/Next will \"jump\"\n\t\t\/\/ over the deleted item and return the new first.\n\t\t_, _ = cursor.First()\n\t\trequire.NoError(t, cursor.Delete())\n\t\trequire.NoError(t, b.Put([]byte(\"a\"), []byte(\"0\")))\n\t\tfk, fv = cursor.First()\n\n\t\trequire.Equal(t, []byte(\"a\"), fk)\n\t\trequire.Equal(t, []byte(\"0\"), fv)\n\n\t\tk, v = cursor.Next()\n\t\trequire.Equal(t, []byte(\"c\"), k)\n\t\trequire.Equal(t, []byte(\"2\"), v)\n\n\t\t\/\/ Similarly test that a new end is returned if\n\t\t\/\/ the old end is deleted first.\n\t\t_, _ = cursor.Last()\n\t\trequire.NoError(t, cursor.Delete())\n\t\trequire.NoError(t, b.Put([]byte(\"f\"), []byte(\"5\")))\n\n\t\tlk, lv = cursor.Last()\n\t\trequire.Equal(t, []byte(\"f\"), lk)\n\t\trequire.Equal(t, []byte(\"5\"), lv)\n\n\t\tk, v = cursor.Prev()\n\t\trequire.Equal(t, []byte(\"da\"), k)\n\t\trequire.Equal(t, []byte(\"3\"), v)\n\n\t\t\/\/ Overwrite k\/v in the middle of the interval.\n\t\trequire.NoError(t, b.Put([]byte(\"c\"), []byte(\"3\")))\n\t\tk, v = cursor.Prev()\n\t\trequire.Equal(t, []byte(\"c\"), k)\n\t\trequire.Equal(t, []byte(\"3\"), v)\n\n\t\t\/\/ Insert new key\/values.\n\t\trequire.NoError(t, b.Put([]byte(\"cx\"), []byte(\"x\")))\n\t\trequire.NoError(t, b.Put([]byte(\"cy\"), []byte(\"y\")))\n\n\t\tk, v = cursor.Next()\n\t\trequire.Equal(t, []byte(\"cx\"), k)\n\t\trequire.Equal(t, []byte(\"x\"), v)\n\n\t\tk, v = cursor.Next()\n\t\trequire.Equal(t, []byte(\"cy\"), k)\n\t\trequire.Equal(t, []byte(\"y\"), v)\n\n\t\texpected := []KV{\n\t\t\t{\"a\", \"0\"},\n\t\t\t{\"c\", \"3\"},\n\t\t\t{\"cx\", \"x\"},\n\t\t\t{\"cy\", \"y\"},\n\t\t\t{\"da\", \"3\"},\n\t\t\t{\"f\", \"5\"},\n\t\t}\n\n\t\t\/\/ Iterate from the front.\n\t\tvar kvs []KV\n\t\tk, v = cursor.First()\n\n\t\tfor k != nil && v != nil {\n\t\t\tkvs = append(kvs, KV{string(k), string(v)})\n\t\t\tk, v = cursor.Next()\n\t\t}\n\t\trequire.Equal(t, expected, kvs)\n\n\t\t\/\/ Iterate from the back.\n\t\tkvs = []KV{}\n\t\tk, v = cursor.Last()\n\n\t\tfor k != nil && v != nil {\n\t\t\tkvs = append(kvs, KV{string(k), string(v)})\n\t\t\tk, v = cursor.Prev()\n\t\t}\n\t\trequire.Equal(t, reverseKVs(expected), kvs)\n\n\t\treturn nil\n\t})\n\n\trequire.NoError(t, err)\n\n\texpected := map[string]string{\n\t\tbkey(\"apple\"):       bval(\"apple\"),\n\t\tvkey(\"a\", \"apple\"):  \"0\",\n\t\tvkey(\"c\", \"apple\"):  \"3\",\n\t\tvkey(\"cx\", \"apple\"): \"x\",\n\t\tvkey(\"cy\", \"apple\"): \"y\",\n\t\tvkey(\"da\", \"apple\"): \"3\",\n\t\tvkey(\"f\", \"apple\"):  \"5\",\n\t}\n\trequire.Equal(t, expected, f.Dump())\n}\n<commit_msg>kvdb: s\/hu\/en\/g<commit_after>\/\/ +build kvdb_etcd\n\npackage etcd\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/btcsuite\/btcwallet\/walletdb\"\n\t\"github.com\/stretchr\/testify\/require\"\n)\n\nfunc TestReadCursorEmptyInterval(t *testing.T) {\n\tt.Parallel()\n\n\tf := NewEtcdTestFixture(t)\n\tdefer f.Cleanup()\n\n\tdb, err := newEtcdBackend(f.BackendConfig())\n\trequire.NoError(t, err)\n\n\terr = db.Update(func(tx walletdb.ReadWriteTx) error {\n\t\tb, err := tx.CreateTopLevelBucket([]byte(\"apple\"))\n\t\trequire.NoError(t, err)\n\t\trequire.NotNil(t, b)\n\n\t\treturn nil\n\t})\n\trequire.NoError(t, err)\n\n\terr = db.View(func(tx walletdb.ReadTx) error {\n\t\tb := tx.ReadBucket([]byte(\"apple\"))\n\t\trequire.NotNil(t, b)\n\n\t\tcursor := b.ReadCursor()\n\t\tk, v := cursor.First()\n\t\trequire.Nil(t, k)\n\t\trequire.Nil(t, v)\n\n\t\tk, v = cursor.Next()\n\t\trequire.Nil(t, k)\n\t\trequire.Nil(t, v)\n\n\t\tk, v = cursor.Last()\n\t\trequire.Nil(t, k)\n\t\trequire.Nil(t, v)\n\n\t\tk, v = cursor.Prev()\n\t\trequire.Nil(t, k)\n\t\trequire.Nil(t, v)\n\n\t\treturn nil\n\t})\n\trequire.NoError(t, err)\n}\n\nfunc TestReadCursorNonEmptyInterval(t *testing.T) {\n\tt.Parallel()\n\n\tf := NewEtcdTestFixture(t)\n\tdefer f.Cleanup()\n\n\tdb, err := newEtcdBackend(f.BackendConfig())\n\trequire.NoError(t, err)\n\n\ttestKeyValues := []KV{\n\t\t{\"b\", \"1\"},\n\t\t{\"c\", \"2\"},\n\t\t{\"da\", \"3\"},\n\t\t{\"e\", \"4\"},\n\t}\n\n\terr = db.Update(func(tx walletdb.ReadWriteTx) error {\n\t\tb, err := tx.CreateTopLevelBucket([]byte(\"apple\"))\n\t\trequire.NoError(t, err)\n\t\trequire.NotNil(t, b)\n\n\t\tfor _, kv := range testKeyValues {\n\t\t\trequire.NoError(t, b.Put([]byte(kv.key), []byte(kv.val)))\n\t\t}\n\t\treturn nil\n\t})\n\n\trequire.NoError(t, err)\n\n\terr = db.View(func(tx walletdb.ReadTx) error {\n\t\tb := tx.ReadBucket([]byte(\"apple\"))\n\t\trequire.NotNil(t, b)\n\n\t\t\/\/ Iterate from the front.\n\t\tvar kvs []KV\n\t\tcursor := b.ReadCursor()\n\t\tk, v := cursor.First()\n\n\t\tfor k != nil && v != nil {\n\t\t\tkvs = append(kvs, KV{string(k), string(v)})\n\t\t\tk, v = cursor.Next()\n\t\t}\n\t\trequire.Equal(t, testKeyValues, kvs)\n\n\t\t\/\/ Iterate from the back.\n\t\tkvs = []KV{}\n\t\tk, v = cursor.Last()\n\n\t\tfor k != nil && v != nil {\n\t\t\tkvs = append(kvs, KV{string(k), string(v)})\n\t\t\tk, v = cursor.Prev()\n\t\t}\n\t\trequire.Equal(t, reverseKVs(testKeyValues), kvs)\n\n\t\t\/\/ Random access\n\t\tperm := []int{3, 0, 2, 1}\n\t\tfor _, i := range perm {\n\t\t\tk, v := cursor.Seek([]byte(testKeyValues[i].key))\n\t\t\trequire.Equal(t, []byte(testKeyValues[i].key), k)\n\t\t\trequire.Equal(t, []byte(testKeyValues[i].val), v)\n\t\t}\n\n\t\t\/\/ Seek to nonexisting key.\n\t\tk, v = cursor.Seek(nil)\n\t\trequire.Nil(t, k)\n\t\trequire.Nil(t, v)\n\n\t\tk, v = cursor.Seek([]byte(\"x\"))\n\t\trequire.Nil(t, k)\n\t\trequire.Nil(t, v)\n\n\t\treturn nil\n\t})\n\n\trequire.NoError(t, err)\n}\n\nfunc TestReadWriteCursor(t *testing.T) {\n\tt.Parallel()\n\n\tf := NewEtcdTestFixture(t)\n\tdefer f.Cleanup()\n\n\tdb, err := newEtcdBackend(f.BackendConfig())\n\trequire.NoError(t, err)\n\n\ttestKeyValues := []KV{\n\t\t{\"b\", \"1\"},\n\t\t{\"c\", \"2\"},\n\t\t{\"da\", \"3\"},\n\t\t{\"e\", \"4\"},\n\t}\n\n\tcount := len(testKeyValues)\n\n\t\/\/ Pre-store the first half of the interval.\n\trequire.NoError(t, db.Update(func(tx walletdb.ReadWriteTx) error {\n\t\tb, err := tx.CreateTopLevelBucket([]byte(\"apple\"))\n\t\trequire.NoError(t, err)\n\t\trequire.NotNil(t, b)\n\n\t\tfor i := 0; i < count\/2; i++ {\n\t\t\terr = b.Put(\n\t\t\t\t[]byte(testKeyValues[i].key),\n\t\t\t\t[]byte(testKeyValues[i].val),\n\t\t\t)\n\t\t\trequire.NoError(t, err)\n\t\t}\n\t\treturn nil\n\t}))\n\n\terr = db.Update(func(tx walletdb.ReadWriteTx) error {\n\t\tb := tx.ReadWriteBucket([]byte(\"apple\"))\n\t\trequire.NotNil(t, b)\n\n\t\t\/\/ Store the second half of the interval.\n\t\tfor i := count \/ 2; i < count; i++ {\n\t\t\terr = b.Put(\n\t\t\t\t[]byte(testKeyValues[i].key),\n\t\t\t\t[]byte(testKeyValues[i].val),\n\t\t\t)\n\t\t\trequire.NoError(t, err)\n\t\t}\n\n\t\tcursor := b.ReadWriteCursor()\n\n\t\t\/\/ First on valid interval.\n\t\tfk, fv := cursor.First()\n\t\trequire.Equal(t, []byte(\"b\"), fk)\n\t\trequire.Equal(t, []byte(\"1\"), fv)\n\n\t\t\/\/ Prev(First()) = nil\n\t\tk, v := cursor.Prev()\n\t\trequire.Nil(t, k)\n\t\trequire.Nil(t, v)\n\n\t\t\/\/ Last on valid interval.\n\t\tlk, lv := cursor.Last()\n\t\trequire.Equal(t, []byte(\"e\"), lk)\n\t\trequire.Equal(t, []byte(\"4\"), lv)\n\n\t\t\/\/ Next(Last()) = nil\n\t\tk, v = cursor.Next()\n\t\trequire.Nil(t, k)\n\t\trequire.Nil(t, v)\n\n\t\t\/\/ Delete first item, then add an item before the\n\t\t\/\/ deleted one. Check that First\/Next will \"jump\"\n\t\t\/\/ over the deleted item and return the new first.\n\t\t_, _ = cursor.First()\n\t\trequire.NoError(t, cursor.Delete())\n\t\trequire.NoError(t, b.Put([]byte(\"a\"), []byte(\"0\")))\n\t\tfk, fv = cursor.First()\n\n\t\trequire.Equal(t, []byte(\"a\"), fk)\n\t\trequire.Equal(t, []byte(\"0\"), fv)\n\n\t\tk, v = cursor.Next()\n\t\trequire.Equal(t, []byte(\"c\"), k)\n\t\trequire.Equal(t, []byte(\"2\"), v)\n\n\t\t\/\/ Similarly test that a new end is returned if\n\t\t\/\/ the old end is deleted first.\n\t\t_, _ = cursor.Last()\n\t\trequire.NoError(t, cursor.Delete())\n\t\trequire.NoError(t, b.Put([]byte(\"f\"), []byte(\"5\")))\n\n\t\tlk, lv = cursor.Last()\n\t\trequire.Equal(t, []byte(\"f\"), lk)\n\t\trequire.Equal(t, []byte(\"5\"), lv)\n\n\t\tk, v = cursor.Prev()\n\t\trequire.Equal(t, []byte(\"da\"), k)\n\t\trequire.Equal(t, []byte(\"3\"), v)\n\n\t\t\/\/ Overwrite k\/v in the middle of the interval.\n\t\trequire.NoError(t, b.Put([]byte(\"c\"), []byte(\"3\")))\n\t\tk, v = cursor.Prev()\n\t\trequire.Equal(t, []byte(\"c\"), k)\n\t\trequire.Equal(t, []byte(\"3\"), v)\n\n\t\t\/\/ Insert new key\/values.\n\t\trequire.NoError(t, b.Put([]byte(\"cx\"), []byte(\"x\")))\n\t\trequire.NoError(t, b.Put([]byte(\"cy\"), []byte(\"y\")))\n\n\t\tk, v = cursor.Next()\n\t\trequire.Equal(t, []byte(\"cx\"), k)\n\t\trequire.Equal(t, []byte(\"x\"), v)\n\n\t\tk, v = cursor.Next()\n\t\trequire.Equal(t, []byte(\"cy\"), k)\n\t\trequire.Equal(t, []byte(\"y\"), v)\n\n\t\texpected := []KV{\n\t\t\t{\"a\", \"0\"},\n\t\t\t{\"c\", \"3\"},\n\t\t\t{\"cx\", \"x\"},\n\t\t\t{\"cy\", \"y\"},\n\t\t\t{\"da\", \"3\"},\n\t\t\t{\"f\", \"5\"},\n\t\t}\n\n\t\t\/\/ Iterate from the front.\n\t\tvar kvs []KV\n\t\tk, v = cursor.First()\n\n\t\tfor k != nil && v != nil {\n\t\t\tkvs = append(kvs, KV{string(k), string(v)})\n\t\t\tk, v = cursor.Next()\n\t\t}\n\t\trequire.Equal(t, expected, kvs)\n\n\t\t\/\/ Iterate from the back.\n\t\tkvs = []KV{}\n\t\tk, v = cursor.Last()\n\n\t\tfor k != nil && v != nil {\n\t\t\tkvs = append(kvs, KV{string(k), string(v)})\n\t\t\tk, v = cursor.Prev()\n\t\t}\n\t\trequire.Equal(t, reverseKVs(expected), kvs)\n\n\t\treturn nil\n\t})\n\n\trequire.NoError(t, err)\n\n\texpected := map[string]string{\n\t\tbkey(\"apple\"):       bval(\"apple\"),\n\t\tvkey(\"a\", \"apple\"):  \"0\",\n\t\tvkey(\"c\", \"apple\"):  \"3\",\n\t\tvkey(\"cx\", \"apple\"): \"x\",\n\t\tvkey(\"cy\", \"apple\"): \"y\",\n\t\tvkey(\"da\", \"apple\"): \"3\",\n\t\tvkey(\"f\", \"apple\"):  \"5\",\n\t}\n\trequire.Equal(t, expected, f.Dump())\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage signer\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"time\"\n\n\t\"github.com\/gogo\/protobuf\/proto\"\n\t\"github.com\/google\/keytransparency\/core\/appender\"\n\t\"github.com\/google\/keytransparency\/core\/mutator\"\n\t\"github.com\/google\/keytransparency\/core\/transaction\"\n\n\t\"github.com\/google\/trillian\"\n\t\"golang.org\/x\/net\/context\"\n\n\ttpb \"github.com\/google\/keytransparency\/core\/proto\/keytransparency_v1_types\"\n)\n\n\/\/ Signer processes mutations and sends them to the trillian map.\ntype Signer struct {\n\trealm     string\n\tmapID     int64\n\ttmap      trillian.TrillianMapClient\n\tlogID     int64\n\tsths      appender.Remote\n\tmutator   mutator.Mutator\n\tmutations mutator.Mutation\n\tfactory   transaction.Factory\n}\n\n\/\/ New creates a new instance of the signer.\nfunc New(realm string,\n\tmapID int64,\n\ttmap trillian.TrillianMapClient,\n\tlogID int64,\n\tsths appender.Remote,\n\tmutator mutator.Mutator,\n\tmutations mutator.Mutation,\n\tfactory transaction.Factory) *Signer {\n\treturn &Signer{\n\t\trealm:     realm,\n\t\tmapID:     mapID,\n\t\ttmap:      tmap,\n\t\tsths:      sths,\n\t\tmutator:   mutator,\n\t\tmutations: mutations,\n\t\tfactory:   factory,\n\t}\n}\n\n\/\/ StartSigning advance epochs once per interval.\nfunc (s *Signer) StartSigning(ctx context.Context, interval time.Duration) {\n\tfor range time.NewTicker(interval).C {\n\t\tif err := s.CreateEpoch(ctx); err != nil {\n\t\t\tlog.Fatalf(\"CreateEpoch failed: %v\", err)\n\t\t}\n\t}\n}\n\n\/\/ newMutations returns a list of mutations to process and highest sequence number returned.\nfunc (s *Signer) newMutations(ctx context.Context, startSequence int64) ([]*tpb.SignedKV, int64, error) {\n\ttxn, err := s.factory.NewTxn(ctx)\n\tif err != nil {\n\t\treturn nil, 0, fmt.Errorf(\"NewDBTxn(): %v\", err)\n\t}\n\n\tmaxSequence, mutations, err := s.mutations.ReadAll(txn, uint64(startSequence))\n\tif err != nil {\n\t\tif err := txn.Rollback(); err != nil {\n\t\t\tlog.Printf(\"Cannot rollback the transaction: %v\", err)\n\t\t}\n\t\treturn nil, 0, fmt.Errorf(\"ReadAll(%v): %v\", startSequence, err)\n\t}\n\n\tif err := txn.Commit(); err != nil {\n\t\treturn nil, 0, fmt.Errorf(\"txn.Commit(): %v\", err)\n\t}\n\treturn mutations, int64(maxSequence), nil\n}\n\n\/\/ toArray returns the first 32 bytes from b.\n\/\/ If b is less than 32 bytes long, the output is zero padded.\nfunc toArray(b []byte) [32]byte {\n\tvar i [32]byte\n\tcopy(i[:], b)\n\treturn i\n}\n\n\/\/ applyMutations takes the set of mutations and applies them to given leafs.\n\/\/ Multiple mutations for the same leaf will be applied to provided leaf.\n\/\/ The last valid mutation for each leaf is included in the output.\n\/\/ Returns a list of map leaves that should be updated.\nfunc (s *Signer) applyMutations(mutations []*tpb.SignedKV, leaves []*trillian.MapLeaf) ([]*trillian.MapLeaf, error) {\n\t\/\/ Put leaves in a map from index to leaf value.\n\tleafMap := make(map[[32]byte]*trillian.MapLeaf)\n\tfor _, l := range leaves {\n\t\tleafMap[toArray(l.Index)] = l\n\t}\n\n\tretMap := make(map[[32]byte]*trillian.MapLeaf)\n\tfor _, m := range mutations {\n\t\tindex := m.GetKeyValue().Key\n\t\tvar oldValue []byte \/\/ If no map leaf was found, oldValue will be nil.\n\t\tif leaf, ok := leafMap[toArray(index)]; ok {\n\t\t\toldValue = leaf.LeafValue\n\t\t}\n\n\t\t\/\/ TODO: change mutator interface to accept objects directly.\n\t\tmData, err := proto.Marshal(m)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tnewValue, err := s.mutator.Mutate(oldValue, mData)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Mutate(): %v\", err)\n\t\t\tcontinue \/\/ A bad mutation should not make the whole batch fail.\n\t\t}\n\n\t\tretMap[toArray(index)] = &trillian.MapLeaf{\n\t\t\tIndex:     index,\n\t\t\tLeafValue: newValue,\n\t\t}\n\t}\n\t\/\/ Convert return map back into a list.\n\tret := make([]*trillian.MapLeaf, 0, len(retMap))\n\tfor _, v := range retMap {\n\t\tret = append(ret, v)\n\t}\n\treturn ret, nil\n}\n\n\/\/ CreateEpoch signs the current map head.\nfunc (s *Signer) CreateEpoch(ctx context.Context) error {\n\t\/\/ Get the current root.\n\tstartSequence := int64(0)\n\trootResp, err := s.tmap.GetSignedMapRoot(ctx, &trillian.GetSignedMapRootRequest{\n\t\tMapId: s.mapID,\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"GetSignedMapRoot(%v): %v\", s.mapID, err)\n\t}\n\tstartSequence = rootResp.GetMapRoot().GetMetadata().GetHighestFullyCompletedSeq()\n\n\t\/\/ Get the list of new mutations to process.\n\tmutations, seq, err := s.newMutations(ctx, startSequence)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"newMutations(%v): %v\", startSequence, err)\n\t}\n\n\t\/\/ Get current leaf values.\n\tindexes := make([][]byte, 0, len(mutations))\n\tfor _, m := range mutations {\n\t\tindexes = append(indexes, m.KeyValue.Key)\n\t}\n\tgetResp, err := s.tmap.GetLeaves(ctx, &trillian.GetMapLeavesRequest{\n\t\tMapId: s.mapID,\n\t\tIndex: indexes,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Trust the leaf values provided by the map server.\n\t\/\/ If the map server is run by an untrusted entity, perform inclusion\n\t\/\/ and signature verification here.\n\tleaves := make([]*trillian.MapLeaf, 0, len(getResp.MapLeafInclusion))\n\tfor _, m := range getResp.MapLeafInclusion {\n\t\tleaves = append(leaves, m.Leaf)\n\t}\n\n\t\/\/ Apply mutations to values.\n\tnewLeaves, err := s.applyMutations(mutations, leaves)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Set new leaf values.\n\tsetResp, err := s.tmap.SetLeaves(ctx, &trillian.SetMapLeavesRequest{\n\t\tMapId:  s.mapID,\n\t\tLeaves: newLeaves,\n\t\tMapperData: &trillian.MapperMetadata{\n\t\t\tHighestFullyCompletedSeq: seq,\n\t\t},\n\t})\n\t\/\/ Put SignedMapHead in an append only log.\n\treturn s.sths.Write(ctx, s.logID, setResp.MapRoot.MapRevision, setResp.MapRoot)\n}\n<commit_msg>Fix presubmit errors<commit_after>\/\/ Copyright 2016 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage signer\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"time\"\n\n\t\"github.com\/gogo\/protobuf\/proto\"\n\t\"github.com\/google\/keytransparency\/core\/appender\"\n\t\"github.com\/google\/keytransparency\/core\/mutator\"\n\t\"github.com\/google\/keytransparency\/core\/transaction\"\n\n\t\"github.com\/google\/trillian\"\n\t\"golang.org\/x\/net\/context\"\n\n\ttpb \"github.com\/google\/keytransparency\/core\/proto\/keytransparency_v1_types\"\n)\n\n\/\/ Signer processes mutations and sends them to the trillian map.\ntype Signer struct {\n\trealm     string\n\tmapID     int64\n\ttmap      trillian.TrillianMapClient\n\tlogID     int64\n\tsths      appender.Remote\n\tmutator   mutator.Mutator\n\tmutations mutator.Mutation\n\tfactory   transaction.Factory\n}\n\n\/\/ New creates a new instance of the signer.\nfunc New(realm string,\n\tmapID int64,\n\ttmap trillian.TrillianMapClient,\n\tlogID int64,\n\tsths appender.Remote,\n\tmutator mutator.Mutator,\n\tmutations mutator.Mutation,\n\tfactory transaction.Factory) *Signer {\n\treturn &Signer{\n\t\trealm:     realm,\n\t\tmapID:     mapID,\n\t\ttmap:      tmap,\n\t\tsths:      sths,\n\t\tmutator:   mutator,\n\t\tmutations: mutations,\n\t\tfactory:   factory,\n\t}\n}\n\n\/\/ StartSigning advance epochs once per interval.\nfunc (s *Signer) StartSigning(ctx context.Context, interval time.Duration) {\n\tfor range time.NewTicker(interval).C {\n\t\tif err := s.CreateEpoch(ctx); err != nil {\n\t\t\tlog.Fatalf(\"CreateEpoch failed: %v\", err)\n\t\t}\n\t}\n}\n\n\/\/ newMutations returns a list of mutations to process and highest sequence number returned.\nfunc (s *Signer) newMutations(ctx context.Context, startSequence int64) ([]*tpb.SignedKV, int64, error) {\n\ttxn, err := s.factory.NewTxn(ctx)\n\tif err != nil {\n\t\treturn nil, 0, fmt.Errorf(\"NewDBTxn(): %v\", err)\n\t}\n\n\tmaxSequence, mutations, err := s.mutations.ReadAll(txn, uint64(startSequence))\n\tif err != nil {\n\t\tif err := txn.Rollback(); err != nil {\n\t\t\tlog.Printf(\"Cannot rollback the transaction: %v\", err)\n\t\t}\n\t\treturn nil, 0, fmt.Errorf(\"ReadAll(%v): %v\", startSequence, err)\n\t}\n\n\tif err := txn.Commit(); err != nil {\n\t\treturn nil, 0, fmt.Errorf(\"txn.Commit(): %v\", err)\n\t}\n\treturn mutations, int64(maxSequence), nil\n}\n\n\/\/ toArray returns the first 32 bytes from b.\n\/\/ If b is less than 32 bytes long, the output is zero padded.\nfunc toArray(b []byte) [32]byte {\n\tvar i [32]byte\n\tcopy(i[:], b)\n\treturn i\n}\n\n\/\/ applyMutations takes the set of mutations and applies them to given leafs.\n\/\/ Multiple mutations for the same leaf will be applied to provided leaf.\n\/\/ The last valid mutation for each leaf is included in the output.\n\/\/ Returns a list of map leaves that should be updated.\nfunc (s *Signer) applyMutations(mutations []*tpb.SignedKV, leaves []*trillian.MapLeaf) ([]*trillian.MapLeaf, error) {\n\t\/\/ Put leaves in a map from index to leaf value.\n\tleafMap := make(map[[32]byte]*trillian.MapLeaf)\n\tfor _, l := range leaves {\n\t\tleafMap[toArray(l.Index)] = l\n\t}\n\n\tretMap := make(map[[32]byte]*trillian.MapLeaf)\n\tfor _, m := range mutations {\n\t\tindex := m.GetKeyValue().Key\n\t\tvar oldValue []byte \/\/ If no map leaf was found, oldValue will be nil.\n\t\tif leaf, ok := leafMap[toArray(index)]; ok {\n\t\t\toldValue = leaf.LeafValue\n\t\t}\n\n\t\t\/\/ TODO: change mutator interface to accept objects directly.\n\t\tmData, err := proto.Marshal(m)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tnewValue, err := s.mutator.Mutate(oldValue, mData)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Mutate(): %v\", err)\n\t\t\tcontinue \/\/ A bad mutation should not make the whole batch fail.\n\t\t}\n\n\t\tretMap[toArray(index)] = &trillian.MapLeaf{\n\t\t\tIndex:     index,\n\t\t\tLeafValue: newValue,\n\t\t}\n\t}\n\t\/\/ Convert return map back into a list.\n\tret := make([]*trillian.MapLeaf, 0, len(retMap))\n\tfor _, v := range retMap {\n\t\tret = append(ret, v)\n\t}\n\treturn ret, nil\n}\n\n\/\/ CreateEpoch signs the current map head.\nfunc (s *Signer) CreateEpoch(ctx context.Context) error {\n\t\/\/ Get the current root.\n\trootResp, err := s.tmap.GetSignedMapRoot(ctx, &trillian.GetSignedMapRootRequest{\n\t\tMapId: s.mapID,\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"GetSignedMapRoot(%v): %v\", s.mapID, err)\n\t}\n\tstartSequence := rootResp.GetMapRoot().GetMetadata().GetHighestFullyCompletedSeq()\n\n\t\/\/ Get the list of new mutations to process.\n\tmutations, seq, err := s.newMutations(ctx, startSequence)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"newMutations(%v): %v\", startSequence, err)\n\t}\n\n\t\/\/ Get current leaf values.\n\tindexes := make([][]byte, 0, len(mutations))\n\tfor _, m := range mutations {\n\t\tindexes = append(indexes, m.KeyValue.Key)\n\t}\n\tgetResp, err := s.tmap.GetLeaves(ctx, &trillian.GetMapLeavesRequest{\n\t\tMapId: s.mapID,\n\t\tIndex: indexes,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Trust the leaf values provided by the map server.\n\t\/\/ If the map server is run by an untrusted entity, perform inclusion\n\t\/\/ and signature verification here.\n\tleaves := make([]*trillian.MapLeaf, 0, len(getResp.MapLeafInclusion))\n\tfor _, m := range getResp.MapLeafInclusion {\n\t\tleaves = append(leaves, m.Leaf)\n\t}\n\n\t\/\/ Apply mutations to values.\n\tnewLeaves, err := s.applyMutations(mutations, leaves)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Set new leaf values.\n\tsetResp, err := s.tmap.SetLeaves(ctx, &trillian.SetMapLeavesRequest{\n\t\tMapId:  s.mapID,\n\t\tLeaves: newLeaves,\n\t\tMapperData: &trillian.MapperMetadata{\n\t\t\tHighestFullyCompletedSeq: seq,\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/ Put SignedMapHead in an append only log.\n\treturn s.sths.Write(ctx, s.logID, setResp.MapRoot.MapRevision, setResp.MapRoot)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nPackage byline implements Reader for process line-by-line another Reader\n*\/\npackage byline\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"regexp\"\n)\n\nvar (\n\t\/\/ default field separator\n\tdefaultFS = regexp.MustCompile(`\\s+`)\n\t\/\/ default line separator\n\tdefaultRS byte = '\\n'\n)\n\n\/\/ Reader - line by line Reader\ntype Reader interface {\n\tio.Reader\n\n\tMapErr(func(line []byte) ([]byte, error)) Reader\n}\n\ntype linesReader struct {\n\tbufReader   *bufio.Reader\n\tfilterFuncs []func(line []byte) ([]byte, error)\n\tawkVars     AWKVars\n}\n\n\/\/ AWKVars - settings for AWK mode, see man awk\ntype AWKVars struct {\n\tNR int            \/\/ number of current line (begin from 1)\n\tNF int            \/\/ fields count in curent line\n\tRS byte           \/\/ record separator, default is '\\n'\n\tFS *regexp.Regexp \/\/ field separator, default is `\\s+`\n}\n\n\/\/ NewReader - get new line by line Reader\nfunc NewReader(reader io.Reader) Reader {\n\treturn &linesReader{\n\t\tbufReader: bufio.NewReader(reader),\n\t\tawkVars: AWKVars{\n\t\t\tRS: defaultRS,\n\t\t\tFS: defaultFS,\n\t\t},\n\t}\n}\n\n\/\/ Read - implement io.Reader interface\nfunc (lr *linesReader) Read(p []byte) (n int, err error) {\n\tlineBytes, bufErr := lr.bufReader.ReadBytes(lr.awkVars.RS)\n\tlr.awkVars.NR++\n\tfmt.Printf(\"NR: %d, %s\", lr.awkVars.NR, string(lineBytes))\n\n\tvar filterErr error\n\tfor _, filterFunc := range lr.filterFuncs {\n\t\tlineBytes, filterErr = filterFunc(lineBytes)\n\t\tif bufErr != io.EOF && filterErr != nil {\n\t\t\tbufErr = filterErr\n\t\t}\n\t}\n\n\tcopy(p, lineBytes)\n\treturn len(lineBytes), bufErr\n}\n\n\/\/ MapErr - set filter function for process one line\nfunc (lr *linesReader) MapErr(filterFn func(line []byte) ([]byte, error)) Reader {\n\tlr.filterFuncs = append(lr.filterFuncs, filterFn)\n\treturn lr\n}\n<commit_msg>Don't create interface<commit_after>\/*\nPackage byline implements Reader for process line-by-line another Reader\n*\/\npackage byline\n\nimport (\n\t\"bufio\"\n\t\"io\"\n\t\"regexp\"\n)\n\nvar (\n\t\/\/ default field separator\n\tdefaultFS = regexp.MustCompile(`\\s+`)\n\t\/\/ default line separator\n\tdefaultRS byte = '\\n'\n)\n\n\/\/ Reader - line by line Reader\ntype Reader struct {\n\tbufReader   *bufio.Reader\n\tfilterFuncs []func(line []byte) ([]byte, error)\n\tawkVars     AWKVars\n}\n\n\/\/ AWKVars - settings for AWK mode, see man awk\ntype AWKVars struct {\n\tNR int            \/\/ number of current line (begin from 1)\n\tNF int            \/\/ fields count in curent line\n\tRS byte           \/\/ record separator, default is '\\n'\n\tFS *regexp.Regexp \/\/ field separator, default is `\\s+`\n}\n\n\/\/ NewReader - get new line by line Reader\nfunc NewReader(reader io.Reader) *Reader {\n\treturn &Reader{\n\t\tbufReader: bufio.NewReader(reader),\n\t\tawkVars: AWKVars{\n\t\t\tRS: defaultRS,\n\t\t\tFS: defaultFS,\n\t\t},\n\t}\n}\n\n\/\/ Read - implement io.Reader interface\nfunc (lr *Reader) Read(p []byte) (n int, err error) {\n\tlineBytes, bufErr := lr.bufReader.ReadBytes(lr.awkVars.RS)\n\tlr.awkVars.NR++\n\n\tvar filterErr error\n\tfor _, filterFunc := range lr.filterFuncs {\n\t\tlineBytes, filterErr = filterFunc(lineBytes)\n\t\tif bufErr != io.EOF && filterErr != nil {\n\t\t\tbufErr = filterErr\n\t\t}\n\t}\n\n\tcopy(p, lineBytes)\n\treturn len(lineBytes), bufErr\n}\n\n\/\/ MapErr - set filter function for process each line\nfunc (lr *Reader) MapErr(filterFn func(line []byte) ([]byte, error)) *Reader {\n\tlr.filterFuncs = append(lr.filterFuncs, filterFn)\n\treturn lr\n}\n<|endoftext|>"}
{"text":"<commit_before>import \"code.google.com\/p\/appengine-go\/appengine\/xmpp\"\n\nfunc Send(from string, to []string, text string, messageType string) {\n\tm := &xmpp.Message{\n\t\tFrom: from,\n\t\tTo:   to,\n\t\tBody: text,\n\t\tType: messageType,\n\t}\n\terr := m.Send(c)\n}\n<commit_msg>Fixed package declaration<commit_after>package notifier\n\nimport \"code.google.com\/p\/appengine-go\/appengine\/xmpp\"\n\nfunc Send(from string, to []string, text string, messageType string) {\n\tm := &xmpp.Message{\n\t\tFrom: from,\n\t\tTo:   to,\n\t\tBody: text,\n\t\tType: messageType,\n\t}\n\terr := m.Send(c)\n}\n<|endoftext|>"}
{"text":"<commit_before>package models\n\ntype Item struct {\n\tTitle         string\n\tDescription   string\n\tTags          string \/\/ seperated by comma, should be mapped with Tag model in database\n\tCondition     uint8  \/\/ percentage of status after depreciation\n\tStatus        string \/\/ ([P]ending \/ [A]vailable \/ [H]old \/ [N]ot available...will be hidden) only avabile when it is posted by registered user\n\tDuration      int    \/\/ list duration. default 7 days\n\tLocation      string \/\/ pickup location, free text, can be just district\n\tHandover      string \/\/ ([F]ace \/ [D]elivery) handover method\n\tDelivery      string \/\/ ([P]ost \/ [C]ourrier) delivery method if not handover\n\tContactMethod string \/\/ free text for user\n\tContact       string\n\tEmail         string \/\/ mandatory. used for sending verification email. updating item status by replying email. contacting with request.\n\tOwner         uint   \/\/ owner ID if it is registered (optional subscription)\n\tPostDate      int64  \/\/ returned by time.Time.Now() unixepoch\n\tUpdateDate    int64  \/\/ returned by time.Time.Now() unixepoch\n}\n<commit_msg>Add ID to item model for MongoDB<commit_after>package models\n\nimport \"labix.org\/v2\/mgo\/bson\"\n\ntype Item struct {\n\tId            bson.ObjectId `bson:\"_id,omitempty\"`\n\tTitle         string\n\tDescription   string\n\tTags          string \/\/ seperated by comma, should be mapped with Tag model in database\n\tCondition     uint8  \/\/ percentage of status after depreciation\n\tStatus        string \/\/ ([P]ending \/ [A]vailable \/ [H]old \/ [N]ot available...will be hidden) only avabile when it is posted by registered user\n\tDuration      int    \/\/ list duration. default 7 days\n\tLocation      string \/\/ pickup location, free text, can be just district\n\tHandover      string \/\/ ([F]ace \/ [D]elivery) handover method\n\tDelivery      string \/\/ ([P]ost \/ [C]ourrier) delivery method if not handover\n\tContactMethod string \/\/ free text for user\n\tContact       string\n\tEmail         string \/\/ mandatory. used for sending verification email. updating item status by replying email. contacting with request.\n\tOwner         uint   \/\/ owner ID if it is registered (optional subscription)\n\tPostDate      int64  \/\/ returned by time.Time.Now() unixepoch\n\tUpdateDate    int64  \/\/ returned by time.Time.Now() unixepoch\n}\n<|endoftext|>"}
{"text":"<commit_before>package plugin\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com\/neovim\/go-client\/nvim\"\n)\n\n\/\/ Plugin represents a remote plugin.\ntype Plugin struct {\n\tNvim        *nvim.Nvim\n\tpluginSpecs []*pluginSpec\n\n\t\/\/ Event\/pattern counters used to generate unique paths for autocmds.\n\teventPathCounts map[string]int\n}\n\n\/\/ New returns an intialized plugin.\nfunc New(v *nvim.Nvim) *Plugin {\n\tp := &Plugin{\n\t\tNvim:            v,\n\t\teventPathCounts: make(map[string]int),\n\t}\n\n\t\/\/ Disable support for \"specs\" method until path mechanism for supporting\n\t\/\/ binary exectables with Nvim is worked out.\n\t\/\/ err := v.RegisterHandler(\"specs\", func(path string) ([]*pluginSpec, error) {\n\t\/\/  return p.pluginSpecs, nil\n\t\/\/ })\n\n\treturn p\n}\n\ntype pluginSpec struct {\n\tsm   string\n\tType string            `msgpack:\"type\"`\n\tName string            `msgpack:\"name\"`\n\tSync bool              `msgpack:\"sync\"`\n\tOpts map[string]string `msgpack:\"opts\"`\n}\n\nfunc (spec *pluginSpec) path() string {\n\tif i := strings.Index(spec.sm, \":\"); i > 0 {\n\t\treturn spec.sm[:i]\n\t}\n\n\treturn \"\"\n}\n\nfunc isSync(f interface{}) bool {\n\tt := reflect.TypeOf(f)\n\n\treturn t.Kind() == reflect.Func && t.NumOut() > 0\n}\n\nfunc (p *Plugin) handle(fn interface{}, spec *pluginSpec) {\n\tp.pluginSpecs = append(p.pluginSpecs, spec)\n\tif p.Nvim == nil {\n\t\treturn\n\t}\n\n\tif err := p.Nvim.RegisterHandler(spec.sm, fn); err != nil {\n\t\tpanic(err)\n\t}\n}\n\n\/\/ Handle registers fn as a MessagePack RPC handler for the specified method\n\/\/ name. The function signature for fn is one of\n\/\/\n\/\/  func([v *nvim.Nvim,] {args}) ({resultType}, error)\n\/\/  func([v *nvim.Nvim,] {args}) error\n\/\/  func([v *nvim.Nvim,] {args})\n\/\/\n\/\/ where {args} is zero or more arguments and {resultType} is the type of of a\n\/\/ return value. Call the handler from Nvim using the rpcnotify and rpcrequest\n\/\/ functions:\n\/\/\n\/\/  :help rpcrequest()\n\/\/  :help rpcnotify()\nfunc (p *Plugin) Handle(method string, fn interface{}) {\n\tif p.Nvim == nil {\n\t\treturn\n\t}\n\n\tif err := p.Nvim.RegisterHandler(method, fn); err != nil {\n\t\tpanic(err)\n\t}\n}\n\n\/\/ FunctionOptions specifies function options.\ntype FunctionOptions struct {\n\t\/\/ Name is the name of the function in Nvim. The name must be made of\n\t\/\/ alphanumeric characters and '_', and must start with a capital letter.\n\tName string\n\n\t\/\/ Eval is an expression evaluated in Nvim. The result is passed the\n\t\/\/ handler function.\n\tEval string\n}\n\n\/\/ HandleFunction registers fn as a handler for a Nvim function. The function\n\/\/ signature for fn is one of\n\/\/\n\/\/  func([v *nvim.Nvim,] args {arrayType} [, eval {evalType}]) ({resultType}, error)\n\/\/  func([v *nvim.Nvim,] args {arrayType} [, eval {evalType}]) error\n\/\/\n\/\/ where {arrayType} is a type that can be unmarshaled from a MessagePack\n\/\/ array, {evalType} is a type compatible with the Eval option expression and\n\/\/ {resultType} is the type of function result.\n\/\/\n\/\/ If options.Eval == \"*\", then HandleFunction constructs the expression to\n\/\/ evaluate in Nvim from the type of fn's last argument. The last argument is\n\/\/ assumed to be a pointer to a struct type with 'eval' field tags set to the\n\/\/ expression to evaluate for each field. Nested structs are supported. The\n\/\/ expression for the function\n\/\/\n\/\/  func example(eval *struct{\n\/\/  \tGOPATH string `eval:\"$GOPATH\"`\n\/\/  \tCwd    string `eval:\"getcwd()\"`\n\/\/  })\n\/\/\n\/\/ is\n\/\/\n\/\/  {'GOPATH': $GOPATH, Cwd: getcwd()}\nfunc (p *Plugin) HandleFunction(options *FunctionOptions, fn interface{}) {\n\tm := make(map[string]string)\n\n\tif options.Eval != \"\" {\n\t\tm[\"eval\"] = eval(options.Eval, fn)\n\t}\n\n\tp.handle(fn, &pluginSpec{\n\t\tsm:   `0:function:` + options.Name,\n\t\tType: `function`,\n\t\tName: options.Name,\n\t\tSync: isSync(fn),\n\t\tOpts: m,\n\t})\n}\n\n\/\/ CommandOptions specifies command options.\ntype CommandOptions struct {\n\t\/\/ Name is the name of the command in Nvim. The name must be made of\n\t\/\/ alphanumeric characters and '_', and must start with a capital\n\t\/\/ letter.\n\tName string\n\n\t\/\/ NArgs specifies the number command arguments.\n\t\/\/\n\t\/\/  0   No arguments are allowed\n\t\/\/  1   Exactly one argument is required, it includes spaces\n\t\/\/  *   Any number of arguments are allowed (0, 1, or many),\n\t\/\/      separated by white space\n\t\/\/  ?   0 or 1 arguments are allowed\n\t\/\/  +   Arguments must be supplied, but any number are allowed\n\tNArgs string\n\n\t\/\/ Range specifies that the command accepts a range.\n\t\/\/\n\t\/\/  .   Range allowed, default is current line. The value\n\t\/\/      \".\" is converted to \"\" for Nvim.\n\t\/\/  %   Range allowed, default is whole file (1,$)\n\t\/\/  N   A count (default N) which is specified in the line\n\t\/\/      number position (like |:split|); allows for zero line\n\t\/\/\t    number.\n\t\/\/\n\t\/\/  :help :command-range\n\tRange string\n\n\t\/\/ Count specfies that thecommand accepts a count.\n\t\/\/\n\t\/\/  N   A count (default N) which is specified either in the line\n\t\/\/\t    number position, or as an initial argument (like |:Next|).\n\t\/\/      Specifying -count (without a default) acts like -count=0\n\t\/\/\n\t\/\/  :help :command-count\n\tCount string\n\n\t\/\/ Addr sepcifies the domain for the range option\n\t\/\/\n\t\/\/  lines           Range of lines (this is the default)\n\t\/\/  arguments       Range for arguments\n\t\/\/  buffers         Range for buffers (also not loaded buffers)\n\t\/\/  loaded_buffers  Range for loaded buffers\n\t\/\/  windows         Range for windows\n\t\/\/  tabs            Range for tab pages\n\t\/\/\n\t\/\/  :help command-addr\n\tAddr string\n\n\t\/\/ Eval is evaluated in Nvim and the result is passed as an argument.\n\tEval string\n\n\t\/\/ Complete specifies command completion.\n\t\/\/\n\t\/\/  :help :command-complete\n\tComplete string\n\n\t\/\/ Bang specifies that the command can take a ! modifier (like :q or :w).\n\tBang bool\n\n\t\/\/ Register specifes that the first argument to the command can be an\n\t\/\/ optional register name (like :del, :put, :yank).\n\tRegister bool\n\n\t\/\/ Bar specifies that the command can be followed by a \"|\" and another\n\t\/\/ command.  A \"|\" inside the command argument is not allowed then. Also\n\t\/\/ checks for a \" to start a comment.\n\tBar bool\n}\n\n\/\/ HandleCommand registers fn as a handler for a Nvim command. The arguments\n\/\/ to the function fn are:\n\/\/\n\/\/  v *nvim.Nvim        optional\n\/\/  args []string       when options.NArgs != \"\"\n\/\/  range [2]int        when options.Range == \".\" or Range == \"%\"\n\/\/  range int           when options.Range == N or Count != \"\"\n\/\/  bang bool           when options.Bang == true\n\/\/  register string     when options.Register == true\n\/\/  eval interface{}    when options.Eval != \"\"\n\/\/\n\/\/ The function fn must return an error.\n\/\/\n\/\/ If options.Eval == \"*\", then HandleCommand constructs the expression to\n\/\/ evaluate in Nvim from the type of fn's last argument. See the\n\/\/ HandleFunction documentation for information on how the expression is\n\/\/ generated.\nfunc (p *Plugin) HandleCommand(options *CommandOptions, fn interface{}) {\n\tm := make(map[string]string)\n\n\tif options.NArgs != \"\" {\n\t\tm[`nargs`] = options.NArgs\n\t}\n\n\tswitch {\n\tcase options.Range == `.`:\n\t\toptions.Range = \"\"\n\t\tfallthrough\n\tcase options.Range != \"\":\n\t\tm[`range`] = options.Range\n\tcase options.Count != \"\":\n\t\tm[`count`] = options.Count\n\t}\n\n\tif options.Bang {\n\t\tm[`bang`] = \"\"\n\t}\n\n\tif options.Register {\n\t\tm[`register`] = \"\"\n\t}\n\n\tif options.Eval != \"\" {\n\t\tm[`eval`] = eval(options.Eval, fn)\n\t}\n\n\tif options.Addr != \"\" {\n\t\tm[`addr`] = options.Addr\n\t}\n\n\tif options.Bar {\n\t\tm[`bar`] = \"\"\n\t}\n\n\tif options.Complete != \"\" {\n\t\tm[`complete`] = options.Complete\n\t}\n\n\tp.handle(fn, &pluginSpec{\n\t\tsm:   `0:command:` + options.Name,\n\t\tType: `command`,\n\t\tName: options.Name,\n\t\tSync: isSync(fn),\n\t\tOpts: m,\n\t})\n}\n\n\/\/ AutocmdOptions specifies autocmd options.\ntype AutocmdOptions struct {\n\t\/\/ Event is the event name.\n\tEvent string\n\n\t\/\/ Group specifies the autocmd group.\n\tGroup string\n\n\t\/\/ Pattern specifies an autocmd pattern.\n\t\/\/\n\t\/\/  :help autocmd-patterns\n\tPattern string\n\n\t\/\/ Nested allows nested autocmds.\n\t\/\/\n\t\/\/  :help autocmd-nested\n\tNested bool\n\n\t\/\/ Once supplys the command is executed once, then removed (\"one shot\").\n\t\/\/\n\t\/\/  :help autocmd-once\n\tOnce bool\n\n\t\/\/ Eval is evaluated in Nvim and the result is passed the the handler\n\t\/\/ function.\n\tEval string\n}\n\n\/\/ HandleAutocmd registers fn as a handler an autocmnd event.\n\/\/\n\/\/ If options.Eval == \"*\", then HandleAutocmd constructs the expression to\n\/\/ evaluate in Nvim from the type of fn's last argument. See the HandleFunction\n\/\/ documentation for information on how the expression is generated.\nfunc (p *Plugin) HandleAutocmd(options *AutocmdOptions, fn interface{}) {\n\tpattern := \"\"\n\n\tm := make(map[string]string)\n\n\tif options.Group != \"\" {\n\t\tm[`group`] = options.Group\n\t}\n\n\tif options.Pattern != \"\" {\n\t\tm[`pattern`] = options.Pattern\n\t\tpattern = options.Pattern\n\t}\n\n\tif options.Nested {\n\t\tm[`nested`] = `1`\n\t}\n\n\tif options.Once {\n\t\tm[`once`] = `1`\n\t}\n\n\tif options.Eval != \"\" {\n\t\tm[`eval`] = eval(options.Eval, fn)\n\t}\n\n\t\/\/ Compute unique path for event and pattern.\n\tep := options.Event + \":\" + pattern\n\ti := p.eventPathCounts[ep]\n\tp.eventPathCounts[ep] = i + 1\n\n\tsm := fmt.Sprintf(`%d:autocmd:%s`, i, ep)\n\n\tp.handle(fn, &pluginSpec{\n\t\tsm:   sm,\n\t\tType: `autocmd`,\n\t\tName: options.Event,\n\t\tSync: isSync(fn),\n\t\tOpts: m,\n\t})\n}\n\n\/\/ RegisterForTests registers the plugin with Nvim. Use this method for testing\n\/\/ plugins in an embedded instance of Nvim.\nfunc (p *Plugin) RegisterForTests() error {\n\tspecs := make(map[string][]*pluginSpec)\n\tfor _, spec := range p.pluginSpecs {\n\t\tspecs[spec.path()] = append(specs[spec.path()], spec)\n\t}\n\n\tconst host = \"nvim-go-test\"\n\tfor path, specs := range specs {\n\t\tif err := p.Nvim.Call(\"remote#host#RegisterPlugin\", nil, host, path, specs); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\terr := p.Nvim.Call(\"remote#host#Register\", nil, host, \"x\", p.Nvim.ChannelID())\n\n\treturn err\n}\n\nfunc eval(eval string, f interface{}) string {\n\tif eval != `*` {\n\t\treturn eval\n\t}\n\n\tft := reflect.TypeOf(f)\n\tif ft.Kind() != reflect.Func || ft.NumIn() < 1 {\n\t\tpanic(`Eval: \"*\" option requires function with at least one argument`)\n\t}\n\n\targt := ft.In(ft.NumIn() - 1)\n\tif argt.Kind() != reflect.Ptr || argt.Elem().Kind() != reflect.Struct {\n\t\tpanic(`Eval: \"*\" option requires function with pointer to struct as last argument`)\n\t}\n\n\treturn structEval(argt.Elem())\n}\n\nfunc structEval(t reflect.Type) string {\n\tvar sb strings.Builder\n\n\tsb.WriteByte('{')\n\tsep := \"\"\n\n\tfor i := 0; i < t.NumField(); i++ {\n\t\tsf := t.Field(i)\n\t\tif sf.Anonymous {\n\t\t\tpanic(`Eval: \"*\" does not support anonymous fields`)\n\t\t}\n\n\t\teval := sf.Tag.Get(\"eval\")\n\t\tif eval == \"\" {\n\t\t\tft := sf.Type\n\t\t\tif ft.Kind() == reflect.Ptr {\n\t\t\t\tft = ft.Elem()\n\t\t\t}\n\n\t\t\tif ft.Kind() == reflect.Struct {\n\t\t\t\teval = structEval(ft)\n\t\t\t}\n\t\t}\n\t\tif eval == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tname := strings.Split(sf.Tag.Get(\"msgpack\"), \",\")[0]\n\t\tif name == \"\" {\n\t\t\tname = sf.Name\n\t\t}\n\n\t\tsb.WriteString(sep)\n\t\tsb.WriteByte('\\'')\n\t\tsb.WriteString(name)\n\t\tsb.WriteString(\"': \")\n\t\tsb.WriteString(eval)\n\t\tsep = \", \"\n\t}\n\tsb.WriteByte('}')\n\n\treturn sb.String()\n}\n\ntype byServiceMethod []*pluginSpec\n\nfunc (a byServiceMethod) Len() int           { return len(a) }\nfunc (a byServiceMethod) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }\nfunc (a byServiceMethod) Less(i, j int) bool { return a[i].sm < a[j].sm }\n\nfunc (p *Plugin) Manifest(host string) []byte {\n\tvar buf bytes.Buffer\n\n\t\/\/ Sort for consistent order on output.\n\tsort.Sort(byServiceMethod(p.pluginSpecs))\n\tescape := strings.NewReplacer(`'`, `''`).Replace\n\n\tprevPath := \"\"\n\tfor _, spec := range p.pluginSpecs {\n\t\tpath := spec.path()\n\t\tif path != prevPath {\n\t\t\tif prevPath != \"\" {\n\t\t\t\tfmt.Fprintf(&buf, \"\\\\ )\")\n\t\t\t}\n\t\t\tfmt.Fprintf(&buf, \"call remote#host#RegisterPlugin('%s', '%s', [\\n\", host, path)\n\t\t\tprevPath = path\n\t\t}\n\n\t\tsync := \"0\"\n\t\tif spec.Sync {\n\t\t\tsync = \"1\"\n\t\t}\n\n\t\tfmt.Fprintf(&buf, \"\\\\ {'type': '%s', 'name': '%s', 'sync': %s, 'opts': {\", spec.Type, spec.Name, sync)\n\n\t\tvar keys []string\n\t\tfor k := range spec.Opts {\n\t\t\tkeys = append(keys, k)\n\t\t}\n\t\tsort.Strings(keys)\n\n\t\toptDelim := \"\"\n\t\tfor _, k := range keys {\n\t\t\tfmt.Fprintf(&buf, \"%s'%s': '%s'\", optDelim, k, escape(spec.Opts[k]))\n\t\t\toptDelim = \",\"\n\t\t}\n\n\t\tfmt.Fprintf(&buf, \"}},\\n\")\n\t}\n\tif prevPath != \"\" {\n\t\tfmt.Fprintf(&buf, \"\\\\ ])\\n\")\n\t}\n\n\treturn buf.Bytes()\n}\n<commit_msg>nvim\/plugin: fix lack optDelim space<commit_after>package plugin\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com\/neovim\/go-client\/nvim\"\n)\n\n\/\/ Plugin represents a remote plugin.\ntype Plugin struct {\n\tNvim        *nvim.Nvim\n\tpluginSpecs []*pluginSpec\n\n\t\/\/ Event\/pattern counters used to generate unique paths for autocmds.\n\teventPathCounts map[string]int\n}\n\n\/\/ New returns an intialized plugin.\nfunc New(v *nvim.Nvim) *Plugin {\n\tp := &Plugin{\n\t\tNvim:            v,\n\t\teventPathCounts: make(map[string]int),\n\t}\n\n\t\/\/ Disable support for \"specs\" method until path mechanism for supporting\n\t\/\/ binary exectables with Nvim is worked out.\n\t\/\/ err := v.RegisterHandler(\"specs\", func(path string) ([]*pluginSpec, error) {\n\t\/\/  return p.pluginSpecs, nil\n\t\/\/ })\n\n\treturn p\n}\n\ntype pluginSpec struct {\n\tsm   string\n\tType string            `msgpack:\"type\"`\n\tName string            `msgpack:\"name\"`\n\tSync bool              `msgpack:\"sync\"`\n\tOpts map[string]string `msgpack:\"opts\"`\n}\n\nfunc (spec *pluginSpec) path() string {\n\tif i := strings.Index(spec.sm, \":\"); i > 0 {\n\t\treturn spec.sm[:i]\n\t}\n\n\treturn \"\"\n}\n\nfunc isSync(f interface{}) bool {\n\tt := reflect.TypeOf(f)\n\n\treturn t.Kind() == reflect.Func && t.NumOut() > 0\n}\n\nfunc (p *Plugin) handle(fn interface{}, spec *pluginSpec) {\n\tp.pluginSpecs = append(p.pluginSpecs, spec)\n\tif p.Nvim == nil {\n\t\treturn\n\t}\n\n\tif err := p.Nvim.RegisterHandler(spec.sm, fn); err != nil {\n\t\tpanic(err)\n\t}\n}\n\n\/\/ Handle registers fn as a MessagePack RPC handler for the specified method\n\/\/ name. The function signature for fn is one of\n\/\/\n\/\/  func([v *nvim.Nvim,] {args}) ({resultType}, error)\n\/\/  func([v *nvim.Nvim,] {args}) error\n\/\/  func([v *nvim.Nvim,] {args})\n\/\/\n\/\/ where {args} is zero or more arguments and {resultType} is the type of of a\n\/\/ return value. Call the handler from Nvim using the rpcnotify and rpcrequest\n\/\/ functions:\n\/\/\n\/\/  :help rpcrequest()\n\/\/  :help rpcnotify()\nfunc (p *Plugin) Handle(method string, fn interface{}) {\n\tif p.Nvim == nil {\n\t\treturn\n\t}\n\n\tif err := p.Nvim.RegisterHandler(method, fn); err != nil {\n\t\tpanic(err)\n\t}\n}\n\n\/\/ FunctionOptions specifies function options.\ntype FunctionOptions struct {\n\t\/\/ Name is the name of the function in Nvim. The name must be made of\n\t\/\/ alphanumeric characters and '_', and must start with a capital letter.\n\tName string\n\n\t\/\/ Eval is an expression evaluated in Nvim. The result is passed the\n\t\/\/ handler function.\n\tEval string\n}\n\n\/\/ HandleFunction registers fn as a handler for a Nvim function. The function\n\/\/ signature for fn is one of\n\/\/\n\/\/  func([v *nvim.Nvim,] args {arrayType} [, eval {evalType}]) ({resultType}, error)\n\/\/  func([v *nvim.Nvim,] args {arrayType} [, eval {evalType}]) error\n\/\/\n\/\/ where {arrayType} is a type that can be unmarshaled from a MessagePack\n\/\/ array, {evalType} is a type compatible with the Eval option expression and\n\/\/ {resultType} is the type of function result.\n\/\/\n\/\/ If options.Eval == \"*\", then HandleFunction constructs the expression to\n\/\/ evaluate in Nvim from the type of fn's last argument. The last argument is\n\/\/ assumed to be a pointer to a struct type with 'eval' field tags set to the\n\/\/ expression to evaluate for each field. Nested structs are supported. The\n\/\/ expression for the function\n\/\/\n\/\/  func example(eval *struct{\n\/\/  \tGOPATH string `eval:\"$GOPATH\"`\n\/\/  \tCwd    string `eval:\"getcwd()\"`\n\/\/  })\n\/\/\n\/\/ is\n\/\/\n\/\/  {'GOPATH': $GOPATH, Cwd: getcwd()}\nfunc (p *Plugin) HandleFunction(options *FunctionOptions, fn interface{}) {\n\tm := make(map[string]string)\n\n\tif options.Eval != \"\" {\n\t\tm[\"eval\"] = eval(options.Eval, fn)\n\t}\n\n\tp.handle(fn, &pluginSpec{\n\t\tsm:   `0:function:` + options.Name,\n\t\tType: `function`,\n\t\tName: options.Name,\n\t\tSync: isSync(fn),\n\t\tOpts: m,\n\t})\n}\n\n\/\/ CommandOptions specifies command options.\ntype CommandOptions struct {\n\t\/\/ Name is the name of the command in Nvim. The name must be made of\n\t\/\/ alphanumeric characters and '_', and must start with a capital\n\t\/\/ letter.\n\tName string\n\n\t\/\/ NArgs specifies the number command arguments.\n\t\/\/\n\t\/\/  0   No arguments are allowed\n\t\/\/  1   Exactly one argument is required, it includes spaces\n\t\/\/  *   Any number of arguments are allowed (0, 1, or many),\n\t\/\/      separated by white space\n\t\/\/  ?   0 or 1 arguments are allowed\n\t\/\/  +   Arguments must be supplied, but any number are allowed\n\tNArgs string\n\n\t\/\/ Range specifies that the command accepts a range.\n\t\/\/\n\t\/\/  .   Range allowed, default is current line. The value\n\t\/\/      \".\" is converted to \"\" for Nvim.\n\t\/\/  %   Range allowed, default is whole file (1,$)\n\t\/\/  N   A count (default N) which is specified in the line\n\t\/\/      number position (like |:split|); allows for zero line\n\t\/\/\t    number.\n\t\/\/\n\t\/\/  :help :command-range\n\tRange string\n\n\t\/\/ Count specfies that thecommand accepts a count.\n\t\/\/\n\t\/\/  N   A count (default N) which is specified either in the line\n\t\/\/\t    number position, or as an initial argument (like |:Next|).\n\t\/\/      Specifying -count (without a default) acts like -count=0\n\t\/\/\n\t\/\/  :help :command-count\n\tCount string\n\n\t\/\/ Addr sepcifies the domain for the range option\n\t\/\/\n\t\/\/  lines           Range of lines (this is the default)\n\t\/\/  arguments       Range for arguments\n\t\/\/  buffers         Range for buffers (also not loaded buffers)\n\t\/\/  loaded_buffers  Range for loaded buffers\n\t\/\/  windows         Range for windows\n\t\/\/  tabs            Range for tab pages\n\t\/\/\n\t\/\/  :help command-addr\n\tAddr string\n\n\t\/\/ Eval is evaluated in Nvim and the result is passed as an argument.\n\tEval string\n\n\t\/\/ Complete specifies command completion.\n\t\/\/\n\t\/\/  :help :command-complete\n\tComplete string\n\n\t\/\/ Bang specifies that the command can take a ! modifier (like :q or :w).\n\tBang bool\n\n\t\/\/ Register specifes that the first argument to the command can be an\n\t\/\/ optional register name (like :del, :put, :yank).\n\tRegister bool\n\n\t\/\/ Bar specifies that the command can be followed by a \"|\" and another\n\t\/\/ command.  A \"|\" inside the command argument is not allowed then. Also\n\t\/\/ checks for a \" to start a comment.\n\tBar bool\n}\n\n\/\/ HandleCommand registers fn as a handler for a Nvim command. The arguments\n\/\/ to the function fn are:\n\/\/\n\/\/  v *nvim.Nvim        optional\n\/\/  args []string       when options.NArgs != \"\"\n\/\/  range [2]int        when options.Range == \".\" or Range == \"%\"\n\/\/  range int           when options.Range == N or Count != \"\"\n\/\/  bang bool           when options.Bang == true\n\/\/  register string     when options.Register == true\n\/\/  eval interface{}    when options.Eval != \"\"\n\/\/\n\/\/ The function fn must return an error.\n\/\/\n\/\/ If options.Eval == \"*\", then HandleCommand constructs the expression to\n\/\/ evaluate in Nvim from the type of fn's last argument. See the\n\/\/ HandleFunction documentation for information on how the expression is\n\/\/ generated.\nfunc (p *Plugin) HandleCommand(options *CommandOptions, fn interface{}) {\n\tm := make(map[string]string)\n\n\tif options.NArgs != \"\" {\n\t\tm[`nargs`] = options.NArgs\n\t}\n\n\tswitch {\n\tcase options.Range == `.`:\n\t\toptions.Range = \"\"\n\t\tfallthrough\n\tcase options.Range != \"\":\n\t\tm[`range`] = options.Range\n\tcase options.Count != \"\":\n\t\tm[`count`] = options.Count\n\t}\n\n\tif options.Bang {\n\t\tm[`bang`] = \"\"\n\t}\n\n\tif options.Register {\n\t\tm[`register`] = \"\"\n\t}\n\n\tif options.Eval != \"\" {\n\t\tm[`eval`] = eval(options.Eval, fn)\n\t}\n\n\tif options.Addr != \"\" {\n\t\tm[`addr`] = options.Addr\n\t}\n\n\tif options.Bar {\n\t\tm[`bar`] = \"\"\n\t}\n\n\tif options.Complete != \"\" {\n\t\tm[`complete`] = options.Complete\n\t}\n\n\tp.handle(fn, &pluginSpec{\n\t\tsm:   `0:command:` + options.Name,\n\t\tType: `command`,\n\t\tName: options.Name,\n\t\tSync: isSync(fn),\n\t\tOpts: m,\n\t})\n}\n\n\/\/ AutocmdOptions specifies autocmd options.\ntype AutocmdOptions struct {\n\t\/\/ Event is the event name.\n\tEvent string\n\n\t\/\/ Group specifies the autocmd group.\n\tGroup string\n\n\t\/\/ Pattern specifies an autocmd pattern.\n\t\/\/\n\t\/\/  :help autocmd-patterns\n\tPattern string\n\n\t\/\/ Nested allows nested autocmds.\n\t\/\/\n\t\/\/  :help autocmd-nested\n\tNested bool\n\n\t\/\/ Once supplys the command is executed once, then removed (\"one shot\").\n\t\/\/\n\t\/\/  :help autocmd-once\n\tOnce bool\n\n\t\/\/ Eval is evaluated in Nvim and the result is passed the the handler\n\t\/\/ function.\n\tEval string\n}\n\n\/\/ HandleAutocmd registers fn as a handler an autocmnd event.\n\/\/\n\/\/ If options.Eval == \"*\", then HandleAutocmd constructs the expression to\n\/\/ evaluate in Nvim from the type of fn's last argument. See the HandleFunction\n\/\/ documentation for information on how the expression is generated.\nfunc (p *Plugin) HandleAutocmd(options *AutocmdOptions, fn interface{}) {\n\tpattern := \"\"\n\n\tm := make(map[string]string)\n\n\tif options.Group != \"\" {\n\t\tm[`group`] = options.Group\n\t}\n\n\tif options.Pattern != \"\" {\n\t\tm[`pattern`] = options.Pattern\n\t\tpattern = options.Pattern\n\t}\n\n\tif options.Nested {\n\t\tm[`nested`] = `1`\n\t}\n\n\tif options.Once {\n\t\tm[`once`] = `1`\n\t}\n\n\tif options.Eval != \"\" {\n\t\tm[`eval`] = eval(options.Eval, fn)\n\t}\n\n\t\/\/ Compute unique path for event and pattern.\n\tep := options.Event + \":\" + pattern\n\ti := p.eventPathCounts[ep]\n\tp.eventPathCounts[ep] = i + 1\n\n\tsm := fmt.Sprintf(`%d:autocmd:%s`, i, ep)\n\n\tp.handle(fn, &pluginSpec{\n\t\tsm:   sm,\n\t\tType: `autocmd`,\n\t\tName: options.Event,\n\t\tSync: isSync(fn),\n\t\tOpts: m,\n\t})\n}\n\n\/\/ RegisterForTests registers the plugin with Nvim. Use this method for testing\n\/\/ plugins in an embedded instance of Nvim.\nfunc (p *Plugin) RegisterForTests() error {\n\tspecs := make(map[string][]*pluginSpec)\n\tfor _, spec := range p.pluginSpecs {\n\t\tspecs[spec.path()] = append(specs[spec.path()], spec)\n\t}\n\n\tconst host = \"nvim-go-test\"\n\tfor path, specs := range specs {\n\t\tif err := p.Nvim.Call(\"remote#host#RegisterPlugin\", nil, host, path, specs); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\terr := p.Nvim.Call(\"remote#host#Register\", nil, host, \"x\", p.Nvim.ChannelID())\n\n\treturn err\n}\n\nfunc eval(eval string, f interface{}) string {\n\tif eval != `*` {\n\t\treturn eval\n\t}\n\n\tft := reflect.TypeOf(f)\n\tif ft.Kind() != reflect.Func || ft.NumIn() < 1 {\n\t\tpanic(`Eval: \"*\" option requires function with at least one argument`)\n\t}\n\n\targt := ft.In(ft.NumIn() - 1)\n\tif argt.Kind() != reflect.Ptr || argt.Elem().Kind() != reflect.Struct {\n\t\tpanic(`Eval: \"*\" option requires function with pointer to struct as last argument`)\n\t}\n\n\treturn structEval(argt.Elem())\n}\n\nfunc structEval(t reflect.Type) string {\n\tvar sb strings.Builder\n\n\tsb.WriteByte('{')\n\tsep := \"\"\n\n\tfor i := 0; i < t.NumField(); i++ {\n\t\tsf := t.Field(i)\n\t\tif sf.Anonymous {\n\t\t\tpanic(`Eval: \"*\" does not support anonymous fields`)\n\t\t}\n\n\t\teval := sf.Tag.Get(\"eval\")\n\t\tif eval == \"\" {\n\t\t\tft := sf.Type\n\t\t\tif ft.Kind() == reflect.Ptr {\n\t\t\t\tft = ft.Elem()\n\t\t\t}\n\n\t\t\tif ft.Kind() == reflect.Struct {\n\t\t\t\teval = structEval(ft)\n\t\t\t}\n\t\t}\n\t\tif eval == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tname := strings.Split(sf.Tag.Get(\"msgpack\"), \",\")[0]\n\t\tif name == \"\" {\n\t\t\tname = sf.Name\n\t\t}\n\n\t\tsb.WriteString(sep)\n\t\tsb.WriteByte('\\'')\n\t\tsb.WriteString(name)\n\t\tsb.WriteString(\"': \")\n\t\tsb.WriteString(eval)\n\t\tsep = \", \"\n\t}\n\tsb.WriteByte('}')\n\n\treturn sb.String()\n}\n\ntype byServiceMethod []*pluginSpec\n\nfunc (a byServiceMethod) Len() int           { return len(a) }\nfunc (a byServiceMethod) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }\nfunc (a byServiceMethod) Less(i, j int) bool { return a[i].sm < a[j].sm }\n\nfunc (p *Plugin) Manifest(host string) []byte {\n\tvar buf bytes.Buffer\n\n\t\/\/ Sort for consistent order on output.\n\tsort.Sort(byServiceMethod(p.pluginSpecs))\n\tescape := strings.NewReplacer(`'`, `''`).Replace\n\n\tprevPath := \"\"\n\tfor _, spec := range p.pluginSpecs {\n\t\tpath := spec.path()\n\t\tif path != prevPath {\n\t\t\tif prevPath != \"\" {\n\t\t\t\tfmt.Fprintf(&buf, \"\\\\ )\")\n\t\t\t}\n\t\t\tfmt.Fprintf(&buf, \"call remote#host#RegisterPlugin('%s', '%s', [\\n\", host, path)\n\t\t\tprevPath = path\n\t\t}\n\n\t\tsync := \"0\"\n\t\tif spec.Sync {\n\t\t\tsync = \"1\"\n\t\t}\n\n\t\tfmt.Fprintf(&buf, \"\\\\ {'type': '%s', 'name': '%s', 'sync': %s, 'opts': {\", spec.Type, spec.Name, sync)\n\n\t\tvar keys []string\n\t\tfor k := range spec.Opts {\n\t\t\tkeys = append(keys, k)\n\t\t}\n\t\tsort.Strings(keys)\n\n\t\toptDelim := \"\"\n\t\tfor _, k := range keys {\n\t\t\tfmt.Fprintf(&buf, \"%s'%s': '%s'\", optDelim, k, escape(spec.Opts[k]))\n\t\t\toptDelim = \", \"\n\t\t}\n\n\t\tfmt.Fprintf(&buf, \"}},\\n\")\n\t}\n\tif prevPath != \"\" {\n\t\tfmt.Fprintf(&buf, \"\\\\ ])\\n\")\n\t}\n\n\treturn buf.Bytes()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014 Damjan Cvetko. All rights reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license\n\/\/ that can be found in the LICENSE file in the root of the source\n\/\/ tree.\n\npackage pcapgo\n\nimport (\n\t\"encoding\/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"time\"\n\n\t\"github.com\/google\/gopacket\"\n\t\"github.com\/google\/gopacket\/layers\"\n\t\"compress\/gzip\"\n\t\"bufio\"\n)\n\n\/\/ Reader wraps an underlying io.Reader to read packet data in PCAP\n\/\/ format.  See http:\/\/wiki.wireshark.org\/Development\/LibpcapFileFormat\n\/\/ for information on the file format.\n\/\/\n\/\/ We currenty read v2.4 file format with nanosecond and microsecdond\n\/\/ timestamp resolution in little-endian and big-endian encoding.\ntype Reader struct {\n\tr              io.Reader\n\tbyteOrder      binary.ByteOrder\n\tnanoSecsFactor uint32\n\tversionMajor   uint16\n\tversionMinor   uint16\n\t\/\/ timezone\n\t\/\/ sigfigs\n\tsnaplen  uint32\n\tlinkType layers.LinkType\n\t\/\/ reusable buffer\n\tbuf []byte\n}\n\nconst magicNanoseconds = 0xA1B23C4D\nconst magicMicrosecondsBigendian = 0xD4C3B2A1\nconst magicNanosecondsBigendian = 0x4D3CB2A1\n\nconst magicGzip1 = 0x1f\nconst magicGzip2 = 0x8b\n\n\n\/\/ NewReader returns a new reader object, for reading packet data from\n\/\/ the given reader. The reader must be open and header data is\n\/\/ read from it at this point.\n\/\/ If the file format is not supported an error is returned\n\/\/\n\/\/  \/\/ Create new reader:\n\/\/  f, _ := os.Open(\"\/tmp\/file.pcap\")\n\/\/  defer f.Close()\n\/\/  r, err := NewReader(f)\n\/\/  data, ci, err := r.ReadPacketData()\nfunc NewReader(r io.Reader) (*Reader, error) {\n\tret := Reader{r: r}\n\tif err := ret.readHeader(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ret, nil\n}\n\nfunc (r *Reader) readHeader() error {\n\tbr := bufio.NewReader(r.r)\n\tgzipMagic, err := br.Peek(2)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif gzipMagic[0] == magicGzip1 && gzipMagic[1] == magicGzip2 {\n\t\tif r.r, err = gzip.NewReader(br); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tr.r = br\n\t}\n\n\tbuf := make([]byte, 24)\n\tif n, err := io.ReadFull(r.r, buf); err != nil {\n\t\treturn err\n\t} else if n < 24 {\n\t\treturn errors.New(\"Not enough data for read\")\n\t}\n\tif magic := binary.LittleEndian.Uint32(buf[0:4]); magic == magicNanoseconds {\n\t\tr.byteOrder = binary.LittleEndian\n\t\tr.nanoSecsFactor = 1\n\t} else if magic == magicNanosecondsBigendian {\n\t\tr.byteOrder = binary.BigEndian\n\t\tr.nanoSecsFactor = 1\n\t} else if magic == magicMicroseconds {\n\t\tr.byteOrder = binary.LittleEndian\n\t\tr.nanoSecsFactor = 1000\n\t} else if magic == magicMicrosecondsBigendian {\n\t\tr.byteOrder = binary.BigEndian\n\t\tr.nanoSecsFactor = 1000\n\t} else {\n\t\treturn errors.New(fmt.Sprintf(\"Unknown magic %x\", magic))\n\t}\n\tif r.versionMajor = r.byteOrder.Uint16(buf[4:6]); r.versionMajor != versionMajor {\n\t\treturn errors.New(fmt.Sprintf(\"Unknown major version %d\", r.versionMajor))\n\t}\n\tif r.versionMinor = r.byteOrder.Uint16(buf[6:8]); r.versionMinor != versionMinor {\n\t\treturn errors.New(fmt.Sprintf(\"Unknown minor version %d\", r.versionMinor))\n\t}\n\t\/\/ ignore timezone 8:12 and sigfigs 12:16\n\tr.snaplen = r.byteOrder.Uint32(buf[16:20])\n\tr.buf = make([]byte, r.snaplen+16)\n\tr.linkType = layers.LinkType(r.byteOrder.Uint32(buf[20:24]))\n\treturn nil\n}\n\n\/\/ Read next packet from file\nfunc (r *Reader) ReadPacketData() (data []byte, ci gopacket.CaptureInfo, err error) {\n\tif ci, err = r.readPacketHeader(); err != nil {\n\t\treturn\n\t}\n\n\tvar n int\n\tif 16+ci.CaptureLength > len(r.buf) {\n\t\terr = fmt.Errorf(\"capture length with header exceeds buffer size: %d > %d\", 16+ci.CaptureLength, len(r.buf))\n\t\treturn\n\t}\n\tdata = r.buf[16 : 16+ci.CaptureLength]\n\tif n, err = io.ReadFull(r.r, data); err != nil {\n\t\treturn\n\t} else if n < ci.CaptureLength {\n\t\terr = io.ErrUnexpectedEOF\n\t}\n\treturn\n}\n\nfunc (r *Reader) readPacketHeader() (ci gopacket.CaptureInfo, err error) {\n\tvar n int\n\tif n, err = io.ReadFull(r.r, r.buf[0:16]); err != nil {\n\t\treturn\n\t} else if n < 16 {\n\t\terr = io.ErrUnexpectedEOF\n\t\treturn\n\t}\n\tci.Timestamp = time.Unix(int64(r.byteOrder.Uint32(r.buf[0:4])), int64(r.byteOrder.Uint32(r.buf[4:8])*r.nanoSecsFactor)).UTC()\n\tci.CaptureLength = int(r.byteOrder.Uint32(r.buf[8:12]))\n\tci.Length = int(r.byteOrder.Uint32(r.buf[12:16]))\n\treturn\n}\n\n\/\/ LinkType returns network, as a layers.LinkType.\nfunc (r *Reader) LinkType() layers.LinkType {\n\treturn r.linkType\n}\n\n\/\/ Reader formater\nfunc (r *Reader) String() string {\n\treturn fmt.Sprintf(\"PcapFile  maj: %x min: %x snaplen: %d linktype: %s\", r.versionMajor, r.versionMinor, r.snaplen, r.linkType)\n}\n<commit_msg>Fixed gofmt issue :(<commit_after>\/\/ Copyright 2014 Damjan Cvetko. All rights reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license\n\/\/ that can be found in the LICENSE file in the root of the source\n\/\/ tree.\n\npackage pcapgo\n\nimport (\n\t\"encoding\/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"time\"\n\n\t\"bufio\"\n\t\"compress\/gzip\"\n\t\"github.com\/google\/gopacket\"\n\t\"github.com\/google\/gopacket\/layers\"\n)\n\n\/\/ Reader wraps an underlying io.Reader to read packet data in PCAP\n\/\/ format.  See http:\/\/wiki.wireshark.org\/Development\/LibpcapFileFormat\n\/\/ for information on the file format.\n\/\/\n\/\/ We currenty read v2.4 file format with nanosecond and microsecdond\n\/\/ timestamp resolution in little-endian and big-endian encoding.\ntype Reader struct {\n\tr              io.Reader\n\tbyteOrder      binary.ByteOrder\n\tnanoSecsFactor uint32\n\tversionMajor   uint16\n\tversionMinor   uint16\n\t\/\/ timezone\n\t\/\/ sigfigs\n\tsnaplen  uint32\n\tlinkType layers.LinkType\n\t\/\/ reusable buffer\n\tbuf []byte\n}\n\nconst magicNanoseconds = 0xA1B23C4D\nconst magicMicrosecondsBigendian = 0xD4C3B2A1\nconst magicNanosecondsBigendian = 0x4D3CB2A1\n\nconst magicGzip1 = 0x1f\nconst magicGzip2 = 0x8b\n\n\/\/ NewReader returns a new reader object, for reading packet data from\n\/\/ the given reader. The reader must be open and header data is\n\/\/ read from it at this point.\n\/\/ If the file format is not supported an error is returned\n\/\/\n\/\/  \/\/ Create new reader:\n\/\/  f, _ := os.Open(\"\/tmp\/file.pcap\")\n\/\/  defer f.Close()\n\/\/  r, err := NewReader(f)\n\/\/  data, ci, err := r.ReadPacketData()\nfunc NewReader(r io.Reader) (*Reader, error) {\n\tret := Reader{r: r}\n\tif err := ret.readHeader(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ret, nil\n}\n\nfunc (r *Reader) readHeader() error {\n\tbr := bufio.NewReader(r.r)\n\tgzipMagic, err := br.Peek(2)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif gzipMagic[0] == magicGzip1 && gzipMagic[1] == magicGzip2 {\n\t\tif r.r, err = gzip.NewReader(br); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tr.r = br\n\t}\n\n\tbuf := make([]byte, 24)\n\tif n, err := io.ReadFull(r.r, buf); err != nil {\n\t\treturn err\n\t} else if n < 24 {\n\t\treturn errors.New(\"Not enough data for read\")\n\t}\n\tif magic := binary.LittleEndian.Uint32(buf[0:4]); magic == magicNanoseconds {\n\t\tr.byteOrder = binary.LittleEndian\n\t\tr.nanoSecsFactor = 1\n\t} else if magic == magicNanosecondsBigendian {\n\t\tr.byteOrder = binary.BigEndian\n\t\tr.nanoSecsFactor = 1\n\t} else if magic == magicMicroseconds {\n\t\tr.byteOrder = binary.LittleEndian\n\t\tr.nanoSecsFactor = 1000\n\t} else if magic == magicMicrosecondsBigendian {\n\t\tr.byteOrder = binary.BigEndian\n\t\tr.nanoSecsFactor = 1000\n\t} else {\n\t\treturn errors.New(fmt.Sprintf(\"Unknown magic %x\", magic))\n\t}\n\tif r.versionMajor = r.byteOrder.Uint16(buf[4:6]); r.versionMajor != versionMajor {\n\t\treturn errors.New(fmt.Sprintf(\"Unknown major version %d\", r.versionMajor))\n\t}\n\tif r.versionMinor = r.byteOrder.Uint16(buf[6:8]); r.versionMinor != versionMinor {\n\t\treturn errors.New(fmt.Sprintf(\"Unknown minor version %d\", r.versionMinor))\n\t}\n\t\/\/ ignore timezone 8:12 and sigfigs 12:16\n\tr.snaplen = r.byteOrder.Uint32(buf[16:20])\n\tr.buf = make([]byte, r.snaplen+16)\n\tr.linkType = layers.LinkType(r.byteOrder.Uint32(buf[20:24]))\n\treturn nil\n}\n\n\/\/ Read next packet from file\nfunc (r *Reader) ReadPacketData() (data []byte, ci gopacket.CaptureInfo, err error) {\n\tif ci, err = r.readPacketHeader(); err != nil {\n\t\treturn\n\t}\n\n\tvar n int\n\tif 16+ci.CaptureLength > len(r.buf) {\n\t\terr = fmt.Errorf(\"capture length with header exceeds buffer size: %d > %d\", 16+ci.CaptureLength, len(r.buf))\n\t\treturn\n\t}\n\tdata = r.buf[16 : 16+ci.CaptureLength]\n\tif n, err = io.ReadFull(r.r, data); err != nil {\n\t\treturn\n\t} else if n < ci.CaptureLength {\n\t\terr = io.ErrUnexpectedEOF\n\t}\n\treturn\n}\n\nfunc (r *Reader) readPacketHeader() (ci gopacket.CaptureInfo, err error) {\n\tvar n int\n\tif n, err = io.ReadFull(r.r, r.buf[0:16]); err != nil {\n\t\treturn\n\t} else if n < 16 {\n\t\terr = io.ErrUnexpectedEOF\n\t\treturn\n\t}\n\tci.Timestamp = time.Unix(int64(r.byteOrder.Uint32(r.buf[0:4])), int64(r.byteOrder.Uint32(r.buf[4:8])*r.nanoSecsFactor)).UTC()\n\tci.CaptureLength = int(r.byteOrder.Uint32(r.buf[8:12]))\n\tci.Length = int(r.byteOrder.Uint32(r.buf[12:16]))\n\treturn\n}\n\n\/\/ LinkType returns network, as a layers.LinkType.\nfunc (r *Reader) LinkType() layers.LinkType {\n\treturn r.linkType\n}\n\n\/\/ Reader formater\nfunc (r *Reader) String() string {\n\treturn fmt.Sprintf(\"PcapFile  maj: %x min: %x snaplen: %d linktype: %s\", r.versionMajor, r.versionMinor, r.snaplen, r.linkType)\n}\n<|endoftext|>"}
{"text":"<commit_before>package api\n\nimport (\n    \"testing\"\n    \"net\/url\"\n    \"strconv\"\n)\n\nfunc TestNewProductService(t *testing.T) {\n    affiliate_id := Dummy_Affliate_Id\n    api_id       := Dummy_Api_Id\n\n    srv := NewProductService(affiliate_id, api_id)\n    if srv.AffiliateId != affiliate_id {\n        t.Fatalf(\"ProductService.AffiliateId is expected to equal the input value(affiliate_id)\")\n    }\n\n    if srv.ApiId != api_id {\n        t.Fatalf(\"ProductService.ApiId is expected to equal the input value(api_id)\")\n    }\n}\n\nfunc TestSetLengthInProductService(t *testing.T) {\n    srv := dummyProductService()\n    var length int64 = 10\n    srv.SetLength(length)\n\n    if srv.Length != length {\n        t.Fatalf(\"ProductService.Length is expected to equal the input value(length)\")\n    }\n}\n\nfunc TestSetHitsInProductService(t *testing.T) {\n    srv := dummyProductService()\n    var hits int64 = 10\n    srv.SetHits(hits)\n\n    if srv.Length != hits {\n        t.Fatalf(\"ProductService.Length is expected to equal the input value(hits)\")\n    }\n}\n\nfunc TestSetOffsetInProductService(t *testing.T) {\n    srv := dummyProductService()\n    var offset int64 = 10\n    srv.SetOffset(offset)\n\n    if srv.Offset != offset {\n        t.Fatalf(\"ProductService.Offset is expected to equal the input value(offset)\")\n    }\n}\n\nfunc TestSetKeywordInProductService(t *testing.T) {\n    srv := dummyProductService()\n\n    keyword1 := \"abcdefghijkelmnopqrstuvwxyzABCDEFGHIJKELMNOPQRSTUVWXYZ0123456789\"\n    srv.SetKeyword(keyword1)\n    if srv.Keyword != keyword1 {\n        t.Fatalf(\"ProductService.Keyword is expected to equal the input value(keyword1)\")\n    }\n\n    keyword2 := \"\"\n    srv.SetKeyword(keyword2)\n    if srv.Keyword != keyword2 {\n        t.Fatalf(\"ProductService.Keyword is expected to equal the input value(keyword2)\")\n    }\n\n    keyword3 := \"つれづれなるまゝに、日暮らし、硯にむかひて、心にうつりゆくよしなし事を、そこはかとなく書きつくれば、あやしうこそものぐるほしけれ。\"\n    srv.SetKeyword(keyword3)\n    if srv.Keyword != keyword3 {\n        t.Fatalf(\"ProductService.Keyword is expected to equal the input value(keyword3)\")\n    }\n\n    keyword4 := \" a b c d 0 \"\n    keyword4_expected := \"a b c d 0\"\n    srv.SetKeyword(keyword4)\n    if srv.Keyword != keyword4_expected {\n        t.Fatalf(\"ProductService.Keyword is expected to equal keyword4_expected\")\n    }\n\n    keyword5 := \"　あ ア　化Ａ \"\n    keyword5_expected := \"あ ア　化Ａ\"\n    srv.SetKeyword(keyword5)\n    if srv.Keyword != keyword5_expected {\n        t.Fatalf(\"ProductService.Keyword is expected to equal keyword5_expected\")\n    }\n}\n\nfunc TestSetSiteInProductService(t *testing.T) {\n    srv := dummyProductService()\n\n    var site string\n\n    site = SITE_ALLAGES\n    srv.SetSite(site)\n    if srv.Site != site {\n        t.Fatalf(\"ProductService.Site is expected to equal the input value. value:%s\", site)\n    }\n\n    site = SITE_ADULT\n    srv.SetSite(site)\n    if srv.Site != site {\n        t.Fatalf(\"ProductService.Site is expected to equal the input value. value:%s\", site)\n    }\n}\n\nfunc TestSetServiceInProductService(t *testing.T) {\n    srv := dummyProductService()\n\n    service := \"digital\"\n    srv.SetService(service)\n    if srv.Service != service {\n        t.Fatalf(\"ProductService.Service is expected to equal the input value(service)\")\n    }\n}\n\nfunc TestSetFloorInProductService(t *testing.T) {\n    srv := dummyProductService()\n\n    floor := \"videoa\"\n    srv.SetFloor(floor)\n    if srv.Floor != floor {\n        t.Fatalf(\"ProductService.Floor is expected to equal the input value(floor)\")\n    }\n}\n\nfunc TestValidateLengthInProductService(t *testing.T) {\n    srv := dummyProductService()\n\n    var target int64\n\n    target = 1\n    srv.SetLength(target)\n    if srv.ValidateLength() == false {\n        t.Fatalf(\"ProductService.ValidateLength is expected TRUE.\")\n    }\n\n    target = DEFAULT_PRODUCT_API_LENGTH\n    srv.SetLength(target)\n    if srv.ValidateLength() == false {\n        t.Fatalf(\"ProductService.ValidateLength is expected TRUE.\")\n    }\n\n    target = DEFAULT_PRODUCT_MAX_LENGTH\n    srv.SetLength(target)\n    if srv.ValidateLength() == false {\n        t.Fatalf(\"ProductService.ValidateLength is expected TRUE.\")\n    }\n\n    target = DEFAULT_PRODUCT_MAX_LENGTH + 1\n    srv.SetLength(target)\n    if srv.ValidateLength() == true {\n        t.Fatalf(\"ProductService.ValidateLength is expected FALSE.\")\n    }\n\n    target = 0\n    srv.SetLength(target)\n    if srv.ValidateLength() == true {\n        t.Fatalf(\"ProductService.ValidateLength is expected FALSE.\")\n    }\n\n    target = -1\n    srv.SetLength(target)\n    if srv.ValidateLength() == true {\n        t.Fatalf(\"ProductService.ValidateLength is expected FALSE.\")\n    }\n}\n\nfunc TestValidateOffsetInProductService(t *testing.T) {\n    srv := dummyProductService()\n\n    var target int64\n\n    target = 1\n    srv.SetOffset(target)\n    if srv.ValidateOffset() == false {\n        t.Fatalf(\"ProductService.ValidateOffset is expected TRUE. target:%d\", target)\n    }\n\n    target = DEFAULT_PRODUCT_MAX_OFFSET\n    srv.SetOffset(target)\n    if srv.ValidateOffset() == false {\n        t.Fatalf(\"ProductService.ValidateOffset is expected TRUE. target:%d\", target)\n    }\n\n    target = DEFAULT_PRODUCT_MAX_OFFSET + 1\n    srv.SetOffset(target)\n    if srv.ValidateOffset() == true {\n        t.Fatalf(\"ProductService.ValidateOffset is expected FALSE. target:%d\", target)\n    }\n\n    target = 0\n    srv.SetOffset(target)\n    if srv.ValidateOffset() == true {\n        t.Fatalf(\"ProductService.ValidateOffset is expected FALSE. target:%d\", target)\n    }\n\n    target = -1\n    srv.SetOffset(target)\n    if srv.ValidateOffset() == true {\n        t.Fatalf(\"ProductService.ValidateOffset is expected FALSE. target:%d\", target)\n    }\n}\n\nfunc TestBuildRequestUrlInProductService(t *testing.T) {\n    var srv *ProductService\n    var u string\n    var err error\n    var expected string\n\n    srv = dummyProductService()\n    srv.SetSite(SITE_ADULT)\n    u, err = srv.BuildRequestUrl()\n    expected = API_BASE_URL + \"\/ItemList?affiliate_id=\" + Dummy_Affliate_Id + \"&api_id=\" + Dummy_Api_Id + \"&hits=\" + strconv.FormatInt(DEFAULT_ACTRESS_API_LENGTH, 10) + \"&offset=\" + strconv.FormatInt(DEFAULT_API_OFFSET, 10) + \"&site=\" + SITE_ADULT\n    if u != expected {\n        t.Fatalf(\"ProductService.BuildRequestUrl is expected to equal the expected value.\\nexpected:%s\\nactual:  %s\", expected, u)\n    }\n    if err != nil {\n        t.Fatalf(\"ProductService.BuildRequestUrl is not expected to have error\")\n    }\n\n    srv = dummyProductService()\n    srv.SetSite(SITE_ADULT)\n    srv.SetLength(0)\n    srv.SetOffset(0)\n    u, err = srv.BuildRequestUrl()\n    expected = API_BASE_URL + \"\/ItemList?affiliate_id=\" + Dummy_Affliate_Id + \"&api_id=\" + Dummy_Api_Id\n    expected_base := expected\n    expected = expected_base + \"&site=\" + SITE_ADULT\n    if u != expected {\n        t.Fatalf(\"ProductService.BuildRequestUrl is expected to equal the expected value.\\nexpected:%s\\nactual:  %s\", expected, u)\n    }\n    if err != nil {\n        t.Fatalf(\"ProductService.BuildRequestUrl is not expected to have error\")\n    }\n\n    srv.SetSite(\"\")\n    u, err = srv.BuildRequestUrl()\n    if u != \"\" {\n        t.Fatalf(\"ProductService.BuildRequestUrl is expected empty if error occurs.\")\n    }\n    if err == nil {\n        t.Fatalf(\"ProductService.BuildRequestUrl is expected to return error.\")\n    }\n    srv.SetSite(SITE_ADULT)\n\n    srv.SetLength(-1)\n    u, err = srv.BuildRequestUrl()\n    if u != \"\" {\n        t.Fatalf(\"ProductService.BuildRequestUrl is expected empty if error occurs.\")\n    }\n    if err == nil {\n        t.Fatalf(\"ProductService.BuildRequestUrl is expected to return error.\")\n    }\n    srv.SetLength(0)\n\n    srv.SetOffset(-1)\n    u, err = srv.BuildRequestUrl()\n    if u != \"\" {\n        t.Fatalf(\"ProductService.BuildRequestUrl is expected empty if error occurs.\")\n    }\n    if err == nil {\n        t.Fatalf(\"ProductService.BuildRequestUrl is expected to return error.\")\n    }\n    srv.SetOffset(0)\n\n    srv.SetSort(\"rank\")\n    expected = expected_base + \"&site=\" + SITE_ADULT + \"&sort=rank\"\n    u, err = srv.BuildRequestUrl()\n    if u != expected {\n        t.Fatalf(\"ActressService.BuildRequestUrl is expected to equal the expected value.\\nexpected:%s\\nactual:  %s\", expected, u)\n    }\n    if err != nil {\n        t.Fatalf(\"ActressService.BuildRequestUrl is not expected to have error\")\n    }\n    srv.SetSort(\"\")\n\n    srv.SetKeyword(\"上原亜衣\")\n    expected = expected_base + \"&keyword=\" + url.QueryEscape(\"上原亜衣\") + \"&site=\" + SITE_ADULT\n    u, err = srv.BuildRequestUrl()\n    if u != expected {\n        t.Fatalf(\"ProductService.BuildRequestUrl is expected to equal the expected value.\\nexpected:%s\\nactual:  %s\", expected, u)\n    }\n    if err != nil {\n        t.Fatalf(\"ProductService.BuildRequestUrl is not expected to have error\")\n    }\n    srv.SetKeyword(\"\")\n\n    srv.SetService(\"digital\")\n    expected = expected_base + \"&service=\" + url.QueryEscape(\"digital\") + \"&site=\" + SITE_ADULT\n    u, err = srv.BuildRequestUrl()\n    if u != expected {\n        t.Fatalf(\"ProductService.BuildRequestUrl is expected to equal the expected value.\\nexpected:%s\\nactual:  %s\", expected, u)\n    }\n    if err != nil {\n        t.Fatalf(\"ProductService.BuildRequestUrl is not expected to have error\")\n    }\n    srv.SetService(\"\")\n\n    srv.SetFloor(\"videoa\")\n    expected = expected_base + \"&floor=\" + url.QueryEscape(\"videoa\") + \"&site=\" + SITE_ADULT\n    u, err = srv.BuildRequestUrl()\n    if u != expected {\n        t.Fatalf(\"ProductService.BuildRequestUrl is expected to equal the expected value.\\nexpected:%s\\nactual:  %s\", expected, u)\n    }\n    if err != nil {\n        t.Fatalf(\"ProductService.BuildRequestUrl is not expected to have error\")\n    }\n    srv.SetFloor(\"\")\n}\n\nfunc TestBuildRequestUrlWithoutApiIdInInProductService(t *testing.T) {\n    srv := dummyProductService()\n    srv.ApiId = \"\"\n    u, err := srv.BuildRequestUrl()\n    if u != \"\" {\n        t.Fatalf(\"ProductService.BuildRequestUrl is expected empty if API ID is not set.\")\n    }\n    if err == nil {\n        t.Fatalf(\"ProductService.BuildRequestUrl is expected to return error.\")\n    }\n}\n\nfunc TestBuildRequestUrlWithWrongAffiliateIdInProductService(t *testing.T) {\n    srv := dummyProductService()\n    srv.AffiliateId = \"fizzbizz-100\"\n    u, err := srv.BuildRequestUrl()\n    if u != \"\" {\n        t.Fatalf(\"ProductService.BuildRequestUrl is expected empty if wrong Affiliate ID is set.\")\n    }\n    if err == nil {\n        t.Fatalf(\"ProductService.BuildRequestUrl is expected to return error.\")\n    }\n}\n\nfunc dummyProductService() *ProductService {\n    return NewProductService(Dummy_Affliate_Id, Dummy_Api_Id)\n}<commit_msg>add tests<commit_after>package api\n\nimport (\n    \"testing\"\n    \"net\/url\"\n    \"strconv\"\n)\n\nfunc TestNewProductService(t *testing.T) {\n    affiliate_id := Dummy_Affliate_Id\n    api_id       := Dummy_Api_Id\n\n    srv := NewProductService(affiliate_id, api_id)\n    if srv.AffiliateId != affiliate_id {\n        t.Fatalf(\"ProductService.AffiliateId is expected to equal the input value(affiliate_id)\")\n    }\n\n    if srv.ApiId != api_id {\n        t.Fatalf(\"ProductService.ApiId is expected to equal the input value(api_id)\")\n    }\n}\n\nfunc TestSetLengthInProductService(t *testing.T) {\n    srv := dummyProductService()\n    var length int64 = 10\n    srv.SetLength(length)\n\n    if srv.Length != length {\n        t.Fatalf(\"ProductService.Length is expected to equal the input value(length)\")\n    }\n}\n\nfunc TestSetHitsInProductService(t *testing.T) {\n    srv := dummyProductService()\n    var hits int64 = 10\n    srv.SetHits(hits)\n\n    if srv.Length != hits {\n        t.Fatalf(\"ProductService.Length is expected to equal the input value(hits)\")\n    }\n}\n\nfunc TestSetOffsetInProductService(t *testing.T) {\n    srv := dummyProductService()\n    var offset int64 = 10\n    srv.SetOffset(offset)\n\n    if srv.Offset != offset {\n        t.Fatalf(\"ProductService.Offset is expected to equal the input value(offset)\")\n    }\n}\n\nfunc TestSetKeywordInProductService(t *testing.T) {\n    srv := dummyProductService()\n\n    keyword1 := \"abcdefghijkelmnopqrstuvwxyzABCDEFGHIJKELMNOPQRSTUVWXYZ0123456789\"\n    srv.SetKeyword(keyword1)\n    if srv.Keyword != keyword1 {\n        t.Fatalf(\"ProductService.Keyword is expected to equal the input value(keyword1)\")\n    }\n\n    keyword2 := \"\"\n    srv.SetKeyword(keyword2)\n    if srv.Keyword != keyword2 {\n        t.Fatalf(\"ProductService.Keyword is expected to equal the input value(keyword2)\")\n    }\n\n    keyword3 := \"つれづれなるまゝに、日暮らし、硯にむかひて、心にうつりゆくよしなし事を、そこはかとなく書きつくれば、あやしうこそものぐるほしけれ。\"\n    srv.SetKeyword(keyword3)\n    if srv.Keyword != keyword3 {\n        t.Fatalf(\"ProductService.Keyword is expected to equal the input value(keyword3)\")\n    }\n\n    keyword4 := \" a b c d 0 \"\n    keyword4_expected := \"a b c d 0\"\n    srv.SetKeyword(keyword4)\n    if srv.Keyword != keyword4_expected {\n        t.Fatalf(\"ProductService.Keyword is expected to equal keyword4_expected\")\n    }\n\n    keyword5 := \"　あ ア　化Ａ \"\n    keyword5_expected := \"あ ア　化Ａ\"\n    srv.SetKeyword(keyword5)\n    if srv.Keyword != keyword5_expected {\n        t.Fatalf(\"ProductService.Keyword is expected to equal keyword5_expected\")\n    }\n}\n\nfunc TestSetSiteInProductService(t *testing.T) {\n    srv := dummyProductService()\n\n    var site string\n\n    site = SITE_ALLAGES\n    srv.SetSite(site)\n    if srv.Site != site {\n        t.Fatalf(\"ProductService.Site is expected to equal the input value. value:%s\", site)\n    }\n\n    site = SITE_ADULT\n    srv.SetSite(site)\n    if srv.Site != site {\n        t.Fatalf(\"ProductService.Site is expected to equal the input value. value:%s\", site)\n    }\n}\n\nfunc TestSetServiceInProductService(t *testing.T) {\n    srv := dummyProductService()\n\n    service := \"digital\"\n    srv.SetService(service)\n    if srv.Service != service {\n        t.Fatalf(\"ProductService.Service is expected to equal the input value(service)\")\n    }\n}\n\nfunc TestSetFloorInProductService(t *testing.T) {\n    srv := dummyProductService()\n\n    floor := \"videoa\"\n    srv.SetFloor(floor)\n    if srv.Floor != floor {\n        t.Fatalf(\"ProductService.Floor is expected to equal the input value(floor)\")\n    }\n}\n\nfunc TestValidateLengthInProductService(t *testing.T) {\n    srv := dummyProductService()\n\n    var target int64\n\n    target = 1\n    srv.SetLength(target)\n    if srv.ValidateLength() == false {\n        t.Fatalf(\"ProductService.ValidateLength is expected TRUE.\")\n    }\n\n    target = DEFAULT_PRODUCT_API_LENGTH\n    srv.SetLength(target)\n    if srv.ValidateLength() == false {\n        t.Fatalf(\"ProductService.ValidateLength is expected TRUE.\")\n    }\n\n    target = DEFAULT_PRODUCT_MAX_LENGTH\n    srv.SetLength(target)\n    if srv.ValidateLength() == false {\n        t.Fatalf(\"ProductService.ValidateLength is expected TRUE.\")\n    }\n\n    target = DEFAULT_PRODUCT_MAX_LENGTH + 1\n    srv.SetLength(target)\n    if srv.ValidateLength() == true {\n        t.Fatalf(\"ProductService.ValidateLength is expected FALSE.\")\n    }\n\n    target = 0\n    srv.SetLength(target)\n    if srv.ValidateLength() == true {\n        t.Fatalf(\"ProductService.ValidateLength is expected FALSE.\")\n    }\n\n    target = -1\n    srv.SetLength(target)\n    if srv.ValidateLength() == true {\n        t.Fatalf(\"ProductService.ValidateLength is expected FALSE.\")\n    }\n}\n\nfunc TestValidateOffsetInProductService(t *testing.T) {\n    srv := dummyProductService()\n\n    var target int64\n\n    target = 1\n    srv.SetOffset(target)\n    if srv.ValidateOffset() == false {\n        t.Fatalf(\"ProductService.ValidateOffset is expected TRUE. target:%d\", target)\n    }\n\n    target = DEFAULT_PRODUCT_MAX_OFFSET\n    srv.SetOffset(target)\n    if srv.ValidateOffset() == false {\n        t.Fatalf(\"ProductService.ValidateOffset is expected TRUE. target:%d\", target)\n    }\n\n    target = DEFAULT_PRODUCT_MAX_OFFSET + 1\n    srv.SetOffset(target)\n    if srv.ValidateOffset() == true {\n        t.Fatalf(\"ProductService.ValidateOffset is expected FALSE. target:%d\", target)\n    }\n\n    target = 0\n    srv.SetOffset(target)\n    if srv.ValidateOffset() == true {\n        t.Fatalf(\"ProductService.ValidateOffset is expected FALSE. target:%d\", target)\n    }\n\n    target = -1\n    srv.SetOffset(target)\n    if srv.ValidateOffset() == true {\n        t.Fatalf(\"ProductService.ValidateOffset is expected FALSE. target:%d\", target)\n    }\n}\n\nfunc TestBuildRequestUrlInProductService(t *testing.T) {\n    var srv *ProductService\n    var u string\n    var err error\n    var expected string\n\n    srv = dummyProductService()\n    srv.SetSite(SITE_ADULT)\n    u, err = srv.BuildRequestUrl()\n    expected = API_BASE_URL + \"\/ItemList?affiliate_id=\" + Dummy_Affliate_Id + \"&api_id=\" + Dummy_Api_Id + \"&hits=\" + strconv.FormatInt(DEFAULT_ACTRESS_API_LENGTH, 10) + \"&offset=\" + strconv.FormatInt(DEFAULT_API_OFFSET, 10) + \"&site=\" + SITE_ADULT\n    if u != expected {\n        t.Fatalf(\"ProductService.BuildRequestUrl is expected to equal the expected value.\\nexpected:%s\\nactual:  %s\", expected, u)\n    }\n    if err != nil {\n        t.Fatalf(\"ProductService.BuildRequestUrl is not expected to have error\")\n    }\n\n    srv = dummyProductService()\n    srv.SetSite(SITE_ADULT)\n    srv.SetLength(0)\n    srv.SetOffset(0)\n    u, err = srv.BuildRequestUrl()\n    expected = API_BASE_URL + \"\/ItemList?affiliate_id=\" + Dummy_Affliate_Id + \"&api_id=\" + Dummy_Api_Id\n    expected_base := expected\n    expected = expected_base + \"&site=\" + SITE_ADULT\n    if u != expected {\n        t.Fatalf(\"ProductService.BuildRequestUrl is expected to equal the expected value.\\nexpected:%s\\nactual:  %s\", expected, u)\n    }\n    if err != nil {\n        t.Fatalf(\"ProductService.BuildRequestUrl is not expected to have error\")\n    }\n\n    srv.SetSite(\"\")\n    u, err = srv.BuildRequestUrl()\n    if u != \"\" {\n        t.Fatalf(\"ProductService.BuildRequestUrl is expected empty if error occurs.\")\n    }\n    if err == nil {\n        t.Fatalf(\"ProductService.BuildRequestUrl is expected to return error.\")\n    }\n    srv.SetSite(SITE_ADULT)\n\n    srv.SetLength(-1)\n    u, err = srv.BuildRequestUrl()\n    if u != \"\" {\n        t.Fatalf(\"ProductService.BuildRequestUrl is expected empty if error occurs.\")\n    }\n    if err == nil {\n        t.Fatalf(\"ProductService.BuildRequestUrl is expected to return error.\")\n    }\n    srv.SetLength(0)\n\n    srv.SetOffset(-1)\n    u, err = srv.BuildRequestUrl()\n    if u != \"\" {\n        t.Fatalf(\"ProductService.BuildRequestUrl is expected empty if error occurs.\")\n    }\n    if err == nil {\n        t.Fatalf(\"ProductService.BuildRequestUrl is expected to return error.\")\n    }\n    srv.SetOffset(0)\n\n    srv.SetSort(\"rank\")\n    expected = expected_base + \"&site=\" + SITE_ADULT + \"&sort=rank\"\n    u, err = srv.BuildRequestUrl()\n    if u != expected {\n        t.Fatalf(\"ActressService.BuildRequestUrl is expected to equal the expected value.\\nexpected:%s\\nactual:  %s\", expected, u)\n    }\n    if err != nil {\n        t.Fatalf(\"ActressService.BuildRequestUrl is not expected to have error\")\n    }\n    srv.SetSort(\"\")\n\n    srv.SetKeyword(\"上原亜衣\")\n    expected = expected_base + \"&keyword=\" + url.QueryEscape(\"上原亜衣\") + \"&site=\" + SITE_ADULT\n    u, err = srv.BuildRequestUrl()\n    if u != expected {\n        t.Fatalf(\"ProductService.BuildRequestUrl is expected to equal the expected value.\\nexpected:%s\\nactual:  %s\", expected, u)\n    }\n    if err != nil {\n        t.Fatalf(\"ProductService.BuildRequestUrl is not expected to have error\")\n    }\n    srv.SetKeyword(\"\")\n\n    srv.SetService(\"digital\")\n    expected = expected_base + \"&service=\" + url.QueryEscape(\"digital\") + \"&site=\" + SITE_ADULT\n    u, err = srv.BuildRequestUrl()\n    if u != expected {\n        t.Fatalf(\"ProductService.BuildRequestUrl is expected to equal the expected value.\\nexpected:%s\\nactual:  %s\", expected, u)\n    }\n    if err != nil {\n        t.Fatalf(\"ProductService.BuildRequestUrl is not expected to have error\")\n    }\n    srv.SetService(\"\")\n\n    srv.SetFloor(\"videoa\")\n    expected = expected_base + \"&floor=\" + url.QueryEscape(\"videoa\") + \"&site=\" + SITE_ADULT\n    u, err = srv.BuildRequestUrl()\n    if u != expected {\n        t.Fatalf(\"ProductService.BuildRequestUrl is expected to equal the expected value.\\nexpected:%s\\nactual:  %s\", expected, u)\n    }\n    if err != nil {\n        t.Fatalf(\"ProductService.BuildRequestUrl is not expected to have error\")\n    }\n    srv.SetFloor(\"\")\n\n    srv.SetArticle(\"actress\")\n    expected = expected_base + \"&article=\" + url.QueryEscape(\"actress\") + \"&site=\" + SITE_ADULT\n    u, err = srv.BuildRequestUrl()\n    if u != expected {\n        t.Fatalf(\"ProductService.BuildRequestUrl is expected to equal the expected value.\\nexpected:%s\\nactual:  %s\", expected, u)\n    }\n    if err != nil {\n        t.Fatalf(\"ProductService.BuildRequestUrl is not expected to have error\")\n    }\n    srv.SetArticle(\"\")\n\n    srv.SetArticleId(\"1011199\")\n    expected = expected_base + \"&article_id=\" + url.QueryEscape(\"1011199\") + \"&site=\" + SITE_ADULT\n    u, err = srv.BuildRequestUrl()\n    if u != expected {\n        t.Fatalf(\"ProductService.BuildRequestUrl is expected to equal the expected value.\\nexpected:%s\\nactual:  %s\", expected, u)\n    }\n    if err != nil {\n        t.Fatalf(\"ProductService.BuildRequestUrl is not expected to have error\")\n    }\n    srv.SetArticleId(\"\")\n\n    srv.SetStock(\"mono\")\n    expected = expected_base + \"&mono_stock=\" + url.QueryEscape(\"mono\") + \"&site=\" + SITE_ADULT\n    u, err = srv.BuildRequestUrl()\n    if u != expected {\n        t.Fatalf(\"ProductService.BuildRequestUrl is expected to equal the expected value.\\nexpected:%s\\nactual:  %s\", expected, u)\n    }\n    if err != nil {\n        t.Fatalf(\"ProductService.BuildRequestUrl is not expected to have error\")\n    }\n    srv.SetStock(\"\")\n}\n\nfunc TestBuildRequestUrlWithoutApiIdInInProductService(t *testing.T) {\n    srv := dummyProductService()\n    srv.ApiId = \"\"\n    u, err := srv.BuildRequestUrl()\n    if u != \"\" {\n        t.Fatalf(\"ProductService.BuildRequestUrl is expected empty if API ID is not set.\")\n    }\n    if err == nil {\n        t.Fatalf(\"ProductService.BuildRequestUrl is expected to return error.\")\n    }\n}\n\nfunc TestBuildRequestUrlWithWrongAffiliateIdInProductService(t *testing.T) {\n    srv := dummyProductService()\n    srv.AffiliateId = \"fizzbizz-100\"\n    u, err := srv.BuildRequestUrl()\n    if u != \"\" {\n        t.Fatalf(\"ProductService.BuildRequestUrl is expected empty if wrong Affiliate ID is set.\")\n    }\n    if err == nil {\n        t.Fatalf(\"ProductService.BuildRequestUrl is expected to return error.\")\n    }\n}\n\nfunc dummyProductService() *ProductService {\n    return NewProductService(Dummy_Affliate_Id, Dummy_Api_Id)\n}<|endoftext|>"}
{"text":"<commit_before>package filepathfilter\n\nimport (\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/git-lfs\/wildmatch\"\n)\n\ntype Pattern interface {\n\tMatch(filename string) bool\n\t\/\/ String returns a string representation (see: regular expressions) of\n\t\/\/ the underlying pattern used to match filenames against this Pattern.\n\tString() string\n}\n\ntype Filter struct {\n\tinclude []Pattern\n\texclude []Pattern\n}\n\nfunc NewFromPatterns(include, exclude []Pattern) *Filter {\n\treturn &Filter{include: include, exclude: exclude}\n}\n\nfunc New(include, exclude []string) *Filter {\n\treturn NewFromPatterns(\n\t\tconvertToWildmatch(include),\n\t\tconvertToWildmatch(exclude))\n}\n\n\/\/ Include returns the result of calling String() on each Pattern in the\n\/\/ include set of this *Filter.\nfunc (f *Filter) Include() []string { return wildmatchToString(f.include...) }\n\n\/\/ Exclude returns the result of calling String() on each Pattern in the\n\/\/ exclude set of this *Filter.\nfunc (f *Filter) Exclude() []string { return wildmatchToString(f.exclude...) }\n\n\/\/ wildmatchToString maps the given set of Pattern's to a string slice by\n\/\/ calling String() on each pattern.\nfunc wildmatchToString(ps ...Pattern) []string {\n\ts := make([]string, 0, len(ps))\n\tfor _, p := range ps {\n\t\ts = append(s, p.String())\n\t}\n\n\treturn s\n}\n\nfunc (f *Filter) Allows(filename string) bool {\n\tif f == nil {\n\t\treturn true\n\t}\n\n\tvar matched bool\n\tfor _, inc := range f.include {\n\t\tif matched = inc.Match(filename); matched {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !matched && len(f.include) > 0 {\n\t\treturn false\n\t}\n\n\tfor _, ex := range f.exclude {\n\t\tif ex.Match(filename) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\ntype wm struct {\n\tw    *wildmatch.Wildmatch\n\tdirs bool\n}\n\nfunc (w *wm) Match(filename string) bool {\n\treturn w.w.Match(w.chomp(filename))\n}\n\nfunc (w *wm) chomp(filename string) string {\n\treturn filepath.Clean(filename)\n}\n\nfunc (w *wm) String() string {\n\treturn w.w.String()\n}\n\nfunc NewPattern(p string) Pattern {\n\tp = filepath.Clean(p)\n\n\t\/\/ Special case: \"*\" and \"*.*\" should match everything to match existing\n\t\/\/ behavior.\n\tif p == \"*\" || p == \"*.*\" {\n\t\tp = \"**\/*\"\n\t}\n\n\tw := wildmatch.NewWildmatch(p, wildmatch.SystemCase)\n\tdirs := strings.Contains(w.String(), string(filepath.Separator))\n\n\treturn &wm{\n\t\tw:    w,\n\t\tdirs: dirs,\n\t}\n}\n\nfunc convertToWildmatch(rawpatterns []string) []Pattern {\n\tpatterns := make([]Pattern, len(rawpatterns))\n\tfor i, raw := range rawpatterns {\n\t\tpatterns[i] = NewPattern(raw)\n\t}\n\treturn patterns\n}\n<commit_msg>filepathfilter: rewrite existing wildcard patterns<commit_after>package filepathfilter\n\nimport (\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/git-lfs\/wildmatch\"\n)\n\ntype Pattern interface {\n\tMatch(filename string) bool\n\t\/\/ String returns a string representation (see: regular expressions) of\n\t\/\/ the underlying pattern used to match filenames against this Pattern.\n\tString() string\n}\n\ntype Filter struct {\n\tinclude []Pattern\n\texclude []Pattern\n}\n\nfunc NewFromPatterns(include, exclude []Pattern) *Filter {\n\treturn &Filter{include: include, exclude: exclude}\n}\n\nfunc New(include, exclude []string) *Filter {\n\treturn NewFromPatterns(\n\t\tconvertToWildmatch(include),\n\t\tconvertToWildmatch(exclude))\n}\n\n\/\/ Include returns the result of calling String() on each Pattern in the\n\/\/ include set of this *Filter.\nfunc (f *Filter) Include() []string { return wildmatchToString(f.include...) }\n\n\/\/ Exclude returns the result of calling String() on each Pattern in the\n\/\/ exclude set of this *Filter.\nfunc (f *Filter) Exclude() []string { return wildmatchToString(f.exclude...) }\n\n\/\/ wildmatchToString maps the given set of Pattern's to a string slice by\n\/\/ calling String() on each pattern.\nfunc wildmatchToString(ps ...Pattern) []string {\n\ts := make([]string, 0, len(ps))\n\tfor _, p := range ps {\n\t\ts = append(s, p.String())\n\t}\n\n\treturn s\n}\n\nfunc (f *Filter) Allows(filename string) bool {\n\tif f == nil {\n\t\treturn true\n\t}\n\n\tvar matched bool\n\tfor _, inc := range f.include {\n\t\tif matched = inc.Match(filename); matched {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !matched && len(f.include) > 0 {\n\t\treturn false\n\t}\n\n\tfor _, ex := range f.exclude {\n\t\tif ex.Match(filename) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\ntype wm struct {\n\tw    *wildmatch.Wildmatch\n\tdirs bool\n}\n\nfunc (w *wm) Match(filename string) bool {\n\treturn w.w.Match(w.chomp(filename))\n}\n\nfunc (w *wm) chomp(filename string) string {\n\treturn filepath.Clean(filename)\n}\n\nfunc (w *wm) String() string {\n\treturn w.w.String()\n}\n\nfunc NewPattern(p string) Pattern {\n\tp = filepath.Clean(p)\n\n\t\/\/ Special case: the below patterns match anything according to existing\n\t\/\/ behavior.\n\tswitch p {\n\tcase `*`, `*.*`, `.`, `.\/`, `.\\`:\n\t\tp = filepath.Join(\"**\", \"*\")\n\t}\n\n\tw := wildmatch.NewWildmatch(p, wildmatch.SystemCase)\n\tdirs := strings.Contains(w.String(), string(filepath.Separator))\n\n\treturn &wm{\n\t\tw:    w,\n\t\tdirs: dirs,\n\t}\n}\n\nfunc convertToWildmatch(rawpatterns []string) []Pattern {\n\tpatterns := make([]Pattern, len(rawpatterns))\n\tfor i, raw := range rawpatterns {\n\t\tpatterns[i] = NewPattern(raw)\n\t}\n\treturn patterns\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2017 by caixw, All rights reserved.\n\/\/ Use of this source code is governed by a MIT\n\/\/ license that can be found in the LICENSE file.\n\npackage client\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/caixw\/typing\/data\"\n\t\"github.com\/caixw\/typing\/vars\"\n\t\"github.com\/issue9\/logs\"\n\t\"github.com\/issue9\/middleware\/compress\"\n\t\"github.com\/issue9\/mux\"\n\t\"github.com\/issue9\/mux\/params\"\n\t\"github.com\/issue9\/utils\"\n)\n\nfunc (client *Client) initRoutes() error {\n\tvar err error\n\thandle := func(pattern string, h http.HandlerFunc) {\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tclient.patterns = append(client.patterns, pattern)\n\t\terr = client.mux.HandleFunc(pattern, client.prepare(h), http.MethodGet)\n\t}\n\n\thandle(vars.PostURL(\"{slug}\"), client.getPost)     \/\/ posts\/2016\/about.html   posts\/{slug}.html\n\thandle(vars.IndexURL(0), client.getPosts)          \/\/ index.html\n\thandle(vars.LinksURL(), client.getLinks)           \/\/ links.html\n\thandle(vars.TagURL(\"{slug}\", 1), client.getTag)    \/\/ tags\/tag1.html     tags\/{slug}.html\n\thandle(vars.TagsURL(), client.getTags)             \/\/ tags.html\n\thandle(vars.ArchivesURL(), client.getArchives)     \/\/ archives.html\n\thandle(vars.SearchURL(\"\", 1), client.getSearch)    \/\/ search.html\n\thandle(vars.ThemesURL(\"{path}\"), client.getThemes) \/\/ themes\/...          themes\/{path}\n\thandle(\"\/{path}\", client.getRaws)                  \/\/ \/...                \/{path}\n\n\treturn err\n}\n\n\/\/ 文章详细页\n\/\/ \/posts\/{slug}.html\nfunc (client *Client) getPost(w http.ResponseWriter, r *http.Request) {\n\tid, found := client.paramString(w, r, \"slug\")\n\tif !found {\n\t\treturn\n\t}\n\n\tvar index int\n\tfor i, p := range client.data.Posts {\n\t\tif p.Slug == id {\n\t\t\tindex = i\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif index < 0 {\n\t\tlogs.Debugf(\"并未找到与之相对应的文章:%s\", id)\n\t\tclient.getRaws(w, r) \/\/ 文章不存在，则查找 raws 目录下是否存在同名文件\n\t\treturn\n\t}\n\n\tpost := client.data.Posts[index]\n\n\tp := client.page(typePost)\n\tp.Post = post\n\tp.Keywords = post.Keywords\n\tp.Description = post.Summary\n\tp.Title = post.Title\n\tp.Canonical = post.Permalink\n\tp.License = post.License \/\/ 文章可具体指定协议\n\tp.Author = post.Author   \/\/ 文章可具体指定作者\n\n\tod := client.data.Config.Outdated\n\tnow := time.Now()\n\tif od != nil {\n\t\tvar outdated time.Duration\n\t\tif od.Type == data.OutdatedTypeCreated {\n\t\t\toutdated = now.Sub(post.Created)\n\t\t} else {\n\t\t\toutdated = now.Sub(post.Modified)\n\t\t}\n\t\tif outdated >= od.Duration {\n\t\t\t\/\/ Outdated 是一个动态的值（其中的天数会变化），必须是在请求时生成。\n\t\t\tpost.Outdated = fmt.Sprintf(od.Content, int64(outdated.Hours())\/24)\n\t\t}\n\t}\n\n\tif index > 0 {\n\t\tprev := client.data.Posts[index-1]\n\t\tp.prevPage(prev.Permalink, prev.Title)\n\t}\n\tif index+1 < len(client.data.Posts) {\n\t\tnext := client.data.Posts[index+1]\n\t\tp.nextPage(next.Permalink, next.Title)\n\t}\n\n\tp.render(w, post.Template, nil)\n}\n\n\/\/ 首页及文章列表页\n\/\/ \/\n\/\/ \/posts.html?page=2\nfunc (client *Client) getPosts(w http.ResponseWriter, r *http.Request) {\n\tpage, ok := client.queryInt(w, r, \"page\", 1)\n\tif !ok {\n\t\treturn\n\t}\n\n\tif page < 1 {\n\t\tlogs.Debugf(\"请求的页码[%d]小于1\\n\", page)\n\t\tclient.renderError(w, http.StatusNotFound) \/\/ 页码为负数的表示不存在，跳转到 404 页面\n\t\treturn\n\t}\n\n\tp := client.page(typeIndex)\n\tif page > 1 { \/\/ 非首页，标题显示页码数\n\t\tp.Type = typePosts\n\t\tp.Title = fmt.Sprintf(\"第 %d 页\", page)\n\t}\n\tp.Canonical = vars.PostsURL(page)\n\n\tstart, end, ok := client.getPostsRange(len(client.data.Posts), page, w)\n\tif !ok {\n\t\treturn\n\t}\n\tp.Posts = client.data.Posts[start:end]\n\tif page > 1 {\n\t\tp.prevPage(vars.PostsURL(page-1), \"\")\n\t}\n\tif end < len(client.data.Posts) {\n\t\tp.nextPage(vars.PostsURL(page+1), \"\")\n\t}\n\n\tp.render(w, \"posts\", nil)\n}\n\n\/\/ 标签详细页\n\/\/ \/tags\/tag1.html?page=2\nfunc (client *Client) getTag(w http.ResponseWriter, r *http.Request) {\n\tslug, ok := client.paramString(w, r, \"slug\")\n\tif !ok {\n\t\treturn\n\t}\n\n\tvar tag *data.Tag\n\tfor _, t := range client.data.Tags {\n\t\tif t.Slug == slug {\n\t\t\ttag = t\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif tag == nil {\n\t\tlogs.Debugf(\"查找的标签 %s 不存在\", slug)\n\t\tclient.getRaws(w, r) \/\/ 标签不存在，则查找该文件是否存在于 raws 目录下。\n\t\treturn\n\t}\n\n\tpage, ok := client.queryInt(w, r, \"page\", 1)\n\tif !ok {\n\t\treturn\n\t}\n\tif page < 1 {\n\t\tlogs.Debugf(\"请求的页码[%d]小于1\", page)\n\t\tclient.renderError(w, http.StatusNotFound) \/\/ 页码为负数的表示不存在，跳转到 404 页面\n\t\treturn\n\t}\n\n\tp := client.page(typeTag)\n\tp.Tag = tag\n\tp.Title = tag.Title\n\tp.Keywords = tag.Keywords\n\tp.Description = tag.Description\n\tp.Canonical = vars.TagURL(slug, page)\n\n\tstart, end, ok := client.getPostsRange(len(tag.Posts), page, w)\n\tif !ok {\n\t\treturn\n\t}\n\tp.Posts = tag.Posts[start:end]\n\tif page > 1 {\n\t\tp.prevPage(vars.TagURL(slug, page-1), \"\")\n\t}\n\tif end < len(tag.Posts) {\n\t\tp.nextPage(vars.TagURL(slug, page+1), \"\")\n\t}\n\n\tp.render(w, \"tag\", nil)\n}\n\n\/\/ 友情链接页\n\/\/ \/links.html\nfunc (client *Client) getLinks(w http.ResponseWriter, r *http.Request) {\n\tp := client.page(typeLinks)\n\tp.Title = \"友情链接\"\n\tp.Canonical = vars.LinksURL()\n\n\tp.render(w, \"links\", nil)\n}\n\n\/\/ 标签列表页\n\/\/ \/tags.html\nfunc (client *Client) getTags(w http.ResponseWriter, r *http.Request) {\n\tp := client.page(typeTags)\n\tp.Title = \"标签\"\n\tp.Canonical = vars.TagsURL()\n\tp.Description = \"标签列表\"\n\n\tp.render(w, \"tags\", nil)\n}\n\n\/\/ 归档页\n\/\/ \/archives.html\nfunc (client *Client) getArchives(w http.ResponseWriter, r *http.Request) {\n\tp := client.page(typeArchives)\n\tp.Title = \"归档\"\n\tp.Keywords = \"归档,存档,archive,archives\"\n\tp.Description = \"网站的归档列表，按时间进行排序\"\n\tp.Canonical = vars.ArchivesURL()\n\tp.Archives = client.data.Archives\n\n\tp.render(w, \"archives\", nil)\n}\n\n\/\/ 主题文件\n\/\/ \/themes\/...\nfunc (client *Client) getThemes(w http.ResponseWriter, r *http.Request) {\n\tif isIgnoreThemeFile(r.URL.Path) { \/\/ 不展示模板文件\n\t\tclient.renderError(w, http.StatusNotFound)\n\t\treturn\n\t}\n\n\tpath := strings.TrimPrefix(r.URL.Path, vars.ThemesURL(\"\"))\n\n\tif len(path) < len(r.URL.Path) {\n\t\tfilename := filepath.Join(client.path.ThemesDir, path)\n\n\t\tif !utils.FileExists(filename) {\n\t\t\tclient.renderError(w, http.StatusNotFound)\n\t\t\treturn\n\t\t}\n\n\t\tstat, err := os.Stat(filename)\n\t\tif err != nil {\n\t\t\tlogs.Error(err)\n\t\t\tclient.renderError(w, http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tif stat.IsDir() {\n\t\t\tclient.renderError(w, http.StatusForbidden)\n\t\t\treturn\n\t\t}\n\n\t\thttp.ServeFile(w, r, filename)\n\t\treturn\n\t}\n\n\tclient.renderError(w, http.StatusNotFound)\n}\n\n\/\/ \/search.html?q=key&page=2\nfunc (client *Client) getSearch(w http.ResponseWriter, r *http.Request) {\n\tp := client.page(typeSearch)\n\n\tq := r.FormValue(\"q\")\n\tif len(q) == 0 {\n\t\thttp.Redirect(w, r, vars.PostsURL(1), http.StatusPermanentRedirect)\n\t\treturn\n\t}\n\n\tpage, ok := client.queryInt(w, r, \"page\", 1)\n\tif !ok {\n\t\treturn\n\t}\n\tif page < 1 {\n\t\tlogs.Debugf(\"参数 page: %d 小于 1\", page)\n\t\tclient.renderError(w, http.StatusNotFound) \/\/ 页码为负数的表示不存在，跳转到 404 页面\n\t\treturn\n\t}\n\n\t\/\/ 查找标题和内容\n\tposts := make([]*data.Post, 0, len(client.data.Posts))\n\tkey := strings.ToLower(q)\n\tfor _, v := range client.data.Posts {\n\t\tif strings.Contains(v.Title, key) || strings.Contains(v.Content, key) {\n\t\t\tposts = append(posts, v)\n\t\t}\n\t}\n\n\tp.Title = \"搜索:\" + q\n\tp.Q = q\n\tp.Keywords = q + \",搜索,search\"\n\tp.Description = \"搜索关键字\" + q + \"的结果\"\n\tp.Canonical = vars.SearchURL(p.Q, page)\n\tstart, end, ok := client.getPostsRange(len(posts), page, w)\n\tif !ok {\n\t\treturn\n\t}\n\tp.Posts = posts[start:end]\n\tif page > 1 {\n\t\tp.prevPage(vars.SearchURL(q, page-1), \"\")\n\t}\n\tif end < len(posts) {\n\t\tp.nextPage(vars.SearchURL(q, page+1), \"\")\n\t}\n\n\tp.render(w, \"search\", nil)\n}\n\n\/\/ 读取根下的文件\n\/\/ \/...\nfunc (client *Client) getRaws(w http.ResponseWriter, r *http.Request) {\n\tif r.URL.Path == \"\/\" {\n\t\tclient.getPosts(w, r)\n\t\treturn\n\t}\n\n\tif !utils.FileExists(filepath.Join(client.path.RawsDir, r.URL.Path)) {\n\t\tclient.renderError(w, http.StatusNotFound)\n\t\treturn\n\t}\n\n\tprefix := \"\/\"\n\troot := http.Dir(client.path.RawsDir)\n\thttp.StripPrefix(prefix, http.FileServer(root)).ServeHTTP(w, r)\n}\n\n\/\/ 确认当前文章列表页选择范围。\nfunc (client *Client) getPostsRange(postsSize, page int, w http.ResponseWriter) (start, end int, ok bool) {\n\tsize := client.data.Config.PageSize\n\tstart = size * (page - 1) \/\/ 系统从零开始计数\n\tif start > postsSize {\n\t\tlogs.Debugf(\"请求页码为[%d]，实际文章数量为[%d]\\n\", page, postsSize)\n\t\tclient.renderError(w, http.StatusNotFound) \/\/ 页码超出范围，不存在\n\t\treturn 0, 0, false\n\t}\n\n\tend = start + size\n\tif postsSize < end {\n\t\tend = postsSize\n\t}\n\n\treturn start, end, true\n}\n\n\/\/ 每次访问前需要做的预处理工作。\nfunc (client *Client) prepare(f http.HandlerFunc) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tlogs.Infof(\"%s: %s\", r.UserAgent(), r.URL) \/\/ 输出访问日志\n\n\t\t\/\/ 直接根据整个博客的最后更新时间来确认 etag\n\t\tif r.Header.Get(\"If-None-Match\") == client.etag {\n\t\t\tlogs.Infof(\"304: %s\", r.URL)\n\t\t\tw.WriteHeader(http.StatusNotModified)\n\t\t\treturn\n\t\t}\n\t\tw.Header().Set(\"Etag\", client.etag)\n\t\tw.Header().Set(\"Content-Language\", client.data.Config.Language)\n\t\tcompress.New(f, logs.ERROR()).ServeHTTP(w, r)\n\t}\n}\n\n\/\/ 获取路径匹配中的参数，并以字符串的格式返回。\n\/\/ 若不能找到该参数，返回 false\nfunc (client *Client) paramString(w http.ResponseWriter, r *http.Request, key string) (string, bool) {\n\tps := mux.Params(r)\n\tval, err := ps.String(key)\n\n\tif err == params.ErrParamNotExists {\n\t\tclient.renderError(w, http.StatusNotFound)\n\t\treturn \"\", false\n\t} else if err != nil {\n\t\tlogs.Error(err)\n\t\tclient.renderError(w, http.StatusNotFound)\n\t\treturn \"\", false\n\t} else if len(val) == 0 {\n\t\tclient.renderError(w, http.StatusNotFound)\n\t\treturn \"\", false\n\t}\n\n\treturn val, true\n}\n\n\/\/ 获取查询参数 key 的值，并将其转换成 Int 类型，若该值不存在返回 def 作为其默认值，\n\/\/ 若是类型不正确，则返回一个 false，并向客户端输出一个 400 错误。\nfunc (client *Client) queryInt(w http.ResponseWriter, r *http.Request, key string, def int) (int, bool) {\n\tval := r.FormValue(key)\n\tif len(val) == 0 {\n\t\treturn def, true\n\t}\n\n\tret, err := strconv.Atoi(val)\n\tif err != nil {\n\t\tlogs.Error(err)\n\t\tclient.renderError(w, http.StatusBadRequest)\n\t\treturn 0, false\n\t}\n\treturn ret, true\n}\n<commit_msg>调整 outdated 的计算<commit_after>\/\/ Copyright 2017 by caixw, All rights reserved.\n\/\/ Use of this source code is governed by a MIT\n\/\/ license that can be found in the LICENSE file.\n\npackage client\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/caixw\/typing\/data\"\n\t\"github.com\/caixw\/typing\/vars\"\n\t\"github.com\/issue9\/logs\"\n\t\"github.com\/issue9\/middleware\/compress\"\n\t\"github.com\/issue9\/mux\"\n\t\"github.com\/issue9\/mux\/params\"\n\t\"github.com\/issue9\/utils\"\n)\n\nfunc (client *Client) initRoutes() error {\n\tvar err error\n\thandle := func(pattern string, h http.HandlerFunc) {\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tclient.patterns = append(client.patterns, pattern)\n\t\terr = client.mux.HandleFunc(pattern, client.prepare(h), http.MethodGet)\n\t}\n\n\thandle(vars.PostURL(\"{slug}\"), client.getPost)     \/\/ posts\/2016\/about.html   posts\/{slug}.html\n\thandle(vars.IndexURL(0), client.getPosts)          \/\/ index.html\n\thandle(vars.LinksURL(), client.getLinks)           \/\/ links.html\n\thandle(vars.TagURL(\"{slug}\", 1), client.getTag)    \/\/ tags\/tag1.html     tags\/{slug}.html\n\thandle(vars.TagsURL(), client.getTags)             \/\/ tags.html\n\thandle(vars.ArchivesURL(), client.getArchives)     \/\/ archives.html\n\thandle(vars.SearchURL(\"\", 1), client.getSearch)    \/\/ search.html\n\thandle(vars.ThemesURL(\"{path}\"), client.getThemes) \/\/ themes\/...          themes\/{path}\n\thandle(\"\/{path}\", client.getRaws)                  \/\/ \/...                \/{path}\n\n\treturn err\n}\n\n\/\/ 文章详细页\n\/\/ \/posts\/{slug}.html\nfunc (client *Client) getPost(w http.ResponseWriter, r *http.Request) {\n\tid, found := client.paramString(w, r, \"slug\")\n\tif !found {\n\t\treturn\n\t}\n\n\tvar index int\n\tfor i, p := range client.data.Posts {\n\t\tif p.Slug == id {\n\t\t\tindex = i\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif index < 0 {\n\t\tlogs.Debugf(\"并未找到与之相对应的文章:%s\", id)\n\t\tclient.getRaws(w, r) \/\/ 文章不存在，则查找 raws 目录下是否存在同名文件\n\t\treturn\n\t}\n\n\tpost := client.data.Posts[index]\n\tp := client.page(typePost)\n\n\tp.Post = post\n\tp.Keywords = post.Keywords\n\tp.Description = post.Summary\n\tp.Title = post.Title\n\tp.Canonical = post.Permalink\n\tp.License = post.License \/\/ 文章可具体指定协议\n\tp.Author = post.Author   \/\/ 文章可具体指定作者\n\n\t\/\/ Outdated 是一个动态的值（其中的天数会变化），必须是在请求时生成。\n\tod := client.data.Config.Outdated\n\tif od != nil {\n\t\tnow := time.Now()\n\t\tvar outdated time.Duration\n\n\t\tif od.Type == data.OutdatedTypeCreated {\n\t\t\toutdated = now.Sub(post.Created)\n\t\t} else {\n\t\t\toutdated = now.Sub(post.Modified)\n\t\t}\n\t\tif outdated >= od.Duration {\n\t\t\tpost.Outdated = fmt.Sprintf(od.Content, int64(outdated.Hours())\/24)\n\t\t}\n\t}\n\n\tif index > 0 {\n\t\tprev := client.data.Posts[index-1]\n\t\tp.prevPage(prev.Permalink, prev.Title)\n\t}\n\tif index+1 < len(client.data.Posts) {\n\t\tnext := client.data.Posts[index+1]\n\t\tp.nextPage(next.Permalink, next.Title)\n\t}\n\n\tp.render(w, post.Template, nil)\n}\n\n\/\/ 首页及文章列表页\n\/\/ \/\n\/\/ \/posts.html?page=2\nfunc (client *Client) getPosts(w http.ResponseWriter, r *http.Request) {\n\tpage, ok := client.queryInt(w, r, \"page\", 1)\n\tif !ok {\n\t\treturn\n\t}\n\n\tif page < 1 {\n\t\tlogs.Debugf(\"请求的页码[%d]小于1\\n\", page)\n\t\tclient.renderError(w, http.StatusNotFound) \/\/ 页码为负数的表示不存在，跳转到 404 页面\n\t\treturn\n\t}\n\n\tp := client.page(typeIndex)\n\tif page > 1 { \/\/ 非首页，标题显示页码数\n\t\tp.Type = typePosts\n\t\tp.Title = fmt.Sprintf(\"第 %d 页\", page)\n\t}\n\tp.Canonical = vars.PostsURL(page)\n\n\tstart, end, ok := client.getPostsRange(len(client.data.Posts), page, w)\n\tif !ok {\n\t\treturn\n\t}\n\tp.Posts = client.data.Posts[start:end]\n\tif page > 1 {\n\t\tp.prevPage(vars.PostsURL(page-1), \"\")\n\t}\n\tif end < len(client.data.Posts) {\n\t\tp.nextPage(vars.PostsURL(page+1), \"\")\n\t}\n\n\tp.render(w, \"posts\", nil)\n}\n\n\/\/ 标签详细页\n\/\/ \/tags\/tag1.html?page=2\nfunc (client *Client) getTag(w http.ResponseWriter, r *http.Request) {\n\tslug, ok := client.paramString(w, r, \"slug\")\n\tif !ok {\n\t\treturn\n\t}\n\n\tvar tag *data.Tag\n\tfor _, t := range client.data.Tags {\n\t\tif t.Slug == slug {\n\t\t\ttag = t\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif tag == nil {\n\t\tlogs.Debugf(\"查找的标签 %s 不存在\", slug)\n\t\tclient.getRaws(w, r) \/\/ 标签不存在，则查找该文件是否存在于 raws 目录下。\n\t\treturn\n\t}\n\n\tpage, ok := client.queryInt(w, r, \"page\", 1)\n\tif !ok {\n\t\treturn\n\t}\n\tif page < 1 {\n\t\tlogs.Debugf(\"请求的页码[%d]小于1\", page)\n\t\tclient.renderError(w, http.StatusNotFound) \/\/ 页码为负数的表示不存在，跳转到 404 页面\n\t\treturn\n\t}\n\n\tp := client.page(typeTag)\n\tp.Tag = tag\n\tp.Title = tag.Title\n\tp.Keywords = tag.Keywords\n\tp.Description = tag.Description\n\tp.Canonical = vars.TagURL(slug, page)\n\n\tstart, end, ok := client.getPostsRange(len(tag.Posts), page, w)\n\tif !ok {\n\t\treturn\n\t}\n\tp.Posts = tag.Posts[start:end]\n\tif page > 1 {\n\t\tp.prevPage(vars.TagURL(slug, page-1), \"\")\n\t}\n\tif end < len(tag.Posts) {\n\t\tp.nextPage(vars.TagURL(slug, page+1), \"\")\n\t}\n\n\tp.render(w, \"tag\", nil)\n}\n\n\/\/ 友情链接页\n\/\/ \/links.html\nfunc (client *Client) getLinks(w http.ResponseWriter, r *http.Request) {\n\tp := client.page(typeLinks)\n\tp.Title = \"友情链接\"\n\tp.Canonical = vars.LinksURL()\n\n\tp.render(w, \"links\", nil)\n}\n\n\/\/ 标签列表页\n\/\/ \/tags.html\nfunc (client *Client) getTags(w http.ResponseWriter, r *http.Request) {\n\tp := client.page(typeTags)\n\tp.Title = \"标签\"\n\tp.Canonical = vars.TagsURL()\n\tp.Description = \"标签列表\"\n\n\tp.render(w, \"tags\", nil)\n}\n\n\/\/ 归档页\n\/\/ \/archives.html\nfunc (client *Client) getArchives(w http.ResponseWriter, r *http.Request) {\n\tp := client.page(typeArchives)\n\tp.Title = \"归档\"\n\tp.Keywords = \"归档,存档,archive,archives\"\n\tp.Description = \"网站的归档列表，按时间进行排序\"\n\tp.Canonical = vars.ArchivesURL()\n\tp.Archives = client.data.Archives\n\n\tp.render(w, \"archives\", nil)\n}\n\n\/\/ 主题文件\n\/\/ \/themes\/...\nfunc (client *Client) getThemes(w http.ResponseWriter, r *http.Request) {\n\tif isIgnoreThemeFile(r.URL.Path) { \/\/ 不展示模板文件\n\t\tclient.renderError(w, http.StatusNotFound)\n\t\treturn\n\t}\n\n\tpath := strings.TrimPrefix(r.URL.Path, vars.ThemesURL(\"\"))\n\n\tif len(path) < len(r.URL.Path) {\n\t\tfilename := filepath.Join(client.path.ThemesDir, path)\n\n\t\tif !utils.FileExists(filename) {\n\t\t\tclient.renderError(w, http.StatusNotFound)\n\t\t\treturn\n\t\t}\n\n\t\tstat, err := os.Stat(filename)\n\t\tif err != nil {\n\t\t\tlogs.Error(err)\n\t\t\tclient.renderError(w, http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\n\t\tif stat.IsDir() {\n\t\t\tclient.renderError(w, http.StatusForbidden)\n\t\t\treturn\n\t\t}\n\n\t\thttp.ServeFile(w, r, filename)\n\t\treturn\n\t}\n\n\tclient.renderError(w, http.StatusNotFound)\n}\n\n\/\/ \/search.html?q=key&page=2\nfunc (client *Client) getSearch(w http.ResponseWriter, r *http.Request) {\n\tp := client.page(typeSearch)\n\n\tq := r.FormValue(\"q\")\n\tif len(q) == 0 {\n\t\thttp.Redirect(w, r, vars.PostsURL(1), http.StatusPermanentRedirect)\n\t\treturn\n\t}\n\n\tpage, ok := client.queryInt(w, r, \"page\", 1)\n\tif !ok {\n\t\treturn\n\t}\n\tif page < 1 {\n\t\tlogs.Debugf(\"参数 page: %d 小于 1\", page)\n\t\tclient.renderError(w, http.StatusNotFound) \/\/ 页码为负数的表示不存在，跳转到 404 页面\n\t\treturn\n\t}\n\n\t\/\/ 查找标题和内容\n\tposts := make([]*data.Post, 0, len(client.data.Posts))\n\tkey := strings.ToLower(q)\n\tfor _, v := range client.data.Posts {\n\t\tif strings.Contains(v.Title, key) || strings.Contains(v.Content, key) {\n\t\t\tposts = append(posts, v)\n\t\t}\n\t}\n\n\tp.Title = \"搜索:\" + q\n\tp.Q = q\n\tp.Keywords = q + \",搜索,search\"\n\tp.Description = \"搜索关键字\" + q + \"的结果\"\n\tp.Canonical = vars.SearchURL(p.Q, page)\n\tstart, end, ok := client.getPostsRange(len(posts), page, w)\n\tif !ok {\n\t\treturn\n\t}\n\tp.Posts = posts[start:end]\n\tif page > 1 {\n\t\tp.prevPage(vars.SearchURL(q, page-1), \"\")\n\t}\n\tif end < len(posts) {\n\t\tp.nextPage(vars.SearchURL(q, page+1), \"\")\n\t}\n\n\tp.render(w, \"search\", nil)\n}\n\n\/\/ 读取根下的文件\n\/\/ \/...\nfunc (client *Client) getRaws(w http.ResponseWriter, r *http.Request) {\n\tif r.URL.Path == \"\/\" {\n\t\tclient.getPosts(w, r)\n\t\treturn\n\t}\n\n\tif !utils.FileExists(filepath.Join(client.path.RawsDir, r.URL.Path)) {\n\t\tclient.renderError(w, http.StatusNotFound)\n\t\treturn\n\t}\n\n\tprefix := \"\/\"\n\troot := http.Dir(client.path.RawsDir)\n\thttp.StripPrefix(prefix, http.FileServer(root)).ServeHTTP(w, r)\n}\n\n\/\/ 确认当前文章列表页选择范围。\nfunc (client *Client) getPostsRange(postsSize, page int, w http.ResponseWriter) (start, end int, ok bool) {\n\tsize := client.data.Config.PageSize\n\tstart = size * (page - 1) \/\/ 系统从零开始计数\n\tif start > postsSize {\n\t\tlogs.Debugf(\"请求页码为[%d]，实际文章数量为[%d]\\n\", page, postsSize)\n\t\tclient.renderError(w, http.StatusNotFound) \/\/ 页码超出范围，不存在\n\t\treturn 0, 0, false\n\t}\n\n\tend = start + size\n\tif postsSize < end {\n\t\tend = postsSize\n\t}\n\n\treturn start, end, true\n}\n\n\/\/ 每次访问前需要做的预处理工作。\nfunc (client *Client) prepare(f http.HandlerFunc) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tlogs.Infof(\"%s: %s\", r.UserAgent(), r.URL) \/\/ 输出访问日志\n\n\t\t\/\/ 直接根据整个博客的最后更新时间来确认 etag\n\t\tif r.Header.Get(\"If-None-Match\") == client.etag {\n\t\t\tlogs.Infof(\"304: %s\", r.URL)\n\t\t\tw.WriteHeader(http.StatusNotModified)\n\t\t\treturn\n\t\t}\n\t\tw.Header().Set(\"Etag\", client.etag)\n\t\tw.Header().Set(\"Content-Language\", client.data.Config.Language)\n\t\tcompress.New(f, logs.ERROR()).ServeHTTP(w, r)\n\t}\n}\n\n\/\/ 获取路径匹配中的参数，并以字符串的格式返回。\n\/\/ 若不能找到该参数，返回 false\nfunc (client *Client) paramString(w http.ResponseWriter, r *http.Request, key string) (string, bool) {\n\tps := mux.Params(r)\n\tval, err := ps.String(key)\n\n\tif err == params.ErrParamNotExists {\n\t\tclient.renderError(w, http.StatusNotFound)\n\t\treturn \"\", false\n\t} else if err != nil {\n\t\tlogs.Error(err)\n\t\tclient.renderError(w, http.StatusNotFound)\n\t\treturn \"\", false\n\t} else if len(val) == 0 {\n\t\tclient.renderError(w, http.StatusNotFound)\n\t\treturn \"\", false\n\t}\n\n\treturn val, true\n}\n\n\/\/ 获取查询参数 key 的值，并将其转换成 Int 类型，若该值不存在返回 def 作为其默认值，\n\/\/ 若是类型不正确，则返回一个 false，并向客户端输出一个 400 错误。\nfunc (client *Client) queryInt(w http.ResponseWriter, r *http.Request, key string, def int) (int, bool) {\n\tval := r.FormValue(key)\n\tif len(val) == 0 {\n\t\treturn def, true\n\t}\n\n\tret, err := strconv.Atoi(val)\n\tif err != nil {\n\t\tlogs.Error(err)\n\t\tclient.renderError(w, http.StatusBadRequest)\n\t\treturn 0, false\n\t}\n\treturn ret, true\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2012 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ +build darwin freebsd linux netbsd openbsd\n\npackage test\n\n\/\/ functional test harness for unix.\n\nimport (\n\t\"bytes\"\n\t\"crypto\"\n\t\"crypto\/dsa\"\n\t\"crypto\/rsa\"\n\t\"crypto\/x509\"\n\t\"encoding\/pem\"\n\t\"errors\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"os\/user\"\n\t\"path\/filepath\"\n\t\"testing\"\n\t\"text\/template\"\n\t\"time\"\n\n\t\"code.google.com\/p\/go.crypto\/ssh\"\n)\n\nconst sshd_config = `\nProtocol 2\nHostKey {{.Dir}}\/ssh_host_rsa_key\nHostKey {{.Dir}}\/ssh_host_dsa_key\nHostKey {{.Dir}}\/ssh_host_ecdsa_key\nPidfile {{.Dir}}\/sshd.pid\n#UsePrivilegeSeparation no\nKeyRegenerationInterval 3600\nServerKeyBits 768\nSyslogFacility AUTH\nLogLevel DEBUG2\nLoginGraceTime 120\nPermitRootLogin no\nStrictModes no\nRSAAuthentication yes\nPubkeyAuthentication yes\nAuthorizedKeysFile\t{{.Dir}}\/authorized_keys\nIgnoreRhosts yes\nRhostsRSAAuthentication no\nHostbasedAuthentication no\n`\n\nvar (\n\tconfigTmpl template.Template\n\tsshd       string \/\/ path to sshd\n\trsakey     *rsa.PrivateKey\n)\n\nfunc init() {\n\ttemplate.Must(configTmpl.Parse(sshd_config))\n\tblock, _ := pem.Decode([]byte(testClientPrivateKey))\n\trsakey, _ = x509.ParsePKCS1PrivateKey(block.Bytes)\n}\n\ntype server struct {\n\tt          *testing.T\n\tcleanup    func() \/\/ executed during Shutdown\n\tconfigfile string\n\tcmd        *exec.Cmd\n\toutput     bytes.Buffer \/\/ holds stderr from sshd process\n}\n\nfunc username() string {\n\tvar username string\n\tif user, err := user.Current(); err == nil {\n\t\tusername = user.Username\n\t} else {\n\t\t\/\/ user.Current() currently requires cgo. If an error is\n\t\t\/\/ returned attempt to get the username from the environment.\n\t\tusername = os.Getenv(\"USER\")\n\t}\n\tif username == \"\" {\n\t\tpanic(\"Unable to get username\")\n\t}\n\treturn username\n}\n\nfunc clientConfig() *ssh.ClientConfig {\n\tkc := new(keychain)\n\tkc.keys = append(kc.keys, rsakey)\n\tconfig := &ssh.ClientConfig{\n\t\tUser: username(),\n\t\tAuth: []ssh.ClientAuth{\n\t\t\tssh.ClientAuthKeyring(kc),\n\t\t},\n\t}\n\treturn config\n}\n\nfunc (s *server) Dial(config *ssh.ClientConfig) *ssh.ClientConn {\n\ts.cmd = exec.Command(\"sshd\", \"-f\", s.configfile, \"-i\")\n\tstdin, err := s.cmd.StdinPipe()\n\tif err != nil {\n\t\ts.t.Fatal(err)\n\t}\n\tstdout, err := s.cmd.StdoutPipe()\n\tif err != nil {\n\t\ts.t.Fatal(err)\n\t}\n\ts.cmd.Stderr = os.Stderr \/\/ &s.output\n\terr = s.cmd.Start()\n\tif err != nil {\n\t\ts.t.FailNow()\n\t\ts.Shutdown()\n\t\ts.t.Fatal(err)\n\t}\n\tconn, err := ssh.Client(&client{stdin, stdout}, config)\n\tif err != nil {\n\t\ts.t.FailNow()\n\t\ts.Shutdown()\n\t\ts.t.Fatal(err)\n\t}\n\treturn conn\n}\n\nfunc (s *server) Shutdown() {\n\tif s.cmd.Process != nil {\n\t\tif err := s.cmd.Process.Kill(); err != nil {\n\t\t\ts.t.Error(err)\n\t\t}\n\t\ts.cmd.Wait()\n\t}\n\tif s.t.Failed() {\n\t\t\/\/ log any output from sshd process\n\t\ts.t.Log(s.output.String())\n\t}\n\ts.cleanup()\n}\n\n\/\/ client wraps a pair of Reader\/WriteClosers to implement the\n\/\/ net.Conn interface.\ntype client struct {\n\tio.WriteCloser\n\tio.Reader\n}\n\nfunc (c *client) LocalAddr() net.Addr              { return nil }\nfunc (c *client) RemoteAddr() net.Addr             { return nil }\nfunc (c *client) SetDeadline(time.Time) error      { return nil }\nfunc (c *client) SetReadDeadline(time.Time) error  { return nil }\nfunc (c *client) SetWriteDeadline(time.Time) error { return nil }\n\n\/\/ newServer returns a new mock ssh server.\nfunc newServer(t *testing.T) *server {\n\tdir, err := ioutil.TempDir(\"\", \"sshtest\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tf, err := os.Create(filepath.Join(dir, \"sshd_config\"))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = configTmpl.Execute(f, map[string]string{\n\t\t\"Dir\": dir,\n\t})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tf.Close()\n\n\tfor k, v := range keys {\n\t\tf, err := os.OpenFile(filepath.Join(dir, k), os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0600)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tif _, err := f.Write([]byte(v)); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tf.Close()\n\t}\n\n\treturn &server{\n\t\tt:          t,\n\t\tconfigfile: f.Name(),\n\t\tcleanup: func() {\n\t\t\tif err := os.RemoveAll(dir); err != nil {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\t\t},\n\t}\n}\n\n\/\/ keychain implements the ClientKeyring interface\ntype keychain struct {\n\tkeys []interface{}\n}\n\nfunc (k *keychain) Key(i int) (interface{}, error) {\n\tif i < 0 || i >= len(k.keys) {\n\t\treturn nil, nil\n\t}\n\tswitch key := k.keys[i].(type) {\n\tcase *rsa.PrivateKey:\n\t\treturn &key.PublicKey, nil\n\tcase *dsa.PrivateKey:\n\t\treturn &key.PublicKey, nil\n\t}\n\tpanic(\"unknown key type\")\n}\n\nfunc (k *keychain) Sign(i int, rand io.Reader, data []byte) (sig []byte, err error) {\n\thashFunc := crypto.SHA1\n\th := hashFunc.New()\n\th.Write(data)\n\tdigest := h.Sum(nil)\n\tswitch key := k.keys[i].(type) {\n\tcase *rsa.PrivateKey:\n\t\treturn rsa.SignPKCS1v15(rand, key, hashFunc, digest)\n\t}\n\treturn nil, errors.New(\"ssh: unknown key type\")\n}\n\nfunc (k *keychain) loadPEM(file string) error {\n\tbuf, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\tblock, _ := pem.Decode(buf)\n\tif block == nil {\n\t\treturn errors.New(\"ssh: no key found\")\n\t}\n\tr, err := x509.ParsePKCS1PrivateKey(block.Bytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\tk.keys = append(k.keys, r)\n\treturn nil\n}\n<commit_msg>go.crypto\/ssh\/test: improve diagnostics for test failing to get username.<commit_after>\/\/ Copyright 2012 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ +build darwin freebsd linux netbsd openbsd\n\npackage test\n\n\/\/ functional test harness for unix.\n\nimport (\n\t\"bytes\"\n\t\"crypto\"\n\t\"crypto\/dsa\"\n\t\"crypto\/rsa\"\n\t\"crypto\/x509\"\n\t\"encoding\/pem\"\n\t\"errors\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"os\/user\"\n\t\"path\/filepath\"\n\t\"testing\"\n\t\"text\/template\"\n\t\"time\"\n\n\t\"code.google.com\/p\/go.crypto\/ssh\"\n)\n\nconst sshd_config = `\nProtocol 2\nHostKey {{.Dir}}\/ssh_host_rsa_key\nHostKey {{.Dir}}\/ssh_host_dsa_key\nHostKey {{.Dir}}\/ssh_host_ecdsa_key\nPidfile {{.Dir}}\/sshd.pid\n#UsePrivilegeSeparation no\nKeyRegenerationInterval 3600\nServerKeyBits 768\nSyslogFacility AUTH\nLogLevel DEBUG2\nLoginGraceTime 120\nPermitRootLogin no\nStrictModes no\nRSAAuthentication yes\nPubkeyAuthentication yes\nAuthorizedKeysFile\t{{.Dir}}\/authorized_keys\nIgnoreRhosts yes\nRhostsRSAAuthentication no\nHostbasedAuthentication no\n`\n\nvar (\n\tconfigTmpl template.Template\n\tsshd       string \/\/ path to sshd\n\trsakey     *rsa.PrivateKey\n)\n\nfunc init() {\n\ttemplate.Must(configTmpl.Parse(sshd_config))\n\tblock, _ := pem.Decode([]byte(testClientPrivateKey))\n\trsakey, _ = x509.ParsePKCS1PrivateKey(block.Bytes)\n}\n\ntype server struct {\n\tt          *testing.T\n\tcleanup    func() \/\/ executed during Shutdown\n\tconfigfile string\n\tcmd        *exec.Cmd\n\toutput     bytes.Buffer \/\/ holds stderr from sshd process\n}\n\nfunc username() string {\n\tvar username string\n\tif user, err := user.Current(); err == nil {\n\t\tusername = user.Username\n\t} else {\n\t\t\/\/ user.Current() currently requires cgo. If an error is\n\t\t\/\/ returned attempt to get the username from the environment.\n\t\tlog.Printf(\"user.Current: %v; falling back on $USER\", err)\n\t\tusername = os.Getenv(\"USER\")\n\t}\n\tif username == \"\" {\n\t\tpanic(\"Unable to get username\")\n\t}\n\treturn username\n}\n\nfunc clientConfig() *ssh.ClientConfig {\n\tkc := new(keychain)\n\tkc.keys = append(kc.keys, rsakey)\n\tconfig := &ssh.ClientConfig{\n\t\tUser: username(),\n\t\tAuth: []ssh.ClientAuth{\n\t\t\tssh.ClientAuthKeyring(kc),\n\t\t},\n\t}\n\treturn config\n}\n\nfunc (s *server) Dial(config *ssh.ClientConfig) *ssh.ClientConn {\n\ts.cmd = exec.Command(\"sshd\", \"-f\", s.configfile, \"-i\")\n\tstdin, err := s.cmd.StdinPipe()\n\tif err != nil {\n\t\ts.t.Fatal(err)\n\t}\n\tstdout, err := s.cmd.StdoutPipe()\n\tif err != nil {\n\t\ts.t.Fatal(err)\n\t}\n\ts.cmd.Stderr = os.Stderr \/\/ &s.output\n\terr = s.cmd.Start()\n\tif err != nil {\n\t\ts.t.FailNow()\n\t\ts.Shutdown()\n\t\ts.t.Fatal(err)\n\t}\n\tconn, err := ssh.Client(&client{stdin, stdout}, config)\n\tif err != nil {\n\t\ts.t.FailNow()\n\t\ts.Shutdown()\n\t\ts.t.Fatal(err)\n\t}\n\treturn conn\n}\n\nfunc (s *server) Shutdown() {\n\tif s.cmd.Process != nil {\n\t\tif err := s.cmd.Process.Kill(); err != nil {\n\t\t\ts.t.Error(err)\n\t\t}\n\t\ts.cmd.Wait()\n\t}\n\tif s.t.Failed() {\n\t\t\/\/ log any output from sshd process\n\t\ts.t.Log(s.output.String())\n\t}\n\ts.cleanup()\n}\n\n\/\/ client wraps a pair of Reader\/WriteClosers to implement the\n\/\/ net.Conn interface.\ntype client struct {\n\tio.WriteCloser\n\tio.Reader\n}\n\nfunc (c *client) LocalAddr() net.Addr              { return nil }\nfunc (c *client) RemoteAddr() net.Addr             { return nil }\nfunc (c *client) SetDeadline(time.Time) error      { return nil }\nfunc (c *client) SetReadDeadline(time.Time) error  { return nil }\nfunc (c *client) SetWriteDeadline(time.Time) error { return nil }\n\n\/\/ newServer returns a new mock ssh server.\nfunc newServer(t *testing.T) *server {\n\tdir, err := ioutil.TempDir(\"\", \"sshtest\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tf, err := os.Create(filepath.Join(dir, \"sshd_config\"))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr = configTmpl.Execute(f, map[string]string{\n\t\t\"Dir\": dir,\n\t})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tf.Close()\n\n\tfor k, v := range keys {\n\t\tf, err := os.OpenFile(filepath.Join(dir, k), os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0600)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tif _, err := f.Write([]byte(v)); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tf.Close()\n\t}\n\n\treturn &server{\n\t\tt:          t,\n\t\tconfigfile: f.Name(),\n\t\tcleanup: func() {\n\t\t\tif err := os.RemoveAll(dir); err != nil {\n\t\t\t\tt.Error(err)\n\t\t\t}\n\t\t},\n\t}\n}\n\n\/\/ keychain implements the ClientKeyring interface\ntype keychain struct {\n\tkeys []interface{}\n}\n\nfunc (k *keychain) Key(i int) (interface{}, error) {\n\tif i < 0 || i >= len(k.keys) {\n\t\treturn nil, nil\n\t}\n\tswitch key := k.keys[i].(type) {\n\tcase *rsa.PrivateKey:\n\t\treturn &key.PublicKey, nil\n\tcase *dsa.PrivateKey:\n\t\treturn &key.PublicKey, nil\n\t}\n\tpanic(\"unknown key type\")\n}\n\nfunc (k *keychain) Sign(i int, rand io.Reader, data []byte) (sig []byte, err error) {\n\thashFunc := crypto.SHA1\n\th := hashFunc.New()\n\th.Write(data)\n\tdigest := h.Sum(nil)\n\tswitch key := k.keys[i].(type) {\n\tcase *rsa.PrivateKey:\n\t\treturn rsa.SignPKCS1v15(rand, key, hashFunc, digest)\n\t}\n\treturn nil, errors.New(\"ssh: unknown key type\")\n}\n\nfunc (k *keychain) loadPEM(file string) error {\n\tbuf, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\tblock, _ := pem.Decode(buf)\n\tif block == nil {\n\t\treturn errors.New(\"ssh: no key found\")\n\t}\n\tr, err := x509.ParsePKCS1PrivateKey(block.Bytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\tk.keys = append(k.keys, r)\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package corehttp\n\nimport (\n\t\"html\/template\"\n\t\"io\"\n\t\"net\/http\"\n\t\"path\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/code.google.com\/p\/go.net\/context\"\n\tmh \"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/github.com\/jbenet\/go-multihash\"\n\n\tcore \"github.com\/jbenet\/go-ipfs\/core\"\n\t\"github.com\/jbenet\/go-ipfs\/importer\"\n\tchunk \"github.com\/jbenet\/go-ipfs\/importer\/chunk\"\n\tdag \"github.com\/jbenet\/go-ipfs\/merkledag\"\n\t\"github.com\/jbenet\/go-ipfs\/routing\"\n\tuio \"github.com\/jbenet\/go-ipfs\/unixfs\/io\"\n\tu \"github.com\/jbenet\/go-ipfs\/util\"\n)\n\nconst (\n\tIpfsPathPrefix = \"\/ipfs\/\"\n\tIpnsPathPrefix = \"\/ipns\/\"\n)\n\ntype gateway interface {\n\tResolvePath(string) (*dag.Node, error)\n\tNewDagFromReader(io.Reader) (*dag.Node, error)\n\tAddNodeToDAG(nd *dag.Node) (u.Key, error)\n\tNewDagReader(nd *dag.Node) (uio.ReadSeekCloser, error)\n}\n\n\/\/ shortcut for templating\ntype webHandler map[string]interface{}\n\n\/\/ struct for directory listing\ntype directoryItem struct {\n\tSize uint64\n\tName string\n\tPath string\n}\n\n\/\/ gatewayHandler is a HTTP handler that serves IPFS objects (accessible by default at \/ipfs\/<path>)\n\/\/ (it serves requests like GET \/ipfs\/QmVRzPKPzNtSrEzBFm2UZfxmPAgnaLke4DMcerbsGGSaFe\/link)\ntype gatewayHandler struct {\n\tnode    *core.IpfsNode\n\tdirList *template.Template\n}\n\nfunc newGatewayHandler(node *core.IpfsNode) (*gatewayHandler, error) {\n\ti := &gatewayHandler{\n\t\tnode: node,\n\t}\n\terr := i.loadTemplate()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn i, nil\n}\n\n\/\/ Load the directroy list template\nfunc (i *gatewayHandler) loadTemplate() error {\n\tt, err := template.New(\"dir\").Parse(listingTemplate)\n\tif err != nil {\n\t\treturn err\n\t}\n\ti.dirList = t\n\treturn nil\n}\n\nfunc (i *gatewayHandler) ResolvePath(ctx context.Context, p string) (*dag.Node, string, error) {\n\tp = path.Clean(p)\n\n\tif strings.HasPrefix(p, IpnsPathPrefix) {\n\t\telements := strings.Split(p[len(IpnsPathPrefix):], \"\/\")\n\t\thash := elements[0]\n\t\tk, err := i.node.Namesys.Resolve(ctx, hash)\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\n\t\telements[0] = k.Pretty()\n\t\tp = path.Join(elements...)\n\t}\n\tif !strings.HasPrefix(p, IpfsPathPrefix) {\n\t\tp = path.Join(IpfsPathPrefix, p)\n\t}\n\n\tnode, err := i.node.Resolver.ResolvePath(p)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\treturn node, p, err\n}\n\nfunc (i *gatewayHandler) NewDagFromReader(r io.Reader) (*dag.Node, error) {\n\treturn importer.BuildDagFromReader(\n\t\tr, i.node.DAG, i.node.Pinning.GetManual(), chunk.DefaultSplitter)\n}\n\nfunc (i *gatewayHandler) AddNodeToDAG(nd *dag.Node) (u.Key, error) {\n\treturn i.node.DAG.Add(nd)\n}\n\nfunc (i *gatewayHandler) NewDagReader(nd *dag.Node) (uio.ReadSeekCloser, error) {\n\treturn uio.NewDagReader(i.node.Context(), nd, i.node.DAG)\n}\n\nfunc (i *gatewayHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tctx, cancel := context.WithCancel(i.node.Context())\n\tdefer cancel()\n\n\turlPath := r.URL.Path\n\n\tnd, p, err := i.ResolvePath(ctx, urlPath)\n\tif err != nil {\n\t\tif err == routing.ErrNotFound {\n\t\t\tw.WriteHeader(http.StatusNotFound)\n\t\t} else if err == context.DeadlineExceeded {\n\t\t\tw.WriteHeader(http.StatusRequestTimeout)\n\t\t} else {\n\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t}\n\n\t\tlog.Error(err)\n\t\tw.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\n\tw.Header().Set(\"X-IPFS-Path\", p)\n\tw.Header().Set(\"Etag\", path.Base(p))\n\tw.Header().Set(\"Cache-Control\", \"public, max-age=29030400\")\n\n\tdr, err := i.NewDagReader(nd)\n\tif err == nil {\n\t\tdefer dr.Close()\n\t\t_, name := path.Split(urlPath)\n\t\t\/\/ set modtime to a really long time ago, since files are immutable and should stay cached\n\t\tmodtime := time.Unix(1, 0)\n\t\thttp.ServeContent(w, r, name, modtime, dr)\n\t\treturn\n\t}\n\n\tif err != uio.ErrIsDir {\n\t\t\/\/ not a directory and still an error\n\t\tinternalWebError(w, err)\n\t\treturn\n\t}\n\n\t\/\/ storage for directory listing\n\tvar dirListing []directoryItem\n\t\/\/ loop through files\n\tfoundIndex := false\n\tfor _, link := range nd.Links {\n\t\tif link.Name == \"index.html\" {\n\t\t\tif urlPath[len(urlPath)-1] != '\/' {\n\t\t\t\thttp.Redirect(w, r, urlPath+\"\/\", 302)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tlog.Debug(\"found index\")\n\t\t\tfoundIndex = true\n\t\t\t\/\/ return index page instead.\n\t\t\tnd, _, err := i.ResolvePath(ctx, urlPath+\"\/index.html\")\n\t\t\tif err != nil {\n\t\t\t\tinternalWebError(w, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdr, err := i.NewDagReader(nd)\n\t\t\tif err != nil {\n\t\t\t\tinternalWebError(w, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdefer dr.Close()\n\t\t\t\/\/ write to request\n\t\t\tio.Copy(w, dr)\n\t\t\tbreak\n\t\t}\n\n\t\tdi := directoryItem{link.Size, link.Name, path.Join(urlPath, link.Name)}\n\t\tdirListing = append(dirListing, di)\n\t}\n\n\tif !foundIndex {\n\t\t\/\/ template and return directory listing\n\t\thndlr := webHandler{\n\t\t\t\"listing\": dirListing,\n\t\t\t\"path\":    urlPath,\n\t\t}\n\t\tif err := i.dirList.Execute(w, hndlr); err != nil {\n\t\t\tinternalWebError(w, err)\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (i *gatewayHandler) postHandler(w http.ResponseWriter, r *http.Request) {\n\tnd, err := i.NewDagFromReader(r.Body)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tlog.Error(err)\n\t\tw.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\n\tk, err := i.AddNodeToDAG(nd)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tlog.Error(err)\n\t\tw.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\n\t\/\/TODO: return json representation of list instead\n\tw.WriteHeader(http.StatusCreated)\n\tw.Write([]byte(mh.Multihash(k).B58String()))\n}\n\n\/\/ return a 500 error and log\nfunc internalWebError(w http.ResponseWriter, err error) {\n\tw.WriteHeader(http.StatusInternalServerError)\n\tw.Write([]byte(err.Error()))\n\tlog.Error(\"%s\", err)\n}\n\n\/\/ Directory listing template\nvar listingTemplate = `\n<!DOCTYPE html>\n<html>\n\t<head>\n\t\t<meta charset=\"utf-8\" \/>\n\t\t<title>{{ .path }}<\/title>\n\t<\/head>\n\t<body>\n\t<h2>Index of {{ .path }}<\/h2>\n\t<ul>\n\t<li><a href=\".\/..\">..<\/a><\/li>\n  {{ range .listing }}\n\t<li><a href=\"{{ .Path }}\">{{ .Name }}<\/a> - {{ .Size }} bytes<\/li>\n\t{{ end }}\n\t<\/ul>\n\t<\/body>\n<\/html>\n`\n<commit_msg>core\/corehttp: Handle Etag for caching<commit_after>package corehttp\n\nimport (\n\t\"html\/template\"\n\t\"io\"\n\t\"net\/http\"\n\t\"path\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/code.google.com\/p\/go.net\/context\"\n\tmh \"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/github.com\/jbenet\/go-multihash\"\n\n\tcore \"github.com\/jbenet\/go-ipfs\/core\"\n\t\"github.com\/jbenet\/go-ipfs\/importer\"\n\tchunk \"github.com\/jbenet\/go-ipfs\/importer\/chunk\"\n\tdag \"github.com\/jbenet\/go-ipfs\/merkledag\"\n\t\"github.com\/jbenet\/go-ipfs\/routing\"\n\tuio \"github.com\/jbenet\/go-ipfs\/unixfs\/io\"\n\tu \"github.com\/jbenet\/go-ipfs\/util\"\n)\n\nconst (\n\tIpfsPathPrefix = \"\/ipfs\/\"\n\tIpnsPathPrefix = \"\/ipns\/\"\n)\n\ntype gateway interface {\n\tResolvePath(string) (*dag.Node, error)\n\tNewDagFromReader(io.Reader) (*dag.Node, error)\n\tAddNodeToDAG(nd *dag.Node) (u.Key, error)\n\tNewDagReader(nd *dag.Node) (uio.ReadSeekCloser, error)\n}\n\n\/\/ shortcut for templating\ntype webHandler map[string]interface{}\n\n\/\/ struct for directory listing\ntype directoryItem struct {\n\tSize uint64\n\tName string\n\tPath string\n}\n\n\/\/ gatewayHandler is a HTTP handler that serves IPFS objects (accessible by default at \/ipfs\/<path>)\n\/\/ (it serves requests like GET \/ipfs\/QmVRzPKPzNtSrEzBFm2UZfxmPAgnaLke4DMcerbsGGSaFe\/link)\ntype gatewayHandler struct {\n\tnode    *core.IpfsNode\n\tdirList *template.Template\n}\n\nfunc newGatewayHandler(node *core.IpfsNode) (*gatewayHandler, error) {\n\ti := &gatewayHandler{\n\t\tnode: node,\n\t}\n\terr := i.loadTemplate()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn i, nil\n}\n\n\/\/ Load the directroy list template\nfunc (i *gatewayHandler) loadTemplate() error {\n\tt, err := template.New(\"dir\").Parse(listingTemplate)\n\tif err != nil {\n\t\treturn err\n\t}\n\ti.dirList = t\n\treturn nil\n}\n\nfunc (i *gatewayHandler) ResolvePath(ctx context.Context, p string) (*dag.Node, string, error) {\n\tp = path.Clean(p)\n\n\tif strings.HasPrefix(p, IpnsPathPrefix) {\n\t\telements := strings.Split(p[len(IpnsPathPrefix):], \"\/\")\n\t\thash := elements[0]\n\t\tk, err := i.node.Namesys.Resolve(ctx, hash)\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\n\t\telements[0] = k.Pretty()\n\t\tp = path.Join(elements...)\n\t}\n\tif !strings.HasPrefix(p, IpfsPathPrefix) {\n\t\tp = path.Join(IpfsPathPrefix, p)\n\t}\n\n\tnode, err := i.node.Resolver.ResolvePath(p)\n\tif err != nil {\n\t\treturn nil, \"\", err\n\t}\n\treturn node, p, err\n}\n\nfunc (i *gatewayHandler) NewDagFromReader(r io.Reader) (*dag.Node, error) {\n\treturn importer.BuildDagFromReader(\n\t\tr, i.node.DAG, i.node.Pinning.GetManual(), chunk.DefaultSplitter)\n}\n\nfunc (i *gatewayHandler) AddNodeToDAG(nd *dag.Node) (u.Key, error) {\n\treturn i.node.DAG.Add(nd)\n}\n\nfunc (i *gatewayHandler) NewDagReader(nd *dag.Node) (uio.ReadSeekCloser, error) {\n\treturn uio.NewDagReader(i.node.Context(), nd, i.node.DAG)\n}\n\nfunc (i *gatewayHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tctx, cancel := context.WithCancel(i.node.Context())\n\tdefer cancel()\n\n\turlPath := r.URL.Path\n\n\tnd, p, err := i.ResolvePath(ctx, urlPath)\n\tif err != nil {\n\t\tif err == routing.ErrNotFound {\n\t\t\tw.WriteHeader(http.StatusNotFound)\n\t\t} else if err == context.DeadlineExceeded {\n\t\t\tw.WriteHeader(http.StatusRequestTimeout)\n\t\t} else {\n\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t}\n\n\t\tlog.Error(err)\n\t\tw.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\n\tetag := path.Base(p)\n\tif r.Header.Get(\"If-None-Match\") == etag {\n\t\tw.WriteHeader(http.StatusNotModified)\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Etag\", etag)\n\tw.Header().Set(\"X-IPFS-Path\", p)\n\tw.Header().Set(\"Cache-Control\", \"public, max-age=29030400\")\n\n\tdr, err := i.NewDagReader(nd)\n\tif err == nil {\n\t\tdefer dr.Close()\n\t\t_, name := path.Split(urlPath)\n\t\t\/\/ set modtime to a really long time ago, since files are immutable and should stay cached\n\t\tmodtime := time.Unix(1, 0)\n\t\thttp.ServeContent(w, r, name, modtime, dr)\n\t\treturn\n\t}\n\n\tif err != uio.ErrIsDir {\n\t\t\/\/ not a directory and still an error\n\t\tinternalWebError(w, err)\n\t\treturn\n\t}\n\n\t\/\/ storage for directory listing\n\tvar dirListing []directoryItem\n\t\/\/ loop through files\n\tfoundIndex := false\n\tfor _, link := range nd.Links {\n\t\tif link.Name == \"index.html\" {\n\t\t\tif urlPath[len(urlPath)-1] != '\/' {\n\t\t\t\thttp.Redirect(w, r, urlPath+\"\/\", 302)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tlog.Debug(\"found index\")\n\t\t\tfoundIndex = true\n\t\t\t\/\/ return index page instead.\n\t\t\tnd, _, err := i.ResolvePath(ctx, urlPath+\"\/index.html\")\n\t\t\tif err != nil {\n\t\t\t\tinternalWebError(w, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdr, err := i.NewDagReader(nd)\n\t\t\tif err != nil {\n\t\t\t\tinternalWebError(w, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdefer dr.Close()\n\t\t\t\/\/ write to request\n\t\t\tio.Copy(w, dr)\n\t\t\tbreak\n\t\t}\n\n\t\tdi := directoryItem{link.Size, link.Name, path.Join(urlPath, link.Name)}\n\t\tdirListing = append(dirListing, di)\n\t}\n\n\tif !foundIndex {\n\t\t\/\/ template and return directory listing\n\t\thndlr := webHandler{\n\t\t\t\"listing\": dirListing,\n\t\t\t\"path\":    urlPath,\n\t\t}\n\t\tif err := i.dirList.Execute(w, hndlr); err != nil {\n\t\t\tinternalWebError(w, err)\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (i *gatewayHandler) postHandler(w http.ResponseWriter, r *http.Request) {\n\tnd, err := i.NewDagFromReader(r.Body)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tlog.Error(err)\n\t\tw.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\n\tk, err := i.AddNodeToDAG(nd)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tlog.Error(err)\n\t\tw.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\n\t\/\/TODO: return json representation of list instead\n\tw.WriteHeader(http.StatusCreated)\n\tw.Write([]byte(mh.Multihash(k).B58String()))\n}\n\n\/\/ return a 500 error and log\nfunc internalWebError(w http.ResponseWriter, err error) {\n\tw.WriteHeader(http.StatusInternalServerError)\n\tw.Write([]byte(err.Error()))\n\tlog.Error(\"%s\", err)\n}\n\n\/\/ Directory listing template\nvar listingTemplate = `\n<!DOCTYPE html>\n<html>\n\t<head>\n\t\t<meta charset=\"utf-8\" \/>\n\t\t<title>{{ .path }}<\/title>\n\t<\/head>\n\t<body>\n\t<h2>Index of {{ .path }}<\/h2>\n\t<ul>\n\t<li><a href=\".\/..\">..<\/a><\/li>\n  {{ range .listing }}\n\t<li><a href=\"{{ .Path }}\">{{ .Name }}<\/a> - {{ .Size }} bytes<\/li>\n\t{{ end }}\n\t<\/ul>\n\t<\/body>\n<\/html>\n`\n<|endoftext|>"}
{"text":"<commit_before>package sanity\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"k8s.io\/client-go\/kubernetes\"\n\t\"k8s.io\/client-go\/pkg\/api\/v1\"\n\t\"k8s.io\/client-go\/tools\/clientcmd\"\n)\n\nconst (\n\t\/\/ nodeCountVar is the environment variable to check for Node count.\n\tnodeCountVar = \"NODE_COUNT\"\n\n\t\/\/ kubeconfigEnv is the environment variable that is checked for a the kubeconfig path to be loaded.\n\tkubeconfigEnv = \"TEST_KUBECONFIG\"\n)\n\ntype timer struct {\n\ttimeout time.Time\n}\n\nfunc newTimer(timeout time.Duration) *timer {\n\treturn &timer{time.Now().Add(timeout)}\n}\n\nfunc (t *timer) timedOut() bool {\n\treturn time.Now().After(t.timeout)\n}\n\nfunc newClient(t *testing.T) *kubernetes.Clientset {\n\tkcfgPath := os.Getenv(kubeconfigEnv)\n\tif len(kcfgPath) == 0 {\n\t\tt.Fatalf(\"no kubeconfig path in environment variable %s\", kubeconfigEnv)\n\t}\n\n\trules := &clientcmd.ClientConfigLoadingRules{ExplicitPath: kcfgPath}\n\tcfg := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, &clientcmd.ConfigOverrides{})\n\trestConfig, err := cfg.ClientConfig()\n\tif err != nil {\n\t\tt.Fatalf(\"could not create client config: %v\", err)\n\t}\n\n\tcs, err := kubernetes.NewForConfig(restConfig)\n\tif err != nil {\n\t\tt.Fatalf(\"could not create clientset: %v\", err)\n\t}\n\treturn cs\n}\n\nfunc TestCluster(t *testing.T) {\n\t\/\/ verify that api server is up in 10 min\n\tt.Run(\"APIAvailable\", testAPIAvailable)\n\n\t\/\/ wait for all nodes to become available\n\tt.Run(\"AllNodesRunning\", testAllNodesRunning)\n\tt.Run(\"GetLogs\", testLogs)\n\tt.Run(\"AllPodsRunning\", testAllPodsRunning)\n\tt.Run(\"KillAPIServer\", testKillAPIServer)\n}\n\nfunc testAPIAvailable(t *testing.T) {\n\t\/\/ chan signaled when API server found\n\tdone := waitForAPIServer(t)\n\n\t\/\/ timeout searching for server\n\twait := 10 * time.Minute\n\tt.Logf(\"Waiting %v for API server to become available\", wait)\n\n\ttimeout := time.After(wait)\n\tselect {\n\tcase <-timeout:\n\t\tt.Fatalf(\"Could not connect to API server in %v, FAILING!\", wait)\n\tcase <-done:\n\t\tt.Log(\"API server is available.\")\n\t\treturn\n\t}\n}\n\nfunc testAllPodsRunning(t *testing.T) {\n\tc := newClient(t)\n\n\ttimer := newTimer(10 * time.Minute)\n\n\tfor {\n\t\tif timer.timedOut() {\n\t\t\tt.Fatalf(\"timed out waiting for pods to be ready.\")\n\t\t}\n\n\t\tpods, err := c.Core().Pods(\"\").List(v1.ListOptions{})\n\t\tif err != nil {\n\t\t\tt.Logf(\"could not list pods: %v\", err)\n\t\t\tpods = &v1.PodList{}\n\t\t}\n\n\t\tallReady := len(pods.Items) != 0\n\t\tfor _, p := range pods.Items {\n\t\t\tif p.Status.Phase != v1.PodRunning {\n\t\t\t\tallReady = false\n\t\t\t\tt.Logf(\"pod %s\/%s not running\", p.Namespace, p.Name)\n\t\t\t}\n\t\t}\n\t\tif allReady {\n\t\t\treturn\n\t\t}\n\n\t\ttime.Sleep(3 * time.Second)\n\t}\n}\n\nfunc testLogs(t *testing.T) {\n\tc := newClient(t)\n\n\tnamespace := \"tectonic-system\"\n\tpodPrefix := \"tectonic-identity\"\n\n\twait := 3 * time.Minute\n\ttimeout := time.After(wait)\n\tdone := make(chan struct{})\n\tgo func() {\n\t\tfor {\n\t\t\terr := validatePodLogging(c, namespace, podPrefix)\n\t\t\tif err == nil {\n\t\t\t\tdone <- struct{}{}\n\t\t\t\treturn\n\t\t\t}\n\t\t\tt.Log(\"Failed to get Pod logs with error: \", err)\n\t\t\ttime.Sleep(3 * time.Second)\n\t\t}\n\t}()\n\n\tselect {\n\tcase <-timeout:\n\t\tt.Fatalf(\"Failed to gather logs for %s\/%s* in %v\", namespace, podPrefix, wait)\n\tcase <-done:\n\t\treturn\n\t}\n}\n\n\/\/ validatePodLogging verifies that logs can be retrieved for a container in Pod.\nfunc validatePodLogging(c *kubernetes.Clientset, namespace, podPrefix string) error {\n\tpods, err := c.Pods(namespace).List(v1.ListOptions{})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not list pods: %v\", err)\n\t}\n\n\tvar names string\n\tfor _, p := range pods.Items {\n\t\tif len(names) != 0 {\n\t\t\tnames += \", \"\n\t\t}\n\t\tnames += p.Name\n\n\t\tif !strings.HasPrefix(p.Name, podPrefix) {\n\t\t\tcontinue\n\t\t}\n\t\tif len(p.Spec.Containers) == 0 {\n\t\t\treturn fmt.Errorf(\"tectonic identity pod has no containers\")\n\t\t}\n\n\t\topt := v1.PodLogOptions{\n\t\t\tContainer: p.Spec.Containers[0].Name,\n\t\t}\n\n\t\tresult := c.Core().Pods(namespace).GetLogs(p.Name, &opt).Do()\n\t\tif err := result.Error(); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to get pod logs: %v\", err)\n\t\t}\n\n\t\tvar statusCode int\n\t\tresult.StatusCode(&statusCode)\n\t\tif statusCode\/100 != 2 {\n\t\t\treturn fmt.Errorf(\"expected 200 from log response, got %d\", statusCode)\n\t\t}\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"failed to find tectonic-identity pod (found pods in %s: %s)\", namespace, names)\n}\n\nfunc testAllNodesRunning(t *testing.T) {\n\tc := newClient(t)\n\n\texpNodeCount, err := strconv.Atoi(os.Getenv(nodeCountVar))\n\tif err != nil {\n\t\tt.Fatalf(\"failed to get number of expected nodes from envvar %s: %v\", nodeCountVar, err)\n\t}\n\n\ttimer := newTimer(10 * time.Minute)\n\tfor {\n\t\tif timer.timedOut() {\n\t\t\tt.Fatalf(\"timed out waiting for nodes to be ready.\")\n\t\t}\n\n\t\tnodes, err := c.Core().Nodes().List(v1.ListOptions{})\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"could not list nodes: %v\", err)\n\t\t}\n\n\t\tallReady := len(nodes.Items) != 0\n\t\tfor _, node := range nodes.Items {\n\t\t\tif nodeReady(node) {\n\t\t\t\tt.Logf(\"node %s ready\", node.Name)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tallReady = false\n\t\t\tt.Logf(\"node %s not ready\", node.Name)\n\t\t}\n\n\t\tif allReady {\n\t\t\treturn\n\t\t}\n\n\t\tif got := len(nodes.Items); got != expNodeCount {\n\t\t\tt.Logf(\"expected %d nodes got %d\", expNodeCount, got)\n\t\t}\n\n\t\ttime.Sleep(10 * time.Second)\n\t}\n}\n\nfunc testKillAPIServer(t *testing.T) {\n\tc := newClient(t)\n\tpods, err := getAPIServers(c)\n\tif err != nil {\n\t\tt.Fatalf(\"get apiserver pod: %v\", err)\n\t}\n\n\toldPod := map[string]bool{}\n\n\t\/\/ Nuke all API servers.\n\tfor _, pod := range pods.Items {\n\t\tif err := c.Core().Pods(pod.Namespace).Delete(pod.Name, nil); err != nil {\n\t\t\tt.Fatalf(\"failed to delete pod %s: %v\", pod.Name, err)\n\t\t}\n\t\toldPod[pod.Name] = true\n\t}\n\n\t\/\/ API servers and temp API servers come in and out. Ensure\n\t\/\/ that the API server we detect is running for a couple\n\t\/\/ iterations.\n\trunningLastTime := false\n\n\tapiServerUp := func() bool {\n\t\tpods, err := getAPIServers(c)\n\t\tif err != nil {\n\t\t\tt.Logf(\"get apiserver pod: %v\", err)\n\t\t\treturn false\n\t\t}\n\n\t\tfor _, pod := range pods.Items {\n\t\t\tif oldPod[pod.Name] {\n\t\t\t\tt.Logf(\"old API server %s still running\", pod.Name)\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\n\t\tallReady := len(pods.Items) != 0\n\t\tfor _, p := range pods.Items {\n\t\t\tif p.Status.Phase != v1.PodRunning {\n\t\t\t\tallReady = false\n\t\t\t}\n\t\t}\n\n\t\tif allReady {\n\t\t\tif runningLastTime {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\trunningLastTime = true\n\t\t}\n\t\treturn false\n\t}\n\n\ttimer := newTimer(6 * time.Minute)\n\tfor {\n\t\tif timer.timedOut() {\n\t\t\tt.Fatalf(\"timed out waiting for pods to be ready.\")\n\t\t}\n\n\t\tif apiServerUp() {\n\t\t\treturn\n\t\t}\n\n\t\ttime.Sleep(10 * time.Second)\n\t}\n}\n\nfunc waitForAPIServer(t *testing.T) <-chan struct{} {\n\tdone := make(chan struct{}, 1)\n\tgo func() {\n\t\tvar client *kubernetes.Clientset\n\t\tfor {\n\t\t\tclient = newClient(t)\n\t\t\t_, err := client.ServerVersion()\n\t\t\tif err == nil {\n\t\t\t\tdone <- struct{}{}\n\t\t\t\treturn\n\t\t\t}\n\t\t\twait := 10 * time.Second\n\t\t\tt.Logf(\"Waiting %v after failed attempt to connect to API server. Error was: %v\", wait, err)\n\t\t\ttime.Sleep(wait)\n\t\t}\n\t}()\n\treturn done\n}\n\nfunc getAPIServers(client *kubernetes.Clientset) (*v1.PodList, error) {\n\tconst (\n\t\tapiServerSelector   = \"k8s-app=kube-apiserver\"\n\t\tkubeSystemNamespace = \"kube-system\"\n\t)\n\tpods, err := client.Core().Pods(kubeSystemNamespace).List(v1.ListOptions{LabelSelector: apiServerSelector})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(pods.Items) == 0 {\n\t\treturn nil, fmt.Errorf(\"no pods matched the label selector %q in the %s namespace\", apiServerSelector, kubeSystemNamespace)\n\t}\n\treturn pods, nil\n}\n\n\/\/ podsStr prints a comma separated list of namespaced Pod names\nfunc podsStr(pods []v1.Pod) (out string) {\n\tfor n, p := range pods {\n\t\t\/\/ add comma to all entries except first\n\t\tif n != 0 {\n\t\t\tout += \", \"\n\t\t}\n\t\tout += fmt.Sprintf(\"%s\/%s\", p.GetNamespace(), p.GetName())\n\t}\n\treturn\n}\n\nfunc nodeReady(node v1.Node) (ok bool) {\n\tfor _, cond := range node.Status.Conditions {\n\t\tif cond.Type == v1.NodeReady {\n\t\t\treturn cond.Status == v1.ConditionTrue\n\t\t}\n\t}\n\treturn false\n}\n<commit_msg>tests: wait longer for clusters to come up<commit_after>package sanity\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"k8s.io\/client-go\/kubernetes\"\n\t\"k8s.io\/client-go\/pkg\/api\/v1\"\n\t\"k8s.io\/client-go\/tools\/clientcmd\"\n)\n\nconst (\n\t\/\/ nodeCountVar is the environment variable to check for Node count.\n\tnodeCountVar = \"NODE_COUNT\"\n\n\t\/\/ kubeconfigEnv is the environment variable that is checked for a the kubeconfig path to be loaded.\n\tkubeconfigEnv = \"TEST_KUBECONFIG\"\n)\n\ntype timer struct {\n\ttimeout time.Time\n}\n\nfunc newTimer(timeout time.Duration) *timer {\n\treturn &timer{time.Now().Add(timeout)}\n}\n\nfunc (t *timer) timedOut() bool {\n\treturn time.Now().After(t.timeout)\n}\n\nfunc newClient(t *testing.T) *kubernetes.Clientset {\n\tkcfgPath := os.Getenv(kubeconfigEnv)\n\tif len(kcfgPath) == 0 {\n\t\tt.Fatalf(\"no kubeconfig path in environment variable %s\", kubeconfigEnv)\n\t}\n\n\trules := &clientcmd.ClientConfigLoadingRules{ExplicitPath: kcfgPath}\n\tcfg := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, &clientcmd.ConfigOverrides{})\n\trestConfig, err := cfg.ClientConfig()\n\tif err != nil {\n\t\tt.Fatalf(\"could not create client config: %v\", err)\n\t}\n\n\tcs, err := kubernetes.NewForConfig(restConfig)\n\tif err != nil {\n\t\tt.Fatalf(\"could not create clientset: %v\", err)\n\t}\n\treturn cs\n}\n\nfunc TestCluster(t *testing.T) {\n\t\/\/ verify that api server is up in 10 min\n\tt.Run(\"APIAvailable\", testAPIAvailable)\n\n\t\/\/ wait for all nodes to become available\n\tt.Run(\"AllNodesRunning\", testAllNodesRunning)\n\tt.Run(\"GetLogs\", testLogs)\n\tt.Run(\"AllPodsRunning\", testAllPodsRunning)\n\tt.Run(\"KillAPIServer\", testKillAPIServer)\n}\n\nfunc testAPIAvailable(t *testing.T) {\n\t\/\/ chan signaled when API server found\n\tdone := waitForAPIServer(t)\n\n\t\/\/ timeout searching for server\n\twait := 15 * time.Minute\n\tt.Logf(\"Waiting %v for API server to become available\", wait)\n\n\ttimeout := time.After(wait)\n\tselect {\n\tcase <-timeout:\n\t\tt.Fatalf(\"Could not connect to API server in %v, FAILING!\", wait)\n\tcase <-done:\n\t\tt.Log(\"API server is available.\")\n\t\treturn\n\t}\n}\n\nfunc testAllPodsRunning(t *testing.T) {\n\tc := newClient(t)\n\n\ttimer := newTimer(10 * time.Minute)\n\n\tfor {\n\t\tif timer.timedOut() {\n\t\t\tt.Fatalf(\"timed out waiting for pods to be ready.\")\n\t\t}\n\n\t\tpods, err := c.Core().Pods(\"\").List(v1.ListOptions{})\n\t\tif err != nil {\n\t\t\tt.Logf(\"could not list pods: %v\", err)\n\t\t\tpods = &v1.PodList{}\n\t\t}\n\n\t\tallReady := len(pods.Items) != 0\n\t\tfor _, p := range pods.Items {\n\t\t\tif p.Status.Phase != v1.PodRunning {\n\t\t\t\tallReady = false\n\t\t\t\tt.Logf(\"pod %s\/%s not running\", p.Namespace, p.Name)\n\t\t\t}\n\t\t}\n\t\tif allReady {\n\t\t\treturn\n\t\t}\n\n\t\ttime.Sleep(3 * time.Second)\n\t}\n}\n\nfunc testLogs(t *testing.T) {\n\tc := newClient(t)\n\n\tnamespace := \"tectonic-system\"\n\tpodPrefix := \"tectonic-identity\"\n\n\twait := 3 * time.Minute\n\ttimeout := time.After(wait)\n\tdone := make(chan struct{})\n\tgo func() {\n\t\tfor {\n\t\t\terr := validatePodLogging(c, namespace, podPrefix)\n\t\t\tif err == nil {\n\t\t\t\tdone <- struct{}{}\n\t\t\t\treturn\n\t\t\t}\n\t\t\tt.Log(\"Failed to get Pod logs with error: \", err)\n\t\t\ttime.Sleep(3 * time.Second)\n\t\t}\n\t}()\n\n\tselect {\n\tcase <-timeout:\n\t\tt.Fatalf(\"Failed to gather logs for %s\/%s* in %v\", namespace, podPrefix, wait)\n\tcase <-done:\n\t\treturn\n\t}\n}\n\n\/\/ validatePodLogging verifies that logs can be retrieved for a container in Pod.\nfunc validatePodLogging(c *kubernetes.Clientset, namespace, podPrefix string) error {\n\tpods, err := c.Pods(namespace).List(v1.ListOptions{})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not list pods: %v\", err)\n\t}\n\n\tvar names string\n\tfor _, p := range pods.Items {\n\t\tif len(names) != 0 {\n\t\t\tnames += \", \"\n\t\t}\n\t\tnames += p.Name\n\n\t\tif !strings.HasPrefix(p.Name, podPrefix) {\n\t\t\tcontinue\n\t\t}\n\t\tif len(p.Spec.Containers) == 0 {\n\t\t\treturn fmt.Errorf(\"tectonic identity pod has no containers\")\n\t\t}\n\n\t\topt := v1.PodLogOptions{\n\t\t\tContainer: p.Spec.Containers[0].Name,\n\t\t}\n\n\t\tresult := c.Core().Pods(namespace).GetLogs(p.Name, &opt).Do()\n\t\tif err := result.Error(); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to get pod logs: %v\", err)\n\t\t}\n\n\t\tvar statusCode int\n\t\tresult.StatusCode(&statusCode)\n\t\tif statusCode\/100 != 2 {\n\t\t\treturn fmt.Errorf(\"expected 200 from log response, got %d\", statusCode)\n\t\t}\n\t\treturn nil\n\t}\n\n\treturn fmt.Errorf(\"failed to find tectonic-identity pod (found pods in %s: %s)\", namespace, names)\n}\n\nfunc testAllNodesRunning(t *testing.T) {\n\tc := newClient(t)\n\n\texpNodeCount, err := strconv.Atoi(os.Getenv(nodeCountVar))\n\tif err != nil {\n\t\tt.Fatalf(\"failed to get number of expected nodes from envvar %s: %v\", nodeCountVar, err)\n\t}\n\n\ttimer := newTimer(10 * time.Minute)\n\tfor {\n\t\tif timer.timedOut() {\n\t\t\tt.Fatalf(\"timed out waiting for nodes to be ready.\")\n\t\t}\n\n\t\tnodes, err := c.Core().Nodes().List(v1.ListOptions{})\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"could not list nodes: %v\", err)\n\t\t}\n\n\t\tallReady := len(nodes.Items) != 0\n\t\tfor _, node := range nodes.Items {\n\t\t\tif nodeReady(node) {\n\t\t\t\tt.Logf(\"node %s ready\", node.Name)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tallReady = false\n\t\t\tt.Logf(\"node %s not ready\", node.Name)\n\t\t}\n\n\t\tif allReady {\n\t\t\treturn\n\t\t}\n\n\t\tif got := len(nodes.Items); got != expNodeCount {\n\t\t\tt.Logf(\"expected %d nodes got %d\", expNodeCount, got)\n\t\t}\n\n\t\ttime.Sleep(10 * time.Second)\n\t}\n}\n\nfunc testKillAPIServer(t *testing.T) {\n\tc := newClient(t)\n\tpods, err := getAPIServers(c)\n\tif err != nil {\n\t\tt.Fatalf(\"get apiserver pod: %v\", err)\n\t}\n\n\toldPod := map[string]bool{}\n\n\t\/\/ Nuke all API servers.\n\tfor _, pod := range pods.Items {\n\t\tif err := c.Core().Pods(pod.Namespace).Delete(pod.Name, nil); err != nil {\n\t\t\tt.Fatalf(\"failed to delete pod %s: %v\", pod.Name, err)\n\t\t}\n\t\toldPod[pod.Name] = true\n\t}\n\n\t\/\/ API servers and temp API servers come in and out. Ensure\n\t\/\/ that the API server we detect is running for a couple\n\t\/\/ iterations.\n\trunningLastTime := false\n\n\tapiServerUp := func() bool {\n\t\tpods, err := getAPIServers(c)\n\t\tif err != nil {\n\t\t\tt.Logf(\"get apiserver pod: %v\", err)\n\t\t\treturn false\n\t\t}\n\n\t\tfor _, pod := range pods.Items {\n\t\t\tif oldPod[pod.Name] {\n\t\t\t\tt.Logf(\"old API server %s still running\", pod.Name)\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\n\t\tallReady := len(pods.Items) != 0\n\t\tfor _, p := range pods.Items {\n\t\t\tif p.Status.Phase != v1.PodRunning {\n\t\t\t\tallReady = false\n\t\t\t}\n\t\t}\n\n\t\tif allReady {\n\t\t\tif runningLastTime {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\trunningLastTime = true\n\t\t}\n\t\treturn false\n\t}\n\n\ttimer := newTimer(6 * time.Minute)\n\tfor {\n\t\tif timer.timedOut() {\n\t\t\tt.Fatalf(\"timed out waiting for pods to be ready.\")\n\t\t}\n\n\t\tif apiServerUp() {\n\t\t\treturn\n\t\t}\n\n\t\ttime.Sleep(10 * time.Second)\n\t}\n}\n\nfunc waitForAPIServer(t *testing.T) <-chan struct{} {\n\tdone := make(chan struct{}, 1)\n\tgo func() {\n\t\tvar client *kubernetes.Clientset\n\t\tfor {\n\t\t\tclient = newClient(t)\n\t\t\t_, err := client.ServerVersion()\n\t\t\tif err == nil {\n\t\t\t\tdone <- struct{}{}\n\t\t\t\treturn\n\t\t\t}\n\t\t\twait := 10 * time.Second\n\t\t\tt.Logf(\"Waiting %v after failed attempt to connect to API server. Error was: %v\", wait, err)\n\t\t\ttime.Sleep(wait)\n\t\t}\n\t}()\n\treturn done\n}\n\nfunc getAPIServers(client *kubernetes.Clientset) (*v1.PodList, error) {\n\tconst (\n\t\tapiServerSelector   = \"k8s-app=kube-apiserver\"\n\t\tkubeSystemNamespace = \"kube-system\"\n\t)\n\tpods, err := client.Core().Pods(kubeSystemNamespace).List(v1.ListOptions{LabelSelector: apiServerSelector})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(pods.Items) == 0 {\n\t\treturn nil, fmt.Errorf(\"no pods matched the label selector %q in the %s namespace\", apiServerSelector, kubeSystemNamespace)\n\t}\n\treturn pods, nil\n}\n\n\/\/ podsStr prints a comma separated list of namespaced Pod names\nfunc podsStr(pods []v1.Pod) (out string) {\n\tfor n, p := range pods {\n\t\t\/\/ add comma to all entries except first\n\t\tif n != 0 {\n\t\t\tout += \", \"\n\t\t}\n\t\tout += fmt.Sprintf(\"%s\/%s\", p.GetNamespace(), p.GetName())\n\t}\n\treturn\n}\n\nfunc nodeReady(node v1.Node) (ok bool) {\n\tfor _, cond := range node.Status.Conditions {\n\t\tif cond.Type == v1.NodeReady {\n\t\t\treturn cond.Status == v1.ConditionTrue\n\t\t}\n\t}\n\treturn false\n}\n<|endoftext|>"}
{"text":"<commit_before>package explorerelations\n\nimport (\n\t\"net\/http\"\n\t\"sort\"\n\n\t\"github.com\/animenotifier\/arn\"\n\n\t\"github.com\/aerogo\/aero\"\n\t\"github.com\/animenotifier\/notify.moe\/components\"\n\t\"github.com\/animenotifier\/notify.moe\/utils\"\n)\n\n\/\/ Sequels ...\nfunc Sequels(ctx *aero.Context) string {\n\tuser := utils.GetUser(ctx)\n\n\tif user == nil {\n\t\treturn ctx.Error(http.StatusUnauthorized, \"Not logged in\", nil)\n\t}\n\n\tanimeList := user.AnimeList()\n\tsequels := []*utils.AnimeWithRelatedAnime{}\n\n\tfor anime := range arn.StreamAnime() {\n\t\tif animeList.Contains(anime.ID) {\n\t\t\tcontinue\n\t\t}\n\n\t\tprequels := anime.Prequels()\n\n\t\tfor _, prequel := range prequels {\n\t\t\titem := animeList.Find(prequel.ID)\n\n\t\t\tif item != nil && item.Status == arn.AnimeListStatusCompleted {\n\t\t\t\tsequels = append(sequels, &utils.AnimeWithRelatedAnime{\n\t\t\t\t\tAnime:   anime,\n\t\t\t\t\tRelated: prequel,\n\t\t\t\t})\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tsort.Slice(sequels, func(i, j int) bool {\n\t\taScore := sequels[i].Anime.Score()\n\t\tbScore := sequels[j].Anime.Score()\n\n\t\tif aScore == bScore {\n\t\t\treturn sequels[i].Anime.Title.Canonical < sequels[j].Anime.Title.Canonical\n\t\t}\n\n\t\treturn aScore > bScore\n\t})\n\n\treturn ctx.HTML(components.ExploreAnimeSequels(sequels, user))\n}\n<commit_msg>Minor fix<commit_after>package explorerelations\n\nimport (\n\t\"net\/http\"\n\t\"sort\"\n\n\t\"github.com\/animenotifier\/arn\"\n\n\t\"github.com\/aerogo\/aero\"\n\t\"github.com\/animenotifier\/notify.moe\/components\"\n\t\"github.com\/animenotifier\/notify.moe\/utils\"\n)\n\n\/\/ Sequels ...\nfunc Sequels(ctx *aero.Context) string {\n\tuser := utils.GetUser(ctx)\n\n\tif user == nil {\n\t\treturn ctx.Error(http.StatusUnauthorized, \"Not logged in\", nil)\n\t}\n\n\tanimeList := user.AnimeList()\n\tsequels := []*utils.AnimeWithRelatedAnime{}\n\n\tfor anime := range arn.StreamAnime() {\n\t\titem := animeList.Find(anime.ID)\n\n\t\t\/\/ Ignore if user added the anime and it's not \"Planned\" status\n\t\tif item != nil && item.Status != arn.AnimeListStatusPlanned {\n\t\t\tcontinue\n\t\t}\n\n\t\tprequels := anime.Prequels()\n\n\t\tfor _, prequel := range prequels {\n\t\t\titem := animeList.Find(prequel.ID)\n\n\t\t\tif item != nil && item.Status == arn.AnimeListStatusCompleted {\n\t\t\t\tsequels = append(sequels, &utils.AnimeWithRelatedAnime{\n\t\t\t\t\tAnime:   anime,\n\t\t\t\t\tRelated: prequel,\n\t\t\t\t})\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tsort.Slice(sequels, func(i, j int) bool {\n\t\taScore := sequels[i].Anime.Score()\n\t\tbScore := sequels[j].Anime.Score()\n\n\t\tif aScore == bScore {\n\t\t\treturn sequels[i].Anime.Title.Canonical < sequels[j].Anime.Title.Canonical\n\t\t}\n\n\t\treturn aScore > bScore\n\t})\n\n\treturn ctx.HTML(components.ExploreAnimeSequels(sequels, user))\n}\n<|endoftext|>"}
{"text":"<commit_before>package utils\n\nimport (\n\t\"io\"\n\t\"net\/http\"\n\t\"net\/textproto\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\/\/ ServeContent replies to the request using the content in the provided\n\/\/ reader. The Content-Length and Content-Type headers are added with the\n\/\/ provided values.\nfunc ServeContent(w http.ResponseWriter, r *http.Request, contentType string, size int64, content io.Reader) {\n\th := w.Header()\n\tif size > 0 {\n\t\th.Set(\"Content-Length\", strconv.FormatInt(size, 10))\n\t}\n\tif contentType != \"\" {\n\t\th.Set(\"Content-Type\", contentType)\n\t}\n\tw.WriteHeader(http.StatusOK)\n\tif r.Method != \"HEAD\" {\n\t\tio.Copy(w, content)\n\t}\n}\n\n\/\/ CheckPreconditions evaluates request preconditions based only on the Etag\n\/\/ values.\nfunc CheckPreconditions(w http.ResponseWriter, r *http.Request, etag string) (done bool) {\n\tif etag != \"\" && !checkIfNoneMatch(w, r, etag) {\n\t\tw.WriteHeader(http.StatusNotModified)\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc checkIfNoneMatch(w http.ResponseWriter, r *http.Request, definedETag string) (match bool) {\n\tinm := r.Header.Get(\"If-None-Match\")\n\tif inm == \"\" {\n\t\treturn false\n\t}\n\tbuf := inm\n\tfor {\n\t\tbuf = textproto.TrimString(buf)\n\t\tif len(buf) == 0 {\n\t\t\tbreak\n\t\t}\n\t\tif buf[0] == ',' {\n\t\t\tbuf = buf[1:]\n\t\t}\n\t\tif buf[0] == '*' {\n\t\t\treturn false\n\t\t}\n\t\tetag, remain := scanETag(buf)\n\t\tif etag == \"\" {\n\t\t\tbreak\n\t\t}\n\t\tif etagWeakMatch(etag, definedETag) {\n\t\t\treturn false\n\t\t}\n\t\tbuf = remain\n\t}\n\treturn true\n}\n\n\/\/ etagWeakMatch reports whether a and b match using weak ETag comparison.\n\/\/ Assumes a and b are valid ETags.\nfunc etagWeakMatch(a, b string) bool {\n\treturn strings.TrimPrefix(a, \"W\/\") == strings.TrimPrefix(b, \"W\/\")\n}\n\n\/\/ etagStrongMatch reports whether a and b match using strong ETag comparison.\n\/\/ Assumes a and b are valid ETags.\nfunc etagStrongMatch(a, b string) bool {\n\treturn a == b && a != \"\" && a[0] == '\"'\n}\n\n\/\/ scanETag determines if a syntactically valid ETag is present at s. If so,\n\/\/ the ETag and remaining text after consuming ETag is returned. Otherwise,\n\/\/ it returns \"\", \"\".\nfunc scanETag(s string) (etag string, remain string) {\n\tstart := 0\n\tif len(s) >= 2 && s[0] == 'W' && s[1] == '\/' {\n\t\tstart = 2\n\t}\n\tif len(s[start:]) < 2 || s[start] != '\"' {\n\t\treturn \"\", \"\"\n\t}\n\t\/\/ ETag is either W\/\"text\" or \"text\".\n\t\/\/ See RFC 7232 2.3.\n\tfor i := start + 1; i < len(s); i++ {\n\t\tc := s[i]\n\t\tswitch {\n\t\t\/\/ Character values allowed in ETags.\n\t\tcase c == 0x21 || c >= 0x23 && c <= 0x7E || c >= 0x80:\n\t\tcase c == '\"':\n\t\t\treturn s[:i+1], s[i+1:]\n\t\tdefault:\n\t\t\treturn \"\", \"\"\n\t\t}\n\t}\n\treturn \"\", \"\"\n}\n<commit_msg>Clearer boolean conditions on If-None-Match<commit_after>package utils\n\nimport (\n\t\"io\"\n\t\"net\/http\"\n\t\"net\/textproto\"\n\t\"strconv\"\n\t\"strings\"\n)\n\n\/\/ ServeContent replies to the request using the content in the provided\n\/\/ reader. The Content-Length and Content-Type headers are added with the\n\/\/ provided values.\nfunc ServeContent(w http.ResponseWriter, r *http.Request, contentType string, size int64, content io.Reader) {\n\th := w.Header()\n\tif size > 0 {\n\t\th.Set(\"Content-Length\", strconv.FormatInt(size, 10))\n\t}\n\tif contentType != \"\" {\n\t\th.Set(\"Content-Type\", contentType)\n\t}\n\tw.WriteHeader(http.StatusOK)\n\tif r.Method != \"HEAD\" {\n\t\tio.Copy(w, content)\n\t}\n}\n\n\/\/ CheckPreconditions evaluates request preconditions based only on the Etag\n\/\/ values.\nfunc CheckPreconditions(w http.ResponseWriter, r *http.Request, etag string) (done bool) {\n\tif etag != \"\" && checkIfNoneMatch(w, r, etag) {\n\t\twriteNotModified(w)\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc checkIfNoneMatch(w http.ResponseWriter, r *http.Request, definedETag string) (match bool) {\n\tinm := r.Header.Get(\"If-None-Match\")\n\tif inm == \"\" {\n\t\treturn false\n\t}\n\tbuf := inm\n\tfor {\n\t\tbuf = textproto.TrimString(buf)\n\t\tif len(buf) == 0 {\n\t\t\tbreak\n\t\t}\n\t\tif buf[0] == ',' {\n\t\t\tbuf = buf[1:]\n\t\t}\n\t\tif buf[0] == '*' {\n\t\t\treturn true\n\t\t}\n\t\tetag, remain := scanETag(buf)\n\t\tif etag == \"\" {\n\t\t\tbreak\n\t\t}\n\t\tif etagWeakMatch(etag, definedETag) {\n\t\t\treturn true\n\t\t}\n\t\tbuf = remain\n\t}\n\treturn false\n}\n\n\/\/ etagWeakMatch reports whether a and b match using weak ETag comparison.\n\/\/ Assumes a and b are valid ETags.\nfunc etagWeakMatch(a, b string) bool {\n\treturn strings.TrimPrefix(a, \"W\/\") == strings.TrimPrefix(b, \"W\/\")\n}\n\n\/\/ etagStrongMatch reports whether a and b match using strong ETag comparison.\n\/\/ Assumes a and b are valid ETags.\nfunc etagStrongMatch(a, b string) bool {\n\treturn a == b && a != \"\" && a[0] == '\"'\n}\n\n\/\/ scanETag determines if a syntactically valid ETag is present at s. If so,\n\/\/ the ETag and remaining text after consuming ETag is returned. Otherwise,\n\/\/ it returns \"\", \"\".\nfunc scanETag(s string) (etag string, remain string) {\n\tstart := 0\n\tif len(s) >= 2 && s[0] == 'W' && s[1] == '\/' {\n\t\tstart = 2\n\t}\n\tif len(s[start:]) < 2 || s[start] != '\"' {\n\t\treturn \"\", \"\"\n\t}\n\t\/\/ ETag is either W\/\"text\" or \"text\".\n\t\/\/ See RFC 7232 2.3.\n\tfor i := start + 1; i < len(s); i++ {\n\t\tc := s[i]\n\t\tswitch {\n\t\t\/\/ Character values allowed in ETags.\n\t\tcase c == 0x21 || c >= 0x23 && c <= 0x7E || c >= 0x80:\n\t\tcase c == '\"':\n\t\t\treturn s[:i+1], s[i+1:]\n\t\tdefault:\n\t\t\treturn \"\", \"\"\n\t\t}\n\t}\n\treturn \"\", \"\"\n}\n\nfunc writeNotModified(w http.ResponseWriter) {\n\th := w.Header()\n\tdelete(h, \"Content-Type\")\n\tdelete(h, \"Content-Length\")\n\tw.WriteHeader(http.StatusNotModified)\n}\n<|endoftext|>"}
{"text":"<commit_before>package check\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/optiopay\/kafka\/proto\"\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/samuel\/go-zookeeper\/zk\"\n)\n\nfunc (check *HealthCheck) connect(firstConnection bool, stop <-chan struct{}) error {\n\tvar createHealthTopicIfMissing = firstConnection\n\tvar createReplicationTopicIfMissing = firstConnection\n\tticker := time.NewTicker(check.config.retryInterval)\n\tdefer ticker.Stop()\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tif err := check.tryConnectOnce(&createHealthTopicIfMissing, &createReplicationTopicIfMissing); err == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\tcase <-stop:\n\t\t\treturn errors.New(\"connect was asked to stop\")\n\t\t}\n\t}\n}\n\nfunc (check *HealthCheck) tryConnectOnce(createBrokerTopic, createReplicationTopic *bool) error {\n\tpauseTime := check.config.retryInterval\n\t\/\/ connect to kafka cluster\n\tconnectString := []string{fmt.Sprintf(\"%s:%d\", check.config.brokerHost, check.config.brokerPort)}\n\terr := check.broker.Dial(connectString, check.brokerConfig())\n\tif err != nil {\n\t\tlog.Printf(\"unable to connect to broker, retrying in %s (%s)\", pauseTime.String(), err)\n\t\treturn err\n\t}\n\n\tmetadata, err := check.broker.Metadata()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failure retrieving metadata\")\n\t}\n\n\tcheck.partitionID, err = check.findPartitionID(check.config.topicName, true, createBrokerTopic, metadata)\n\tif err != nil {\n\t\tlog.Printf(\"%s retrying in %s\", err.Error(), pauseTime)\n\t\tcheck.broker.Close()\n\t\treturn err\n\t}\n\n\tcheck.replicationPartitionID, err = check.findPartitionID(check.config.replicationTopicName, false, createReplicationTopic, metadata)\n\tif err != nil {\n\t\tlog.Printf(\"%s retrying in %s\", err.Error(), pauseTime)\n\t\tcheck.broker.Close()\n\t\treturn err\n\t}\n\n\tconsumer, err := check.broker.Consumer(check.consumerConfig())\n\tif err != nil {\n\t\tlog.Printf(\"unable to create consumer, retrying in %s: %s\", pauseTime.String(), err)\n\t\tcheck.broker.Close()\n\t\treturn err\n\t}\n\n\tproducer := check.broker.Producer(check.producerConfig())\n\n\tcheck.consumer = consumer\n\tcheck.producer = producer\n\treturn nil\n}\n\nfunc (check *HealthCheck) findPartitionID(topicName string, forHealthCheck bool, createIfMissing *bool, metadata *proto.MetadataResp) (int32, error) {\n\tbrokerID := int32(check.config.brokerID)\n\n\tif !brokerExists(brokerID, metadata) {\n\t\treturn 0, fmt.Errorf(\"unable to find broker %d in metadata\", brokerID)\n\t}\n\n\ttopic, ok := findTopic(topicName, metadata)\n\n\tif ok {\n\t\tfor _, partition := range topic.Partitions {\n\t\t\tif forHealthCheck && partition.Leader != brokerID {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif !contains(partition.Replicas, brokerID) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tlog.Printf(`found partition id %d for broker %d in topic \"%s\"`, partition.ID, brokerID, topicName)\n\t\t\treturn partition.ID, nil\n\t\t}\n\t}\n\n\tif *createIfMissing {\n\t\terr := check.createTopic(topicName, forHealthCheck)\n\t\tif err != nil {\n\t\t\treturn 0, errors.Wrapf(err, `unable to create topic \"%s\"`, topicName)\n\t\t}\n\t\tlog.Printf(`topic \"%s\" created`, topicName)\n\t\t*createIfMissing = false\n\t\treturn 0, errors.New(\"topic created, try again\")\n\t}\n\n\tif ok {\n\t\treturn 0, fmt.Errorf(`Unable to find broker's parition in topic \"%s\" in metadata`, topicName)\n\t} else {\n\t\treturn 0, fmt.Errorf(`Unable to find broker's topic \"%s\" in metadata`, topicName)\n\t}\n}\n\nfunc findTopic(name string, metadata *proto.MetadataResp) (*proto.MetadataRespTopic, bool) {\n\tfor _, topic := range metadata.Topics {\n\t\tif topic.Name == name {\n\t\t\treturn &topic, true\n\t\t}\n\t}\n\n\treturn nil, false\n}\n\nfunc brokerExists(brokerID int32, metadata *proto.MetadataResp) bool {\n\tfor _, broker := range metadata.Brokers {\n\t\tif broker.NodeID == brokerID {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc zookeeperEnsembleAndChroot(connectString string) (ensemble []string, chroot string) {\n\tresult := strings.Split(connectString, \"\/\")\n\tswitch len(result) {\n\tcase 1:\n\t\tensemble = strings.Split(result[0], \",\")\n\t\tchroot = \"\"\n\tdefault:\n\t\tensemble = strings.Split(result[0], \",\")\n\t\tchroot = \"\/\" + strings.Join(result[1:], \"\/\")\n\t\tif strings.HasSuffix(chroot, \"\/\") {\n\t\t\tchroot = chroot[:len(chroot)-1]\n\t\t}\n\t}\n\treturn\n}\n\nfunc (check *HealthCheck) createTopic(name string, forHealthCheck bool) (err error) {\n\tlog.Printf(\"connecting to ZooKeeper ensemble %s\", check.config.zookeeperConnect)\n\tconnectString, chroot := zookeeperEnsembleAndChroot(check.config.zookeeperConnect)\n\tzkConn := check.zookeeper\n\n\tif _, err = zkConn.Connect(connectString, 10*time.Second); err != nil {\n\t\treturn\n\t}\n\tdefer zkConn.Close()\n\n\ttopicPath := chroot + \"\/config\/topics\/\" + name\n\n\texists := false\n\tif !forHealthCheck {\n\t\texists, _, err = zkConn.Exists(topicPath)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\tbrokerID := int32(check.config.brokerID)\n\n\tif !exists {\n\t\ttopicConfig := `{\"version\":1,\"config\":{\"delete.retention.ms\":\"10000\",` +\n\t\t\t`\"cleanup.policy\":\"delete\",\"compression.type\":\"uncompressed\"}}`\n\t\tlog.Infof(`creating topic \"%s\" configuration node`, name)\n\n\t\tif err = createZkNode(zkConn, topicPath, topicConfig, forHealthCheck); err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tpartitionAssignment := fmt.Sprintf(`{\"version\":1,\"partitions\":{\"0\":[%d]}}`, brokerID)\n\t\tlog.Infof(`creating topic \"%s\" partition assignment node`, name)\n\n\t\tif err = createZkNode(zkConn, chroot+\"\/brokers\/topics\/\"+name, partitionAssignment, forHealthCheck); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\tif !forHealthCheck {\n\t\terr = maybeExpandReplicationTopic(zkConn, brokerID, check.replicationPartitionID, name, chroot)\n\t}\n\n\treturn\n\n}\n\nfunc maybeExpandReplicationTopic(zk ZkConnection, brokerID, partitionID int32, topicName, chroot string) error {\n\ttopic := ZkTopic{Name: topicName}\n\terr := zkPartitions(&topic, zk, topicName, chroot)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Unable to determine if replication topic should be expanded\")\n\t}\n\n\treplicas, ok := topic.Partitions[partitionID]\n\tif !ok {\n\t\treturn fmt.Errorf(`Cannot find partition with ID %d in topic \"%s\"`, partitionID, topicName)\n\t}\n\n\tif !contains(replicas, brokerID) {\n\t\tlog.Info(\"Expanding replication check topic to include broker \", brokerID)\n\t\treplicas = append(replicas, brokerID)\n\n\t\treturn reassignPartition(zk, partitionID, replicas, topicName, chroot)\n\t}\n\treturn nil\n}\n\nfunc reassignPartition(zk ZkConnection, partitionID int32, replicas []int32, topicName, chroot string) (err error) {\n\n\trepeat := true\n\tfor repeat {\n\t\ttime.Sleep(1 * time.Second)\n\t\texists, _, rp_err := zk.Exists(chroot + \"\/admin\/reassign_partitions\")\n\t\tif rp_err != nil {\n\t\t\tlog.Warn(\"Error while checking if reassign_partitions node exists\", err)\n\t\t}\n\t\trepeat = exists || err != nil\n\t}\n\n\tvar replicasStr []string\n\tfor _, ID := range replicas {\n\t\treplicasStr = append(replicasStr, fmt.Sprintf(\"%d\", ID))\n\t}\n\n\treassign := fmt.Sprintf(`{\"version\":1,\"partitions\":[{\"topic\":\"%s\",\"partition\":%d,\"replicas\":[%s]}]}`,\n\t\ttopicName, partitionID, strings.Join(replicasStr, \",\"))\n\n\trepeat = true\n\tfor repeat {\n\t\tlog.Info(\"Creating reassign partition node\")\n\t\terr = createZkNode(zk, chroot+\"\/admin\/reassign_partitions\", reassign, true)\n\t\tif err != nil {\n\t\t\tlog.Warn(\"Error while creating reassignment node\", err)\n\t\t}\n\t\trepeat = err != nil\n\t}\n\n\treturn\n}\n\nfunc createZkNode(zookeeper ZkConnection, path string, content string, failIfExists bool) error {\n\tnodeExists, _, err := zookeeper.Exists(path)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif nodeExists {\n\t\tif failIfExists {\n\t\t\treturn fmt.Errorf(\"node %s cannot be created, exists already\", path)\n\t\t}\n\t\treturn nil\n\t}\n\n\tlog.Println(\"creating node\", path)\n\tflags := int32(0) \/\/ permanent node.\n\tacl := zk.WorldACL(zk.PermAll)\n\t_, err = zookeeper.Create(path, []byte(content), flags, acl)\n\treturn err\n}\n\nfunc (check *HealthCheck) closeConnection(deleteTopicIfPresent bool) {\n\tif deleteTopicIfPresent {\n\t\tlog.Infof(\"connecting to ZooKeeper ensemble %s\", check.config.zookeeperConnect)\n\t\tconnectString, chroot := zookeeperEnsembleAndChroot(check.config.zookeeperConnect)\n\n\t\tzkConn := check.zookeeper\n\t\t_, err := zkConn.Connect(connectString, 10*time.Second)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tdefer zkConn.Close()\n\n\t\tcheck.deleteTopic(zkConn, chroot, check.config.topicName, check.partitionID)\n\t\tcheck.deleteTopic(zkConn, chroot, check.config.replicationTopicName, check.replicationPartitionID)\n\t}\n\tcheck.broker.Close()\n}\n\nfunc (check *HealthCheck) deleteTopic(zkConn ZkConnection, chroot, name string, partitionID int32) error {\n\ttopic := ZkTopic{Name: name}\n\terr := zkPartitions(&topic, zkConn, name, chroot)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treplicas, ok := topic.Partitions[partitionID]\n\tif !ok {\n\t\treturn fmt.Errorf(`Cannot find partition with ID %d in topic \"%s\"`, partitionID, name)\n\t}\n\n\tbrokerID := int32(check.config.brokerID)\n\tif len(replicas) > 1 {\n\t\tlog.Info(\"Shrinking replication check topic to exclude broker \", brokerID)\n\t\treplicas = delAll(replicas, brokerID)\n\t\treturn reassignPartition(zkConn, partitionID, replicas, name, chroot)\n\t}\n\n\tdelTopicPath := chroot + \"\/admin\/delete_topics\/\" + name\n\n\terr = createZkNode(check.zookeeper, delTopicPath, \"\", true)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn check.waitForTopicDeletion(delTopicPath)\n}\n\nfunc (check *HealthCheck) waitForTopicDeletion(topicPath string) error {\n\tfor {\n\t\texists, _, err := check.zookeeper.Exists(topicPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !exists {\n\t\t\treturn nil\n\t\t}\n\t\ttime.Sleep(check.config.retryInterval)\n\t}\n}\n\nfunc (check *HealthCheck) reconnect(stop <-chan struct{}) error {\n\tcheck.closeConnection(false)\n\treturn check.connect(false, stop)\n}\n<commit_msg>Set min.insync.replicas on topic creation<commit_after>package check\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/optiopay\/kafka\/proto\"\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/samuel\/go-zookeeper\/zk\"\n)\n\nfunc (check *HealthCheck) connect(firstConnection bool, stop <-chan struct{}) error {\n\tvar createHealthTopicIfMissing = firstConnection\n\tvar createReplicationTopicIfMissing = firstConnection\n\tticker := time.NewTicker(check.config.retryInterval)\n\tdefer ticker.Stop()\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tif err := check.tryConnectOnce(&createHealthTopicIfMissing, &createReplicationTopicIfMissing); err == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\tcase <-stop:\n\t\t\treturn errors.New(\"connect was asked to stop\")\n\t\t}\n\t}\n}\n\nfunc (check *HealthCheck) tryConnectOnce(createBrokerTopic, createReplicationTopic *bool) error {\n\tpauseTime := check.config.retryInterval\n\t\/\/ connect to kafka cluster\n\tconnectString := []string{fmt.Sprintf(\"%s:%d\", check.config.brokerHost, check.config.brokerPort)}\n\terr := check.broker.Dial(connectString, check.brokerConfig())\n\tif err != nil {\n\t\tlog.Printf(\"unable to connect to broker, retrying in %s (%s)\", pauseTime.String(), err)\n\t\treturn err\n\t}\n\n\tmetadata, err := check.broker.Metadata()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failure retrieving metadata\")\n\t}\n\n\tcheck.partitionID, err = check.findPartitionID(check.config.topicName, true, createBrokerTopic, metadata)\n\tif err != nil {\n\t\tlog.Printf(\"%s retrying in %s\", err.Error(), pauseTime)\n\t\tcheck.broker.Close()\n\t\treturn err\n\t}\n\n\tcheck.replicationPartitionID, err = check.findPartitionID(check.config.replicationTopicName, false, createReplicationTopic, metadata)\n\tif err != nil {\n\t\tlog.Printf(\"%s retrying in %s\", err.Error(), pauseTime)\n\t\tcheck.broker.Close()\n\t\treturn err\n\t}\n\n\tconsumer, err := check.broker.Consumer(check.consumerConfig())\n\tif err != nil {\n\t\tlog.Printf(\"unable to create consumer, retrying in %s: %s\", pauseTime.String(), err)\n\t\tcheck.broker.Close()\n\t\treturn err\n\t}\n\n\tproducer := check.broker.Producer(check.producerConfig())\n\n\tcheck.consumer = consumer\n\tcheck.producer = producer\n\treturn nil\n}\n\nfunc (check *HealthCheck) findPartitionID(topicName string, forHealthCheck bool, createIfMissing *bool, metadata *proto.MetadataResp) (int32, error) {\n\tbrokerID := int32(check.config.brokerID)\n\n\tif !brokerExists(brokerID, metadata) {\n\t\treturn 0, fmt.Errorf(\"unable to find broker %d in metadata\", brokerID)\n\t}\n\n\ttopic, ok := findTopic(topicName, metadata)\n\n\tif ok {\n\t\tfor _, partition := range topic.Partitions {\n\t\t\tif forHealthCheck && partition.Leader != brokerID {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif !contains(partition.Replicas, brokerID) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tlog.Printf(`found partition id %d for broker %d in topic \"%s\"`, partition.ID, brokerID, topicName)\n\t\t\treturn partition.ID, nil\n\t\t}\n\t}\n\n\tif *createIfMissing {\n\t\terr := check.createTopic(topicName, forHealthCheck)\n\t\tif err != nil {\n\t\t\treturn 0, errors.Wrapf(err, `unable to create topic \"%s\"`, topicName)\n\t\t}\n\t\tlog.Printf(`topic \"%s\" created`, topicName)\n\t\t*createIfMissing = false\n\t\treturn 0, errors.New(\"topic created, try again\")\n\t}\n\n\tif ok {\n\t\treturn 0, fmt.Errorf(`Unable to find broker's parition in topic \"%s\" in metadata`, topicName)\n\t} else {\n\t\treturn 0, fmt.Errorf(`Unable to find broker's topic \"%s\" in metadata`, topicName)\n\t}\n}\n\nfunc findTopic(name string, metadata *proto.MetadataResp) (*proto.MetadataRespTopic, bool) {\n\tfor _, topic := range metadata.Topics {\n\t\tif topic.Name == name {\n\t\t\treturn &topic, true\n\t\t}\n\t}\n\n\treturn nil, false\n}\n\nfunc brokerExists(brokerID int32, metadata *proto.MetadataResp) bool {\n\tfor _, broker := range metadata.Brokers {\n\t\tif broker.NodeID == brokerID {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc zookeeperEnsembleAndChroot(connectString string) (ensemble []string, chroot string) {\n\tresult := strings.Split(connectString, \"\/\")\n\tswitch len(result) {\n\tcase 1:\n\t\tensemble = strings.Split(result[0], \",\")\n\t\tchroot = \"\"\n\tdefault:\n\t\tensemble = strings.Split(result[0], \",\")\n\t\tchroot = \"\/\" + strings.Join(result[1:], \"\/\")\n\t\tif strings.HasSuffix(chroot, \"\/\") {\n\t\t\tchroot = chroot[:len(chroot)-1]\n\t\t}\n\t}\n\treturn\n}\n\nfunc (check *HealthCheck) createTopic(name string, forHealthCheck bool) (err error) {\n\tlog.Printf(\"connecting to ZooKeeper ensemble %s\", check.config.zookeeperConnect)\n\tconnectString, chroot := zookeeperEnsembleAndChroot(check.config.zookeeperConnect)\n\tzkConn := check.zookeeper\n\n\tif _, err = zkConn.Connect(connectString, 10*time.Second); err != nil {\n\t\treturn\n\t}\n\tdefer zkConn.Close()\n\n\ttopicPath := chroot + \"\/config\/topics\/\" + name\n\n\texists := false\n\tif !forHealthCheck {\n\t\texists, _, err = zkConn.Exists(topicPath)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\tbrokerID := int32(check.config.brokerID)\n\n\tif !exists {\n\t\ttopicConfig := `{\"version\":1,\"config\":{\"delete.retention.ms\":\"10000\",` +\n\t\t\t`\"cleanup.policy\":\"delete\",\"compression.type\":\"uncompressed\",` +\n\t\t\t`\"min.insync.replicas\":\"1\"}}`\n\t\tlog.Infof(`creating topic \"%s\" configuration node`, name)\n\n\t\tif err = createZkNode(zkConn, topicPath, topicConfig, forHealthCheck); err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tpartitionAssignment := fmt.Sprintf(`{\"version\":1,\"partitions\":{\"0\":[%d]}}`, brokerID)\n\t\tlog.Infof(`creating topic \"%s\" partition assignment node`, name)\n\n\t\tif err = createZkNode(zkConn, chroot+\"\/brokers\/topics\/\"+name, partitionAssignment, forHealthCheck); err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\tif !forHealthCheck {\n\t\terr = maybeExpandReplicationTopic(zkConn, brokerID, check.replicationPartitionID, name, chroot)\n\t}\n\n\treturn\n\n}\n\nfunc maybeExpandReplicationTopic(zk ZkConnection, brokerID, partitionID int32, topicName, chroot string) error {\n\ttopic := ZkTopic{Name: topicName}\n\terr := zkPartitions(&topic, zk, topicName, chroot)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Unable to determine if replication topic should be expanded\")\n\t}\n\n\treplicas, ok := topic.Partitions[partitionID]\n\tif !ok {\n\t\treturn fmt.Errorf(`Cannot find partition with ID %d in topic \"%s\"`, partitionID, topicName)\n\t}\n\n\tif !contains(replicas, brokerID) {\n\t\tlog.Info(\"Expanding replication check topic to include broker \", brokerID)\n\t\treplicas = append(replicas, brokerID)\n\n\t\treturn reassignPartition(zk, partitionID, replicas, topicName, chroot)\n\t}\n\treturn nil\n}\n\nfunc reassignPartition(zk ZkConnection, partitionID int32, replicas []int32, topicName, chroot string) (err error) {\n\n\trepeat := true\n\tfor repeat {\n\t\ttime.Sleep(1 * time.Second)\n\t\texists, _, rp_err := zk.Exists(chroot + \"\/admin\/reassign_partitions\")\n\t\tif rp_err != nil {\n\t\t\tlog.Warn(\"Error while checking if reassign_partitions node exists\", err)\n\t\t}\n\t\trepeat = exists || err != nil\n\t}\n\n\tvar replicasStr []string\n\tfor _, ID := range replicas {\n\t\treplicasStr = append(replicasStr, fmt.Sprintf(\"%d\", ID))\n\t}\n\n\treassign := fmt.Sprintf(`{\"version\":1,\"partitions\":[{\"topic\":\"%s\",\"partition\":%d,\"replicas\":[%s]}]}`,\n\t\ttopicName, partitionID, strings.Join(replicasStr, \",\"))\n\n\trepeat = true\n\tfor repeat {\n\t\tlog.Info(\"Creating reassign partition node\")\n\t\terr = createZkNode(zk, chroot+\"\/admin\/reassign_partitions\", reassign, true)\n\t\tif err != nil {\n\t\t\tlog.Warn(\"Error while creating reassignment node\", err)\n\t\t}\n\t\trepeat = err != nil\n\t}\n\n\treturn\n}\n\nfunc createZkNode(zookeeper ZkConnection, path string, content string, failIfExists bool) error {\n\tnodeExists, _, err := zookeeper.Exists(path)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif nodeExists {\n\t\tif failIfExists {\n\t\t\treturn fmt.Errorf(\"node %s cannot be created, exists already\", path)\n\t\t}\n\t\treturn nil\n\t}\n\n\tlog.Println(\"creating node\", path)\n\tflags := int32(0) \/\/ permanent node.\n\tacl := zk.WorldACL(zk.PermAll)\n\t_, err = zookeeper.Create(path, []byte(content), flags, acl)\n\treturn err\n}\n\nfunc (check *HealthCheck) closeConnection(deleteTopicIfPresent bool) {\n\tif deleteTopicIfPresent {\n\t\tlog.Infof(\"connecting to ZooKeeper ensemble %s\", check.config.zookeeperConnect)\n\t\tconnectString, chroot := zookeeperEnsembleAndChroot(check.config.zookeeperConnect)\n\n\t\tzkConn := check.zookeeper\n\t\t_, err := zkConn.Connect(connectString, 10*time.Second)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tdefer zkConn.Close()\n\n\t\tcheck.deleteTopic(zkConn, chroot, check.config.topicName, check.partitionID)\n\t\tcheck.deleteTopic(zkConn, chroot, check.config.replicationTopicName, check.replicationPartitionID)\n\t}\n\tcheck.broker.Close()\n}\n\nfunc (check *HealthCheck) deleteTopic(zkConn ZkConnection, chroot, name string, partitionID int32) error {\n\ttopic := ZkTopic{Name: name}\n\terr := zkPartitions(&topic, zkConn, name, chroot)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treplicas, ok := topic.Partitions[partitionID]\n\tif !ok {\n\t\treturn fmt.Errorf(`Cannot find partition with ID %d in topic \"%s\"`, partitionID, name)\n\t}\n\n\tbrokerID := int32(check.config.brokerID)\n\tif len(replicas) > 1 {\n\t\tlog.Info(\"Shrinking replication check topic to exclude broker \", brokerID)\n\t\treplicas = delAll(replicas, brokerID)\n\t\treturn reassignPartition(zkConn, partitionID, replicas, name, chroot)\n\t}\n\n\tdelTopicPath := chroot + \"\/admin\/delete_topics\/\" + name\n\n\terr = createZkNode(check.zookeeper, delTopicPath, \"\", true)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn check.waitForTopicDeletion(delTopicPath)\n}\n\nfunc (check *HealthCheck) waitForTopicDeletion(topicPath string) error {\n\tfor {\n\t\texists, _, err := check.zookeeper.Exists(topicPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !exists {\n\t\t\treturn nil\n\t\t}\n\t\ttime.Sleep(check.config.retryInterval)\n\t}\n}\n\nfunc (check *HealthCheck) reconnect(stop <-chan struct{}) error {\n\tcheck.closeConnection(false)\n\treturn check.connect(false, stop)\n}\n<|endoftext|>"}
{"text":"<commit_before>package api\n\nimport (\n\tapiv1 \"k8s.io\/client-go\/pkg\/api\/v1\"\n)\n\n\/\/ StorageSpec defines storage provisioning\ntype StorageSpec struct {\n\t\/\/ Name of the StorageClass to use when requesting storage provisioning.\n\tClass string `json:\"class\"`\n\t\/\/ Persistent Volume Claim\n\tapiv1.PersistentVolumeClaimSpec `json:\",inline,omitempty\"`\n}\n\ntype InitSpec struct {\n\tScriptSource   *ScriptSourceSpec   `json:\"scriptSource,omitempty\"`\n\tSnapshotSource *SnapshotSourceSpec `json:\"snapshotSource,omitempty\"`\n}\n\ntype ScriptSourceSpec struct {\n\tScriptPath         string `json:\"scriptPath,omitempty\"`\n\tapiv1.VolumeSource `json:\",inline,omitempty\"`\n}\n\ntype SnapshotSourceSpec struct {\n\tNamespace string `json:\"namespace,omitempty\"`\n\tName      string `json:\"name,omitempty\"`\n}\n\ntype BackupScheduleSpec struct {\n\tCronExpression      string `json:\"cronExpression,omitempty\"`\n\tSnapshotStorageSpec `json:\",inline,omitempty\"`\n\t\/\/ Compute Resources required by the sidecar container.\n\tResources apiv1.ResourceRequirements `json:\"resources,omitempty\"`\n}\n\nconst (\n\tAWS_ACCESS_KEY_ID     = \"AWS_ACCESS_KEY_ID\"\n\tAWS_SECRET_ACCESS_KEY = \"AWS_SECRET_ACCESS_KEY\"\n\n\tGOOGLE_PROJECT_ID               = \"GOOGLE_PROJECT_ID\"\n\tGOOGLE_SERVICE_ACCOUNT_JSON_KEY = \"GOOGLE_SERVICE_ACCOUNT_JSON_KEY\"\n\n\tAZURE_ACCOUNT_NAME = \"AZURE_ACCOUNT_NAME\"\n\tAZURE_ACCOUNT_KEY  = \"AZURE_ACCOUNT_KEY\"\n\n\t\/\/ swift\n\tOS_USERNAME    = \"OS_USERNAME\"\n\tOS_PASSWORD    = \"OS_PASSWORD\"\n\tOS_REGION_NAME = \"OS_REGION_NAME\"\n\tOS_AUTH_URL    = \"OS_AUTH_URL\"\n\n\t\/\/ v3 specific\n\tOS_USER_DOMAIN_NAME    = \"OS_USER_DOMAIN_NAME\"\n\tOS_PROJECT_NAME        = \"OS_PROJECT_NAME\"\n\tOS_PROJECT_DOMAIN_NAME = \"OS_PROJECT_DOMAIN_NAME\"\n\n\t\/\/ v2 specific\n\tOS_TENANT_ID   = \"OS_TENANT_ID\"\n\tOS_TENANT_NAME = \"OS_TENANT_NAME\"\n\n\t\/\/ v1 specific\n\tST_AUTH = \"ST_AUTH\"\n\tST_USER = \"ST_USER\"\n\tST_KEY  = \"ST_KEY\"\n\n\t\/\/ Manual authentication\n\tOS_STORAGE_URL = \"OS_STORAGE_URL\"\n\tOS_AUTH_TOKEN  = \"OS_AUTH_TOKEN\"\n)\n\ntype SnapshotStorageSpec struct {\n\tStorageSecretName string `json:\"storageSecretName,omitempty\"`\n\n\tLocal *LocalSpec `json:\"local\"`\n\tS3    *S3Spec    `json:\"s3,omitempty\"`\n\tGCS   *GCSSpec   `json:\"gcs,omitempty\"`\n\tAzure *AzureSpec `json:\"azure,omitempty\"`\n\tSwift *SwiftSpec `json:\"swift,omitempty\"`\n}\n\ntype LocalSpec struct {\n\tVolume apiv1.Volume `json:\"volume,omitempty\"`\n\tPath   string       `json:\"path,omitempty\"`\n}\n\ntype S3Spec struct {\n\tEndpoint string `json:\"endpoint,omitempty\"`\n\tBucket   string `json:\"bucket,omiempty\"`\n\tPrefix   string `json:\"prefix,omitempty\"`\n}\n\ntype GCSSpec struct {\n\tLocation string `json:\"location,omitempty\"`\n\tBucket   string `json:\"bucket,omiempty\"`\n\tPrefix   string `json:\"prefix,omitempty\"`\n}\n\ntype AzureSpec struct {\n\tContainer string `json:\"container,omitempty\"`\n\tPrefix    string `json:\"prefix,omitempty\"`\n}\n\ntype SwiftSpec struct {\n\tContainer string `json:\"container,omitempty\"`\n\tPrefix    string `json:\"prefix,omitempty\"`\n}\n\ntype MonitorSpec struct {\n\t\/\/ Valid values: coreos-prometheus-operator\n\tAgent      string          `json:\"agent,omitempty\"`\n\tPrometheus *PrometheusSpec `json:\"prometheus,omitempty\"`\n}\n\ntype PrometheusSpec struct {\n\t\/\/ Namespace of Prometheus. Service monitors will be created in this namespace.\n\tNamespace string `json:\"namespace,omitempty\"`\n\t\/\/ Labels are key value pairs that is used to select Prometheus instance via ServiceMonitor labels.\n\t\/\/ +optional\n\tLabels map[string]string `json:\"labels,omitempty\"`\n\n\t\/\/ Interval at which metrics should be scraped\n\tInterval string `json:\"interval,omitempty\"`\n\n\t\/\/ Parameters are key value pairs that are passed as flags to exporters.\n\t\/\/ Parameters map[string]string `json:\"parameters,omitempty\"`\n}\n\ntype DatabasePhase string\n\nconst (\n\t\/\/ used for Databases that are currently running\n\tDatabasePhaseRunning DatabasePhase = \"Running\"\n\t\/\/ used for Databases that are currently creating\n\tDatabasePhaseCreating DatabasePhase = \"Creating\"\n\t\/\/ used for Databases that are currently initializing\n\tDatabasePhaseInitializing DatabasePhase = \"Initializing\"\n\t\/\/ used for Databases that are Failed\n\tDatabasePhaseFailed DatabasePhase = \"Failed\"\n)\n<commit_msg>Use VolumeSource instead of Volume for LocalSpec.<commit_after>package api\n\nimport (\n\tapiv1 \"k8s.io\/client-go\/pkg\/api\/v1\"\n)\n\n\/\/ StorageSpec defines storage provisioning\ntype StorageSpec struct {\n\t\/\/ Name of the StorageClass to use when requesting storage provisioning.\n\tClass string `json:\"class\"`\n\t\/\/ Persistent Volume Claim\n\tapiv1.PersistentVolumeClaimSpec `json:\",inline,omitempty\"`\n}\n\ntype InitSpec struct {\n\tScriptSource   *ScriptSourceSpec   `json:\"scriptSource,omitempty\"`\n\tSnapshotSource *SnapshotSourceSpec `json:\"snapshotSource,omitempty\"`\n}\n\ntype ScriptSourceSpec struct {\n\tScriptPath         string `json:\"scriptPath,omitempty\"`\n\tapiv1.VolumeSource `json:\",inline,omitempty\"`\n}\n\ntype SnapshotSourceSpec struct {\n\tNamespace string `json:\"namespace,omitempty\"`\n\tName      string `json:\"name,omitempty\"`\n}\n\ntype BackupScheduleSpec struct {\n\tCronExpression      string `json:\"cronExpression,omitempty\"`\n\tSnapshotStorageSpec `json:\",inline,omitempty\"`\n\t\/\/ Compute Resources required by the sidecar container.\n\tResources apiv1.ResourceRequirements `json:\"resources,omitempty\"`\n}\n\nconst (\n\tAWS_ACCESS_KEY_ID     = \"AWS_ACCESS_KEY_ID\"\n\tAWS_SECRET_ACCESS_KEY = \"AWS_SECRET_ACCESS_KEY\"\n\n\tGOOGLE_PROJECT_ID               = \"GOOGLE_PROJECT_ID\"\n\tGOOGLE_SERVICE_ACCOUNT_JSON_KEY = \"GOOGLE_SERVICE_ACCOUNT_JSON_KEY\"\n\n\tAZURE_ACCOUNT_NAME = \"AZURE_ACCOUNT_NAME\"\n\tAZURE_ACCOUNT_KEY  = \"AZURE_ACCOUNT_KEY\"\n\n\t\/\/ swift\n\tOS_USERNAME    = \"OS_USERNAME\"\n\tOS_PASSWORD    = \"OS_PASSWORD\"\n\tOS_REGION_NAME = \"OS_REGION_NAME\"\n\tOS_AUTH_URL    = \"OS_AUTH_URL\"\n\n\t\/\/ v3 specific\n\tOS_USER_DOMAIN_NAME    = \"OS_USER_DOMAIN_NAME\"\n\tOS_PROJECT_NAME        = \"OS_PROJECT_NAME\"\n\tOS_PROJECT_DOMAIN_NAME = \"OS_PROJECT_DOMAIN_NAME\"\n\n\t\/\/ v2 specific\n\tOS_TENANT_ID   = \"OS_TENANT_ID\"\n\tOS_TENANT_NAME = \"OS_TENANT_NAME\"\n\n\t\/\/ v1 specific\n\tST_AUTH = \"ST_AUTH\"\n\tST_USER = \"ST_USER\"\n\tST_KEY  = \"ST_KEY\"\n\n\t\/\/ Manual authentication\n\tOS_STORAGE_URL = \"OS_STORAGE_URL\"\n\tOS_AUTH_TOKEN  = \"OS_AUTH_TOKEN\"\n)\n\ntype SnapshotStorageSpec struct {\n\tStorageSecretName string `json:\"storageSecretName,omitempty\"`\n\n\tLocal *LocalSpec `json:\"local\"`\n\tS3    *S3Spec    `json:\"s3,omitempty\"`\n\tGCS   *GCSSpec   `json:\"gcs,omitempty\"`\n\tAzure *AzureSpec `json:\"azure,omitempty\"`\n\tSwift *SwiftSpec `json:\"swift,omitempty\"`\n}\n\ntype LocalSpec struct {\n\tVolume apiv1.VolumeSource `json:\"volume,omitempty\"`\n\tPath   string             `json:\"path,omitempty\"`\n}\n\ntype S3Spec struct {\n\tEndpoint string `json:\"endpoint,omitempty\"`\n\tBucket   string `json:\"bucket,omiempty\"`\n\tPrefix   string `json:\"prefix,omitempty\"`\n}\n\ntype GCSSpec struct {\n\tLocation string `json:\"location,omitempty\"`\n\tBucket   string `json:\"bucket,omiempty\"`\n\tPrefix   string `json:\"prefix,omitempty\"`\n}\n\ntype AzureSpec struct {\n\tContainer string `json:\"container,omitempty\"`\n\tPrefix    string `json:\"prefix,omitempty\"`\n}\n\ntype SwiftSpec struct {\n\tContainer string `json:\"container,omitempty\"`\n\tPrefix    string `json:\"prefix,omitempty\"`\n}\n\ntype MonitorSpec struct {\n\t\/\/ Valid values: coreos-prometheus-operator\n\tAgent      string          `json:\"agent,omitempty\"`\n\tPrometheus *PrometheusSpec `json:\"prometheus,omitempty\"`\n}\n\ntype PrometheusSpec struct {\n\t\/\/ Namespace of Prometheus. Service monitors will be created in this namespace.\n\tNamespace string `json:\"namespace,omitempty\"`\n\t\/\/ Labels are key value pairs that is used to select Prometheus instance via ServiceMonitor labels.\n\t\/\/ +optional\n\tLabels map[string]string `json:\"labels,omitempty\"`\n\n\t\/\/ Interval at which metrics should be scraped\n\tInterval string `json:\"interval,omitempty\"`\n\n\t\/\/ Parameters are key value pairs that are passed as flags to exporters.\n\t\/\/ Parameters map[string]string `json:\"parameters,omitempty\"`\n}\n\ntype DatabasePhase string\n\nconst (\n\t\/\/ used for Databases that are currently running\n\tDatabasePhaseRunning DatabasePhase = \"Running\"\n\t\/\/ used for Databases that are currently creating\n\tDatabasePhaseCreating DatabasePhase = \"Creating\"\n\t\/\/ used for Databases that are currently initializing\n\tDatabasePhaseInitializing DatabasePhase = \"Initializing\"\n\t\/\/ used for Databases that are Failed\n\tDatabasePhaseFailed DatabasePhase = \"Failed\"\n)\n<|endoftext|>"}
{"text":"<commit_before>package api\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n\n\t\"github.com\/raintank\/metrictank\/api\/models\"\n\t\"github.com\/raintank\/metrictank\/mdata\"\n\t\"github.com\/raintank\/metrictank\/util\"\n\t\"github.com\/raintank\/worldping-api\/pkg\/log\"\n)\n\n\/\/ represents a data \"archive\", i.e. the raw one, or an aggregated series\ntype archive struct {\n\tinterval   uint32\n\tpointCount uint32\n\tchosen     bool\n\tttl        uint32\n}\n\nfunc (b archive) String() string {\n\treturn fmt.Sprintf(\"<archive int:%d, pointCount: %d, chosen: %t\", b.interval, b.pointCount, b.chosen)\n}\n\ntype archives []archive\n\nfunc (a archives) Len() int           { return len(a) }\nfunc (a archives) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }\nfunc (a archives) Less(i, j int) bool { return a[i].interval < a[j].interval }\n\n\/\/ updates the requests with all details for fetching, making sure all metrics are in the same, optimal interval\n\/\/ luckily, all metrics still use the same aggSettings, making this a bit simpler\n\/\/ note: it is assumed that all requests have the same from, to and maxdatapoints!\n\/\/ this function ignores the TTL values. it is assumed that you've set sensible TTL's\nfunc alignRequests(reqs []models.Req, aggSettings mdata.AggSettings) ([]models.Req, error) {\n\n\t\/\/ model all the archives for each requested metric\n\t\/\/ the 0th archive is always the raw series, with highest res (lowest interval)\n\taggs := mdata.AggSettingsSpanAsc(aggSettings.Aggs)\n\tsort.Sort(aggs)\n\n\toptions := make([]archive, 1, len(aggs)+1)\n\n\tminInterval := uint32(0) \/\/ will contain the smallest rawInterval from all requested series\n\trawIntervals := make(map[uint32]struct{})\n\tfor _, req := range reqs {\n\t\tif minInterval == 0 || minInterval > req.RawInterval {\n\t\t\tminInterval = req.RawInterval\n\t\t}\n\t\trawIntervals[req.RawInterval] = struct{}{}\n\t}\n\ttsRange := (reqs[0].To - reqs[0].From)\n\n\t\/\/ note: not all series necessarily have the same raw settings, will be fixed further down\n\toptions[0] = archive{minInterval, tsRange \/ minInterval, false, aggSettings.RawTTL}\n\t\/\/ now model the archives we get from the aggregations\n\t\/\/ note that during the processing, we skip non-ready aggregations for simplicity, but at the\n\t\/\/ end we need to convert the index back to the real index in the full (incl non-ready) aggSettings array.\n\taggRef := []int{0}\n\tfor j, agg := range aggs {\n\t\tif agg.Ready {\n\t\t\toptions = append(options, archive{agg.Span, tsRange \/ agg.Span, false, agg.TTL})\n\t\t\taggRef = append(aggRef, j+1)\n\t\t}\n\t}\n\n\t\/\/ find the first, i.e. highest-res option with a pointCount <= maxDataPoints\n\t\/\/ if all options have too many points, fall back to the lowest-res option and apply runtime\n\t\/\/ consolidation\n\tselected := len(options) - 1\n\trunTimeConsolidate := true\n\tfor i, opt := range options {\n\t\tif opt.pointCount <= reqs[0].MaxPoints {\n\t\t\trunTimeConsolidate = false\n\t\t\tselected = i\n\t\t\tbreak\n\t\t}\n\t}\n\n\t\/*\n\t   do a quick calculation of the ratio between pointCount and maxDatapoints of\n\t   the selected option, and the option before that; if the previous option is\n\t   a lot closer to max points than we are, we pick that and apply some runtime\n\t   consolidation.\n\t   eg. with a time range of 1hour,\n\t   our options are:\n\t   i | span  | pointCount\n\t   ======================\n\t   0 | 10s   | 360\n\t   1 | 600s  | 6\n\t   2 | 7200s | 0\n\n\t   if maxPoints is 100, then selected will be 1, our 600s rollups.\n\t   We then calculate the ratio between maxPoints and our\n\t   selected pointCount \"6\" and the previous option \"360\".\n\t   belowMaxDataPointsRatio = 100\/6   = 16.67\n\t   aboveMaxDataPointsRatio = 360\/100 = 3.6\n\n\t   As the maxDataPoint requested is much closer to 360 then it is to 6,\n\t   we will use 360 and do runtime consolidation.\n\t*\/\n\tif selected > 0 {\n\t\tbelowMaxDataPointsRatio := float64(reqs[0].MaxPoints) \/ float64(options[selected].pointCount)\n\t\taboveMaxDataPointsRatio := float64(options[selected-1].pointCount) \/ float64(reqs[0].MaxPoints)\n\n\t\tif aboveMaxDataPointsRatio < belowMaxDataPointsRatio {\n\t\t\tselected--\n\t\t\trunTimeConsolidate = true\n\t\t}\n\t}\n\n\tchosenInterval := options[selected].interval\n\n\t\/\/ if we are using raw metrics, we need to find an interval that all request intervals work with.\n\tif selected == 0 && len(rawIntervals) > 1 {\n\t\trunTimeConsolidate = true\n\t\tkeys := make([]uint32, len(rawIntervals))\n\t\ti := 0\n\t\tfor k := range rawIntervals {\n\t\t\tkeys[i] = k\n\t\t\ti++\n\t\t}\n\t\tchosenInterval = util.Lcm(keys)\n\t\toptions[0].interval = chosenInterval\n\t\toptions[0].pointCount = tsRange \/ chosenInterval\n\t\t\/\/make sure that the calculated interval is not greater then the interval of the first rollup.\n\t\tif len(options) > 1 && chosenInterval >= options[1].interval {\n\t\t\tselected = 1\n\t\t\tchosenInterval = options[1].interval\n\t\t}\n\t}\n\n\tif LogLevel < 2 {\n\t\toptions[selected].chosen = true\n\t\tfor i, archive := range options {\n\t\t\tif archive.chosen {\n\t\t\t\tlog.Debug(\"QE %-2d %-6d %-6d <-\", i, archive.interval, tsRange\/archive.interval)\n\t\t\t} else {\n\t\t\t\tlog.Debug(\"QE %-2d %-6d %-6d\", i, archive.interval, tsRange\/archive.interval)\n\t\t\t}\n\t\t}\n\t}\n\n\t\/* we now just need to update the following properties for each req:\n\t   archive      int    \/\/ 0 means original data, 1 means first agg level, 2 means 2nd, etc.\n\t   archInterval uint32 \/\/ the interval corresponding to the archive we'll fetch\n\t   outInterval  uint32 \/\/ the interval of the output data, after any runtime consolidation\n\t   aggNum       uint32 \/\/ how many points to consolidate together at runtime, after fetching from the archive\n\t*\/\n\tfor i := range reqs {\n\t\treq := &reqs[i]\n\t\treq.Archive = aggRef[selected]\n\t\treq.ArchInterval = options[selected].interval\n\t\treq.TTL = options[selected].ttl\n\t\treq.OutInterval = chosenInterval\n\t\treq.AggNum = 1\n\t\tif runTimeConsolidate {\n\t\t\treq.AggNum = aggEvery(options[selected].pointCount, req.MaxPoints)\n\n\t\t\t\/\/ options[0].{interval,pointCount} didn't necessarily reflect the actual raw archive for this request,\n\t\t\t\/\/ so adjust where needed.\n\t\t\tif selected == 0 && chosenInterval != req.RawInterval {\n\t\t\t\treq.ArchInterval = req.RawInterval\n\t\t\t\treq.AggNum *= chosenInterval \/ req.RawInterval\n\t\t\t}\n\n\t\t\treq.OutInterval = req.ArchInterval * req.AggNum\n\t\t}\n\t}\n\treturn reqs, nil\n}\n<commit_msg>Collect metrics about datapoints sent to graphite-api<commit_after>package api\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n\t\"time\"\n\n\t\"github.com\/raintank\/metrictank\/api\/models\"\n\t\"github.com\/raintank\/metrictank\/mdata\"\n\t\"github.com\/raintank\/metrictank\/stats\"\n\t\"github.com\/raintank\/metrictank\/util\"\n\t\"github.com\/raintank\/worldping-api\/pkg\/log\"\n)\n\nvar (\n\tdpAdjGranularity  = stats.NewGauge32(\"api.dp_adj_granularity\")\n\tdpMaxGranularity  = stats.NewGauge32(\"api.dp_max_granularity\")\n\taggAdjGranularity = stats.NewGauge32(\"api.agg_adj_granularity\")\n\taggMaxGranularity = stats.NewGauge32(\"api.agg_max_granularity\")\n)\n\n\/\/ represents a data \"archive\", i.e. the raw one, or an aggregated series\ntype archive struct {\n\tinterval   uint32\n\tpointCount uint32\n\tchosen     bool\n\tttl        uint32\n}\n\nfunc (b archive) String() string {\n\treturn fmt.Sprintf(\"<archive int:%d, pointCount: %d, chosen: %t\", b.interval, b.pointCount, b.chosen)\n}\n\ntype archives []archive\n\nfunc (a archives) Len() int           { return len(a) }\nfunc (a archives) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }\nfunc (a archives) Less(i, j int) bool { return a[i].interval < a[j].interval }\n\n\/\/ takes a ttl and returns the oldest timestamp with that ttl\nfunc oldestTs(ttl uint32) uint32 {\n\treturn uint32(time.Now().Unix()) - ttl\n}\n\n\/\/ updates the requests with all details for fetching, making sure all metrics are in the same, optimal interval\n\/\/ luckily, all metrics still use the same aggSettings, making this a bit simpler\n\/\/ note: it is assumed that all requests have the same from, to and maxdatapoints!\n\/\/ this function ignores the TTL values. it is assumed that you've set sensible TTL's\nfunc alignRequests(reqs []models.Req, aggSettings mdata.AggSettings) ([]models.Req, error) {\n\n\t\/\/ model all the archives for each requested metric\n\t\/\/ the 0th archive is always the raw series, with highest res (lowest interval)\n\taggs := mdata.AggSettingsSpanAsc(aggSettings.Aggs)\n\tsort.Sort(aggs)\n\n\toptions := make([]archive, 1, len(aggs)+1)\n\n\tminInterval := uint32(0) \/\/ will contain the smallest rawInterval from all requested series\n\trawIntervals := make(map[uint32]struct{})\n\tfor _, req := range reqs {\n\t\tif minInterval == 0 || minInterval > req.RawInterval {\n\t\t\tminInterval = req.RawInterval\n\t\t}\n\t\trawIntervals[req.RawInterval] = struct{}{}\n\t}\n\ttsRange := (reqs[0].To - reqs[0].From)\n\n\t\/\/ note: not all series necessarily have the same raw settings, will be fixed further down\n\toptions[0] = archive{minInterval, tsRange \/ minInterval, false, aggSettings.RawTTL}\n\t\/\/ now model the archives we get from the aggregations\n\t\/\/ note that during the processing, we skip non-ready aggregations for simplicity, but at the\n\t\/\/ end we need to convert the index back to the real index in the full (incl non-ready) aggSettings array.\n\taggRef := []int{0}\n\tfor j, agg := range aggs {\n\t\tif agg.Ready {\n\t\t\toptions = append(options, archive{agg.Span, tsRange \/ agg.Span, false, agg.TTL})\n\t\t\taggRef = append(aggRef, j+1)\n\t\t}\n\t}\n\n\t\/\/ find the first, i.e. highest-res option with a pointCount <= maxDataPoints\n\t\/\/ if all options have too many points, fall back to the lowest-res option and apply runtime\n\t\/\/ consolidation\n\tselected := len(options) - 1\n\trunTimeConsolidate := true\n\tfor i, opt := range options {\n\t\tif opt.pointCount <= reqs[0].MaxPoints {\n\t\t\trunTimeConsolidate = false\n\t\t\tselected = i\n\t\t\tbreak\n\t\t}\n\t}\n\n\t\/*\n\t   do a quick calculation of the ratio between pointCount and maxDatapoints of\n\t   the selected option, and the option before that; if the previous option is\n\t   a lot closer to max points than we are, we pick that and apply some runtime\n\t   consolidation.\n\t   eg. with a time range of 1hour,\n\t   our options are:\n\t   i | span  | pointCount\n\t   ======================\n\t   0 | 10s   | 360\n\t   1 | 600s  | 6\n\t   2 | 7200s | 0\n\n\t   if maxPoints is 100, then selected will be 1, our 600s rollups.\n\t   We then calculate the ratio between maxPoints and our\n\t   selected pointCount \"6\" and the previous option \"360\".\n\t   belowMaxDataPointsRatio = 100\/6   = 16.67\n\t   aboveMaxDataPointsRatio = 360\/100 = 3.6\n\n\t   As the maxDataPoint requested is much closer to 360 then it is to 6,\n\t   we will use 360 and do runtime consolidation.\n\t*\/\n\tif selected > 0 {\n\t\tbelowMaxDataPointsRatio := float64(reqs[0].MaxPoints) \/ float64(options[selected].pointCount)\n\t\taboveMaxDataPointsRatio := float64(options[selected-1].pointCount) \/ float64(reqs[0].MaxPoints)\n\n\t\tif aboveMaxDataPointsRatio < belowMaxDataPointsRatio {\n\t\t\tselected--\n\t\t\trunTimeConsolidate = true\n\t\t}\n\t}\n\n\tchosenInterval := options[selected].interval\n\n\t\/\/ by default we select the lowest res (longest time range) option.\n\tselectedHighestRes := len(options) - 1\n\t\/\/ then we loop over the remaining options trying to find the highest res where the\n\t\/\/ oldest timestamp is still older than our From ts\n\tfor i := len(options) - 2; i >= 0; i-- {\n\t\tif oldestTs(options[i].ttl) > reqs[0].From {\n\t\t\tbreak\n\t\t}\n\t\tselectedHighestRes = i\n\t}\n\n\t\/\/ record how many datapoints will be sent to graphite-api if we use the old-style selection mechanism\n\tdpAdjGranularity.SetUint32(tsRange \/ chosenInterval)\n\n\t\/\/ record the aggregation index that has been selected\n\taggAdjGranularity.SetUint32(uint32(selected))\n\n\t\/\/ also record how many there would be if instead we select the aggregation with the highest resolution\n\t\/\/ that can still cover the requested time range\n\tdpMaxGranularity.SetUint32(tsRange \/ options[selectedHighestRes].interval)\n\n\t\/\/ record the aggregation index that would be selected for max granularity\n\taggMaxGranularity.SetUint32(uint32(selectedHighestRes))\n\n\t\/\/ if we are using raw metrics, we need to find an interval that all request intervals work with.\n\tif selected == 0 && len(rawIntervals) > 1 {\n\t\trunTimeConsolidate = true\n\t\tkeys := make([]uint32, len(rawIntervals))\n\t\ti := 0\n\t\tfor k := range rawIntervals {\n\t\t\tkeys[i] = k\n\t\t\ti++\n\t\t}\n\t\tchosenInterval = util.Lcm(keys)\n\t\toptions[0].interval = chosenInterval\n\t\toptions[0].pointCount = tsRange \/ chosenInterval\n\t\t\/\/make sure that the calculated interval is not greater then the interval of the first rollup.\n\t\tif len(options) > 1 && chosenInterval >= options[1].interval {\n\t\t\tselected = 1\n\t\t\tchosenInterval = options[1].interval\n\t\t}\n\t}\n\n\tif LogLevel < 2 {\n\t\toptions[selected].chosen = true\n\t\tfor i, archive := range options {\n\t\t\tif archive.chosen {\n\t\t\t\tlog.Debug(\"QE %-2d %-6d %-6d <-\", i, archive.interval, tsRange\/archive.interval)\n\t\t\t} else {\n\t\t\t\tlog.Debug(\"QE %-2d %-6d %-6d\", i, archive.interval, tsRange\/archive.interval)\n\t\t\t}\n\t\t}\n\t}\n\n\t\/* we now just need to update the following properties for each req:\n\t   archive      int    \/\/ 0 means original data, 1 means first agg level, 2 means 2nd, etc.\n\t   archInterval uint32 \/\/ the interval corresponding to the archive we'll fetch\n\t   outInterval  uint32 \/\/ the interval of the output data, after any runtime consolidation\n\t   aggNum       uint32 \/\/ how many points to consolidate together at runtime, after fetching from the archive\n\t*\/\n\tfor i := range reqs {\n\t\treq := &reqs[i]\n\t\treq.Archive = aggRef[selected]\n\t\treq.ArchInterval = options[selected].interval\n\t\treq.TTL = options[selected].ttl\n\t\treq.OutInterval = chosenInterval\n\t\treq.AggNum = 1\n\t\tif runTimeConsolidate {\n\t\t\treq.AggNum = aggEvery(options[selected].pointCount, req.MaxPoints)\n\n\t\t\t\/\/ options[0].{interval,pointCount} didn't necessarily reflect the actual raw archive for this request,\n\t\t\t\/\/ so adjust where needed.\n\t\t\tif selected == 0 && chosenInterval != req.RawInterval {\n\t\t\t\treq.ArchInterval = req.RawInterval\n\t\t\t\treq.AggNum *= chosenInterval \/ req.RawInterval\n\t\t\t}\n\n\t\t\treq.OutInterval = req.ArchInterval * req.AggNum\n\t\t}\n\t}\n\treturn reqs, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 David Lavieri.  All rights reserved.\n\/\/ Use of this source code is governed by a MIT License\n\/\/ License that can be found in the LICENSE file.\n\npackage goradix\n\nimport \"testing\"\n\n\/\/ ----------------------- Benchmarks ------------------------ \/\/\n\nfunc BenchmarkInsertString(b *testing.B) {\n\trx := New(false)\n\ttn := 0\n\tsd2 := sampleData2()\n\tsdLen := len(sd2) - 1\n\n\tfor i := 0; i < b.N; i++ {\n\t\tif tn == sdLen {\n\t\t\trx = New(false)\n\t\t\ttn = 0\n\t\t}\n\n\t\trx.Insert(sd2[tn], i)\n\n\t\ttn++\n\t}\n}\n\nfunc BenchmarkInsertBytes(b *testing.B) {\n\trx := New(false)\n\ttn := 0\n\tsd2 := sampleData3()\n\tsdLen := len(sd2) - 1\n\n\tfor i := 0; i < b.N; i++ {\n\t\tif tn == sdLen {\n\t\t\trx = New(false)\n\t\t\ttn = 0\n\t\t}\n\n\t\trx.InsertBytes(sd2[tn], i)\n\n\t\ttn++\n\t}\n}\n<commit_msg>Update insert benchmark<commit_after>\/\/ Copyright 2016 David Lavieri.  All rights reserved.\n\/\/ Use of this source code is governed by a MIT License\n\/\/ License that can be found in the LICENSE file.\n\npackage goradix\n\nimport \"testing\"\n\n\/\/ ----------------------- Benchmarks ------------------------ \/\/\n\nfunc BenchmarkInsertNTS(b *testing.B) {\n\trx := New(false)\n\ttn := 0\n\tsd2 := sampleData3()\n\tsdLen := len(sd2) - 1\n\n\tfor i := 0; i < b.N; i++ {\n\t\tif tn == sdLen {\n\t\t\trx = New(false)\n\t\t\ttn = 0\n\t\t}\n\n\t\trx.InsertBytes(sd2[tn], i)\n\n\t\ttn++\n\t}\n}\n\nfunc BenchmarkInsertTS(b *testing.B) {\n\trx := New(true)\n\ttn := 0\n\tsd2 := sampleData3()\n\tsdLen := len(sd2) - 1\n\n\tfor i := 0; i < b.N; i++ {\n\t\tif tn == sdLen {\n\t\t\trx = New(true)\n\t\t\ttn = 0\n\t\t}\n\n\t\trx.InsertBytes(sd2[tn], i)\n\n\t\ttn++\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package api\n\nimport (\n\t\"encoding\/json\"\n\t\"net\/http\"\n\t\"strings\"\n\n\t\"github.com\/FederationOfFathers\/dashboard\/bridge\"\n\t\"github.com\/FederationOfFathers\/dashboard\/db\"\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/jinzhu\/gorm\"\n\t\"go.uber.org\/zap\"\n)\n\nfunc init() {\n\tRouter.Path(\"\/api\/v0\/meta\/member\/{memberID}\/{key}\").Methods(\"DELETE\").Handler(jwtHandlerFunc(\n\t\tfunc(w http.ResponseWriter, r *http.Request) {\n\t\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\t\tid := getSlackUserID(r)\n\t\t\tadmin, _ := bridge.Data.Slack.IsUserIDAdmin(id)\n\t\t\tmember, err := DB.MemberBySlackID(mux.Vars(r)[\"memberID\"])\n\t\t\tif err != nil {\n\t\t\t\thttp.NotFound(w, r)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif strings.ToLower(member.Slack) != strings.ToLower(id) && !admin {\n\t\t\t\thttp.NotFound(w, r)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tDB.Delete(db.MemberMeta{}, \"member_ID = ? AND meta_key = ?\", member.ID, mux.Vars(r)[\"key\"])\n\t\t},\n\t))\n\n\tRouter.Path(\"\/api\/v0\/meta\/member\/{memberID}\").Methods(\"GET\").Handler(jwtHandlerFunc(\n\t\tfunc(w http.ResponseWriter, r *http.Request) {\n\t\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\t\tmember, err := DB.MemberByAny(mux.Vars(r)[\"memberID\"])\n\t\t\tif err != nil {\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif err == gorm.ErrRecordNotFound || member == nil {\n\t\t\t\thttp.NotFound(w, r)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tvar out = map[string]string{}\n\t\t\tvar entries []*db.MemberMeta\n\t\t\tDB.Where(\"member_ID = ?\", member.ID).Find(&entries)\n\t\t\tfor _, entry := range entries {\n\t\t\t\tout[entry.MetaKey] = string(entry.MetaJSON)\n\t\t\t}\n\t\t\tjson.NewEncoder(w).Encode(out)\n\t\t},\n\t))\n\n\tRouter.Path(\"\/api\/v0\/meta\/member\/{memberID}\/{key}\").Methods(\"GET\").Handler(jwtHandlerFunc(\n\t\tfunc(w http.ResponseWriter, r *http.Request) {\n\t\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\t\tmember, err := DB.MemberByAny(mux.Vars(r)[\"memberID\"])\n\t\t\tif err != nil {\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif err == gorm.ErrRecordNotFound || member == nil {\n\t\t\t\thttp.NotFound(w, r)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tvar out = map[string]string{}\n\t\t\tvar entries []*db.MemberMeta\n\t\t\tDB.Where(\"member_ID = ? AND meta_key = ?\", member.ID, mux.Vars(r)[\"key\"]).Find(&entries)\n\t\t\tfor _, entry := range entries {\n\t\t\t\tout[entry.MetaKey] = string(entry.MetaJSON)\n\t\t\t}\n\t\t\tjson.NewEncoder(w).Encode(out)\n\t\t},\n\t))\n\n\tRouter.Path(\"\/api\/v0\/meta\/member\/{memberID}\").Methods(\"PUT\", \"POST\").Handler(\n\t\tjwtHandlerFunc(\n\t\t\tfunc(w http.ResponseWriter, r *http.Request) {\n\t\t\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\t\t\tdefer r.Body.Close()\n\t\t\t\tmember, err := DB.MemberBySlackID(mux.Vars(r)[\"memberID\"])\n\t\t\t\tif err != nil {\n\t\t\t\t\thttp.NotFound(w, r)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif !strings.Contains(strings.ToLower(r.Header.Get(\"Content-Type\")), \"json\") {\n\t\t\t\t\thttp.NotFound(w, r)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tvar form = map[string]string{}\n\n\t\t\t\terr = json.NewDecoder(r.Body).Decode(&form)\n\t\t\t\tif err != nil {\n\t\t\t\t\tLogger.Error(\"Error decoding JSON\", zap.String(\"uri\", r.URL.RawPath), zap.Error(err))\n\t\t\t\t}\n\n\t\t\t\tsid := getSlackUserID(r)\n\t\t\t\tadmin, _ := bridge.Data.Slack.IsUserIDAdmin(sid)\n\t\t\t\tif sid != member.Slack && !admin {\n\t\t\t\t\thttp.NotFound(w, r)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tfor k, v := range form {\n\t\t\t\t\terr := DB.Exec(\n\t\t\t\t\t\t\"INSERT INTO member_meta (`member_id`,`meta_key`,`meta_json`,`created_at`,`updated_at`) \"+\n\t\t\t\t\t\t\t\"VALUES(?,?,?,NOW(),NOW()) \"+\n\t\t\t\t\t\t\t\"ON DUPLICATE KEY UPDATE \"+\n\t\t\t\t\t\t\t\"`meta_json` = ?, `updated_at` = NOW(), `deleted_at` = NULL\",\n\t\t\t\t\t\tmember.ID,\n\t\t\t\t\t\tk,\n\t\t\t\t\t\t[]byte(v),\n\t\t\t\t\t\t[]byte(v),\n\t\t\t\t\t).Error\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\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}\n<commit_msg>membermeta GET<commit_after>package api\n\nimport (\n\t\"encoding\/json\"\n\t\"net\/http\"\n\t\"strings\"\n\n\t\"github.com\/FederationOfFathers\/dashboard\/bridge\"\n\t\"github.com\/FederationOfFathers\/dashboard\/db\"\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/jinzhu\/gorm\"\n\t\"go.uber.org\/zap\"\n)\n\nfunc init() {\n\tRouter.Path(\"\/api\/v0\/meta\/member\/{memberID}\/{key}\").Methods(\"DELETE\").Handler(jwtHandlerFunc(\n\t\tfunc(w http.ResponseWriter, r *http.Request) {\n\t\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\t\tid := getSlackUserID(r)\n\t\t\tadmin, _ := bridge.Data.Slack.IsUserIDAdmin(id)\n\t\t\tmember, err := DB.MemberBySlackID(mux.Vars(r)[\"memberID\"])\n\t\t\tif err != nil {\n\t\t\t\thttp.NotFound(w, r)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif strings.ToLower(member.Slack) != strings.ToLower(id) && !admin {\n\t\t\t\thttp.NotFound(w, r)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tDB.Delete(db.MemberMeta{}, \"member_ID = ? AND meta_key = ?\", member.ID, mux.Vars(r)[\"key\"])\n\t\t},\n\t))\n\n\tRouter.Path(\"\/api\/v0\/meta\/member\/{memberID}\").Methods(\"GET\").Handler(jwtHandlerFunc(\n\t\tfunc(w http.ResponseWriter, r *http.Request) {\n\t\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\t\tmember, err := DB.MemberByAny(mux.Vars(r)[\"memberID\"])\n\t\t\tif err == gorm.ErrRecordNotFound || member == nil {\n\t\t\t\thttp.NotFound(w, r)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tLogger.Error(\"querying user\", zap.Error(err))\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tvar out = map[string]string{}\n\t\t\trows, err := DB.Raw(\"SELECT meta_key,meta_value FROM membermeta WHERE member_id = ?\", member.ID).Rows()\n\t\t\tdefer rows.Close()\n\t\t\tif err != nil {\n\t\t\t\tLogger.Error(\"querying\", zap.Error(err))\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tfor rows.Next() {\n\t\t\t\tvar k string\n\t\t\t\tvar v string\n\t\t\t\tif err := rows.Scan(&k, &v); err != nil {\n\t\t\t\t\tLogger.Error(\"scanning\", zap.Error(err))\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tout[k] = v\n\t\t\t}\n\t\t\tjson.NewEncoder(w).Encode(out)\n\t\t},\n\t))\n\n\tRouter.Path(\"\/api\/v0\/meta\/member\/{memberID}\").Methods(\"PUT\", \"POST\").Handler(\n\t\tjwtHandlerFunc(\n\t\t\tfunc(w http.ResponseWriter, r *http.Request) {\n\t\t\t\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\t\t\t\tdefer r.Body.Close()\n\t\t\t\tmember, err := DB.MemberBySlackID(mux.Vars(r)[\"memberID\"])\n\t\t\t\tif err != nil {\n\t\t\t\t\thttp.NotFound(w, r)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif !strings.Contains(strings.ToLower(r.Header.Get(\"Content-Type\")), \"json\") {\n\t\t\t\t\thttp.NotFound(w, r)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tvar form = map[string]string{}\n\n\t\t\t\terr = json.NewDecoder(r.Body).Decode(&form)\n\t\t\t\tif err != nil {\n\t\t\t\t\tLogger.Error(\"Error decoding JSON\", zap.String(\"uri\", r.URL.RawPath), zap.Error(err))\n\t\t\t\t}\n\n\t\t\t\tsid := getSlackUserID(r)\n\t\t\t\tadmin, _ := bridge.Data.Slack.IsUserIDAdmin(sid)\n\t\t\t\tif sid != member.Slack && !admin {\n\t\t\t\t\thttp.NotFound(w, r)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tfor k, v := range form {\n\t\t\t\t\terr := DB.Exec(\n\t\t\t\t\t\t\"INSERT INTO member_meta (`member_id`,`meta_key`,`meta_json`,`created_at`,`updated_at`) \"+\n\t\t\t\t\t\t\t\"VALUES(?,?,?,NOW(),NOW()) \"+\n\t\t\t\t\t\t\t\"ON DUPLICATE KEY UPDATE \"+\n\t\t\t\t\t\t\t\"`meta_json` = ?, `updated_at` = NOW(), `deleted_at` = NULL\",\n\t\t\t\t\t\tmember.ID,\n\t\t\t\t\t\tk,\n\t\t\t\t\t\t[]byte(v),\n\t\t\t\t\t\t[]byte(v),\n\t\t\t\t\t).Error\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\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}\n<|endoftext|>"}
{"text":"<commit_before>package engine\n\nimport (\n\t\"github.com\/coreos\/fleet\/agent\"\n\t\"github.com\/coreos\/fleet\/job\"\n\t\"github.com\/coreos\/fleet\/machine\"\n)\n\ntype clusterState struct {\n\tjobs     map[string]*job.Job\n\tmachines map[string]*machine.MachineState\n}\n\nfunc newClusterState(units []job.Unit, sUnits []job.ScheduledUnit, machines []machine.MachineState) *clusterState {\n\tsUnitMap := make(map[string]*job.ScheduledUnit)\n\tfor _, sUnit := range sUnits {\n\t\tsUnit := sUnit\n\t\tsUnitMap[sUnit.Name] = &sUnit\n\t}\n\n\tjMap := make(map[string]*job.Job, len(units))\n\tfor _, u := range units {\n\t\tj := job.Job{\n\t\t\tName:        u.Name,\n\t\t\tUnit:        u.Unit,\n\t\t\tTargetState: u.TargetState,\n\t\t}\n\n\t\tif sUnit, ok := sUnitMap[u.Name]; ok {\n\t\t\tj.TargetMachineID = sUnit.TargetMachineID\n\t\t\tj.State = sUnit.State\n\t\t}\n\n\t\tjMap[j.Name] = &j\n\t}\n\n\tmMap := make(map[string]*machine.MachineState, len(machines))\n\tfor _, ms := range machines {\n\t\tms := ms\n\t\tmMap[ms.ID] = &ms\n\t}\n\n\treturn &clusterState{\n\t\tjobs:     jMap,\n\t\tmachines: mMap,\n\t}\n}\n\nfunc (cs *clusterState) agents() map[string]*agent.AgentState {\n\tagents := make(map[string]*agent.AgentState, len(cs.machines))\n\tfor _, ms := range cs.machines {\n\t\tms := ms\n\t\tagents[ms.ID] = agent.NewAgentState(ms)\n\t}\n\n\tfor _, j := range cs.jobs {\n\t\tif !j.Scheduled() || j.TargetState == job.JobStateInactive {\n\t\t\tcontinue\n\t\t}\n\n\t\tas := agents[j.TargetMachineID]\n\t\tif as == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tj := j\n\t\tas.Jobs[j.Name] = j\n\t}\n\n\treturn agents\n}\n\nfunc (cs *clusterState) schedule(jobName, targetMachineID string) {\n\tj := cs.jobs[jobName]\n\tif j == nil {\n\t\treturn\n\t}\n\tj.TargetMachineID = targetMachineID\n}\n\nfunc (cs *clusterState) unschedule(jobName string) {\n\tj := cs.jobs[jobName]\n\tif j == nil {\n\t\treturn\n\t}\n\tj.TargetMachineID = \"\"\n}\n<commit_msg>engine: do not consider global units for scheduling<commit_after>package engine\n\nimport (\n\t\"github.com\/coreos\/fleet\/agent\"\n\t\"github.com\/coreos\/fleet\/job\"\n\t\"github.com\/coreos\/fleet\/machine\"\n)\n\ntype clusterState struct {\n\tjobs     map[string]*job.Job\n\tgUnits   map[string]*job.Unit\n\tmachines map[string]*machine.MachineState\n}\n\nfunc newClusterState(units []job.Unit, sUnits []job.ScheduledUnit, machines []machine.MachineState) *clusterState {\n\tsUnitMap := make(map[string]*job.ScheduledUnit)\n\tfor _, sUnit := range sUnits {\n\t\tsUnit := sUnit\n\t\tsUnitMap[sUnit.Name] = &sUnit\n\t}\n\n\tjMap := make(map[string]*job.Job)\n\tguMap := make(map[string]*job.Unit)\n\tfor _, u := range units {\n\t\tif u.IsGlobal() {\n\t\t\tu := u\n\t\t\tguMap[u.Name] = &u\n\t\t} else {\n\t\t\tj := job.Job{\n\t\t\t\tName:        u.Name,\n\t\t\t\tUnit:        u.Unit,\n\t\t\t\tTargetState: u.TargetState,\n\t\t\t}\n\n\t\t\tif sUnit, ok := sUnitMap[u.Name]; ok {\n\t\t\t\tj.TargetMachineID = sUnit.TargetMachineID\n\t\t\t\tj.State = sUnit.State\n\t\t\t}\n\n\t\t\tjMap[j.Name] = &j\n\t\t}\n\t}\n\n\tmMap := make(map[string]*machine.MachineState, len(machines))\n\tfor _, ms := range machines {\n\t\tms := ms\n\t\tmMap[ms.ID] = &ms\n\t}\n\n\treturn &clusterState{\n\t\tjobs:     jMap,\n\t\tgUnits:   guMap,\n\t\tmachines: mMap,\n\t}\n}\n\nfunc (cs *clusterState) agents() map[string]*agent.AgentState {\n\tagents := make(map[string]*agent.AgentState, len(cs.machines))\n\tfor _, ms := range cs.machines {\n\t\tms := ms\n\t\tagents[ms.ID] = agent.NewAgentState(ms)\n\t}\n\n\tfor _, j := range cs.jobs {\n\t\tj := j\n\t\tif !j.Scheduled() || j.TargetState == job.JobStateInactive {\n\t\t\tcontinue\n\t\t}\n\t\tif as, ok := agents[j.TargetMachineID]; ok {\n\t\t\tas.Jobs[j.Name] = j\n\t\t}\n\t}\n\n\tfor _, gu := range cs.gUnits {\n\t\tj := &job.Job{\n\t\t\tName:        gu.Name,\n\t\t\tUnit:        gu.Unit,\n\t\t\tTargetState: gu.TargetState,\n\t\t}\n\t\tfor _, a := range agents {\n\t\t\ta.Jobs[gu.Name] = j\n\t\t}\n\t}\n\n\treturn agents\n}\n\nfunc (cs *clusterState) schedule(jobName, targetMachineID string) {\n\tj := cs.jobs[jobName]\n\tif j == nil {\n\t\treturn\n\t}\n\tj.TargetMachineID = targetMachineID\n}\n\nfunc (cs *clusterState) unschedule(jobName string) {\n\tj := cs.jobs[jobName]\n\tif j == nil {\n\t\treturn\n\t}\n\tj.TargetMachineID = \"\"\n}\n<|endoftext|>"}
{"text":"<commit_before>package nodepool\n\nimport (\n\t\"fmt\"\n\n\tv1alpha1 \"github.com\/jetstack\/navigator\/pkg\/apis\/navigator\/v1alpha1\"\n\t\"github.com\/jetstack\/navigator\/pkg\/controllers\/cassandra\/util\"\n\tk8sErrors \"k8s.io\/apimachinery\/pkg\/api\/errors\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/client-go\/kubernetes\"\n\tappslisters \"k8s.io\/client-go\/listers\/apps\/v1beta2\"\n\t\"k8s.io\/client-go\/tools\/record\"\n)\n\ntype Interface interface {\n\tSync(*v1alpha1.CassandraCluster) error\n}\n\ntype defaultCassandraClusterNodepoolControl struct {\n\tkubeClient        kubernetes.Interface\n\tstatefulsetLister appslisters.StatefulSetLister\n\trecorder          record.EventRecorder\n}\n\nvar _ Interface = &defaultCassandraClusterNodepoolControl{}\n\nfunc NewControl(\n\tkubeClient kubernetes.Interface,\n\tstatefulsetLister appslisters.StatefulSetLister,\n\trecorder record.EventRecorder,\n) Interface {\n\treturn &defaultCassandraClusterNodepoolControl{\n\t\tkubeClient:        kubeClient,\n\t\tstatefulsetLister: statefulsetLister,\n\t\trecorder:          recorder,\n\t}\n}\n\nfunc (e *defaultCassandraClusterNodepoolControl) removeUnusedStatefulSets(\n\tcluster *v1alpha1.CassandraCluster,\n) error {\n\texpectedStatefulSetNames := map[string]bool{}\n\tfor _, pool := range cluster.Spec.NodePools {\n\t\tname := util.NodePoolResourceName(cluster, &pool)\n\t\texpectedStatefulSetNames[name] = true\n\t}\n\tclient := e.kubeClient.AppsV1beta2().StatefulSets(cluster.Namespace)\n\tselector, err := util.SelectorForCluster(cluster)\n\tif err != nil {\n\t\treturn err\n\t}\n\texistingSets, err := e.statefulsetLister.\n\t\tStatefulSets(cluster.Namespace).\n\t\tList(selector)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, set := range existingSets {\n\t\tif !metav1.IsControlledBy(set, cluster) {\n\t\t\townerRef := metav1.GetControllerOf(set)\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"Foreign owned StatefulSet: \"+\n\t\t\t\t\t\"A StatefulSet with name '%s\/%s' already exists, \"+\n\t\t\t\t\t\"but it is controlled by '%v', not '%s\/%s'.\",\n\t\t\t\tset.Namespace, set.Name, ownerRef,\n\t\t\t\tcluster.Namespace, cluster.Name,\n\t\t\t)\n\t\t}\n\t\t_, found := expectedStatefulSetNames[set.Name]\n\t\tif !found {\n\t\t\terr := client.Delete(set.Name, nil)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (e *defaultCassandraClusterNodepoolControl) createOrUpdateStatefulSet(\n\tcluster *v1alpha1.CassandraCluster,\n\tnodePool *v1alpha1.CassandraClusterNodePool,\n) error {\n\tclient := e.kubeClient.AppsV1beta2().StatefulSets(cluster.Namespace)\n\tdesiredSet := StatefulSetForCluster(cluster, nodePool)\n\texistingSet, err := e.statefulsetLister.\n\t\tStatefulSets(desiredSet.Namespace).\n\t\tGet(desiredSet.Name)\n\tif k8sErrors.IsNotFound(err) {\n\t\t_, err = client.Create(desiredSet)\n\t\treturn err\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !metav1.IsControlledBy(existingSet, cluster) {\n\t\townerRef := metav1.GetControllerOf(existingSet)\n\t\treturn fmt.Errorf(\n\t\t\t\"Foreign owned StatefulSet: \"+\n\t\t\t\t\"A StatefulSet with name '%s\/%s' already exists, \"+\n\t\t\t\t\"but it is controlled by '%v', not '%s\/%s'.\",\n\t\t\texistingSet.Namespace, existingSet.Name, ownerRef,\n\t\t\tcluster.Namespace, cluster.Name,\n\t\t)\n\t}\n\t_, err = client.Update(desiredSet)\n\treturn err\n}\n\nfunc (e *defaultCassandraClusterNodepoolControl) syncStatefulSets(\n\tcluster *v1alpha1.CassandraCluster,\n) error {\n\tfor _, pool := range cluster.Spec.NodePools {\n\t\terr := e.createOrUpdateStatefulSet(cluster, &pool)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\terr := e.removeUnusedStatefulSets(cluster)\n\treturn err\n}\n\nfunc (e *defaultCassandraClusterNodepoolControl) Sync(cluster *v1alpha1.CassandraCluster) error {\n\treturn e.syncStatefulSets(cluster)\n}\n<commit_msg>refactor ownerCheck into a function<commit_after>package nodepool\n\nimport (\n\t\"fmt\"\n\n\tv1alpha1 \"github.com\/jetstack\/navigator\/pkg\/apis\/navigator\/v1alpha1\"\n\t\"github.com\/jetstack\/navigator\/pkg\/controllers\/cassandra\/util\"\n\t\"k8s.io\/api\/apps\/v1beta2\"\n\tk8sErrors \"k8s.io\/apimachinery\/pkg\/api\/errors\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/client-go\/kubernetes\"\n\tappslisters \"k8s.io\/client-go\/listers\/apps\/v1beta2\"\n\t\"k8s.io\/client-go\/tools\/record\"\n)\n\ntype Interface interface {\n\tSync(*v1alpha1.CassandraCluster) error\n}\n\ntype defaultCassandraClusterNodepoolControl struct {\n\tkubeClient        kubernetes.Interface\n\tstatefulsetLister appslisters.StatefulSetLister\n\trecorder          record.EventRecorder\n}\n\nvar _ Interface = &defaultCassandraClusterNodepoolControl{}\n\nfunc NewControl(\n\tkubeClient kubernetes.Interface,\n\tstatefulsetLister appslisters.StatefulSetLister,\n\trecorder record.EventRecorder,\n) Interface {\n\treturn &defaultCassandraClusterNodepoolControl{\n\t\tkubeClient:        kubeClient,\n\t\tstatefulsetLister: statefulsetLister,\n\t\trecorder:          recorder,\n\t}\n}\n\nfunc ownerCheck(\n\tset *v1beta2.StatefulSet,\n\tcluster *v1alpha1.CassandraCluster,\n) error {\n\tif !metav1.IsControlledBy(set, cluster) {\n\t\townerRef := metav1.GetControllerOf(set)\n\t\treturn fmt.Errorf(\n\t\t\t\"Foreign owned StatefulSet: \"+\n\t\t\t\t\"A StatefulSet with name '%s\/%s' already exists, \"+\n\t\t\t\t\"but it is controlled by '%v', not '%s\/%s'.\",\n\t\t\tset.Namespace, set.Name, ownerRef,\n\t\t\tcluster.Namespace, cluster.Name,\n\t\t)\n\t}\n\treturn nil\n}\n\nfunc (e *defaultCassandraClusterNodepoolControl) removeUnusedStatefulSets(\n\tcluster *v1alpha1.CassandraCluster,\n) error {\n\texpectedStatefulSetNames := map[string]bool{}\n\tfor _, pool := range cluster.Spec.NodePools {\n\t\tname := util.NodePoolResourceName(cluster, &pool)\n\t\texpectedStatefulSetNames[name] = true\n\t}\n\tclient := e.kubeClient.AppsV1beta2().StatefulSets(cluster.Namespace)\n\tselector, err := util.SelectorForCluster(cluster)\n\tif err != nil {\n\t\treturn err\n\t}\n\texistingSets, err := e.statefulsetLister.\n\t\tStatefulSets(cluster.Namespace).\n\t\tList(selector)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, set := range existingSets {\n\t\terr := ownerCheck(set, cluster)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, found := expectedStatefulSetNames[set.Name]\n\t\tif !found {\n\t\t\terr := client.Delete(set.Name, nil)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (e *defaultCassandraClusterNodepoolControl) createOrUpdateStatefulSet(\n\tcluster *v1alpha1.CassandraCluster,\n\tnodePool *v1alpha1.CassandraClusterNodePool,\n) error {\n\tclient := e.kubeClient.AppsV1beta2().StatefulSets(cluster.Namespace)\n\tdesiredSet := StatefulSetForCluster(cluster, nodePool)\n\texistingSet, err := e.statefulsetLister.\n\t\tStatefulSets(desiredSet.Namespace).\n\t\tGet(desiredSet.Name)\n\tif k8sErrors.IsNotFound(err) {\n\t\t_, err = client.Create(desiredSet)\n\t\treturn err\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ownerCheck(existingSet, cluster)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = client.Update(desiredSet)\n\treturn err\n}\n\nfunc (e *defaultCassandraClusterNodepoolControl) syncStatefulSets(\n\tcluster *v1alpha1.CassandraCluster,\n) error {\n\tfor _, pool := range cluster.Spec.NodePools {\n\t\terr := e.createOrUpdateStatefulSet(cluster, &pool)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\terr := e.removeUnusedStatefulSets(cluster)\n\treturn err\n}\n\nfunc (e *defaultCassandraClusterNodepoolControl) Sync(cluster *v1alpha1.CassandraCluster) error {\n\treturn e.syncStatefulSets(cluster)\n}\n<|endoftext|>"}
{"text":"<commit_before>package vendor\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestDeduceRemoteRepo(t *testing.T) {\n\tif testing.Short() {\n\t\tt.Skipf(\"skipping network tests in -short mode\")\n\t}\n\ttests := []struct {\n\t\tpath     string\n\t\twant     RemoteRepo\n\t\textra    string\n\t\terr      error\n\t\tinsecure bool\n\t}{{\n\t\tpath: \"\",\n\t\terr:  fmt.Errorf(`\"\" is not a valid import path`),\n\t}, {\n\t\tpath: \"corporate\",\n\t\terr:  fmt.Errorf(`\"corporate\" is not a valid import path`),\n\t}, {\n\t\tpath: \"github.com\/cznic\/b\",\n\t\twant: &gitrepo{\n\t\t\turl: \"https:\/\/github.com\/cznic\/b\",\n\t\t},\n\t}, {\n\t\tpath: \"github.com\/pkg\/sftp\",\n\t\twant: &gitrepo{\n\t\t\turl: \"https:\/\/github.com\/pkg\/sftp\",\n\t\t},\n\t}, {\n\t\tpath: \"github.com\/pkg\/sftp\/examples\/gsftp\",\n\t\twant: &gitrepo{\n\t\t\turl: \"https:\/\/github.com\/pkg\/sftp\",\n\t\t},\n\t\textra: \"\/examples\/gsftp\",\n\t}, {\n\t\tpath: \"github.com\/coreos\/go-etcd\",\n\t\twant: &gitrepo{\n\t\t\turl: \"https:\/\/github.com\/coreos\/go-etcd\",\n\t\t},\n\t}, {\n\t\tpath: \"bitbucket.org\/davecheney\/gitrepo\/cmd\/main\",\n\t\twant: &gitrepo{\n\t\t\turl: \"https:\/\/bitbucket.org\/davecheney\/gitrepo\",\n\t\t},\n\t\textra: \"\/cmd\/main\",\n\t}, {\n\t\tpath: \"bitbucket.org\/davecheney\/hgrepo\/cmd\/main\",\n\t\twant: &hgrepo{\n\t\t\turl: \"https:\/\/bitbucket.org\/davecheney\/hgrepo\",\n\t\t},\n\t\textra: \"\/cmd\/main\",\n\t}, {\n\t\tpath: \"code.google.com\/p\/goauth2\/oauth\",\n\t\twant: &hgrepo{\n\t\t\turl: \"https:\/\/code.google.com\/p\/goauth2\",\n\t\t},\n\t\textra: \"\/oauth\",\n\t}, {\n\t\tpath: \"code.google.com\/p\/gami\",\n\t\twant: &gitrepo{\n\t\t\turl: \"https:\/\/code.google.com\/p\/gami\",\n\t\t},\n\t}, {\n\t\tpath: \"git.eclipse.org\/gitroot\/paho\/org.eclipse.paho.mqtt.golang.git\",\n\t\twant: &gitrepo{\n\t\t\turl: \"https:\/\/git.eclipse.org\/gitroot\/paho\/org.eclipse.paho.mqtt.golang.git\",\n\t\t},\n\t}, {\n\t\tpath: \"git.apache.org\/thrift.git\/lib\/go\/thrift\",\n\t\twant: &gitrepo{\n\t\t\turl: \"https:\/\/git.apache.org\/thrift.git\",\n\t\t},\n\t\textra: \"\/lib\/go\/thrift\",\n\t}, {\n\t\tpath: \"gopkg.in\/check.v1\",\n\t\twant: &gitrepo{\n\t\t\turl: \"https:\/\/gopkg.in\/check.v1\",\n\t\t},\n\t\textra: \"\",\n\t}, {\n\t\tpath: \"golang.org\/x\/tools\/go\/vcs\",\n\t\twant: &gitrepo{\n\t\t\turl: \"https:\/\/go.googlesource.com\/tools\",\n\t\t},\n\t\textra: \"\/go\/vcs\",\n\t}, {\n\t\tpath: \"labix.org\/v2\/mgo\",\n\t\twant: &bzrrepo{\n\t\t\turl: \"https:\/\/launchpad.net\/mgo\/v2\",\n\t\t},\n\t\tinsecure: true,\n\t}, {\n\t\tpath: \"launchpad.net\/gnuflag\",\n\t\twant: &bzrrepo{\n\t\t\turl: \"https:\/\/launchpad.net\/gnuflag\",\n\t\t},\n\t}, {\n\t\tpath: \"https:\/\/github.com\/pkg\/sftp\",\n\t\twant: &gitrepo{\n\t\t\turl: \"https:\/\/github.com\/pkg\/sftp\",\n\t\t},\n\t}, {\n\t\tpath: \"git:\/\/github.com\/pkg\/sftp\",\n\t\twant: &gitrepo{\n\t\t\turl: \"git:\/\/github.com\/pkg\/sftp\",\n\t\t},\n\t\tinsecure: true,\n\t}, {\n\t\tpath: \"code.google.com\/p\/google-api-go-client\/bigquery\/v2\",\n\t\twant: &hgrepo{\n\t\t\turl: \"https:\/\/code.google.com\/p\/google-api-go-client\",\n\t\t},\n\t\textra: \"\/bigquery\/v2\",\n\t}}\n\n\tfor _, tt := range tests {\n\t\tt.Logf(\"DeduceRemoteRepo(%q, %v)\", tt.path, tt.insecure)\n\t\tgot, extra, err := DeduceRemoteRepo(tt.path, tt.insecure)\n\t\tif !reflect.DeepEqual(err, tt.err) {\n\t\t\tt.Errorf(\"DeduceRemoteRepo(%q): want err: %v, got err: %v\", tt.path, tt.err, err)\n\t\t\tcontinue\n\t\t}\n\t\tif !reflect.DeepEqual(got, tt.want) || extra != tt.extra {\n\t\t\tt.Errorf(\"DeduceRemoteRepo(%q): want %#v, %v, got %#v, %v\", tt.path, tt.want, tt.extra, got, extra)\n\t\t}\n\t}\n}\n<commit_msg>Extra tests<commit_after>package vendor\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestDeduceRemoteRepo(t *testing.T) {\n\tif testing.Short() {\n\t\tt.Skipf(\"skipping network tests in -short mode\")\n\t}\n\ttests := []struct {\n\t\tpath     string\n\t\twant     RemoteRepo\n\t\textra    string\n\t\terr      error\n\t\tinsecure bool\n\t}{{\n\t\tpath: \"\",\n\t\terr:  fmt.Errorf(`\"\" is not a valid import path`),\n\t}, {\n\t\tpath: \"corporate\",\n\t\terr:  fmt.Errorf(`\"corporate\" is not a valid import path`),\n\t}, {\n\t\tpath: \"github.com\/cznic\/b\",\n\t\twant: &gitrepo{\n\t\t\turl: \"https:\/\/github.com\/cznic\/b\",\n\t\t},\n\t}, {\n\t\tpath: \"github.com\/pkg\/sftp\",\n\t\twant: &gitrepo{\n\t\t\turl: \"https:\/\/github.com\/pkg\/sftp\",\n\t\t},\n\t}, {\n\t\tpath: \"github.com\/pkg\/sftp\/examples\/gsftp\",\n\t\twant: &gitrepo{\n\t\t\turl: \"https:\/\/github.com\/pkg\/sftp\",\n\t\t},\n\t\textra: \"\/examples\/gsftp\",\n\t}, {\n\t\tpath: \"github.com\/coreos\/go-etcd\",\n\t\twant: &gitrepo{\n\t\t\turl: \"https:\/\/github.com\/coreos\/go-etcd\",\n\t\t},\n\t}, {\n\t\tpath: \"bitbucket.org\/davecheney\/gitrepo\/cmd\/main\",\n\t\twant: &gitrepo{\n\t\t\turl: \"https:\/\/bitbucket.org\/davecheney\/gitrepo\",\n\t\t},\n\t\textra: \"\/cmd\/main\",\n\t}, {\n\t\tpath: \"bitbucket.org\/davecheney\/hgrepo\/cmd\/main\",\n\t\twant: &hgrepo{\n\t\t\turl: \"https:\/\/bitbucket.org\/davecheney\/hgrepo\",\n\t\t},\n\t\textra: \"\/cmd\/main\",\n\t}, {\n\t\tpath: \"code.google.com\/p\/goauth2\/oauth\",\n\t\twant: &hgrepo{\n\t\t\turl: \"https:\/\/code.google.com\/p\/goauth2\",\n\t\t},\n\t\textra: \"\/oauth\",\n\t}, {\n\t\tpath: \"code.google.com\/p\/gami\",\n\t\twant: &gitrepo{\n\t\t\turl: \"https:\/\/code.google.com\/p\/gami\",\n\t\t},\n\t}, {\n\t\tpath: \"git.eclipse.org\/gitroot\/paho\/org.eclipse.paho.mqtt.golang.git\",\n\t\twant: &gitrepo{\n\t\t\turl: \"https:\/\/git.eclipse.org\/gitroot\/paho\/org.eclipse.paho.mqtt.golang.git\",\n\t\t},\n\t}, {\n\t\tpath: \"git.apache.org\/thrift.git\/lib\/go\/thrift\",\n\t\twant: &gitrepo{\n\t\t\turl: \"https:\/\/git.apache.org\/thrift.git\",\n\t\t},\n\t\textra: \"\/lib\/go\/thrift\",\n\t}, {\n\t\tpath: \"gopkg.in\/check.v1\",\n\t\twant: &gitrepo{\n\t\t\turl: \"https:\/\/gopkg.in\/check.v1\",\n\t\t},\n\t\textra: \"\",\n\t}, {\n\t\tpath: \"golang.org\/x\/tools\/go\/vcs\",\n\t\twant: &gitrepo{\n\t\t\turl: \"https:\/\/go.googlesource.com\/tools\",\n\t\t},\n\t\textra: \"\/go\/vcs\",\n\t}, {\n\t\tpath: \"labix.org\/v2\/mgo\",\n\t\twant: &bzrrepo{\n\t\t\turl: \"https:\/\/launchpad.net\/mgo\/v2\",\n\t\t},\n\t\tinsecure: true,\n\t}, {\n\t\tpath: \"launchpad.net\/gnuflag\",\n\t\twant: &bzrrepo{\n\t\t\turl: \"https:\/\/launchpad.net\/gnuflag\",\n\t\t},\n\t}, {\n\t\tpath: \"https:\/\/github.com\/pkg\/sftp\",\n\t\twant: &gitrepo{\n\t\t\turl: \"https:\/\/github.com\/pkg\/sftp\",\n\t\t},\n\t}, {\n\t\tpath: \"git:\/\/github.com\/pkg\/sftp\",\n\t\twant: &gitrepo{\n\t\t\turl: \"git:\/\/github.com\/pkg\/sftp\",\n\t\t},\n\t\tinsecure: true,\n\t}, {\n\t\tpath: \"code.google.com\/p\/google-api-go-client\/bigquery\/v2\",\n\t\twant: &hgrepo{\n\t\t\turl: \"https:\/\/code.google.com\/p\/google-api-go-client\",\n\t\t},\n\t\textra: \"\/bigquery\/v2\",\n\t}, {\n\t\tpath: \"code.google.com\/p\/go-sqlite\/go1\/sqlite3\",\n\t\twant: &hgrepo{\n\t\t\turl: \"https:\/\/code.google.com\/p\/go-sqlite\",\n\t\t},\n\t\textra: \"\/go1\/sqlite3\",\n\t}}\n\n\tfor _, tt := range tests {\n\t\tt.Logf(\"DeduceRemoteRepo(%q, %v)\", tt.path, tt.insecure)\n\t\tgot, extra, err := DeduceRemoteRepo(tt.path, tt.insecure)\n\t\tif !reflect.DeepEqual(err, tt.err) {\n\t\t\tt.Errorf(\"DeduceRemoteRepo(%q): want err: %v, got err: %v\", tt.path, tt.err, err)\n\t\t\tcontinue\n\t\t}\n\t\tif !reflect.DeepEqual(got, tt.want) || extra != tt.extra {\n\t\t\tt.Errorf(\"DeduceRemoteRepo(%q): want %#v, %v, got %#v, %v\", tt.path, tt.want, tt.extra, got, extra)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package cryptica\n\nimport \"bytes\"\n\ntype Solution []Direction\n\nfunc (solution *Solution) String() string {\n\tvar buffer bytes.Buffer\n\tfor i, dir := range *solution {\n\t\tswitch {\n\t\tcase i > 0:\n\t\t\tbuffer.WriteRune(' ')\n\t\tdefault:\n\t\t\tbuffer.WriteString(dir.String())\n\t\t}\n\t}\n\treturn buffer.String()\n}\n\ntype Game struct {\n\tState State\n\tGoal  Goal\n\tSteps int\n}\n\ntype Solver interface {\n\tsolve(game Game, solutions chan Solution)\n}\n\ntype DepthFirstSolver struct {\n}\n\nfunc (solver DepthFirstSolver) solve(game Game, solutions chan Solution) {\n\tcache := make(map[uint64]int)\n\tf := func(state State, solution Solution, k interface{}) {\n\t\tn := len(solution)\n\t\tif n > game.Steps {\n\t\t\treturn\n\t\t}\n\t\tcode := state.Board.Encode(state)\n\t\tif m, exists := cache[code]; exists && m <= n {\n\t\t\treturn\n\t\t}\n\t\tcache[code] = n\n\t\tif state.Match(game.Goal) {\n\t\t\tnewsolution := make(Solution, len(solution))\n\t\t\tcopy(newsolution, solution)\n\t\t\tsolutions <- newsolution\n\t\t\treturn\n\t\t}\n\t\tf := k.(func(State, Solution, interface{}))\n\t\tfor i := Up; i <= Right; i++ {\n\t\t\tdir := Direction(i)\n\t\t\tf(state.Move(dir), append(solution, dir), k)\n\t\t}\n\t}\n\tf(game.State, make(Solution, 0), f)\n}\n\ntype BreadthFirstSolver struct {\n}\n\nfunc (solver BreadthFirstSolver) solve(game Game, solutions chan Solution) {\n\tcache := make(map[uint64]Solution)\n\tvar current, next []uint64\n\t{\n\t\tcode := game.State.Board.Encode(game.State)\n\t\tcache[code] = make(Solution, 0)\n\t\tcurrent = []uint64{code}\n\t}\n\tfor len(current) > 0 {\n\t\tnext = make([]uint64, 0)\n\t\tfor _, code := range current {\n\t\t\tsolution := cache[code]\n\t\t\tstate := game.State.Board.Decode(code)\n\t\t\tif state.Match(game.Goal) {\n\t\t\t\tsolutions <- solution\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor i := Up; i <= Right; i++ {\n\t\t\t\tdir := Direction(i)\n\t\t\t\tnewstate := state.Move(dir)\n\t\t\t\tnewcode := game.State.Board.Encode(newstate)\n\t\t\t\tif _, exists := cache[newcode]; !exists {\n\t\t\t\t\tnewsolution := make(Solution, len(solution))\n\t\t\t\t\tcopy(newsolution, solution)\n\t\t\t\t\tnewsolution = append(newsolution, dir)\n\t\t\t\t\tcache[newcode] = newsolution\n\t\t\t\t\tnext = append(next, newcode)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcurrent = next\n\t}\n}\n<commit_msg>breadth-first search now also stops at Steps<commit_after>package cryptica\n\nimport \"bytes\"\n\ntype Solution []Direction\n\nfunc (solution *Solution) String() string {\n\tvar buffer bytes.Buffer\n\tfor i, dir := range *solution {\n\t\tswitch {\n\t\tcase i > 0:\n\t\t\tbuffer.WriteRune(' ')\n\t\tdefault:\n\t\t\tbuffer.WriteString(dir.String())\n\t\t}\n\t}\n\treturn buffer.String()\n}\n\ntype Game struct {\n\tState State\n\tGoal  Goal\n\tSteps int\n}\n\ntype Solver interface {\n\tsolve(game Game, solutions chan Solution)\n}\n\ntype DepthFirstSolver struct {\n}\n\nfunc (solver DepthFirstSolver) solve(game Game, solutions chan Solution) {\n\tcache := make(map[uint64]int)\n\tf := func(state State, solution Solution, k interface{}) {\n\t\tn := len(solution)\n\t\tif n > game.Steps {\n\t\t\treturn\n\t\t}\n\t\tcode := state.Board.Encode(state)\n\t\tif m, exists := cache[code]; exists && m <= n {\n\t\t\treturn\n\t\t}\n\t\tcache[code] = n\n\t\tif state.Match(game.Goal) {\n\t\t\tnewsolution := make(Solution, len(solution))\n\t\t\tcopy(newsolution, solution)\n\t\t\tsolutions <- newsolution\n\t\t\treturn\n\t\t}\n\t\tf := k.(func(State, Solution, interface{}))\n\t\tfor i := Up; i <= Right; i++ {\n\t\t\tdir := Direction(i)\n\t\t\tf(state.Move(dir), append(solution, dir), k)\n\t\t}\n\t}\n\tf(game.State, make(Solution, 0), f)\n}\n\ntype BreadthFirstSolver struct {\n}\n\nfunc (solver BreadthFirstSolver) solve(game Game, solutions chan Solution) {\n\tcache := make(map[uint64]Solution)\n\tvar current, next []uint64\n\t{\n\t\tcode := game.State.Board.Encode(game.State)\n\t\tcache[code] = make(Solution, 0)\n\t\tcurrent = []uint64{code}\n\t}\n\tfor depth := 0; depth < game.Steps && len(current) > 0; depth++ {\n\t\tnext = make([]uint64, 0)\n\t\tfor _, code := range current {\n\t\t\tsolution := cache[code]\n\t\t\tstate := game.State.Board.Decode(code)\n\t\t\tif state.Match(game.Goal) {\n\t\t\t\tsolutions <- solution\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor i := Up; i <= Right; i++ {\n\t\t\t\tdir := Direction(i)\n\t\t\t\tnewstate := state.Move(dir)\n\t\t\t\tnewcode := game.State.Board.Encode(newstate)\n\t\t\t\tif _, exists := cache[newcode]; !exists {\n\t\t\t\t\tnewsolution := make(Solution, len(solution))\n\t\t\t\t\tcopy(newsolution, solution)\n\t\t\t\t\tnewsolution = append(newsolution, dir)\n\t\t\t\t\tcache[newcode] = newsolution\n\t\t\t\t\tnext = append(next, newcode)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcurrent = next\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc TestInitialiseKubeconfig(t *testing.T) {\n\n\tcmd := make([]string, 2)\n\tcmd[0] = \"install\"\n\tcmd[1] = \"--debug\"\n\n\tplugin := Plugin{\n\t\tConfig: Config{\n\t\t\tAPIServer:     \"http:\/\/myapiserver\",\n\t\t\tToken:         \"secret-token\",\n\t\t\tHelmCommand:   cmd,\n\t\t\tNamespace:     \"default\",\n\t\t\tSkipTLSVerify: true,\n\t\t},\n\t}\n\n\tinitialiseKubeconfig(&plugin.Config, \"kubeconfig\", \"config3.test\")\n\n}\n\nfunc TestGetHelmCommand(t *testing.T) {\n\tplugin := &Plugin{\n\t\tConfig: Config{\n\t\t\tAPIServer:     \"http:\/\/myapiserver\",\n\t\t\tToken:         \"secret-token\",\n\t\t\tHelmCommand:   nil,\n\t\t\tNamespace:     \"default\",\n\t\t\tSkipTLSVerify: true,\n\t\t\tDebug:         true,\n\t\t\tDryRun:        true,\n\t\t\tChart:         \".\/chart\/test\",\n\t\t\tRelease:       \"test-release\",\n\t\t},\n\t}\n\tsetHelmCommand(plugin)\n\tfmt.Println(plugin.Config.HelmCommand)\n\n}\n<commit_msg>remove debug from test<commit_after>package main\n\nimport (\n\t\"io\/ioutil\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestInitialiseKubeconfig(t *testing.T) {\n\n\tcmd := make([]string, 2)\n\tcmd[0] = \"install\"\n\tcmd[1] = \"--debug\"\n\n\tplugin := Plugin{\n\t\tConfig: Config{\n\t\t\tAPIServer:     \"http:\/\/myapiserver\",\n\t\t\tToken:         \"secret-token\",\n\t\t\tHelmCommand:   cmd,\n\t\t\tNamespace:     \"default\",\n\t\t\tSkipTLSVerify: true,\n\t\t},\n\t}\n\n\tconfigfile := \"config3.test\"\n\tinitialiseKubeconfig(&plugin.Config, \"kubeconfig\", configfile)\n\tdata, err := ioutil.ReadFile(configfile)\n\tif err != nil {\n\t\tt.Errorf(\"Error reading file %v\", err)\n\t}\n\tkubeConfigStr := string(data)\n\n\tif !strings.Contains(kubeConfigStr, \"secret-token\") {\n\t\tt.Errorf(\"Kubeconfig doesn't render token\")\n\t}\n\tif !strings.Contains(kubeConfigStr, \"http:\/\/myapiserver\") {\n\t\tt.Errorf(\"Kubeconfig doesn't render APIServer\")\n\t}\n\n}\n\nfunc TestGetHelmCommand(t *testing.T) {\n\tplugin := &Plugin{\n\t\tConfig: Config{\n\t\t\tAPIServer:     \"http:\/\/myapiserver\",\n\t\t\tToken:         \"secret-token\",\n\t\t\tHelmCommand:   nil,\n\t\t\tNamespace:     \"default\",\n\t\t\tSkipTLSVerify: true,\n\t\t\tDebug:         true,\n\t\t\tDryRun:        true,\n\t\t\tChart:         \".\/chart\/test\",\n\t\t\tRelease:       \"test-release\",\n\t\t},\n\t}\n\tsetHelmCommand(plugin)\n\tres := strings.Join(plugin.Config.HelmCommand[:], \" \")\n\texpected := \"upgrade --install test-release .\/chart\/test --debug --dry-run\"\n\tif res != expected {\n\t\tt.Errorf(\"Result is %s and we expected %s\", res, expected)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package ws\n\nimport (\n\t\"net\/http\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/gin-gonic\/gin\"\n\t\"github.com\/gorilla\/websocket\"\n)\n\nvar wsUpgrader = websocket.Upgrader{\n\tReadBufferSize:  1024,\n\tWriteBufferSize: 1024,\n\tCheckOrigin:     func(r *http.Request) bool { return true },\n}\n\n\/\/ InitWS add ws handler for api\nfunc InitWS(router *gin.Engine) {\n\trouter.GET(\"\/ws\", wsHandler)\n}\n\nfunc wsHandler(c *gin.Context) {\n\tconn, err := wsUpgrader.Upgrade(c.Writer, c.Request, nil)\n\tif err != nil {\n\t\tlogrus.Warnf(\"Failed to set websocket upgrade %+v\", err)\n\t\tc.AbortWithStatus(http.StatusBadRequest)\n\t}\n\tdefer conn.Close()\n\n\tfor {\n\t\tt, msg, err := conn.ReadMessage()\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\tlogrus.Debugf(\"Got ws message type=%d %s\", t, msg)\n\t\tconn.WriteMessage(t, msg)\n\t}\n}\n<commit_msg>Added ws authentication<commit_after>package ws\n\nimport (\n\t\"encoding\/json\"\n\t\"net\/http\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/da4nik\/swanager\/core\/auth\"\n\t\"github.com\/da4nik\/swanager\/core\/entities\"\n\t\"github.com\/gin-gonic\/gin\"\n\t\"github.com\/gorilla\/websocket\"\n)\n\ntype authMessage struct {\n\tToken string `json:\"token\"`\n}\n\ntype answer struct {\n\tAnswerType string `json:\"type\"`\n\tData       string\n}\n\ntype connContext struct {\n\tState     string\n\tUser      *entities.User\n\tConn      *websocket.Conn\n\tAuthError error\n}\n\nconst (\n\tstateWorking         = \"working\"\n\tstateUnauthenticated = \"unauthenticated\"\n)\n\nvar wsUpgrader = websocket.Upgrader{\n\tReadBufferSize:  1024,\n\tWriteBufferSize: 1024,\n\tCheckOrigin:     func(r *http.Request) bool { return true },\n}\n\n\/\/ InitWS add ws handler for api\nfunc InitWS(router *gin.Engine) {\n\trouter.GET(\"\/ws\", wsHandler)\n}\n\nfunc wsHandler(c *gin.Context) {\n\tconn, err := wsUpgrader.Upgrade(c.Writer, c.Request, nil)\n\tif err != nil {\n\t\tlogrus.Warnf(\"Failed to set websocket upgrade %+v\", err)\n\t\tc.AbortWithStatus(http.StatusBadRequest)\n\t}\n\tdefer conn.Close()\n\n\tcontext := connContext{\n\t\tState: stateUnauthenticated,\n\t\tConn:  conn,\n\t}\n\n\tfor {\n\t\tt, msg, err := conn.ReadMessage()\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tlogrus.Debugf(\"[%s] Got ws message type=%d %s\", context.State, t, msg)\n\n\t\tswitch context.State {\n\t\tcase stateUnauthenticated:\n\t\t\tcontext.authenticate(msg)\n\t\t\tbreak\n\t\tcase stateWorking:\n\t\t\tcontext.processMessage(msg)\n\t\t}\n\t}\n}\n\nfunc (c *connContext) processMessage(msg []byte) {\n\tc.Conn.WriteMessage(1, msg)\n}\n\nfunc (c *connContext) authenticate(msg []byte) {\n\tvar message authMessage\n\tc.AuthError = json.Unmarshal(msg, &message)\n\tif c.AuthError != nil {\n\t\tc.authError()\n\t\treturn\n\t}\n\n\tc.User, c.AuthError = auth.WithToken(message.Token)\n\tif c.AuthError != nil {\n\t\tc.authError()\n\t\treturn\n\t}\n\n\tlogrus.Debugf(\"[WS] Authenticated, proceeding with normal mode\")\n\n\tc.State = stateWorking\n\n\tc.sendAnswer(answer{\n\t\tAnswerType: \"authenticated\",\n\t\tData:       \"Ok\",\n\t})\n}\n\nfunc (c *connContext) authError() {\n\tlogrus.Debugf(\"[WS] Auth error: %s\", c.AuthError.Error())\n\n\tc.sendAnswer(answer{\n\t\tAnswerType: \"error\",\n\t\tData:       c.AuthError.Error(),\n\t})\n\n\tc.Conn.Close()\n}\n\nfunc (c *connContext) sendAnswer(ans answer) {\n\tresult, _ := json.Marshal(ans)\n\tc.Conn.WriteMessage(1, result)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"sync\"\n\t\"sync\/atomic\"\n)\n\nvar wg sync.WaitGroup\n\ntype CallFrame struct {\n\tparent    *CallFrame\n\tvar_table map[string]Object\n\tstack     []Object\n\tme        Object\n}\n\ntype Transaction struct {\n\tstartInst        Instruction\n\tinstList         []Instruction\n\tobjectSet        map[*RObject]*RObject\n\ttransactionStack []*CallFrame\n\tenv              *ThreadEnv\n\tinevitable       bool\n\trev              int64\n}\n\ntype ThreadEnv struct {\n\tinstList      []Instruction\n\tthreadStack   []*CallFrame\n\ttransactionPC *Transaction\n\tid            int\n}\n\ntype GobiesVM struct {\n\tinstList       []Instruction\n\tcallFrameStack []*CallFrame\n\tconsts         map[string]*RObject\n\tsymbols        map[string]int\n\trev            int64\n\tglobalLock     sync.RWMutex\n\thas_inevitable int32\n}\n\nfunc initVM() *GobiesVM {\n\tVM := &GobiesVM{}\n\ttop := initCallFrame()\n\tVM.callFrameStack = append(VM.callFrameStack, top)\n\tVM.consts = make(map[string]*RObject)\n\tVM.initConsts()\n\tVM.symbols = make(map[string]int)\n\ttop.me = initRKernel()\n\treturn VM\n}\n\nfunc initCallFrame() *CallFrame {\n\tframe := &CallFrame{}\n\tframe.var_table = make(map[string]Object)\n\treturn frame\n}\n\nfunc (VM *GobiesVM) initConsts() {\n\tVM.consts[\"RString\"] = initRString()\n\tVM.consts[\"RFixnum\"] = initRFixnum()\n\tVM.consts[\"RArray\"] = initRArray()\n\tVM.consts[\"RHash\"] = initRHash()\n\tVM.consts[\"IO\"] = initRIO()\n\tVM.consts[\"Thread\"] = initRThread()\n}\n\nfunc (obj *RObject) methodLookup(method_name string) *RMethod {\n\tif val, ok := obj.methods[method_name]; ok {\n\t\treturn val\n\t}\n\tif obj.class != nil {\n\t\treturn obj.class.methodLookup(method_name)\n\t}\n\treturn nil\n}\n\nfunc (currentCallFrame *CallFrame) variableLookup(var_name string) Object {\n\tif obj, ok := currentCallFrame.var_table[var_name]; ok {\n\t\treturn obj\n\t}\n\tif currentCallFrame.parent != nil {\n\t\treturn currentCallFrame.parent.variableLookup(var_name)\n\t}\n\treturn nil\n}\n\nfunc (t *Transaction) initTransaction(env *ThreadEnv, instList []Instruction) *Transaction {\n\tt.instList = []Instruction{}\n\tfor _, inst := range instList {\n\t\tt.instList = append(t.instList, inst)\n\t}\n\tt.transactionStack = copyFrames(env.threadStack)\n\tt.objectSet = make(map[*RObject]*RObject)\n\treturn t\n}\n\nfunc copyFrames(src []*CallFrame) []*CallFrame {\n\tnewStack := []*CallFrame{}\n\tfor _, frame := range src {\n\t\tnewFrame := initCallFrame()\n\t\tnewFrame.me = frame.me\n\t\tnewFrame.parent = frame.parent\n\n\t\t\/\/ Copy every object \"pointer\" in old frame stack\n\t\tfor _, obj := range frame.stack {\n\t\t\tnewFrame.stack = append(newFrame.stack, obj)\n\t\t}\n\n\t\t\/\/ Copy every object \"pointer\" in instance variable table\n\t\tfor key, obj := range frame.var_table {\n\t\t\tnewFrame.var_table[key] = obj\n\t\t}\n\n\t\tnewStack = append(newStack, newFrame)\n\t}\n\treturn newStack\n}\n\nfunc (obj *RObject) copyObject(src *RObject) {\n\t\/\/ Copy instance variables\n\tivars := src.ivars\n\tfor k, v := range ivars {\n\t\tobj.ivars[k] = v\n\t}\n}\n\nfunc addRObjectToSet(obj *RObject, env *ThreadEnv) *RObject {\n\tif env == nil { \/\/ created during complication\n\t\treturn obj\n\t}\n\tif _, ok := env.transactionPC.objectSet[obj]; !ok {\n\t\tenv.transactionPC.objectSet[obj] = obj\n\t}\n\treturn obj\n}\n\nfunc (VM *GobiesVM) execute() {\n\t\/\/ \troot := initTransaction(VM.instList)\n\t\/\/ \troot.inevitable = true\n\n\tVM.rev = 0\n\n\t\/\/ Execute root transaction which is inevitable\n\twg.Add(1)\n\tgo VM.executeThread(VM.instList, nil)\n\twg.Wait()\n}\n\nfunc (VM *GobiesVM) executeThread(instList []Instruction, parentScope *ThreadEnv) {\n\t\/\/ Create clean call frame without pushing back to VM stack\n\tcurrentCallFrame := initCallFrame()\n\n\tenv := &ThreadEnv{instList: instList}\n\tif parentScope == nil {\n\t\tcurrentCallFrame.parent = VM.callFrameStack[len(VM.callFrameStack)-1]\n\t} else {\n\t\tenv.threadStack = copyFrames(parentScope.threadStack)\n\t\tcurrentCallFrame.parent = env.threadStack[len(env.threadStack)-1]\n\t\t\/\/ currentCallFrame.parent = parentScope.threadStack[len(parentScope.threadStack)-1]\n\t}\n\tcurrentCallFrame.me = currentCallFrame.parent.me\n\tenv.threadStack = append(env.threadStack, currentCallFrame)\n\n\t\/\/ t.inevitable = true\n\tVM.executeBytecodes(nil, env)\n\twg.Done()\n}\n\nfunc (VM *GobiesVM) transactionBegin(env *ThreadEnv, inst []Instruction) *Transaction {\n\tt := &Transaction{}\n\tt.initTransaction(env, inst)\n\tt.rev = atomic.LoadInt64(&VM.rev)\n\tenv.transactionPC = t\n\tt.env = env\n\n\t\/\/ Initialize environment\n\tif t.inevitable {\n\t\tVM.globalLock.Lock()\n\t\tatomic.StoreInt32(&VM.has_inevitable, 1)\n\t} else {\n\t\tVM.globalLock.RLock()\n\t}\n\n\treturn t\n}\n\nfunc (VM *GobiesVM) transactionEnd(env *ThreadEnv) bool {\n\tt := env.transactionPC\n\n\t\/\/ Lock the write-set\n\tlocked := []*RObject{}\n\tfor orig_obj, new_obj := range t.objectSet {\n\t\t\/\/ fmt.Println(orig_obj, new_obj)\n\t\tif orig_obj != new_obj {\n\t\t\tif orig_obj.writeLock.TryLock() {\n\t\t\t\tlocked = append(locked, orig_obj)\n\t\t\t} else { \/\/ Attempt to acquire lock failed\n\t\t\t\t\/\/ Release all locks\n\t\t\t\tfor _, locked_obj := range locked {\n\t\t\t\t\tlocked_obj.writeLock.Unlock()\n\t\t\t\t}\n\t\t\t\t\/\/ Retry\n\t\t\t\tgoto TRANSACTION_RETRY\n\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Increment global revision\n\tfor !atomic.CompareAndSwapInt64(&VM.rev, VM.rev, VM.rev+1) {\n\t}\n\n\t\/\/ Validate the read-set\n\tfor orig_obj, new_obj := range t.objectSet {\n\t\tif orig_obj == new_obj {\n\t\t\tif orig_obj.rev > t.rev {\n\t\t\t\t\/\/ Release write locks\n\t\t\t\tfor _, locked_obj := range locked {\n\t\t\t\t\tlocked_obj.writeLock.Unlock()\n\t\t\t\t}\n\t\t\t\t\/\/ Retry\n\t\t\t\tgoto TRANSACTION_RETRY\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Commit then release the locks\n\tfor _, locked_obj := range locked {\n\t\tsrc := t.objectSet[locked_obj]\n\t\tlocked_obj.copyObject(src)\n\t}\n\tfor _, locked_obj := range locked {\n\t\tlocked_obj.writeLock.Unlock()\n\t}\n\n\tenv.threadStack = copyFrames(t.transactionStack)\n\n\tif t.inevitable {\n\t\tVM.globalLock.Unlock()\n\t\tatomic.StoreInt32(&VM.has_inevitable, 0)\n\t} else {\n\t\tVM.globalLock.RUnlock()\n\t}\n\n\tenv.transactionPC = nil\n\treturn true\n\nTRANSACTION_RETRY:\n\tt.initTransaction(env, t.instList)\n\tt.rev = atomic.LoadInt64(&VM.rev)\n\treturn false\n}\n\nfunc (VM *GobiesVM) executeBytecodes(instList []Instruction, env *ThreadEnv) {\n\tt := env.transactionPC\n\n\tif instList == nil {\n\t\tinstList = env.instList\n\t}\n\n\t\/\/ SPECULATIVE_EXEC:\n\t\/\/ Speculative execution\n\tfor i, v := range instList {\n\t\tt = env.transactionPC\n\t\tif t == nil {\n\t\t\tt = VM.transactionBegin(env, instList[i:])\n\t\t}\n\t\tcurrentCallFrame := t.transactionStack[len(t.transactionStack)-1]\n\n\t\tswitch v.inst_type {\n\t\tcase BC_PUTSELF:\n\t\t\tcurrentCallFrame.stack = append(currentCallFrame.stack, currentCallFrame.me)\n\t\tcase BC_PUTNIL:\n\t\t\tcurrentCallFrame.stack = append(currentCallFrame.stack, nil)\n\t\tcase BC_PUTOBJ:\n\t\t\tcurrentCallFrame.stack = append(currentCallFrame.stack, v.obj)\n\t\tcase BC_PUTFIXNUM:\n\t\t\tcurrentCallFrame.stack = append(currentCallFrame.stack, RFixnum_new(VM, nil, nil, v.obj.([]Object)))\n\t\tcase BC_PUTSTRING:\n\t\t\tcurrentCallFrame.stack = append(currentCallFrame.stack, RString_new(VM, nil, nil, v.obj.([]Object)))\n\t\tcase BC_PUTTRUE:\n\t\tcase BC_PUTFALSE:\n\t\tcase BC_SETLOCAL:\n\t\t\ttop := currentCallFrame.stack[len(currentCallFrame.stack)-1]\n\t\t\tcurrentCallFrame.var_table[v.obj.(string)] = top\n\t\t\tcurrentCallFrame.stack = currentCallFrame.stack[0 : len(currentCallFrame.stack)-1] \/\/ Pop object from stack\n\t\tcase BC_GETLOCAL:\n\t\t\tobj := currentCallFrame.variableLookup(v.obj.(string)).(*RObject)\n\t\t\tif _, ok := t.objectSet[obj]; ok {\n\t\t\t\tobj = t.objectSet[obj]\n\t\t\t}\n\t\t\tcurrentCallFrame.stack = append(currentCallFrame.stack, obj)\n\t\t\tif VM.transactionEnd(env) == false {\n\n\t\t\t}\n\t\tcase BC_SETGLOBAL:\n\t\tcase BC_GETGLOBAL:\n\t\tcase BC_SETSYMBOL:\n\t\tcase BC_GETSYMBOL:\n\t\tcase BC_SETCONST:\n\t\tcase BC_GETCONST:\n\t\t\tcurrentCallFrame.stack = append(currentCallFrame.stack, VM.consts[v.obj.(string)])\n\t\tcase BC_SETIVAR:\n\t\tcase BC_GETIVAR:\n\t\tcase BC_SETCVAR:\n\t\tcase BC_GETCVAR:\n\t\tcase BC_SEND:\n\t\t\targLists := currentCallFrame.stack[len(currentCallFrame.stack)-(v.argc+1):] \/\/ argc + 1 ensures inclusion of receiver\n\t\t\tcurrentCallFrame.stack = currentCallFrame.stack[:len(currentCallFrame.stack)-(v.argc+1)]\n\t\t\trecv := argLists[0].(*RObject)\n\t\t\targLists = argLists[1:]\n\t\t\treturn_val := recv.methodLookup(v.obj.(string)).gofunc(VM, env, recv, argLists)\n\t\t\t\/\/ fmt.Println(env.transactionPC)\n\t\t\t\/\/ Update address since some functions might init new transaction\n\t\t\tcurrentCallFrame = env.transactionPC.transactionStack[len(env.transactionPC.transactionStack)-1]\n\t\t\tif return_val != nil {\n\t\t\t\tcurrentCallFrame.stack = append(currentCallFrame.stack, return_val)\n\t\t\t}\n\t\t\tif VM.transactionEnd(env) == false {\n\n\t\t\t}\n\t\tcase BC_JUMP:\n\n\t\t}\n\t}\n\t\/\/ End transaction if any\n\tif env.transactionPC != nil {\n\t\tVM.transactionEnd(env)\n\t}\n}\n\nfunc (VM *GobiesVM) executeBlock(env *ThreadEnv, block *RObject, args []*RObject) {\n\tif env.transactionPC != nil { \/\/ Before\n\t\tVM.transactionEnd(env)\n\t}\n\tt := VM.transactionBegin(env, block.methods[\"def\"].def)\n\n\t\/\/ Create clean call frame\n\tcurrentCallFrame := initCallFrame()\n\tcurrentCallFrame.parent = t.transactionStack[len(t.transactionStack)-1]\n\tcurrentCallFrame.me = currentCallFrame.parent.me\n\tt.transactionStack = append(t.transactionStack, currentCallFrame)\n\n\t\/\/ Fill in arguments to current call frame\n\tif block.ivars[\"params\"] != nil {\n\t\tparams := block.ivars[\"params\"].(*RObject).ivars[\"array\"].([]*RObject)\n\t\tfor i, v := range params {\n\t\t\tvar_name := v.val.str\n\t\t\tcurrentCallFrame.var_table[var_name] = args[i]\n\t\t}\n\t}\n\n\t\/\/ Execute block definition\n\tVM.executeBytecodes(block.methods[\"def\"].def, env)\n\n\tVM.transactionBegin(env, []Instruction{})\n}\n<commit_msg>Eliminate extra \"main\" thread overhead<commit_after>package main\n\nimport (\n\t\"sync\"\n\t\"sync\/atomic\"\n)\n\nvar wg sync.WaitGroup\n\ntype CallFrame struct {\n\tparent    *CallFrame\n\tvar_table map[string]Object\n\tstack     []Object\n\tme        Object\n}\n\ntype Transaction struct {\n\tstartInst        Instruction\n\tinstList         []Instruction\n\tobjectSet        map[*RObject]*RObject\n\ttransactionStack []*CallFrame\n\tenv              *ThreadEnv\n\tinevitable       bool\n\trev              int64\n}\n\ntype ThreadEnv struct {\n\tinstList      []Instruction\n\tthreadStack   []*CallFrame\n\ttransactionPC *Transaction\n\tid            int\n}\n\ntype GobiesVM struct {\n\tinstList       []Instruction\n\tcallFrameStack []*CallFrame\n\tconsts         map[string]*RObject\n\tsymbols        map[string]int\n\trev            int64\n\tglobalLock     sync.RWMutex\n\thas_inevitable int32\n}\n\nfunc initVM() *GobiesVM {\n\tVM := &GobiesVM{}\n\ttop := initCallFrame()\n\tVM.callFrameStack = append(VM.callFrameStack, top)\n\tVM.consts = make(map[string]*RObject)\n\tVM.initConsts()\n\tVM.symbols = make(map[string]int)\n\ttop.me = initRKernel()\n\treturn VM\n}\n\nfunc initCallFrame() *CallFrame {\n\tframe := &CallFrame{}\n\tframe.var_table = make(map[string]Object)\n\treturn frame\n}\n\nfunc (VM *GobiesVM) initConsts() {\n\tVM.consts[\"RString\"] = initRString()\n\tVM.consts[\"RFixnum\"] = initRFixnum()\n\tVM.consts[\"RArray\"] = initRArray()\n\tVM.consts[\"RHash\"] = initRHash()\n\tVM.consts[\"IO\"] = initRIO()\n\tVM.consts[\"Thread\"] = initRThread()\n}\n\nfunc (obj *RObject) methodLookup(method_name string) *RMethod {\n\tif val, ok := obj.methods[method_name]; ok {\n\t\treturn val\n\t}\n\tif obj.class != nil {\n\t\treturn obj.class.methodLookup(method_name)\n\t}\n\treturn nil\n}\n\nfunc (currentCallFrame *CallFrame) variableLookup(var_name string) Object {\n\tif obj, ok := currentCallFrame.var_table[var_name]; ok {\n\t\treturn obj\n\t}\n\tif currentCallFrame.parent != nil {\n\t\treturn currentCallFrame.parent.variableLookup(var_name)\n\t}\n\treturn nil\n}\n\nfunc (t *Transaction) initTransaction(env *ThreadEnv, instList []Instruction) *Transaction {\n\tt.instList = []Instruction{}\n\tfor _, inst := range instList {\n\t\tt.instList = append(t.instList, inst)\n\t}\n\tt.transactionStack = copyFrames(env.threadStack)\n\tt.objectSet = make(map[*RObject]*RObject)\n\treturn t\n}\n\nfunc copyFrames(src []*CallFrame) []*CallFrame {\n\tnewStack := []*CallFrame{}\n\tfor _, frame := range src {\n\t\tnewFrame := initCallFrame()\n\t\tnewFrame.me = frame.me\n\t\tnewFrame.parent = frame.parent\n\n\t\t\/\/ Copy every object \"pointer\" in old frame stack\n\t\tfor _, obj := range frame.stack {\n\t\t\tnewFrame.stack = append(newFrame.stack, obj)\n\t\t}\n\n\t\t\/\/ Copy every object \"pointer\" in instance variable table\n\t\tfor key, obj := range frame.var_table {\n\t\t\tnewFrame.var_table[key] = obj\n\t\t}\n\n\t\tnewStack = append(newStack, newFrame)\n\t}\n\treturn newStack\n}\n\nfunc (obj *RObject) copyObject(src *RObject) {\n\t\/\/ Copy instance variables\n\tivars := src.ivars\n\tfor k, v := range ivars {\n\t\tobj.ivars[k] = v\n\t}\n}\n\nfunc addRObjectToSet(obj *RObject, env *ThreadEnv) *RObject {\n\tif env == nil { \/\/ created during complication\n\t\treturn obj\n\t}\n\tif _, ok := env.transactionPC.objectSet[obj]; !ok {\n\t\tenv.transactionPC.objectSet[obj] = obj\n\t}\n\treturn obj\n}\n\nfunc (VM *GobiesVM) execute() {\n\t\/\/ \troot := initTransaction(VM.instList)\n\t\/\/ \troot.inevitable = true\n\n\tVM.rev = 0\n\n\t\/\/ Execute root transaction which is inevitable\n\tVM.executeThread(VM.instList, nil)\n\twg.Wait()\n}\n\nfunc (VM *GobiesVM) executeThread(instList []Instruction, parentScope *ThreadEnv) {\n\t\/\/ Create clean call frame without pushing back to VM stack\n\tcurrentCallFrame := initCallFrame()\n\n\tenv := &ThreadEnv{instList: instList}\n\tif parentScope == nil {\n\t\tcurrentCallFrame.parent = VM.callFrameStack[len(VM.callFrameStack)-1]\n\t} else {\n\t\tenv.threadStack = copyFrames(parentScope.threadStack)\n\t\tcurrentCallFrame.parent = env.threadStack[len(env.threadStack)-1]\n\t\t\/\/ currentCallFrame.parent = parentScope.threadStack[len(parentScope.threadStack)-1]\n\t}\n\tcurrentCallFrame.me = currentCallFrame.parent.me\n\tenv.threadStack = append(env.threadStack, currentCallFrame)\n\n\t\/\/ t.inevitable = true\n\tVM.executeBytecodes(nil, env)\n\tif parentScope != nil {\n\t\twg.Done()\n\t}\n}\n\nfunc (VM *GobiesVM) transactionBegin(env *ThreadEnv, inst []Instruction) *Transaction {\n\tt := &Transaction{}\n\tt.initTransaction(env, inst)\n\tt.rev = atomic.LoadInt64(&VM.rev)\n\tenv.transactionPC = t\n\tt.env = env\n\n\t\/\/ Initialize environment\n\tif t.inevitable {\n\t\tVM.globalLock.Lock()\n\t\tatomic.StoreInt32(&VM.has_inevitable, 1)\n\t} else {\n\t\tVM.globalLock.RLock()\n\t}\n\n\treturn t\n}\n\nfunc (VM *GobiesVM) transactionEnd(env *ThreadEnv) bool {\n\tt := env.transactionPC\n\n\t\/\/ Lock the write-set\n\tlocked := []*RObject{}\n\tfor orig_obj, new_obj := range t.objectSet {\n\t\t\/\/ fmt.Println(orig_obj, new_obj)\n\t\tif orig_obj != new_obj {\n\t\t\tif orig_obj.writeLock.TryLock() {\n\t\t\t\tlocked = append(locked, orig_obj)\n\t\t\t} else { \/\/ Attempt to acquire lock failed\n\t\t\t\t\/\/ Release all locks\n\t\t\t\tfor _, locked_obj := range locked {\n\t\t\t\t\tlocked_obj.writeLock.Unlock()\n\t\t\t\t}\n\t\t\t\t\/\/ Retry\n\t\t\t\tgoto TRANSACTION_RETRY\n\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Increment global revision\n\tfor !atomic.CompareAndSwapInt64(&VM.rev, VM.rev, VM.rev+1) {\n\t}\n\n\t\/\/ Validate the read-set\n\tfor orig_obj, new_obj := range t.objectSet {\n\t\tif orig_obj == new_obj {\n\t\t\tif orig_obj.rev > t.rev {\n\t\t\t\t\/\/ Release write locks\n\t\t\t\tfor _, locked_obj := range locked {\n\t\t\t\t\tlocked_obj.writeLock.Unlock()\n\t\t\t\t}\n\t\t\t\t\/\/ Retry\n\t\t\t\tgoto TRANSACTION_RETRY\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Commit then release the locks\n\tfor _, locked_obj := range locked {\n\t\tsrc := t.objectSet[locked_obj]\n\t\tlocked_obj.copyObject(src)\n\t}\n\tfor _, locked_obj := range locked {\n\t\tlocked_obj.writeLock.Unlock()\n\t}\n\n\tenv.threadStack = copyFrames(t.transactionStack)\n\n\tif t.inevitable {\n\t\tVM.globalLock.Unlock()\n\t\tatomic.StoreInt32(&VM.has_inevitable, 0)\n\t} else {\n\t\tVM.globalLock.RUnlock()\n\t}\n\n\tenv.transactionPC = nil\n\treturn true\n\nTRANSACTION_RETRY:\n\tt.initTransaction(env, t.instList)\n\tt.rev = atomic.LoadInt64(&VM.rev)\n\treturn false\n}\n\nfunc (VM *GobiesVM) executeBytecodes(instList []Instruction, env *ThreadEnv) {\n\tt := env.transactionPC\n\n\tif instList == nil {\n\t\tinstList = env.instList\n\t}\n\n\t\/\/ SPECULATIVE_EXEC:\n\t\/\/ Speculative execution\n\tfor i, v := range instList {\n\t\tt = env.transactionPC\n\t\tif t == nil {\n\t\t\tt = VM.transactionBegin(env, instList[i:])\n\t\t}\n\t\tcurrentCallFrame := t.transactionStack[len(t.transactionStack)-1]\n\n\t\tswitch v.inst_type {\n\t\tcase BC_PUTSELF:\n\t\t\tcurrentCallFrame.stack = append(currentCallFrame.stack, currentCallFrame.me)\n\t\tcase BC_PUTNIL:\n\t\t\tcurrentCallFrame.stack = append(currentCallFrame.stack, nil)\n\t\tcase BC_PUTOBJ:\n\t\t\tcurrentCallFrame.stack = append(currentCallFrame.stack, v.obj)\n\t\tcase BC_PUTFIXNUM:\n\t\t\tcurrentCallFrame.stack = append(currentCallFrame.stack, RFixnum_new(VM, nil, nil, v.obj.([]Object)))\n\t\tcase BC_PUTSTRING:\n\t\t\tcurrentCallFrame.stack = append(currentCallFrame.stack, RString_new(VM, nil, nil, v.obj.([]Object)))\n\t\tcase BC_PUTTRUE:\n\t\tcase BC_PUTFALSE:\n\t\tcase BC_SETLOCAL:\n\t\t\ttop := currentCallFrame.stack[len(currentCallFrame.stack)-1]\n\t\t\tcurrentCallFrame.var_table[v.obj.(string)] = top\n\t\t\tcurrentCallFrame.stack = currentCallFrame.stack[0 : len(currentCallFrame.stack)-1] \/\/ Pop object from stack\n\t\tcase BC_GETLOCAL:\n\t\t\tobj := currentCallFrame.variableLookup(v.obj.(string)).(*RObject)\n\t\t\tif _, ok := t.objectSet[obj]; ok {\n\t\t\t\tobj = t.objectSet[obj]\n\t\t\t}\n\t\t\tcurrentCallFrame.stack = append(currentCallFrame.stack, obj)\n\t\t\tif VM.transactionEnd(env) == false {\n\n\t\t\t}\n\t\tcase BC_SETGLOBAL:\n\t\tcase BC_GETGLOBAL:\n\t\tcase BC_SETSYMBOL:\n\t\tcase BC_GETSYMBOL:\n\t\tcase BC_SETCONST:\n\t\tcase BC_GETCONST:\n\t\t\tcurrentCallFrame.stack = append(currentCallFrame.stack, VM.consts[v.obj.(string)])\n\t\tcase BC_SETIVAR:\n\t\tcase BC_GETIVAR:\n\t\tcase BC_SETCVAR:\n\t\tcase BC_GETCVAR:\n\t\tcase BC_SEND:\n\t\t\targLists := currentCallFrame.stack[len(currentCallFrame.stack)-(v.argc+1):] \/\/ argc + 1 ensures inclusion of receiver\n\t\t\tcurrentCallFrame.stack = currentCallFrame.stack[:len(currentCallFrame.stack)-(v.argc+1)]\n\t\t\trecv := argLists[0].(*RObject)\n\t\t\targLists = argLists[1:]\n\t\t\treturn_val := recv.methodLookup(v.obj.(string)).gofunc(VM, env, recv, argLists)\n\t\t\t\/\/ fmt.Println(env.transactionPC)\n\t\t\t\/\/ Update address since some functions might init new transaction\n\t\t\tcurrentCallFrame = env.transactionPC.transactionStack[len(env.transactionPC.transactionStack)-1]\n\t\t\tif return_val != nil {\n\t\t\t\tcurrentCallFrame.stack = append(currentCallFrame.stack, return_val)\n\t\t\t}\n\t\t\tif VM.transactionEnd(env) == false {\n\n\t\t\t}\n\t\tcase BC_JUMP:\n\n\t\t}\n\t}\n\t\/\/ End transaction if any\n\tif env.transactionPC != nil {\n\t\tVM.transactionEnd(env)\n\t}\n}\n\nfunc (VM *GobiesVM) executeBlock(env *ThreadEnv, block *RObject, args []*RObject) {\n\tif env.transactionPC != nil { \/\/ Before\n\t\tVM.transactionEnd(env)\n\t}\n\tt := VM.transactionBegin(env, block.methods[\"def\"].def)\n\n\t\/\/ Create clean call frame\n\tcurrentCallFrame := initCallFrame()\n\tcurrentCallFrame.parent = t.transactionStack[len(t.transactionStack)-1]\n\tcurrentCallFrame.me = currentCallFrame.parent.me\n\tt.transactionStack = append(t.transactionStack, currentCallFrame)\n\n\t\/\/ Fill in arguments to current call frame\n\tif block.ivars[\"params\"] != nil {\n\t\tparams := block.ivars[\"params\"].(*RObject).ivars[\"array\"].([]*RObject)\n\t\tfor i, v := range params {\n\t\t\tvar_name := v.val.str\n\t\t\tcurrentCallFrame.var_table[var_name] = args[i]\n\t\t}\n\t}\n\n\t\/\/ Execute block definition\n\tVM.executeBytecodes(block.methods[\"def\"].def, env)\n\n\tVM.transactionBegin(env, []Instruction{})\n}\n<|endoftext|>"}
{"text":"<commit_before>package generator\n\nvar ProjectTemplate = `\n{{ range $i, $store := .projectTargets }}\n{{- if $store.CurrentTarget }}\n \n  {{- if eq $store.IsSystemProject true }}\n  <source>\n    @type  tail\n    path  \/var\/lib\/rancher\/rke\/log\/*.log\n    pos_file  \/fluentd\/log\/fluentd-rke-logging-system-project.pos\n    time_format  %Y-%m-%dT%H:%M:%S\n    tag  rke.*\n    format  json\n    read_from_head  true\n  <\/source>\n\n  <filter rke.**>\n    @type record_transformer\n    enable_ruby true  \n    <record>\n      tag ${tag}\n      log_type k8s_infrastructure_container \n      driver rke\n      component ${tag_suffix[6].split(\"_\")[0]}\n      container_id ${tag_suffix[6].split(\".\")[0]}\n    <\/record>\n  <\/filter>\n  {{end }}\n\n  <source>\n     @type  tail\n     path  \/var\/log\/containers\/*.log\n     pos_file  \/fluentd\/log\/fluentd-project-{{$store.ProjectName}}-logging.pos\n     time_format  %Y-%m-%dT%H:%M:%S\n     tag  {{$store.ProjectName}}.*\n     format  json\n     read_from_head  true\n  <\/source>\n\n  <filter {{$store.ProjectName}}.**>\n     @type  kubernetes_metadata\n     merge_json_log  true\n     preserve_json_log  true\n  <\/filter>\n\n  <filter {{$store.ProjectName}}.**>\n    @type record_transformer\n    enable_ruby  true\n    <record>\n      tag ${tag}\n      namespace ${record[\"kubernetes\"][\"namespace_name\"]}\n      {{range $k, $val := $store.OutputTags -}}\n      {{$k}} {{$val}}\n      {{end -}}\n      projectID {{$store.ProjectName}}\n    <\/record>\n  <\/filter>\n\n  <filter {{$store.ProjectName}}.**>\n    @type grep\n    <regexp>\n      key namespace\n      pattern {{$store.GrepNamespace}}\n    <\/regexp>\n  <\/filter>\n  \n  <filter {{$store.ProjectName}}.**>\n    @type record_transformer\n    remove_keys namespace\n  <\/filter>\n\n  {{- if eq $store.CurrentTarget \"syslog\"}}\n  {{- if $store.SyslogConfig.Token}}\n  <filter {{$store.ProjectName}}.** project-custom.{{$store.ProjectName}}.** {{ if eq $store.IsSystemProject true }}rke.**{{end }} >\n    @type record_transformer\n    <record>\n      tag ${tag} {{$store.SyslogConfig.Token}}\n    <\/record>\n  <\/filter>\n  {{end }}\n  {{end }}\n\n  <filter {{$store.ProjectName}}.**>\n    @type prometheus\n    <metric>\n      name fluentd_input_status_num_records_total\n      type counter\n      desc The total number of incoming records\n      <labels>\n        tag ${tag}\n        hostname ${hostname}\n      <\/labels>\n    <\/metric>\n  <\/filter>\n\n  <match  {{$store.ProjectName}}.** project-custom.{{$store.ProjectName}}.** {{ if eq $store.IsSystemProject true }}rke.**{{end }}> \n    @type copy\n    <store>\n      {{- if or (eq $store.CurrentTarget \"elasticsearch\") (eq $store.CurrentTarget \"splunk\") (eq $store.CurrentTarget \"syslog\") (eq $store.CurrentTarget \"kafka\") (eq $store.CurrentTarget \"fluentforwarder\")}}\n  \n      {{- if eq $store.CurrentTarget \"elasticsearch\"}}\n      @type elasticsearch\n      include_tag_key  true\n      {{- if and $store.ElasticsearchConfig.AuthUserName $store.ElasticsearchConfig.AuthPassword}}\n      hosts {{$store.ElasticsearchTemplateWrap.Scheme}}:\/\/{{$store.ElasticsearchConfig.AuthUserName}}:{{$store.ElasticsearchConfig.AuthPassword}}@{{$store.ElasticsearchTemplateWrap.Host}}\n      {{else }}\n      hosts {{$store.ElasticsearchConfig.Endpoint}}    \n      {{end }}\n\n      logstash_prefix \"{{$store.ElasticsearchConfig.IndexPrefix}}\"\n      logstash_format true\n      logstash_dateformat  {{$store.ElasticsearchTemplateWrap.DateFormat}}\n      type_name  \"container_log\"\n\n      {{- if eq $store.ElasticsearchTemplateWrap.Scheme \"https\"}}\n      ssl_verify {{$store.ElasticsearchConfig.SSLVerify}}\n      ssl_version {{ $store.ElasticsearchConfig.SSLVersion }}\n\n      {{- if $store.ElasticsearchConfig.Certificate }}\n      ca_file \/fluentd\/etc\/config\/ssl\/project_{{$store.WrapProjectName}}_ca.pem\n      {{end }}\n\n      {{- if and $store.ElasticsearchConfig.ClientCert $store.ElasticsearchConfig.ClientKey}}\n      client_cert \/fluentd\/etc\/config\/ssl\/project_{{$store.WrapProjectName}}_client-cert.pem\n      client_key \/fluentd\/etc\/config\/ssl\/project_{{$store.WrapProjectName}}_client-key.pem\n      {{end }}\n\n      {{- if $store.ElasticsearchConfig.ClientKeyPass}}\n      client_key_pass {{$store.ElasticsearchConfig.ClientKeyPass}}\n      {{end }}\n      {{end }}\n      {{end }}\n\n      {{- if eq $store.CurrentTarget \"splunk\"}}\n      @type splunk_hec\n      host {{$store.SplunkTemplateWrap.Host}}\n      port {{$store.SplunkTemplateWrap.Port}}\n      token {{$store.SplunkConfig.Token}}\n      {{- if $store.SplunkConfig.Source}}\n      sourcetype {{$store.SplunkConfig.Source}}\n      {{end }}\n      {{- if $store.SplunkConfig.Index}}\n      default_index {{ $store.SplunkConfig.Index }}\n      {{end }}\n\n      {{- if eq $store.SplunkTemplateWrap.Scheme \"https\"}}\n      use_ssl true    \n      ssl_verify {{$store.SplunkConfig.SSLVerify}}    \n\n      {{- if $store.SplunkConfig.Certificate }}    \n      ca_file \/fluentd\/etc\/config\/ssl\/project_{{$store.WrapProjectName}}_ca.pem\n      {{end }}\n\n      {{- if and $store.SplunkConfig.ClientCert $store.SplunkConfig.ClientKey}}    \n      client_cert \/fluentd\/etc\/config\/ssl\/project_{{$store.WrapProjectName}}_client-cert.pem\n      client_key \/fluentd\/etc\/config\/ssl\/project_{{$store.WrapProjectName}}_client-key.pem\n      {{end }}\n\n      {{- if $store.SplunkConfig.ClientKeyPass}}    \n      client_key_pass {{ $store.SplunkConfig.ClientKeyPass }}\n      {{end }}\n      {{end }}\n      {{end }}\n\n      {{- if eq $store.CurrentTarget \"kafka\"}}\n      @type kafka_buffered\n      {{- if $store.KafkaConfig.ZookeeperEndpoint }}\n      zookeeper {{$store.WrapKafka.Zookeeper}}\n      {{else}}\n      brokers {{$store.WrapKafka.Brokers}}\n      {{end }}\n      default_topic {{$store.KafkaConfig.Topic}}\n      output_data_type  \"json\"\n      output_include_tag  true\n      output_include_time  true\n      max_send_retries 3\n\n      {{- if $store.KafkaConfig.Certificate }}        \n      ssl_ca_cert \/fluentd\/etc\/config\/ssl\/project_{{$store.WrapProjectName}}_ca.pem\n      {{end }}\n\n      {{- if and $store.KafkaConfig.ClientCert $store.KafkaConfig.ClientKey}}        \n      ssl_client_cert \/fluentd\/etc\/config\/ssl\/project_{{$store.WrapProjectName}}_client-cert.pem\n      ssl_client_cert_key \/fluentd\/etc\/config\/ssl\/project_{{$store.WrapProjectName}}_client-key.pem\n      {{end }}\n\n      {{- if and $store.KafkaConfig.SaslUsername $store.KafkaConfig.SaslPassword}}        \n      username {{$store.KafkaConfig.SaslUsername}}\n      password {{$store.KafkaConfig.SaslPassword}}\n      {{end }}\n  \n      {{- if and (eq $store.KafkaConfig.SaslType \"scram\") $store.KafkaConfig.SaslScramMechanism}}        \n      scram_mechanism {{$store.KafkaConfig.SaslScramMechanism}}\n      {{- if eq $store.KafkaTemplateWrap.IsSSL false}}\n      sasl_over_ssl false\n      {{end}}\n      {{end }}\n      {{end }}\n\n      {{- if eq $store.CurrentTarget \"syslog\"}}\n      @type remote_syslog\n      host {{$store.SyslogTemplateWrap.Host}}\n      port {{$store.SyslogTemplateWrap.Port}}\n      severity {{$store.SyslogConfig.Severity}}\n      protocol {{$store.SyslogConfig.Protocol}}\n      {{- if $store.SyslogConfig.Program }}\n      program {{$store.SyslogConfig.Program}}\n      {{end }}\n      packet_size 65535\n\n      {{- if eq $store.SyslogConfig.SSLVerify true}}\n      verify_mode 1\n      {{else }}\n      verify_mode 0\n      {{end }}\n\n      {{- if $store.SyslogConfig.Certificate }}\n      tls true        \n      ca_file \/fluentd\/etc\/config\/ssl\/project_{{$store.WrapProjectName}}_ca.pem\n      {{end }}\n\n      {{- if and $store.SyslogConfig.ClientCert $store.SyslogConfig.ClientKey}}        \n      client_cert \/fluentd\/etc\/config\/ssl\/project_{{$store.WrapProjectName}}_client-cert.pem\n      client_cert_key \/fluentd\/etc\/config\/ssl\/project_{{$store.WrapProjectName}}_client-key.pem\n      {{end }}\n      {{end }}\n\n      {{- if eq $store.CurrentTarget \"fluentforwarder\"}}\n      @type forward\n      {{- if $store.FluentForwarderConfig.EnableTLS }}\n      transport tls    \n      tls_allow_self_signed_cert true\n      tls_verify_hostname true\n      {{end }}\n      {{- if $store.FluentForwarderConfig.Certificate }}\n      tls_cert_path \/fluentd\/etc\/config\/ssl\/project_{{$store.WrapProjectName}}_ca.pem\n      {{end }}  \n\n      {{- if $store.FluentForwarderConfig.Compress }}\n      compress gzip\n      {{end }}\n\n      {{- if $store.FluentForwarderTemplateWrap.EnableShareKey }}\n      <security>\n        self_hostname \"#{Socket.gethostname}\"\n        shared_key true\n      <\/security>\n      {{end }}\n\n      {{- range $k, $val := $store.FluentForwarderTemplateWrap.FluentServers }}\n      <server>\n        {{if $val.Hostname}}\n        name {{$val.Hostname}}\n        {{end }}\n        host {{$val.Host}}\n        port {{$val.Port}}\n        {{ if $val.SharedKey}}\n        shared_key {{$val.SharedKey}}\n        {{end }}\n        {{ if $val.Username}}\n        username  {{$val.Username}}\n        {{end }}\n        {{ if $val.Password}}\n        password  {{$val.Password}}\n        {{end }}\n        weight  {{$val.Weight}}\n        {{if $val.Standby}}\n        standby\n        {{end }}\n      <\/server>\n      {{end }}\n      {{end }}   \n\n      <buffer>\n        @type file\n        path \/fluentd\/log\/buffer\/project.{{$store.WrapProjectName}}.buffer\n        flush_mode interval\n        flush_interval {{$store.OutputFlushInterval}}s\n        flush_thread_count 8\n        {{- if eq $store.CurrentTarget \"splunk\"}}\n        chunk_limit_size 8m\n        {{end }}\n      <\/buffer> \n\n      slow_flush_log_threshold 40.0\n      queued_chunks_limit_size 200\n      {{end }}\n\n      {{- if eq $store.CurrentTarget \"customtarget\"}}\n      {{$store.CustomTargetWrap.Content}} \n      {{end }}\n    <\/store>\n\n    <store>\n    @type prometheus\n    <metric>\n      name fluentd_output_status_num_records_total\n      type counter\n      desc The total number of outgoing records\n      <labels>\n        tag ${tag}\n        hostname ${hostname}\n      <\/labels>\n    <\/metric>\n    <\/store>\n  <\/match>\n\n{{end }}\n{{end }}\n`\n<commit_msg>fixed the project config template bug<commit_after>package generator\n\nvar ProjectTemplate = `\n{{ range $i, $store := .projectTargets }}\n{{- if $store.CurrentTarget }}\n \n  {{- if eq $store.IsSystemProject true }}\n  <source>\n    @type  tail\n    path  \/var\/lib\/rancher\/rke\/log\/*.log\n    pos_file  \/fluentd\/log\/fluentd-rke-logging-system-project.pos\n    time_format  %Y-%m-%dT%H:%M:%S\n    tag  rke.*\n    format  json\n    read_from_head  true\n  <\/source>\n\n  <filter rke.**>\n    @type record_transformer\n    enable_ruby true  \n    <record>\n      tag ${tag}\n      log_type k8s_infrastructure_container \n      driver rke\n      component ${tag_suffix[6].split(\"_\")[0]}\n      container_id ${tag_suffix[6].split(\".\")[0]}\n    <\/record>\n  <\/filter>\n  {{end }}\n\n  <source>\n     @type  tail\n     path  \/var\/log\/containers\/*.log\n     pos_file  \/fluentd\/log\/fluentd-project-{{$store.ProjectName}}-logging.pos\n     time_format  %Y-%m-%dT%H:%M:%S\n     tag  {{$store.ProjectName}}.*\n     format  json\n     read_from_head  true\n  <\/source>\n\n  <filter {{$store.ProjectName}}.**>\n     @type  kubernetes_metadata\n     merge_json_log  true\n     preserve_json_log  true\n  <\/filter>\n\n  <filter {{$store.ProjectName}}.**>\n    @type record_transformer\n    enable_ruby  true\n    <record>\n      tag ${tag}\n      namespace ${record[\"kubernetes\"][\"namespace_name\"]}\n      {{range $k, $val := $store.OutputTags -}}\n      {{$k}} {{$val}}\n      {{end -}}\n      projectID {{$store.ProjectName}}\n    <\/record>\n  <\/filter>\n\n  <filter {{$store.ProjectName}}.**>\n    @type grep\n    <regexp>\n      key namespace\n      pattern {{$store.GrepNamespace}}\n    <\/regexp>\n  <\/filter>\n  \n  <filter {{$store.ProjectName}}.**>\n    @type record_transformer\n    remove_keys namespace\n  <\/filter>\n\n  {{- if eq $store.CurrentTarget \"syslog\"}}\n  {{- if $store.SyslogConfig.Token}}\n  <filter {{$store.ProjectName}}.** project-custom.{{$store.ProjectName}}.** {{ if eq $store.IsSystemProject true }}rke.**{{end }} >\n    @type record_transformer\n    <record>\n      tag ${tag} {{$store.SyslogConfig.Token}}\n    <\/record>\n  <\/filter>\n  {{end }}\n  {{end }}\n\n  <filter {{$store.ProjectName}}.**>\n    @type prometheus\n    <metric>\n      name fluentd_input_status_num_records_total\n      type counter\n      desc The total number of incoming records\n      <labels>\n        tag ${tag}\n        hostname ${hostname}\n      <\/labels>\n    <\/metric>\n  <\/filter>\n\n  <match  {{$store.ProjectName}}.** project-custom.{{$store.ProjectName}}.** {{ if eq $store.IsSystemProject true }}rke.**{{end }}> \n    @type copy\n    <store>\n      {{- if or (eq $store.CurrentTarget \"elasticsearch\") (eq $store.CurrentTarget \"splunk\") (eq $store.CurrentTarget \"syslog\") (eq $store.CurrentTarget \"kafka\") (eq $store.CurrentTarget \"fluentforwarder\")}}\n  \n      {{- if eq $store.CurrentTarget \"elasticsearch\"}}\n      @type elasticsearch\n      include_tag_key  true\n      {{- if and $store.ElasticsearchConfig.AuthUserName $store.ElasticsearchConfig.AuthPassword}}\n      hosts {{$store.ElasticsearchTemplateWrap.Scheme}}:\/\/{{$store.ElasticsearchConfig.AuthUserName}}:{{$store.ElasticsearchConfig.AuthPassword}}@{{$store.ElasticsearchTemplateWrap.Host}}\n      {{else }}\n      hosts {{$store.ElasticsearchConfig.Endpoint}}    \n      {{end }}\n\n      logstash_prefix \"{{$store.ElasticsearchConfig.IndexPrefix}}\"\n      logstash_format true\n      logstash_dateformat  {{$store.ElasticsearchTemplateWrap.DateFormat}}\n      type_name  \"container_log\"\n\n      {{- if eq $store.ElasticsearchTemplateWrap.Scheme \"https\"}}\n      ssl_verify {{$store.ElasticsearchConfig.SSLVerify}}\n      ssl_version {{ $store.ElasticsearchConfig.SSLVersion }}\n\n      {{- if $store.ElasticsearchConfig.Certificate }}\n      ca_file \/fluentd\/etc\/config\/ssl\/project_{{$store.WrapProjectName}}_ca.pem\n      {{end }}\n\n      {{- if and $store.ElasticsearchConfig.ClientCert $store.ElasticsearchConfig.ClientKey}}\n      client_cert \/fluentd\/etc\/config\/ssl\/project_{{$store.WrapProjectName}}_client-cert.pem\n      client_key \/fluentd\/etc\/config\/ssl\/project_{{$store.WrapProjectName}}_client-key.pem\n      {{end }}\n\n      {{- if $store.ElasticsearchConfig.ClientKeyPass}}\n      client_key_pass {{$store.ElasticsearchConfig.ClientKeyPass}}\n      {{end }}\n      {{end }}\n      {{end }}\n\n      {{- if eq $store.CurrentTarget \"splunk\"}}\n      @type splunk_hec\n      host {{$store.SplunkTemplateWrap.Host}}\n      port {{$store.SplunkTemplateWrap.Port}}\n      token {{$store.SplunkConfig.Token}}\n      {{- if $store.SplunkConfig.Source}}\n      sourcetype {{$store.SplunkConfig.Source}}\n      {{end }}\n      {{- if $store.SplunkConfig.Index}}\n      default_index {{ $store.SplunkConfig.Index }}\n      {{end }}\n\n      {{- if eq $store.SplunkTemplateWrap.Scheme \"https\"}}\n      use_ssl true    \n      ssl_verify {{$store.SplunkConfig.SSLVerify}}    \n\n      {{- if $store.SplunkConfig.Certificate }}    \n      ca_file \/fluentd\/etc\/config\/ssl\/project_{{$store.WrapProjectName}}_ca.pem\n      {{end }}\n\n      {{- if and $store.SplunkConfig.ClientCert $store.SplunkConfig.ClientKey}}    \n      client_cert \/fluentd\/etc\/config\/ssl\/project_{{$store.WrapProjectName}}_client-cert.pem\n      client_key \/fluentd\/etc\/config\/ssl\/project_{{$store.WrapProjectName}}_client-key.pem\n      {{end }}\n\n      {{- if $store.SplunkConfig.ClientKeyPass}}    \n      client_key_pass {{ $store.SplunkConfig.ClientKeyPass }}\n      {{end }}\n      {{end }}\n      {{end }}\n\n      {{- if eq $store.CurrentTarget \"kafka\"}}\n      @type kafka_buffered\n      {{- if $store.KafkaConfig.ZookeeperEndpoint }}\n      zookeeper {{$store.KafkaTemplateWrap.Zookeeper}}\n      {{else}}\n      brokers {{$store.KafkaTemplateWrap.Brokers}}\n      {{end }}\n      default_topic {{$store.KafkaConfig.Topic}}\n      output_data_type  \"json\"\n      output_include_tag  true\n      output_include_time  true\n      max_send_retries 3\n\n      {{- if $store.KafkaConfig.Certificate }}        \n      ssl_ca_cert \/fluentd\/etc\/config\/ssl\/project_{{$store.WrapProjectName}}_ca.pem\n      {{end }}\n\n      {{- if and $store.KafkaConfig.ClientCert $store.KafkaConfig.ClientKey}}        \n      ssl_client_cert \/fluentd\/etc\/config\/ssl\/project_{{$store.WrapProjectName}}_client-cert.pem\n      ssl_client_cert_key \/fluentd\/etc\/config\/ssl\/project_{{$store.WrapProjectName}}_client-key.pem\n      {{end }}\n\n      {{- if and $store.KafkaConfig.SaslUsername $store.KafkaConfig.SaslPassword}}        \n      username {{$store.KafkaConfig.SaslUsername}}\n      password {{$store.KafkaConfig.SaslPassword}}\n      {{end }}\n  \n      {{- if and (eq $store.KafkaConfig.SaslType \"scram\") $store.KafkaConfig.SaslScramMechanism}}        \n      scram_mechanism {{$store.KafkaConfig.SaslScramMechanism}}\n      {{- if eq $store.KafkaTemplateWrap.IsSSL false}}\n      sasl_over_ssl false\n      {{end}}\n      {{end }}\n      {{end }}\n\n      {{- if eq $store.CurrentTarget \"syslog\"}}\n      @type remote_syslog\n      host {{$store.SyslogTemplateWrap.Host}}\n      port {{$store.SyslogTemplateWrap.Port}}\n      severity {{$store.SyslogConfig.Severity}}\n      protocol {{$store.SyslogConfig.Protocol}}\n      {{- if $store.SyslogConfig.Program }}\n      program {{$store.SyslogConfig.Program}}\n      {{end }}\n      packet_size 65535\n\n      {{- if eq $store.SyslogConfig.SSLVerify true}}\n      verify_mode 1\n      {{else }}\n      verify_mode 0\n      {{end }}\n\n      {{- if $store.SyslogConfig.Certificate }}\n      tls true        \n      ca_file \/fluentd\/etc\/config\/ssl\/project_{{$store.WrapProjectName}}_ca.pem\n      {{end }}\n\n      {{- if and $store.SyslogConfig.ClientCert $store.SyslogConfig.ClientKey}}        \n      client_cert \/fluentd\/etc\/config\/ssl\/project_{{$store.WrapProjectName}}_client-cert.pem\n      client_cert_key \/fluentd\/etc\/config\/ssl\/project_{{$store.WrapProjectName}}_client-key.pem\n      {{end }}\n      {{end }}\n\n      {{- if eq $store.CurrentTarget \"fluentforwarder\"}}\n      @type forward\n      {{- if $store.FluentForwarderConfig.EnableTLS }}\n      transport tls    \n      tls_allow_self_signed_cert true\n      tls_verify_hostname true\n      {{end }}\n      {{- if $store.FluentForwarderConfig.Certificate }}\n      tls_cert_path \/fluentd\/etc\/config\/ssl\/project_{{$store.WrapProjectName}}_ca.pem\n      {{end }}  \n\n      {{- if $store.FluentForwarderConfig.Compress }}\n      compress gzip\n      {{end }}\n\n      {{- if $store.FluentForwarderTemplateWrap.EnableShareKey }}\n      <security>\n        self_hostname \"#{Socket.gethostname}\"\n        shared_key true\n      <\/security>\n      {{end }}\n\n      {{- range $k, $val := $store.FluentForwarderTemplateWrap.FluentServers }}\n      <server>\n        {{if $val.Hostname}}\n        name {{$val.Hostname}}\n        {{end }}\n        host {{$val.Host}}\n        port {{$val.Port}}\n        {{ if $val.SharedKey}}\n        shared_key {{$val.SharedKey}}\n        {{end }}\n        {{ if $val.Username}}\n        username  {{$val.Username}}\n        {{end }}\n        {{ if $val.Password}}\n        password  {{$val.Password}}\n        {{end }}\n        weight  {{$val.Weight}}\n        {{if $val.Standby}}\n        standby\n        {{end }}\n      <\/server>\n      {{end }}\n      {{end }}   \n\n      <buffer>\n        @type file\n        path \/fluentd\/log\/buffer\/project.{{$store.WrapProjectName}}.buffer\n        flush_mode interval\n        flush_interval {{$store.OutputFlushInterval}}s\n        flush_thread_count 8\n        {{- if eq $store.CurrentTarget \"splunk\"}}\n        chunk_limit_size 8m\n        {{end }}\n      <\/buffer> \n\n      slow_flush_log_threshold 40.0\n      queued_chunks_limit_size 200\n      {{end }}\n\n      {{- if eq $store.CurrentTarget \"customtarget\"}}\n      {{$store.CustomTargetWrap.Content}} \n      {{end }}\n    <\/store>\n\n    <store>\n    @type prometheus\n    <metric>\n      name fluentd_output_status_num_records_total\n      type counter\n      desc The total number of outgoing records\n      <labels>\n        tag ${tag}\n        hostname ${hostname}\n      <\/labels>\n    <\/metric>\n    <\/store>\n  <\/match>\n\n{{end }}\n{{end }}\n`\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"context\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com\/docker\/docker\/api\/types\"\n\t\"github.com\/docker\/docker\/api\/types\/filters\"\n\t\"github.com\/docker\/docker\/client\"\n\t\"github.com\/docker\/docker\/integration-cli\/cli\"\n\t\"github.com\/docker\/docker\/integration-cli\/cli\/build\"\n\t\"github.com\/docker\/docker\/pkg\/parsers\/kernel\"\n\t\"github.com\/docker\/docker\/testutil\/request\"\n\t\"gotest.tools\/assert\"\n)\n\nfunc (s *DockerSuite) TestAPIImagesFilter(c *testing.T) {\n\tcli, err := client.NewClientWithOpts(client.FromEnv)\n\tassert.NilError(c, err)\n\tdefer cli.Close()\n\n\tname := \"utest:tag1\"\n\tname2 := \"utest\/docker:tag2\"\n\tname3 := \"utest:5000\/docker:tag3\"\n\tfor _, n := range []string{name, name2, name3} {\n\t\tdockerCmd(c, \"tag\", \"busybox\", n)\n\t}\n\tgetImages := func(filter string) []types.ImageSummary {\n\t\tfilters := filters.NewArgs()\n\t\tfilters.Add(\"reference\", filter)\n\t\toptions := types.ImageListOptions{\n\t\t\tAll:     false,\n\t\t\tFilters: filters,\n\t\t}\n\t\timages, err := cli.ImageList(context.Background(), options)\n\t\tassert.NilError(c, err)\n\n\t\treturn images\n\t}\n\n\t\/\/incorrect number of matches returned\n\timages := getImages(\"utest*\/*\")\n\tassert.Equal(c, len(images[0].RepoTags), 2)\n\n\timages = getImages(\"utest\")\n\tassert.Equal(c, len(images[0].RepoTags), 1)\n\n\timages = getImages(\"utest*\")\n\tassert.Equal(c, len(images[0].RepoTags), 1)\n\n\timages = getImages(\"*5000*\/*\")\n\tassert.Equal(c, len(images[0].RepoTags), 1)\n}\n\nfunc (s *DockerSuite) TestAPIImagesSaveAndLoad(c *testing.T) {\n\tif runtime.GOOS == \"windows\" {\n\t\tv, err := kernel.GetKernelVersion()\n\t\tassert.NilError(c, err)\n\t\tbuild, _ := strconv.Atoi(strings.Split(strings.SplitN(v.String(), \" \", 3)[2][1:], \".\")[0])\n\t\tif build == 16299 {\n\t\t\tc.Skip(\"Temporarily disabled on RS3 builds\")\n\t\t}\n\t}\n\n\ttestRequires(c, Network)\n\tbuildImageSuccessfully(c, \"saveandload\", build.WithDockerfile(\"FROM busybox\\nENV FOO bar\"))\n\tid := getIDByName(c, \"saveandload\")\n\n\tres, body, err := request.Get(\"\/images\/\" + id + \"\/get\")\n\tassert.NilError(c, err)\n\tdefer body.Close()\n\tassert.Equal(c, res.StatusCode, http.StatusOK)\n\n\tdockerCmd(c, \"rmi\", id)\n\n\tres, loadBody, err := request.Post(\"\/images\/load\", request.RawContent(body), request.ContentType(\"application\/x-tar\"))\n\tassert.NilError(c, err)\n\tdefer loadBody.Close()\n\tassert.Equal(c, res.StatusCode, http.StatusOK)\n\n\tinspectOut := cli.InspectCmd(c, id, cli.Format(\".Id\")).Combined()\n\tassert.Equal(c, strings.TrimSpace(string(inspectOut)), id, \"load did not work properly\")\n}\n\nfunc (s *DockerSuite) TestAPIImagesDelete(c *testing.T) {\n\tcli, err := client.NewClientWithOpts(client.FromEnv)\n\tassert.NilError(c, err)\n\tdefer cli.Close()\n\n\tif testEnv.OSType != \"windows\" {\n\t\ttestRequires(c, Network)\n\t}\n\tname := \"test-api-images-delete\"\n\tbuildImageSuccessfully(c, name, build.WithDockerfile(\"FROM busybox\\nENV FOO bar\"))\n\tid := getIDByName(c, name)\n\n\tdockerCmd(c, \"tag\", name, \"test:tag1\")\n\n\t_, err = cli.ImageRemove(context.Background(), id, types.ImageRemoveOptions{})\n\tassert.ErrorContains(c, err, \"unable to delete\")\n\n\t_, err = cli.ImageRemove(context.Background(), \"test:noexist\", types.ImageRemoveOptions{})\n\tassert.ErrorContains(c, err, \"No such image\")\n\n\t_, err = cli.ImageRemove(context.Background(), \"test:tag1\", types.ImageRemoveOptions{})\n\tassert.NilError(c, err)\n}\n\nfunc (s *DockerSuite) TestAPIImagesHistory(c *testing.T) {\n\tcli, err := client.NewClientWithOpts(client.FromEnv)\n\tassert.NilError(c, err)\n\tdefer cli.Close()\n\n\tif testEnv.OSType != \"windows\" {\n\t\ttestRequires(c, Network)\n\t}\n\tname := \"test-api-images-history\"\n\tbuildImageSuccessfully(c, name, build.WithDockerfile(\"FROM busybox\\nENV FOO bar\"))\n\tid := getIDByName(c, name)\n\n\thistorydata, err := cli.ImageHistory(context.Background(), id)\n\tassert.NilError(c, err)\n\n\tassert.Assert(c, len(historydata) != 0)\n\tvar found bool\n\tfor _, tag := range historydata[0].Tags {\n\t\tif tag == \"test-api-images-history:latest\" {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\tassert.Assert(c, found)\n}\n\nfunc (s *DockerSuite) TestAPIImagesImportBadSrc(c *testing.T) {\n\tif runtime.GOOS == \"windows\" {\n\t\tv, err := kernel.GetKernelVersion()\n\t\tassert.NilError(c, err)\n\t\tbuild, _ := strconv.Atoi(strings.Split(strings.SplitN(v.String(), \" \", 3)[2][1:], \".\")[0])\n\t\tif build == 16299 {\n\t\t\tc.Skip(\"Temporarily disabled on RS3 builds\")\n\t\t}\n\t}\n\n\ttestRequires(c, Network, testEnv.IsLocalDaemon)\n\n\tserver := httptest.NewServer(http.NewServeMux())\n\tdefer server.Close()\n\n\ttt := []struct {\n\t\tstatusExp int\n\t\tfromSrc   string\n\t}{\n\t\t{http.StatusNotFound, server.URL + \"\/nofile.tar\"},\n\t\t{http.StatusNotFound, strings.TrimPrefix(server.URL, \"http:\/\/\") + \"\/nofile.tar\"},\n\t\t{http.StatusNotFound, strings.TrimPrefix(server.URL, \"http:\/\/\") + \"%2Fdata%2Ffile.tar\"},\n\t\t{http.StatusInternalServerError, \"%2Fdata%2Ffile.tar\"},\n\t}\n\n\tfor _, te := range tt {\n\t\tres, _, err := request.Post(strings.Join([]string{\"\/images\/create?fromSrc=\", te.fromSrc}, \"\"), request.JSON)\n\t\tassert.NilError(c, err)\n\t\tassert.Equal(c, res.StatusCode, te.statusExp)\n\t\tassert.Equal(c, res.Header.Get(\"Content-Type\"), \"application\/json\")\n\t}\n\n}\n\n\/\/ #14846\nfunc (s *DockerSuite) TestAPIImagesSearchJSONContentType(c *testing.T) {\n\ttestRequires(c, Network)\n\n\tres, b, err := request.Get(\"\/images\/search?term=test\", request.JSON)\n\tassert.NilError(c, err)\n\tb.Close()\n\tassert.Equal(c, res.StatusCode, http.StatusOK)\n\tassert.Equal(c, res.Header.Get(\"Content-Type\"), \"application\/json\")\n}\n\n\/\/ Test case for 30027: image size reported as -1 in v1.12 client against v1.13 daemon.\n\/\/ This test checks to make sure both v1.12 and v1.13 client against v1.13 daemon get correct `Size` after the fix.\nfunc (s *DockerSuite) TestAPIImagesSizeCompatibility(c *testing.T) {\n\tapiclient := testEnv.APIClient()\n\tdefer apiclient.Close()\n\n\timages, err := apiclient.ImageList(context.Background(), types.ImageListOptions{})\n\tassert.NilError(c, err)\n\tassert.Assert(c, len(images) != 0)\n\tfor _, image := range images {\n\t\tassert.Assert(c, image.Size != int64(-1))\n\t}\n\n\tapiclient, err = client.NewClientWithOpts(client.FromEnv, client.WithVersion(\"v1.24\"))\n\tassert.NilError(c, err)\n\tdefer apiclient.Close()\n\n\tv124Images, err := apiclient.ImageList(context.Background(), types.ImageListOptions{})\n\tassert.NilError(c, err)\n\tassert.Assert(c, len(v124Images) != 0)\n\tfor _, image := range v124Images {\n\t\tassert.Assert(c, image.Size != int64(-1))\n\t}\n}\n<commit_msg>integration-cli: Skip TestAPIImagesSaveAndLoad on RS3 and older<commit_after>package main\n\nimport (\n\t\"context\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com\/docker\/docker\/api\/types\"\n\t\"github.com\/docker\/docker\/api\/types\/filters\"\n\t\"github.com\/docker\/docker\/client\"\n\t\"github.com\/docker\/docker\/integration-cli\/cli\"\n\t\"github.com\/docker\/docker\/integration-cli\/cli\/build\"\n\t\"github.com\/docker\/docker\/pkg\/parsers\/kernel\"\n\t\"github.com\/docker\/docker\/testutil\/request\"\n\t\"gotest.tools\/assert\"\n)\n\nfunc (s *DockerSuite) TestAPIImagesFilter(c *testing.T) {\n\tcli, err := client.NewClientWithOpts(client.FromEnv)\n\tassert.NilError(c, err)\n\tdefer cli.Close()\n\n\tname := \"utest:tag1\"\n\tname2 := \"utest\/docker:tag2\"\n\tname3 := \"utest:5000\/docker:tag3\"\n\tfor _, n := range []string{name, name2, name3} {\n\t\tdockerCmd(c, \"tag\", \"busybox\", n)\n\t}\n\tgetImages := func(filter string) []types.ImageSummary {\n\t\tfilters := filters.NewArgs()\n\t\tfilters.Add(\"reference\", filter)\n\t\toptions := types.ImageListOptions{\n\t\t\tAll:     false,\n\t\t\tFilters: filters,\n\t\t}\n\t\timages, err := cli.ImageList(context.Background(), options)\n\t\tassert.NilError(c, err)\n\n\t\treturn images\n\t}\n\n\t\/\/incorrect number of matches returned\n\timages := getImages(\"utest*\/*\")\n\tassert.Equal(c, len(images[0].RepoTags), 2)\n\n\timages = getImages(\"utest\")\n\tassert.Equal(c, len(images[0].RepoTags), 1)\n\n\timages = getImages(\"utest*\")\n\tassert.Equal(c, len(images[0].RepoTags), 1)\n\n\timages = getImages(\"*5000*\/*\")\n\tassert.Equal(c, len(images[0].RepoTags), 1)\n}\n\nfunc (s *DockerSuite) TestAPIImagesSaveAndLoad(c *testing.T) {\n\tif runtime.GOOS == \"windows\" {\n\t\tv, err := kernel.GetKernelVersion()\n\t\tassert.NilError(c, err)\n\t\tbuild, _ := strconv.Atoi(strings.Split(strings.SplitN(v.String(), \" \", 3)[2][1:], \".\")[0])\n\t\tif build <= 16299 {\n\t\t\tc.Skip(\"Temporarily disabled on RS3 and older because they are too slow. See #39909\")\n\t\t}\n\t}\n\n\ttestRequires(c, Network)\n\tbuildImageSuccessfully(c, \"saveandload\", build.WithDockerfile(\"FROM busybox\\nENV FOO bar\"))\n\tid := getIDByName(c, \"saveandload\")\n\n\tres, body, err := request.Get(\"\/images\/\" + id + \"\/get\")\n\tassert.NilError(c, err)\n\tdefer body.Close()\n\tassert.Equal(c, res.StatusCode, http.StatusOK)\n\n\tdockerCmd(c, \"rmi\", id)\n\n\tres, loadBody, err := request.Post(\"\/images\/load\", request.RawContent(body), request.ContentType(\"application\/x-tar\"))\n\tassert.NilError(c, err)\n\tdefer loadBody.Close()\n\tassert.Equal(c, res.StatusCode, http.StatusOK)\n\n\tinspectOut := cli.InspectCmd(c, id, cli.Format(\".Id\")).Combined()\n\tassert.Equal(c, strings.TrimSpace(string(inspectOut)), id, \"load did not work properly\")\n}\n\nfunc (s *DockerSuite) TestAPIImagesDelete(c *testing.T) {\n\tcli, err := client.NewClientWithOpts(client.FromEnv)\n\tassert.NilError(c, err)\n\tdefer cli.Close()\n\n\tif testEnv.OSType != \"windows\" {\n\t\ttestRequires(c, Network)\n\t}\n\tname := \"test-api-images-delete\"\n\tbuildImageSuccessfully(c, name, build.WithDockerfile(\"FROM busybox\\nENV FOO bar\"))\n\tid := getIDByName(c, name)\n\n\tdockerCmd(c, \"tag\", name, \"test:tag1\")\n\n\t_, err = cli.ImageRemove(context.Background(), id, types.ImageRemoveOptions{})\n\tassert.ErrorContains(c, err, \"unable to delete\")\n\n\t_, err = cli.ImageRemove(context.Background(), \"test:noexist\", types.ImageRemoveOptions{})\n\tassert.ErrorContains(c, err, \"No such image\")\n\n\t_, err = cli.ImageRemove(context.Background(), \"test:tag1\", types.ImageRemoveOptions{})\n\tassert.NilError(c, err)\n}\n\nfunc (s *DockerSuite) TestAPIImagesHistory(c *testing.T) {\n\tcli, err := client.NewClientWithOpts(client.FromEnv)\n\tassert.NilError(c, err)\n\tdefer cli.Close()\n\n\tif testEnv.OSType != \"windows\" {\n\t\ttestRequires(c, Network)\n\t}\n\tname := \"test-api-images-history\"\n\tbuildImageSuccessfully(c, name, build.WithDockerfile(\"FROM busybox\\nENV FOO bar\"))\n\tid := getIDByName(c, name)\n\n\thistorydata, err := cli.ImageHistory(context.Background(), id)\n\tassert.NilError(c, err)\n\n\tassert.Assert(c, len(historydata) != 0)\n\tvar found bool\n\tfor _, tag := range historydata[0].Tags {\n\t\tif tag == \"test-api-images-history:latest\" {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\tassert.Assert(c, found)\n}\n\nfunc (s *DockerSuite) TestAPIImagesImportBadSrc(c *testing.T) {\n\tif runtime.GOOS == \"windows\" {\n\t\tv, err := kernel.GetKernelVersion()\n\t\tassert.NilError(c, err)\n\t\tbuild, _ := strconv.Atoi(strings.Split(strings.SplitN(v.String(), \" \", 3)[2][1:], \".\")[0])\n\t\tif build == 16299 {\n\t\t\tc.Skip(\"Temporarily disabled on RS3 builds\")\n\t\t}\n\t}\n\n\ttestRequires(c, Network, testEnv.IsLocalDaemon)\n\n\tserver := httptest.NewServer(http.NewServeMux())\n\tdefer server.Close()\n\n\ttt := []struct {\n\t\tstatusExp int\n\t\tfromSrc   string\n\t}{\n\t\t{http.StatusNotFound, server.URL + \"\/nofile.tar\"},\n\t\t{http.StatusNotFound, strings.TrimPrefix(server.URL, \"http:\/\/\") + \"\/nofile.tar\"},\n\t\t{http.StatusNotFound, strings.TrimPrefix(server.URL, \"http:\/\/\") + \"%2Fdata%2Ffile.tar\"},\n\t\t{http.StatusInternalServerError, \"%2Fdata%2Ffile.tar\"},\n\t}\n\n\tfor _, te := range tt {\n\t\tres, _, err := request.Post(strings.Join([]string{\"\/images\/create?fromSrc=\", te.fromSrc}, \"\"), request.JSON)\n\t\tassert.NilError(c, err)\n\t\tassert.Equal(c, res.StatusCode, te.statusExp)\n\t\tassert.Equal(c, res.Header.Get(\"Content-Type\"), \"application\/json\")\n\t}\n\n}\n\n\/\/ #14846\nfunc (s *DockerSuite) TestAPIImagesSearchJSONContentType(c *testing.T) {\n\ttestRequires(c, Network)\n\n\tres, b, err := request.Get(\"\/images\/search?term=test\", request.JSON)\n\tassert.NilError(c, err)\n\tb.Close()\n\tassert.Equal(c, res.StatusCode, http.StatusOK)\n\tassert.Equal(c, res.Header.Get(\"Content-Type\"), \"application\/json\")\n}\n\n\/\/ Test case for 30027: image size reported as -1 in v1.12 client against v1.13 daemon.\n\/\/ This test checks to make sure both v1.12 and v1.13 client against v1.13 daemon get correct `Size` after the fix.\nfunc (s *DockerSuite) TestAPIImagesSizeCompatibility(c *testing.T) {\n\tapiclient := testEnv.APIClient()\n\tdefer apiclient.Close()\n\n\timages, err := apiclient.ImageList(context.Background(), types.ImageListOptions{})\n\tassert.NilError(c, err)\n\tassert.Assert(c, len(images) != 0)\n\tfor _, image := range images {\n\t\tassert.Assert(c, image.Size != int64(-1))\n\t}\n\n\tapiclient, err = client.NewClientWithOpts(client.FromEnv, client.WithVersion(\"v1.24\"))\n\tassert.NilError(c, err)\n\tdefer apiclient.Close()\n\n\tv124Images, err := apiclient.ImageList(context.Background(), types.ImageListOptions{})\n\tassert.NilError(c, err)\n\tassert.Assert(c, len(v124Images) != 0)\n\tfor _, image := range v124Images {\n\t\tassert.Assert(c, image.Size != int64(-1))\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package daemon\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com\/gdamore\/mangos\"\n\t\"github.com\/gdamore\/mangos\/protocol\/rep\"\n\t\"github.com\/gdamore\/mangos\/transport\/tcp\"\n\t\"github.com\/davidgev\/Flotilla\/flotilla-server\/daemon\/broker\/activemq\"\n\t\"github.com\/davidgev\/Flotilla\/flotilla-server\/daemon\/broker\/amqp\"\n\t\"github.com\/davidgev\/Flotilla\/flotilla-server\/daemon\/broker\/amqp\/rabbitmq\"\n\t\"github.com\/davidgev\/Flotilla\/flotilla-server\/daemon\/broker\/beanstalkd\"\n\t\"github.com\/davidgev\/Flotilla\/flotilla-server\/daemon\/broker\/kafka\"\n\/\/\t\"github.com\/davidgev\/Flotilla\/flotilla-server\/daemon\/broker\/kestrel\"\n\t\"github.com\/davidgev\/Flotilla\/flotilla-server\/daemon\/broker\/nats\"\n\t\"github.com\/davidgev\/Flotilla\/flotilla-server\/daemon\/broker\/nsq\"\n\t\"github.com\/davidgev\/Flotilla\/flotilla-server\/daemon\/broker\/pubsub\"\n)\n\ntype daemon string\ntype operation string\n\nconst (\n\tstart    operation = \"start\"\n\tstop     operation = \"stop\"\n\trun      operation = \"run\"\n\tsub      operation = \"subscribers\"\n\tpub      operation = \"publishers\"\n\tresults  operation = \"results\"\n\tteardown operation = \"teardown\"\n)\n\n\/\/ These are supported message brokers.\nconst (\n\tNATS        = \"nats\"\n\tBeanstalkd  = \"beanstalkd\"\n\tKafka       = \"kafka\"\n\tKestrel     = \"kestrel\"\n\tActiveMQ    = \"activemq\"\n\tRabbitMQ    = \"rabbitmq\"\n\tNSQ         = \"nsq\"\n\tCloudPubSub = \"pubsub\"\n)\n\ntype request struct {\n\tOperation   operation `json:\"operation\"`\n\tBroker      string    `json:\"broker\"`\n\tPort        string    `json:\"port\"`\n\tNumMessages int       `json:\"num_messages\"`\n\tMessageSize int64     `json:\"message_size\"`\n\tCount       int       `json:\"count\"`\n\tHost        string    `json:\"host\"`\n}\n\ntype response struct {\n\tSuccess    bool        `json:\"success\"`\n\tMessage    string      `json:\"message\"`\n\tResult     interface{} `json:\"result\"`\n\tPubResults []*result   `json:\"pub_results,omitempty\"`\n\tSubResults []*result   `json:\"sub_results,omitempty\"`\n}\n\ntype result struct {\n\tDuration   float32         `json:\"duration,omitempty\"`\n\tThroughput float32         `json:\"throughput,omitempty\"`\n\tLatency    *latencyResults `json:\"latency,omitempty\"`\n\tErr        string          `json:\"error,omitempty\"`\n}\n\n\/\/ broker handles configuring the message broker for testing.\ntype broker interface {\n\t\/\/ Start will start the message broker and prepare it for testing.\n\tStart(string, string) (interface{}, error)\n\n\t\/\/ Stop will stop the message broker.\n\tStop() (interface{}, error)\n}\n\n\/\/ peer is a single producer or consumer in the test.\ntype peer interface {\n\t\/\/ Subscribe prepares the peer to consume messages.\n\tSubscribe() error\n\n\t\/\/ Recv returns a single message consumed by the peer. Subscribe must be\n\t\/\/ called before this. It returns an error if the receive failed.\n\tRecv() ([]byte, error)\n\n\t\/\/ Send returns a channel on which messages can be sent for publishing.\n\tSend() chan<- []byte\n\n\t\/\/ Errors returns the channel on which the peer sends publish errors.\n\tErrors() <-chan error\n\n\t\/\/ Done signals to the peer that message publishing has completed.\n\tDone()\n\n\t\/\/ Setup prepares the peer for testing.\n\tSetup()\n\n\t\/\/ Teardown performs any cleanup logic that needs to be performed after the\n\t\/\/ test is complete.\n\tTeardown()\n}\n\n\/\/ Config contains configuration settings for the Flotilla daemon.\ntype Config struct {\n\tGoogleCloudProjectID string\n\tGoogleCloudJSONKey   string\n}\n\n\/\/ Daemon is the server portion of Flotilla which runs on machines we want to\n\/\/ communicate with and include in our benchmarks.\ntype Daemon struct {\n\tmangos.Socket\n\tbroker      broker\n\tpublishers  []*publisher\n\tsubscribers []*subscriber\n\tconfig      *Config\n}\n\n\/\/ NewDaemon creates and returns a new Daemon from the provided Config. An\n\/\/ error is returned if the Daemon cannot be created.\nfunc NewDaemon(config *Config) (*Daemon, error) {\n\trep, err := rep.NewSocket()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trep.AddTransport(tcp.NewTransport())\n\treturn &Daemon{rep, nil, []*publisher{}, []*subscriber{}, config}, nil\n}\n\n\/\/ Start will allow the Daemon to begin processing requests. This is a blocking\n\/\/ call.\nfunc (d *Daemon) Start(port int) error {\n\tif err := d.Listen(fmt.Sprintf(\"tcp:\/\/:%d\", port)); err != nil {\n\t\treturn err\n\t}\n\treturn d.loop()\n}\n\nfunc (d *Daemon) loop() error {\n\tfor {\n\t\tmsg, err := d.Recv()\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tvar req request\n\t\tif err := json.Unmarshal(msg, &req); err != nil {\n\t\t\tlog.Println(\"Invalid peer request:\", err)\n\t\t\td.sendResponse(response{\n\t\t\t\tSuccess: false,\n\t\t\t\tMessage: fmt.Sprintf(\"Invalid request: %s\", err.Error()),\n\t\t\t})\n\t\t\tcontinue\n\t\t}\n\n\t\tresp := d.processRequest(req)\n\t\td.sendResponse(resp)\n\t}\n}\n\nfunc (d *Daemon) sendResponse(rep response) {\n\trepJSON, err := json.Marshal(rep)\n\tif err != nil {\n\t\t\/\/ This is not recoverable.\n\t\tpanic(err)\n\t}\n\n\tif err := d.Send(repJSON); err != nil {\n\t\tlog.Println(err)\n\t}\n}\n\nfunc (d *Daemon) processRequest(req request) response {\n\tvar (\n\t\tresponse response\n\t\terr      error\n\t)\n\tswitch req.Operation {\n\tcase start:\n\t\tresponse.Result, err = d.processBrokerStart(req.Broker, req.Host, req.Port)\n\tcase stop:\n\t\tresponse.Result, err = d.processBrokerStop()\n\tcase pub:\n\t\terr = d.processPub(req)\n\tcase sub:\n\t\terr = d.processSub(req)\n\tcase run:\n\t\terr = d.processPublisherStart()\n\tcase results:\n\t\tresponse.PubResults, response.SubResults, err = d.processResults()\n\t\tif err != nil {\n\t\t\tresponse.Message = err.Error()\n\t\t\terr = nil\n\t\t}\n\tcase teardown:\n\t\td.processTeardown()\n\tdefault:\n\t\terr = fmt.Errorf(\"Invalid operation %s\", req.Operation)\n\t}\n\n\tif err != nil {\n\t\tresponse.Message = err.Error()\n\t} else {\n\t\tresponse.Success = true\n\t}\n\n\treturn response\n}\nfunc (d *Daemon) processBrokerStart(broker, host, port string) (interface{}, error) {\n\tif d.broker != nil {\n\t\treturn \"\", errors.New(\"Broker already running\")\n\t}\n\n\tswitch broker {\n\tcase NATS:\n\t\td.broker = &nats.Broker{}\n\tcase Beanstalkd:\n\t\td.broker = &beanstalkd.Broker{}\n\tcase Kafka:\n\t\td.broker = &kafka.Broker{}\n\tcase Kestrel:\n\t\td.broker = &kestrel.Broker{}\n\tcase ActiveMQ:\n\t\td.broker = &activemq.Broker{}\n\tcase RabbitMQ:\n\t\td.broker = &rabbitmq.Broker{}\n\tcase NSQ:\n\t\td.broker = &nsq.Broker{}\n\tcase CloudPubSub:\n\t\td.broker = &pubsub.Broker{\n\t\t\tProjectID: d.config.GoogleCloudProjectID,\n\t\t\tJSONKey:   d.config.GoogleCloudJSONKey,\n\t\t}\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"Invalid broker %s\", broker)\n\t}\n\n\tresult, err := d.broker.Start(host, port)\n\tif err != nil {\n\t\td.broker = nil\n\t}\n\treturn result, err\n}\n\nfunc (d *Daemon) processBrokerStop() (interface{}, error) {\n\tif d.broker == nil {\n\t\treturn \"\", errors.New(\"No broker running\")\n\t}\n\n\tresult, err := d.broker.Stop()\n\tif err == nil {\n\t\td.broker = nil\n\t}\n\treturn result, err\n}\n\nfunc (d *Daemon) processPub(req request) error {\n\tfor i := 0; i < req.Count; i++ {\n\t\tsender, err := d.newPeer(req.Broker, req.Host)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\td.publishers = append(d.publishers, &publisher{\n\t\t\tpeer:        sender,\n\t\t\tid:          i,\n\t\t\tnumMessages: req.NumMessages,\n\t\t\tmessageSize: req.MessageSize,\n\t\t})\n\t}\n\n\treturn nil\n}\n\nfunc (d *Daemon) processSub(req request) error {\n\tfor i := 0; i < req.Count; i++ {\n\t\treceiver, err := d.newPeer(req.Broker, req.Host)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := receiver.Subscribe(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tsubscriber := &subscriber{\n\t\t\tpeer:        receiver,\n\t\t\tid:          i,\n\t\t\tnumMessages: req.NumMessages,\n\t\t\tmessageSize: req.MessageSize,\n\t\t}\n\t\td.subscribers = append(d.subscribers, subscriber)\n\t\tgo subscriber.start()\n\t}\n\n\treturn nil\n}\n\nfunc (d *Daemon) processPublisherStart() error {\n\tfor _, publisher := range d.publishers {\n\t\tgo publisher.start()\n\t}\n\n\treturn nil\n}\n\nfunc (d *Daemon) processResults() ([]*result, []*result, error) {\n\tsubResults := make([]*result, 0, len(d.subscribers))\n\tfor _, subscriber := range d.subscribers {\n\t\tresult, err := subscriber.getResults()\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tsubResults = append(subResults, result)\n\t}\n\n\tpubResults := make([]*result, 0, len(d.publishers))\n\tfor _, publisher := range d.publishers {\n\t\tresult, err := publisher.getResults()\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tpubResults = append(pubResults, result)\n\t}\n\n\tlog.Println(\"Benchmark completed\")\n\treturn pubResults, subResults, nil\n}\n\nfunc (d *Daemon) processTeardown() {\n\tfor _, subscriber := range d.subscribers {\n\t\tsubscriber.Teardown()\n\t}\n\td.subscribers = d.subscribers[:0]\n\n\tfor _, publisher := range d.publishers {\n\t\tpublisher.Teardown()\n\t}\n\td.publishers = d.publishers[:0]\n}\n\nfunc (d *Daemon) newPeer(broker, host string) (peer, error) {\n\tswitch broker {\n\tcase NATS:\n\t\treturn nats.NewPeer(host)\n\tcase Beanstalkd:\n\t\treturn beanstalkd.NewPeer(host)\n\tcase Kafka:\n\t\treturn kafka.NewPeer(host)\n\tcase Kestrel:\n\t\treturn kestrel.NewPeer(host)\n\tcase ActiveMQ:\n\t\treturn activemq.NewPeer(host)\n\tcase RabbitMQ:\n\t\treturn amqp.NewPeer(host)\n\tcase NSQ:\n\t\treturn nsq.NewPeer(host)\n\tcase CloudPubSub:\n\t\treturn pubsub.NewPeer(\n\t\t\td.config.GoogleCloudProjectID,\n\t\t\td.config.GoogleCloudJSONKey,\n\t\t)\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Invalid broker: %s\", broker)\n\t}\n}\n<commit_msg>Removed kestrel, since it is not able to download some dependencies.<commit_after>package daemon\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com\/gdamore\/mangos\"\n\t\"github.com\/gdamore\/mangos\/protocol\/rep\"\n\t\"github.com\/gdamore\/mangos\/transport\/tcp\"\n\t\"github.com\/davidgev\/Flotilla\/flotilla-server\/daemon\/broker\/activemq\"\n\t\"github.com\/davidgev\/Flotilla\/flotilla-server\/daemon\/broker\/amqp\"\n\t\"github.com\/davidgev\/Flotilla\/flotilla-server\/daemon\/broker\/amqp\/rabbitmq\"\n\t\"github.com\/davidgev\/Flotilla\/flotilla-server\/daemon\/broker\/beanstalkd\"\n\t\"github.com\/davidgev\/Flotilla\/flotilla-server\/daemon\/broker\/kafka\"\n\/\/\t\"github.com\/davidgev\/Flotilla\/flotilla-server\/daemon\/broker\/kestrel\"\n\t\"github.com\/davidgev\/Flotilla\/flotilla-server\/daemon\/broker\/nats\"\n\t\"github.com\/davidgev\/Flotilla\/flotilla-server\/daemon\/broker\/nsq\"\n\t\"github.com\/davidgev\/Flotilla\/flotilla-server\/daemon\/broker\/pubsub\"\n)\n\ntype daemon string\ntype operation string\n\nconst (\n\tstart    operation = \"start\"\n\tstop     operation = \"stop\"\n\trun      operation = \"run\"\n\tsub      operation = \"subscribers\"\n\tpub      operation = \"publishers\"\n\tresults  operation = \"results\"\n\tteardown operation = \"teardown\"\n)\n\n\/\/ These are supported message brokers.\nconst (\n\tNATS        = \"nats\"\n\tBeanstalkd  = \"beanstalkd\"\n\tKafka       = \"kafka\"\n\tKestrel     = \"kestrel\"\n\tActiveMQ    = \"activemq\"\n\tRabbitMQ    = \"rabbitmq\"\n\tNSQ         = \"nsq\"\n\tCloudPubSub = \"pubsub\"\n)\n\ntype request struct {\n\tOperation   operation `json:\"operation\"`\n\tBroker      string    `json:\"broker\"`\n\tPort        string    `json:\"port\"`\n\tNumMessages int       `json:\"num_messages\"`\n\tMessageSize int64     `json:\"message_size\"`\n\tCount       int       `json:\"count\"`\n\tHost        string    `json:\"host\"`\n}\n\ntype response struct {\n\tSuccess    bool        `json:\"success\"`\n\tMessage    string      `json:\"message\"`\n\tResult     interface{} `json:\"result\"`\n\tPubResults []*result   `json:\"pub_results,omitempty\"`\n\tSubResults []*result   `json:\"sub_results,omitempty\"`\n}\n\ntype result struct {\n\tDuration   float32         `json:\"duration,omitempty\"`\n\tThroughput float32         `json:\"throughput,omitempty\"`\n\tLatency    *latencyResults `json:\"latency,omitempty\"`\n\tErr        string          `json:\"error,omitempty\"`\n}\n\n\/\/ broker handles configuring the message broker for testing.\ntype broker interface {\n\t\/\/ Start will start the message broker and prepare it for testing.\n\tStart(string, string) (interface{}, error)\n\n\t\/\/ Stop will stop the message broker.\n\tStop() (interface{}, error)\n}\n\n\/\/ peer is a single producer or consumer in the test.\ntype peer interface {\n\t\/\/ Subscribe prepares the peer to consume messages.\n\tSubscribe() error\n\n\t\/\/ Recv returns a single message consumed by the peer. Subscribe must be\n\t\/\/ called before this. It returns an error if the receive failed.\n\tRecv() ([]byte, error)\n\n\t\/\/ Send returns a channel on which messages can be sent for publishing.\n\tSend() chan<- []byte\n\n\t\/\/ Errors returns the channel on which the peer sends publish errors.\n\tErrors() <-chan error\n\n\t\/\/ Done signals to the peer that message publishing has completed.\n\tDone()\n\n\t\/\/ Setup prepares the peer for testing.\n\tSetup()\n\n\t\/\/ Teardown performs any cleanup logic that needs to be performed after the\n\t\/\/ test is complete.\n\tTeardown()\n}\n\n\/\/ Config contains configuration settings for the Flotilla daemon.\ntype Config struct {\n\tGoogleCloudProjectID string\n\tGoogleCloudJSONKey   string\n}\n\n\/\/ Daemon is the server portion of Flotilla which runs on machines we want to\n\/\/ communicate with and include in our benchmarks.\ntype Daemon struct {\n\tmangos.Socket\n\tbroker      broker\n\tpublishers  []*publisher\n\tsubscribers []*subscriber\n\tconfig      *Config\n}\n\n\/\/ NewDaemon creates and returns a new Daemon from the provided Config. An\n\/\/ error is returned if the Daemon cannot be created.\nfunc NewDaemon(config *Config) (*Daemon, error) {\n\trep, err := rep.NewSocket()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trep.AddTransport(tcp.NewTransport())\n\treturn &Daemon{rep, nil, []*publisher{}, []*subscriber{}, config}, nil\n}\n\n\/\/ Start will allow the Daemon to begin processing requests. This is a blocking\n\/\/ call.\nfunc (d *Daemon) Start(port int) error {\n\tif err := d.Listen(fmt.Sprintf(\"tcp:\/\/:%d\", port)); err != nil {\n\t\treturn err\n\t}\n\treturn d.loop()\n}\n\nfunc (d *Daemon) loop() error {\n\tfor {\n\t\tmsg, err := d.Recv()\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\n\t\tvar req request\n\t\tif err := json.Unmarshal(msg, &req); err != nil {\n\t\t\tlog.Println(\"Invalid peer request:\", err)\n\t\t\td.sendResponse(response{\n\t\t\t\tSuccess: false,\n\t\t\t\tMessage: fmt.Sprintf(\"Invalid request: %s\", err.Error()),\n\t\t\t})\n\t\t\tcontinue\n\t\t}\n\n\t\tresp := d.processRequest(req)\n\t\td.sendResponse(resp)\n\t}\n}\n\nfunc (d *Daemon) sendResponse(rep response) {\n\trepJSON, err := json.Marshal(rep)\n\tif err != nil {\n\t\t\/\/ This is not recoverable.\n\t\tpanic(err)\n\t}\n\n\tif err := d.Send(repJSON); err != nil {\n\t\tlog.Println(err)\n\t}\n}\n\nfunc (d *Daemon) processRequest(req request) response {\n\tvar (\n\t\tresponse response\n\t\terr      error\n\t)\n\tswitch req.Operation {\n\tcase start:\n\t\tresponse.Result, err = d.processBrokerStart(req.Broker, req.Host, req.Port)\n\tcase stop:\n\t\tresponse.Result, err = d.processBrokerStop()\n\tcase pub:\n\t\terr = d.processPub(req)\n\tcase sub:\n\t\terr = d.processSub(req)\n\tcase run:\n\t\terr = d.processPublisherStart()\n\tcase results:\n\t\tresponse.PubResults, response.SubResults, err = d.processResults()\n\t\tif err != nil {\n\t\t\tresponse.Message = err.Error()\n\t\t\terr = nil\n\t\t}\n\tcase teardown:\n\t\td.processTeardown()\n\tdefault:\n\t\terr = fmt.Errorf(\"Invalid operation %s\", req.Operation)\n\t}\n\n\tif err != nil {\n\t\tresponse.Message = err.Error()\n\t} else {\n\t\tresponse.Success = true\n\t}\n\n\treturn response\n}\nfunc (d *Daemon) processBrokerStart(broker, host, port string) (interface{}, error) {\n\tif d.broker != nil {\n\t\treturn \"\", errors.New(\"Broker already running\")\n\t}\n\n\tswitch broker {\n\tcase NATS:\n\t\td.broker = &nats.Broker{}\n\tcase Beanstalkd:\n\t\td.broker = &beanstalkd.Broker{}\n\tcase Kafka:\n\t\td.broker = &kafka.Broker{}\n\/\/\tcase Kestrel:\n\/\/\t\td.broker = &kestrel.Broker{}\n\tcase ActiveMQ:\n\t\td.broker = &activemq.Broker{}\n\tcase RabbitMQ:\n\t\td.broker = &rabbitmq.Broker{}\n\tcase NSQ:\n\t\td.broker = &nsq.Broker{}\n\tcase CloudPubSub:\n\t\td.broker = &pubsub.Broker{\n\t\t\tProjectID: d.config.GoogleCloudProjectID,\n\t\t\tJSONKey:   d.config.GoogleCloudJSONKey,\n\t\t}\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"Invalid broker %s\", broker)\n\t}\n\n\tresult, err := d.broker.Start(host, port)\n\tif err != nil {\n\t\td.broker = nil\n\t}\n\treturn result, err\n}\n\nfunc (d *Daemon) processBrokerStop() (interface{}, error) {\n\tif d.broker == nil {\n\t\treturn \"\", errors.New(\"No broker running\")\n\t}\n\n\tresult, err := d.broker.Stop()\n\tif err == nil {\n\t\td.broker = nil\n\t}\n\treturn result, err\n}\n\nfunc (d *Daemon) processPub(req request) error {\n\tfor i := 0; i < req.Count; i++ {\n\t\tsender, err := d.newPeer(req.Broker, req.Host)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\td.publishers = append(d.publishers, &publisher{\n\t\t\tpeer:        sender,\n\t\t\tid:          i,\n\t\t\tnumMessages: req.NumMessages,\n\t\t\tmessageSize: req.MessageSize,\n\t\t})\n\t}\n\n\treturn nil\n}\n\nfunc (d *Daemon) processSub(req request) error {\n\tfor i := 0; i < req.Count; i++ {\n\t\treceiver, err := d.newPeer(req.Broker, req.Host)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := receiver.Subscribe(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tsubscriber := &subscriber{\n\t\t\tpeer:        receiver,\n\t\t\tid:          i,\n\t\t\tnumMessages: req.NumMessages,\n\t\t\tmessageSize: req.MessageSize,\n\t\t}\n\t\td.subscribers = append(d.subscribers, subscriber)\n\t\tgo subscriber.start()\n\t}\n\n\treturn nil\n}\n\nfunc (d *Daemon) processPublisherStart() error {\n\tfor _, publisher := range d.publishers {\n\t\tgo publisher.start()\n\t}\n\n\treturn nil\n}\n\nfunc (d *Daemon) processResults() ([]*result, []*result, error) {\n\tsubResults := make([]*result, 0, len(d.subscribers))\n\tfor _, subscriber := range d.subscribers {\n\t\tresult, err := subscriber.getResults()\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tsubResults = append(subResults, result)\n\t}\n\n\tpubResults := make([]*result, 0, len(d.publishers))\n\tfor _, publisher := range d.publishers {\n\t\tresult, err := publisher.getResults()\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tpubResults = append(pubResults, result)\n\t}\n\n\tlog.Println(\"Benchmark completed\")\n\treturn pubResults, subResults, nil\n}\n\nfunc (d *Daemon) processTeardown() {\n\tfor _, subscriber := range d.subscribers {\n\t\tsubscriber.Teardown()\n\t}\n\td.subscribers = d.subscribers[:0]\n\n\tfor _, publisher := range d.publishers {\n\t\tpublisher.Teardown()\n\t}\n\td.publishers = d.publishers[:0]\n}\n\nfunc (d *Daemon) newPeer(broker, host string) (peer, error) {\n\tswitch broker {\n\tcase NATS:\n\t\treturn nats.NewPeer(host)\n\tcase Beanstalkd:\n\t\treturn beanstalkd.NewPeer(host)\n\tcase Kafka:\n\t\treturn kafka.NewPeer(host)\n\/\/\tcase Kestrel:\n\/\/\t\treturn kestrel.NewPeer(host)\n\tcase ActiveMQ:\n\t\treturn activemq.NewPeer(host)\n\tcase RabbitMQ:\n\t\treturn amqp.NewPeer(host)\n\tcase NSQ:\n\t\treturn nsq.NewPeer(host)\n\tcase CloudPubSub:\n\t\treturn pubsub.NewPeer(\n\t\t\td.config.GoogleCloudProjectID,\n\t\t\td.config.GoogleCloudJSONKey,\n\t\t)\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Invalid broker: %s\", broker)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package rpc\n\nimport (\n\t\"cgl.tideland.biz\/asserts\"\n\t\"net\/rpc\"\n\t\"testing\"\n)\n\ntype testUi struct {\n\tsayCalled bool\n\tsayFormat string\n\tsayVars []interface{}\n}\n\nfunc (u *testUi) Say(format string, a ...interface{}) {\n\tu.sayCalled = true\n\tu.sayFormat = format\n\tu.sayVars = a\n}\n\nfunc TestUiRPC(t *testing.T) {\n\tassert := asserts.NewTestingAsserts(t, true)\n\n\t\/\/ Create the UI to test\n\tui := new(testUi)\n\tuiServer := &UiServer{ui}\n\n\t\/\/ Start the RPC server\n\treadyChan := make(chan int)\n\tstopChan := make(chan int)\n\tdefer func() { stopChan <- 1 }()\n\tgo testRPCServer(\":1234\", \"Ui\", uiServer, readyChan, stopChan)\n\t<-readyChan\n\n\t\/\/ Create the client over RPC and run some methods to verify it works\n\tclient, err := rpc.Dial(\"tcp\", \":1234\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tuiClient := &Ui{client}\n\tuiClient.Say(\"format\", \"arg0\", 42)\n\n\tassert.Equal(ui.sayFormat, \"format\", \"format should be correct\")\n}\n<commit_msg>packer\/rpc: Use the proper Server for tests<commit_after>package rpc\n\nimport (\n\t\"cgl.tideland.biz\/asserts\"\n\t\"net\/rpc\"\n\t\"testing\"\n)\n\ntype testUi struct {\n\tsayCalled bool\n\tsayFormat string\n\tsayVars []interface{}\n}\n\nfunc (u *testUi) Say(format string, a ...interface{}) {\n\tu.sayCalled = true\n\tu.sayFormat = format\n\tu.sayVars = a\n}\n\nfunc TestUiRPC(t *testing.T) {\n\tassert := asserts.NewTestingAsserts(t, true)\n\n\t\/\/ Create the UI to test\n\tui := new(testUi)\n\n\t\/\/ Start the RPC server\n\tserver := NewServer()\n\tserver.RegisterUi(ui)\n\tserver.Start()\n\tdefer server.Stop()\n\n\t\/\/ Create the client over RPC and run some methods to verify it works\n\tclient, err := rpc.Dial(\"tcp\", server.Address())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tuiClient := &Ui{client}\n\tuiClient.Say(\"format\", \"arg0\", 42)\n\n\tassert.Equal(ui.sayFormat, \"format\", \"format should be correct\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package openjpeg\n\n\/\/ #cgo LDFLAGS: -lopenjp2\n\/\/ #include \"handlers.h\"\nimport \"C\"\n\nimport (\n\t\"errors\"\n\t\"image\"\n\t\"image\/color\"\n\t\"reflect\"\n\t\"runtime\"\n\t\"unsafe\"\n\t\"fmt\"\n)\n\n\/\/ Debug by default\nvar LogLevel = 7\nvar LogLevels = []string{\"EMERG\", \"ALERT\", \"CRIT\", \"ERROR\", \"WARN\", \"NOTICE\", \"INFO\", \"DEBUG\"}\n\n\/\/export GoLog\nfunc GoLog(clevel C.int, cmessage *C.char) {\n\tlevel := int(clevel)\n\tmessage := C.GoString(cmessage)\n\n\tgoLog(level, message)\n}\n\n\/\/ Internal go-specific version of logger\nfunc goLog(level int, message string) {\n\tif level <= LogLevel {\n\t\tfmt.Printf(\"[%s] %s\", LogLevels[level], message)\n\t}\n}\n\nconst MAX_PROGRESSION_LEVEL = uint(6)\n\nfunc scaled_dimension(progression_level uint, dimension int) int {\n\tscale_factor := uint(2) << (progression_level - uint(1))\n\treturn int(float32(dimension) \/ float32(scale_factor))\n}\n\nfunc desired_progression_level(r image.Rectangle, width, height int) uint {\n\tlevel := MAX_PROGRESSION_LEVEL\n\tfor ; level > 0 && width > scaled_dimension(level, r.Dx()) && height > scaled_dimension(level, r.Dy()); level-- {\n\t}\n\treturn level\n}\n\nfunc NewImageTile(filename string, r image.Rectangle, width, height int) (err error, tile *ImageTile) {\n\tl_stream := C.opj_stream_create_default_file_stream_v3(C.CString(filename), 1)\n\tif l_stream == nil {\n\t\treturn errors.New(\"failed to create stream\"), nil\n\t}\n\n\tl_codec := C.opj_create_decompress(C.OPJ_CODEC_JP2)\n\n\tvar parameters C.opj_dparameters_t\n\tC.opj_set_default_decoder_parameters(&parameters)\n\tlevel := desired_progression_level(r, width, height)\n\tgoLog(6, fmt.Sprintf(\"desired level: %d\", level))\n\t\/\/(parameters).cp_reduce = C.OPJ_UINT32(level)\n\n\tC.set_handlers(l_codec)\n\n\tif err == nil && C.opj_setup_decoder(l_codec, &parameters) == C.OPJ_FALSE {\n\t\terr = errors.New(\"failed to setup decoder\")\n\t}\n\n\tif err == nil && C.opj_set_decoded_resolution_factor(l_codec, C.OPJ_UINT32(level)) == C.OPJ_FALSE {\n\t\terr = errors.New(\"failed to set decode resolution factor\")\n\t}\n\n\tvar img *C.opj_image_t\n\tif err == nil && C.opj_read_header(l_stream, l_codec, &img) == C.OPJ_FALSE {\n\t\terr = errors.New(\"failed to read the header\")\n\t}\n\n\tif err == nil {\n\t\tgoLog(6, fmt.Sprintf(\"num comps: %d\", img.numcomps))\n\t\tgoLog(6, fmt.Sprintf(\"x0: %d, x1: %d, y0: %d, y1: %d\", img.x0, img.x1, img.y0, img.y1))\n\t}\n\n\tif err == nil && C.opj_set_decode_area(l_codec, img, C.OPJ_INT32(r.Min.X), C.OPJ_INT32(r.Min.Y), C.OPJ_INT32(r.Max.X), C.OPJ_INT32(r.Max.Y)) == C.OPJ_FALSE {\n\t\terr = errors.New(\"failed to set the decoded area\")\n\t}\n\n\tif err == nil && C.opj_decode(l_codec, l_stream, img) == C.OPJ_FALSE {\n\t\terr = errors.New(\"failed to decode image\")\n\t}\n\tif err == nil && C.opj_end_decompress(l_codec, l_stream) == C.OPJ_FALSE {\n\t\terr = errors.New(\"failed to decode image\")\n\t}\n\n\tC.opj_stream_destroy_v3(l_stream)\n\tif l_codec != nil {\n\t\tC.opj_destroy_codec(l_codec)\n\t}\n\n\tif err == nil {\n\t\tvar comps []C.opj_image_comp_t\n\t\tcompsSlice := (*reflect.SliceHeader)((unsafe.Pointer(&comps)))\n\t\tcompsSlice.Cap = int(img.numcomps)\n\t\tcompsSlice.Len = int(img.numcomps)\n\t\tcompsSlice.Data = uintptr(unsafe.Pointer(img.comps))\n\n\t\tbounds := image.Rect(0, 0, int(comps[0].w), int(comps[0].h))\n\n\t\tvar data []int32\n\t\tdataSlice := (*reflect.SliceHeader)((unsafe.Pointer(&data)))\n\t\tdataSlice.Cap = bounds.Dx() * bounds.Dy()\n\t\tdataSlice.Len = bounds.Dx() * bounds.Dy()\n\t\tdataSlice.Data = uintptr(unsafe.Pointer(comps[0].data))\n\n\t\ttile = &ImageTile{data, bounds, bounds.Dx(), img}\n\t\truntime.SetFinalizer(tile, func(it *ImageTile) {\n\t\t\tC.opj_image_destroy(it.img)\n\t\t})\n\t} else {\n\t\tC.opj_image_destroy(img)\n\t}\n\treturn\n}\n\ntype ImageTile struct {\n\tdata   []int32\n\tbounds image.Rectangle\n\tstride int\n\timg    *C.opj_image_t\n}\n\nfunc (p *ImageTile) ColorModel() color.Model {\n\treturn color.GrayModel\n}\n\nfunc (p *ImageTile) Bounds() image.Rectangle {\n\treturn p.bounds\n}\n\nfunc (p *ImageTile) At(x, y int) color.Color {\n\tif !(image.Point{x, y}.In(p.bounds)) {\n\t\treturn color.Gray{}\n\t}\n\tindex := p.PixOffset(x, y)\n\treturn color.Gray{uint8(p.data[index])}\n}\n\nfunc (p *ImageTile) PixOffset(x, y int) int {\n\treturn (y-p.bounds.Min.Y)*p.stride + (x-p.bounds.Min.X)*1\n}\n<commit_msg>Add better logging of stream errors<commit_after>package openjpeg\n\n\/\/ #cgo LDFLAGS: -lopenjp2\n\/\/ #include \"handlers.h\"\nimport \"C\"\n\nimport (\n\t\"errors\"\n\t\"image\"\n\t\"image\/color\"\n\t\"reflect\"\n\t\"runtime\"\n\t\"unsafe\"\n\t\"fmt\"\n)\n\n\/\/ Debug by default\nvar LogLevel = 7\nvar LogLevels = []string{\"EMERG\", \"ALERT\", \"CRIT\", \"ERROR\", \"WARN\", \"NOTICE\", \"INFO\", \"DEBUG\"}\n\n\/\/export GoLog\nfunc GoLog(clevel C.int, cmessage *C.char) {\n\tlevel := int(clevel)\n\tmessage := C.GoString(cmessage)\n\n\tgoLog(level, message)\n}\n\n\/\/ Internal go-specific version of logger\nfunc goLog(level int, message string) {\n\tif level <= LogLevel {\n\t\tfmt.Printf(\"[%s] %s\", LogLevels[level], message)\n\t}\n}\n\nconst MAX_PROGRESSION_LEVEL = uint(6)\n\nfunc scaled_dimension(progression_level uint, dimension int) int {\n\tscale_factor := uint(2) << (progression_level - uint(1))\n\treturn int(float32(dimension) \/ float32(scale_factor))\n}\n\nfunc desired_progression_level(r image.Rectangle, width, height int) uint {\n\tlevel := MAX_PROGRESSION_LEVEL\n\tfor ; level > 0 && width > scaled_dimension(level, r.Dx()) && height > scaled_dimension(level, r.Dy()); level-- {\n\t}\n\treturn level\n}\n\nfunc NewImageTile(filename string, r image.Rectangle, width, height int) (err error, tile *ImageTile) {\n\tl_stream := C.opj_stream_create_default_file_stream_v3(C.CString(filename), 1)\n\tif l_stream == nil {\n\t\treturn errors.New(fmt.Sprintf(\"Failed to create stream in %#v\", filename)), nil\n\t}\n\n\tl_codec := C.opj_create_decompress(C.OPJ_CODEC_JP2)\n\n\tvar parameters C.opj_dparameters_t\n\tC.opj_set_default_decoder_parameters(&parameters)\n\tlevel := desired_progression_level(r, width, height)\n\tgoLog(6, fmt.Sprintf(\"desired level: %d\", level))\n\t\/\/(parameters).cp_reduce = C.OPJ_UINT32(level)\n\n\tC.set_handlers(l_codec)\n\n\tif err == nil && C.opj_setup_decoder(l_codec, &parameters) == C.OPJ_FALSE {\n\t\terr = errors.New(\"failed to setup decoder\")\n\t}\n\n\tif err == nil && C.opj_set_decoded_resolution_factor(l_codec, C.OPJ_UINT32(level)) == C.OPJ_FALSE {\n\t\terr = errors.New(\"failed to set decode resolution factor\")\n\t}\n\n\tvar img *C.opj_image_t\n\tif err == nil && C.opj_read_header(l_stream, l_codec, &img) == C.OPJ_FALSE {\n\t\terr = errors.New(\"failed to read the header\")\n\t}\n\n\tif err == nil {\n\t\tgoLog(6, fmt.Sprintf(\"num comps: %d\", img.numcomps))\n\t\tgoLog(6, fmt.Sprintf(\"x0: %d, x1: %d, y0: %d, y1: %d\", img.x0, img.x1, img.y0, img.y1))\n\t}\n\n\tif err == nil && C.opj_set_decode_area(l_codec, img, C.OPJ_INT32(r.Min.X), C.OPJ_INT32(r.Min.Y), C.OPJ_INT32(r.Max.X), C.OPJ_INT32(r.Max.Y)) == C.OPJ_FALSE {\n\t\terr = errors.New(\"failed to set the decoded area\")\n\t}\n\n\tif err == nil && C.opj_decode(l_codec, l_stream, img) == C.OPJ_FALSE {\n\t\terr = errors.New(\"failed to decode image\")\n\t}\n\tif err == nil && C.opj_end_decompress(l_codec, l_stream) == C.OPJ_FALSE {\n\t\terr = errors.New(\"failed to decode image\")\n\t}\n\n\tC.opj_stream_destroy_v3(l_stream)\n\tif l_codec != nil {\n\t\tC.opj_destroy_codec(l_codec)\n\t}\n\n\tif err == nil {\n\t\tvar comps []C.opj_image_comp_t\n\t\tcompsSlice := (*reflect.SliceHeader)((unsafe.Pointer(&comps)))\n\t\tcompsSlice.Cap = int(img.numcomps)\n\t\tcompsSlice.Len = int(img.numcomps)\n\t\tcompsSlice.Data = uintptr(unsafe.Pointer(img.comps))\n\n\t\tbounds := image.Rect(0, 0, int(comps[0].w), int(comps[0].h))\n\n\t\tvar data []int32\n\t\tdataSlice := (*reflect.SliceHeader)((unsafe.Pointer(&data)))\n\t\tdataSlice.Cap = bounds.Dx() * bounds.Dy()\n\t\tdataSlice.Len = bounds.Dx() * bounds.Dy()\n\t\tdataSlice.Data = uintptr(unsafe.Pointer(comps[0].data))\n\n\t\ttile = &ImageTile{data, bounds, bounds.Dx(), img}\n\t\truntime.SetFinalizer(tile, func(it *ImageTile) {\n\t\t\tC.opj_image_destroy(it.img)\n\t\t})\n\t} else {\n\t\tC.opj_image_destroy(img)\n\t}\n\treturn\n}\n\ntype ImageTile struct {\n\tdata   []int32\n\tbounds image.Rectangle\n\tstride int\n\timg    *C.opj_image_t\n}\n\nfunc (p *ImageTile) ColorModel() color.Model {\n\treturn color.GrayModel\n}\n\nfunc (p *ImageTile) Bounds() image.Rectangle {\n\treturn p.bounds\n}\n\nfunc (p *ImageTile) At(x, y int) color.Color {\n\tif !(image.Point{x, y}.In(p.bounds)) {\n\t\treturn color.Gray{}\n\t}\n\tindex := p.PixOffset(x, y)\n\treturn color.Gray{uint8(p.data[index])}\n}\n\nfunc (p *ImageTile) PixOffset(x, y int) int {\n\treturn (y-p.bounds.Min.Y)*p.stride + (x-p.bounds.Min.X)*1\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage addresser\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/juju\/loggo\"\n\t\"launchpad.net\/tomb\"\n\n\t\"github.com\/juju\/juju\/state\"\n\t\"github.com\/juju\/juju\/state\/watcher\"\n\t\"github.com\/juju\/juju\/worker\"\n)\n\nvar logger = loggo.GetLogger(\"juju.worker.addresser\")\n\ntype addresserWorker struct {\n\tst   *state.State\n\ttomb tomb.Tomb\n\n\tobserver *worker.EnvironObserver\n}\n\n\/\/ NewWorker returns a worker that keeps track of\n\/\/ IP address lifecycles, removing Dead addresses.\nfunc NewWorker(st *state.State) worker.Worker {\n\ta := &addresserWorker{\n\t\tst: st,\n\t}\n\t\/\/ wait for environment\n\tgo func() {\n\t\tdefer a.tomb.Done()\n\t\ta.tomb.Kill(a.loop())\n\t}()\n\treturn a\n}\n\nfunc (a *addresserWorker) Kill() {\n\ta.tomb.Kill(nil)\n}\n\nfunc (a *addresserWorker) Wait() error {\n\treturn a.tomb.Wait()\n}\n\nfunc (a *addresserWorker) loop() (err error) {\n\ta.observer, err = worker.NewEnvironObserver(a.st)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlogger.Infof(\"addresser received inital environment configuration\")\n\tdefer func() {\n\t\tobsErr := worker.Stop(a.observer)\n\t\tif err == nil {\n\t\t\terr = obsErr\n\t\t}\n\t}()\n\treturn watchAddressesLoop(a, a.st.WatchIPAddresses())\n}\n\nfunc (a *addresserWorker) dying() <-chan struct{} {\n\treturn a.tomb.Dying()\n}\n\nfunc (a *addresserWorker) killAll(err error) {\n\ta.tomb.Kill(err)\n}\n\nfunc (a *addresserWorker) checkAddresses(ids []string) error {\n\n\treturn nil\n}\n\nfunc watchAddressesLoop(addresser *addresserWorker, w state.StringsWatcher) (err error) {\n\tdefer func() {\n\t\tif stopErr := w.Stop(); stopErr != nil {\n\t\t\tif err == nil {\n\t\t\t\terr = fmt.Errorf(\"error stopping watcher: %v\", stopErr)\n\t\t\t} else {\n\t\t\t\tlogger.Warningf(\"ignoring error when stopping watcher: %v\", stopErr)\n\t\t\t}\n\t\t}\n\t}()\n\tfor {\n\t\tselect {\n\t\tcase ids, ok := <-w.Changes():\n\t\t\tif !ok {\n\t\t\t\treturn watcher.EnsureErr(w)\n\t\t\t}\n\t\t\tif err := addresser.checkAddresses(ids); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase <-addresser.dying():\n\t\t\treturn nil\n\t\t}\n\t}\n}\n<commit_msg>Body of addresser worker<commit_after>\/\/ Copyright 2015 Canonical Ltd.\n\/\/ Licensed under the AGPLv3, see LICENCE file for details.\n\npackage addresser\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/juju\/errors\"\n\t\"github.com\/juju\/loggo\"\n\t\"launchpad.net\/tomb\"\n\n\t\"github.com\/juju\/juju\/state\"\n\t\"github.com\/juju\/juju\/state\/watcher\"\n\t\"github.com\/juju\/juju\/worker\"\n)\n\nvar logger = loggo.GetLogger(\"juju.worker.addresser\")\n\ntype addresserWorker struct {\n\tst   *state.State\n\ttomb tomb.Tomb\n\n\tobserver *worker.EnvironObserver\n}\n\n\/\/ NewWorker returns a worker that keeps track of\n\/\/ IP address lifecycles, removing Dead addresses.\nfunc NewWorker(st *state.State) worker.Worker {\n\ta := &addresserWorker{\n\t\tst: st,\n\t}\n\t\/\/ wait for environment\n\tgo func() {\n\t\tdefer a.tomb.Done()\n\t\ta.tomb.Kill(a.loop())\n\t}()\n\treturn a\n}\n\nfunc (a *addresserWorker) Kill() {\n\ta.tomb.Kill(nil)\n}\n\nfunc (a *addresserWorker) Wait() error {\n\treturn a.tomb.Wait()\n}\n\nfunc (a *addresserWorker) loop() (err error) {\n\ta.observer, err = worker.NewEnvironObserver(a.st)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlogger.Infof(\"addresser received inital environment configuration\")\n\tdefer func() {\n\t\tobsErr := worker.Stop(a.observer)\n\t\tif err == nil {\n\t\t\terr = obsErr\n\t\t}\n\t}()\n\treturn watchAddressesLoop(a, a.st.WatchIPAddresses())\n}\n\nfunc (a *addresserWorker) dying() <-chan struct{} {\n\treturn a.tomb.Dying()\n}\n\nfunc (a *addresserWorker) killAll(err error) {\n\ta.tomb.Kill(err)\n}\n\nfunc (a *addresserWorker) checkAddresses(ids []string) error {\n\tfor _, id := range ids {\n\t\taddr, err := a.st.IPAddress(id)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif addr.Life() != state.Dead {\n\t\t\tcontinue\n\t\t}\n\t\terr = addr.Remove()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc watchAddressesLoop(addresser *addresserWorker, w state.StringsWatcher) (err error) {\n\tdefer func() {\n\t\tif stopErr := w.Stop(); stopErr != nil {\n\t\t\tif err == nil {\n\t\t\t\terr = fmt.Errorf(\"error stopping watcher: %v\", stopErr)\n\t\t\t} else {\n\t\t\t\tlogger.Warningf(\"ignoring error when stopping watcher: %v\", stopErr)\n\t\t\t}\n\t\t}\n\t}()\n\n\tdead, err := addresser.st.DeadIPAddresses()\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\tdeadQueue := make(chan *state.IPAddress, len(dead))\n\tfor _, deadAddr := range dead {\n\t\tdeadQueue <- deadAddr\n\t}\n\tgo func() {\n\t\tselect {\n\t\tcase addr := <-deadQueue:\n\t\t\terr := addr.Remove()\n\t\t\tif err != nil {\n\t\t\t\tlogger.Warningf(\"error releasing dead IP address %q: %v\", addr, err)\n\t\t\t}\n\t\tcase <-addresser.dying():\n\t\t\treturn\n\t\tdefault:\n\t\t\treturn\n\t\t}\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase ids, ok := <-w.Changes():\n\t\t\tif !ok {\n\t\t\t\treturn watcher.EnsureErr(w)\n\t\t\t}\n\t\t\tif err := addresser.checkAddresses(ids); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase <-addresser.dying():\n\t\t\treturn nil\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Rename keepalive to ticker<commit_after><|endoftext|>"}
{"text":"<commit_before>package automaton\n\n\/\/ util\/automaton\/Automaton.java\n\n\/*\nFinite-state automaton with regular expression operations.\n\nClass invariants:\n\n1. An automaton is either represented explicitly (with State and\nTransition object) or with a singleton string (see Singleton() and\nexpandSingleton()) in case the automaton is known to accept exactly\none string. (Implicitly, all states and transitions of an automaton\nare reachable from its initial state.)\n2. Automata are always reduced (see Reduce()) and have no transitions\nto dead states (see RemoveDeadTransitions()).\n3. If an automaton is nondeterministic, then IsDeterministic()\nreturns false (but the converse is not required).\n4. Automata provided as input to operations are generally assumed to\nbe disjoint.\n\nIf the states or transitions are manipulated manually, the\nRestoreInvariant() and SetDeterministic(bool) methods should be used\nafterwards to restore representation invariants that are assumed by\nthe built-in automata operations.\n\nNote: This class has internal mutable state and is not thread safe.\nIt is the caller's responsibility to ensure any necessary\nsynchronization if you wish to use the same Automaton from multiple\nthreads. In general it is instead recommended to use a RunAutomaton\nfor multithreaded matching: it is immutable, thread safe, and much\nfaster.\n*\/\ntype Automaton struct {\n\t\/\/ Initial state of this automation.\n\tinitial *State\n\t\/\/ If true, then this automaton is definitely deterministic (i.e.,\n\t\/\/ there are no choices for any run, but a run may crash).\n\tdeterministic bool\n}\n\n\/\/ Constructs a new automaton that accepts the empty language. Using\n\/\/ this constructor, automata can be constructed manually from State\n\/\/ and Transition objects.\nfunc newAutomatonWithState(initial *State) *Automaton {\n\treturn &Automaton{initial: initial, deterministic: true}\n}\n\nfunc newEmptyAutomaton() *Automaton {\n\treturn newAutomatonWithState(newState())\n}\n\n\/\/ util\/automaton\/State.java\n\nvar next_id int\n\n\/\/ Automaton state\ntype State struct {\n\tid int\n}\n\n\/\/ Constructs a new state. Initially, the new state is a reject state.\nfunc newState() *State {\n\ts := &State{}\n\ts.resetTransitions()\n\ts.id = next_id\n\tnext_id++\n\treturn s\n}\n\n\/\/ Resets transition set.\nfunc (s *State) resetTransitions() {\n\tpanic(\"not implemented yet\")\n}\n\n\/\/ util\/automaton\/BasicAutomata.java\n\n\/\/ Returns a new (deterministic) automaton with the empty language.\nfunc MakeEmpty() *Automaton {\n\ta := newEmptyAutomaton()\n\ta.initial = newState()\n\ta.deterministic = true\n\treturn a\n}\n<commit_msg>add transition object<commit_after>package automaton\n\n\/\/ util\/automaton\/Automaton.java\n\n\/*\nFinite-state automaton with regular expression operations.\n\nClass invariants:\n\n1. An automaton is either represented explicitly (with State and\nTransition object) or with a singleton string (see Singleton() and\nexpandSingleton()) in case the automaton is known to accept exactly\none string. (Implicitly, all states and transitions of an automaton\nare reachable from its initial state.)\n2. Automata are always reduced (see Reduce()) and have no transitions\nto dead states (see RemoveDeadTransitions()).\n3. If an automaton is nondeterministic, then IsDeterministic()\nreturns false (but the converse is not required).\n4. Automata provided as input to operations are generally assumed to\nbe disjoint.\n\nIf the states or transitions are manipulated manually, the\nRestoreInvariant() and SetDeterministic(bool) methods should be used\nafterwards to restore representation invariants that are assumed by\nthe built-in automata operations.\n\nNote: This class has internal mutable state and is not thread safe.\nIt is the caller's responsibility to ensure any necessary\nsynchronization if you wish to use the same Automaton from multiple\nthreads. In general it is instead recommended to use a RunAutomaton\nfor multithreaded matching: it is immutable, thread safe, and much\nfaster.\n*\/\ntype Automaton struct {\n\t\/\/ Initial state of this automation.\n\tinitial *State\n\t\/\/ If true, then this automaton is definitely deterministic (i.e.,\n\t\/\/ there are no choices for any run, but a run may crash).\n\tdeterministic bool\n}\n\n\/\/ Constructs a new automaton that accepts the empty language. Using\n\/\/ this constructor, automata can be constructed manually from State\n\/\/ and Transition objects.\nfunc newAutomatonWithState(initial *State) *Automaton {\n\treturn &Automaton{initial: initial, deterministic: true}\n}\n\nfunc newEmptyAutomaton() *Automaton {\n\treturn newAutomatonWithState(newState())\n}\n\n\/\/ util\/automaton\/State.java\n\nvar next_id int\n\n\/\/ Automaton state\ntype State struct {\n\taccept           bool\n\ttransitionsArray []*Transition\n\tnumTransitions   int\n\n\tnumber int\n\n\tid int\n}\n\n\/\/ Constructs a new state. Initially, the new state is a reject state.\nfunc newState() *State {\n\ts := &State{}\n\ts.resetTransitions()\n\ts.id = next_id\n\tnext_id++\n\treturn s\n}\n\n\/\/ Resets transition set.\nfunc (s *State) resetTransitions() {\n\ts.transitionsArray = make([]*Transition, 0)\n\ts.numTransitions = 0\n}\n\n\/\/ util\/automaton\/Transition.java\n\n\/*\nAutomaton transition.\n\nA transition, which belongs to a source state, consists of a Unicode\ncodepoint interval and a destination state.\n*\/\ntype Transition struct {\n}\n\n\/\/ util\/automaton\/BasicAutomata.java\n\n\/\/ Returns a new (deterministic) automaton with the empty language.\nfunc MakeEmpty() *Automaton {\n\ta := newEmptyAutomaton()\n\ta.initial = newState()\n\ta.deterministic = true\n\treturn a\n}\n<|endoftext|>"}
{"text":"<commit_before>package vmwarevsphere\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/rancher\/machine\/libmachine\/log\"\n\t\"github.com\/vmware\/govmomi\/find\"\n\t\"github.com\/vmware\/govmomi\/guest\"\n\t\"github.com\/vmware\/govmomi\/object\"\n\t\"github.com\/vmware\/govmomi\/vapi\/tags\"\n\t\"github.com\/vmware\/govmomi\/vim25\/mo\"\n\t\"github.com\/vmware\/govmomi\/vim25\/types\"\n)\n\nfunc (d *Driver) getVmFolder(vm *object.VirtualMachine) (string, error) {\n\tvar mvm mo.VirtualMachine\n\tc, err := d.getSoapClient()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\terr = c.RetrieveOne(d.getCtx(), vm.Reference(), nil, &mvm)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tp := mvm.Summary.Config.VmPathName\n\tsp := strings.Split(p, \"]\")\n\tpath := strings.Replace(sp[1], fmt.Sprintf(\"\/%s.vmx\", d.MachineName), \"\", 1)\n\n\treturn path, nil\n}\n\nfunc (d *Driver) getVmDatastore(vm *object.VirtualMachine) (*object.Datastore, error) {\n\tvar mvm mo.VirtualMachine\n\tc, err := d.getSoapClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = c.RetrieveOne(d.getCtx(), vm.Reference(), nil, &mvm)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(mvm.Datastore) == 0 {\n\t\treturn nil, fmt.Errorf(\"No datastores for this VM\")\n\t}\n\n\tvar ds mo.Datastore\n\terr = c.RetrieveOne(d.getCtx(), mvm.Datastore[0], nil, &ds)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn d.finder.Datastore(d.getCtx(), ds.Name) \/\/convert mo to object\n}\n\nfunc (d *Driver) fetchVM(vmname string) (*object.VirtualMachine, error) {\n\tif d.vms[vmname] != nil {\n\t\treturn d.vms[vmname], nil\n\t}\n\n\tc, err := d.getSoapClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Create a new finder\n\tf := find.NewFinder(c.Client, true)\n\tvar vm *object.VirtualMachine\n\n\tdc, err := f.DatacenterOrDefault(d.getCtx(), d.Datacenter)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tf.SetDatacenter(dc)\n\tvm, err = f.VirtualMachine(d.getCtx(), vmname)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\td.vms[vmname] = vm\n\treturn vm, nil\n}\n\nfunc (d *Driver) addNetworks(vm *object.VirtualMachine, networks map[string]object.NetworkReference) error {\n\tif len(networks) <= 0 {\n\t\treturn nil\n\t}\n\n\tdevices, _ := vm.Device(d.getCtx())\n\tfor _, v := range devices {\n\t\tdev := v.GetVirtualDevice()\n\t\tif strings.Contains(dev.DeviceInfo.GetDescription().Label, \"Network adapter\") {\n\t\t\t\/\/remove old networks\n\t\t\tif err := vm.RemoveDevice(d.getCtx(), false, dev); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t}\n\t}\n\n\tvar add []types.BaseVirtualDevice\n\tfor _, netName := range d.Networks {\n\t\tbacking, err := networks[netName].EthernetCardBackingInfo(d.getCtx())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tnetdev, err := object.EthernetCardTypes().CreateEthernetCard(\"vmxnet3\", backing)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tlog.Infof(\"Adding network: %s\", netName)\n\t\tadd = append(add, netdev)\n\t}\n\n\tif err := vm.AddDevice(d.getCtx(), add...); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (d *Driver) provisionVm(vm *object.VirtualMachine) error {\n\tlog.Infof(\"Provisioning certs and ssh keys...\")\n\n\tc, err := d.getSoapClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Generate a tar keys bundle\n\tif err := d.generateKeyBundle(); err != nil {\n\t\treturn err\n\t}\n\n\topman := guest.NewOperationsManager(c.Client, vm.Reference())\n\n\tfileman, err := opman.FileManager(d.getCtx())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsrc := d.ResolveStorePath(\"userdata.tar\")\n\ts, err := os.Stat(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tauth := NewAuthFlag(d.SSHUser, d.SSHPassword)\n\tflag := FileAttrFlag{}\n\tflag.SetPerms(0, 0, 660)\n\n\ttmpDir, err := fileman.CreateTemporaryDirectory(d.getCtx(), auth.Auth(), \"docker_\", \"\", \"\/tmp\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\turl, err := fileman.InitiateFileTransferToGuest(d.getCtx(), auth.Auth(), tmpDir+\"\/userdata.tar\", flag.Attr(), s.Size(), true)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tu, err := c.Client.ParseURL(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = c.Client.UploadFile(d.getCtx(), src, u, nil); err != nil {\n\t\treturn err\n\t}\n\n\tprocman, err := opman.ProcessManager(d.getCtx())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmds := []string{\n\t\tfmt.Sprintf(\"\/bin\/tar xvf %s\/userdata.tar -C %s\", tmpDir, tmpDir),\n\t\tfmt.Sprintf(\"\/bin\/chown -R %s:%s %s\", d.SSHUser, d.SSHUserGroup, tmpDir),\n\t\t\"\/bin\/mkdir -p \/var\/lib\/boot2docker\",\n\t\tfmt.Sprintf(\"\/bin\/cp %s\/userdata.tar \/var\/lib\/boot2docker\/userdata.tar\", tmpDir),\n\t\tfmt.Sprintf(\"\/bin\/mkdir -p \/home\/%s\/.ssh\", d.SSHUser),\n\t\tfmt.Sprintf(\"\/bin\/cp %s\/.ssh\/* \/home\/%s\/.ssh\", tmpDir, d.SSHUser), \/\/copy keys to user homedir\n\t}\n\n\tfor _, cmd := range cmds {\n\t\tif _, err := d.remoteExec(procman, cmd); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (d *Driver) addConfigParams(vm *object.VirtualMachine) error {\n\tvar opts []types.BaseOptionValue\n\tif len(d.CfgParams) > 0 {\n\t\tfor _, param := range d.CfgParams {\n\t\t\tv := strings.SplitN(param, \"=\", 2)\n\t\t\tkey := v[0]\n\t\t\tvalue := \"\"\n\t\t\tif len(v) > 1 {\n\t\t\t\tvalue = v[1]\n\t\t\t}\n\t\t\tfmt.Printf(\"Setting %s to %s\\n\", key, value)\n\t\t\topts = append(opts, &types.OptionValue{\n\t\t\t\tKey:   key,\n\t\t\t\tValue: value,\n\t\t\t})\n\t\t}\n\t}\n\n\treturn d.applyOpts(vm, opts)\n}\n\nfunc (d *Driver) applyOpts(vm *object.VirtualMachine, opts []types.BaseOptionValue) error {\n\tif len(opts) == 0 {\n\t\treturn nil\n\t}\n\n\ttask, err := vm.Reconfigure(d.getCtx(), types.VirtualMachineConfigSpec{\n\t\tExtraConfig: opts,\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn task.Wait(d.getCtx())\n}\n\nfunc (d *Driver) addTags(vm *object.VirtualMachine) error {\n\tif len(d.Tags) <= 0 {\n\t\treturn nil\n\t}\n\n\tlog.Infof(\"Adding %d tag(s) to VM\", len(d.Tags))\n\tc, err := d.getSoapClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttagsManager := tags.NewManager(d.getRestLogin(c.Client))\n\tif err = tagsManager.Login(d.getCtx(), d.getUserInfo()); err != nil {\n\t\treturn err\n\t}\n\n\tfor _, tagID := range d.Tags {\n\t\ttag, err := tagsManager.GetTag(d.getCtx(), tagID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\ttagsManager.AttachTag(d.getCtx(), tag.ID, vm)\n\t}\n\n\treturn nil\n}\n\nfunc (d *Driver) addCustomAttributes(vm *object.VirtualMachine) error {\n\tif len(d.CustomAttributes) <= 0 {\n\t\treturn nil\n\t}\n\n\tlog.Infof(\"Adding %d custom attribute(s) to VM\", len(d.CustomAttributes))\n\tc, err := d.getSoapClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfieldsManager, err := object.GetCustomFieldsManager(c.Client)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, field := range d.CustomAttributes {\n\t\tsplit := strings.SplitN(field, \"=\", 2)\n\t\ti, err := strconv.Atoi(split[0])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := fieldsManager.Set(d.getCtx(), vm.Reference(), int32(i), split[1]); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (d *Driver) resizeDisk(vm *object.VirtualMachine) error {\n\tdevices, err := vm.Device(d.getCtx())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar disks []*types.VirtualDisk\n\tfor _, device := range devices {\n\t\tswitch md := device.(type) {\n\t\tcase *types.VirtualDisk:\n\t\t\tdisks = append(disks, md)\n\t\tdefault:\n\t\t\tcontinue\n\t\t}\n\t}\n\n\tif len(disks) < 1 {\n\t\treturn fmt.Errorf(\"No disks found for vm: %s\", vm.InventoryPath)\n\t}\n\n\t\/\/ only allow an edit on the first primary disk, multi disk resizing not supported\n\teditdisk := disks[0]\n\tnewSize := int64(d.DiskSize) * 1024\n\tif newSize <= editdisk.CapacityInKB {\n\t\tlog.Infof(\"Can only resize up, passed size is less than or equal to the cloned disk size: %dKb <= %dKb\",\n\t\t\tnewSize, editdisk.CapacityInKB)\n\t\treturn nil\n\t}\n\n\tlog.Infof(\"Resizing disk %s up from %dKb to %dKb\",\n\t\tdevices.Name(editdisk), editdisk.CapacityInKB, newSize)\n\teditdisk.CapacityInKB = newSize\n\tspec := types.VirtualMachineConfigSpec{}\n\tconfig := &types.VirtualDeviceConfigSpec{\n\t\tDevice:    editdisk,\n\t\tOperation: types.VirtualDeviceConfigSpecOperationEdit,\n\t}\n\n\tconfig.FileOperation = \"\"\n\tspec.DeviceChange = append(spec.DeviceChange, config)\n\n\ttask, err := vm.Reconfigure(d.getCtx(), spec)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = task.Wait(d.getCtx())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error resizing main disk\\nLogged Item:  %s\", err)\n\t}\n\treturn nil\n}\n<commit_msg>Added TrimSpace<commit_after>package vmwarevsphere\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/rancher\/machine\/libmachine\/log\"\n\t\"github.com\/vmware\/govmomi\/find\"\n\t\"github.com\/vmware\/govmomi\/guest\"\n\t\"github.com\/vmware\/govmomi\/object\"\n\t\"github.com\/vmware\/govmomi\/vapi\/tags\"\n\t\"github.com\/vmware\/govmomi\/vim25\/mo\"\n\t\"github.com\/vmware\/govmomi\/vim25\/types\"\n)\n\nfunc (d *Driver) getVmFolder(vm *object.VirtualMachine) (string, error) {\n\tvar mvm mo.VirtualMachine\n\tc, err := d.getSoapClient()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\terr = c.RetrieveOne(d.getCtx(), vm.Reference(), nil, &mvm)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tp := mvm.Summary.Config.VmPathName\n\tsp := strings.Split(p, \"]\")\n\tpath := strings.TrimSpace(strings.Replace(sp[1], fmt.Sprintf(\"\/%s.vmx\", d.MachineName), \"\", 1))\n\n\treturn path, nil\n}\n\nfunc (d *Driver) getVmDatastore(vm *object.VirtualMachine) (*object.Datastore, error) {\n\tvar mvm mo.VirtualMachine\n\tc, err := d.getSoapClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = c.RetrieveOne(d.getCtx(), vm.Reference(), nil, &mvm)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(mvm.Datastore) == 0 {\n\t\treturn nil, fmt.Errorf(\"No datastores for this VM\")\n\t}\n\n\tvar ds mo.Datastore\n\terr = c.RetrieveOne(d.getCtx(), mvm.Datastore[0], nil, &ds)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn d.finder.Datastore(d.getCtx(), ds.Name) \/\/convert mo to object\n}\n\nfunc (d *Driver) fetchVM(vmname string) (*object.VirtualMachine, error) {\n\tif d.vms[vmname] != nil {\n\t\treturn d.vms[vmname], nil\n\t}\n\n\tc, err := d.getSoapClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Create a new finder\n\tf := find.NewFinder(c.Client, true)\n\tvar vm *object.VirtualMachine\n\n\tdc, err := f.DatacenterOrDefault(d.getCtx(), d.Datacenter)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tf.SetDatacenter(dc)\n\tvm, err = f.VirtualMachine(d.getCtx(), vmname)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\td.vms[vmname] = vm\n\treturn vm, nil\n}\n\nfunc (d *Driver) addNetworks(vm *object.VirtualMachine, networks map[string]object.NetworkReference) error {\n\tif len(networks) <= 0 {\n\t\treturn nil\n\t}\n\n\tdevices, _ := vm.Device(d.getCtx())\n\tfor _, v := range devices {\n\t\tdev := v.GetVirtualDevice()\n\t\tif strings.Contains(dev.DeviceInfo.GetDescription().Label, \"Network adapter\") {\n\t\t\t\/\/remove old networks\n\t\t\tif err := vm.RemoveDevice(d.getCtx(), false, dev); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t}\n\t}\n\n\tvar add []types.BaseVirtualDevice\n\tfor _, netName := range d.Networks {\n\t\tbacking, err := networks[netName].EthernetCardBackingInfo(d.getCtx())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tnetdev, err := object.EthernetCardTypes().CreateEthernetCard(\"vmxnet3\", backing)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tlog.Infof(\"Adding network: %s\", netName)\n\t\tadd = append(add, netdev)\n\t}\n\n\tif err := vm.AddDevice(d.getCtx(), add...); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (d *Driver) provisionVm(vm *object.VirtualMachine) error {\n\tlog.Infof(\"Provisioning certs and ssh keys...\")\n\n\tc, err := d.getSoapClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Generate a tar keys bundle\n\tif err := d.generateKeyBundle(); err != nil {\n\t\treturn err\n\t}\n\n\topman := guest.NewOperationsManager(c.Client, vm.Reference())\n\n\tfileman, err := opman.FileManager(d.getCtx())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsrc := d.ResolveStorePath(\"userdata.tar\")\n\ts, err := os.Stat(src)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tauth := NewAuthFlag(d.SSHUser, d.SSHPassword)\n\tflag := FileAttrFlag{}\n\tflag.SetPerms(0, 0, 660)\n\n\ttmpDir, err := fileman.CreateTemporaryDirectory(d.getCtx(), auth.Auth(), \"docker_\", \"\", \"\/tmp\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\turl, err := fileman.InitiateFileTransferToGuest(d.getCtx(), auth.Auth(), tmpDir+\"\/userdata.tar\", flag.Attr(), s.Size(), true)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tu, err := c.Client.ParseURL(url)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = c.Client.UploadFile(d.getCtx(), src, u, nil); err != nil {\n\t\treturn err\n\t}\n\n\tprocman, err := opman.ProcessManager(d.getCtx())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmds := []string{\n\t\tfmt.Sprintf(\"\/bin\/tar xvf %s\/userdata.tar -C %s\", tmpDir, tmpDir),\n\t\tfmt.Sprintf(\"\/bin\/chown -R %s:%s %s\", d.SSHUser, d.SSHUserGroup, tmpDir),\n\t\t\"\/bin\/mkdir -p \/var\/lib\/boot2docker\",\n\t\tfmt.Sprintf(\"\/bin\/cp %s\/userdata.tar \/var\/lib\/boot2docker\/userdata.tar\", tmpDir),\n\t\tfmt.Sprintf(\"\/bin\/mkdir -p \/home\/%s\/.ssh\", d.SSHUser),\n\t\tfmt.Sprintf(\"\/bin\/cp %s\/.ssh\/* \/home\/%s\/.ssh\", tmpDir, d.SSHUser), \/\/copy keys to user homedir\n\t}\n\n\tfor _, cmd := range cmds {\n\t\tif _, err := d.remoteExec(procman, cmd); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (d *Driver) addConfigParams(vm *object.VirtualMachine) error {\n\tvar opts []types.BaseOptionValue\n\tif len(d.CfgParams) > 0 {\n\t\tfor _, param := range d.CfgParams {\n\t\t\tv := strings.SplitN(param, \"=\", 2)\n\t\t\tkey := v[0]\n\t\t\tvalue := \"\"\n\t\t\tif len(v) > 1 {\n\t\t\t\tvalue = v[1]\n\t\t\t}\n\t\t\tfmt.Printf(\"Setting %s to %s\\n\", key, value)\n\t\t\topts = append(opts, &types.OptionValue{\n\t\t\t\tKey:   key,\n\t\t\t\tValue: value,\n\t\t\t})\n\t\t}\n\t}\n\n\treturn d.applyOpts(vm, opts)\n}\n\nfunc (d *Driver) applyOpts(vm *object.VirtualMachine, opts []types.BaseOptionValue) error {\n\tif len(opts) == 0 {\n\t\treturn nil\n\t}\n\n\ttask, err := vm.Reconfigure(d.getCtx(), types.VirtualMachineConfigSpec{\n\t\tExtraConfig: opts,\n\t})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn task.Wait(d.getCtx())\n}\n\nfunc (d *Driver) addTags(vm *object.VirtualMachine) error {\n\tif len(d.Tags) <= 0 {\n\t\treturn nil\n\t}\n\n\tlog.Infof(\"Adding %d tag(s) to VM\", len(d.Tags))\n\tc, err := d.getSoapClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttagsManager := tags.NewManager(d.getRestLogin(c.Client))\n\tif err = tagsManager.Login(d.getCtx(), d.getUserInfo()); err != nil {\n\t\treturn err\n\t}\n\n\tfor _, tagID := range d.Tags {\n\t\ttag, err := tagsManager.GetTag(d.getCtx(), tagID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\ttagsManager.AttachTag(d.getCtx(), tag.ID, vm)\n\t}\n\n\treturn nil\n}\n\nfunc (d *Driver) addCustomAttributes(vm *object.VirtualMachine) error {\n\tif len(d.CustomAttributes) <= 0 {\n\t\treturn nil\n\t}\n\n\tlog.Infof(\"Adding %d custom attribute(s) to VM\", len(d.CustomAttributes))\n\tc, err := d.getSoapClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfieldsManager, err := object.GetCustomFieldsManager(c.Client)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, field := range d.CustomAttributes {\n\t\tsplit := strings.SplitN(field, \"=\", 2)\n\t\ti, err := strconv.Atoi(split[0])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := fieldsManager.Set(d.getCtx(), vm.Reference(), int32(i), split[1]); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (d *Driver) resizeDisk(vm *object.VirtualMachine) error {\n\tdevices, err := vm.Device(d.getCtx())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar disks []*types.VirtualDisk\n\tfor _, device := range devices {\n\t\tswitch md := device.(type) {\n\t\tcase *types.VirtualDisk:\n\t\t\tdisks = append(disks, md)\n\t\tdefault:\n\t\t\tcontinue\n\t\t}\n\t}\n\n\tif len(disks) < 1 {\n\t\treturn fmt.Errorf(\"No disks found for vm: %s\", vm.InventoryPath)\n\t}\n\n\t\/\/ only allow an edit on the first primary disk, multi disk resizing not supported\n\teditdisk := disks[0]\n\tnewSize := int64(d.DiskSize) * 1024\n\tif newSize <= editdisk.CapacityInKB {\n\t\tlog.Infof(\"Can only resize up, passed size is less than or equal to the cloned disk size: %dKb <= %dKb\",\n\t\t\tnewSize, editdisk.CapacityInKB)\n\t\treturn nil\n\t}\n\n\tlog.Infof(\"Resizing disk %s up from %dKb to %dKb\",\n\t\tdevices.Name(editdisk), editdisk.CapacityInKB, newSize)\n\teditdisk.CapacityInKB = newSize\n\tspec := types.VirtualMachineConfigSpec{}\n\tconfig := &types.VirtualDeviceConfigSpec{\n\t\tDevice:    editdisk,\n\t\tOperation: types.VirtualDeviceConfigSpecOperationEdit,\n\t}\n\n\tconfig.FileOperation = \"\"\n\tspec.DeviceChange = append(spec.DeviceChange, config)\n\n\ttask, err := vm.Reconfigure(d.getCtx(), spec)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = task.Wait(d.getCtx())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error resizing main disk\\nLogged Item:  %s\", err)\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package apis\n\nimport (\n\t\"time\"\n\n\t\"github.com\/dgrijalva\/jwt-go\"\n\t\"github.com\/go-ozzo\/ozzo-routing\"\n\t\"github.com\/go-ozzo\/ozzo-routing\/auth\"\n\t\"github.com\/Zhanat87\/go\/app\"\n\t\"github.com\/Zhanat87\/go\/errors\"\n\t\"github.com\/Zhanat87\/go\/models\"\n\t\"golang.org\/x\/crypto\/bcrypt\"\n)\n\ntype Credential struct {\n\tUsername string `json:\"username\"`\n\tPassword string `json:\"password\"`\n}\n\nfunc Auth(signingKey string) routing.Handler {\n\treturn func(c *routing.Context) error {\n\t\tvar credential Credential\n\t\tif err := c.Read(&credential); err != nil {\n\t\t\treturn errors.Unauthorized(err.Error())\n\t\t}\n\n\t\tidentity := authenticate(credential)\n\t\tif identity == nil {\n\t\t\treturn errors.Unauthorized(\"invalid credential\")\n\t\t}\n\n\t\ttoken, err := auth.NewJWT(jwt.MapClaims{\n\t\t\t\"id\":   identity.GetID(),\n\t\t\t\"name\": identity.GetName(),\n\t\t\t\"exp\":  time.Now().Add(time.Hour * 72).Unix(),\n\t\t}, signingKey)\n\t\tif err != nil {\n\t\t\treturn errors.Unauthorized(err.Error())\n\t\t}\n\n\t\treturn c.Write(map[string]string{\n\t\t\t\"token\": token,\n\t\t})\n\t}\n}\n\nfunc authenticate(c Credential) models.Identity {\n\tif c.Username == \"demo\" && validatePassword(c.Password) {\n\t\treturn &models.User{ID: \"100\", Name: \"demo\"}\n\t}\n\treturn nil\n}\n\nfunc validatePassword(string password) bool {\n\t\/\/ demo hash\n\thashedPassword := \"$2a$10$t1RYRtQK.K2hjmCpX4ti7.\/3q4F.jww79M4VSHCtCFWpUsYrUFQiK\"\n\tpassword = []byte(password)\n\terr := bcrypt.CompareHashAndPassword(hashedPassword, password)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc JWTHandler(c *routing.Context, j *jwt.Token) error {\n\tuserID := j.Claims.(jwt.MapClaims)[\"id\"].(string)\n\tapp.GetRequestScope(c).SetUserID(userID)\n\treturn nil\n}\n<commit_msg>validatePassword<commit_after>package apis\n\nimport (\n\t\"time\"\n\n\t\"github.com\/dgrijalva\/jwt-go\"\n\t\"github.com\/go-ozzo\/ozzo-routing\"\n\t\"github.com\/go-ozzo\/ozzo-routing\/auth\"\n\t\"github.com\/Zhanat87\/go\/app\"\n\t\"github.com\/Zhanat87\/go\/errors\"\n\t\"github.com\/Zhanat87\/go\/models\"\n\t\"golang.org\/x\/crypto\/bcrypt\"\n)\n\ntype Credential struct {\n\tUsername string `json:\"username\"`\n\tPassword string `json:\"password\"`\n}\n\nfunc Auth(signingKey string) routing.Handler {\n\treturn func(c *routing.Context) error {\n\t\tvar credential Credential\n\t\tif err := c.Read(&credential); err != nil {\n\t\t\treturn errors.Unauthorized(err.Error())\n\t\t}\n\n\t\tidentity := authenticate(credential)\n\t\tif identity == nil {\n\t\t\treturn errors.Unauthorized(\"invalid credential\")\n\t\t}\n\n\t\ttoken, err := auth.NewJWT(jwt.MapClaims{\n\t\t\t\"id\":   identity.GetID(),\n\t\t\t\"name\": identity.GetName(),\n\t\t\t\"exp\":  time.Now().Add(time.Hour * 72).Unix(),\n\t\t}, signingKey)\n\t\tif err != nil {\n\t\t\treturn errors.Unauthorized(err.Error())\n\t\t}\n\n\t\treturn c.Write(map[string]string{\n\t\t\t\"token\": token,\n\t\t})\n\t}\n}\n\nfunc authenticate(c Credential) models.Identity {\n\tif c.Username == \"demo\" && validatePassword([]byte(c.Password)) {\n\t\treturn &models.User{ID: \"100\", Name: \"demo\"}\n\t}\n\treturn nil\n}\n\nfunc validatePassword([]byte password) bool {\n\t\/\/ demo hash\n\thashedPassword := \"$2a$10$t1RYRtQK.K2hjmCpX4ti7.\/3q4F.jww79M4VSHCtCFWpUsYrUFQiK\"\n\terr := bcrypt.CompareHashAndPassword(hashedPassword, password)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc JWTHandler(c *routing.Context, j *jwt.Token) error {\n\tuserID := j.Claims.(jwt.MapClaims)[\"id\"].(string)\n\tapp.GetRequestScope(c).SetUserID(userID)\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n   Copyright (c) 2016, Percona LLC and\/or its affiliates. All rights reserved.\n\n   This program is free software: you can redistribute it and\/or modify\n   it under the terms of the GNU Affero General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU Affero General Public License for more details.\n\n   You should have received a copy of the GNU Affero General Public License\n   along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>\n*\/\n\npackage mysql\n\nimport (\n\t\"database\/sql\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/percona\/pmm\/proto\"\n\t\"github.com\/percona\/qan-agent\/mysql\"\n)\n\ntype QueryExecutor struct {\n\tconn mysql.Connector\n}\n\nfunc NewQueryExecutor(conn mysql.Connector) *QueryExecutor {\n\te := &QueryExecutor{\n\t\tconn: conn,\n\t}\n\treturn e\n}\n\nfunc (e *QueryExecutor) Explain(db, query string, convert bool) (*proto.ExplainResult, error) {\n\tif db != \"\" && !strings.HasPrefix(db, \"`\") {\n\t\tdb = \"`\" + db + \"`\"\n\t}\n\texplain, err := e.explain(db, query)\n\tif err != nil {\n\t\t\/\/ MySQL 5.5 returns syntax error because it doesn't support non-SELECT EXPLAIN.\n\t\t\/\/ MySQL 5.6 non-SELECT EXPLAIN requires privs for the SQL statement.\n\t\terrCode := mysql.MySQLErrorCode(err)\n\t\tif convert && (errCode == mysql.ER_SYNTAX_ERROR || errCode == mysql.ER_USER_DENIED) && IsDMLQuery(query) {\n\t\t\tquery = DMLToSelect(query)\n\t\t\tif query == \"\" {\n\t\t\t\treturn nil, fmt.Errorf(\"cannot convert query to SELECT\")\n\t\t\t}\n\t\t\texplain, err = e.explain(db, query) \/\/ query converted to SELECT\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn explain, nil\n}\n\nfunc (e *QueryExecutor) TableInfo(tables *proto.TableInfoQuery) (proto.TableInfoResult, error) {\n\tres := make(proto.TableInfoResult)\n\n\tif len(tables.Create) > 0 {\n\t\tfor _, t := range tables.Create {\n\t\t\tdbTable := t.Db + \".\" + t.Table\n\t\t\ttableInfo, ok := res[dbTable]\n\t\t\tif !ok {\n\t\t\t\tres[dbTable] = &proto.TableInfo{}\n\t\t\t\ttableInfo = res[dbTable]\n\t\t\t}\n\n\t\t\tdb := escapeString(t.Db)\n\t\t\ttable := escapeString(t.Table)\n\t\t\tdef, err := e.showCreate(Ident(db, table))\n\t\t\tif err != nil {\n\t\t\t\tif tableInfo.Errors == nil {\n\t\t\t\t\ttableInfo.Errors = []string{}\n\t\t\t\t}\n\t\t\t\ttableInfo.Errors = append(tableInfo.Errors, fmt.Sprintf(\"SHOW CREATE TABLE %s: %s\", t.Table, err))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttableInfo.Create = def\n\t\t}\n\t}\n\n\tif len(tables.Index) > 0 {\n\t\tfor _, t := range tables.Index {\n\t\t\tdbTable := t.Db + \".\" + t.Table\n\t\t\ttableInfo, ok := res[dbTable]\n\t\t\tif !ok {\n\t\t\t\tres[dbTable] = &proto.TableInfo{}\n\t\t\t\ttableInfo = res[dbTable]\n\t\t\t}\n\n\t\t\tdb := escapeString(t.Db)\n\t\t\ttable := escapeString(t.Table)\n\t\t\tindexes, err := e.showIndex(Ident(db, table))\n\t\t\tif err != nil {\n\t\t\t\tif tableInfo.Errors == nil {\n\t\t\t\t\ttableInfo.Errors = []string{}\n\t\t\t\t}\n\t\t\t\ttableInfo.Errors = append(tableInfo.Errors, fmt.Sprintf(\"SHOW INDEX FROM %s: %s\", t.Table, err))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttableInfo.Index = indexes\n\t\t}\n\t}\n\n\tif len(tables.Status) > 0 {\n\t\tfor _, t := range tables.Status {\n\t\t\tdbTable := t.Db + \".\" + t.Table\n\t\t\ttableInfo, ok := res[dbTable]\n\t\t\tif !ok {\n\t\t\t\tres[dbTable] = &proto.TableInfo{}\n\t\t\t\ttableInfo = res[dbTable]\n\t\t\t}\n\n\t\t\t\/\/ SHOW TABLE STATUS does not accept db.tbl so pass them separately,\n\t\t\t\/\/ and tbl is used in LIKE so it's not an ident.\n\t\t\tdb := escapeString(t.Db)\n\t\t\ttable := escapeString(t.Table)\n\t\t\tstatus, err := e.showStatus(Ident(db, \"\"), table)\n\t\t\tif err != nil {\n\t\t\t\tif tableInfo.Errors == nil {\n\t\t\t\t\ttableInfo.Errors = []string{}\n\t\t\t\t}\n\t\t\t\ttableInfo.Errors = append(tableInfo.Errors, fmt.Sprintf(\"SHOW TABLE STATUS FROM %s LIKE %s: %s\", t.Db, t.Table, err))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttableInfo.Status = status\n\t\t}\n\t}\n\n\treturn res, nil\n}\n\n\/\/ --------------------------------------------------------------------------\n\nfunc (e *QueryExecutor) explain(db, query string) (*proto.ExplainResult, error) {\n\t\/\/ Transaction because we need to ensure USE and EXPLAIN are run in one connection\n\ttx, err := e.conn.DB().Begin()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer tx.Rollback()\n\n\t\/\/ If the query has a default db, use it; else, all tables need to be db-qualified\n\t\/\/ or EXPLAIN will throw an error.\n\tif db != \"\" {\n\t\t_, err := tx.Exec(fmt.Sprintf(\"USE %s\", db))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tclassicExplain, err := e.classicExplain(tx, query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tjsonExplain, err := e.jsonExplain(tx, query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\texplain := &proto.ExplainResult{\n\t\tClassic: classicExplain,\n\t\tJSON:    jsonExplain,\n\t}\n\n\treturn explain, nil\n}\n\nfunc (e *QueryExecutor) classicExplain(tx *sql.Tx, query string) (classicExplain []*proto.ExplainRow, err error) {\n\t\/\/ Partitions are introduced since MySQL 5.1\n\t\/\/ We can simply run EXPLAIN \/*!50100 PARTITIONS*\/ to get this column when it's available\n\t\/\/ without prior check for MySQL version.\n\tif strings.TrimSpace(query) == \"\" {\n\t\treturn nil, fmt.Errorf(\"cannot run EXPLAIN on an empty query example\")\n\t}\n\trows, err := tx.Query(fmt.Sprintf(\"EXPLAIN PARTITIONS %s\", query))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\t\/\/ Go rows.Scan() expects exact number of columns\n\t\/\/ so when number of columns is undefined then the easiest way to\n\t\/\/ overcome this problem is to count received number of columns\n\tcolumns, err := rows.Columns()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnCols := len(columns)\n\n\tfor rows.Next() {\n\t\texplainRow := &proto.ExplainRow{}\n\t\tswitch nCols {\n\t\tcase 10:\n\t\t\terr = rows.Scan(\n\t\t\t\t&explainRow.Id,\n\t\t\t\t&explainRow.SelectType,\n\t\t\t\t&explainRow.Table,\n\t\t\t\t&explainRow.Type,\n\t\t\t\t&explainRow.PossibleKeys,\n\t\t\t\t&explainRow.Key,\n\t\t\t\t&explainRow.KeyLen,\n\t\t\t\t&explainRow.Ref,\n\t\t\t\t&explainRow.Rows,\n\t\t\t\t&explainRow.Extra,\n\t\t\t)\n\t\tcase 11: \/\/ MySQL 5.1 with \"partitions\"\n\t\t\terr = rows.Scan(\n\t\t\t\t&explainRow.Id,\n\t\t\t\t&explainRow.SelectType,\n\t\t\t\t&explainRow.Table,\n\t\t\t\t&explainRow.Partitions, \/\/ here\n\t\t\t\t&explainRow.Type,\n\t\t\t\t&explainRow.PossibleKeys,\n\t\t\t\t&explainRow.Key,\n\t\t\t\t&explainRow.KeyLen,\n\t\t\t\t&explainRow.Ref,\n\t\t\t\t&explainRow.Rows,\n\t\t\t\t&explainRow.Extra,\n\t\t\t)\n\t\tcase 12: \/\/ MySQL 5.7 with \"filtered\"\n\t\t\terr = rows.Scan(\n\t\t\t\t&explainRow.Id,\n\t\t\t\t&explainRow.SelectType,\n\t\t\t\t&explainRow.Table,\n\t\t\t\t&explainRow.Partitions,\n\t\t\t\t&explainRow.Type,\n\t\t\t\t&explainRow.PossibleKeys,\n\t\t\t\t&explainRow.Key,\n\t\t\t\t&explainRow.KeyLen,\n\t\t\t\t&explainRow.Ref,\n\t\t\t\t&explainRow.Rows,\n\t\t\t\t&explainRow.Filtered, \/\/ here\n\t\t\t\t&explainRow.Extra,\n\t\t\t)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tclassicExplain = append(classicExplain, explainRow)\n\t}\n\terr = rows.Err()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn classicExplain, nil\n}\n\nfunc (e *QueryExecutor) jsonExplain(tx *sql.Tx, query string) (string, error) {\n\t\/\/ EXPLAIN in JSON format is introduced since MySQL 5.6.5\n\tok, err := e.conn.AtLeastVersion(\"5.6.5\")\n\tif !ok || err != nil {\n\t\treturn \"\", err\n\t}\n\n\texplain := \"\"\n\terr = tx.QueryRow(fmt.Sprintf(\"EXPLAIN FORMAT=JSON %s\", query)).Scan(&explain)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn explain, nil\n}\n\nfunc (e *QueryExecutor) showCreate(dbTable string) (string, error) {\n\t\/\/ Result from SHOW CREATE TABLE includes two columns, \"Table\" and\n\t\/\/ \"Create Table\", we ignore the first one as we need only \"Create Table\".\n\tvar tableName string\n\tvar tableDef string\n\terr := e.conn.DB().QueryRow(\"SHOW CREATE TABLE \"+dbTable).Scan(&tableName, &tableDef)\n\tif err == sql.ErrNoRows {\n\t\terr = fmt.Errorf(\"table %s doesn't exist \", dbTable)\n\t}\n\treturn tableDef, err\n}\n\nfunc (e *QueryExecutor) showIndex(dbTable string) (map[string][]proto.ShowIndexRow, error) {\n\trows, err := e.conn.DB().Query(\"SHOW INDEX FROM \" + dbTable)\n\tif err != nil && err != sql.ErrNoRows {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\tif err == sql.ErrNoRows {\n\t\terr = fmt.Errorf(\"table %s doesn't exist\", dbTable)\n\t\treturn nil, err\n\t}\n\n\tcolumns, err := rows.Columns()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thasIndexComment := len(columns) == 13 \/\/ added in MySQL 5.5\n\n\tindexes := map[string][]proto.ShowIndexRow{} \/\/ keyed on KeyName\n\tprevKeyName := \"\"\n\tfor rows.Next() {\n\t\tindexRow := proto.ShowIndexRow{}\n\t\tif hasIndexComment {\n\t\t\terr = rows.Scan(\n\t\t\t\t&indexRow.Table,\n\t\t\t\t&indexRow.NonUnique,\n\t\t\t\t&indexRow.KeyName,\n\t\t\t\t&indexRow.SeqInIndex,\n\t\t\t\t&indexRow.ColumnName,\n\t\t\t\t&indexRow.Collation,\n\t\t\t\t&indexRow.Cardinality,\n\t\t\t\t&indexRow.SubPart,\n\t\t\t\t&indexRow.Packed,\n\t\t\t\t&indexRow.Null,\n\t\t\t\t&indexRow.IndexType,\n\t\t\t\t&indexRow.Comment,\n\t\t\t\t&indexRow.IndexComment,\n\t\t\t)\n\t\t} else {\n\t\t\terr = rows.Scan(\n\t\t\t\t&indexRow.Table,\n\t\t\t\t&indexRow.NonUnique,\n\t\t\t\t&indexRow.KeyName,\n\t\t\t\t&indexRow.SeqInIndex,\n\t\t\t\t&indexRow.ColumnName,\n\t\t\t\t&indexRow.Collation,\n\t\t\t\t&indexRow.Cardinality,\n\t\t\t\t&indexRow.SubPart,\n\t\t\t\t&indexRow.Packed,\n\t\t\t\t&indexRow.Null,\n\t\t\t\t&indexRow.IndexType,\n\t\t\t\t&indexRow.Comment,\n\t\t\t)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif indexRow.KeyName != prevKeyName {\n\t\t\tindexes[indexRow.KeyName] = []proto.ShowIndexRow{}\n\t\t\tprevKeyName = indexRow.KeyName\n\t\t}\n\t\tindexes[indexRow.KeyName] = append(indexes[indexRow.KeyName], indexRow)\n\t}\n\terr = rows.Err()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn indexes, nil\n}\n\nfunc (e *QueryExecutor) showStatus(db, table string) (*proto.ShowTableStatus, error) {\n\t\/\/ Escape _ in the table name because it's a wildcard in LIKE.\n\ttable = strings.Replace(table, \"_\", \"\\\\_\", -1)\n\tstatus := &proto.ShowTableStatus{}\n\terr := e.conn.DB().QueryRow(fmt.Sprintf(\"SHOW TABLE STATUS FROM %s LIKE '%s'\", db, table)).Scan(\n\t\t&status.Name,\n\t\t&status.Engine,\n\t\t&status.Version,\n\t\t&status.RowFormat,\n\t\t&status.Rows,\n\t\t&status.AvgRowLength,\n\t\t&status.DataLength,\n\t\t&status.MaxDataLength,\n\t\t&status.IndexLength,\n\t\t&status.DataFree,\n\t\t&status.AutoIncrement,\n\t\t&status.CreateTime,\n\t\t&status.UpdateTime,\n\t\t&status.CheckTime,\n\t\t&status.Collation,\n\t\t&status.Checksum,\n\t\t&status.CreateOptions,\n\t\t&status.Comment,\n\t)\n\tif err == sql.ErrNoRows {\n\t\terr = fmt.Errorf(\"table %s.%s doesn't exist\", db, table)\n\t}\n\treturn status, err\n}\n\nfunc escapeString(v string) string {\n\treturn strings.NewReplacer(\n\t\t\"\\x00\", \"\\\\0\",\n\t\t\"\\n\", \"\\\\n\",\n\t\t\"\\r\", \"\\\\r\",\n\t\t\"\\x1a\", \"\\\\Z\",\n\t\t\"'\", \"\\\\'\",\n\t\t\"\\\"\", \"\\\\\\\"\",\n\t\t\"\\\\\", \"\\\\\\\\\",\n\t).Replace(v)\n}\n<commit_msg>PMM-405 Removed PARTITIONS from explain<commit_after>\/*\n   Copyright (c) 2016, Percona LLC and\/or its affiliates. All rights reserved.\n\n   This program is free software: you can redistribute it and\/or modify\n   it under the terms of the GNU Affero General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU Affero General Public License for more details.\n\n   You should have received a copy of the GNU Affero General Public License\n   along with this program.  If not, see <http:\/\/www.gnu.org\/licenses\/>\n*\/\n\npackage mysql\n\nimport (\n\t\"database\/sql\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/percona\/pmm\/proto\"\n\t\"github.com\/percona\/qan-agent\/mysql\"\n)\n\ntype QueryExecutor struct {\n\tconn mysql.Connector\n}\n\nfunc NewQueryExecutor(conn mysql.Connector) *QueryExecutor {\n\te := &QueryExecutor{\n\t\tconn: conn,\n\t}\n\treturn e\n}\n\nfunc (e *QueryExecutor) Explain(db, query string, convert bool) (*proto.ExplainResult, error) {\n\tif db != \"\" && !strings.HasPrefix(db, \"`\") {\n\t\tdb = \"`\" + db + \"`\"\n\t}\n\texplain, err := e.explain(db, query)\n\tif err != nil {\n\t\t\/\/ MySQL 5.5 returns syntax error because it doesn't support non-SELECT EXPLAIN.\n\t\t\/\/ MySQL 5.6 non-SELECT EXPLAIN requires privs for the SQL statement.\n\t\terrCode := mysql.MySQLErrorCode(err)\n\t\tif convert && (errCode == mysql.ER_SYNTAX_ERROR || errCode == mysql.ER_USER_DENIED) && IsDMLQuery(query) {\n\t\t\tquery = DMLToSelect(query)\n\t\t\tif query == \"\" {\n\t\t\t\treturn nil, fmt.Errorf(\"cannot convert query to SELECT\")\n\t\t\t}\n\t\t\texplain, err = e.explain(db, query) \/\/ query converted to SELECT\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn explain, nil\n}\n\nfunc (e *QueryExecutor) TableInfo(tables *proto.TableInfoQuery) (proto.TableInfoResult, error) {\n\tres := make(proto.TableInfoResult)\n\n\tif len(tables.Create) > 0 {\n\t\tfor _, t := range tables.Create {\n\t\t\tdbTable := t.Db + \".\" + t.Table\n\t\t\ttableInfo, ok := res[dbTable]\n\t\t\tif !ok {\n\t\t\t\tres[dbTable] = &proto.TableInfo{}\n\t\t\t\ttableInfo = res[dbTable]\n\t\t\t}\n\n\t\t\tdb := escapeString(t.Db)\n\t\t\ttable := escapeString(t.Table)\n\t\t\tdef, err := e.showCreate(Ident(db, table))\n\t\t\tif err != nil {\n\t\t\t\tif tableInfo.Errors == nil {\n\t\t\t\t\ttableInfo.Errors = []string{}\n\t\t\t\t}\n\t\t\t\ttableInfo.Errors = append(tableInfo.Errors, fmt.Sprintf(\"SHOW CREATE TABLE %s: %s\", t.Table, err))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttableInfo.Create = def\n\t\t}\n\t}\n\n\tif len(tables.Index) > 0 {\n\t\tfor _, t := range tables.Index {\n\t\t\tdbTable := t.Db + \".\" + t.Table\n\t\t\ttableInfo, ok := res[dbTable]\n\t\t\tif !ok {\n\t\t\t\tres[dbTable] = &proto.TableInfo{}\n\t\t\t\ttableInfo = res[dbTable]\n\t\t\t}\n\n\t\t\tdb := escapeString(t.Db)\n\t\t\ttable := escapeString(t.Table)\n\t\t\tindexes, err := e.showIndex(Ident(db, table))\n\t\t\tif err != nil {\n\t\t\t\tif tableInfo.Errors == nil {\n\t\t\t\t\ttableInfo.Errors = []string{}\n\t\t\t\t}\n\t\t\t\ttableInfo.Errors = append(tableInfo.Errors, fmt.Sprintf(\"SHOW INDEX FROM %s: %s\", t.Table, err))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttableInfo.Index = indexes\n\t\t}\n\t}\n\n\tif len(tables.Status) > 0 {\n\t\tfor _, t := range tables.Status {\n\t\t\tdbTable := t.Db + \".\" + t.Table\n\t\t\ttableInfo, ok := res[dbTable]\n\t\t\tif !ok {\n\t\t\t\tres[dbTable] = &proto.TableInfo{}\n\t\t\t\ttableInfo = res[dbTable]\n\t\t\t}\n\n\t\t\t\/\/ SHOW TABLE STATUS does not accept db.tbl so pass them separately,\n\t\t\t\/\/ and tbl is used in LIKE so it's not an ident.\n\t\t\tdb := escapeString(t.Db)\n\t\t\ttable := escapeString(t.Table)\n\t\t\tstatus, err := e.showStatus(Ident(db, \"\"), table)\n\t\t\tif err != nil {\n\t\t\t\tif tableInfo.Errors == nil {\n\t\t\t\t\ttableInfo.Errors = []string{}\n\t\t\t\t}\n\t\t\t\ttableInfo.Errors = append(tableInfo.Errors, fmt.Sprintf(\"SHOW TABLE STATUS FROM %s LIKE %s: %s\", t.Db, t.Table, err))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttableInfo.Status = status\n\t\t}\n\t}\n\n\treturn res, nil\n}\n\n\/\/ --------------------------------------------------------------------------\n\nfunc (e *QueryExecutor) explain(db, query string) (*proto.ExplainResult, error) {\n\t\/\/ Transaction because we need to ensure USE and EXPLAIN are run in one connection\n\ttx, err := e.conn.DB().Begin()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer tx.Rollback()\n\n\t\/\/ If the query has a default db, use it; else, all tables need to be db-qualified\n\t\/\/ or EXPLAIN will throw an error.\n\tif db != \"\" {\n\t\t_, err := tx.Exec(fmt.Sprintf(\"USE %s\", db))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tclassicExplain, err := e.classicExplain(tx, query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tjsonExplain, err := e.jsonExplain(tx, query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\texplain := &proto.ExplainResult{\n\t\tClassic: classicExplain,\n\t\tJSON:    jsonExplain,\n\t}\n\n\treturn explain, nil\n}\n\nfunc (e *QueryExecutor) classicExplain(tx *sql.Tx, query string) (classicExplain []*proto.ExplainRow, err error) {\n\t\/\/ Partitions are introduced since MySQL 5.1\n\t\/\/ We can simply run EXPLAIN \/*!50100 PARTITIONS*\/ to get this column when it's available\n\t\/\/ without prior check for MySQL version.\n\tif strings.TrimSpace(query) == \"\" {\n\t\treturn nil, fmt.Errorf(\"cannot run EXPLAIN on an empty query example\")\n\t}\n\trows, err := tx.Query(fmt.Sprintf(\"EXPLAIN %s\", query))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\t\/\/ Go rows.Scan() expects exact number of columns\n\t\/\/ so when number of columns is undefined then the easiest way to\n\t\/\/ overcome this problem is to count received number of columns\n\tcolumns, err := rows.Columns()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnCols := len(columns)\n\n\tfor rows.Next() {\n\t\texplainRow := &proto.ExplainRow{}\n\t\tswitch nCols {\n\t\tcase 10:\n\t\t\terr = rows.Scan(\n\t\t\t\t&explainRow.Id,\n\t\t\t\t&explainRow.SelectType,\n\t\t\t\t&explainRow.Table,\n\t\t\t\t&explainRow.Type,\n\t\t\t\t&explainRow.PossibleKeys,\n\t\t\t\t&explainRow.Key,\n\t\t\t\t&explainRow.KeyLen,\n\t\t\t\t&explainRow.Ref,\n\t\t\t\t&explainRow.Rows,\n\t\t\t\t&explainRow.Extra,\n\t\t\t)\n\t\tcase 11: \/\/ MySQL 5.1 with \"partitions\"\n\t\t\terr = rows.Scan(\n\t\t\t\t&explainRow.Id,\n\t\t\t\t&explainRow.SelectType,\n\t\t\t\t&explainRow.Table,\n\t\t\t\t&explainRow.Partitions, \/\/ here\n\t\t\t\t&explainRow.Type,\n\t\t\t\t&explainRow.PossibleKeys,\n\t\t\t\t&explainRow.Key,\n\t\t\t\t&explainRow.KeyLen,\n\t\t\t\t&explainRow.Ref,\n\t\t\t\t&explainRow.Rows,\n\t\t\t\t&explainRow.Extra,\n\t\t\t)\n\t\tcase 12: \/\/ MySQL 5.7 with \"filtered\"\n\t\t\terr = rows.Scan(\n\t\t\t\t&explainRow.Id,\n\t\t\t\t&explainRow.SelectType,\n\t\t\t\t&explainRow.Table,\n\t\t\t\t&explainRow.Partitions,\n\t\t\t\t&explainRow.Type,\n\t\t\t\t&explainRow.PossibleKeys,\n\t\t\t\t&explainRow.Key,\n\t\t\t\t&explainRow.KeyLen,\n\t\t\t\t&explainRow.Ref,\n\t\t\t\t&explainRow.Rows,\n\t\t\t\t&explainRow.Filtered, \/\/ here\n\t\t\t\t&explainRow.Extra,\n\t\t\t)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tclassicExplain = append(classicExplain, explainRow)\n\t}\n\terr = rows.Err()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn classicExplain, nil\n}\n\nfunc (e *QueryExecutor) jsonExplain(tx *sql.Tx, query string) (string, error) {\n\t\/\/ EXPLAIN in JSON format is introduced since MySQL 5.6.5\n\tok, err := e.conn.AtLeastVersion(\"5.6.5\")\n\tif !ok || err != nil {\n\t\treturn \"\", err\n\t}\n\n\texplain := \"\"\n\terr = tx.QueryRow(fmt.Sprintf(\"EXPLAIN FORMAT=JSON %s\", query)).Scan(&explain)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn explain, nil\n}\n\nfunc (e *QueryExecutor) showCreate(dbTable string) (string, error) {\n\t\/\/ Result from SHOW CREATE TABLE includes two columns, \"Table\" and\n\t\/\/ \"Create Table\", we ignore the first one as we need only \"Create Table\".\n\tvar tableName string\n\tvar tableDef string\n\terr := e.conn.DB().QueryRow(\"SHOW CREATE TABLE \"+dbTable).Scan(&tableName, &tableDef)\n\tif err == sql.ErrNoRows {\n\t\terr = fmt.Errorf(\"table %s doesn't exist \", dbTable)\n\t}\n\treturn tableDef, err\n}\n\nfunc (e *QueryExecutor) showIndex(dbTable string) (map[string][]proto.ShowIndexRow, error) {\n\trows, err := e.conn.DB().Query(\"SHOW INDEX FROM \" + dbTable)\n\tif err != nil && err != sql.ErrNoRows {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\tif err == sql.ErrNoRows {\n\t\terr = fmt.Errorf(\"table %s doesn't exist\", dbTable)\n\t\treturn nil, err\n\t}\n\n\tcolumns, err := rows.Columns()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\thasIndexComment := len(columns) == 13 \/\/ added in MySQL 5.5\n\n\tindexes := map[string][]proto.ShowIndexRow{} \/\/ keyed on KeyName\n\tprevKeyName := \"\"\n\tfor rows.Next() {\n\t\tindexRow := proto.ShowIndexRow{}\n\t\tif hasIndexComment {\n\t\t\terr = rows.Scan(\n\t\t\t\t&indexRow.Table,\n\t\t\t\t&indexRow.NonUnique,\n\t\t\t\t&indexRow.KeyName,\n\t\t\t\t&indexRow.SeqInIndex,\n\t\t\t\t&indexRow.ColumnName,\n\t\t\t\t&indexRow.Collation,\n\t\t\t\t&indexRow.Cardinality,\n\t\t\t\t&indexRow.SubPart,\n\t\t\t\t&indexRow.Packed,\n\t\t\t\t&indexRow.Null,\n\t\t\t\t&indexRow.IndexType,\n\t\t\t\t&indexRow.Comment,\n\t\t\t\t&indexRow.IndexComment,\n\t\t\t)\n\t\t} else {\n\t\t\terr = rows.Scan(\n\t\t\t\t&indexRow.Table,\n\t\t\t\t&indexRow.NonUnique,\n\t\t\t\t&indexRow.KeyName,\n\t\t\t\t&indexRow.SeqInIndex,\n\t\t\t\t&indexRow.ColumnName,\n\t\t\t\t&indexRow.Collation,\n\t\t\t\t&indexRow.Cardinality,\n\t\t\t\t&indexRow.SubPart,\n\t\t\t\t&indexRow.Packed,\n\t\t\t\t&indexRow.Null,\n\t\t\t\t&indexRow.IndexType,\n\t\t\t\t&indexRow.Comment,\n\t\t\t)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif indexRow.KeyName != prevKeyName {\n\t\t\tindexes[indexRow.KeyName] = []proto.ShowIndexRow{}\n\t\t\tprevKeyName = indexRow.KeyName\n\t\t}\n\t\tindexes[indexRow.KeyName] = append(indexes[indexRow.KeyName], indexRow)\n\t}\n\terr = rows.Err()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn indexes, nil\n}\n\nfunc (e *QueryExecutor) showStatus(db, table string) (*proto.ShowTableStatus, error) {\n\t\/\/ Escape _ in the table name because it's a wildcard in LIKE.\n\ttable = strings.Replace(table, \"_\", \"\\\\_\", -1)\n\tstatus := &proto.ShowTableStatus{}\n\terr := e.conn.DB().QueryRow(fmt.Sprintf(\"SHOW TABLE STATUS FROM %s LIKE '%s'\", db, table)).Scan(\n\t\t&status.Name,\n\t\t&status.Engine,\n\t\t&status.Version,\n\t\t&status.RowFormat,\n\t\t&status.Rows,\n\t\t&status.AvgRowLength,\n\t\t&status.DataLength,\n\t\t&status.MaxDataLength,\n\t\t&status.IndexLength,\n\t\t&status.DataFree,\n\t\t&status.AutoIncrement,\n\t\t&status.CreateTime,\n\t\t&status.UpdateTime,\n\t\t&status.CheckTime,\n\t\t&status.Collation,\n\t\t&status.Checksum,\n\t\t&status.CreateOptions,\n\t\t&status.Comment,\n\t)\n\tif err == sql.ErrNoRows {\n\t\terr = fmt.Errorf(\"table %s.%s doesn't exist\", db, table)\n\t}\n\treturn status, err\n}\n\nfunc escapeString(v string) string {\n\treturn strings.NewReplacer(\n\t\t\"\\x00\", \"\\\\0\",\n\t\t\"\\n\", \"\\\\n\",\n\t\t\"\\r\", \"\\\\r\",\n\t\t\"\\x1a\", \"\\\\Z\",\n\t\t\"'\", \"\\\\'\",\n\t\t\"\\\"\", \"\\\\\\\"\",\n\t\t\"\\\\\", \"\\\\\\\\\",\n\t).Replace(v)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * This file is a part of linuxdeploy - tool for\n * creating standalone applications for Linux\n *\n * Copyright (C) 2017 Taras Kushnir <kushnirTV@gmail.com>\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the MIT License.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\npackage main\n\nimport (\n  \"log\"\n  \"os\/exec\"\n  \"path\/filepath\"\n  \"strings\"\n  \"os\"\n  \"fmt\"\n)\n\nfunc (ad *AppDeployer) processLibTasks() {\n  for request := range ad.libsChannel {\n    ad.processLibTask(request)\n    ad.waitGroup.Done()\n  }\n\n  log.Println(\"Libraries processing finished\")\n}\n\nfunc (ad *AppDeployer) processLibTask(request *DeployRequest) {\n  libpath := request.FullPath()\n\n  if ad.canSkipLibrary(libpath) {\n    log.Printf(\"Skipping library: %v\", libpath)\n    return\n  }\n\n  log.Printf(\"Processing library: %v\", libpath)\n\n  dependencies, err := ad.findLddDependencies(request.Basename(), libpath)\n  if err != nil {\n    log.Printf(\"Error while dependency check for %v: %v\", libpath, err)\n    return\n  }\n\n  ad.accountLibrary(libpath)\n\n  ad.waitGroup.Add(1)\n  go func(copyRequest *DeployRequest) {\n    ad.copyChannel <- copyRequest\n  }(request)\n\n  flags := request.flags\n  \/\/flags.ClearFlag(FIX_RPATH_FLAG)\n  flags.AddFlag(LDD_DEPENDENCY_FLAG)\n\n  for _, dependPath := range dependencies {\n    if !ad.isLibraryDeployed(dependPath) {\n      ad.addLibTask(\"\", dependPath, \"lib\", flags)\n    }\n  }\n}\n\nfunc (ad *AppDeployer) canSkipLibrary(libpath string) bool {\n  canSkip := false\n  if strings.HasPrefix(libpath, \"linux-vdso.so\") {\n    canSkip = true\n  } else if ad.isLibraryDeployed(libpath) {\n    canSkip = true\n  }\n\n  return canSkip\n}\n\nfunc (ad *AppDeployer) findLddDependencies(basename, filepath string) ([]string, error) {\n  log.Printf(\"Inspecting %v\", filepath)\n\n  out, err := exec.Command(\"ldd\", filepath).Output()\n  if err != nil { return nil, err }\n\n  dependencies := make([]string, 0, 10)\n\n  output := string(out)\n  lines := strings.Split(output, \"\\n\")\n  for _, line := range lines {\n    line = strings.TrimSpace(line)\n    libname, libpath, err := parseLddOutputLine(line)\n\n    if err != nil {\n      log.Printf(\"Cannot parse ldd line: %v\", line)\n      continue\n    }\n\n    if len(libpath) == 0 {\n      libpath = ad.resolveLibrary(libname)\n    }\n\n    log.Printf(\"[%v]: depends on %v from ldd [%v]\", basename, libpath, line)\n    dependencies = append(dependencies, libpath)\n  }\n\n  return dependencies, nil\n}\n\nfunc (ad *AppDeployer) addAdditionalLibPath(libpath string) {\n  log.Printf(\"Adding addition libpath: %v\", libpath)\n  foundPath := libpath\n  var err error\n\n  if !filepath.IsAbs(foundPath) {\n    if foundPath, err = filepath.Abs(foundPath); err == nil {\n      log.Printf(\"Trying to resolve libpath to: %v\", foundPath)\n\n      if _, err = os.Stat(foundPath); os.IsNotExist(err) {\n        exeDir := filepath.Dir(ad.targetExePath)\n        foundPath = filepath.Join(exeDir, libpath)\n        log.Printf(\"Trying to resolve libpath to: %v\", foundPath)\n      }\n    }\n  }\n\n  if _, err := os.Stat(foundPath); os.IsNotExist(err) {\n    log.Printf(\"Cannot find library path: %v\", foundPath)\n    return\n  }\n\n  log.Printf(\"Resolved additional libpath to: %v\", foundPath)\n  ad.additionalLibPaths = append(ad.additionalLibPaths, foundPath)\n}\n\nfunc (ad *AppDeployer) resolveLibrary(libname string) (foundPath string) {\n  foundPath = libname\n\n  for _, extraLibPath := range ad.additionalLibPaths {\n    possiblePath := filepath.Join(extraLibPath, libname)\n\n    if _, err := os.Stat(possiblePath); err == nil {\n      foundPath = possiblePath\n      break\n    }\n  }\n\n  log.Printf(\"Resolving library %v to %v\", libname, foundPath)\n  return foundPath\n}\n\nfunc (ad *AppDeployer) processFixRPathTasks() {\n  patchelfAvailable := true\n\n  if _, err := exec.LookPath(\"patchelf\"); err != nil {\n    log.Printf(\"Patchelf cannot be found!\")\n    patchelfAvailable = false\n  }\n\n  destinationRoot := ad.destinationPath\n  fixedFiles := make(map[string]bool)\n\n  for fullpath := range ad.rpathChannel {\n    if patchelfAvailable {\n      if _, ok := fixedFiles[fullpath]; !ok {\n        fixRPath(fullpath, destinationRoot)\n        fixedFiles[fullpath] = true\n      } else {\n        log.Printf(\"RPATH has been already fixed for %v\", fullpath)\n      }\n    }\n\n    ad.addStripTask(fullpath)\n\n    ad.waitGroup.Done()\n  }\n\n  log.Printf(\"RPath change requests processing finished\")\n}\n\nfunc fixRPath(fullpath, destinationRoot string) {\n  libdir := filepath.Dir(fullpath)\n  relativePath, err := filepath.Rel(libdir, destinationRoot)\n  if err != nil {\n    log.Println(err)\n    return\n  }\n\n  rpath := fmt.Sprintf(\"$ORIGIN:$ORIGIN\/%s\/lib\/\", relativePath)\n  log.Printf(\"Changing RPATH for %v to %v\", fullpath, rpath)\n\n  cmd := exec.Command(\"patchelf\", \"--set-rpath\", rpath, fullpath)\n  if err = cmd.Run(); err != nil {\n    log.Println(err)\n  }\n}\n\nfunc (ad *AppDeployer) addStripTask(fullpath string) {\n  if *stripFlag {\n    ad.waitGroup.Add(1)\n    go func() {\n      ad.stripChannel <- fullpath\n    }()\n  }\n}\n\nfunc (ad *AppDeployer) processStripTasks() {\n  stripAvailable := true\n\n  if _, err := exec.LookPath(\"strip\"); err != nil {\n    log.Printf(\"Strip cannot be found!\")\n    stripAvailable = false\n  }\n\n  strippedBinaries := make(map[string]bool)\n\n  for fullpath := range ad.stripChannel {\n    if stripAvailable {\n      if _, ok := strippedBinaries[fullpath]; !ok {\n        stripBinary(fullpath)\n      } else {\n        log.Printf(\"%v has been already stripped\", fullpath)\n      }\n    }\n\n    ad.waitGroup.Done()\n  }\n\n  log.Printf(\"Strip requests processing finished\")\n}\n\nfunc stripBinary(fullpath string) {\n  log.Printf(\"Running strip on %v\", fullpath)\n\n  cmd := exec.Command(\"strip\", fullpath)\n  if err := cmd.Run(); err != nil {\n    log.Println(err)\n  }\n}\n<commit_msg>Crash if ldd cannot be found<commit_after>\/*\n * This file is a part of linuxdeploy - tool for\n * creating standalone applications for Linux\n *\n * Copyright (C) 2017 Taras Kushnir <kushnirTV@gmail.com>\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the MIT License.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\npackage main\n\nimport (\n  \"log\"\n  \"os\/exec\"\n  \"path\/filepath\"\n  \"strings\"\n  \"os\"\n  \"fmt\"\n)\n\nfunc (ad *AppDeployer) processLibTasks() {\n  if _, err := exec.LookPath(\"ldd\"); err != nil {\n    log.Fatal(\"ldd cannot be found!\")\n  }\n\n  for request := range ad.libsChannel {\n    ad.processLibTask(request)\n    ad.waitGroup.Done()\n  }\n\n  log.Println(\"Libraries processing finished\")\n}\n\nfunc (ad *AppDeployer) processLibTask(request *DeployRequest) {\n  libpath := request.FullPath()\n\n  if ad.canSkipLibrary(libpath) {\n    log.Printf(\"Skipping library: %v\", libpath)\n    return\n  }\n\n  log.Printf(\"Processing library: %v\", libpath)\n\n  dependencies, err := ad.findLddDependencies(request.Basename(), libpath)\n  if err != nil {\n    log.Printf(\"Error while dependency check for %v: %v\", libpath, err)\n    return\n  }\n\n  ad.accountLibrary(libpath)\n\n  ad.waitGroup.Add(1)\n  go func(copyRequest *DeployRequest) {\n    ad.copyChannel <- copyRequest\n  }(request)\n\n  flags := request.flags\n  \/\/ fix rpath of all the libs\n  \/\/flags.ClearFlag(FIX_RPATH_FLAG)\n  flags.AddFlag(LDD_DEPENDENCY_FLAG)\n\n  for _, dependPath := range dependencies {\n    if !ad.isLibraryDeployed(dependPath) {\n      ad.addLibTask(\"\", dependPath, \"lib\", flags)\n    }\n  }\n}\n\nfunc (ad *AppDeployer) canSkipLibrary(libpath string) bool {\n  canSkip := false\n  if strings.HasPrefix(libpath, \"linux-vdso.so\") {\n    canSkip = true\n  } else if ad.isLibraryDeployed(libpath) {\n    canSkip = true\n  }\n\n  return canSkip\n}\n\nfunc (ad *AppDeployer) findLddDependencies(basename, filepath string) ([]string, error) {\n  log.Printf(\"Inspecting %v\", filepath)\n\n  out, err := exec.Command(\"ldd\", filepath).Output()\n  if err != nil { return nil, err }\n\n  dependencies := make([]string, 0, 10)\n\n  output := string(out)\n  lines := strings.Split(output, \"\\n\")\n  for _, line := range lines {\n    line = strings.TrimSpace(line)\n    libname, libpath, err := parseLddOutputLine(line)\n\n    if err != nil {\n      log.Printf(\"Cannot parse ldd line: %v\", line)\n      continue\n    }\n\n    if len(libpath) == 0 {\n      libpath = ad.resolveLibrary(libname)\n    }\n\n    log.Printf(\"[%v]: depends on %v from ldd [%v]\", basename, libpath, line)\n    dependencies = append(dependencies, libpath)\n  }\n\n  return dependencies, nil\n}\n\nfunc (ad *AppDeployer) addAdditionalLibPath(libpath string) {\n  log.Printf(\"Adding addition libpath: %v\", libpath)\n  foundPath := libpath\n  var err error\n\n  if !filepath.IsAbs(foundPath) {\n    if foundPath, err = filepath.Abs(foundPath); err == nil {\n      log.Printf(\"Trying to resolve libpath to: %v\", foundPath)\n\n      if _, err = os.Stat(foundPath); os.IsNotExist(err) {\n        exeDir := filepath.Dir(ad.targetExePath)\n        foundPath = filepath.Join(exeDir, libpath)\n        log.Printf(\"Trying to resolve libpath to: %v\", foundPath)\n      }\n    }\n  }\n\n  if _, err := os.Stat(foundPath); os.IsNotExist(err) {\n    log.Printf(\"Cannot find library path: %v\", foundPath)\n    return\n  }\n\n  log.Printf(\"Resolved additional libpath to: %v\", foundPath)\n  ad.additionalLibPaths = append(ad.additionalLibPaths, foundPath)\n}\n\nfunc (ad *AppDeployer) resolveLibrary(libname string) (foundPath string) {\n  foundPath = libname\n\n  for _, extraLibPath := range ad.additionalLibPaths {\n    possiblePath := filepath.Join(extraLibPath, libname)\n\n    if _, err := os.Stat(possiblePath); err == nil {\n      foundPath = possiblePath\n      break\n    }\n  }\n\n  log.Printf(\"Resolving library %v to %v\", libname, foundPath)\n  return foundPath\n}\n\nfunc (ad *AppDeployer) processFixRPathTasks() {\n  patchelfAvailable := true\n\n  if _, err := exec.LookPath(\"patchelf\"); err != nil {\n    log.Printf(\"Patchelf cannot be found!\")\n    patchelfAvailable = false\n  }\n\n  destinationRoot := ad.destinationPath\n  fixedFiles := make(map[string]bool)\n\n  for fullpath := range ad.rpathChannel {\n    if patchelfAvailable {\n      if _, ok := fixedFiles[fullpath]; !ok {\n        fixRPath(fullpath, destinationRoot)\n        fixedFiles[fullpath] = true\n      } else {\n        log.Printf(\"RPATH has been already fixed for %v\", fullpath)\n      }\n    }\n\n    ad.addStripTask(fullpath)\n\n    ad.waitGroup.Done()\n  }\n\n  log.Printf(\"RPath change requests processing finished\")\n}\n\nfunc fixRPath(fullpath, destinationRoot string) {\n  libdir := filepath.Dir(fullpath)\n  relativePath, err := filepath.Rel(libdir, destinationRoot)\n  if err != nil {\n    log.Println(err)\n    return\n  }\n\n  rpath := fmt.Sprintf(\"$ORIGIN:$ORIGIN\/%s\/lib\/\", relativePath)\n  log.Printf(\"Changing RPATH for %v to %v\", fullpath, rpath)\n\n  cmd := exec.Command(\"patchelf\", \"--set-rpath\", rpath, fullpath)\n  if err = cmd.Run(); err != nil {\n    log.Println(err)\n  }\n}\n\nfunc (ad *AppDeployer) addStripTask(fullpath string) {\n  if *stripFlag {\n    ad.waitGroup.Add(1)\n    go func() {\n      ad.stripChannel <- fullpath\n    }()\n  }\n}\n\nfunc (ad *AppDeployer) processStripTasks() {\n  stripAvailable := true\n\n  if _, err := exec.LookPath(\"strip\"); err != nil {\n    log.Printf(\"Strip cannot be found!\")\n    stripAvailable = false\n  }\n\n  strippedBinaries := make(map[string]bool)\n\n  for fullpath := range ad.stripChannel {\n    if stripAvailable {\n      if _, ok := strippedBinaries[fullpath]; !ok {\n        stripBinary(fullpath)\n      } else {\n        log.Printf(\"%v has been already stripped\", fullpath)\n      }\n    }\n\n    ad.waitGroup.Done()\n  }\n\n  log.Printf(\"Strip requests processing finished\")\n}\n\nfunc stripBinary(fullpath string) {\n  log.Printf(\"Running strip on %v\", fullpath)\n\n  cmd := exec.Command(\"strip\", fullpath)\n  if err := cmd.Run(); err != nil {\n    log.Println(err)\n  }\n}\n<|endoftext|>"}
{"text":"<commit_before>package p10\r\n\r\nimport (\r\n\tc \"common\"\r\n\t\"fmt\"\r\n\t\"math\"\r\n\t\"regexp\"\r\n)\r\n\r\n\/\/ --- Day 9: Marble Mania ---\r\n\/\/ http:\/\/adventofcode.com\/2018\/day\/9\r\nfunc Solve(input string) (string, string) {\r\n\tlines := c.SplitByNewline(input)\r\n\tpoints := make([]*point, len(lines))\r\n\tfor i, l := range lines {\r\n\t\tpoints[i] = newPoint(l)\r\n\t}\r\n\tseconds := 0\r\n\twidth, height := math.MaxInt32, math.MaxInt32\r\n\tfor ; ; seconds++ {\r\n\t\tw, h := draw(points, false)\r\n\t\t\/\/ Stop once both width and height start growing again.\r\n\t\tif w > width && h > height {\r\n\t\t\tbreak\r\n\t\t}\r\n\t\twidth, height = w, h\r\n\t\titerate(points, 1)\r\n\t}\r\n\t\/\/ Reverse one step to where the bounding box was the smallest.\r\n\titerate(points, -1)\r\n\t\/\/ Uncomment this to see the result\r\n\t\/\/ draw(points, true)\r\n\treturn \"ZNNRZJXP\", c.ToString(seconds - 1)\r\n}\r\n\r\nfunc iterate(points []*point, mul int) {\r\n\tfor _, p := range points {\r\n\t\tp.x, p.y = p.x+(p.vX*mul), p.y+(p.vY*mul)\r\n\t}\r\n}\r\n\r\nfunc draw(points []*point, print bool) (int, int) {\r\n\tminX, maxX := math.MaxInt32, math.MinInt32\r\n\tminY, maxY := math.MaxInt32, math.MinInt32\r\n\tfor _, p := range points {\r\n\t\tminX, maxX = c.Min(minX, p.x), c.Max(maxX, p.x)\r\n\t\tminY, maxY = c.Min(minY, p.y), c.Max(maxY, p.y)\r\n\t}\r\n\tif print {\r\n\t\tfor y := minY; y <= maxY; y++ {\r\n\t\t\tfor x := minX; x <= maxX; x++ {\r\n\t\t\t\tch := \".\"\r\n\t\t\t\tfor _, p := range points {\r\n\t\t\t\t\tif p.x == x && p.y == y {\r\n\t\t\t\t\t\tch = \"#\"\r\n\t\t\t\t\t\tbreak\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tfmt.Print(ch)\r\n\t\t\t}\r\n\t\t\tfmt.Print(\"\\n\")\r\n\t\t}\r\n\t}\r\n\treturn maxX - minX, maxY - minY\r\n}\r\n\r\nfunc newPoint(line string) *point {\r\n\tm := regexp.MustCompile(\"position=<(.*?),(.*?)> velocity=<(.*),(.*)>\").FindStringSubmatch(line)\r\n\treturn &point{x: c.TrInt(m[1]), y: c.TrInt(m[2]), vX: c.TrInt(m[3]), vY: c.TrInt(m[4])}\r\n}\r\n\r\ntype point struct {\r\n\tx, y, vX, vY int\r\n}\r\n<commit_msg>Update comment to point to Day 10<commit_after>package p10\r\n\r\nimport (\r\n\tc \"common\"\r\n\t\"fmt\"\r\n\t\"math\"\r\n\t\"regexp\"\r\n)\r\n\r\n\/\/ --- Day 10: The Stars Align ---\r\n\/\/ http:\/\/adventofcode.com\/2018\/day\/10\r\nfunc Solve(input string) (string, string) {\r\n\tlines := c.SplitByNewline(input)\r\n\tpoints := make([]*point, len(lines))\r\n\tfor i, l := range lines {\r\n\t\tpoints[i] = newPoint(l)\r\n\t}\r\n\tseconds := 0\r\n\twidth, height := math.MaxInt32, math.MaxInt32\r\n\tfor ; ; seconds++ {\r\n\t\tw, h := draw(points, false)\r\n\t\t\/\/ Stop once both width and height start growing again.\r\n\t\tif w > width && h > height {\r\n\t\t\tbreak\r\n\t\t}\r\n\t\twidth, height = w, h\r\n\t\titerate(points, 1)\r\n\t}\r\n\t\/\/ Reverse one step to where the bounding box was the smallest.\r\n\titerate(points, -1)\r\n\t\/\/ Uncomment this to see the result\r\n\t\/\/ draw(points, true)\r\n\treturn \"ZNNRZJXP\", c.ToString(seconds - 1)\r\n}\r\n\r\nfunc iterate(points []*point, mul int) {\r\n\tfor _, p := range points {\r\n\t\tp.x, p.y = p.x+(p.vX*mul), p.y+(p.vY*mul)\r\n\t}\r\n}\r\n\r\nfunc draw(points []*point, print bool) (int, int) {\r\n\tminX, maxX := math.MaxInt32, math.MinInt32\r\n\tminY, maxY := math.MaxInt32, math.MinInt32\r\n\tfor _, p := range points {\r\n\t\tminX, maxX = c.Min(minX, p.x), c.Max(maxX, p.x)\r\n\t\tminY, maxY = c.Min(minY, p.y), c.Max(maxY, p.y)\r\n\t}\r\n\tif print {\r\n\t\tfor y := minY; y <= maxY; y++ {\r\n\t\t\tfor x := minX; x <= maxX; x++ {\r\n\t\t\t\tch := \".\"\r\n\t\t\t\tfor _, p := range points {\r\n\t\t\t\t\tif p.x == x && p.y == y {\r\n\t\t\t\t\t\tch = \"#\"\r\n\t\t\t\t\t\tbreak\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tfmt.Print(ch)\r\n\t\t\t}\r\n\t\t\tfmt.Print(\"\\n\")\r\n\t\t}\r\n\t}\r\n\treturn maxX - minX, maxY - minY\r\n}\r\n\r\nfunc newPoint(line string) *point {\r\n\tm := regexp.MustCompile(\"position=<(.*?),(.*?)> velocity=<(.*),(.*)>\").FindStringSubmatch(line)\r\n\treturn &point{x: c.TrInt(m[1]), y: c.TrInt(m[2]), vX: c.TrInt(m[3]), vY: c.TrInt(m[4])}\r\n}\r\n\r\ntype point struct {\r\n\tx, y, vX, vY int\r\n}\r\n<|endoftext|>"}
{"text":"<commit_before>package replay\n\nimport (\n\t\"net\/http\"\n\t\"fmt\"\n)\n\ntype HttpRequest struct {\n\tTag     string\n\tMethod  string\n\tUrl     string\n\tHeaders map[string]string\n}\n\ntype HttpResponse struct {\n\thost *ForwardHost\n\treq  *HttpRequest\n\tresp *http.Response\n\terr  error\n}\n\ntype RequestFactory struct {\n\tresponses chan *HttpResponse\n\trequests  chan *HttpRequest\n}\n\nfunc NewRequestFactory() (factory *RequestFactory) {\n\tfactory = &RequestFactory{}\n\tfactory.responses = make(chan *HttpResponse)\n\tfactory.requests = make(chan *HttpRequest)\n\n\tgo factory.handleRequests()\n\n\treturn\n}\n\nfunc (f *RequestFactory) sendRequest(host *ForwardHost, request *HttpRequest) {\n\tvar req *http.Request\n\n\tclient := &http.Client{}\n\n\treq, err := http.NewRequest(\"GET\", host.Url+request.Url, nil)\n\n\tfor key, value := range request.Headers {\n\t\treq.Header.Add(key, value)\n\t}\n\n\tresp, err := client.Do(req)\n\n\tdefer resp.Body.Close()\n\n\tf.responses <- &HttpResponse{host, request, resp, err}\n}\n\nfunc (f *RequestFactory) handleRequests() {\n\thosts := settings.ForwardedHosts()\n\n\tfor {\n\t\tselect {\n\t\tcase req := <- f.requests:\n\t\t\tfor _, host := range hosts {\n\t\t\t\thost.Stat.Touch()\n\n\t\t\t\tif host.Limit == 0 || host.Stat.Count < host.Limit {\n\t\t\t\t\thost.Stat.IncReq()\n\n\t\t\t\t\tfmt.Println(\"Sending request\")\n\t\t\t\t\tgo f.sendRequest(host, req)\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Println(\"Throttling for host:\", host.Url, host.Stat.Count, host.Limit)\n\t\t\t\t}\n\t\t\t}\n\t\tcase resp := <- f.responses:\n\t\t\tresp.host.Stat.IncResp(resp)\n\t\t}\n\t}\n}\n\nfunc (f *RequestFactory) Add(request *HttpRequest) {\n\tf.requests <- request\n}\n<commit_msg>Fixed craching when tried to close nil response<commit_after>package replay\n\nimport (\n\t\"net\/http\"\n\t\"fmt\"\n)\n\ntype HttpRequest struct {\n\tTag     string\n\tMethod  string\n\tUrl     string\n\tHeaders map[string]string\n}\n\ntype HttpResponse struct {\n\thost *ForwardHost\n\treq  *HttpRequest\n\tresp *http.Response\n\terr  error\n}\n\ntype RequestFactory struct {\n\tresponses chan *HttpResponse\n\trequests  chan *HttpRequest\n}\n\nfunc NewRequestFactory() (factory *RequestFactory) {\n\tfactory = &RequestFactory{}\n\tfactory.responses = make(chan *HttpResponse)\n\tfactory.requests = make(chan *HttpRequest)\n\n\tgo factory.handleRequests()\n\n\treturn\n}\n\nfunc (f *RequestFactory) sendRequest(host *ForwardHost, request *HttpRequest) {\n\tvar req *http.Request\n\n\tclient := &http.Client{}\n\n\treq, err := http.NewRequest(\"GET\", host.Url+request.Url, nil)\n\n\tfor key, value := range request.Headers {\n\t\treq.Header.Add(key, value)\n\t}\n\n\tresp, err := client.Do(req)\n\n\tif err == nil {\n\t\tdefer resp.Body.Close()\n\t}\t\n\n\tf.responses <- &HttpResponse{host, request, resp, err}\n}\n\nfunc (f *RequestFactory) handleRequests() {\n\thosts := settings.ForwardedHosts()\n\n\tfor {\n\t\tselect {\n\t\tcase req := <- f.requests:\n\t\t\tfor _, host := range hosts {\n\t\t\t\thost.Stat.Touch()\n\n\t\t\t\tif host.Limit == 0 || host.Stat.Count < host.Limit {\n\t\t\t\t\thost.Stat.IncReq()\n\n\t\t\t\t\tfmt.Println(\"Sending request\")\n\t\t\t\t\tgo f.sendRequest(host, req)\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Println(\"Throttling for host:\", host.Url, host.Stat.Count, host.Limit)\n\t\t\t\t}\n\t\t\t}\n\t\tcase resp := <- f.responses:\n\t\t\tresp.host.Stat.IncResp(resp)\n\t\t}\n\t}\n}\n\nfunc (f *RequestFactory) Add(request *HttpRequest) {\n\tf.requests <- request\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2021 The Oto Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage oto\n\nimport (\n\t\"fmt\"\n\t\"unsafe\"\n\n\t\"golang.org\/x\/sys\/windows\"\n)\n\n\/\/ Avoid goroutines on Windows (hajimehoshi\/ebiten#1768).\n\/\/ Apparently, switching contexts might take longer than other platforms.\n\nconst headerBufferSize = 4096\n\ntype header struct {\n\twaveOut uintptr\n\tbuffer  []float32\n\twaveHdr *wavehdr\n}\n\nfunc newHeader(waveOut uintptr, bufferSizeInBytes int) (*header, error) {\n\th := &header{\n\t\twaveOut: waveOut,\n\t\tbuffer:  make([]float32, bufferSizeInBytes\/4),\n\t}\n\th.waveHdr = &wavehdr{\n\t\tlpData:         uintptr(unsafe.Pointer(&h.buffer[0])),\n\t\tdwBufferLength: uint32(bufferSizeInBytes),\n\t}\n\tif err := waveOutPrepareHeader(waveOut, h.waveHdr); err != nil {\n\t\treturn nil, err\n\t}\n\treturn h, nil\n}\n\nfunc (h *header) Write(data []float32) error {\n\tcopy(h.buffer, data)\n\tif err := waveOutWrite(h.waveOut, h.waveHdr); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (h *header) IsQueued() bool {\n\treturn h.waveHdr.dwFlags&whdrInqueue != 0\n}\n\nfunc (h *header) Close() error {\n\treturn waveOutUnprepareHeader(h.waveOut, h.waveHdr)\n}\n\ntype context struct {\n\tsampleRate      int\n\tchannelNum      int\n\tbitDepthInBytes int\n\n\twaveOut uintptr\n\theaders []*header\n\n\tbuf32 []float32\n\n\tplayers *players\n}\n\nvar theContext *context\n\nfunc newContext(sampleRate, channelNum, bitDepthInBytes int) (*context, chan struct{}, error) {\n\tready := make(chan struct{})\n\tclose(ready)\n\n\tc := &context{\n\t\tsampleRate:      sampleRate,\n\t\tchannelNum:      channelNum,\n\t\tbitDepthInBytes: bitDepthInBytes,\n\t\tplayers:         newPlayers(),\n\t}\n\ttheContext = c\n\n\tconst bitsPerSample = 32\n\tnBlockAlign := c.channelNum * bitsPerSample \/ 8\n\tf := &waveformatex{\n\t\twFormatTag:      waveFormatIEEEFloat,\n\t\tnChannels:       uint16(c.channelNum),\n\t\tnSamplesPerSec:  uint32(c.sampleRate),\n\t\tnAvgBytesPerSec: uint32(c.sampleRate * nBlockAlign),\n\t\twBitsPerSample:  bitsPerSample,\n\t\tnBlockAlign:     uint16(nBlockAlign),\n\t}\n\n\t\/\/ TOOD: What about using an event instead of a callback? PortAudio and other libraries do that.\n\tw, err := waveOutOpen(f, waveOutOpenCallback)\n\tconst elementNotFound = 1168\n\tif e, ok := err.(*winmmError); ok && e.errno == elementNotFound {\n\t\t\/\/ TODO: No device was found. Return the dummy device (#77).\n\t\t\/\/ TODO: Retry to open the device when possible.\n\t\treturn nil, nil, err\n\t}\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tc.waveOut = w\n\tc.headers = make([]*header, 0, 6)\n\tfor len(c.headers) < cap(c.headers) {\n\t\th, err := newHeader(c.waveOut, headerBufferSize)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tc.headers = append(c.headers, h)\n\t}\n\n\tc.buf32 = make([]float32, headerBufferSize\/4)\n\tfor range c.headers {\n\t\tc.appendBuffers()\n\t}\n\n\treturn c, ready, nil\n}\n\nfunc (c *context) Suspend() error {\n\tif err := waveOutPause(c.waveOut); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (c *context) Resume() error {\n\t\/\/ TODO: Ensure at least one header is queued?\n\n\tif err := waveOutRestart(c.waveOut); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (c *context) isHeaderAvailable() bool {\n\tfor _, h := range c.headers {\n\t\tif !h.IsQueued() {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nvar waveOutOpenCallback = windows.NewCallbackCDecl(func(hwo, uMsg, dwInstance, dwParam1, dwParam2 uintptr) uintptr {\n\tconst womDone = 0x3bd\n\tif uMsg != womDone {\n\t\treturn 0\n\t}\n\ttheContext.appendBuffers()\n\treturn 0\n})\n\nfunc (c *context) appendBuffers() {\n\tfor i := range c.buf32 {\n\t\tc.buf32[i] = 0\n\t}\n\tc.players.read(c.buf32)\n\n\tfor _, h := range c.headers {\n\t\tif h.IsQueued() {\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := h.Write(c.buf32); err != nil {\n\t\t\t\/\/ This error can happen when e.g. a new HDMI connection is detected (#51).\n\t\t\tconst errorNotFound = 1168\n\t\t\tif werr := err.(*winmmError); werr.fname == \"waveOutWrite\" {\n\t\t\t\tswitch {\n\t\t\t\tcase werr.mmresult == mmsyserrNomem:\n\t\t\t\t\tcontinue\n\t\t\t\tcase werr.errno == errorNotFound:\n\t\t\t\t\t\/\/ TODO: Retry later.\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/ TODO: Treat the error corretly\n\t\t\tpanic(fmt.Errorf(\"oto: Queueing the header failed: %v\", err))\n\t\t}\n\t\treturn\n\t}\n}\n<commit_msg>windows: Bug fix: Don't queue a header in the callback<commit_after>\/\/ Copyright 2021 The Oto Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage oto\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\t\"unsafe\"\n\n\t\"golang.org\/x\/sys\/windows\"\n)\n\n\/\/ Avoid goroutines on Windows (hajimehoshi\/ebiten#1768).\n\/\/ Apparently, switching contexts might take longer than other platforms.\n\nconst headerBufferSize = 4096\n\ntype header struct {\n\twaveOut uintptr\n\tbuffer  []float32\n\twaveHdr *wavehdr\n}\n\nfunc newHeader(waveOut uintptr, bufferSizeInBytes int) (*header, error) {\n\th := &header{\n\t\twaveOut: waveOut,\n\t\tbuffer:  make([]float32, bufferSizeInBytes\/4),\n\t}\n\th.waveHdr = &wavehdr{\n\t\tlpData:         uintptr(unsafe.Pointer(&h.buffer[0])),\n\t\tdwBufferLength: uint32(bufferSizeInBytes),\n\t}\n\tif err := waveOutPrepareHeader(waveOut, h.waveHdr); err != nil {\n\t\treturn nil, err\n\t}\n\treturn h, nil\n}\n\nfunc (h *header) Write(data []float32) error {\n\tcopy(h.buffer, data)\n\tif err := waveOutWrite(h.waveOut, h.waveHdr); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (h *header) IsQueued() bool {\n\treturn h.waveHdr.dwFlags&whdrInqueue != 0\n}\n\nfunc (h *header) Close() error {\n\treturn waveOutUnprepareHeader(h.waveOut, h.waveHdr)\n}\n\ntype context struct {\n\tsampleRate      int\n\tchannelNum      int\n\tbitDepthInBytes int\n\n\twaveOut uintptr\n\theaders []*header\n\n\tbuf32 []float32\n\n\tplayers *players\n\n\tcond *sync.Cond\n}\n\nvar theContext *context\n\nfunc newContext(sampleRate, channelNum, bitDepthInBytes int) (*context, chan struct{}, error) {\n\tready := make(chan struct{})\n\tclose(ready)\n\n\tc := &context{\n\t\tsampleRate:      sampleRate,\n\t\tchannelNum:      channelNum,\n\t\tbitDepthInBytes: bitDepthInBytes,\n\t\tplayers:         newPlayers(),\n\t\tcond:            sync.NewCond(&sync.Mutex{}),\n\t}\n\ttheContext = c\n\n\tconst bitsPerSample = 32\n\tnBlockAlign := c.channelNum * bitsPerSample \/ 8\n\tf := &waveformatex{\n\t\twFormatTag:      waveFormatIEEEFloat,\n\t\tnChannels:       uint16(c.channelNum),\n\t\tnSamplesPerSec:  uint32(c.sampleRate),\n\t\tnAvgBytesPerSec: uint32(c.sampleRate * nBlockAlign),\n\t\twBitsPerSample:  bitsPerSample,\n\t\tnBlockAlign:     uint16(nBlockAlign),\n\t}\n\n\t\/\/ TOOD: What about using an event instead of a callback? PortAudio and other libraries do that.\n\tw, err := waveOutOpen(f, waveOutOpenCallback)\n\tconst elementNotFound = 1168\n\tif e, ok := err.(*winmmError); ok && e.errno == elementNotFound {\n\t\t\/\/ TODO: No device was found. Return the dummy device (#77).\n\t\t\/\/ TODO: Retry to open the device when possible.\n\t\treturn nil, nil, err\n\t}\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tc.waveOut = w\n\tc.headers = make([]*header, 0, 6)\n\tfor len(c.headers) < cap(c.headers) {\n\t\th, err := newHeader(c.waveOut, headerBufferSize)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tc.headers = append(c.headers, h)\n\t}\n\n\tc.buf32 = make([]float32, headerBufferSize\/4)\n\tgo c.loop()\n\n\treturn c, ready, nil\n}\n\nfunc (c *context) Suspend() error {\n\tc.cond.L.Lock()\n\tdefer c.cond.L.Unlock()\n\n\tif err := waveOutPause(c.waveOut); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (c *context) Resume() error {\n\tc.cond.L.Lock()\n\tdefer c.cond.L.Unlock()\n\n\t\/\/ TODO: Ensure at least one header is queued?\n\n\tif err := waveOutRestart(c.waveOut); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (c *context) isHeaderAvailable() bool {\n\tfor _, h := range c.headers {\n\t\tif !h.IsQueued() {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nvar waveOutOpenCallback = windows.NewCallbackCDecl(func(hwo, uMsg, dwInstance, dwParam1, dwParam2 uintptr) uintptr {\n\t\/\/ The callback is not reliable and might not be called e.g., when a headset is disconnected.\n\t\/\/ Just signal the condition vairable and don't do other things.\n\tconst womDone = 0x3bd\n\tif uMsg != womDone {\n\t\treturn 0\n\t}\n\ttheContext.cond.Signal()\n\treturn 0\n})\n\nfunc (c *context) waitUntilHeaderAvailable() {\n\tc.cond.L.Lock()\n\tdefer c.cond.L.Unlock()\n\n\tfor !c.isHeaderAvailable() {\n\t\tc.cond.Wait()\n\t}\n}\n\nfunc (c *context) loop() {\n\tfor {\n\t\tc.waitUntilHeaderAvailable()\n\t\tc.appendBuffers()\n\t}\n}\n\nfunc (c *context) appendBuffers() {\n\tc.cond.L.Lock()\n\tdefer c.cond.L.Unlock()\n\n\tfor i := range c.buf32 {\n\t\tc.buf32[i] = 0\n\t}\n\tc.players.read(c.buf32)\n\n\tfor _, h := range c.headers {\n\t\tif h.IsQueued() {\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := h.Write(c.buf32); err != nil {\n\t\t\t\/\/ This error can happen when e.g. a new HDMI connection is detected (#51).\n\t\t\tconst errorNotFound = 1168\n\t\t\tif werr := err.(*winmmError); werr.fname == \"waveOutWrite\" {\n\t\t\t\tswitch {\n\t\t\t\tcase werr.mmresult == mmsyserrNomem:\n\t\t\t\t\tcontinue\n\t\t\t\tcase werr.errno == errorNotFound:\n\t\t\t\t\t\/\/ TODO: Retry later.\n\t\t\t\t}\n\t\t\t}\n\t\t\t\/\/ TODO: Treat the error corretly\n\t\t\tpanic(fmt.Errorf(\"oto: Queueing the header failed: %v\", err))\n\t\t}\n\t\treturn\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package entities\n\nimport (\n\t\"fmt\"\n\t\"github.com\/Vladimiroff\/vec2d\"\n\t\"math\/rand\"\n\t\"strconv\"\n)\n\ntype Sun struct {\n\tUsername string\n\tName     string\n\tspeed    int\n\ttarget   *vec2d.Vector\n\tPosition *vec2d.Vector\n}\n\nfunc (s *Sun) GetKey() string {\n\treturn fmt.Sprintf(\"sun.%s\", s.Name)\n}\n\nfunc (s *Sun) String() string {\n\treturn fmt.Sprintf(\"Sun %s\", s.Name)\n}\n\nfunc (s *Sun) update() {\n\tdirection := vec2d.Sub(s.target, s.Position)\n\tif int(direction.Length()) >= s.speed {\n\t\tdirection.SetLength(float64(s.speed) * ((direction.Length() \/ 50) + 1))\n\t\ts.Position = vec2d.New(float64(s.Position.X+direction.X), float64(s.Position.Y+direction.Y))\n\t}\n}\n\nfunc (s *Sun) collider(staticSun *Sun) {\n\tdistance := vec2d.GetDistance(s.Position, staticSun.Position)\n\tif distance < SUNS_SOLAR_SYSTEM_RADIUS {\n\t\toverlap := SUNS_SOLAR_SYSTEM_RADIUS - distance\n\t\tndir := vec2d.Sub(staticSun.Position, s.Position)\n\t\tndir.SetLength(overlap)\n\t\ts.Position.Sub(ndir)\n\t}\n}\n\nfunc (s *Sun) MoveSun(position *vec2d.Vector) {\n\ts.target = position\n}\n\n\/\/ Generate sun's name out of user's initials and 3-digit random number\nfunc (s *Sun) generateName(nickname string) {\n\thash, _ := strconv.ParseInt(generateHash(nickname), 10, 64)\n\trandom := rand.New(rand.NewSource(hash))\n\tinitials := extractUsernameInitials(nickname)\n\tnumber := random.Int31n(899) + 100 \/\/ we need a 3-digit number\n\ts.Name = fmt.Sprintf(\"%s%v\", initials, number)\n}\n\nfunc GenerateSun(username string, friends, others []Sun) *Sun {\n\tnewSun := Sun{\n\t\tUsername: username,\n\t\tName:     \"\",\n\t\tspeed:    5,\n\t\ttarget:   vec2d.New(0, 0),\n\t\tPosition: getRandomStartPosition(SUNS_RANDOM_SPAWN_ZONE_RADIUS),\n\t}\n\tnewSun.generateName(username)\n\ttargetPosition := vec2d.New(0, 0)\n\n\tfor _, friend := range friends {\n\t\ttargetPosition.X += friend.Position.X\n\t\ttargetPosition.Y += friend.Position.Y\n\t}\n\ttargetPosition.X \/= float64(len(friends))\n\ttargetPosition.Y \/= float64(len(friends))\n\n\tnoChange := false\n\n\tvar oldPos *vec2d.Vector\n\tfor noChange != true {\n\t\toldPos = newSun.Position\n\t\tnewSun.update()\n\t\tfor _, sunEntity := range append(friends, others...) {\n\t\t\tnewSun.collider(&sunEntity)\n\t\t}\n\n\t\tif int64(newSun.Position.X) == int64(oldPos.X) && int64(newSun.Position.Y) == int64(oldPos.Y) {\n\t\t\tnoChange = true\n\t\t}\n\t}\n\treturn &newSun\n\t\/\/Base player placement on worker movement from BotWars\n}\n<commit_msg>Delete left-over sun.MoveSun()<commit_after>package entities\n\nimport (\n\t\"fmt\"\n\t\"github.com\/Vladimiroff\/vec2d\"\n\t\"math\/rand\"\n\t\"strconv\"\n)\n\ntype Sun struct {\n\tUsername string\n\tName     string\n\tspeed    int\n\ttarget   *vec2d.Vector\n\tPosition *vec2d.Vector\n}\n\nfunc (s *Sun) GetKey() string {\n\treturn fmt.Sprintf(\"sun.%s\", s.Name)\n}\n\nfunc (s *Sun) String() string {\n\treturn fmt.Sprintf(\"Sun %s\", s.Name)\n}\n\nfunc (s *Sun) update() {\n\tdirection := vec2d.Sub(s.target, s.Position)\n\tif int(direction.Length()) >= s.speed {\n\t\tdirection.SetLength(float64(s.speed) * ((direction.Length() \/ 50) + 1))\n\t\ts.Position = vec2d.New(float64(s.Position.X+direction.X), float64(s.Position.Y+direction.Y))\n\t}\n}\n\nfunc (s *Sun) collider(staticSun *Sun) {\n\tdistance := vec2d.GetDistance(s.Position, staticSun.Position)\n\tif distance < SUNS_SOLAR_SYSTEM_RADIUS {\n\t\toverlap := SUNS_SOLAR_SYSTEM_RADIUS - distance\n\t\tndir := vec2d.Sub(staticSun.Position, s.Position)\n\t\tndir.SetLength(overlap)\n\t\ts.Position.Sub(ndir)\n\t}\n}\n\n\/\/ Generate sun's name out of user's initials and 3-digit random number\nfunc (s *Sun) generateName(nickname string) {\n\thash, _ := strconv.ParseInt(generateHash(nickname), 10, 64)\n\trandom := rand.New(rand.NewSource(hash))\n\tinitials := extractUsernameInitials(nickname)\n\tnumber := random.Int31n(899) + 100 \/\/ we need a 3-digit number\n\ts.Name = fmt.Sprintf(\"%s%v\", initials, number)\n}\n\nfunc GenerateSun(username string, friends, others []Sun) *Sun {\n\tnewSun := Sun{\n\t\tUsername: username,\n\t\tName:     \"\",\n\t\tspeed:    5,\n\t\ttarget:   vec2d.New(0, 0),\n\t\tPosition: getRandomStartPosition(SUNS_RANDOM_SPAWN_ZONE_RADIUS),\n\t}\n\tnewSun.generateName(username)\n\ttargetPosition := vec2d.New(0, 0)\n\n\tfor _, friend := range friends {\n\t\ttargetPosition.X += friend.Position.X\n\t\ttargetPosition.Y += friend.Position.Y\n\t}\n\ttargetPosition.X \/= float64(len(friends))\n\ttargetPosition.Y \/= float64(len(friends))\n\n\tnoChange := false\n\n\tvar oldPos *vec2d.Vector\n\tfor noChange != true {\n\t\toldPos = newSun.Position\n\t\tnewSun.update()\n\t\tfor _, sunEntity := range append(friends, others...) {\n\t\t\tnewSun.collider(&sunEntity)\n\t\t}\n\n\t\tif int64(newSun.Position.X) == int64(oldPos.X) && int64(newSun.Position.Y) == int64(oldPos.Y) {\n\t\t\tnoChange = true\n\t\t}\n\t}\n\treturn &newSun\n\t\/\/Base player placement on worker movement from BotWars\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2014 tsuru authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage api\n\nimport (\n\t\"fmt\"\n\tstdLog \"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"reflect\"\n\t\"time\"\n\n\t\"github.com\/codegangsta\/negroni\"\n\t\"github.com\/tsuru\/tsuru\/api\/context\"\n\t\"github.com\/tsuru\/tsuru\/app\"\n\t\"github.com\/tsuru\/tsuru\/auth\"\n\t\"github.com\/tsuru\/tsuru\/errors\"\n\t\"github.com\/tsuru\/tsuru\/io\"\n\t\"github.com\/tsuru\/tsuru\/log\"\n)\n\nconst (\n\ttsuruMin      = \"0.12.0\"\n\tcraneMin      = \"0.6.0\"\n\ttsuruAdminMin = \"0.6.0\"\n)\n\nfunc validate(token string, r *http.Request) (auth.Token, error) {\n\tt, err := app.AuthScheme.Auth(token)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Invalid token\")\n\t}\n\tif t.IsAppToken() {\n\t\tif q := r.URL.Query().Get(\":app\"); q != \"\" && t.GetAppName() != q {\n\t\t\treturn nil, fmt.Errorf(\"App token mismatch, token for %q, request for %q\", t.GetAppName(), q)\n\t\t}\n\t} else if user, err := t.User(); err == nil {\n\t\tif q := r.URL.Query().Get(\":app\"); q != \"\" {\n\t\t\t_, err = getApp(q, user)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\treturn t, nil\n}\n\nfunc contextClearerMiddleware(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\tdefer context.Clear(r)\n\tnext(w, r)\n}\n\nfunc flushingWriterMiddleware(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\tdefer func() {\n\t\tif r.Body != nil {\n\t\t\tr.Body.Close()\n\t\t}\n\t}()\n\tfw := io.FlushingWriter{ResponseWriter: w}\n\tnext(&fw, r)\n}\n\nfunc setVersionHeadersMiddleware(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\tw.Header().Set(\"Supported-Tsuru\", tsuruMin)\n\tw.Header().Set(\"Supported-Crane\", craneMin)\n\tw.Header().Set(\"Supported-Tsuru-Admin\", tsuruAdminMin)\n\tnext(w, r)\n}\n\nfunc errorHandlingMiddleware(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\tnext(w, r)\n\terr := context.GetRequestError(r)\n\tif err != nil {\n\t\tcode := http.StatusInternalServerError\n\t\tif e, ok := err.(*errors.HTTP); ok {\n\t\t\tcode = e.Code\n\t\t}\n\t\tflushing, ok := w.(*io.FlushingWriter)\n\t\tif ok && flushing.Wrote() {\n\t\t\tfmt.Fprintln(w, err)\n\t\t} else {\n\t\t\thttp.Error(w, err.Error(), code)\n\t\t}\n\t\tlog.Error(err.Error())\n\t}\n}\n\nfunc authTokenMiddleware(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\ttoken := r.Header.Get(\"Authorization\")\n\tif token != \"\" {\n\t\tt, err := validate(token, r)\n\t\tif err != nil {\n\t\t\tif _, ok := err.(*errors.HTTP); ok {\n\t\t\t\tcontext.AddRequestError(r, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlog.Debugf(\"Ignored invalid token for %s: %s\", r.URL.Path, err.Error())\n\t\t} else {\n\t\t\tcontext.SetAuthToken(r, t)\n\t\t}\n\t}\n\tnext(w, r)\n}\n\ntype appLockMiddleware struct {\n\texcludedHandlers []http.Handler\n}\n\nfunc (m *appLockMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\tif r.Method == \"GET\" {\n\t\tnext(w, r)\n\t\treturn\n\t}\n\tcurrentHandler := context.GetDelayedHandler(r)\n\tif currentHandler != nil {\n\t\tcurrentHandlerPtr := reflect.ValueOf(currentHandler).Pointer()\n\t\tfor _, h := range m.excludedHandlers {\n\t\t\tif reflect.ValueOf(h).Pointer() == currentHandlerPtr {\n\t\t\t\tnext(w, r)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\tappName := r.URL.Query().Get(\":app\")\n\tif appName == \"\" {\n\t\tappName = r.URL.Query().Get(\":appname\")\n\t}\n\tif appName == \"\" {\n\t\tnext(w, r)\n\t\treturn\n\t}\n\tt := context.GetAuthToken(r)\n\tvar owner string\n\tif t != nil {\n\t\tif t.IsAppToken() {\n\t\t\towner = t.GetAppName()\n\t\t} else {\n\t\t\towner = t.GetUserName()\n\t\t}\n\t}\n\tok, err := app.AcquireApplicationLock(appName, owner, fmt.Sprintf(\"%s %s\", r.Method, r.URL.Path))\n\tif err != nil {\n\t\tcontext.AddRequestError(r, fmt.Errorf(\"Error trying to acquire application lock: %s\", err))\n\t\treturn\n\t}\n\tif ok {\n\t\tdefer func() {\n\t\t\tif !context.IsPreventUnlock(r) {\n\t\t\t\tapp.ReleaseApplicationLock(appName)\n\t\t\t}\n\t\t}()\n\t\tnext(w, r)\n\t\treturn\n\t}\n\ta, err := app.GetByName(appName)\n\thttpErr := &errors.HTTP{Code: http.StatusInternalServerError}\n\tif err != nil {\n\t\tif err == app.ErrAppNotFound {\n\t\t\thttpErr.Code = http.StatusNotFound\n\t\t\thttpErr.Message = err.Error()\n\t\t} else {\n\t\t\thttpErr.Message = fmt.Sprintf(\"Error to get application: %s\", err)\n\t\t}\n\t} else {\n\t\thttpErr.Code = http.StatusConflict\n\t\tif a.Lock.Locked {\n\t\t\thttpErr.Message = fmt.Sprintf(\"%s\", &a.Lock)\n\t\t} else {\n\t\t\thttpErr.Message = \"Not locked anymore, please try again.\"\n\t\t}\n\t}\n\tcontext.AddRequestError(r, httpErr)\n}\n\nfunc runDelayedHandler(w http.ResponseWriter, r *http.Request) {\n\th := context.GetDelayedHandler(r)\n\tif h != nil {\n\t\th.ServeHTTP(w, r)\n\t}\n}\n\ntype loggerMiddleware struct {\n\tlogger *stdLog.Logger\n}\n\nfunc newLoggerMiddleware() *loggerMiddleware {\n\treturn &loggerMiddleware{\n\t\tlogger: stdLog.New(os.Stdout, \"\", 0),\n\t}\n}\n\nfunc (l *loggerMiddleware) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\tstart := time.Now()\n\tnext(rw, r)\n\tduration := time.Since(start)\n\tres := rw.(negroni.ResponseWriter)\n\tnowFormatted := time.Now().Format(time.RFC3339Nano)\n\tl.logger.Printf(\"%s %s %s %d in %0.6fms\", nowFormatted, r.Method, r.URL.Path, res.Status(), float64(duration)\/float64(time.Millisecond))\n}\n<commit_msg>api\/middleware: update minimum requirements for tsuru and tsuru-admin<commit_after>\/\/ Copyright 2014 tsuru authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage api\n\nimport (\n\t\"fmt\"\n\tstdLog \"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"reflect\"\n\t\"time\"\n\n\t\"github.com\/codegangsta\/negroni\"\n\t\"github.com\/tsuru\/tsuru\/api\/context\"\n\t\"github.com\/tsuru\/tsuru\/app\"\n\t\"github.com\/tsuru\/tsuru\/auth\"\n\t\"github.com\/tsuru\/tsuru\/errors\"\n\t\"github.com\/tsuru\/tsuru\/io\"\n\t\"github.com\/tsuru\/tsuru\/log\"\n)\n\nconst (\n\ttsuruMin      = \"0.13.0\"\n\tcraneMin      = \"0.6.0\"\n\ttsuruAdminMin = \"0.7.0\"\n)\n\nfunc validate(token string, r *http.Request) (auth.Token, error) {\n\tt, err := app.AuthScheme.Auth(token)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Invalid token\")\n\t}\n\tif t.IsAppToken() {\n\t\tif q := r.URL.Query().Get(\":app\"); q != \"\" && t.GetAppName() != q {\n\t\t\treturn nil, fmt.Errorf(\"App token mismatch, token for %q, request for %q\", t.GetAppName(), q)\n\t\t}\n\t} else if user, err := t.User(); err == nil {\n\t\tif q := r.URL.Query().Get(\":app\"); q != \"\" {\n\t\t\t_, err = getApp(q, user)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\treturn t, nil\n}\n\nfunc contextClearerMiddleware(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\tdefer context.Clear(r)\n\tnext(w, r)\n}\n\nfunc flushingWriterMiddleware(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\tdefer func() {\n\t\tif r.Body != nil {\n\t\t\tr.Body.Close()\n\t\t}\n\t}()\n\tfw := io.FlushingWriter{ResponseWriter: w}\n\tnext(&fw, r)\n}\n\nfunc setVersionHeadersMiddleware(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\tw.Header().Set(\"Supported-Tsuru\", tsuruMin)\n\tw.Header().Set(\"Supported-Crane\", craneMin)\n\tw.Header().Set(\"Supported-Tsuru-Admin\", tsuruAdminMin)\n\tnext(w, r)\n}\n\nfunc errorHandlingMiddleware(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\tnext(w, r)\n\terr := context.GetRequestError(r)\n\tif err != nil {\n\t\tcode := http.StatusInternalServerError\n\t\tif e, ok := err.(*errors.HTTP); ok {\n\t\t\tcode = e.Code\n\t\t}\n\t\tflushing, ok := w.(*io.FlushingWriter)\n\t\tif ok && flushing.Wrote() {\n\t\t\tfmt.Fprintln(w, err)\n\t\t} else {\n\t\t\thttp.Error(w, err.Error(), code)\n\t\t}\n\t\tlog.Error(err.Error())\n\t}\n}\n\nfunc authTokenMiddleware(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\ttoken := r.Header.Get(\"Authorization\")\n\tif token != \"\" {\n\t\tt, err := validate(token, r)\n\t\tif err != nil {\n\t\t\tif _, ok := err.(*errors.HTTP); ok {\n\t\t\t\tcontext.AddRequestError(r, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlog.Debugf(\"Ignored invalid token for %s: %s\", r.URL.Path, err.Error())\n\t\t} else {\n\t\t\tcontext.SetAuthToken(r, t)\n\t\t}\n\t}\n\tnext(w, r)\n}\n\ntype appLockMiddleware struct {\n\texcludedHandlers []http.Handler\n}\n\nfunc (m *appLockMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\tif r.Method == \"GET\" {\n\t\tnext(w, r)\n\t\treturn\n\t}\n\tcurrentHandler := context.GetDelayedHandler(r)\n\tif currentHandler != nil {\n\t\tcurrentHandlerPtr := reflect.ValueOf(currentHandler).Pointer()\n\t\tfor _, h := range m.excludedHandlers {\n\t\t\tif reflect.ValueOf(h).Pointer() == currentHandlerPtr {\n\t\t\t\tnext(w, r)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\tappName := r.URL.Query().Get(\":app\")\n\tif appName == \"\" {\n\t\tappName = r.URL.Query().Get(\":appname\")\n\t}\n\tif appName == \"\" {\n\t\tnext(w, r)\n\t\treturn\n\t}\n\tt := context.GetAuthToken(r)\n\tvar owner string\n\tif t != nil {\n\t\tif t.IsAppToken() {\n\t\t\towner = t.GetAppName()\n\t\t} else {\n\t\t\towner = t.GetUserName()\n\t\t}\n\t}\n\tok, err := app.AcquireApplicationLock(appName, owner, fmt.Sprintf(\"%s %s\", r.Method, r.URL.Path))\n\tif err != nil {\n\t\tcontext.AddRequestError(r, fmt.Errorf(\"Error trying to acquire application lock: %s\", err))\n\t\treturn\n\t}\n\tif ok {\n\t\tdefer func() {\n\t\t\tif !context.IsPreventUnlock(r) {\n\t\t\t\tapp.ReleaseApplicationLock(appName)\n\t\t\t}\n\t\t}()\n\t\tnext(w, r)\n\t\treturn\n\t}\n\ta, err := app.GetByName(appName)\n\thttpErr := &errors.HTTP{Code: http.StatusInternalServerError}\n\tif err != nil {\n\t\tif err == app.ErrAppNotFound {\n\t\t\thttpErr.Code = http.StatusNotFound\n\t\t\thttpErr.Message = err.Error()\n\t\t} else {\n\t\t\thttpErr.Message = fmt.Sprintf(\"Error to get application: %s\", err)\n\t\t}\n\t} else {\n\t\thttpErr.Code = http.StatusConflict\n\t\tif a.Lock.Locked {\n\t\t\thttpErr.Message = fmt.Sprintf(\"%s\", &a.Lock)\n\t\t} else {\n\t\t\thttpErr.Message = \"Not locked anymore, please try again.\"\n\t\t}\n\t}\n\tcontext.AddRequestError(r, httpErr)\n}\n\nfunc runDelayedHandler(w http.ResponseWriter, r *http.Request) {\n\th := context.GetDelayedHandler(r)\n\tif h != nil {\n\t\th.ServeHTTP(w, r)\n\t}\n}\n\ntype loggerMiddleware struct {\n\tlogger *stdLog.Logger\n}\n\nfunc newLoggerMiddleware() *loggerMiddleware {\n\treturn &loggerMiddleware{\n\t\tlogger: stdLog.New(os.Stdout, \"\", 0),\n\t}\n}\n\nfunc (l *loggerMiddleware) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\tstart := time.Now()\n\tnext(rw, r)\n\tduration := time.Since(start)\n\tres := rw.(negroni.ResponseWriter)\n\tnowFormatted := time.Now().Format(time.RFC3339Nano)\n\tl.logger.Printf(\"%s %s %s %d in %0.6fms\", nowFormatted, r.Method, r.URL.Path, res.Status(), float64(duration)\/float64(time.Millisecond))\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Datastore implements workers that work with the Redis Index and Cassandra Metric datastores\npackage datastore\n\nimport (\n\t\"encoding\/json\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gopkg.in\/redis.v3\"\n\n\t\"github.com\/jeffpierce\/cassabon\/config\"\n\t\"github.com\/jeffpierce\/cassabon\/middleware\"\n)\n\ntype StatPathGopher struct {\n\trc *redis.Client \/\/ Redis client connection\n}\n\ntype MetricResponse struct {\n\tPath   string `json:\"path\"`\n\tDepth  int    `json:\"depth\"`\n\tTenant string `json:\"tenant\"`\n\tLeaf   bool   `json:\"leaf\"`\n}\n\nfunc (gopher *StatPathGopher) Init() {\n}\n\nfunc (gopher *StatPathGopher) Start() {\n\tconfig.G.OnReload2WG.Add(1)\n\tgo gopher.run()\n}\n\nfunc (gopher *StatPathGopher) run() {\n\n\tdefer config.G.OnPanic()\n\n\t\/\/ Initalize Redis client pool.\n\tvar err error\n\tif config.G.Redis.Sentinel {\n\t\tconfig.G.Log.System.LogDebug(\"Gopher initializing Redis client (Sentinel)\")\n\t\tgopher.rc, err = middleware.RedisFailoverClient(\n\t\t\tconfig.G.Redis.Addr,\n\t\t\tconfig.G.Redis.Pwd,\n\t\t\tconfig.G.Redis.Master,\n\t\t\tconfig.G.Redis.DB,\n\t\t)\n\t} else {\n\t\tconfig.G.Log.System.LogDebug(\"Gopher initializing Redis client\")\n\t\tgopher.rc, err = middleware.RedisClient(\n\t\t\tconfig.G.Redis.Addr,\n\t\t\tconfig.G.Redis.Pwd,\n\t\t\tconfig.G.Redis.DB,\n\t\t)\n\t}\n\n\tif err != nil {\n\t\t\/\/ Without Redis client we can't do our job, so log, whine, and crash.\n\t\tconfig.G.Log.System.LogFatal(\"Gopher unable to connect to Redis at %v: %v\",\n\t\t\tconfig.G.Redis.Addr, err)\n\t}\n\n\tdefer gopher.rc.Close()\n\tconfig.G.Log.System.LogDebug(\"Gopher Redis client initialized\")\n\n\t\/\/ Wait for queries to arrive, and process them.\n\tfor {\n\t\tselect {\n\t\tcase <-config.G.OnReload2:\n\t\t\tconfig.G.Log.System.LogDebug(\"Gopher::run received QUIT message\")\n\t\t\tconfig.G.OnReload2WG.Done()\n\t\t\treturn\n\t\tcase gopherQuery := <-config.G.Channels.Gopher:\n\t\t\tgo gopher.query(gopherQuery)\n\t\t}\n\t}\n}\n\nfunc (gopher *StatPathGopher) query(q config.IndexQuery) {\n\tconfig.G.Log.System.LogDebug(\"Gopher::query %v\", q.Query)\n\n\t\/\/ Listen to the channel, get string query.\n\tstatQuery := q.Query\n\n\t\/\/ Split it since we need the node length for the Redis Query\n\tqueryNodes := strings.Split(statQuery, \".\")\n\n\t\/\/ Split on wildcards.\n\tsplitWild := strings.Split(statQuery, \"*\")\n\n\t\/\/ Determine if we need a simple query or a complex one.\n\t\/\/ len(splitWild) == 2 and splitWild[-1] == \"\" means we have an ending wildcard only.\n\tif len(splitWild) == 1 {\n\t\tq.Channel <- gopher.noWild(statQuery, len(queryNodes))\n\t} else if len(splitWild) == 2 && splitWild[1] == \"\" {\n\t\tq.Channel <- gopher.simpleWild(splitWild[0], len(queryNodes))\n\t} else {\n\t\tq.Channel <- gopher.complexWild(splitWild, len(queryNodes))\n\t}\n}\n\nfunc (gopher *StatPathGopher) getMax(s string) string {\n\t\/\/ Returns the max range parameter for a ZRANGEBYLEX\n\tvar max string\n\n\tif s[len(s)-1:] == \".\" || s[len(s)-1:] == \":\" {\n\t\t\/\/ If a dot is on the end, the max path has to have a \\ put before the final dot.\n\t\tmax = strings.Join([]string{s[:len(s)-1], `\\`, s[len(s)-1:], `\\xff`}, \"\")\n\t} else {\n\t\t\/\/ If a dot's not on the end, just append \"\\xff\"\n\t\tmax = strings.Join([]string{s, `\\xff`}, \"\")\n\t}\n\n\treturn max\n}\n\nfunc (gopher *StatPathGopher) simpleWild(q string, l int) []byte {\n\t\/\/ Queries with an ending wild card only are easy, as the response from\n\t\/\/ ZRANGEBYLEX <key> [bigE_len:path [bigE_len:path\\xff is the answer.\n\tqueryString := strings.Join([]string{\"[\", ToBigEndianString(l), \":\", q}, \"\")\n\tqueryStringMax := gopher.getMax(queryString)\n\n\t\/\/ Perform the query.\n\tresp, err := gopher.rc.ZRangeByLex(config.G.Redis.PathKeyname, redis.ZRangeByScore{\n\t\tqueryString, queryStringMax, 0, 0,\n\t}).Result()\n\n\tif err != nil || len(resp) == 0 {\n\t\t\/\/ Errored, return empty set.\n\t\tconfig.G.Log.System.LogWarn(\"Redis error or zero length response.\")\n\t\treturn nil\n\t}\n\n\t\/\/ Send query results off to be processed into a string and return them.\n\treturn gopher.processQueryResults(resp, l)\n}\n\nfunc (gopher *StatPathGopher) noWild(q string, l int) []byte {\n\t\/\/ No wild card means we should be retrieving one stat, or none at all.\n\tqueryString := strings.Join([]string{\"[\", ToBigEndianString(l), \":\", q, \":\"}, \"\")\n\tqueryStringMax := gopher.getMax(queryString)\n\n\tresp, err := gopher.rc.ZRangeByLex(config.G.Redis.PathKeyname, redis.ZRangeByScore{\n\t\tqueryString, queryStringMax, 0, 0,\n\t}).Result()\n\n\tif err != nil || len(resp) == 0 {\n\t\t\/\/ Error or empty set, return an empty set.\n\t\tconfig.G.Log.System.LogInfo(\"Redis error or zero length response.\")\n\t\treturn nil\n\t}\n\n\treturn gopher.processQueryResults(resp, l)\n}\n\nfunc (gopher *StatPathGopher) complexWild(splitWild []string, l int) []byte {\n\t\/\/ Resolve multiple wildcards by pulling in the nodes with length l that start with\n\t\/\/ the first part of the non-wildcard, then filter that set with a regex match.\n\tvar matches []string\n\n\tqueryString := strings.Join([]string{\"[\", ToBigEndianString(l), \":\", splitWild[0]}, \"\")\n\tqueryStringMax := gopher.getMax(queryString)\n\n\tconfig.G.Log.System.LogDebug(\n\t\t\"complexWild querying redis with %s, %s as range\", queryString, queryStringMax)\n\n\tresp, err := gopher.rc.ZRangeByLex(config.G.Redis.PathKeyname, redis.ZRangeByScore{\n\t\tqueryString, queryStringMax, 0, 0,\n\t}).Result()\n\n\tconfig.G.Log.System.LogDebug(\n\t\t\"Received %v as response from redis.\", resp)\n\n\tif err != nil || len(resp) == 0 {\n\t\tconfig.G.Log.System.LogInfo(\"Redis error or zero length response.\")\n\t\treturn nil\n\t}\n\n\t\/\/ Build regular expression to match against results.\n\trawRegex := strings.Join(splitWild, `.*`)\n\tconfig.G.Log.System.LogDebug(\"Attempting to compile %s into regex\", rawRegex)\n\n\tregex, err := regexp.Compile(rawRegex)\n\tif err != nil {\n\t\tconfig.G.Log.System.LogError(\"Could not compile %s into regex, %v\", rawRegex, err)\n\t\treturn nil\n\t}\n\n\tfor _, iter := range resp {\n\t\tconfig.G.Log.System.LogDebug(\"Attempting to match %s against %s\", rawRegex, iter)\n\t\tif regex.MatchString(iter) {\n\t\t\tmatches = append(matches, iter)\n\t\t}\n\t}\n\n\treturn gopher.processQueryResults(matches, l)\n}\n\nfunc (gopher *StatPathGopher) processQueryResults(results []string, l int) []byte {\n\tvar responseList []MetricResponse\n\t\/\/ Process the result into a map, make it a string, send it along is the goal here.\n\tfor _, match := range results {\n\t\tdecodedString := strings.Split(match, \":\")\n\t\tisLeaf, _ := strconv.ParseBool(decodedString[2])\n\t\tm := MetricResponse{decodedString[1], l, \"\", isLeaf}\n\t\tresponseList = append(responseList, m)\n\t}\n\n\tj, _ := json.Marshal(responseList)\n\treturn j\n}\n<commit_msg>Make a comment match the code<commit_after>\/\/ Datastore implements workers that work with the Redis Index and Cassandra Metric datastores\npackage datastore\n\nimport (\n\t\"encoding\/json\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"gopkg.in\/redis.v3\"\n\n\t\"github.com\/jeffpierce\/cassabon\/config\"\n\t\"github.com\/jeffpierce\/cassabon\/middleware\"\n)\n\ntype StatPathGopher struct {\n\trc *redis.Client \/\/ Redis client connection\n}\n\ntype MetricResponse struct {\n\tPath   string `json:\"path\"`\n\tDepth  int    `json:\"depth\"`\n\tTenant string `json:\"tenant\"`\n\tLeaf   bool   `json:\"leaf\"`\n}\n\nfunc (gopher *StatPathGopher) Init() {\n}\n\nfunc (gopher *StatPathGopher) Start() {\n\tconfig.G.OnReload2WG.Add(1)\n\tgo gopher.run()\n}\n\nfunc (gopher *StatPathGopher) run() {\n\n\tdefer config.G.OnPanic()\n\n\t\/\/ Initalize Redis client pool.\n\tvar err error\n\tif config.G.Redis.Sentinel {\n\t\tconfig.G.Log.System.LogDebug(\"Gopher initializing Redis client (Sentinel)\")\n\t\tgopher.rc, err = middleware.RedisFailoverClient(\n\t\t\tconfig.G.Redis.Addr,\n\t\t\tconfig.G.Redis.Pwd,\n\t\t\tconfig.G.Redis.Master,\n\t\t\tconfig.G.Redis.DB,\n\t\t)\n\t} else {\n\t\tconfig.G.Log.System.LogDebug(\"Gopher initializing Redis client\")\n\t\tgopher.rc, err = middleware.RedisClient(\n\t\t\tconfig.G.Redis.Addr,\n\t\t\tconfig.G.Redis.Pwd,\n\t\t\tconfig.G.Redis.DB,\n\t\t)\n\t}\n\n\tif err != nil {\n\t\t\/\/ Without Redis client we can't do our job, so log, whine, and crash.\n\t\tconfig.G.Log.System.LogFatal(\"Gopher unable to connect to Redis at %v: %v\",\n\t\t\tconfig.G.Redis.Addr, err)\n\t}\n\n\tdefer gopher.rc.Close()\n\tconfig.G.Log.System.LogDebug(\"Gopher Redis client initialized\")\n\n\t\/\/ Wait for queries to arrive, and process them.\n\tfor {\n\t\tselect {\n\t\tcase <-config.G.OnReload2:\n\t\t\tconfig.G.Log.System.LogDebug(\"Gopher::run received QUIT message\")\n\t\t\tconfig.G.OnReload2WG.Done()\n\t\t\treturn\n\t\tcase gopherQuery := <-config.G.Channels.Gopher:\n\t\t\tgo gopher.query(gopherQuery)\n\t\t}\n\t}\n}\n\nfunc (gopher *StatPathGopher) query(q config.IndexQuery) {\n\tconfig.G.Log.System.LogDebug(\"Gopher::query %v\", q.Query)\n\n\t\/\/ Listen to the channel, get string query.\n\tstatQuery := q.Query\n\n\t\/\/ Split it since we need the node length for the Redis Query\n\tqueryNodes := strings.Split(statQuery, \".\")\n\n\t\/\/ Split on wildcards.\n\tsplitWild := strings.Split(statQuery, \"*\")\n\n\t\/\/ Determine if we need a simple query or a complex one.\n\t\/\/ len(splitWild) == 2 and splitWild[1] == \"\" means we have an ending wildcard only.\n\tif len(splitWild) == 1 {\n\t\tq.Channel <- gopher.noWild(statQuery, len(queryNodes))\n\t} else if len(splitWild) == 2 && splitWild[1] == \"\" {\n\t\tq.Channel <- gopher.simpleWild(splitWild[0], len(queryNodes))\n\t} else {\n\t\tq.Channel <- gopher.complexWild(splitWild, len(queryNodes))\n\t}\n}\n\nfunc (gopher *StatPathGopher) getMax(s string) string {\n\t\/\/ Returns the max range parameter for a ZRANGEBYLEX\n\tvar max string\n\n\tif s[len(s)-1:] == \".\" || s[len(s)-1:] == \":\" {\n\t\t\/\/ If a dot is on the end, the max path has to have a \\ put before the final dot.\n\t\tmax = strings.Join([]string{s[:len(s)-1], `\\`, s[len(s)-1:], `\\xff`}, \"\")\n\t} else {\n\t\t\/\/ If a dot's not on the end, just append \"\\xff\"\n\t\tmax = strings.Join([]string{s, `\\xff`}, \"\")\n\t}\n\n\treturn max\n}\n\nfunc (gopher *StatPathGopher) simpleWild(q string, l int) []byte {\n\t\/\/ Queries with an ending wild card only are easy, as the response from\n\t\/\/ ZRANGEBYLEX <key> [bigE_len:path [bigE_len:path\\xff is the answer.\n\tqueryString := strings.Join([]string{\"[\", ToBigEndianString(l), \":\", q}, \"\")\n\tqueryStringMax := gopher.getMax(queryString)\n\n\t\/\/ Perform the query.\n\tresp, err := gopher.rc.ZRangeByLex(config.G.Redis.PathKeyname, redis.ZRangeByScore{\n\t\tqueryString, queryStringMax, 0, 0,\n\t}).Result()\n\n\tif err != nil || len(resp) == 0 {\n\t\t\/\/ Errored, return empty set.\n\t\tconfig.G.Log.System.LogWarn(\"Redis error or zero length response.\")\n\t\treturn nil\n\t}\n\n\t\/\/ Send query results off to be processed into a string and return them.\n\treturn gopher.processQueryResults(resp, l)\n}\n\nfunc (gopher *StatPathGopher) noWild(q string, l int) []byte {\n\t\/\/ No wild card means we should be retrieving one stat, or none at all.\n\tqueryString := strings.Join([]string{\"[\", ToBigEndianString(l), \":\", q, \":\"}, \"\")\n\tqueryStringMax := gopher.getMax(queryString)\n\n\tresp, err := gopher.rc.ZRangeByLex(config.G.Redis.PathKeyname, redis.ZRangeByScore{\n\t\tqueryString, queryStringMax, 0, 0,\n\t}).Result()\n\n\tif err != nil || len(resp) == 0 {\n\t\t\/\/ Error or empty set, return an empty set.\n\t\tconfig.G.Log.System.LogInfo(\"Redis error or zero length response.\")\n\t\treturn nil\n\t}\n\n\treturn gopher.processQueryResults(resp, l)\n}\n\nfunc (gopher *StatPathGopher) complexWild(splitWild []string, l int) []byte {\n\t\/\/ Resolve multiple wildcards by pulling in the nodes with length l that start with\n\t\/\/ the first part of the non-wildcard, then filter that set with a regex match.\n\tvar matches []string\n\n\tqueryString := strings.Join([]string{\"[\", ToBigEndianString(l), \":\", splitWild[0]}, \"\")\n\tqueryStringMax := gopher.getMax(queryString)\n\n\tconfig.G.Log.System.LogDebug(\n\t\t\"complexWild querying redis with %s, %s as range\", queryString, queryStringMax)\n\n\tresp, err := gopher.rc.ZRangeByLex(config.G.Redis.PathKeyname, redis.ZRangeByScore{\n\t\tqueryString, queryStringMax, 0, 0,\n\t}).Result()\n\n\tconfig.G.Log.System.LogDebug(\n\t\t\"Received %v as response from redis.\", resp)\n\n\tif err != nil || len(resp) == 0 {\n\t\tconfig.G.Log.System.LogInfo(\"Redis error or zero length response.\")\n\t\treturn nil\n\t}\n\n\t\/\/ Build regular expression to match against results.\n\trawRegex := strings.Join(splitWild, `.*`)\n\tconfig.G.Log.System.LogDebug(\"Attempting to compile %s into regex\", rawRegex)\n\n\tregex, err := regexp.Compile(rawRegex)\n\tif err != nil {\n\t\tconfig.G.Log.System.LogError(\"Could not compile %s into regex, %v\", rawRegex, err)\n\t\treturn nil\n\t}\n\n\tfor _, iter := range resp {\n\t\tconfig.G.Log.System.LogDebug(\"Attempting to match %s against %s\", rawRegex, iter)\n\t\tif regex.MatchString(iter) {\n\t\t\tmatches = append(matches, iter)\n\t\t}\n\t}\n\n\treturn gopher.processQueryResults(matches, l)\n}\n\nfunc (gopher *StatPathGopher) processQueryResults(results []string, l int) []byte {\n\tvar responseList []MetricResponse\n\t\/\/ Process the result into a map, make it a string, send it along is the goal here.\n\tfor _, match := range results {\n\t\tdecodedString := strings.Split(match, \":\")\n\t\tisLeaf, _ := strconv.ParseBool(decodedString[2])\n\t\tm := MetricResponse{decodedString[1], l, \"\", isLeaf}\n\t\tresponseList = append(responseList, m)\n\t}\n\n\tj, _ := json.Marshal(responseList)\n\treturn j\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2017 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage cmd\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com\/ghodss\/yaml\"\n\t\"github.com\/spf13\/cobra\"\n\n\t\"k8s.io\/apimachinery\/pkg\/api\/errors\"\n\t\"k8s.io\/apimachinery\/pkg\/api\/meta\"\n\t\"k8s.io\/apimachinery\/pkg\/runtime\"\n\t\"k8s.io\/apimachinery\/pkg\/types\"\n\tapijson \"k8s.io\/apimachinery\/pkg\/util\/json\"\n\t\"k8s.io\/kubernetes\/pkg\/api\"\n\t\"k8s.io\/kubernetes\/pkg\/kubectl\"\n\t\"k8s.io\/kubernetes\/pkg\/kubectl\/cmd\/templates\"\n\tcmdutil \"k8s.io\/kubernetes\/pkg\/kubectl\/cmd\/util\"\n\t\"k8s.io\/kubernetes\/pkg\/kubectl\/cmd\/util\/editor\"\n\t\"k8s.io\/kubernetes\/pkg\/kubectl\/resource\"\n\t\"k8s.io\/kubernetes\/pkg\/util\/i18n\"\n)\n\ntype SetLastAppliedOptions struct {\n\tFilenameOptions  resource.FilenameOptions\n\tSelector         string\n\tInfoList         []*resource.Info\n\tMapper           meta.RESTMapper\n\tTyper            runtime.ObjectTyper\n\tNamespace        string\n\tEnforceNamespace bool\n\tDryRun           bool\n\tShortOutput      bool\n\tCreateAnnotation bool\n\tOutput           string\n\tCodec            runtime.Encoder\n\tPatchBufferList  []PatchBuffer\n\tFactory          cmdutil.Factory\n\tOut              io.Writer\n\tErrOut           io.Writer\n}\n\ntype PatchBuffer struct {\n\tPatch     []byte\n\tPatchType types.PatchType\n}\n\nvar (\n\tapplySetLastAppliedLong = templates.LongDesc(i18n.T(`\n\t\tSet the latest last-applied-configuration annotations by setting it to match the contents of a file.\n\t\tThis results in the last-applied-configuration being updated as though 'kubectl apply -f <file>' was run,\n\t\twithout updating any other parts of the object.`))\n\n\tapplySetLastAppliedExample = templates.Examples(i18n.T(`\n\t\t# Set the last-applied-configuration of a resource to match the contents of a file.\n\t\tkubectl apply set-last-applied -f deploy.yaml\n\n\t\t# Execute set-last-applied against each configuration file in a directory.\n\t\tkubectl apply set-last-applied -f path\/\n\n\t\t# Set the last-applied-configuration of a resource to match the contents of a file, will create the annotation if it does not already exist.\n\t\tkubectl apply set-last-applied -f deploy.yaml --create-annotation=true\n\t\t`))\n)\n\nfunc NewCmdApplySetLastApplied(f cmdutil.Factory, out, err io.Writer) *cobra.Command {\n\toptions := &SetLastAppliedOptions{Out: out, ErrOut: err}\n\tcmd := &cobra.Command{\n\t\tUse:     \"set-last-applied -f FILENAME\",\n\t\tShort:   i18n.T(\"Set the last-applied-configuration annotation on a live object to match the contents of a file.\"),\n\t\tLong:    applySetLastAppliedLong,\n\t\tExample: applySetLastAppliedExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(options.Complete(f, cmd))\n\t\t\tcmdutil.CheckErr(options.Validate(f, cmd))\n\t\t\tcmdutil.CheckErr(options.RunSetLastApplied(f, cmd))\n\t\t},\n\t}\n\n\tcmdutil.AddDryRunFlag(cmd)\n\tcmdutil.AddRecordFlag(cmd)\n\tcmdutil.AddPrinterFlags(cmd)\n\tcmd.Flags().BoolVar(&options.CreateAnnotation, \"create-annotation\", false, \"Will create 'last-applied-configuration' annotations if current objects doesn't have one\")\n\tusage := \"that contains the last-applied-configuration annotations\"\n\tkubectl.AddJsonFilenameFlag(cmd, &options.FilenameOptions.Filenames, \"Filename, directory, or URL to files \"+usage)\n\n\treturn cmd\n}\n\nfunc (o *SetLastAppliedOptions) Complete(f cmdutil.Factory, cmd *cobra.Command) error {\n\to.DryRun = cmdutil.GetFlagBool(cmd, \"dry-run\")\n\to.Output = cmdutil.GetFlagString(cmd, \"output\")\n\to.ShortOutput = o.Output == \"name\"\n\to.Codec = f.JSONEncoder()\n\n\tvar err error\n\to.Mapper, o.Typer, err = f.UnstructuredObject()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.Namespace, o.EnforceNamespace, err = f.DefaultNamespace()\n\treturn err\n}\n\nfunc (o *SetLastAppliedOptions) Validate(f cmdutil.Factory, cmd *cobra.Command) error {\n\tbuilder, err := f.NewUnstructuredBuilder(true)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tr := builder.\n\t\tNamespaceParam(o.Namespace).DefaultNamespace().\n\t\tFilenameParam(o.EnforceNamespace, &o.FilenameOptions).\n\t\tLatest().\n\t\tFlatten().\n\t\tDo()\n\terr = r.Err()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = r.Visit(func(info *resource.Info, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tpatchBuf, diffBuf, patchType, err := editor.GetApplyPatch(info.VersionedObject, o.Codec)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Verify the object exists in the cluster before trying to patch it.\n\t\tif err := info.Get(); err != nil {\n\t\t\tif errors.IsNotFound(err) {\n\t\t\t\treturn err\n\t\t\t} else {\n\t\t\t\treturn cmdutil.AddSourceToErr(fmt.Sprintf(\"retrieving current configuration of:\\n%v\\nfrom server for:\", info), info.Source, err)\n\t\t\t}\n\t\t}\n\t\toringalBuf, err := kubectl.GetOriginalConfiguration(info.Mapping, info.Object)\n\t\tif err != nil {\n\t\t\treturn cmdutil.AddSourceToErr(fmt.Sprintf(\"retrieving current configuration of:\\n%v\\nfrom server for:\", info), info.Source, err)\n\t\t}\n\t\tif oringalBuf == nil && !o.CreateAnnotation {\n\t\t\treturn cmdutil.UsageErrorf(cmd, \"no last-applied-configuration annotation found on resource: %s, to create the annotation, run the command with --create-annotation\", info.Name)\n\t\t}\n\n\t\t\/\/only add to PatchBufferList when changed\n\t\tif !bytes.Equal(cmdutil.StripComments(oringalBuf), cmdutil.StripComments(diffBuf)) {\n\t\t\tp := PatchBuffer{Patch: patchBuf, PatchType: patchType}\n\t\t\to.PatchBufferList = append(o.PatchBufferList, p)\n\t\t\to.InfoList = append(o.InfoList, info)\n\t\t} else {\n\t\t\tfmt.Fprintf(o.Out, \"set-last-applied %s: no changes required.\\n\", info.Name)\n\t\t}\n\n\t\treturn nil\n\t})\n\treturn err\n}\n\nfunc (o *SetLastAppliedOptions) RunSetLastApplied(f cmdutil.Factory, cmd *cobra.Command) error {\n\tfor i, patch := range o.PatchBufferList {\n\t\tinfo := o.InfoList[i]\n\t\tif !o.DryRun {\n\t\t\tmapping := info.ResourceMapping()\n\t\t\tclient, err := f.UnstructuredClientForMapping(mapping)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\thelper := resource.NewHelper(client, mapping)\n\t\t\tpatchedObj, err := helper.Patch(o.Namespace, info.Name, patch.PatchType, patch.Patch)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif len(o.Output) > 0 && !o.ShortOutput {\n\t\t\t\tinfo.Refresh(patchedObj, false)\n\t\t\t\treturn cmdutil.PrintResourceInfoForCommand(cmd, info, f, o.Out)\n\t\t\t}\n\t\t\tcmdutil.PrintSuccess(o.Mapper, o.ShortOutput, o.Out, info.Mapping.Resource, info.Name, o.DryRun, \"configured\")\n\n\t\t} else {\n\t\t\terr := o.formatPrinter(o.Output, patch.Patch, o.Out)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcmdutil.PrintSuccess(o.Mapper, o.ShortOutput, o.Out, info.Mapping.Resource, info.Name, o.DryRun, \"configured\")\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (o *SetLastAppliedOptions) formatPrinter(output string, buf []byte, w io.Writer) error {\n\tyamlOutput, err := yaml.JSONToYAML(buf)\n\tif err != nil {\n\t\treturn err\n\t}\n\tswitch output {\n\tcase \"json\":\n\t\tjsonBuffer := &bytes.Buffer{}\n\t\terr = json.Indent(jsonBuffer, buf, \"\", \"  \")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Fprintf(w, string(jsonBuffer.Bytes()))\n\tcase \"yaml\":\n\t\tfmt.Fprintf(w, string(yamlOutput))\n\t}\n\treturn nil\n}\n\nfunc (o *SetLastAppliedOptions) getPatch(info *resource.Info) ([]byte, []byte, error) {\n\tobjMap := map[string]map[string]map[string]string{}\n\tmetadataMap := map[string]map[string]string{}\n\tannotationsMap := map[string]string{}\n\tlocalFile, err := runtime.Encode(o.Codec, info.VersionedObject)\n\tif err != nil {\n\t\treturn nil, localFile, err\n\t}\n\tannotationsMap[api.LastAppliedConfigAnnotation] = string(localFile)\n\tmetadataMap[\"annotations\"] = annotationsMap\n\tobjMap[\"metadata\"] = metadataMap\n\tjsonString, err := apijson.Marshal(objMap)\n\treturn jsonString, localFile, err\n}\n<commit_msg>fix apply_set_last_applied dry-run output issue<commit_after>\/*\nCopyright 2017 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage cmd\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com\/ghodss\/yaml\"\n\t\"github.com\/spf13\/cobra\"\n\n\t\"k8s.io\/apimachinery\/pkg\/api\/errors\"\n\t\"k8s.io\/apimachinery\/pkg\/api\/meta\"\n\t\"k8s.io\/apimachinery\/pkg\/runtime\"\n\t\"k8s.io\/apimachinery\/pkg\/types\"\n\tapijson \"k8s.io\/apimachinery\/pkg\/util\/json\"\n\t\"k8s.io\/kubernetes\/pkg\/api\"\n\t\"k8s.io\/kubernetes\/pkg\/kubectl\"\n\t\"k8s.io\/kubernetes\/pkg\/kubectl\/cmd\/templates\"\n\tcmdutil \"k8s.io\/kubernetes\/pkg\/kubectl\/cmd\/util\"\n\t\"k8s.io\/kubernetes\/pkg\/kubectl\/cmd\/util\/editor\"\n\t\"k8s.io\/kubernetes\/pkg\/kubectl\/resource\"\n\t\"k8s.io\/kubernetes\/pkg\/util\/i18n\"\n)\n\ntype SetLastAppliedOptions struct {\n\tFilenameOptions  resource.FilenameOptions\n\tSelector         string\n\tInfoList         []*resource.Info\n\tMapper           meta.RESTMapper\n\tTyper            runtime.ObjectTyper\n\tNamespace        string\n\tEnforceNamespace bool\n\tDryRun           bool\n\tShortOutput      bool\n\tCreateAnnotation bool\n\tOutput           string\n\tCodec            runtime.Encoder\n\tPatchBufferList  []PatchBuffer\n\tFactory          cmdutil.Factory\n\tOut              io.Writer\n\tErrOut           io.Writer\n}\n\ntype PatchBuffer struct {\n\tPatch     []byte\n\tPatchType types.PatchType\n}\n\nvar (\n\tapplySetLastAppliedLong = templates.LongDesc(i18n.T(`\n\t\tSet the latest last-applied-configuration annotations by setting it to match the contents of a file.\n\t\tThis results in the last-applied-configuration being updated as though 'kubectl apply -f <file>' was run,\n\t\twithout updating any other parts of the object.`))\n\n\tapplySetLastAppliedExample = templates.Examples(i18n.T(`\n\t\t# Set the last-applied-configuration of a resource to match the contents of a file.\n\t\tkubectl apply set-last-applied -f deploy.yaml\n\n\t\t# Execute set-last-applied against each configuration file in a directory.\n\t\tkubectl apply set-last-applied -f path\/\n\n\t\t# Set the last-applied-configuration of a resource to match the contents of a file, will create the annotation if it does not already exist.\n\t\tkubectl apply set-last-applied -f deploy.yaml --create-annotation=true\n\t\t`))\n)\n\nfunc NewCmdApplySetLastApplied(f cmdutil.Factory, out, err io.Writer) *cobra.Command {\n\toptions := &SetLastAppliedOptions{Out: out, ErrOut: err}\n\tcmd := &cobra.Command{\n\t\tUse:     \"set-last-applied -f FILENAME\",\n\t\tShort:   i18n.T(\"Set the last-applied-configuration annotation on a live object to match the contents of a file.\"),\n\t\tLong:    applySetLastAppliedLong,\n\t\tExample: applySetLastAppliedExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tcmdutil.CheckErr(options.Complete(f, cmd))\n\t\t\tcmdutil.CheckErr(options.Validate(f, cmd))\n\t\t\tcmdutil.CheckErr(options.RunSetLastApplied(f, cmd))\n\t\t},\n\t}\n\n\tcmdutil.AddDryRunFlag(cmd)\n\tcmdutil.AddRecordFlag(cmd)\n\tcmdutil.AddPrinterFlags(cmd)\n\tcmd.Flags().BoolVar(&options.CreateAnnotation, \"create-annotation\", false, \"Will create 'last-applied-configuration' annotations if current objects doesn't have one\")\n\tusage := \"that contains the last-applied-configuration annotations\"\n\tkubectl.AddJsonFilenameFlag(cmd, &options.FilenameOptions.Filenames, \"Filename, directory, or URL to files \"+usage)\n\n\treturn cmd\n}\n\nfunc (o *SetLastAppliedOptions) Complete(f cmdutil.Factory, cmd *cobra.Command) error {\n\to.DryRun = cmdutil.GetFlagBool(cmd, \"dry-run\")\n\to.Output = cmdutil.GetFlagString(cmd, \"output\")\n\to.ShortOutput = o.Output == \"name\"\n\to.Codec = f.JSONEncoder()\n\n\tvar err error\n\to.Mapper, o.Typer, err = f.UnstructuredObject()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\to.Namespace, o.EnforceNamespace, err = f.DefaultNamespace()\n\treturn err\n}\n\nfunc (o *SetLastAppliedOptions) Validate(f cmdutil.Factory, cmd *cobra.Command) error {\n\tbuilder, err := f.NewUnstructuredBuilder(true)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tr := builder.\n\t\tNamespaceParam(o.Namespace).DefaultNamespace().\n\t\tFilenameParam(o.EnforceNamespace, &o.FilenameOptions).\n\t\tLatest().\n\t\tFlatten().\n\t\tDo()\n\terr = r.Err()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = r.Visit(func(info *resource.Info, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tpatchBuf, diffBuf, patchType, err := editor.GetApplyPatch(info.VersionedObject, o.Codec)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Verify the object exists in the cluster before trying to patch it.\n\t\tif err := info.Get(); err != nil {\n\t\t\tif errors.IsNotFound(err) {\n\t\t\t\treturn err\n\t\t\t} else {\n\t\t\t\treturn cmdutil.AddSourceToErr(fmt.Sprintf(\"retrieving current configuration of:\\n%v\\nfrom server for:\", info), info.Source, err)\n\t\t\t}\n\t\t}\n\t\toringalBuf, err := kubectl.GetOriginalConfiguration(info.Mapping, info.Object)\n\t\tif err != nil {\n\t\t\treturn cmdutil.AddSourceToErr(fmt.Sprintf(\"retrieving current configuration of:\\n%v\\nfrom server for:\", info), info.Source, err)\n\t\t}\n\t\tif oringalBuf == nil && !o.CreateAnnotation {\n\t\t\treturn cmdutil.UsageErrorf(cmd, \"no last-applied-configuration annotation found on resource: %s, to create the annotation, run the command with --create-annotation\", info.Name)\n\t\t}\n\n\t\t\/\/only add to PatchBufferList when changed\n\t\tif !bytes.Equal(cmdutil.StripComments(oringalBuf), cmdutil.StripComments(diffBuf)) {\n\t\t\tp := PatchBuffer{Patch: patchBuf, PatchType: patchType}\n\t\t\to.PatchBufferList = append(o.PatchBufferList, p)\n\t\t\to.InfoList = append(o.InfoList, info)\n\t\t} else {\n\t\t\tfmt.Fprintf(o.Out, \"set-last-applied %s: no changes required.\\n\", info.Name)\n\t\t}\n\n\t\treturn nil\n\t})\n\treturn err\n}\n\nfunc (o *SetLastAppliedOptions) RunSetLastApplied(f cmdutil.Factory, cmd *cobra.Command) error {\n\tfor i, patch := range o.PatchBufferList {\n\t\tinfo := o.InfoList[i]\n\t\tif !o.DryRun {\n\t\t\tmapping := info.ResourceMapping()\n\t\t\tclient, err := f.UnstructuredClientForMapping(mapping)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\thelper := resource.NewHelper(client, mapping)\n\t\t\tpatchedObj, err := helper.Patch(o.Namespace, info.Name, patch.PatchType, patch.Patch)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif len(o.Output) > 0 && !o.ShortOutput {\n\t\t\t\tinfo.Refresh(patchedObj, false)\n\t\t\t\treturn cmdutil.PrintResourceInfoForCommand(cmd, info, f, o.Out)\n\t\t\t}\n\t\t\tcmdutil.PrintSuccess(o.Mapper, o.ShortOutput, o.Out, info.Mapping.Resource, info.Name, o.DryRun, \"configured\")\n\n\t\t} else {\n\t\t\terr := o.formatPrinter(o.Output, patch.Patch, o.Out)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcmdutil.PrintSuccess(o.Mapper, o.ShortOutput, o.Out, info.Mapping.Resource, info.Name, o.DryRun, \"configured\")\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (o *SetLastAppliedOptions) formatPrinter(output string, buf []byte, w io.Writer) error {\n\tyamlOutput, err := yaml.JSONToYAML(buf)\n\tif err != nil {\n\t\treturn err\n\t}\n\tswitch output {\n\tcase \"json\":\n\t\tjsonBuffer := &bytes.Buffer{}\n\t\terr = json.Indent(jsonBuffer, buf, \"\", \"  \")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Fprintf(w, \"%s\\n\", jsonBuffer.String())\n\tcase \"yaml\":\n\t\tfmt.Fprintf(w, \"%s\\n\", string(yamlOutput))\n\t}\n\treturn nil\n}\n\nfunc (o *SetLastAppliedOptions) getPatch(info *resource.Info) ([]byte, []byte, error) {\n\tobjMap := map[string]map[string]map[string]string{}\n\tmetadataMap := map[string]map[string]string{}\n\tannotationsMap := map[string]string{}\n\tlocalFile, err := runtime.Encode(o.Codec, info.VersionedObject)\n\tif err != nil {\n\t\treturn nil, localFile, err\n\t}\n\tannotationsMap[api.LastAppliedConfigAnnotation] = string(localFile)\n\tmetadataMap[\"annotations\"] = annotationsMap\n\tobjMap[\"metadata\"] = metadataMap\n\tjsonString, err := apijson.Marshal(objMap)\n\treturn jsonString, localFile, err\n}\n<|endoftext|>"}
{"text":"<commit_before>package client\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\n\t\"github.com\/cybersiddhu\/go-micro-auth\/api\"\n)\n\ntype AuthClient struct {\n\tHost string\n}\n\ntype respErr struct {\n\tMessage string\n}\n\ntype tokenString struct {\n\tToken string\n}\n\nfunc (ac *AuthClient) Login(email string, pass string) (string, error) {\n\tuser := &api.UserJSON{Email: email, Password: pass}\n\turl := ac.Host + \"\/auth\/login\"\n\n\tb, err := json.Marshal(user)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewBuffer(b))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treq.Header.Set(\"content-type\", \"application\/json\")\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif resp.StatusCode == 400 || resp.StatusCode == 401 {\n\t\tvar rerr respErr\n\t\tif err := json.Unmarshal(body, rerr); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn \"\", fmt.Errorf(\"Unable to process request, error:%s\\n\", rerr.Message)\n\t}\n\tvar ts tokenString\n\tif err := json.Unmarshal(body, ts); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn ts.Token, nil\n}\n<commit_msg>Added new client method for signing up<commit_after>package client\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\n\t\"github.com\/cybersiddhu\/go-micro-auth\/api\"\n)\n\ntype AuthClient struct {\n\tHost string\n}\n\ntype respMsg struct {\n\tMessage string\n}\n\ntype tokenString struct {\n\tToken string\n}\n\nfunc (ac *AuthClient) Login(email string, pass string) (string, error) {\n\tuser := &api.UserJSON{Email: email, Password: pass}\n\turl := ac.Host + \"\/auth\/login\"\n\n\tb, err := json.Marshal(user)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error in marshaling user %s\", err)\n\t}\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewBuffer(b))\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error in new request %s\", err)\n\t}\n\treq.Header.Set(\"content-type\", \"application\/json\")\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error in response %s\", err)\n\t}\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error in reading response body %s\", err)\n\t}\n\tif resp.StatusCode == 400 || resp.StatusCode == 401 {\n\t\tvar rerr respMsg\n\t\tif err := json.Unmarshal(body, &rerr); err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"error in unmarshaling HTTP error response\\nerror: %s\\ncode: %d body: %s\", err, resp.StatusCode, string(body))\n\t\t}\n\t\treturn \"\", fmt.Errorf(\"Unable to process request, error:%s\\n\", rerr.Message)\n\t}\n\tvar ts tokenString\n\tif err := json.Unmarshal(body, &ts); err != nil {\n\t\treturn \"\", fmt.Errorf(\"error in unmarshaling token response %s\", err)\n\t}\n\treturn ts.Token, nil\n}\n\nfunc (ac *AuthClient) SignUp(email string, pass string) (string, error) {\n\tuser := &api.UserJSON{Email: email, Password: pass}\n\turl := ac.Host + \"\/auth\/signup\"\n\n\tb, err := json.Marshal(user)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error in marshaling user %s\", err)\n\t}\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewBuffer(b))\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error in new request %s\", err)\n\t}\n\treq.Header.Set(\"content-type\", \"application\/json\")\n\tresp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error in response %s\", err)\n\t}\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"error in reading response body %s\", err)\n\t}\n\n\tvar jsp respMsg\n\tif resp.StatusCode == 400 || resp.StatusCode == 401 {\n\t\tif err := json.Unmarshal(body, &jsp); err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"error in unmarshaling HTTP error response\\nerror: %s\\ncode: %d body: %s\", err, resp.StatusCode, string(body))\n\t\t}\n\t\treturn \"\", fmt.Errorf(\"Unable to process request\\nerror:%s\", jsp.Message)\n\t}\n\tif err := json.Unmarshal(body, &jsp); err != nil {\n\t\treturn \"\", fmt.Errorf(\"error in unmarshaling successful HTTP response\\nbody: %s\\n error: %s\", string(body), err)\n\t}\n\treturn jsp.Message, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package internal\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n)\n\n\/\/ Domain represents domain name.\ntype Domain struct {\n\tID   int    `json:\"id,omitempty\"`\n\tName string `json:\"name,omitempty\"`\n}\n\n\/\/ Record represents DNS record.\ntype Record struct {\n\tID      int    `json:\"id,omitempty\"`\n\tName    string `json:\"name,omitempty\"`\n\tType    string `json:\"type,omitempty\"` \/\/ Record type (SOA, NS, A\/AAAA, CNAME, SRV, MX, TXT, SPF)\n\tTTL     int    `json:\"ttl,omitempty\"`\n\tEmail   string `json:\"email,omitempty\"`   \/\/ Email of domain's admin (only for SOA records)\n\tContent string `json:\"content,omitempty\"` \/\/ Record content (not for SRV)\n}\n\n\/\/ APIError API error message\ntype APIError struct {\n\tDescription string `json:\"error\"`\n\tCode        int    `json:\"code\"`\n\tField       string `json:\"field\"`\n}\n\nfunc (a *APIError) Error() string {\n\treturn fmt.Sprintf(\"API error: %d - %s - %s\", a.Code, a.Description, a.Field)\n}\n\n\/\/ ClientOpts represents options to init client.\ntype ClientOpts struct {\n\tBaseURL    string\n\tToken      string\n\tUserAgent  string\n\tHTTPClient *http.Client\n}\n\n\/\/ Client represents DNS client.\ntype Client struct {\n\tbaseURL    string\n\ttoken      string\n\tuserAgent  string\n\thttpClient *http.Client\n}\n\n\/\/ NewClient returns a client instance.\nfunc NewClient(opts ClientOpts) *Client {\n\tif opts.HTTPClient == nil {\n\t\topts.HTTPClient = &http.Client{}\n\t}\n\n\treturn &Client{\n\t\ttoken:      opts.Token,\n\t\tbaseURL:    opts.BaseURL,\n\t\thttpClient: opts.HTTPClient,\n\t\tuserAgent:  opts.UserAgent,\n\t}\n}\n\n\/\/ GetDomainByName gets Domain object by its name.\nfunc (c *Client) GetDomainByName(domainName string) (*Domain, error) {\n\turi := fmt.Sprintf(\"\/%s\", domainName)\n\treq, err := c.newRequest(http.MethodGet, uri, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdomain := &Domain{}\n\t_, err = c.do(req, domain)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn domain, nil\n}\n\n\/\/ AddRecord adds Record for given domain.\nfunc (c *Client) AddRecord(domainID int, body Record) (*Record, error) {\n\turi := fmt.Sprintf(\"\/%d\/records\/\", domainID)\n\treq, err := c.newRequest(http.MethodPost, uri, body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trecord := &Record{}\n\t_, err = c.do(req, record)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn record, nil\n}\n\n\/\/ ListRecords returns list records for specific domain.\nfunc (c *Client) ListRecords(domainID int) ([]*Record, error) {\n\turi := fmt.Sprintf(\"\/%d\/records\/\", domainID)\n\treq, err := c.newRequest(http.MethodGet, uri, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar records []*Record\n\t_, err = c.do(req, &records)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn records, nil\n}\n\n\/\/ DeleteRecord deletes specific record.\nfunc (c *Client) DeleteRecord(domainID, recordID int) error {\n\turi := fmt.Sprintf(\"\/%d\/records\/%d\", domainID, recordID)\n\treq, err := c.newRequest(http.MethodDelete, uri, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = c.do(req, nil)\n\treturn err\n}\n\nfunc (c *Client) newRequest(method, uri string, body interface{}) (*http.Request, error) {\n\tbuf := new(bytes.Buffer)\n\n\tif body != nil {\n\t\terr := json.NewEncoder(buf).Encode(body)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to encode request body with error: %v\", err)\n\t\t}\n\t}\n\n\treq, err := http.NewRequest(method, c.baseURL+uri, buf)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create new http request with error: %v\", err)\n\t}\n\n\treq.Header.Add(\"X-Token\", c.token)\n\treq.Header.Add(\"Content-Type\", \"application\/json\")\n\treq.Header.Add(\"Accept\", \"application\/json\")\n\n\treturn req, nil\n}\n\nfunc (c *Client) do(req *http.Request, to interface{}) (*http.Response, error) {\n\tresp, err := c.httpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"request failed with error: %v\", err)\n\t}\n\n\terr = checkResponse(resp)\n\tif err != nil {\n\t\treturn resp, err\n\t}\n\n\tif to != nil {\n\t\tif err = unmarshalBody(resp, to); err != nil {\n\t\t\treturn resp, err\n\t\t}\n\t}\n\n\treturn resp, nil\n}\n\nfunc checkResponse(resp *http.Response) error {\n\tif resp.StatusCode >= http.StatusBadRequest &&\n\t\tresp.StatusCode <= http.StatusNetworkAuthenticationRequired {\n\n\t\tif resp.Body == nil {\n\t\t\treturn fmt.Errorf(\"request failed with status code %d and empty body\", resp.StatusCode)\n\t\t}\n\n\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer resp.Body.Close()\n\n\t\tapiError := APIError{}\n\t\terr = json.Unmarshal(body, &apiError)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"request failed with status code %d, response body: %s\", resp.StatusCode, string(body))\n\t\t}\n\n\t\treturn fmt.Errorf(\"request failed with status code %d: %v\", resp.StatusCode, apiError)\n\t}\n\n\treturn nil\n}\n\nfunc unmarshalBody(resp *http.Response, to interface{}) error {\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\terr = json.Unmarshal(body, to)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unmarshaling error: %v: %s\", err, string(body))\n\t}\n\n\treturn nil\n}\n<commit_msg> selectel: getting sub-domain (#803)<commit_after>package internal\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"strings\"\n)\n\n\/\/ Domain represents domain name.\ntype Domain struct {\n\tID   int    `json:\"id,omitempty\"`\n\tName string `json:\"name,omitempty\"`\n}\n\n\/\/ Record represents DNS record.\ntype Record struct {\n\tID      int    `json:\"id,omitempty\"`\n\tName    string `json:\"name,omitempty\"`\n\tType    string `json:\"type,omitempty\"` \/\/ Record type (SOA, NS, A\/AAAA, CNAME, SRV, MX, TXT, SPF)\n\tTTL     int    `json:\"ttl,omitempty\"`\n\tEmail   string `json:\"email,omitempty\"`   \/\/ Email of domain's admin (only for SOA records)\n\tContent string `json:\"content,omitempty\"` \/\/ Record content (not for SRV)\n}\n\n\/\/ APIError API error message\ntype APIError struct {\n\tDescription string `json:\"error\"`\n\tCode        int    `json:\"code\"`\n\tField       string `json:\"field\"`\n}\n\nfunc (a *APIError) Error() string {\n\treturn fmt.Sprintf(\"API error: %d - %s - %s\", a.Code, a.Description, a.Field)\n}\n\n\/\/ ClientOpts represents options to init client.\ntype ClientOpts struct {\n\tBaseURL    string\n\tToken      string\n\tUserAgent  string\n\tHTTPClient *http.Client\n}\n\n\/\/ Client represents DNS client.\ntype Client struct {\n\tbaseURL    string\n\ttoken      string\n\tuserAgent  string\n\thttpClient *http.Client\n}\n\n\/\/ NewClient returns a client instance.\nfunc NewClient(opts ClientOpts) *Client {\n\tif opts.HTTPClient == nil {\n\t\topts.HTTPClient = &http.Client{}\n\t}\n\n\treturn &Client{\n\t\ttoken:      opts.Token,\n\t\tbaseURL:    opts.BaseURL,\n\t\thttpClient: opts.HTTPClient,\n\t\tuserAgent:  opts.UserAgent,\n\t}\n}\n\n\/\/ GetDomainByName gets Domain object by its name. If `domainName` level > 2 and there is\n\/\/ no such domain on the account - it'll recursively search for the first\n\/\/ which is exists in Selectel Domain API.\nfunc (c *Client) GetDomainByName(domainName string) (*Domain, error) {\n\turi := fmt.Sprintf(\"\/%s\", domainName)\n\treq, err := c.newRequest(http.MethodGet, uri, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdomain := &Domain{}\n\tresp, err := c.do(req, domain)\n\tif err != nil {\n\t\tswitch {\n\t\tcase resp.StatusCode == http.StatusNotFound && strings.Count(domainName, \".\") > 1:\n\t\t\t\/\/ Look up for the next sub domain\n\t\t\tsubIndex := strings.Index(domainName, \".\")\n\t\t\treturn c.GetDomainByName(domainName[subIndex+1:])\n\t\tdefault:\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn domain, nil\n}\n\n\/\/ AddRecord adds Record for given domain.\nfunc (c *Client) AddRecord(domainID int, body Record) (*Record, error) {\n\turi := fmt.Sprintf(\"\/%d\/records\/\", domainID)\n\treq, err := c.newRequest(http.MethodPost, uri, body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trecord := &Record{}\n\t_, err = c.do(req, record)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn record, nil\n}\n\n\/\/ ListRecords returns list records for specific domain.\nfunc (c *Client) ListRecords(domainID int) ([]*Record, error) {\n\turi := fmt.Sprintf(\"\/%d\/records\/\", domainID)\n\treq, err := c.newRequest(http.MethodGet, uri, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar records []*Record\n\t_, err = c.do(req, &records)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn records, nil\n}\n\n\/\/ DeleteRecord deletes specific record.\nfunc (c *Client) DeleteRecord(domainID, recordID int) error {\n\turi := fmt.Sprintf(\"\/%d\/records\/%d\", domainID, recordID)\n\treq, err := c.newRequest(http.MethodDelete, uri, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, err = c.do(req, nil)\n\treturn err\n}\n\nfunc (c *Client) newRequest(method, uri string, body interface{}) (*http.Request, error) {\n\tbuf := new(bytes.Buffer)\n\n\tif body != nil {\n\t\terr := json.NewEncoder(buf).Encode(body)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to encode request body with error: %v\", err)\n\t\t}\n\t}\n\n\treq, err := http.NewRequest(method, c.baseURL+uri, buf)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create new http request with error: %v\", err)\n\t}\n\n\treq.Header.Add(\"X-Token\", c.token)\n\treq.Header.Add(\"Content-Type\", \"application\/json\")\n\treq.Header.Add(\"Accept\", \"application\/json\")\n\n\treturn req, nil\n}\n\nfunc (c *Client) do(req *http.Request, to interface{}) (*http.Response, error) {\n\tresp, err := c.httpClient.Do(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"request failed with error: %v\", err)\n\t}\n\n\terr = checkResponse(resp)\n\tif err != nil {\n\t\treturn resp, err\n\t}\n\n\tif to != nil {\n\t\tif err = unmarshalBody(resp, to); err != nil {\n\t\t\treturn resp, err\n\t\t}\n\t}\n\n\treturn resp, nil\n}\n\nfunc checkResponse(resp *http.Response) error {\n\tif resp.StatusCode >= http.StatusBadRequest &&\n\t\tresp.StatusCode <= http.StatusNetworkAuthenticationRequired {\n\n\t\tif resp.Body == nil {\n\t\t\treturn fmt.Errorf(\"request failed with status code %d and empty body\", resp.StatusCode)\n\t\t}\n\n\t\tbody, err := ioutil.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer resp.Body.Close()\n\n\t\tapiError := APIError{}\n\t\terr = json.Unmarshal(body, &apiError)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"request failed with status code %d, response body: %s\", resp.StatusCode, string(body))\n\t\t}\n\n\t\treturn fmt.Errorf(\"request failed with status code %d: %v\", resp.StatusCode, apiError)\n\t}\n\n\treturn nil\n}\n\nfunc unmarshalBody(resp *http.Response, to interface{}) error {\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\terr = json.Unmarshal(body, to)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unmarshaling error: %v: %s\", err, string(body))\n\t}\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright (C) 2016 Space Monkey, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage dbx\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"gopkg.in\/yaml.v2\"\n)\n\nfunc deserial(t string) string {\n\tswitch t {\n\tcase \"serial\":\n\t\treturn \"int\"\n\tcase \"serial64\":\n\t\treturn \"int64\"\n\tdefault:\n\t\treturn t\n\t}\n}\n\nfunc LoadSchema(path string) (schema *Schema, err error) {\n\ttype YRelation struct {\n\t\tOwnedBy  string `yaml:\"owned_by\"`\n\t\tHasA     string `yaml:\"has_a\"`\n\t\tName     string `yaml:\"name\"`\n\t\tNullable bool   `yaml:\"nullable\"`\n\t}\n\n\ttype YColumn struct {\n\t\tName       string `yaml:\"name\"`\n\t\tType       string `yaml:\"type\"`\n\t\tNullable   bool   `yaml:\"nullable\"`\n\t\tUpdatable  bool   `yaml:\"updatable\"`\n\t\tAutoInsert bool   `yaml:\"auto_insert\"`\n\t\tAutoUpdate bool   `yaml:\"auto_update\"`\n\t}\n\n\ttype YTable struct {\n\t\tName       string      `yaml:\"name\"`\n\t\tColumns    []YColumn   `yaml:\"columns\"`\n\t\tRelations  []YRelation `yaml:\"relations\"`\n\t\tUnique     [][]string  `yaml:\"unique\"`\n\t\tPrimaryKey []string    `yaml:\"primary_key\"`\n\t}\n\n\ttype YSchema struct {\n\t\tTables  []YTable `yaml:\"tables\"`\n\t\tQueries [][][]string\n\t}\n\n\tyaml_bytes, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar yschema YSchema\n\terr = yaml.Unmarshal(yaml_bytes, &yschema)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsplitdot := func(s string) (table, column string) {\n\t\trsplit := strings.SplitN(s, \".\", 2)\n\t\tif len(rsplit) < 2 {\n\t\t\treturn rsplit[0], \"\"\n\t\t}\n\t\treturn rsplit[0], rsplit[1]\n\t}\n\n\ttables := map[string]*Table{}\n\t\/\/ create tables and columns\n\tfor _, ytable := range yschema.Tables {\n\t\ttable := &Table{Name: ytable.Name}\n\t\tfor _, ycolumn := range ytable.Columns {\n\t\t\tif table.GetColumn(ycolumn.Name) != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"%s.%s already defined\",\n\t\t\t\t\tytable.Name, ycolumn.Name)\n\t\t\t}\n\t\t\tif ycolumn.AutoUpdate && !ycolumn.Updatable {\n\t\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\t\"%s.%s is marked to auto-update but is not updatable\",\n\t\t\t\t\tytable.Name, ycolumn.Name)\n\t\t\t}\n\t\t\ttable.Columns = append(table.Columns, &Column{\n\t\t\t\tTable:      table,\n\t\t\t\tName:       ycolumn.Name,\n\t\t\t\tType:       ycolumn.Type,\n\t\t\t\tNotNull:    !ycolumn.Nullable,\n\t\t\t\tUpdatable:  ycolumn.Updatable,\n\t\t\t\tAutoInsert: ycolumn.AutoInsert,\n\t\t\t\tAutoUpdate: ycolumn.AutoUpdate,\n\t\t\t})\n\t\t}\n\t\ttables[ytable.Name] = table\n\t}\n\n\t\/\/ resolve relations\n\tfor _, ytable := range yschema.Tables {\n\t\ttable := tables[ytable.Name]\n\t\tfor _, yrelation := range ytable.Relations {\n\t\t\tvar rtable string\n\t\t\tvar rcolumn string\n\t\t\tvar kind RelationKind\n\t\t\tswitch {\n\t\t\tcase yrelation.OwnedBy == \"\" && yrelation.HasA == \"\":\n\t\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\t\"empty relationship specified on %s relation\",\n\t\t\t\t\tytable.Name)\n\t\t\tcase yrelation.OwnedBy != \"\" && yrelation.HasA != \"\":\n\t\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\t\"both has_a and owned_by specified on %s relation\",\n\t\t\t\t\tytable.Name)\n\t\t\tcase yrelation.OwnedBy != \"\":\n\t\t\t\tkind = OwnedBy\n\t\t\t\trtable, rcolumn = splitdot(yrelation.OwnedBy)\n\t\t\tcase yrelation.HasA != \"\":\n\t\t\t\tkind = HasA\n\t\t\t\trtable, rcolumn = splitdot(yrelation.HasA)\n\t\t\t}\n\n\t\t\tname := yrelation.Name\n\t\t\tif name == \"\" {\n\t\t\t\tname = fmt.Sprintf(\"%s_%s\", rtable, rcolumn)\n\t\t\t}\n\n\t\t\tftable := tables[rtable]\n\t\t\tif ftable == nil {\n\t\t\t\treturn nil, fmt.Errorf(\"no table %s in relation %s.%s\",\n\t\t\t\t\trtable, ytable.Name, name)\n\t\t\t}\n\t\t\tfcolumn := ftable.GetColumn(rcolumn)\n\t\t\tif fcolumn == nil {\n\t\t\t\treturn nil, fmt.Errorf(\"no column %s.%s in relation %s.%s\",\n\t\t\t\t\trcolumn, rtable,\n\t\t\t\t\tytable.Name, name)\n\t\t\t}\n\t\t\ttable.Columns = append(table.Columns, &Column{\n\t\t\t\tTable:   table,\n\t\t\t\tName:    name,\n\t\t\t\tType:    deserial(fcolumn.Type),\n\t\t\t\tNotNull: !yrelation.Nullable,\n\t\t\t\tRelation: &Relation{\n\t\t\t\t\tColumn: fcolumn,\n\t\t\t\t\tKind:   kind,\n\t\t\t\t},\n\t\t\t})\n\t\t}\n\t}\n\n\t\/\/ Primary key and unique's\n\tfor _, ytable := range yschema.Tables {\n\t\ttable := tables[ytable.Name]\n\t\ttable.PrimaryKey = table.GetColumns(ytable.PrimaryKey...)\n\t\tif table.PrimaryKey == nil {\n\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\"table %s missing columns in primary key %s\",\n\t\t\t\tytable.Name, ytable.PrimaryKey)\n\t\t}\n\t\tfor _, yunique := range ytable.Unique {\n\t\t\tunique := table.GetColumns(yunique...)\n\t\t\tif unique == nil {\n\t\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\t\"table %s missing columns in unique %s\",\n\t\t\t\t\tytable.Name, yunique)\n\t\t\t}\n\t\t\ttable.Unique = append(table.Unique, unique)\n\t\t}\n\t\ttables[ytable.Name] = table\n\t}\n\n\tresolvedot := func(s string, need_column bool) (*Table, *Column, error) {\n\t\tt, c := splitdot(s)\n\t\tif t == \"\" {\n\t\t\treturn nil, nil, fmt.Errorf(\"invalid dotname syntax %q\", s)\n\t\t}\n\t\ttable := tables[t]\n\t\tif table == nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"no such table %q in dotname %q\", t, s)\n\t\t}\n\t\tif c == \"\" {\n\t\t\tif need_column {\n\t\t\t\treturn nil, nil, fmt.Errorf(\n\t\t\t\t\t\"missing required column in dotname %q\", s)\n\t\t\t}\n\t\t\treturn table, nil, nil\n\t\t}\n\t\tcolumn := table.GetColumn(c)\n\t\tif column == nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"no such column in dotname %q\", c, s)\n\t\t}\n\t\treturn table, column, nil\n\t}\n\n\tschema = &Schema{}\n\n\t\/\/ create queries\n\tfor _, yquery := range yschema.Queries {\n\t\tvar ystarts []string\n\t\tvar yjoins []string\n\t\tvar yends []string\n\n\t\tswitch len(yquery) {\n\t\tcase 0:\n\t\t\tcontinue\n\t\tcase 3:\n\t\t\tyends = yquery[2]\n\t\t\tfallthrough\n\t\tcase 2:\n\t\t\tyjoins = yquery[1]\n\t\t\tfallthrough\n\t\tcase 1:\n\t\t\tystarts = yquery[0]\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"query %q has too many parts\", yquery)\n\t\t}\n\n\t\tquery := &Query{}\n\t\tvar curtable *Table\n\n\t\tfor _, ystart := range ystarts {\n\t\t\ttable, column, err := resolvedot(ystart, false)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\t\"invalid dotname on query %+v: %v\", yquery, err)\n\t\t\t}\n\t\t\tif curtable == nil {\n\t\t\t\tquery.Table = table\n\t\t\t\tcurtable = table\n\t\t\t} else if table != curtable {\n\t\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\t\"expected table %q on %q; got %q\",\n\t\t\t\t\tcurtable.Name, yquery, table.Name)\n\t\t\t}\n\t\t\tif column != nil {\n\t\t\t\tquery.Start = append(query.Start, column)\n\t\t\t}\n\t\t}\n\n\t\tfor _, yjoin := range yjoins {\n\t\t\t_, jcolumn, err := resolvedot(yjoin, true)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\t\"invalid dotname on join %+v: %v\", yquery, err)\n\t\t\t}\n\n\t\t\tif curtable == nil {\n\t\t\t\tquery.Table = jcolumn.Table\n\t\t\t\tcurtable = jcolumn.Table\n\t\t\t}\n\n\t\t\tvar relation *Join\n\t\t\tif jcolumn.Table == curtable {\n\t\t\t\trelation = jcolumn.RelationLeft()\n\t\t\t} else {\n\t\t\t\trelation = jcolumn.RelationRight()\n\t\t\t}\n\t\t\tif relation == nil {\n\t\t\t\treturn nil, fmt.Errorf(\"missing relation on join %s\",\n\t\t\t\t\tyjoin)\n\t\t\t}\n\t\t\tif relation.Left.Table != curtable {\n\t\t\t\treturn nil, fmt.Errorf(\"incomplete table chain on %s\",\n\t\t\t\t\tyquery)\n\t\t\t}\n\t\t\tcurtable = relation.Right.Table\n\t\t\tquery.Joins = append(query.Joins, relation)\n\t\t}\n\n\t\tfor _, yend := range yends {\n\t\t\ttable, column, err := resolvedot(yend, true)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\t\"invalid dotname on query %+v: %v\", yquery, err)\n\t\t\t}\n\t\t\tif curtable != nil && table != curtable {\n\t\t\t\treturn nil, fmt.Errorf(\"incomplete table chain on %s\",\n\t\t\t\t\tyquery)\n\t\t\t}\n\t\t\tquery.End = append(query.End, column)\n\t\t}\n\n\t\tschema.Queries = append(schema.Queries, query)\n\t}\n\n\t\/\/ In order to create tables in dependency order and also to reduce\n\t\/\/ generated code churn between runs, order the tables first by depth and\n\t\/\/ then alphabetically.\n\tfor _, table := range tables {\n\t\tschema.Tables = append(schema.Tables, table)\n\t}\n\tsort.Sort(sortTable(schema.Tables))\n\n\treturn schema, nil\n}\n\ntype sortTable []*Table\n\nfunc (by sortTable) Len() int {\n\treturn len(by)\n}\n\nfunc (by sortTable) Swap(a, b int) {\n\tby[a], by[b] = by[b], by[a]\n}\n\nfunc (by sortTable) Less(a, b int) bool {\n\tadepth := by[a].Depth()\n\tbdepth := by[b].Depth()\n\tif adepth < bdepth {\n\t\treturn true\n\t}\n\tif adepth > bdepth {\n\t\treturn false\n\t}\n\treturn by[a].Name < by[b].Name\n}\n<commit_msg>updatable relations. maybe.<commit_after>\/\/ Copyright (C) 2016 Space Monkey, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage dbx\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"gopkg.in\/yaml.v2\"\n)\n\nfunc deserial(t string) string {\n\tswitch t {\n\tcase \"serial\":\n\t\treturn \"int\"\n\tcase \"serial64\":\n\t\treturn \"int64\"\n\tdefault:\n\t\treturn t\n\t}\n}\n\nfunc LoadSchema(path string) (schema *Schema, err error) {\n\ttype YRelation struct {\n\t\tOwnedBy   string `yaml:\"owned_by\"`\n\t\tHasA      string `yaml:\"has_a\"`\n\t\tName      string `yaml:\"name\"`\n\t\tNullable  bool   `yaml:\"nullable\"`\n\t\tUpdatable bool   `yaml:\"updatable\"`\n\t}\n\n\ttype YColumn struct {\n\t\tName       string `yaml:\"name\"`\n\t\tType       string `yaml:\"type\"`\n\t\tNullable   bool   `yaml:\"nullable\"`\n\t\tUpdatable  bool   `yaml:\"updatable\"`\n\t\tAutoInsert bool   `yaml:\"auto_insert\"`\n\t\tAutoUpdate bool   `yaml:\"auto_update\"`\n\t}\n\n\ttype YTable struct {\n\t\tName       string      `yaml:\"name\"`\n\t\tColumns    []YColumn   `yaml:\"columns\"`\n\t\tRelations  []YRelation `yaml:\"relations\"`\n\t\tUnique     [][]string  `yaml:\"unique\"`\n\t\tPrimaryKey []string    `yaml:\"primary_key\"`\n\t}\n\n\ttype YSchema struct {\n\t\tTables  []YTable `yaml:\"tables\"`\n\t\tQueries [][][]string\n\t}\n\n\tyaml_bytes, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar yschema YSchema\n\terr = yaml.Unmarshal(yaml_bytes, &yschema)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsplitdot := func(s string) (table, column string) {\n\t\trsplit := strings.SplitN(s, \".\", 2)\n\t\tif len(rsplit) < 2 {\n\t\t\treturn rsplit[0], \"\"\n\t\t}\n\t\treturn rsplit[0], rsplit[1]\n\t}\n\n\ttables := map[string]*Table{}\n\t\/\/ create tables and columns\n\tfor _, ytable := range yschema.Tables {\n\t\ttable := &Table{Name: ytable.Name}\n\t\tfor _, ycolumn := range ytable.Columns {\n\t\t\tif table.GetColumn(ycolumn.Name) != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"%s.%s already defined\",\n\t\t\t\t\tytable.Name, ycolumn.Name)\n\t\t\t}\n\t\t\tif ycolumn.AutoUpdate && !ycolumn.Updatable {\n\t\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\t\"%s.%s is marked to auto-update but is not updatable\",\n\t\t\t\t\tytable.Name, ycolumn.Name)\n\t\t\t}\n\t\t\ttable.Columns = append(table.Columns, &Column{\n\t\t\t\tTable:      table,\n\t\t\t\tName:       ycolumn.Name,\n\t\t\t\tType:       ycolumn.Type,\n\t\t\t\tNotNull:    !ycolumn.Nullable,\n\t\t\t\tUpdatable:  ycolumn.Updatable,\n\t\t\t\tAutoInsert: ycolumn.AutoInsert,\n\t\t\t\tAutoUpdate: ycolumn.AutoUpdate,\n\t\t\t})\n\t\t}\n\t\ttables[ytable.Name] = table\n\t}\n\n\t\/\/ resolve relations\n\tfor _, ytable := range yschema.Tables {\n\t\ttable := tables[ytable.Name]\n\t\tfor _, yrelation := range ytable.Relations {\n\t\t\tvar rtable string\n\t\t\tvar rcolumn string\n\t\t\tvar kind RelationKind\n\t\t\tswitch {\n\t\t\tcase yrelation.OwnedBy == \"\" && yrelation.HasA == \"\":\n\t\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\t\"empty relationship specified on %s relation\",\n\t\t\t\t\tytable.Name)\n\t\t\tcase yrelation.OwnedBy != \"\" && yrelation.HasA != \"\":\n\t\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\t\"both has_a and owned_by specified on %s relation\",\n\t\t\t\t\tytable.Name)\n\t\t\tcase yrelation.OwnedBy != \"\":\n\t\t\t\tkind = OwnedBy\n\t\t\t\trtable, rcolumn = splitdot(yrelation.OwnedBy)\n\t\t\tcase yrelation.HasA != \"\":\n\t\t\t\tkind = HasA\n\t\t\t\trtable, rcolumn = splitdot(yrelation.HasA)\n\t\t\t}\n\n\t\t\tname := yrelation.Name\n\t\t\tif name == \"\" {\n\t\t\t\tname = fmt.Sprintf(\"%s_%s\", rtable, rcolumn)\n\t\t\t}\n\n\t\t\tftable := tables[rtable]\n\t\t\tif ftable == nil {\n\t\t\t\treturn nil, fmt.Errorf(\"no table %s in relation %s.%s\",\n\t\t\t\t\trtable, ytable.Name, name)\n\t\t\t}\n\t\t\tfcolumn := ftable.GetColumn(rcolumn)\n\t\t\tif fcolumn == nil {\n\t\t\t\treturn nil, fmt.Errorf(\"no column %s.%s in relation %s.%s\",\n\t\t\t\t\trcolumn, rtable,\n\t\t\t\t\tytable.Name, name)\n\t\t\t}\n\t\t\ttable.Columns = append(table.Columns, &Column{\n\t\t\t\tTable:     table,\n\t\t\t\tName:      name,\n\t\t\t\tType:      deserial(fcolumn.Type),\n\t\t\t\tNotNull:   !yrelation.Nullable,\n\t\t\t\tUpdatable: yrelation.Updatable,\n\t\t\t\tRelation: &Relation{\n\t\t\t\t\tColumn: fcolumn,\n\t\t\t\t\tKind:   kind,\n\t\t\t\t},\n\t\t\t})\n\t\t}\n\t}\n\n\t\/\/ Primary key and unique's\n\tfor _, ytable := range yschema.Tables {\n\t\ttable := tables[ytable.Name]\n\t\ttable.PrimaryKey = table.GetColumns(ytable.PrimaryKey...)\n\t\tif table.PrimaryKey == nil {\n\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\"table %s missing columns in primary key %s\",\n\t\t\t\tytable.Name, ytable.PrimaryKey)\n\t\t}\n\t\tfor _, yunique := range ytable.Unique {\n\t\t\tunique := table.GetColumns(yunique...)\n\t\t\tif unique == nil {\n\t\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\t\"table %s missing columns in unique %s\",\n\t\t\t\t\tytable.Name, yunique)\n\t\t\t}\n\t\t\ttable.Unique = append(table.Unique, unique)\n\t\t}\n\t\ttables[ytable.Name] = table\n\t}\n\n\tresolvedot := func(s string, need_column bool) (*Table, *Column, error) {\n\t\tt, c := splitdot(s)\n\t\tif t == \"\" {\n\t\t\treturn nil, nil, fmt.Errorf(\"invalid dotname syntax %q\", s)\n\t\t}\n\t\ttable := tables[t]\n\t\tif table == nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"no such table %q in dotname %q\", t, s)\n\t\t}\n\t\tif c == \"\" {\n\t\t\tif need_column {\n\t\t\t\treturn nil, nil, fmt.Errorf(\n\t\t\t\t\t\"missing required column in dotname %q\", s)\n\t\t\t}\n\t\t\treturn table, nil, nil\n\t\t}\n\t\tcolumn := table.GetColumn(c)\n\t\tif column == nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"no such column in dotname %q\", c, s)\n\t\t}\n\t\treturn table, column, nil\n\t}\n\n\tschema = &Schema{}\n\n\t\/\/ create queries\n\tfor _, yquery := range yschema.Queries {\n\t\tvar ystarts []string\n\t\tvar yjoins []string\n\t\tvar yends []string\n\n\t\tswitch len(yquery) {\n\t\tcase 0:\n\t\t\tcontinue\n\t\tcase 3:\n\t\t\tyends = yquery[2]\n\t\t\tfallthrough\n\t\tcase 2:\n\t\t\tyjoins = yquery[1]\n\t\t\tfallthrough\n\t\tcase 1:\n\t\t\tystarts = yquery[0]\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"query %q has too many parts\", yquery)\n\t\t}\n\n\t\tquery := &Query{}\n\t\tvar curtable *Table\n\n\t\tfor _, ystart := range ystarts {\n\t\t\ttable, column, err := resolvedot(ystart, false)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\t\"invalid dotname on query %+v: %v\", yquery, err)\n\t\t\t}\n\t\t\tif curtable == nil {\n\t\t\t\tquery.Table = table\n\t\t\t\tcurtable = table\n\t\t\t} else if table != curtable {\n\t\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\t\"expected table %q on %q; got %q\",\n\t\t\t\t\tcurtable.Name, yquery, table.Name)\n\t\t\t}\n\t\t\tif column != nil {\n\t\t\t\tquery.Start = append(query.Start, column)\n\t\t\t}\n\t\t}\n\n\t\tfor _, yjoin := range yjoins {\n\t\t\t_, jcolumn, err := resolvedot(yjoin, true)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\t\"invalid dotname on join %+v: %v\", yquery, err)\n\t\t\t}\n\n\t\t\tif curtable == nil {\n\t\t\t\tquery.Table = jcolumn.Table\n\t\t\t\tcurtable = jcolumn.Table\n\t\t\t}\n\n\t\t\tvar relation *Join\n\t\t\tif jcolumn.Table == curtable {\n\t\t\t\trelation = jcolumn.RelationLeft()\n\t\t\t} else {\n\t\t\t\trelation = jcolumn.RelationRight()\n\t\t\t}\n\t\t\tif relation == nil {\n\t\t\t\treturn nil, fmt.Errorf(\"missing relation on join %s\",\n\t\t\t\t\tyjoin)\n\t\t\t}\n\t\t\tif relation.Left.Table != curtable {\n\t\t\t\treturn nil, fmt.Errorf(\"incomplete table chain on %s\",\n\t\t\t\t\tyquery)\n\t\t\t}\n\t\t\tcurtable = relation.Right.Table\n\t\t\tquery.Joins = append(query.Joins, relation)\n\t\t}\n\n\t\tfor _, yend := range yends {\n\t\t\ttable, column, err := resolvedot(yend, true)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\t\"invalid dotname on query %+v: %v\", yquery, err)\n\t\t\t}\n\t\t\tif curtable != nil && table != curtable {\n\t\t\t\treturn nil, fmt.Errorf(\"incomplete table chain on %s\",\n\t\t\t\t\tyquery)\n\t\t\t}\n\t\t\tquery.End = append(query.End, column)\n\t\t}\n\n\t\tschema.Queries = append(schema.Queries, query)\n\t}\n\n\t\/\/ In order to create tables in dependency order and also to reduce\n\t\/\/ generated code churn between runs, order the tables first by depth and\n\t\/\/ then alphabetically.\n\tfor _, table := range tables {\n\t\tschema.Tables = append(schema.Tables, table)\n\t}\n\tsort.Sort(sortTable(schema.Tables))\n\n\treturn schema, nil\n}\n\ntype sortTable []*Table\n\nfunc (by sortTable) Len() int {\n\treturn len(by)\n}\n\nfunc (by sortTable) Swap(a, b int) {\n\tby[a], by[b] = by[b], by[a]\n}\n\nfunc (by sortTable) Less(a, b int) bool {\n\tadepth := by[a].Depth()\n\tbdepth := by[b].Depth()\n\tif adepth < bdepth {\n\t\treturn true\n\t}\n\tif adepth > bdepth {\n\t\treturn false\n\t}\n\treturn by[a].Name < by[b].Name\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package pkcs7 implements the subset of the CMS PKCS #7 datatype that is typically\n\/\/ used to package certificates and CRLs.  Using openssl, every certificate converted\n\/\/ to PKCS #7 format from another encoding such as PEM conforms to this implementation.\n\/\/ reference: https:\/\/www.openssl.org\/docs\/apps\/crl2pkcs7.html\n\/\/\n\/\/\t\t\tPKCS #7 Data type, reference: https:\/\/tools.ietf.org\/html\/rfc2315\n\/\/\n\/\/ The full pkcs#7 cryptographic message syntax allows for cryptographic enhancements,\n\/\/ for example data can be encrypted and signed and then packaged through pkcs#7 to be\n\/\/ sent over a network and then verified and decrypted.  It is asn1, and the type of\n\/\/ PKCS #7 ContentInfo, which comprises the PKCS #7 structure, is:\n\/\/\n\/\/\t\t\tContentInfo ::= SEQUENCE {\n\/\/\t\t\t\tcontentType ContentType,\n\/\/\t\t\t\tcontent [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL\n\/\/\t\t\t}\n\/\/\n\/\/ There are 6 possible ContentTypes, data, signedData, envelopedData,\n\/\/ signedAndEnvelopedData, digestedData, and encryptedData.  Here signedData, Data, and encrypted\n\/\/ Data are implemented, as the degenerate case of signedData without a signature is the typical\n\/\/ format for transferring certificates and CRLS, and Data and encryptedData are used in PKCS #12\n\/\/ formats.\n\/\/ The ContentType signedData has the form:\n\/\/\n\/\/\n\/\/\t\t\tsignedData ::= SEQUENCE {\n\/\/\t\t\t\tversion Version,\n\/\/\t\t\t\tdigestAlgorithms DigestAlgorithmIdentifiers,\n\/\/\t\t\t\tcontentInfo ContentInfo,\n\/\/\t\t\t\tcertificates [0] IMPLICIT ExtendedCertificatesAndCertificates OPTIONAL\n\/\/\t\t\t\tcrls [1] IMPLICIT CertificateRevocationLists OPTIONAL,\n\/\/\t\t\t\tsignerInfos SignerInfos\n\/\/\t\t\t}\n\/\/\n\/\/ As of yet signerInfos and digestAlgorithms are not parsed, as they are not relevant to\n\/\/ this system's use of PKCS #7 data.  Version is an integer type, note that PKCS #7 is\n\/\/ recursive, this second layer of ContentInfo is similar ignored for our degenerate\n\/\/ usage.  The ExtendedCertificatesAndCertificates type consists of a sequence of choices\n\/\/ between PKCS #6 extended certificates andx509 certificates.  Any sequence consisting\n\/\/ of any number of  extended certificates is not yet supported in this implementation\n\/\/\n\/\/ The ContentType Data is simpy a raw octet string and is parsed directly into a Go []byte\n\/\/\n\/\/ The ContentType encryptedData is the most complicated and its form can be gathered by\n\/\/ the go type below.  It essentially contains a raw octet string of encrypted data and an\n\/\/ algorithm identifier for use in decrypting this data\npackage pkcs7\n\nimport (\n\t\"crypto\/x509\"\n\t\"crypto\/x509\/pkix\"\n\t\"encoding\/asn1\"\n\t\"errors\"\n\n\tcferr \"github.com\/cloudflare\/cfssl\/errors\"\n)\n\n\/\/ Types used for asn1 Unmarshaling\n\ntype signedData struct {\n\tVersion          int\n\tDigestAlgorithms asn1.RawValue\n\tContentInfo      asn1.RawValue\n\tCertificates     asn1.RawValue `asn1:\"optional\" asn1:\"tag:0\"`\n\tCrls             asn1.RawValue `asn1:\"optional\"`\n\tSignerInfos      asn1.RawValue\n}\n\ntype initPKCS7 struct {\n\tRaw         asn1.RawContent\n\tContentType asn1.ObjectIdentifier\n\tContent     asn1.RawValue `asn1:\"tag:0,explicit,optional\"`\n}\n\n\/\/ Object identifiers strings of the three implemented PKCS7 types\nconst (\n\tObjIDData          = \"1.2.840.113549.1.7.1\"\n\tObjIDSignedData    = \"1.2.840.113549.1.7.2\"\n\tObjIDEncryptedData = \"1.2.840.113549.1.7.6\"\n)\n\n\/\/ PKCS7 represents the ASN1 PKCS #7 Content type.  It contains one of three\n\/\/ possible types of Content objects, as denoted by the object identifier in\n\/\/ the ContentInfo field, the other two being nil.  SignedData\n\/\/ is the degenerate SignedData Content info without signature used\n\/\/ to hold certificates and crls.  Data is raw bytes, and EncryptedData\n\/\/ is as defined in PKCS #7 standard\ntype PKCS7 struct {\n\tRaw         asn1.RawContent\n\tContentInfo string\n\tContent     Content\n}\n\n\/\/ Content implements three of the six possible PKCS7 data types.  Only one is non-nil\ntype Content struct {\n\tData          []byte\n\tSignedData    SignedData\n\tEncryptedData EncryptedData\n}\n\n\/\/ SignedData defines the typical carrier of certificates and crls\ntype SignedData struct {\n\tRaw          asn1.RawContent\n\tVersion      int\n\tCertificates []*x509.Certificate\n\tCrl          *pkix.CertificateList\n}\n\n\/\/ Data contains raw bytes.  Used as a subtype in PKCS12\ntype Data struct {\n\tBytes []byte\n}\n\n\/\/ EncryptedData contains encrypted data.  Used as a subtype in PKCS12\ntype EncryptedData struct {\n\tRaw                  asn1.RawContent\n\tVersion              int\n\tEncryptedContentInfo EncryptedContentInfo\n}\n\n\/\/ EncryptedContentInfo is a subtype of PKCS7EncryptedData\ntype EncryptedContentInfo struct {\n\tRaw                        asn1.RawContent\n\tContentType                asn1.ObjectIdentifier\n\tContentEncryptionAlgorithm pkix.AlgorithmIdentifier\n\tEncryptedContent           []byte `asn1:\"tag:0,optional\"`\n}\n\n\/\/ ParsePKCS7 attempts to parse the DER encoded bytes of a\n\/\/ PKCS7 structure\nfunc ParsePKCS7(raw []byte) (msg *PKCS7, err error) {\n\n\tvar pkcs7 initPKCS7\n\t_, err = asn1.Unmarshal(raw, &pkcs7)\n\tif err != nil {\n\t\treturn nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err)\n\t}\n\n\tmsg = new(PKCS7)\n\tmsg.Raw = pkcs7.Raw\n\tmsg.ContentInfo = pkcs7.ContentType.String()\n\tswitch {\n\tcase msg.ContentInfo == ObjIDData:\n\t\tmsg.ContentInfo = \"Data\"\n\t\t_, err = asn1.Unmarshal(pkcs7.Content.Bytes, &msg.Content.Data)\n\t\tif err != nil {\n\t\t\treturn nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err)\n\t\t}\n\tcase msg.ContentInfo == ObjIDSignedData:\n\t\tmsg.ContentInfo = \"SignedData\"\n\t\tvar signedData signedData\n\t\t_, err = asn1.Unmarshal(pkcs7.Content.Bytes, &signedData)\n\t\tif err != nil {\n\t\t\treturn nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err)\n\t\t}\n\t\tif len(signedData.Certificates.Bytes) != 0 {\n\t\t\tmsg.Content.SignedData.Certificates, err = x509.ParseCertificates(signedData.Certificates.Bytes)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err)\n\t\t\t}\n\t\t}\n\t\tif len(signedData.Crls.Bytes) != 0 {\n\t\t\tmsg.Content.SignedData.Crl, err = x509.ParseDERCRL(signedData.Crls.Bytes)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err)\n\t\t\t}\n\t\t}\n\t\tmsg.Content.SignedData.Version = signedData.Version\n\t\tmsg.Content.SignedData.Raw = pkcs7.Content.Bytes\n\tcase msg.ContentInfo == ObjIDEncryptedData:\n\t\tmsg.ContentInfo = \"EncryptedData\"\n\t\tvar encryptedData EncryptedData\n\t\t_, err = asn1.Unmarshal(pkcs7.Content.Bytes, &encryptedData)\n\t\tif err != nil {\n\t\t\treturn nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err)\n\t\t}\n\t\tif encryptedData.Version != 0 {\n\t\t\treturn nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, errors.New(\"Only support for PKCS #7 encryptedData version 0\"))\n\t\t}\n\t\tmsg.Content.EncryptedData = encryptedData\n\n\tdefault:\n\t\treturn nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, errors.New(\"Attempt to parse PKCS# 7 Content not of type data, signed data or encrypted data\"))\n\t}\n\n\treturn msg, nil\n\n}\n<commit_msg>pkcs7: a missing space and a typo<commit_after>\/\/ Package pkcs7 implements the subset of the CMS PKCS #7 datatype that is typically\n\/\/ used to package certificates and CRLs.  Using openssl, every certificate converted\n\/\/ to PKCS #7 format from another encoding such as PEM conforms to this implementation.\n\/\/ reference: https:\/\/www.openssl.org\/docs\/apps\/crl2pkcs7.html\n\/\/\n\/\/\t\t\tPKCS #7 Data type, reference: https:\/\/tools.ietf.org\/html\/rfc2315\n\/\/\n\/\/ The full pkcs#7 cryptographic message syntax allows for cryptographic enhancements,\n\/\/ for example data can be encrypted and signed and then packaged through pkcs#7 to be\n\/\/ sent over a network and then verified and decrypted.  It is asn1, and the type of\n\/\/ PKCS #7 ContentInfo, which comprises the PKCS #7 structure, is:\n\/\/\n\/\/\t\t\tContentInfo ::= SEQUENCE {\n\/\/\t\t\t\tcontentType ContentType,\n\/\/\t\t\t\tcontent [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL\n\/\/\t\t\t}\n\/\/\n\/\/ There are 6 possible ContentTypes, data, signedData, envelopedData,\n\/\/ signedAndEnvelopedData, digestedData, and encryptedData.  Here signedData, Data, and encrypted\n\/\/ Data are implemented, as the degenerate case of signedData without a signature is the typical\n\/\/ format for transferring certificates and CRLS, and Data and encryptedData are used in PKCS #12\n\/\/ formats.\n\/\/ The ContentType signedData has the form:\n\/\/\n\/\/\n\/\/\t\t\tsignedData ::= SEQUENCE {\n\/\/\t\t\t\tversion Version,\n\/\/\t\t\t\tdigestAlgorithms DigestAlgorithmIdentifiers,\n\/\/\t\t\t\tcontentInfo ContentInfo,\n\/\/\t\t\t\tcertificates [0] IMPLICIT ExtendedCertificatesAndCertificates OPTIONAL\n\/\/\t\t\t\tcrls [1] IMPLICIT CertificateRevocationLists OPTIONAL,\n\/\/\t\t\t\tsignerInfos SignerInfos\n\/\/\t\t\t}\n\/\/\n\/\/ As of yet signerInfos and digestAlgorithms are not parsed, as they are not relevant to\n\/\/ this system's use of PKCS #7 data.  Version is an integer type, note that PKCS #7 is\n\/\/ recursive, this second layer of ContentInfo is similar ignored for our degenerate\n\/\/ usage.  The ExtendedCertificatesAndCertificates type consists of a sequence of choices\n\/\/ between PKCS #6 extended certificates and x509 certificates.  Any sequence consisting\n\/\/ of any number of extended certificates is not yet supported in this implementation.\n\/\/\n\/\/ The ContentType Data is simply a raw octet string and is parsed directly into a Go []byte slice.\n\/\/\n\/\/ The ContentType encryptedData is the most complicated and its form can be gathered by\n\/\/ the go type below.  It essentially contains a raw octet string of encrypted data and an\n\/\/ algorithm identifier for use in decrypting this data.\npackage pkcs7\n\nimport (\n\t\"crypto\/x509\"\n\t\"crypto\/x509\/pkix\"\n\t\"encoding\/asn1\"\n\t\"errors\"\n\n\tcferr \"github.com\/cloudflare\/cfssl\/errors\"\n)\n\n\/\/ Types used for asn1 Unmarshaling.\n\ntype signedData struct {\n\tVersion          int\n\tDigestAlgorithms asn1.RawValue\n\tContentInfo      asn1.RawValue\n\tCertificates     asn1.RawValue `asn1:\"optional\" asn1:\"tag:0\"`\n\tCrls             asn1.RawValue `asn1:\"optional\"`\n\tSignerInfos      asn1.RawValue\n}\n\ntype initPKCS7 struct {\n\tRaw         asn1.RawContent\n\tContentType asn1.ObjectIdentifier\n\tContent     asn1.RawValue `asn1:\"tag:0,explicit,optional\"`\n}\n\n\/\/ Object identifier strings of the three implemented PKCS7 types.\nconst (\n\tObjIDData          = \"1.2.840.113549.1.7.1\"\n\tObjIDSignedData    = \"1.2.840.113549.1.7.2\"\n\tObjIDEncryptedData = \"1.2.840.113549.1.7.6\"\n)\n\n\/\/ PKCS7 represents the ASN1 PKCS #7 Content type.  It contains one of three\n\/\/ possible types of Content objects, as denoted by the object identifier in\n\/\/ the ContentInfo field, the other two being nil.  SignedData\n\/\/ is the degenerate SignedData Content info without signature used\n\/\/ to hold certificates and crls.  Data is raw bytes, and EncryptedData\n\/\/ is as defined in PKCS #7 standard.\ntype PKCS7 struct {\n\tRaw         asn1.RawContent\n\tContentInfo string\n\tContent     Content\n}\n\n\/\/ Content implements three of the six possible PKCS7 data types.  Only one is non-nil.\ntype Content struct {\n\tData          []byte\n\tSignedData    SignedData\n\tEncryptedData EncryptedData\n}\n\n\/\/ SignedData defines the typical carrier of certificates and crls.\ntype SignedData struct {\n\tRaw          asn1.RawContent\n\tVersion      int\n\tCertificates []*x509.Certificate\n\tCrl          *pkix.CertificateList\n}\n\n\/\/ Data contains raw bytes.  Used as a subtype in PKCS12.\ntype Data struct {\n\tBytes []byte\n}\n\n\/\/ EncryptedData contains encrypted data.  Used as a subtype in PKCS12.\ntype EncryptedData struct {\n\tRaw                  asn1.RawContent\n\tVersion              int\n\tEncryptedContentInfo EncryptedContentInfo\n}\n\n\/\/ EncryptedContentInfo is a subtype of PKCS7EncryptedData.\ntype EncryptedContentInfo struct {\n\tRaw                        asn1.RawContent\n\tContentType                asn1.ObjectIdentifier\n\tContentEncryptionAlgorithm pkix.AlgorithmIdentifier\n\tEncryptedContent           []byte `asn1:\"tag:0,optional\"`\n}\n\n\/\/ ParsePKCS7 attempts to parse the DER encoded bytes of a\n\/\/ PKCS7 structure.\nfunc ParsePKCS7(raw []byte) (msg *PKCS7, err error) {\n\n\tvar pkcs7 initPKCS7\n\t_, err = asn1.Unmarshal(raw, &pkcs7)\n\tif err != nil {\n\t\treturn nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err)\n\t}\n\n\tmsg = new(PKCS7)\n\tmsg.Raw = pkcs7.Raw\n\tmsg.ContentInfo = pkcs7.ContentType.String()\n\tswitch {\n\tcase msg.ContentInfo == ObjIDData:\n\t\tmsg.ContentInfo = \"Data\"\n\t\t_, err = asn1.Unmarshal(pkcs7.Content.Bytes, &msg.Content.Data)\n\t\tif err != nil {\n\t\t\treturn nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err)\n\t\t}\n\tcase msg.ContentInfo == ObjIDSignedData:\n\t\tmsg.ContentInfo = \"SignedData\"\n\t\tvar signedData signedData\n\t\t_, err = asn1.Unmarshal(pkcs7.Content.Bytes, &signedData)\n\t\tif err != nil {\n\t\t\treturn nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err)\n\t\t}\n\t\tif len(signedData.Certificates.Bytes) != 0 {\n\t\t\tmsg.Content.SignedData.Certificates, err = x509.ParseCertificates(signedData.Certificates.Bytes)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err)\n\t\t\t}\n\t\t}\n\t\tif len(signedData.Crls.Bytes) != 0 {\n\t\t\tmsg.Content.SignedData.Crl, err = x509.ParseDERCRL(signedData.Crls.Bytes)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err)\n\t\t\t}\n\t\t}\n\t\tmsg.Content.SignedData.Version = signedData.Version\n\t\tmsg.Content.SignedData.Raw = pkcs7.Content.Bytes\n\tcase msg.ContentInfo == ObjIDEncryptedData:\n\t\tmsg.ContentInfo = \"EncryptedData\"\n\t\tvar encryptedData EncryptedData\n\t\t_, err = asn1.Unmarshal(pkcs7.Content.Bytes, &encryptedData)\n\t\tif err != nil {\n\t\t\treturn nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, err)\n\t\t}\n\t\tif encryptedData.Version != 0 {\n\t\t\treturn nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, errors.New(\"Only support for PKCS #7 encryptedData version 0\"))\n\t\t}\n\t\tmsg.Content.EncryptedData = encryptedData\n\n\tdefault:\n\t\treturn nil, cferr.Wrap(cferr.CertificateError, cferr.ParseFailed, errors.New(\"Attempt to parse PKCS# 7 Content not of type data, signed data or encrypted data\"))\n\t}\n\n\treturn msg, nil\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ archive is package that helps create archives in a format that\n\/\/ Atlas expects with its various upload endpoints.\npackage archive\n\nimport (\n\t\"archive\/tar\"\n\t\"bufio\"\n\t\"compress\/gzip\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n)\n\n\/\/\ntype Archive struct {\n\tio.ReadCloser\n\n\tSize     int64\n\tMetadata map[string]string\n}\n\n\/\/ ArchiveOpts are the options for defining how the archive will be built.\ntype ArchiveOpts struct {\n\t\/\/ Exclude and Include are filters of files to include\/exclude in\n\t\/\/ the archive when creating it from a directory. These filters should\n\t\/\/ be relative to the packaging directory and should be basic glob\n\t\/\/ patterns.\n\tExclude []string\n\tInclude []string\n\n\t\/\/ Extra is a mapping of extra files to include within the archive. The\n\t\/\/ key should be the path within the archive and the value should be\n\t\/\/ an absolute path to the file to put into the archive. These extra\n\t\/\/ files will override any other files in the archive.\n\tExtra map[string]string\n\n\t\/\/ VCS, if true, will detect and use a VCS system to determine what\n\t\/\/ files to include the archive.\n\tVCS bool\n}\n\n\/\/ IsSet says whether any options were set.\nfunc (o *ArchiveOpts) IsSet() bool {\n\treturn len(o.Exclude) > 0 || len(o.Include) > 0 || o.VCS\n}\n\n\/\/ CreateArchive takes the given path and ArchiveOpts and archives it.\n\/\/\n\/\/ The archive will be fully completed and put into a temporary file.\n\/\/ This must be done to retrieve the content length of the archive which\n\/\/ is needed for almost all operations involving archives with Atlas. Because\n\/\/ of this, sufficient disk space will be required to buffer the archive.\nfunc CreateArchive(path string, opts *ArchiveOpts) (*Archive, error) {\n\tlog.Printf(\"[INFO] creating archive from %s\", path)\n\n\tfi, err := os.Stat(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Direct file paths cannot have archive options\n\tif !fi.IsDir() && opts.IsSet() {\n\t\treturn nil, fmt.Errorf(\n\t\t\t\"options such as exclude, include, and VCS can't be set when \" +\n\t\t\t\t\"the path is a file.\")\n\t}\n\n\tif fi.IsDir() {\n\t\treturn archiveDir(path, opts)\n\t} else {\n\t\treturn archiveFile(path, opts)\n\t}\n}\n\nfunc archiveFile(path string, opts *ArchiveOpts) (*Archive, error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif _, err := gzip.NewReader(f); err == nil {\n\t\t\/\/ Reset the read offset for future reading\n\t\tif _, err := f.Seek(0, 0); err != nil {\n\t\t\tf.Close()\n\t\t\treturn nil, err\n\t\t}\n\n\t\t\/\/ Get the file info for the size\n\t\tfi, err := f.Stat()\n\t\tif err != nil {\n\t\t\tf.Close()\n\t\t\treturn nil, err\n\t\t}\n\n\t\t\/\/ This is a gzip file, let it through.\n\t\treturn &Archive{ReadCloser: f, Size: fi.Size()}, nil\n\t}\n\n\t\/\/ Close the file, no use for it anymore\n\tf.Close()\n\n\t\/\/ We have a single file that is not gzipped. Compress it.\n\tpath, err = filepath.Abs(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Act like we're compressing a directory, but only include this one\n\t\/\/ file.\n\treturn archiveDir(filepath.Dir(path), &ArchiveOpts{\n\t\tInclude: []string{filepath.Base(path)},\n\t})\n}\n\nfunc archiveDir(root string, opts *ArchiveOpts) (*Archive, error) {\n\tvar vcsInclude []string\n\tvar metadata map[string]string\n\tif opts.VCS {\n\t\tvar err error\n\n\t\tif err = vcsPreflight(root); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvcsInclude, err = vcsFiles(root)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tmetadata, err = vcsMetadata(root)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t\/\/ Create the temporary file that we'll send the archive data to.\n\tarchiveF, err := ioutil.TempFile(\"\", \"atlas-archive\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Create the wrapper for the result which will automatically\n\t\/\/ remove the temporary file on close.\n\tarchiveWrapper := &readCloseRemover{F: archiveF}\n\n\t\/\/ Buffer the writer so that we can push as much data to disk at\n\t\/\/ a time as possible. 4M should be good.\n\tbufW := bufio.NewWriterSize(archiveF, 4096*1024)\n\n\t\/\/ Gzip compress all the output data\n\tgzipW := gzip.NewWriter(bufW)\n\n\t\/\/ Tar the file contents\n\ttarW := tar.NewWriter(gzipW)\n\n\t\/\/ Build the function that'll do all the compression\n\twalkFn := func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Get the relative path from the path since it contains the root\n\t\t\/\/ plus the path.\n\t\tsubpath, err := filepath.Rel(root, path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif subpath == \".\" {\n\t\t\treturn nil\n\t\t}\n\n\t\t\/\/ If we have a list of VCS files, check that first\n\t\tskip := false\n\t\tif len(vcsInclude) > 0 {\n\t\t\tskip = true\n\t\t\tfor _, f := range vcsInclude {\n\t\t\t\tif f == subpath {\n\t\t\t\t\tskip = false\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tif info.IsDir() && strings.HasPrefix(f, subpath+\"\/\") {\n\t\t\t\t\tskip = false\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ If include is present, we only include what is listed\n\t\tif len(opts.Include) > 0 {\n\t\t\tskip = true\n\t\t\tfor _, include := range opts.Include {\n\t\t\t\tmatch, err := filepath.Match(include, subpath)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif match {\n\t\t\t\t\tskip = false\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ If exclude, it is one last gate to excluding files\n\t\tfor _, exclude := range opts.Exclude {\n\t\t\tmatch, err := filepath.Match(exclude, subpath)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif match {\n\t\t\t\tskip = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\t\/\/ If we have to skip this file, then skip it, properly skipping\n\t\t\/\/ children if we're a directory.\n\t\tif skip {\n\t\t\tif info.IsDir() {\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}\n\n\t\t\/\/ Read the symlink target. We don't track the error because\n\t\t\/\/ it doesn't matter if there is an error.\n\t\ttarget, _ := os.Readlink(path)\n\n\t\t\/\/ Build the file header for the tar entry\n\t\theader, err := tar.FileInfoHeader(info, target)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"failed creating archive header: %s\", path)\n\t\t}\n\n\t\t\/\/ Modify the header to properly be the full subpath\n\t\theader.Name = subpath\n\t\tif info.IsDir() {\n\t\t\theader.Name += \"\/\"\n\t\t}\n\n\t\t\/\/ Write the header first to the archive.\n\t\tif err := tarW.WriteHeader(header); err != nil {\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"failed writing archive header: %s\", path)\n\t\t}\n\n\t\t\/\/ If it is a directory, then we're done (no body to write)\n\t\tif info.IsDir() {\n\t\t\treturn nil\n\t\t}\n\n\t\t\/\/ Open the target file to write the data\n\t\tf, err := os.Open(path)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"failed opening file '%s' to write compressed archive.\", path)\n\t\t}\n\t\tdefer f.Close()\n\n\t\tif _, err = io.Copy(tarW, f); err != nil {\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"failed copying file to archive: %s\", path)\n\t\t}\n\n\t\treturn nil\n\t}\n\n\t\/\/ First, walk the path and do the normal files\n\twerr := filepath.Walk(root, walkFn)\n\tif werr == nil {\n\t\t\/\/ If that succeeded, handle the extra files\n\t\twerr = copyExtras(tarW, opts.Extra)\n\t}\n\n\t\/\/ Attempt to close all the things. If we get an error on the way\n\t\/\/ and we haven't had an error yet, then record that as the critical\n\t\/\/ error. But we still try to close everything.\n\n\t\/\/ Close the tar writer\n\tif err := tarW.Close(); err != nil && werr == nil {\n\t\twerr = err\n\t}\n\n\t\/\/ Close the gzip writer\n\tif err := gzipW.Close(); err != nil && werr == nil {\n\t\twerr = err\n\t}\n\n\t\/\/ Flush the buffer\n\tif err := bufW.Flush(); err != nil && werr == nil {\n\t\twerr = err\n\t}\n\n\t\/\/ If we had an error, then close the file (removing it) and\n\t\/\/ return the error.\n\tif werr != nil {\n\t\tarchiveWrapper.Close()\n\t\treturn nil, werr\n\t}\n\n\t\/\/ Seek to the beginning\n\tif _, err := archiveWrapper.F.Seek(0, 0); err != nil {\n\t\tarchiveWrapper.Close()\n\t\treturn nil, err\n\t}\n\n\t\/\/ Get the file information so we can get the size\n\tfi, err := archiveWrapper.F.Stat()\n\tif err != nil {\n\t\tarchiveWrapper.Close()\n\t\treturn nil, err\n\t}\n\n\treturn &Archive{\n\t\tReadCloser: archiveWrapper,\n\t\tSize:       fi.Size(),\n\t\tMetadata:   metadata,\n\t}, nil\n}\n\nfunc copyExtras(w *tar.Writer, extra map[string]string) error {\n\tfor entry, path := range extra {\n\t\tinfo, err := os.Stat(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Read the symlink target. We don't track the error because\n\t\t\/\/ it doesn't matter if there is an error.\n\t\ttarget, _ := os.Readlink(path)\n\n\t\t\/\/ Build the file header for the tar entry\n\t\theader, err := tar.FileInfoHeader(info, target)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"failed creating archive header: %s\", path)\n\t\t}\n\n\t\t\/\/ Modify the header to properly be the full subpath\n\t\theader.Name = entry\n\n\t\t\/\/ Write the header first to the archive.\n\t\tif err := w.WriteHeader(header); err != nil {\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"failed writing archive header: %s\", path)\n\t\t}\n\n\t\t\/\/ If it is a directory, then we're done (no body to write)\n\t\tif info.IsDir() {\n\t\t\treturn nil\n\t\t}\n\n\t\t\/\/ Open the target file to write the data\n\t\tf, err := os.Open(path)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"failed opening file '%s' to write compressed archive.\", path)\n\t\t}\n\n\t\t_, err = io.Copy(w, f)\n\t\tf.Close()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"failed copying file to archive: %s\", path)\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ readCloseRemover is an io.ReadCloser implementation that will remove\n\/\/ the file on Close(). We use this to clean up our temporary file for\n\/\/ the archive.\ntype readCloseRemover struct {\n\tF *os.File\n}\n\nfunc (r *readCloseRemover) Read(p []byte) (int, error) {\n\treturn r.F.Read(p)\n}\n\nfunc (r *readCloseRemover) Close() error {\n\t\/\/ First close the file\n\terr := r.F.Close()\n\n\t\/\/ Next make sure to remove it, or at least try, regardless of error\n\t\/\/ above.\n\tos.Remove(r.F.Name())\n\n\treturn err\n}\n<commit_msg>archive: comments<commit_after>\/\/ archive is package that helps create archives in a format that\n\/\/ Atlas expects with its various upload endpoints.\npackage archive\n\nimport (\n\t\"archive\/tar\"\n\t\"bufio\"\n\t\"compress\/gzip\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n)\n\n\/\/ Archive is the resulting archive. The archive data is generally streamed\n\/\/ so the io.ReadCloser can be used to backpressure the archive progress\n\/\/ and avoid memory pressure.\ntype Archive struct {\n\tio.ReadCloser\n\n\tSize     int64\n\tMetadata map[string]string\n}\n\n\/\/ ArchiveOpts are the options for defining how the archive will be built.\ntype ArchiveOpts struct {\n\t\/\/ Exclude and Include are filters of files to include\/exclude in\n\t\/\/ the archive when creating it from a directory. These filters should\n\t\/\/ be relative to the packaging directory and should be basic glob\n\t\/\/ patterns.\n\tExclude []string\n\tInclude []string\n\n\t\/\/ Extra is a mapping of extra files to include within the archive. The\n\t\/\/ key should be the path within the archive and the value should be\n\t\/\/ an absolute path to the file to put into the archive. These extra\n\t\/\/ files will override any other files in the archive.\n\tExtra map[string]string\n\n\t\/\/ VCS, if true, will detect and use a VCS system to determine what\n\t\/\/ files to include the archive.\n\tVCS bool\n}\n\n\/\/ IsSet says whether any options were set.\nfunc (o *ArchiveOpts) IsSet() bool {\n\treturn len(o.Exclude) > 0 || len(o.Include) > 0 || o.VCS\n}\n\n\/\/ CreateArchive takes the given path and ArchiveOpts and archives it.\n\/\/\n\/\/ The archive will be fully completed and put into a temporary file.\n\/\/ This must be done to retrieve the content length of the archive which\n\/\/ is needed for almost all operations involving archives with Atlas. Because\n\/\/ of this, sufficient disk space will be required to buffer the archive.\nfunc CreateArchive(path string, opts *ArchiveOpts) (*Archive, error) {\n\tlog.Printf(\"[INFO] creating archive from %s\", path)\n\n\tfi, err := os.Stat(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Direct file paths cannot have archive options\n\tif !fi.IsDir() && opts.IsSet() {\n\t\treturn nil, fmt.Errorf(\n\t\t\t\"options such as exclude, include, and VCS can't be set when \" +\n\t\t\t\t\"the path is a file.\")\n\t}\n\n\tif fi.IsDir() {\n\t\treturn archiveDir(path, opts)\n\t} else {\n\t\treturn archiveFile(path, opts)\n\t}\n}\n\nfunc archiveFile(path string, opts *ArchiveOpts) (*Archive, error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif _, err := gzip.NewReader(f); err == nil {\n\t\t\/\/ Reset the read offset for future reading\n\t\tif _, err := f.Seek(0, 0); err != nil {\n\t\t\tf.Close()\n\t\t\treturn nil, err\n\t\t}\n\n\t\t\/\/ Get the file info for the size\n\t\tfi, err := f.Stat()\n\t\tif err != nil {\n\t\t\tf.Close()\n\t\t\treturn nil, err\n\t\t}\n\n\t\t\/\/ This is a gzip file, let it through.\n\t\treturn &Archive{ReadCloser: f, Size: fi.Size()}, nil\n\t}\n\n\t\/\/ Close the file, no use for it anymore\n\tf.Close()\n\n\t\/\/ We have a single file that is not gzipped. Compress it.\n\tpath, err = filepath.Abs(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Act like we're compressing a directory, but only include this one\n\t\/\/ file.\n\treturn archiveDir(filepath.Dir(path), &ArchiveOpts{\n\t\tInclude: []string{filepath.Base(path)},\n\t})\n}\n\nfunc archiveDir(root string, opts *ArchiveOpts) (*Archive, error) {\n\tvar vcsInclude []string\n\tvar metadata map[string]string\n\tif opts.VCS {\n\t\tvar err error\n\n\t\tif err = vcsPreflight(root); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvcsInclude, err = vcsFiles(root)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tmetadata, err = vcsMetadata(root)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t\/\/ Create the temporary file that we'll send the archive data to.\n\tarchiveF, err := ioutil.TempFile(\"\", \"atlas-archive\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Create the wrapper for the result which will automatically\n\t\/\/ remove the temporary file on close.\n\tarchiveWrapper := &readCloseRemover{F: archiveF}\n\n\t\/\/ Buffer the writer so that we can push as much data to disk at\n\t\/\/ a time as possible. 4M should be good.\n\tbufW := bufio.NewWriterSize(archiveF, 4096*1024)\n\n\t\/\/ Gzip compress all the output data\n\tgzipW := gzip.NewWriter(bufW)\n\n\t\/\/ Tar the file contents\n\ttarW := tar.NewWriter(gzipW)\n\n\t\/\/ Build the function that'll do all the compression\n\twalkFn := func(path string, info os.FileInfo, err error) error {\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Get the relative path from the path since it contains the root\n\t\t\/\/ plus the path.\n\t\tsubpath, err := filepath.Rel(root, path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif subpath == \".\" {\n\t\t\treturn nil\n\t\t}\n\n\t\t\/\/ If we have a list of VCS files, check that first\n\t\tskip := false\n\t\tif len(vcsInclude) > 0 {\n\t\t\tskip = true\n\t\t\tfor _, f := range vcsInclude {\n\t\t\t\tif f == subpath {\n\t\t\t\t\tskip = false\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tif info.IsDir() && strings.HasPrefix(f, subpath+\"\/\") {\n\t\t\t\t\tskip = false\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ If include is present, we only include what is listed\n\t\tif len(opts.Include) > 0 {\n\t\t\tskip = true\n\t\t\tfor _, include := range opts.Include {\n\t\t\t\tmatch, err := filepath.Match(include, subpath)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif match {\n\t\t\t\t\tskip = false\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ If exclude, it is one last gate to excluding files\n\t\tfor _, exclude := range opts.Exclude {\n\t\t\tmatch, err := filepath.Match(exclude, subpath)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif match {\n\t\t\t\tskip = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\t\/\/ If we have to skip this file, then skip it, properly skipping\n\t\t\/\/ children if we're a directory.\n\t\tif skip {\n\t\t\tif info.IsDir() {\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}\n\n\t\t\/\/ Read the symlink target. We don't track the error because\n\t\t\/\/ it doesn't matter if there is an error.\n\t\ttarget, _ := os.Readlink(path)\n\n\t\t\/\/ Build the file header for the tar entry\n\t\theader, err := tar.FileInfoHeader(info, target)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"failed creating archive header: %s\", path)\n\t\t}\n\n\t\t\/\/ Modify the header to properly be the full subpath\n\t\theader.Name = subpath\n\t\tif info.IsDir() {\n\t\t\theader.Name += \"\/\"\n\t\t}\n\n\t\t\/\/ Write the header first to the archive.\n\t\tif err := tarW.WriteHeader(header); err != nil {\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"failed writing archive header: %s\", path)\n\t\t}\n\n\t\t\/\/ If it is a directory, then we're done (no body to write)\n\t\tif info.IsDir() {\n\t\t\treturn nil\n\t\t}\n\n\t\t\/\/ Open the target file to write the data\n\t\tf, err := os.Open(path)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"failed opening file '%s' to write compressed archive.\", path)\n\t\t}\n\t\tdefer f.Close()\n\n\t\tif _, err = io.Copy(tarW, f); err != nil {\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"failed copying file to archive: %s\", path)\n\t\t}\n\n\t\treturn nil\n\t}\n\n\t\/\/ First, walk the path and do the normal files\n\twerr := filepath.Walk(root, walkFn)\n\tif werr == nil {\n\t\t\/\/ If that succeeded, handle the extra files\n\t\twerr = copyExtras(tarW, opts.Extra)\n\t}\n\n\t\/\/ Attempt to close all the things. If we get an error on the way\n\t\/\/ and we haven't had an error yet, then record that as the critical\n\t\/\/ error. But we still try to close everything.\n\n\t\/\/ Close the tar writer\n\tif err := tarW.Close(); err != nil && werr == nil {\n\t\twerr = err\n\t}\n\n\t\/\/ Close the gzip writer\n\tif err := gzipW.Close(); err != nil && werr == nil {\n\t\twerr = err\n\t}\n\n\t\/\/ Flush the buffer\n\tif err := bufW.Flush(); err != nil && werr == nil {\n\t\twerr = err\n\t}\n\n\t\/\/ If we had an error, then close the file (removing it) and\n\t\/\/ return the error.\n\tif werr != nil {\n\t\tarchiveWrapper.Close()\n\t\treturn nil, werr\n\t}\n\n\t\/\/ Seek to the beginning\n\tif _, err := archiveWrapper.F.Seek(0, 0); err != nil {\n\t\tarchiveWrapper.Close()\n\t\treturn nil, err\n\t}\n\n\t\/\/ Get the file information so we can get the size\n\tfi, err := archiveWrapper.F.Stat()\n\tif err != nil {\n\t\tarchiveWrapper.Close()\n\t\treturn nil, err\n\t}\n\n\treturn &Archive{\n\t\tReadCloser: archiveWrapper,\n\t\tSize:       fi.Size(),\n\t\tMetadata:   metadata,\n\t}, nil\n}\n\nfunc copyExtras(w *tar.Writer, extra map[string]string) error {\n\tfor entry, path := range extra {\n\t\tinfo, err := os.Stat(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Read the symlink target. We don't track the error because\n\t\t\/\/ it doesn't matter if there is an error.\n\t\ttarget, _ := os.Readlink(path)\n\n\t\t\/\/ Build the file header for the tar entry\n\t\theader, err := tar.FileInfoHeader(info, target)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"failed creating archive header: %s\", path)\n\t\t}\n\n\t\t\/\/ Modify the header to properly be the full subpath\n\t\theader.Name = entry\n\n\t\t\/\/ Write the header first to the archive.\n\t\tif err := w.WriteHeader(header); err != nil {\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"failed writing archive header: %s\", path)\n\t\t}\n\n\t\t\/\/ If it is a directory, then we're done (no body to write)\n\t\tif info.IsDir() {\n\t\t\treturn nil\n\t\t}\n\n\t\t\/\/ Open the target file to write the data\n\t\tf, err := os.Open(path)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"failed opening file '%s' to write compressed archive.\", path)\n\t\t}\n\n\t\t_, err = io.Copy(w, f)\n\t\tf.Close()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"failed copying file to archive: %s\", path)\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ readCloseRemover is an io.ReadCloser implementation that will remove\n\/\/ the file on Close(). We use this to clean up our temporary file for\n\/\/ the archive.\ntype readCloseRemover struct {\n\tF *os.File\n}\n\nfunc (r *readCloseRemover) Read(p []byte) (int, error) {\n\treturn r.F.Read(p)\n}\n\nfunc (r *readCloseRemover) Close() error {\n\t\/\/ First close the file\n\terr := r.F.Close()\n\n\t\/\/ Next make sure to remove it, or at least try, regardless of error\n\t\/\/ above.\n\tos.Remove(r.F.Name())\n\n\treturn err\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"crypto\/md5\"\n\t\"database\/sql\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"sync\"\n\n\t\"github.com\/cheggaaa\/pb\"\n\t_ \"github.com\/mattn\/go-sqlite3\"\n)\n\nconst (\n\tthumbsDir      = \"public\/thumbs\"\n\tbigThumbSize   = \"1000\"\n\tsmallThumbSize = \"200\"\n\tworkers        = 4 \/\/ min: 1\n)\n\nfunc generateSmallThumb(photoPath, identifier string) (thumbPath string, err error) {\n\tthumbPath = path.Join(thumbsDir, fmt.Sprintf(\"%s_small.jpg\", identifier))\n\n\tabsThumbPath, err := filepath.Abs(thumbPath)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif _, err = os.Stat(thumbPath); os.IsNotExist(err) { \/\/ file does not exist\n\t\terr = exec.Command(\n\t\t\t\"vipsthumbnail\", photoPath,\n\t\t\t\"--rotate\",\n\t\t\t\"--size\", smallThumbSize,\n\t\t\t\"--crop\",\n\t\t\t\"--interpolator\", \"bicubic\",\n\t\t\t\"--output\", absThumbPath+\"[Q=97,no_subsample,strip]\").Run()\n\t}\n\n\treturn\n}\n\nfunc generateBigThumb(photoPath, identifier string) (thumbPath string, err error) {\n\tthumbPath = path.Join(thumbsDir, fmt.Sprintf(\"%s_big.jpg\", identifier))\n\n\tabsThumbPath, err := filepath.Abs(thumbPath)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif _, err = os.Stat(thumbPath); os.IsNotExist(err) { \/\/ file does not exist\n\t\terr = exec.Command(\n\t\t\t\"vipsthumbnail\", photoPath,\n\t\t\t\"--rotate\",\n\t\t\t\"--size\", bigThumbSize,\n\t\t\t\"--interpolator\", \"bicubic\",\n\t\t\t\"--output\", absThumbPath+\"[Q=97,no_subsample,strip]\").Run()\n\t}\n\n\treturn\n}\n\nfunc generateThumbsImpl(photoPath string) (err error) {\n\tidentifier := fmt.Sprintf(\"%x\", md5.Sum([]byte(photoPath)))\n\n\tbigThumbPath, err := generateBigThumb(photoPath, identifier)\n\tif err == nil { \/\/ success\n\t\t_, err = generateSmallThumb(bigThumbPath, identifier)\n\t}\n\n\treturn\n}\n\nfunc generateThumbs(ch chan string, wg *sync.WaitGroup, bar *pb.ProgressBar) {\n\tdefer wg.Done()\n\n\tfor photoPath := range ch {\n\t\tgenerateThumbsImpl(photoPath)\n\t\tbar.Increment()\n\t}\n}\n\nfunc main() {\n\tvar photosCount int\n\n\tif workers < 1 {\n\t\tlog.Fatal(\"number of workers must be at least 1\")\n\t}\n\n\tdb, err := sql.Open(\"sqlite3\", \"thyme.db\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer db.Close()\n\n\trows, err := db.Query(`\n\tSELECT path FROM photos\n\tJOIN sets ON photos.set_id = sets.id\n\tORDER BY sets.taken_at DESC, photos.taken_at ASC\n\t`)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer rows.Close()\n\n\terr = db.QueryRow(\"SELECT COUNT(*) FROM photos\").Scan(&photosCount)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif err := os.MkdirAll(thumbsDir, os.ModeDir|0755); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tch := make(chan string)\n\twg := sync.WaitGroup{}\n\tbar := pb.StartNew(photosCount)\n\n\tfor i := 0; i < workers; i++ {\n\t\twg.Add(1)\n\t\tgo generateThumbs(ch, &wg, bar)\n\t}\n\n\tfor rows.Next() {\n\t\tvar photoPath string\n\t\trows.Scan(&photoPath)\n\t\tch <- photoPath\n\t}\n\n\tclose(ch)\n\twg.Wait()\n\n\tif err := rows.Err(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n<commit_msg>Generate small thumb from original if big thumb failed<commit_after>package main\n\nimport (\n\t\"crypto\/md5\"\n\t\"database\/sql\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\"\n\t\"path\/filepath\"\n\t\"sync\"\n\n\t\"github.com\/cheggaaa\/pb\"\n\t_ \"github.com\/mattn\/go-sqlite3\"\n)\n\nconst (\n\tthumbsDir      = \"public\/thumbs\"\n\tbigThumbSize   = \"1000\"\n\tsmallThumbSize = \"200\"\n\tworkers        = 4 \/\/ min: 1\n)\n\nfunc generateSmallThumb(photoPath, identifier string) (thumbPath string, err error) {\n\tthumbPath = path.Join(thumbsDir, fmt.Sprintf(\"%s_small.jpg\", identifier))\n\n\tabsThumbPath, err := filepath.Abs(thumbPath)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif _, err = os.Stat(thumbPath); os.IsNotExist(err) { \/\/ file does not exist\n\t\terr = exec.Command(\n\t\t\t\"vipsthumbnail\", photoPath,\n\t\t\t\"--rotate\",\n\t\t\t\"--size\", smallThumbSize,\n\t\t\t\"--crop\",\n\t\t\t\"--interpolator\", \"bicubic\",\n\t\t\t\"--output\", absThumbPath+\"[Q=97,no_subsample,strip]\").Run()\n\t}\n\n\treturn\n}\n\nfunc generateBigThumb(photoPath, identifier string) (thumbPath string, err error) {\n\tthumbPath = path.Join(thumbsDir, fmt.Sprintf(\"%s_big.jpg\", identifier))\n\n\tabsThumbPath, err := filepath.Abs(thumbPath)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif _, err = os.Stat(thumbPath); os.IsNotExist(err) { \/\/ file does not exist\n\t\terr = exec.Command(\n\t\t\t\"vipsthumbnail\", photoPath,\n\t\t\t\"--rotate\",\n\t\t\t\"--size\", bigThumbSize,\n\t\t\t\"--interpolator\", \"bicubic\",\n\t\t\t\"--output\", absThumbPath+\"[Q=97,no_subsample,strip]\").Run()\n\t}\n\n\treturn\n}\n\nfunc generateThumbsImpl(photoPath string) (err error) {\n\tidentifier := fmt.Sprintf(\"%x\", md5.Sum([]byte(photoPath)))\n\n\tbigThumbPath, err := generateBigThumb(photoPath, identifier)\n\tif err == nil { \/\/ success\n\t\t_, err = generateSmallThumb(bigThumbPath, identifier)\n\t} else { \/\/ create from original photo since big thumb failed\n\t\t_, err = generateSmallThumb(photoPath, identifier)\n\t}\n\n\treturn\n}\n\nfunc generateThumbs(ch chan string, wg *sync.WaitGroup, bar *pb.ProgressBar) {\n\tdefer wg.Done()\n\n\tfor photoPath := range ch {\n\t\tgenerateThumbsImpl(photoPath)\n\t\tbar.Increment()\n\t}\n}\n\nfunc main() {\n\tvar photosCount int\n\n\tif workers < 1 {\n\t\tlog.Fatal(\"number of workers must be at least 1\")\n\t}\n\n\tdb, err := sql.Open(\"sqlite3\", \"thyme.db\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer db.Close()\n\n\trows, err := db.Query(`\n\tSELECT path FROM photos\n\tJOIN sets ON photos.set_id = sets.id\n\tORDER BY sets.taken_at DESC, photos.taken_at ASC\n\t`)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer rows.Close()\n\n\terr = db.QueryRow(\"SELECT COUNT(*) FROM photos\").Scan(&photosCount)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif err := os.MkdirAll(thumbsDir, os.ModeDir|0755); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tch := make(chan string)\n\twg := sync.WaitGroup{}\n\tbar := pb.StartNew(photosCount)\n\n\tfor i := 0; i < workers; i++ {\n\t\twg.Add(1)\n\t\tgo generateThumbs(ch, &wg, bar)\n\t}\n\n\tfor rows.Next() {\n\t\tvar photoPath string\n\t\trows.Scan(&photoPath)\n\t\tch <- photoPath\n\t}\n\n\tclose(ch)\n\twg.Wait()\n\n\tif err := rows.Err(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2016 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage openstack\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"path\"\n\t\"strings\"\n\n\t\"k8s.io\/kubernetes\/pkg\/volume\"\n\n\t\"github.com\/rackspace\/gophercloud\"\n\t\"github.com\/rackspace\/gophercloud\/openstack\"\n\t\"github.com\/rackspace\/gophercloud\/openstack\/blockstorage\/v1\/volumes\"\n\t\"github.com\/rackspace\/gophercloud\/openstack\/compute\/v2\/extensions\/volumeattach\"\n\t\"github.com\/rackspace\/gophercloud\/pagination\"\n\n\t\"github.com\/golang\/glog\"\n)\n\n\/\/ Attaches given cinder volume to the compute running kubelet\nfunc (os *OpenStack) AttachDisk(instanceID string, diskName string) (string, error) {\n\tdisk, err := os.getVolume(diskName)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tcClient, err := openstack.NewComputeV2(os.provider, gophercloud.EndpointOpts{\n\t\tRegion: os.region,\n\t})\n\tif err != nil || cClient == nil {\n\t\tglog.Errorf(\"Unable to initialize nova client for region: %s\", os.region)\n\t\treturn \"\", err\n\t}\n\n\tif len(disk.Attachments) > 0 && disk.Attachments[0][\"server_id\"] != nil {\n\t\tif instanceID == disk.Attachments[0][\"server_id\"] {\n\t\t\tglog.V(4).Infof(\"Disk: %q is already attached to compute: %q\", diskName, instanceID)\n\t\t\treturn disk.ID, nil\n\t\t} else {\n\t\t\terrMsg := fmt.Sprintf(\"Disk %q is attached to a different compute: %q, should be detached before proceeding\", diskName, disk.Attachments[0][\"server_id\"])\n\t\t\tglog.Errorf(errMsg)\n\t\t\treturn \"\", errors.New(errMsg)\n\t\t}\n\t}\n\t\/\/ add read only flag here if possible spothanis\n\t_, err = volumeattach.Create(cClient, instanceID, &volumeattach.CreateOpts{\n\t\tVolumeID: disk.ID,\n\t}).Extract()\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to attach %s volume to %s compute\", diskName, instanceID)\n\t\treturn \"\", err\n\t}\n\tglog.V(2).Infof(\"Successfully attached %s volume to %s compute\", diskName, instanceID)\n\treturn disk.ID, nil\n}\n\n\/\/ Detaches given cinder volume from the compute running kubelet\nfunc (os *OpenStack) DetachDisk(instanceID string, partialDiskId string) error {\n\tdisk, err := os.getVolume(partialDiskId)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcClient, err := openstack.NewComputeV2(os.provider, gophercloud.EndpointOpts{\n\t\tRegion: os.region,\n\t})\n\tif err != nil || cClient == nil {\n\t\tglog.Errorf(\"Unable to initialize nova client for region: %s\", os.region)\n\t\treturn err\n\t}\n\tif len(disk.Attachments) > 0 && disk.Attachments[0][\"server_id\"] != nil && instanceID == disk.Attachments[0][\"server_id\"] {\n\t\t\/\/ This is a blocking call and effects kubelet's performance directly.\n\t\t\/\/ We should consider kicking it out into a separate routine, if it is bad.\n\t\terr = volumeattach.Delete(cClient, instanceID, disk.ID).ExtractErr()\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"Failed to delete volume %s from compute %s attached %v\", disk.ID, instanceID, err)\n\t\t\treturn err\n\t\t}\n\t\tglog.V(2).Infof(\"Successfully detached volume: %s from compute: %s\", disk.ID, instanceID)\n\t} else {\n\t\terrMsg := fmt.Sprintf(\"Disk: %s has no attachments or is not attached to compute: %s\", disk.Name, instanceID)\n\t\tglog.Errorf(errMsg)\n\t\treturn errors.New(errMsg)\n\t}\n\treturn nil\n}\n\n\/\/ Takes a partial\/full disk id or diskname\nfunc (os *OpenStack) getVolume(diskName string) (volumes.Volume, error) {\n\tsClient, err := openstack.NewBlockStorageV1(os.provider, gophercloud.EndpointOpts{\n\t\tRegion: os.region,\n\t})\n\n\tvar volume volumes.Volume\n\tif err != nil || sClient == nil {\n\t\tglog.Errorf(\"Unable to initialize cinder client for region: %s\", os.region)\n\t\treturn volume, err\n\t}\n\n\terr = volumes.List(sClient, nil).EachPage(func(page pagination.Page) (bool, error) {\n\t\tvols, err := volumes.ExtractVolumes(page)\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"Failed to extract volumes: %v\", err)\n\t\t\treturn false, err\n\t\t} else {\n\t\t\tfor _, v := range vols {\n\t\t\t\tglog.V(4).Infof(\"%s %s %v\", v.ID, v.Name, v.Attachments)\n\t\t\t\tif v.Name == diskName || strings.Contains(v.ID, diskName) {\n\t\t\t\t\tvolume = v\n\t\t\t\t\treturn true, nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\/\/ if it reached here then no disk with the given name was found.\n\t\terrmsg := fmt.Sprintf(\"Unable to find disk: %s in region %s\", diskName, os.region)\n\t\treturn false, errors.New(errmsg)\n\t})\n\tif err != nil {\n\t\tglog.Errorf(\"Error occurred getting volume: %s\", diskName)\n\t\treturn volume, err\n\t}\n\treturn volume, err\n}\n\n\/\/ Create a volume of given size (in GiB)\nfunc (os *OpenStack) CreateVolume(name string, size int, vtype, availability string, tags *map[string]string) (volumeName string, err error) {\n\n\tsClient, err := openstack.NewBlockStorageV1(os.provider, gophercloud.EndpointOpts{\n\t\tRegion: os.region,\n\t})\n\n\tif err != nil || sClient == nil {\n\t\tglog.Errorf(\"Unable to initialize cinder client for region: %s\", os.region)\n\t\treturn \"\", err\n\t}\n\n\topts := volumes.CreateOpts{\n\t\tName:         name,\n\t\tSize:         size,\n\t\tVolumeType:   vtype,\n\t\tAvailability: availability,\n\t}\n\tif tags != nil {\n\t\topts.Metadata = *tags\n\t}\n\tvol, err := volumes.Create(sClient, opts).Extract()\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to create a %d GB volume: %v\", size, err)\n\t\treturn \"\", err\n\t}\n\tglog.Infof(\"Created volume %v\", vol.ID)\n\treturn vol.ID, err\n}\n\n\/\/ GetDevicePath returns the path of an attached block storage volume, specified by its id.\nfunc (os *OpenStack) GetDevicePath(diskId string) string {\n\tfiles, _ := ioutil.ReadDir(\"\/dev\/disk\/by-id\/\")\n\tfor _, f := range files {\n\t\tif strings.Contains(f.Name(), \"virtio-\") {\n\t\t\tdevid_prefix := f.Name()[len(\"virtio-\"):len(f.Name())]\n\t\t\tif strings.Contains(diskId, devid_prefix) {\n\t\t\t\tglog.V(4).Infof(\"Found disk attached as %q; full devicepath: %s\\n\", f.Name(), path.Join(\"\/dev\/disk\/by-id\/\", f.Name()))\n\t\t\t\treturn path.Join(\"\/dev\/disk\/by-id\/\", f.Name())\n\t\t\t}\n\t\t}\n\t}\n\tglog.Warningf(\"Failed to find device for the diskid: %q\\n\", diskId)\n\treturn \"\"\n}\n\nfunc (os *OpenStack) DeleteVolume(volumeName string) error {\n\tused, err := os.diskIsUsed(volumeName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif used {\n\t\tmsg := fmt.Sprintf(\"Cannot delete the volume %q, it's still attached to a node\", volumeName)\n\t\treturn volume.NewDeletedVolumeInUseError(msg)\n\t}\n\n\tsClient, err := openstack.NewBlockStorageV1(os.provider, gophercloud.EndpointOpts{\n\t\tRegion: os.region,\n\t})\n\n\tif err != nil || sClient == nil {\n\t\tglog.Errorf(\"Unable to initialize cinder client for region: %s\", os.region)\n\t\treturn err\n\t}\n\terr = volumes.Delete(sClient, volumeName).ExtractErr()\n\tif err != nil {\n\t\tglog.Errorf(\"Cannot delete volume %s: %v\", volumeName, err)\n\t}\n\treturn err\n}\n\n\/\/ Get device path of attached volume to the compute running kubelet\nfunc (os *OpenStack) GetAttachmentDiskPath(instanceID string, diskName string) (string, error) {\n\tdisk, err := os.getVolume(diskName)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif len(disk.Attachments) > 0 && disk.Attachments[0][\"server_id\"] != nil {\n\t\tif instanceID == disk.Attachments[0][\"server_id\"] {\n\t\t\t\/\/ Attachment[0][\"device\"] points to the device path\n\t\t\t\/\/ see http:\/\/developer.openstack.org\/api-ref-blockstorage-v1.html\n\t\t\treturn disk.Attachments[0][\"device\"].(string), nil\n\t\t} else {\n\t\t\terrMsg := fmt.Sprintf(\"Disk %q is attached to a different compute: %q, should be detached before proceeding\", diskName, disk.Attachments[0][\"server_id\"])\n\t\t\tglog.Errorf(errMsg)\n\t\t\treturn \"\", errors.New(errMsg)\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"volume %s is not attached to %s\", diskName, instanceID)\n}\n\n\/\/ query if a volume is attached to a compute instance\nfunc (os *OpenStack) DiskIsAttached(diskName, instanceID string) (bool, error) {\n\tdisk, err := os.getVolume(diskName)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif len(disk.Attachments) > 0 && disk.Attachments[0][\"server_id\"] != nil && instanceID == disk.Attachments[0][\"server_id\"] {\n\t\treturn true, nil\n\t}\n\treturn false, nil\n}\n\n\/\/ diskIsUsed returns true a disk is attached to any node.\nfunc (os *OpenStack) diskIsUsed(diskName string) (bool, error) {\n\tdisk, err := os.getVolume(diskName)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif len(disk.Attachments) > 0 {\n\t\treturn true, nil\n\t}\n\treturn false, nil\n}\n<commit_msg>Add sync state loop in master's volume reconciler<commit_after>\/*\nCopyright 2016 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage openstack\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"path\"\n\t\"strings\"\n\n\t\"k8s.io\/kubernetes\/pkg\/volume\"\n\n\t\"github.com\/rackspace\/gophercloud\"\n\t\"github.com\/rackspace\/gophercloud\/openstack\"\n\t\"github.com\/rackspace\/gophercloud\/openstack\/blockstorage\/v1\/volumes\"\n\t\"github.com\/rackspace\/gophercloud\/openstack\/compute\/v2\/extensions\/volumeattach\"\n\t\"github.com\/rackspace\/gophercloud\/pagination\"\n\n\t\"github.com\/golang\/glog\"\n)\n\n\/\/ Attaches given cinder volume to the compute running kubelet\nfunc (os *OpenStack) AttachDisk(instanceID string, diskName string) (string, error) {\n\tdisk, err := os.getVolume(diskName)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tcClient, err := openstack.NewComputeV2(os.provider, gophercloud.EndpointOpts{\n\t\tRegion: os.region,\n\t})\n\tif err != nil || cClient == nil {\n\t\tglog.Errorf(\"Unable to initialize nova client for region: %s\", os.region)\n\t\treturn \"\", err\n\t}\n\n\tif len(disk.Attachments) > 0 && disk.Attachments[0][\"server_id\"] != nil {\n\t\tif instanceID == disk.Attachments[0][\"server_id\"] {\n\t\t\tglog.V(4).Infof(\"Disk: %q is already attached to compute: %q\", diskName, instanceID)\n\t\t\treturn disk.ID, nil\n\t\t} else {\n\t\t\terrMsg := fmt.Sprintf(\"Disk %q is attached to a different compute: %q, should be detached before proceeding\", diskName, disk.Attachments[0][\"server_id\"])\n\t\t\tglog.Errorf(errMsg)\n\t\t\treturn \"\", errors.New(errMsg)\n\t\t}\n\t}\n\t\/\/ add read only flag here if possible spothanis\n\t_, err = volumeattach.Create(cClient, instanceID, &volumeattach.CreateOpts{\n\t\tVolumeID: disk.ID,\n\t}).Extract()\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to attach %s volume to %s compute\", diskName, instanceID)\n\t\treturn \"\", err\n\t}\n\tglog.V(2).Infof(\"Successfully attached %s volume to %s compute\", diskName, instanceID)\n\treturn disk.ID, nil\n}\n\n\/\/ Detaches given cinder volume from the compute running kubelet\nfunc (os *OpenStack) DetachDisk(instanceID string, partialDiskId string) error {\n\tdisk, err := os.getVolume(partialDiskId)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcClient, err := openstack.NewComputeV2(os.provider, gophercloud.EndpointOpts{\n\t\tRegion: os.region,\n\t})\n\tif err != nil || cClient == nil {\n\t\tglog.Errorf(\"Unable to initialize nova client for region: %s\", os.region)\n\t\treturn err\n\t}\n\tif len(disk.Attachments) > 0 && disk.Attachments[0][\"server_id\"] != nil && instanceID == disk.Attachments[0][\"server_id\"] {\n\t\t\/\/ This is a blocking call and effects kubelet's performance directly.\n\t\t\/\/ We should consider kicking it out into a separate routine, if it is bad.\n\t\terr = volumeattach.Delete(cClient, instanceID, disk.ID).ExtractErr()\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"Failed to delete volume %s from compute %s attached %v\", disk.ID, instanceID, err)\n\t\t\treturn err\n\t\t}\n\t\tglog.V(2).Infof(\"Successfully detached volume: %s from compute: %s\", disk.ID, instanceID)\n\t} else {\n\t\terrMsg := fmt.Sprintf(\"Disk: %s has no attachments or is not attached to compute: %s\", disk.Name, instanceID)\n\t\tglog.Errorf(errMsg)\n\t\treturn errors.New(errMsg)\n\t}\n\treturn nil\n}\n\n\/\/ Takes a partial\/full disk id or diskname\nfunc (os *OpenStack) getVolume(diskName string) (volumes.Volume, error) {\n\tsClient, err := openstack.NewBlockStorageV1(os.provider, gophercloud.EndpointOpts{\n\t\tRegion: os.region,\n\t})\n\n\tvar volume volumes.Volume\n\tif err != nil || sClient == nil {\n\t\tglog.Errorf(\"Unable to initialize cinder client for region: %s\", os.region)\n\t\treturn volume, err\n\t}\n\n\terr = volumes.List(sClient, nil).EachPage(func(page pagination.Page) (bool, error) {\n\t\tvols, err := volumes.ExtractVolumes(page)\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"Failed to extract volumes: %v\", err)\n\t\t\treturn false, err\n\t\t} else {\n\t\t\tfor _, v := range vols {\n\t\t\t\tglog.V(4).Infof(\"%s %s %v\", v.ID, v.Name, v.Attachments)\n\t\t\t\tif v.Name == diskName || strings.Contains(v.ID, diskName) {\n\t\t\t\t\tvolume = v\n\t\t\t\t\treturn true, nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\/\/ if it reached here then no disk with the given name was found.\n\t\terrmsg := fmt.Sprintf(\"Unable to find disk: %s in region %s\", diskName, os.region)\n\t\treturn false, errors.New(errmsg)\n\t})\n\tif err != nil {\n\t\tglog.Errorf(\"Error occurred getting volume: %s\", diskName)\n\t\treturn volume, err\n\t}\n\treturn volume, err\n}\n\n\/\/ Create a volume of given size (in GiB)\nfunc (os *OpenStack) CreateVolume(name string, size int, vtype, availability string, tags *map[string]string) (volumeName string, err error) {\n\n\tsClient, err := openstack.NewBlockStorageV1(os.provider, gophercloud.EndpointOpts{\n\t\tRegion: os.region,\n\t})\n\n\tif err != nil || sClient == nil {\n\t\tglog.Errorf(\"Unable to initialize cinder client for region: %s\", os.region)\n\t\treturn \"\", err\n\t}\n\n\topts := volumes.CreateOpts{\n\t\tName:         name,\n\t\tSize:         size,\n\t\tVolumeType:   vtype,\n\t\tAvailability: availability,\n\t}\n\tif tags != nil {\n\t\topts.Metadata = *tags\n\t}\n\tvol, err := volumes.Create(sClient, opts).Extract()\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to create a %d GB volume: %v\", size, err)\n\t\treturn \"\", err\n\t}\n\tglog.Infof(\"Created volume %v\", vol.ID)\n\treturn vol.ID, err\n}\n\n\/\/ GetDevicePath returns the path of an attached block storage volume, specified by its id.\nfunc (os *OpenStack) GetDevicePath(diskId string) string {\n\tfiles, _ := ioutil.ReadDir(\"\/dev\/disk\/by-id\/\")\n\tfor _, f := range files {\n\t\tif strings.Contains(f.Name(), \"virtio-\") {\n\t\t\tdevid_prefix := f.Name()[len(\"virtio-\"):len(f.Name())]\n\t\t\tif strings.Contains(diskId, devid_prefix) {\n\t\t\t\tglog.V(4).Infof(\"Found disk attached as %q; full devicepath: %s\\n\", f.Name(), path.Join(\"\/dev\/disk\/by-id\/\", f.Name()))\n\t\t\t\treturn path.Join(\"\/dev\/disk\/by-id\/\", f.Name())\n\t\t\t}\n\t\t}\n\t}\n\tglog.Warningf(\"Failed to find device for the diskid: %q\\n\", diskId)\n\treturn \"\"\n}\n\nfunc (os *OpenStack) DeleteVolume(volumeName string) error {\n\tused, err := os.diskIsUsed(volumeName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif used {\n\t\tmsg := fmt.Sprintf(\"Cannot delete the volume %q, it's still attached to a node\", volumeName)\n\t\treturn volume.NewDeletedVolumeInUseError(msg)\n\t}\n\n\tsClient, err := openstack.NewBlockStorageV1(os.provider, gophercloud.EndpointOpts{\n\t\tRegion: os.region,\n\t})\n\n\tif err != nil || sClient == nil {\n\t\tglog.Errorf(\"Unable to initialize cinder client for region: %s\", os.region)\n\t\treturn err\n\t}\n\terr = volumes.Delete(sClient, volumeName).ExtractErr()\n\tif err != nil {\n\t\tglog.Errorf(\"Cannot delete volume %s: %v\", volumeName, err)\n\t}\n\treturn err\n}\n\n\/\/ Get device path of attached volume to the compute running kubelet\nfunc (os *OpenStack) GetAttachmentDiskPath(instanceID string, diskName string) (string, error) {\n\tdisk, err := os.getVolume(diskName)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif len(disk.Attachments) > 0 && disk.Attachments[0][\"server_id\"] != nil {\n\t\tif instanceID == disk.Attachments[0][\"server_id\"] {\n\t\t\t\/\/ Attachment[0][\"device\"] points to the device path\n\t\t\t\/\/ see http:\/\/developer.openstack.org\/api-ref-blockstorage-v1.html\n\t\t\treturn disk.Attachments[0][\"device\"].(string), nil\n\t\t} else {\n\t\t\terrMsg := fmt.Sprintf(\"Disk %q is attached to a different compute: %q, should be detached before proceeding\", diskName, disk.Attachments[0][\"server_id\"])\n\t\t\tglog.Errorf(errMsg)\n\t\t\treturn \"\", errors.New(errMsg)\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"volume %s is not attached to %s\", diskName, instanceID)\n}\n\n\/\/ query if a volume is attached to a compute instance\nfunc (os *OpenStack) DiskIsAttached(diskName, instanceID string) (bool, error) {\n\tdisk, err := os.getVolume(diskName)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif len(disk.Attachments) > 0 && disk.Attachments[0][\"server_id\"] != nil && instanceID == disk.Attachments[0][\"server_id\"] {\n\t\treturn true, nil\n\t}\n\treturn false, nil\n}\n\n\/\/ query if a list of volumes are attached to a compute instance\nfunc (os *OpenStack) DisksAreAttached(diskNames []string, instanceID string) (map[string]bool, error) {\n\tattached := make(map[string]bool)\n\tfor _, diskName := range diskNames {\n\t\tattached[diskName] = false\n\t}\n\tfor _, diskName := range diskNames {\n\t\tdisk, err := os.getVolume(diskName)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tif len(disk.Attachments) > 0 && disk.Attachments[0][\"server_id\"] != nil && instanceID == disk.Attachments[0][\"server_id\"] {\n\t\t\tattached[diskName] = true\n\t\t}\n\t}\n\treturn attached, nil\n}\n\n\/\/ diskIsUsed returns true a disk is attached to any node.\nfunc (os *OpenStack) diskIsUsed(diskName string) (bool, error) {\n\tdisk, err := os.getVolume(diskName)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif len(disk.Attachments) > 0 {\n\t\treturn true, nil\n\t}\n\treturn false, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package api\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strconv\"\n\n\t\"github.com\/netlify\/gotrue\/models\"\n)\n\nconst defaultPerPage = 50\n\nfunc calculateTotalPages(perPage, total uint64) uint64 {\n\tpages := total \/ perPage\n\tif total%perPage > 0 {\n\t\treturn pages + 1\n\t}\n\treturn pages\n}\n\nfunc addPaginationHeaders(w http.ResponseWriter, r *http.Request, p *models.Pagination) {\n\ttotalPages := calculateTotalPages(p.PerPage, p.Count)\n\turl, _ := url.ParseRequestURI(r.URL.String())\n\tquery := url.Query()\n\theader := \"\"\n\tif totalPages > p.Page {\n\t\tquery.Set(\"page\", fmt.Sprintf(\"%v\", p.Page+1))\n\t\turl.RawQuery = query.Encode()\n\t\theader += \"<\" + url.String() + \">; rel=\\\"next\\\", \"\n\t}\n\tquery.Set(\"page\", fmt.Sprintf(\"%v\", totalPages))\n\turl.RawQuery = query.Encode()\n\theader += \"<\" + url.String() + \">; rel=\\\"last\\\"\"\n\n\tw.Header().Add(\"Link\", header)\n\tw.Header().Add(\"X-Total-Count\", fmt.Sprintf(\"%v\", p.Count))\n}\n\nfunc paginate(r *http.Request) (*models.Pagination, error) {\n\tparams := r.URL.Query()\n\tqueryPage := params.Get(\"page\")\n\tqueryPerPage := params.Get(\"per_page\")\n\tvar page uint64 = 1\n\tvar perPage uint64 = defaultPerPage\n\tvar err error\n\tif queryPage != \"\" {\n\t\tpage, err = strconv.ParseUint(queryPage, 10, 64)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif queryPerPage != \"\" {\n\t\tperPage, err = strconv.ParseUint(queryPerPage, 10, 64)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &models.Pagination{\n\t\tPage:    page,\n\t\tPerPage: perPage,\n\t}, nil\n}\n<commit_msg>add prev pagination header<commit_after>package api\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strconv\"\n\n\t\"github.com\/netlify\/gotrue\/models\"\n)\n\nconst defaultPerPage = 50\n\nfunc calculateTotalPages(perPage, total uint64) uint64 {\n\tpages := total \/ perPage\n\tif total%perPage > 0 {\n\t\treturn pages + 1\n\t}\n\treturn pages\n}\n\nfunc addPaginationHeaders(w http.ResponseWriter, r *http.Request, p *models.Pagination) {\n\ttotalPages := calculateTotalPages(p.PerPage, p.Count)\n\turl, _ := url.ParseRequestURI(r.URL.String())\n\tquery := url.Query()\n\theader := \"\"\n\tif totalPages > p.Page {\n\t\tquery.Set(\"page\", fmt.Sprintf(\"%v\", p.Page+1))\n\t\turl.RawQuery = query.Encode()\n\t\theader += \"<\" + url.String() + \">; rel=\\\"next\\\", \"\n\t}\n\tif p.Page > 1 {\n\t\tquery.Set(\"page\", fmt.Sprintf(\"%v\", p.Page-1))\n\t\turl.RawQuery = query.Encode()\n\t\theader += \"<\" + url.String() + \">; rel=\\\"prev\\\", \"\n\t}\n\tquery.Set(\"page\", fmt.Sprintf(\"%v\", totalPages))\n\turl.RawQuery = query.Encode()\n\theader += \"<\" + url.String() + \">; rel=\\\"last\\\"\"\n\n\tw.Header().Add(\"Link\", header)\n\tw.Header().Add(\"X-Total-Count\", fmt.Sprintf(\"%v\", p.Count))\n}\n\nfunc paginate(r *http.Request) (*models.Pagination, error) {\n\tparams := r.URL.Query()\n\tqueryPage := params.Get(\"page\")\n\tqueryPerPage := params.Get(\"per_page\")\n\tvar page uint64 = 1\n\tvar perPage uint64 = defaultPerPage\n\tvar err error\n\tif queryPage != \"\" {\n\t\tpage, err = strconv.ParseUint(queryPage, 10, 64)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif queryPerPage != \"\" {\n\t\tperPage, err = strconv.ParseUint(queryPerPage, 10, 64)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &models.Pagination{\n\t\tPage:    page,\n\t\tPerPage: perPage,\n\t}, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/alecthomas\/jsonschema\"\n\n\tvegeta \"github.com\/tsenart\/vegeta\/lib\"\n)\n\nfunc main() {\n\ttypes := map[string]interface{}{\n\t\t\"Target\": &vegeta.Target{},\n\t}\n\n\tvalid := strings.Join(keys(types), \", \")\n\n\tfs := flag.NewFlagSet(\"jsonschema\", flag.ExitOnError)\n\ttyp := fs.String(\"type\", \"\", fmt.Sprintf(\"Vegeta type to generate a JSON schema for [%s]\", valid))\n\tout := fs.String(\"output\", \"stdout\", \"Output file\")\n\n\tfs.Parse(os.Args[1:])\n\n\tt, ok := types[*typ]\n\tif !ok {\n\t\tdie(\"invalid type %q not in [%s]\", *typ, valid)\n\t}\n\n\tschema, err := json.MarshalIndent(jsonschema.Reflect(t), \"\", \"  \")\n\tif err != nil {\n\t\tdie(\"%s\", err)\n\t}\n\n\tswitch *out {\n\tcase \"stdout\":\n\t\t_, err = os.Stdout.Write(schema)\n\tdefault:\n\t\terr = ioutil.WriteFile(*out, schema, 0644)\n\t}\n\n\tif err != nil {\n\t\tdie(\"%s\", err)\n\t}\n}\n\nfunc die(s string, args ...interface{}) {\n\tfmt.Fprintf(os.Stderr, s, args...)\n\tos.Exit(1)\n}\n\nfunc keys(types map[string]interface{}) (ks []string) {\n\tfor k := range types {\n\t\tks = append(ks, k)\n\t}\n\treturn ks\n}\n<commit_msg>jsonschema: Exit on fs.Parse error<commit_after>package main\n\nimport (\n\t\"encoding\/json\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com\/alecthomas\/jsonschema\"\n\n\tvegeta \"github.com\/tsenart\/vegeta\/lib\"\n)\n\nfunc main() {\n\ttypes := map[string]interface{}{\n\t\t\"Target\": &vegeta.Target{},\n\t}\n\n\tvalid := strings.Join(keys(types), \", \")\n\n\tfs := flag.NewFlagSet(\"jsonschema\", flag.ContinueOnError)\n\ttyp := fs.String(\"type\", \"\", fmt.Sprintf(\"Vegeta type to generate a JSON schema for [%s]\", valid))\n\tout := fs.String(\"output\", \"stdout\", \"Output file\")\n\n\tif err := fs.Parse(os.Args[1:]); err != nil {\n\t\tdie(\"%s\", err)\n\t}\n\n\tt, ok := types[*typ]\n\tif !ok {\n\t\tdie(\"invalid type %q not in [%s]\", *typ, valid)\n\t}\n\n\tschema, err := json.MarshalIndent(jsonschema.Reflect(t), \"\", \"  \")\n\tif err != nil {\n\t\tdie(\"%s\", err)\n\t}\n\n\tswitch *out {\n\tcase \"stdout\":\n\t\t_, err = os.Stdout.Write(schema)\n\tdefault:\n\t\terr = ioutil.WriteFile(*out, schema, 0644)\n\t}\n\n\tif err != nil {\n\t\tdie(\"%s\", err)\n\t}\n}\n\nfunc die(s string, args ...interface{}) {\n\tfmt.Fprintf(os.Stderr, s, args...)\n\tos.Exit(1)\n}\n\nfunc keys(types map[string]interface{}) (ks []string) {\n\tfor k := range types {\n\t\tks = append(ks, k)\n\t}\n\treturn ks\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2022 The Skaffold Authors\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage helm\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\n\tapimachinery \"k8s.io\/apimachinery\/pkg\/runtime\/schema\"\n\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/config\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/graph\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/helm\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/instrumentation\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/kubernetes\/manifest\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/output\/log\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/render\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/render\/generate\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/render\/renderer\/util\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/schema\/latest\"\n\tsUtil \"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/util\"\n)\n\ntype Helm struct {\n\tconfigName string\n\tgenerate.Generator\n\tconfig *latest.Helm\n\n\tkubeContext string\n\tkubeConfig  string\n\tnamespace   string\n\tconfigFile  string\n\tlabels      map[string]string\n\tenableDebug bool\n\n\ttransformAllowlist map[apimachinery.GroupKind]latest.ResourceFilter\n\ttransformDenylist  map[apimachinery.GroupKind]latest.ResourceFilter\n}\n\nfunc (h Helm) EnableDebug() bool         { return h.enableDebug }\nfunc (h Helm) ConfigFile() string        { return h.configFile }\nfunc (h Helm) KubeContext() string       { return h.kubeContext }\nfunc (h Helm) KubeConfig() string        { return h.kubeConfig }\nfunc (h Helm) Labels() map[string]string { return h.labels }\nfunc (h Helm) GlobalFlags() []string     { return h.config.Flags.Global }\n\nfunc New(cfg render.Config, rCfg latest.RenderConfig, labels map[string]string, configName string) (Helm, error) {\n\tgenerator := generate.NewGenerator(cfg.GetWorkingDir(), rCfg.Generate, \"\")\n\ttransformAllowlist, transformDenylist, err := util.ConsolidateTransformConfiguration(cfg)\n\tif err != nil {\n\t\treturn Helm{}, err\n\t}\n\treturn Helm{\n\t\tconfigName: configName,\n\t\tGenerator:  generator,\n\t\tconfig:     rCfg.Helm,\n\n\t\tenableDebug: cfg.Mode() == config.RunModes.Debug,\n\t\tconfigFile:  cfg.ConfigurationFile(),\n\t\tkubeContext: cfg.GetKubeContext(),\n\t\tkubeConfig:  cfg.GetKubeConfig(),\n\t\tlabels:      labels,\n\t\tnamespace:   cfg.GetNamespace(),\n\n\t\ttransformAllowlist: transformAllowlist,\n\t\ttransformDenylist:  transformDenylist,\n\t}, nil\n}\n\nfunc (h Helm) Render(ctx context.Context, out io.Writer, builds []graph.Artifact, _ bool) (manifest.ManifestListByConfig, error) {\n\t_, endTrace := instrumentation.StartTrace(ctx, \"Render_HelmManifests\")\n\tlog.Entry(ctx).Infof(\"rendering using helm\")\n\tinstrumentation.AddAttributesToCurrentSpanFromContext(ctx, map[string]string{\n\t\t\"RendererType\": \"helm\",\n\t})\n\n\tmanifests, err := h.generateHelmManifests(ctx, builds)\n\tendTrace()\n\tmanifestListByConfig := manifest.NewManifestListByConfig()\n\tmanifestListByConfig.Add(h.configName, manifests)\n\treturn manifestListByConfig, err\n}\n\nfunc (h Helm) generateHelmManifests(ctx context.Context, builds []graph.Artifact) (manifest.ManifestList, error) {\n\tvar renderedManifests manifest.ManifestList\n\thelmEnv := sUtil.OSEnviron()\n\tvar postRendererArgs []string\n\n\tif len(builds) > 0 {\n\t\tskaffoldBinary, filterEnv, cleanup, err := helm.PrepareSkaffoldFilter(h, builds)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"could not prepare `skaffold filter`: %w\", err)\n\t\t}\n\t\t\/\/ need to include current environment, specifically for HOME to lookup ~\/.kube\/config\n\t\thelmEnv = append(helmEnv, filterEnv...)\n\t\tpostRendererArgs = []string{\"--post-renderer\", skaffoldBinary}\n\t\tdefer cleanup()\n\t}\n\n\tfor _, release := range h.config.Releases {\n\t\treleaseName, err := sUtil.ExpandEnvTemplateOrFail(release.Name, nil)\n\t\tif err != nil {\n\t\t\treturn nil, helm.UserErr(fmt.Sprintf(\"cannot expand release name %q\", release.Name), err)\n\t\t}\n\n\t\targs := []string{\"template\", releaseName, helm.ChartSource(release)}\n\t\targs = append(args, postRendererArgs...)\n\t\tif release.Packaged == nil && release.Version != \"\" {\n\t\t\targs = append(args, \"--version\", release.Version)\n\t\t}\n\n\t\targs, err = helm.ConstructOverrideArgs(&release, builds, args)\n\t\tif err != nil {\n\t\t\treturn nil, helm.UserErr(\"construct override args\", err)\n\t\t}\n\n\t\tnamespace, err := helm.ReleaseNamespace(h.namespace, release)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif h.namespace != \"\" {\n\t\t\tnamespace = h.namespace\n\t\t}\n\t\tif namespace != \"\" {\n\t\t\targs = append(args, \"--namespace\", namespace)\n\t\t}\n\n\t\tif release.Repo != \"\" {\n\t\t\targs = append(args, \"--repo\")\n\t\t\targs = append(args, release.Repo)\n\t\t}\n\n\t\toutBuffer := new(bytes.Buffer)\n\t\terrBuffer := new(bytes.Buffer)\n\t\tif err := helm.ExecWithStdoutAndStderr(ctx, h, outBuffer, errBuffer, false, helmEnv, args...); err != nil {\n\t\t\treturn nil, helm.UserErr(\"std out err\", fmt.Errorf(outBuffer.String(), fmt.Errorf(errBuffer.String())))\n\t\t}\n\t\tlog.Entry(ctx).Errorf(errBuffer.String())\n\t\trenderedManifests.Append(outBuffer.Bytes())\n\t}\n\n\tmanifests, err := renderedManifests.SetLabels(h.labels, manifest.NewResourceSelectorLabels(h.transformAllowlist, h.transformDenylist))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn manifests, nil\n}\n<commit_msg>fix: not print error message if it is empty (#8005)<commit_after>\/*\nCopyright 2022 The Skaffold Authors\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage helm\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\n\tapimachinery \"k8s.io\/apimachinery\/pkg\/runtime\/schema\"\n\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/config\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/graph\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/helm\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/instrumentation\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/kubernetes\/manifest\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/output\/log\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/render\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/render\/generate\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/render\/renderer\/util\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/schema\/latest\"\n\tsUtil \"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/util\"\n)\n\ntype Helm struct {\n\tconfigName string\n\tgenerate.Generator\n\tconfig *latest.Helm\n\n\tkubeContext string\n\tkubeConfig  string\n\tnamespace   string\n\tconfigFile  string\n\tlabels      map[string]string\n\tenableDebug bool\n\n\ttransformAllowlist map[apimachinery.GroupKind]latest.ResourceFilter\n\ttransformDenylist  map[apimachinery.GroupKind]latest.ResourceFilter\n}\n\nfunc (h Helm) EnableDebug() bool         { return h.enableDebug }\nfunc (h Helm) ConfigFile() string        { return h.configFile }\nfunc (h Helm) KubeContext() string       { return h.kubeContext }\nfunc (h Helm) KubeConfig() string        { return h.kubeConfig }\nfunc (h Helm) Labels() map[string]string { return h.labels }\nfunc (h Helm) GlobalFlags() []string     { return h.config.Flags.Global }\n\nfunc New(cfg render.Config, rCfg latest.RenderConfig, labels map[string]string, configName string) (Helm, error) {\n\tgenerator := generate.NewGenerator(cfg.GetWorkingDir(), rCfg.Generate, \"\")\n\ttransformAllowlist, transformDenylist, err := util.ConsolidateTransformConfiguration(cfg)\n\tif err != nil {\n\t\treturn Helm{}, err\n\t}\n\treturn Helm{\n\t\tconfigName: configName,\n\t\tGenerator:  generator,\n\t\tconfig:     rCfg.Helm,\n\n\t\tenableDebug: cfg.Mode() == config.RunModes.Debug,\n\t\tconfigFile:  cfg.ConfigurationFile(),\n\t\tkubeContext: cfg.GetKubeContext(),\n\t\tkubeConfig:  cfg.GetKubeConfig(),\n\t\tlabels:      labels,\n\t\tnamespace:   cfg.GetNamespace(),\n\n\t\ttransformAllowlist: transformAllowlist,\n\t\ttransformDenylist:  transformDenylist,\n\t}, nil\n}\n\nfunc (h Helm) Render(ctx context.Context, out io.Writer, builds []graph.Artifact, _ bool) (manifest.ManifestListByConfig, error) {\n\t_, endTrace := instrumentation.StartTrace(ctx, \"Render_HelmManifests\")\n\tlog.Entry(ctx).Infof(\"rendering using helm\")\n\tinstrumentation.AddAttributesToCurrentSpanFromContext(ctx, map[string]string{\n\t\t\"RendererType\": \"helm\",\n\t})\n\n\tmanifests, err := h.generateHelmManifests(ctx, builds)\n\tendTrace()\n\tmanifestListByConfig := manifest.NewManifestListByConfig()\n\tmanifestListByConfig.Add(h.configName, manifests)\n\treturn manifestListByConfig, err\n}\n\nfunc (h Helm) generateHelmManifests(ctx context.Context, builds []graph.Artifact) (manifest.ManifestList, error) {\n\tvar renderedManifests manifest.ManifestList\n\thelmEnv := sUtil.OSEnviron()\n\tvar postRendererArgs []string\n\n\tif len(builds) > 0 {\n\t\tskaffoldBinary, filterEnv, cleanup, err := helm.PrepareSkaffoldFilter(h, builds)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"could not prepare `skaffold filter`: %w\", err)\n\t\t}\n\t\t\/\/ need to include current environment, specifically for HOME to lookup ~\/.kube\/config\n\t\thelmEnv = append(helmEnv, filterEnv...)\n\t\tpostRendererArgs = []string{\"--post-renderer\", skaffoldBinary}\n\t\tdefer cleanup()\n\t}\n\n\tfor _, release := range h.config.Releases {\n\t\treleaseName, err := sUtil.ExpandEnvTemplateOrFail(release.Name, nil)\n\t\tif err != nil {\n\t\t\treturn nil, helm.UserErr(fmt.Sprintf(\"cannot expand release name %q\", release.Name), err)\n\t\t}\n\n\t\targs := []string{\"template\", releaseName, helm.ChartSource(release)}\n\t\targs = append(args, postRendererArgs...)\n\t\tif release.Packaged == nil && release.Version != \"\" {\n\t\t\targs = append(args, \"--version\", release.Version)\n\t\t}\n\n\t\targs, err = helm.ConstructOverrideArgs(&release, builds, args)\n\t\tif err != nil {\n\t\t\treturn nil, helm.UserErr(\"construct override args\", err)\n\t\t}\n\n\t\tnamespace, err := helm.ReleaseNamespace(h.namespace, release)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif h.namespace != \"\" {\n\t\t\tnamespace = h.namespace\n\t\t}\n\t\tif namespace != \"\" {\n\t\t\targs = append(args, \"--namespace\", namespace)\n\t\t}\n\n\t\tif release.Repo != \"\" {\n\t\t\targs = append(args, \"--repo\")\n\t\t\targs = append(args, release.Repo)\n\t\t}\n\n\t\toutBuffer := new(bytes.Buffer)\n\t\terrBuffer := new(bytes.Buffer)\n\n\t\terr = helm.ExecWithStdoutAndStderr(ctx, h, outBuffer, errBuffer, false, helmEnv, args...)\n\t\terrorMsg := errBuffer.String()\n\n\t\tif len(errorMsg) > 0 {\n\t\t\tlog.Entry(ctx).Errorf(errorMsg)\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn nil, helm.UserErr(\"std out err\", fmt.Errorf(outBuffer.String(), fmt.Errorf(errorMsg)))\n\t\t}\n\n\t\trenderedManifests.Append(outBuffer.Bytes())\n\t}\n\n\tmanifests, err := renderedManifests.SetLabels(h.labels, manifest.NewResourceSelectorLabels(h.transformAllowlist, h.transformDenylist))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn manifests, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package cmd\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\n\t\"github.com\/jarosser06\/fastfood\"\n)\n\nconst (\n\ttempPackEnvVar = \"FASTFOOD_TEMPLATE_PACK\"\n)\n\ntype Generator struct {\n\tMappedArgs    map[string]string\n\tTemplatesPath string\n}\n\n\/\/ Translates key:value strings into a map\nfunc MapArgs(args []string) map[string]string {\n\tvar argMap map[string]string\n\targMap = make(map[string]string)\n\n\tfor _, arg := range args {\n\t\tif strings.Contains(arg, \":\") {\n\t\t\t\/\/ Split at the first : in an arg\n\t\t\tsplitArg := strings.SplitN(arg, \":\", 2)\n\n\t\t\targMap[splitArg[0]] = splitArg[1]\n\t\t}\n\t}\n\n\treturn argMap\n}\n\nfunc DefTempPack() string {\n\tpackEnv := os.Getenv(\"FASTFOOD_TEMPLATE_PACK\")\n\tif packEnv == \"\" {\n\t\treturn path.Join(os.Getenv(\"HOME\"), \"fastfood\")\n\t} else {\n\t\treturn packEnv\n\t}\n}\n\nfunc (g *Generator) Run(args []string) int {\n\tworkingDir, _ := os.Getwd()\n\tcmdFlags := flag.NewFlagSet(\"gen\", flag.ContinueOnError)\n\tcmdFlags.Usage = func() { fmt.Println(g.Help()) }\n\n\ttemplatePack := *cmdFlags.String(\"templates-pack\", DefTempPack(), \"path to the templates directory\")\n\n\tif err := cmdFlags.Parse(args); err != nil {\n\t\treturn 1\n\t}\n\n\tif fastfood.PathIsCookbook(workingDir) {\n\t\tckbk, err := fastfood.NewCookbookFromPath(workingDir)\n\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Unable to parse cookbook\")\n\t\t\treturn 1\n\t\t}\n\n\t\tcmdManifest := path.Join(templatePack, \"manifest.json\")\n\t\tif !fastfood.FileExist(cmdManifest) {\n\t\t\tfmt.Printf(\"Error no such file %s\\n\", cmdManifest)\n\t\t\treturn 1\n\t\t}\n\n\t\t\/\/ Remove the first arg as the command\n\t\tgenCommand, args := args[0], args[1:len(args)]\n\n\t\tcommands := ParseCommandsFromFile(cmdManifest)\n\t\tif _, ok := commands[genCommand]; ok {\n\t\t\tgoto CMDFound\n\t\t}\n\n\t\t\/\/ If the loop finishes without finding the commnad exit\n\t\tfmt.Printf(\"No generator found for %s\\n\", genCommand)\n\t\treturn 1\n\n\t\t\/\/ Command was found continue to execute\n\tCMDFound:\n\n\t\tp, err := fastfood.NewProviderFromFile(\n\t\t\tckbk,\n\t\t\tpath.Join(templatePack, commands[genCommand].Manifest),\n\t\t)\n\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Error loading provider %s: %v\", genCommand, err)\n\t\t\treturn 1\n\t\t}\n\n\t\tmappedArgs := MapArgs(args)\n\t\tvar providerType string\n\t\tif val, ok := mappedArgs[\"type\"]; ok {\n\t\t\tproviderType = val\n\t\t} else {\n\t\t\tif p.DefaultType != \"\" {\n\t\t\t\tproviderType = p.DefaultType\n\t\t\t} else {\n\t\t\t\tfmt.Println(\"You must pass a type b\/c not default type is set\")\n\t\t\t\treturn 1\n\t\t\t}\n\t\t}\n\n\t\tp.GenDirs(providerType)\n\t\terr = p.GenFiles(\n\t\t\tproviderType,\n\t\t\tpath.Join(templatePack, genCommand),\n\t\t\tmappedArgs,\n\t\t)\n\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Error generating files %v\\n\", err)\n\t\t\treturn 1\n\t\t}\n\n\t} else {\n\t\tfmt.Println(\"You must run this command from a cookbook directory\")\n\t\treturn 1\n\t}\n\treturn 0\n}\n\nfunc (g *Generator) Synopsis() string {\n\treturn \"Generates a new recipe for an existing cookbook\"\n}\n\n\/\/ Autogenerate based on commands parsed\nfunc (g *Generator) Help() string {\n\thelpText := `\nUsage: fastfood gen [provider] [options]\n\n  This will generate a recipe and spec file\n  based on the provider and options you\n  provide that provider.\n\n  Options are passed using using a key:value\n  notation so to set the name you would use\n  the following:\n\n  name:recipe_name\n\nGenerators:\n\n  db     - Creates a database recipe based\n           on the type, defaults to MySQL\n\n  app    - Creates an application recipe\n           based on the type, defaults to Generic`\n\n\treturn helpText\n}\n<commit_msg>re-enabled metatdata appending<commit_after>package cmd\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\n\t\"github.com\/jarosser06\/fastfood\"\n)\n\nconst (\n\ttempPackEnvVar = \"FASTFOOD_TEMPLATE_PACK\"\n)\n\ntype Generator struct {\n\tMappedArgs    map[string]string\n\tTemplatesPath string\n}\n\n\/\/ Translates key:value strings into a map\nfunc MapArgs(args []string) map[string]string {\n\tvar argMap map[string]string\n\targMap = make(map[string]string)\n\n\tfor _, arg := range args {\n\t\tif strings.Contains(arg, \":\") {\n\t\t\t\/\/ Split at the first : in an arg\n\t\t\tsplitArg := strings.SplitN(arg, \":\", 2)\n\n\t\t\targMap[splitArg[0]] = splitArg[1]\n\t\t}\n\t}\n\n\treturn argMap\n}\n\nfunc DefTempPack() string {\n\tpackEnv := os.Getenv(\"FASTFOOD_TEMPLATE_PACK\")\n\tif packEnv == \"\" {\n\t\treturn path.Join(os.Getenv(\"HOME\"), \"fastfood\")\n\t} else {\n\t\treturn packEnv\n\t}\n}\n\nfunc (g *Generator) Run(args []string) int {\n\tworkingDir, _ := os.Getwd()\n\tcmdFlags := flag.NewFlagSet(\"gen\", flag.ContinueOnError)\n\tcmdFlags.Usage = func() { fmt.Println(g.Help()) }\n\n\ttemplatePack := *cmdFlags.String(\"templates-pack\", DefTempPack(), \"path to the templates directory\")\n\n\tif err := cmdFlags.Parse(args); err != nil {\n\t\treturn 1\n\t}\n\n\tif fastfood.PathIsCookbook(workingDir) {\n\t\tckbk, err := fastfood.NewCookbookFromPath(workingDir)\n\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Unable to parse cookbook\")\n\t\t\treturn 1\n\t\t}\n\n\t\tcmdManifest := path.Join(templatePack, \"manifest.json\")\n\t\tif !fastfood.FileExist(cmdManifest) {\n\t\t\tfmt.Printf(\"Error no such file %s\\n\", cmdManifest)\n\t\t\treturn 1\n\t\t}\n\n\t\t\/\/ Remove the first arg as the command\n\t\tgenCommand, args := args[0], args[1:len(args)]\n\n\t\tcommands := ParseCommandsFromFile(cmdManifest)\n\t\tif _, ok := commands[genCommand]; ok {\n\t\t\tgoto CMDFound\n\t\t}\n\n\t\t\/\/ If the loop finishes without finding the commnad exit\n\t\tfmt.Printf(\"No generator found for %s\\n\", genCommand)\n\t\treturn 1\n\n\t\t\/\/ Command was found continue to execute\n\tCMDFound:\n\n\t\tp, err := fastfood.NewProviderFromFile(\n\t\t\tckbk,\n\t\t\tpath.Join(templatePack, commands[genCommand].Manifest),\n\t\t)\n\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Error loading provider %s: %v\", genCommand, err)\n\t\t\treturn 1\n\t\t}\n\n\t\tmappedArgs := MapArgs(args)\n\t\tvar providerType string\n\t\tif val, ok := mappedArgs[\"type\"]; ok {\n\t\t\tproviderType = val\n\t\t} else {\n\t\t\tif p.DefaultType != \"\" {\n\t\t\t\tproviderType = p.DefaultType\n\t\t\t} else {\n\t\t\t\tfmt.Println(\"You must pass a type b\/c not default type is set\")\n\t\t\t\treturn 1\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Add the needed dependencies to the metadata\n\t\tckbk.AppendDependencies(p.Dependencies(providerType))\n\t\tp.GenDirs(providerType)\n\n\t\terr = p.GenFiles(\n\t\t\tproviderType,\n\t\t\tpath.Join(templatePack, genCommand),\n\t\t\tmappedArgs,\n\t\t)\n\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Error generating files %v\\n\", err)\n\t\t\treturn 1\n\t\t}\n\n\t} else {\n\t\tfmt.Println(\"You must run this command from a cookbook directory\")\n\t\treturn 1\n\t}\n\treturn 0\n}\n\nfunc (g *Generator) Synopsis() string {\n\treturn \"Generates a new recipe for an existing cookbook\"\n}\n\n\/\/ Autogenerate based on commands parsed\nfunc (g *Generator) Help() string {\n\thelpText := `\nUsage: fastfood gen [provider] [options]\n\n  This will generate a recipe and spec file\n  based on the provider and options you\n  provide that provider.\n\n  Options are passed using using a key:value\n  notation so to set the name you would use\n  the following:\n\n  name:recipe_name\n\nGenerators:\n\n  db     - Creates a database recipe based\n           on the type, defaults to MySQL\n\n  app    - Creates an application recipe\n           based on the type, defaults to Generic`\n\n\treturn helpText\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013 Michael Yang. All rights reserved.\n\/\/ Use of this source code is governed by a MIT-style\n\/\/ license that can be found in the LICENSE file.\npackage id3\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n)\n\nconst (\n\tFrameHeaderSize = 10\n)\n\n\/\/ FrameType holds frame id metadata and constructor method\n\/\/ A set number of these are created in the version specific files\ntype FrameType struct {\n\tid          string\n\tdescription string\n\tconstructor func(FrameHead, []byte) Framer\n}\n\n\/\/ Framer provides a generic interface for frames\n\/\/ This is the default type returned when creating frames\ntype Framer interface {\n\tId() string\n\tSize() int\n\tStatusFlags() byte\n\tFormatFlags() byte\n\tString() string\n\tBytes() []byte\n}\n\n\/\/ FrameHead represents the header of each frame\n\/\/ Additional metadata is kept through the embedded frame type\n\/\/ These do not usually need to be manually created\ntype FrameHead struct {\n\tFrameType\n\tstatusFlags byte\n\tformatFlags byte\n\tsize        int32\n}\n\nfunc (h FrameHead) Id() string {\n\treturn h.id\n}\n\nfunc (h FrameHead) Size() int {\n\treturn int(h.size)\n}\n\nfunc (h FrameHead) StatusFlags() byte {\n\treturn h.statusFlags\n}\n\nfunc (h FrameHead) FormatFlags() byte {\n\treturn h.formatFlags\n}\n\n\/\/ DataFrame is the default frame for binary data\ntype DataFrame struct {\n\tFrameHead\n\tdata []byte\n}\n\nfunc NewDataFrame(head FrameHead, data []byte) Framer {\n\treturn &DataFrame{head, data}\n}\n\nfunc (f DataFrame) Data() []byte {\n\treturn f.data\n}\n\nfunc (f *DataFrame) SetData(b []byte) {\n\tf.size += int32(len(b)) - f.size\n\tf.data = b\n}\n\nfunc (f DataFrame) String() string {\n\treturn \"<binary data>\"\n}\n\nfunc (f DataFrame) Bytes() []byte {\n\treturn f.data\n}\n\n\/\/ TextFramer represents frames that contain encoded text\ntype TextFramer interface {\n\tFramer\n\tEncoding() string\n\tSetEncoding(string) error\n\tText() string\n\tSetText(string) error\n}\n\n\/\/ TextFrame represents frames that contain encoded text\ntype TextFrame struct {\n\tFrameHead\n\tencoding byte\n\ttext     string\n}\n\nfunc NewTextFrame(head FrameHead, data []byte) Framer {\n\tvar err error\n\tf := &TextFrame{FrameHead: head}\n\n\tf.encoding = data[0]\n\n\tif f.text, err = Decoders[f.encoding].ConvertString(string(data[1:])); err != nil {\n\t\treturn nil\n\t}\n\n\treturn f\n}\n\nfunc (f TextFrame) Encoding() string {\n\treturn encodingForIndex(f.encoding)\n}\n\nfunc (f *TextFrame) SetEncoding(encoding string) error {\n\ti := byte(indexForEncoding(encoding))\n\tif i < 0 {\n\t\treturn errors.New(\"encoding: invalid encoding\")\n\t}\n\n\tf.encoding = i\n\treturn nil\n}\n\nfunc (f TextFrame) Text() string {\n\treturn f.text\n}\n\nfunc (f *TextFrame) SetText(text string) error {\n\tdiff, err := encodedDiff(f.encoding, text, f.text)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf.size += int32(diff)\n\tf.text = text\n\treturn nil\n}\n\nfunc (f TextFrame) String() string {\n\treturn f.text\n}\n\nfunc (f TextFrame) Bytes() []byte {\n\tbytes := make([]byte, f.Size())\n\n\tencodedString, err := Encoders[f.encoding].ConvertString(f.text)\n\tif err != nil {\n\t\treturn bytes\n\t}\n\n\tbytes[0] = f.encoding\n\tcopy(bytes[1:], []byte(encodedString))\n\n\treturn bytes\n}\n\ntype DescTextFrame struct {\n\tFrameHead\n\tTextFrame\n\tdescription string\n}\n\n\/\/ DescTextFrame represents frames that contain encoded text and descriptions\nfunc NewDescTextFrame(head FrameHead, data []byte) Framer {\n\tf := &DescTextFrame{FrameHead: head}\n\n\tvar err error\n\n\tf.encoding = data[0]\n\n\tcutoff := 1\n\tif i := afterNullIndex(data[1:], f.encoding); i < 0 {\n\t\treturn nil\n\t} else {\n\t\tcutoff += i\n\t}\n\n\tif f.description, err = Decoders[f.encoding].ConvertString(string(data[1:cutoff])); err != nil {\n\t\treturn nil\n\t}\n\n\tif f.text, err = Decoders[f.encoding].ConvertString(string(data[cutoff:])); err != nil {\n\t\treturn nil\n\t}\n\n\treturn f\n}\n\nfunc (f DescTextFrame) Description() string {\n\treturn f.description\n}\n\nfunc (f *DescTextFrame) SetDescription(description string) error {\n\tdiff, err := encodedDiff(f.encoding, description, f.description)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf.size += int32(diff)\n\tf.description = description\n\treturn nil\n}\n\nfunc (f DescTextFrame) Bytes() []byte {\n\tbytes := make([]byte, f.Size())\n\n\tencodedDescription, err := Encoders[f.encoding].ConvertString(f.description)\n\tif err != nil {\n\t\treturn bytes\n\t}\n\tencodedText, err := Encoders[f.encoding].ConvertString(f.text)\n\tif err != nil {\n\t\treturn bytes\n\t}\n\n\tbytes[0] = f.encoding\n\tindex := 1\n\tcopy(bytes[index:index+len(encodedDescription)], []byte(encodedDescription))\n\tindex += len(encodedDescription)\n\tcopy(bytes[index:index+len(encodedText)], []byte(encodedText))\n\n\treturn bytes\n}\n\n\/\/ UnsynchTextFrame represents frames that contain unsynchronized text\ntype UnsynchTextFrame struct {\n\tFrameHead\n\tDescTextFrame\n\tlanguage string\n}\n\nfunc NewUnsynchTextFrame(head FrameHead, data []byte) Framer {\n\tvar err error\n\tf := &UnsynchTextFrame{FrameHead: head}\n\n\tf.encoding = data[0]\n\tf.language = string(data[1:4])\n\n\tcutoff := 4\n\tif i := afterNullIndex(data[4:], f.encoding); i < 0 {\n\t\treturn nil\n\t} else {\n\t\tcutoff += i\n\t}\n\n\tif f.description, err = Decoders[f.encoding].ConvertString(string(data[4:cutoff])); err != nil {\n\t\treturn nil\n\t}\n\n\tif f.text, err = Decoders[f.encoding].ConvertString(string(data[cutoff:])); err != nil {\n\t\treturn nil\n\t}\n\n\treturn f\n}\n\nfunc (f UnsynchTextFrame) Language() string {\n\treturn f.language\n}\n\nfunc (f *UnsynchTextFrame) SetLanguage(language string) error {\n\tif len(language) != 3 {\n\t\treturn errors.New(\"language: invalid language string\")\n\t}\n\n\tf.language = language\n\treturn nil\n}\n\nfunc (f UnsynchTextFrame) Bytes() []byte {\n\tbytes := make([]byte, f.Size())\n\n\tencodedDescription, err := Encoders[f.encoding].ConvertString(f.description)\n\tif err != nil {\n\t\treturn bytes\n\t}\n\tencodedText, err := Encoders[f.encoding].ConvertString(f.text)\n\tif err != nil {\n\t\treturn bytes\n\t}\n\n\tbytes[0] = f.encoding\n\tcopy(bytes[1:4], []byte(f.language))\n\tindex := 4\n\tcopy(bytes[index:index+len(encodedDescription)], []byte(encodedDescription))\n\tindex += len(encodedDescription)\n\tcopy(bytes[index:index+len(encodedText)], []byte(encodedText))\n\n\treturn bytes\n}\n\n\/\/ ImageFrame represent frames that have media attached\ntype ImageFrame struct {\n\tFrameHead\n\tDataFrame\n\tencoding    byte\n\tmimeType    string\n\tpictureType byte\n\tdescription string\n}\n\nfunc NewImageFrame(head FrameHead, data []byte) Framer {\n\tf := &ImageFrame{FrameHead: head}\n\n\tvar err error\n\tencodingIndex := data[0]\n\n\tf.encoding = encodingIndex\n\n\tbuffer := bytes.NewBuffer(data[1:])\n\tif f.mimeType, err = buffer.ReadString(0); err != nil {\n\t\treturn nil\n\t}\n\n\tif f.pictureType, err = buffer.ReadByte(); err != nil {\n\t\treturn nil\n\t}\n\n\tbeginIndex := 1 + len(f.mimeType) + 1\n\tvar cutoff int\n\tif i := afterNullIndex(data[beginIndex:], f.encoding); i < 0 {\n\t\treturn nil\n\t} else {\n\t\tcutoff = beginIndex + i\n\t}\n\n\tif f.description, err = Decoders[encodingIndex].ConvertString(string(data[beginIndex:cutoff])); err != nil {\n\t\treturn nil\n\t}\n\n\tf.data = data[cutoff:]\n\n\treturn f\n}\n\nfunc (f ImageFrame) Encoding() string {\n\treturn encodingForIndex(f.encoding)\n}\n\nfunc (f *ImageFrame) SetEncoding(encoding string) error {\n\ti := byte(indexForEncoding(encoding))\n\tif i < 0 {\n\t\treturn errors.New(\"encoding: invalid encoding\")\n\t}\n\n\tf.encoding = i\n\treturn nil\n}\n\nfunc (f ImageFrame) MIMEType() string {\n\treturn f.mimeType\n}\n\nfunc (f *ImageFrame) SetMIMEType(mimeType string) {\n\tf.size += int32(len(mimeType)) - f.size\n\tif mimeType[len(mimeType)-1] != 0 {\n\t\tnullTermBytes := append([]byte(mimeType), 0x00)\n\t\tf.mimeType = string(nullTermBytes)\n\t\tf.size += 1\n\t} else {\n\t\tf.mimeType = mimeType\n\t}\n}\n\nfunc (f ImageFrame) Bytes() []byte {\n\tbytes := make([]byte, f.Size())\n\n\tencodedDescription, err := Encoders[f.encoding].ConvertString(f.description)\n\tif err != nil {\n\t\treturn bytes\n\t}\n\n\tbytes[0] = f.encoding\n\tindex := 1\n\tcopy(bytes[index:index+len(f.mimeType)], []byte(f.mimeType))\n\tindex += len(f.mimeType)\n\tbytes[index] = f.pictureType\n\tindex += 1\n\tcopy(bytes[index:index+len(encodedDescription)], []byte(encodedDescription))\n\tindex += len(encodedDescription)\n\tcopy(bytes[index:index+len(f.data)], f.data)\n\n\treturn bytes\n}\n<commit_msg>Change Framer String() methods<commit_after>\/\/ Copyright 2013 Michael Yang. All rights reserved.\n\/\/ Use of this source code is governed by a MIT-style\n\/\/ license that can be found in the LICENSE file.\npackage id3\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n)\n\nconst (\n\tFrameHeaderSize = 10\n)\n\n\/\/ FrameType holds frame id metadata and constructor method\n\/\/ A set number of these are created in the version specific files\ntype FrameType struct {\n\tid          string\n\tdescription string\n\tconstructor func(FrameHead, []byte) Framer\n}\n\n\/\/ Framer provides a generic interface for frames\n\/\/ This is the default type returned when creating frames\ntype Framer interface {\n\tId() string\n\tSize() int\n\tStatusFlags() byte\n\tFormatFlags() byte\n\tString() string\n\tBytes() []byte\n}\n\n\/\/ FrameHead represents the header of each frame\n\/\/ Additional metadata is kept through the embedded frame type\n\/\/ These do not usually need to be manually created\ntype FrameHead struct {\n\tFrameType\n\tstatusFlags byte\n\tformatFlags byte\n\tsize        int32\n}\n\nfunc (h FrameHead) Id() string {\n\treturn h.id\n}\n\nfunc (h FrameHead) Size() int {\n\treturn int(h.size)\n}\n\nfunc (h FrameHead) StatusFlags() byte {\n\treturn h.statusFlags\n}\n\nfunc (h FrameHead) FormatFlags() byte {\n\treturn h.formatFlags\n}\n\n\/\/ DataFrame is the default frame for binary data\ntype DataFrame struct {\n\tFrameHead\n\tdata []byte\n}\n\nfunc NewDataFrame(head FrameHead, data []byte) Framer {\n\treturn &DataFrame{head, data}\n}\n\nfunc (f DataFrame) Data() []byte {\n\treturn f.data\n}\n\nfunc (f *DataFrame) SetData(b []byte) {\n\tf.size += int32(len(b)) - f.size\n\tf.data = b\n}\n\nfunc (f DataFrame) String() string {\n\treturn \"<binary data>\"\n}\n\nfunc (f DataFrame) Bytes() []byte {\n\treturn f.data\n}\n\n\/\/ TextFramer represents frames that contain encoded text\ntype TextFramer interface {\n\tFramer\n\tEncoding() string\n\tSetEncoding(string) error\n\tText() string\n\tSetText(string) error\n}\n\n\/\/ TextFrame represents frames that contain encoded text\ntype TextFrame struct {\n\tFrameHead\n\tencoding byte\n\ttext     string\n}\n\nfunc NewTextFrame(head FrameHead, data []byte) Framer {\n\tvar err error\n\tf := &TextFrame{FrameHead: head}\n\n\tf.encoding = data[0]\n\n\tif f.text, err = Decoders[f.encoding].ConvertString(string(data[1:])); err != nil {\n\t\treturn nil\n\t}\n\n\treturn f\n}\n\nfunc (f TextFrame) Encoding() string {\n\treturn encodingForIndex(f.encoding)\n}\n\nfunc (f *TextFrame) SetEncoding(encoding string) error {\n\ti := byte(indexForEncoding(encoding))\n\tif i < 0 {\n\t\treturn errors.New(\"encoding: invalid encoding\")\n\t}\n\n\tf.encoding = i\n\treturn nil\n}\n\nfunc (f TextFrame) Text() string {\n\treturn f.text\n}\n\nfunc (f *TextFrame) SetText(text string) error {\n\tdiff, err := encodedDiff(f.encoding, text, f.text)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf.size += int32(diff)\n\tf.text = text\n\treturn nil\n}\n\nfunc (f TextFrame) String() string {\n\treturn f.text\n}\n\nfunc (f TextFrame) Bytes() []byte {\n\tbytes := make([]byte, f.Size())\n\n\tencodedString, err := Encoders[f.encoding].ConvertString(f.text)\n\tif err != nil {\n\t\treturn bytes\n\t}\n\n\tbytes[0] = f.encoding\n\tcopy(bytes[1:], []byte(encodedString))\n\n\treturn bytes\n}\n\ntype DescTextFrame struct {\n\tFrameHead\n\tTextFrame\n\tdescription string\n}\n\n\/\/ DescTextFrame represents frames that contain encoded text and descriptions\nfunc NewDescTextFrame(head FrameHead, data []byte) Framer {\n\tf := &DescTextFrame{FrameHead: head}\n\n\tvar err error\n\n\tf.encoding = data[0]\n\n\tcutoff := 1\n\tif i := afterNullIndex(data[1:], f.encoding); i < 0 {\n\t\treturn nil\n\t} else {\n\t\tcutoff += i\n\t}\n\n\tif f.description, err = Decoders[f.encoding].ConvertString(string(data[1:cutoff])); err != nil {\n\t\treturn nil\n\t}\n\n\tif f.text, err = Decoders[f.encoding].ConvertString(string(data[cutoff:])); err != nil {\n\t\treturn nil\n\t}\n\n\treturn f\n}\n\nfunc (f DescTextFrame) Description() string {\n\treturn f.description\n}\n\nfunc (f *DescTextFrame) SetDescription(description string) error {\n\tdiff, err := encodedDiff(f.encoding, description, f.description)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf.size += int32(diff)\n\tf.description = description\n\treturn nil\n}\n\nfunc (f DescTextFrame) String() string {\n\treturn fmt.Sprintf(\"%s: %s\", f.description, f.text)\n}\n\nfunc (f DescTextFrame) Bytes() []byte {\n\tbytes := make([]byte, f.Size())\n\n\tencodedDescription, err := Encoders[f.encoding].ConvertString(f.description)\n\tif err != nil {\n\t\treturn bytes\n\t}\n\tencodedText, err := Encoders[f.encoding].ConvertString(f.text)\n\tif err != nil {\n\t\treturn bytes\n\t}\n\n\tbytes[0] = f.encoding\n\tindex := 1\n\tcopy(bytes[index:index+len(encodedDescription)], []byte(encodedDescription))\n\tindex += len(encodedDescription)\n\tcopy(bytes[index:index+len(encodedText)], []byte(encodedText))\n\n\treturn bytes\n}\n\n\/\/ UnsynchTextFrame represents frames that contain unsynchronized text\ntype UnsynchTextFrame struct {\n\tFrameHead\n\tDescTextFrame\n\tlanguage string\n}\n\nfunc NewUnsynchTextFrame(head FrameHead, data []byte) Framer {\n\tvar err error\n\tf := &UnsynchTextFrame{FrameHead: head}\n\n\tf.encoding = data[0]\n\tf.language = string(data[1:4])\n\n\tcutoff := 4\n\tif i := afterNullIndex(data[4:], f.encoding); i < 0 {\n\t\treturn nil\n\t} else {\n\t\tcutoff += i\n\t}\n\n\tif f.description, err = Decoders[f.encoding].ConvertString(string(data[4:cutoff])); err != nil {\n\t\treturn nil\n\t}\n\n\tif f.text, err = Decoders[f.encoding].ConvertString(string(data[cutoff:])); err != nil {\n\t\treturn nil\n\t}\n\n\treturn f\n}\n\nfunc (f UnsynchTextFrame) Language() string {\n\treturn f.language\n}\n\nfunc (f *UnsynchTextFrame) SetLanguage(language string) error {\n\tif len(language) != 3 {\n\t\treturn errors.New(\"language: invalid language string\")\n\t}\n\n\tf.language = language\n\treturn nil\n}\n\nfunc (f UnsynchTextFrame) String() string {\n\treturn fmt.Sprintf(\"%s\\t%s:\\n%s\", f.language, f.description, f.text)\n}\n\nfunc (f UnsynchTextFrame) Bytes() []byte {\n\tbytes := make([]byte, f.Size())\n\n\tencodedDescription, err := Encoders[f.encoding].ConvertString(f.description)\n\tif err != nil {\n\t\treturn bytes\n\t}\n\tencodedText, err := Encoders[f.encoding].ConvertString(f.text)\n\tif err != nil {\n\t\treturn bytes\n\t}\n\n\tbytes[0] = f.encoding\n\tcopy(bytes[1:4], []byte(f.language))\n\tindex := 4\n\tcopy(bytes[index:index+len(encodedDescription)], []byte(encodedDescription))\n\tindex += len(encodedDescription)\n\tcopy(bytes[index:index+len(encodedText)], []byte(encodedText))\n\n\treturn bytes\n}\n\n\/\/ ImageFrame represent frames that have media attached\ntype ImageFrame struct {\n\tFrameHead\n\tDataFrame\n\tencoding    byte\n\tmimeType    string\n\tpictureType byte\n\tdescription string\n}\n\nfunc NewImageFrame(head FrameHead, data []byte) Framer {\n\tf := &ImageFrame{FrameHead: head}\n\n\tvar err error\n\tencodingIndex := data[0]\n\n\tf.encoding = encodingIndex\n\n\tbuffer := bytes.NewBuffer(data[1:])\n\tif f.mimeType, err = buffer.ReadString(0); err != nil {\n\t\treturn nil\n\t}\n\n\tif f.pictureType, err = buffer.ReadByte(); err != nil {\n\t\treturn nil\n\t}\n\n\tbeginIndex := 1 + len(f.mimeType) + 1\n\tvar cutoff int\n\tif i := afterNullIndex(data[beginIndex:], f.encoding); i < 0 {\n\t\treturn nil\n\t} else {\n\t\tcutoff = beginIndex + i\n\t}\n\n\tif f.description, err = Decoders[encodingIndex].ConvertString(string(data[beginIndex:cutoff])); err != nil {\n\t\treturn nil\n\t}\n\n\tf.data = data[cutoff:]\n\n\treturn f\n}\n\nfunc (f ImageFrame) Encoding() string {\n\treturn encodingForIndex(f.encoding)\n}\n\nfunc (f *ImageFrame) SetEncoding(encoding string) error {\n\ti := byte(indexForEncoding(encoding))\n\tif i < 0 {\n\t\treturn errors.New(\"encoding: invalid encoding\")\n\t}\n\n\tf.encoding = i\n\treturn nil\n}\n\nfunc (f ImageFrame) MIMEType() string {\n\treturn f.mimeType\n}\n\nfunc (f *ImageFrame) SetMIMEType(mimeType string) {\n\tf.size += int32(len(mimeType)) - f.size\n\tif mimeType[len(mimeType)-1] != 0 {\n\t\tnullTermBytes := append([]byte(mimeType), 0x00)\n\t\tf.mimeType = string(nullTermBytes)\n\t\tf.size += 1\n\t} else {\n\t\tf.mimeType = mimeType\n\t}\n}\n\nfunc (f ImageFrame) String() string {\n\treturn fmt.Sprintf(\"%s\\t%s: <binary data>\", f.mimeType, f.description)\n}\n\nfunc (f ImageFrame) Bytes() []byte {\n\tbytes := make([]byte, f.Size())\n\n\tencodedDescription, err := Encoders[f.encoding].ConvertString(f.description)\n\tif err != nil {\n\t\treturn bytes\n\t}\n\n\tbytes[0] = f.encoding\n\tindex := 1\n\tcopy(bytes[index:index+len(f.mimeType)], []byte(f.mimeType))\n\tindex += len(f.mimeType)\n\tbytes[index] = f.pictureType\n\tindex += 1\n\tcopy(bytes[index:index+len(encodedDescription)], []byte(encodedDescription))\n\tindex += len(encodedDescription)\n\tcopy(bytes[index:index+len(f.data)], f.data)\n\n\treturn bytes\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2016 The etcd Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage e2e\n\nimport (\n\t\"net\/url\"\n\t\"testing\"\n)\n\nfunc TestCtlV3EndpointHealth(t *testing.T) { testCtl(t, endpointHealthTest, withQuorum()) }\nfunc TestCtlV3EndpointStatus(t *testing.T) { testCtl(t, endpointStatusTest, withQuorum()) }\nfunc TestCtlV3EndpointHealthWithAuth(t *testing.T) {\n\ttestCtl(t, endpointHealthTestWithAuth, withQuorum())\n}\n\nfunc endpointHealthTest(cx ctlCtx) {\n\tif err := ctlV3EndpointHealth(cx); err != nil {\n\t\tcx.t.Fatalf(\"endpointStatusTest ctlV3EndpointHealth error (%v)\", err)\n\t}\n}\n\nfunc ctlV3EndpointHealth(cx ctlCtx) error {\n\tcmdArgs := append(cx.PrefixArgs(), \"endpoint\", \"health\")\n\tlines := make([]string, cx.epc.cfg.clusterSize)\n\tfor i := range lines {\n\t\tlines[i] = \"is healthy\"\n\t}\n\treturn spawnWithExpects(cmdArgs, lines...)\n}\n\nfunc ctlV3EndpointHealthWithKey(cx ctlCtx, key string) error {\n\tcmdArgs := append(cx.PrefixArgs(), \"endpoint\", \"health\", \"--health-check-key\", key)\n\tlines := make([]string, cx.epc.cfg.clusterSize)\n\tfor i := range lines {\n\t\tlines[i] = \"is healthy\"\n\t}\n\treturn spawnWithExpects(cmdArgs, lines...)\n}\n\nfunc endpointStatusTest(cx ctlCtx) {\n\tif err := ctlV3EndpointStatus(cx); err != nil {\n\t\tcx.t.Fatalf(\"endpointStatusTest ctlV3EndpointStatus error (%v)\", err)\n\t}\n}\n\nfunc ctlV3EndpointStatus(cx ctlCtx) error {\n\tcmdArgs := append(cx.PrefixArgs(), \"endpoint\", \"status\")\n\tvar eps []string\n\tfor _, ep := range cx.epc.endpoints() {\n\t\tu, _ := url.Parse(ep)\n\t\teps = append(eps, u.Host)\n\t}\n\treturn spawnWithExpects(cmdArgs, eps...)\n}\n\nfunc ctlV3EndpointHealthFailPermissionDenied(cx ctlCtx) error {\n\tcmdArgs := append(cx.PrefixArgs(), \"endpoint\", \"health\")\n\tlines := make([]string, cx.epc.cfg.clusterSize)\n\tfor i := range lines {\n\t\tlines[i] = \"is unhealthy: failed to commit proposal: etcdserver: permission denied\"\n\t}\n\treturn spawnWithExpects(cmdArgs, lines...)\n}\n\nfunc endpointHealthTestWithAuth(cx ctlCtx) {\n\tif err := authEnable(cx); err != nil {\n\t\tcx.t.Fatal(err)\n\t}\n\n\tcx.user, cx.pass = \"root\", \"root\"\n\tauthSetupTestUser(cx)\n\n\tif err := ctlV3EndpointHealth(cx); err != nil {\n\t\tcx.t.Fatalf(\"endpointStatusTest ctlV3EndpointHealth error (%v)\", err)\n\t}\n\n\t\/\/ health checking with an ordinal user must fail because the user isn't granted a permission of the key \"health\"\n\tcx.user, cx.pass = \"test-user\", \"pass\"\n\tif err := ctlV3EndpointHealthFailPermissionDenied(cx); err != nil {\n\t\tcx.t.Fatalf(\"endpointStatusTest ctlV3EndpointHealth error (%v)\", err)\n\t}\n\n\tcx.user, cx.pass = \"root\", \"root\"\n\tif err := ctlV3RoleGrantPermission(cx, \"test-role\", grantingPerm{true, true, \"custom-key\", \"\", false}); err != nil {\n\t\tcx.t.Fatal(err)\n\t}\n\n\tcx.user, cx.pass = \"test-user\", \"pass\"\n\tif err := ctlV3EndpointHealthWithKey(cx, \"custom-key\"); err != nil {\n\t\tcx.t.Fatalf(\"endpointStatusTest ctlV3EndpointHealth error (%v)\", err)\n\t}\n}\n<commit_msg>e2e: check etcdctl endpoint health is healthy if denied permission to key<commit_after>\/\/ Copyright 2016 The etcd Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage e2e\n\nimport (\n\t\"net\/url\"\n\t\"testing\"\n)\n\nfunc TestCtlV3EndpointHealth(t *testing.T) { testCtl(t, endpointHealthTest, withQuorum()) }\nfunc TestCtlV3EndpointStatus(t *testing.T) { testCtl(t, endpointStatusTest, withQuorum()) }\nfunc TestCtlV3EndpointHealthWithAuth(t *testing.T) {\n\ttestCtl(t, endpointHealthTestWithAuth, withQuorum())\n}\n\nfunc endpointHealthTest(cx ctlCtx) {\n\tif err := ctlV3EndpointHealth(cx); err != nil {\n\t\tcx.t.Fatalf(\"endpointStatusTest ctlV3EndpointHealth error (%v)\", err)\n\t}\n}\n\nfunc ctlV3EndpointHealth(cx ctlCtx) error {\n\tcmdArgs := append(cx.PrefixArgs(), \"endpoint\", \"health\")\n\tlines := make([]string, cx.epc.cfg.clusterSize)\n\tfor i := range lines {\n\t\tlines[i] = \"is healthy\"\n\t}\n\treturn spawnWithExpects(cmdArgs, lines...)\n}\n\nfunc endpointStatusTest(cx ctlCtx) {\n\tif err := ctlV3EndpointStatus(cx); err != nil {\n\t\tcx.t.Fatalf(\"endpointStatusTest ctlV3EndpointStatus error (%v)\", err)\n\t}\n}\n\nfunc ctlV3EndpointStatus(cx ctlCtx) error {\n\tcmdArgs := append(cx.PrefixArgs(), \"endpoint\", \"status\")\n\tvar eps []string\n\tfor _, ep := range cx.epc.endpoints() {\n\t\tu, _ := url.Parse(ep)\n\t\teps = append(eps, u.Host)\n\t}\n\treturn spawnWithExpects(cmdArgs, eps...)\n}\n\nfunc endpointHealthTestWithAuth(cx ctlCtx) {\n\tif err := authEnable(cx); err != nil {\n\t\tcx.t.Fatal(err)\n\t}\n\n\tcx.user, cx.pass = \"root\", \"root\"\n\tauthSetupTestUser(cx)\n\n\tif err := ctlV3EndpointHealth(cx); err != nil {\n\t\tcx.t.Fatalf(\"endpointStatusTest ctlV3EndpointHealth error (%v)\", err)\n\t}\n\n\t\/\/ health checking with an ordinal user \"succeeds\" since permission denial goes through consensus\n\tcx.user, cx.pass = \"test-user\", \"pass\"\n\tif err := ctlV3EndpointHealth(cx); err != nil {\n\t\tcx.t.Fatalf(\"endpointStatusTest ctlV3EndpointHealth error (%v)\", err)\n\t}\n\n\t\/\/ succeed if permissions granted for ordinary user\n\tcx.user, cx.pass = \"root\", \"root\"\n\tif err := ctlV3RoleGrantPermission(cx, \"test-role\", grantingPerm{true, true, \"health\", \"\", false}); err != nil {\n\t\tcx.t.Fatal(err)\n\t}\n\tcx.user, cx.pass = \"test-user\", \"pass\"\n\tif err := ctlV3EndpointHealth(cx); err != nil {\n\t\tcx.t.Fatalf(\"endpointStatusTest ctlV3EndpointHealth error (%v)\", err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Package crawler implements asynchronous web sites crawler using interfaces\n\/\/ from tasker and ability to specify number of workers and size of tasks' buffer.\npackage crawler\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/fatih\/color\"\n\t\"github.com\/krasoffski\/gomill\/tasker\"\n)\n\nvar result = map[bool]string{\n\ttrue:  color.GreenString(\"PASS\"),\n\tfalse: color.RedString(\"FAIL\"),\n}\n\n\/\/ httpTask represents HTTP task with required for processing fields.\n\/\/ ok idecates that url is fetched without issues within timeout\n\/\/ url is URL to fetch\n\/\/ bsize is body size of response\n\/\/ start is start time of processing\n\/\/ client is http.Client with timeout\n\/\/ elapsed is elapsed time for processing\ntype httpTask struct {\n\tok      bool\n\turl     string\n\tbsize   int64\n\tstart   time.Time\n\tclient  *http.Client\n\telapsed time.Duration\n}\n\n\/\/ Process processes and fills required fields of HTTPTask.\nfunc (h *httpTask) Process() {\n\th.start = time.Now()\n\tresp, err := h.client.Get(h.url)\n\th.elapsed = time.Since(h.start)\n\n\tif err != nil {\n\t\th.ok = false\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\t\/\/ TODO: Think about handling error for Copy.\n\th.bsize, _ = io.Copy(ioutil.Discard, resp.Body)\n\n\tif resp.StatusCode == http.StatusOK {\n\t\th.ok = true\n\t\treturn\n\t}\n\th.ok = false\n}\n\n\/\/ Output prints out Task result to standart output.\nfunc (h *httpTask) Output() {\n\tsecs := color.BlueString(\"[%7.2fs]\", h.elapsed.Seconds())\n\tbsize := color.YellowString(\"[%10db]\", h.bsize)\n\tfmt.Printf(\"%s %s %s %s\\n\", result[h.ok], secs, bsize, h.url)\n}\n\ntype taskBuilder struct {\n\tsource     io.Reader\n\tbufSize    int\n\thttpClient *http.Client\n}\n\nfunc (tb *taskBuilder) BufSize() int {\n\treturn tb.bufSize\n}\n\nfunc (tb *taskBuilder) Create(url string) tasker.Task {\n\th := new(httpTask)\n\th.url = url\n\th.client = tb.httpClient\n\treturn h\n}\n\nfunc (tb *taskBuilder) Items() <-chan string {\n\turls := make(chan string, tb.bufSize)\n\ts := bufio.NewScanner(tb.source)\n\tgo func() {\n\t\tdefer close(urls)\n\t\tfor s.Scan() {\n\n\t\t\tline := strings.TrimSpace(s.Text())\n\n\t\t\tif line == \"\" || strings.HasPrefix(line, \"#\") {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\turls <- line\n\t\t}\n\t}()\n\tif s.Err() != nil {\n\t\tlog.Fatalf(\"error reading: %s\", s.Err())\n\t}\n\treturn urls\n}\n\n\/\/ Run creates tasks and process them with given number of workers.\nfunc (tb *taskBuilder) Run(workers int) {\n\ttasker.Run(tb, workers)\n}\n\n\/\/ New creates and initializes new task builder.\nfunc New(r io.Reader, bufSize int, client *http.Client) tasker.Builder {\n\tm := new(taskBuilder)\n\tm.source = r\n\tm.bufSize = bufSize\n\tm.httpClient = client\n\treturn m\n}\n<commit_msg>updated docstring for crawler<commit_after>\/\/ Package crawler implements asynchronous web sites crawler using interfaces\n\/\/ from tasker and ability to specify number of workers and size of tasks' buffer.\npackage crawler\n\nimport (\n\t\"bufio\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/fatih\/color\"\n\t\"github.com\/krasoffski\/gomill\/tasker\"\n)\n\nvar result = map[bool]string{\n\ttrue:  color.GreenString(\"PASS\"),\n\tfalse: color.RedString(\"FAIL\"),\n}\n\n\/\/ httpTask represents HTTP task with required for processing fields.\n\/\/ ok idecates that url is fetched without issues within timeout\n\/\/ url is URL to fetch\n\/\/ bsize is body size of response\n\/\/ start is start time of processing\n\/\/ client is http.Client with timeout\n\/\/ elapsed is elapsed time for processing\ntype httpTask struct {\n\tok      bool\n\turl     string\n\tbsize   int64\n\tstart   time.Time\n\tclient  *http.Client\n\telapsed time.Duration\n}\n\n\/\/ Process processes and fills required fields of HTTPTask.\nfunc (h *httpTask) Process() {\n\th.start = time.Now()\n\tresp, err := h.client.Get(h.url)\n\th.elapsed = time.Since(h.start)\n\n\tif err != nil {\n\t\th.ok = false\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\t\/\/ TODO: Think about handling error for Copy.\n\th.bsize, _ = io.Copy(ioutil.Discard, resp.Body)\n\n\tif resp.StatusCode == http.StatusOK {\n\t\th.ok = true\n\t\treturn\n\t}\n\th.ok = false\n}\n\n\/\/ Output prints out Task result to standart output.\nfunc (h *httpTask) Output() {\n\tsecs := color.BlueString(\"[%7.2fs]\", h.elapsed.Seconds())\n\tbsize := color.YellowString(\"[%10db]\", h.bsize)\n\tfmt.Printf(\"%s %s %s %s\\n\", result[h.ok], secs, bsize, h.url)\n}\n\ntype taskBuilder struct {\n\tsource     io.Reader\n\tbufSize    int\n\thttpClient *http.Client\n}\n\nfunc (tb *taskBuilder) BufSize() int {\n\treturn tb.bufSize\n}\n\nfunc (tb *taskBuilder) Create(url string) tasker.Task {\n\th := new(httpTask)\n\th.url = url\n\th.client = tb.httpClient\n\treturn h\n}\n\nfunc (tb *taskBuilder) Items() <-chan string {\n\turls := make(chan string, tb.bufSize)\n\ts := bufio.NewScanner(tb.source)\n\tgo func() {\n\t\tdefer close(urls)\n\t\tfor s.Scan() {\n\n\t\t\tline := strings.TrimSpace(s.Text())\n\n\t\t\tif line == \"\" || strings.HasPrefix(line, \"#\") {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\turls <- line\n\t\t}\n\t}()\n\tif s.Err() != nil {\n\t\tlog.Fatalf(\"error reading: %s\", s.Err())\n\t}\n\treturn urls\n}\n\n\/\/ Run processes the tasks which are created internally using Create method.\n\/\/ It blocks execution and waits till all tasks completed.\nfunc (tb *taskBuilder) Run(workers int) {\n\ttasker.Run(tb, workers)\n}\n\n\/\/ New creates and initializes new task builder.\nfunc New(r io.Reader, bufSize int, client *http.Client) tasker.Builder {\n\tm := new(taskBuilder)\n\tm.source = r\n\tm.bufSize = bufSize\n\tm.httpClient = client\n\treturn m\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"image\"\n\t\"image\/draw\"\n\t\"sync\"\n\n\t\"github.com\/as\/frame\"\n\t\"golang.org\/x\/exp\/shiny\/driver\"\n\t\"golang.org\/x\/exp\/shiny\/screen\"\n\t\"golang.org\/x\/mobile\/event\/key\"\n\t\"golang.org\/x\/mobile\/event\/lifecycle\"\n\t\"golang.org\/x\/mobile\/event\/mouse\"\n\t\"golang.org\/x\/mobile\/event\/paint\"\n\t\"golang.org\/x\/mobile\/event\/size\"\n)\n\nvar wg sync.WaitGroup\nvar winSize = image.Pt(1024, 768)\n\nfunc pt(e mouse.Event) image.Point {\n\treturn image.Pt(int(e.X), int(e.Y))\n}\n\nfunc main() {\n\tdriver.Main(func(src screen.Screen) {\n\t\tvar dirty = true\n\t\twind, _ := src.NewWindow(&screen.NewWindowOptions{winSize.X, winSize.Y, \"basic\"})\n\t\tb, _ := src.NewBuffer(winSize)\n\t\tdraw.Draw(b.RGBA(), b.Bounds(), frame.A.Back, image.ZP, draw.Src)\n\t\tfr := frame.New(b.RGBA(), b.Bounds(), nil)\n\t\tfr.Refresh()\n\t\twind.Send(paint.Event{})\n\t\tck := func() {\n\t\t\tif dirty || fr.Dirty() {\n\t\t\t\twind.Send(paint.Event{})\n\t\t\t}\n\t\t\tdirty = false\n\t\t}\n\n\t\tfor {\n\t\t\tswitch e := wind.NextEvent().(type) {\n\t\t\tcase mouse.Event:\n\t\t\t\tif e.Button == 1 && e.Direction == 1 {\n\t\t\t\t\tp0 := fr.IndexOf(pt(e))\n\t\t\t\t\tfr.Select(p0, p0)\n\t\t\t\t\tflush := func() {\n\t\t\t\t\t\twind.Upload(fr.Bounds().Min, b, fr.Bounds())\n\t\t\t\t\t\twind.Publish()\n\t\t\t\t\t}\n\t\t\t\t\tflush()\n\t\t\t\t\tfr.Sweep(wind, flush)\n\t\t\t\t\twind.Send(paint.Event{})\n\t\t\t\t}\n\t\t\tcase key.Event:\n\t\t\t\tif e.Direction == 2 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif e.Rune == '\\r' {\n\t\t\t\t\te.Rune = '\\n'\n\t\t\t\t}\n\t\t\t\tif e.Rune > 0x79 || e.Rune < 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tp0, p1 := fr.Dot()\n\t\t\t\tif e.Rune == '\\x08' {\n\t\t\t\t\tif p0 == p1 && p0 > 0 {\n\t\t\t\t\t\tp0--\n\t\t\t\t\t}\n\t\t\t\t\tfr.Delete(p0, p1)\n\t\t\t\t} else {\n\t\t\t\t\tfr.Insert([]byte{byte(e.Rune)}, p0)\n\t\t\t\t\tp0++\n\t\t\t\t}\n\t\t\t\tfr.Select(p0, p0)\n\t\t\t\tdirty = true\n\t\t\t\tck()\n\t\t\tcase size.Event:\n\t\t\t\twind.Upload(image.ZP, b, b.Bounds())\n\t\t\t\tfr.Refresh()\n\t\t\t\tck()\n\t\t\tcase paint.Event:\n\t\t\t\twind.Upload(fr.Bounds().Min, b, fr.Bounds())\n\t\t\t\tfr.Flush()\n\t\t\t\twind.Publish()\n\t\t\tcase lifecycle.Event:\n\t\t\t\tif e.To == lifecycle.StageDead {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t})\n}\n<commit_msg>frame: update basic example<commit_after>package main\n\nimport (\n\t\"image\"\n\t\"image\/draw\"\n\t\"sync\"\n\n\t\"github.com\/as\/frame\"\n\t\"golang.org\/x\/exp\/shiny\/driver\"\n\t\"golang.org\/x\/exp\/shiny\/screen\"\n\t\"golang.org\/x\/mobile\/event\/key\"\n\t\"golang.org\/x\/mobile\/event\/lifecycle\"\n\t\"golang.org\/x\/mobile\/event\/mouse\"\n\t\"golang.org\/x\/mobile\/event\/paint\"\n\t\"golang.org\/x\/mobile\/event\/size\"\n)\n\nvar wg sync.WaitGroup\nvar winSize = image.Pt(1024, 768)\n\nfunc pt(e mouse.Event) image.Point {\n\treturn image.Pt(int(e.X), int(e.Y))\n}\n\nfunc main() {\n\tdriver.Main(func(src screen.Screen) {\n\t\tvar dirty = true\n\t\twind, _ := src.NewWindow(&screen.NewWindowOptions{winSize.X, winSize.Y, \"basic\"})\n\t\tb, _ := src.NewBuffer(winSize)\n\t\tdraw.Draw(b.RGBA(), b.Bounds(), frame.A.Back, image.ZP, draw.Src)\n\t\tfr := frame.New(b.RGBA(), b.Bounds(), nil)\n\t\tfr.Refresh()\n\t\twind.Send(paint.Event{})\n\t\tck := func() {\n\t\t\tif dirty || fr.Dirty() {\n\t\t\t\twind.Send(paint.Event{})\n\t\t\t}\n\t\t\tdirty = false\n\t\t}\n\n\t\tfor {\n\t\t\tswitch e := wind.NextEvent().(type) {\n\t\t\tcase mouse.Event:\n\t\t\t\tif e.Button == 1 && e.Direction == 1 {\n\t\t\t\t\tp0 := fr.IndexOf(pt(e))\n\t\t\t\t\tfr.Select(p0, p0)\n\t\t\t\t\tflush := func() {\n\t\t\t\t\t\twind.Upload(fr.Bounds().Min, b, fr.Bounds())\n\t\t\t\t\t\twind.Publish()\n\t\t\t\t\t}\n\t\t\t\t\tflush()\n\t\t\t\t\tfr.Sweep(wind, flush)\n\t\t\t\t\twind.Send(paint.Event{})\n\t\t\t\t}\n\t\t\tcase key.Event:\n\t\t\t\tif e.Direction == 2 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif e.Rune == '\\r' {\n\t\t\t\t\te.Rune = '\\n'\n\t\t\t\t}\n\t\t\t\tp0, p1 := fr.Dot()\n\t\t\t\tif e.Rune > 0x79 || e.Rune < 0 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif e.Rune == '\\x08' {\n\t\t\t\t\tif p0 == p1 && p0 > 0 {\n\t\t\t\t\t\tp0--\n\t\t\t\t\t}\n\t\t\t\t\tfr.Delete(p0, p1)\n\t\t\t\t} else {\n\t\t\t\t\tif p0 != p1 {\n\t\t\t\t\t\tfr.Delete(p0, p1)\n\t\t\t\t\t}\n\t\t\t\t\tfr.Insert([]byte{byte(e.Rune)}, p0)\n\t\t\t\t}\n\t\t\t\tdirty = true\n\t\t\t\tck()\n\t\t\tcase size.Event:\n\t\t\t\twind.Upload(image.ZP, b, b.Bounds())\n\t\t\t\tfr.Refresh()\n\t\t\t\tck()\n\t\t\tcase paint.Event:\n\t\t\t\twind.Upload(fr.Bounds().Min, b, fr.Bounds())\n\t\t\t\tfr.Flush()\n\t\t\t\twind.Publish()\n\t\t\tcase lifecycle.Event:\n\t\t\t\tif e.To == lifecycle.StageDead {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>package govaluate\n\nimport (\n\t\"errors\"\n\t\"math\"\n\t\"time\"\n)\n\n\/*\n\tEvaluableExpression represents a set of ExpressionTokens which, taken together,\n\trepresent an arbitrary expression that can be evaluated down into a single value.\n*\/\ntype EvaluableExpression struct {\n\n\ttokens []ExpressionToken\n\tinputExpression string\n}\n\n\/*\n\tCreates a new EvaluableExpression from the given [expression] string.\n\tReturns an error if the given expression has invalid syntax.\n*\/\nfunc NewEvaluableExpression(expression string) (*EvaluableExpression, error) {\n\n\tvar ret *EvaluableExpression;\n\tvar err error\n\n\tret = new(EvaluableExpression)\n\tret.inputExpression = expression;\n\tret.tokens, err = parseTokens(expression)\n\n\tif(err != nil) {\n\t\treturn nil, err\n\t}\n\treturn ret, nil\n}\n\n\/*\n\tEvaluate runs the entire expression using the given [parameters]. \n\tEach parameter is mapped from a string to a value, such as \"foo\" = 1.0. \n\tIf the expression contains a reference to the variable \"foo\", it will be taken from parameters[\"foo\"].\n\n\tThis function returns errors if the combination of expression and parameters cannot be run,\n\tsuch as if a string parameter is given in an expression that expects it to be a boolean. \n\te.g., \"foo == true\", where foo is any string.\n\tThese errors are almost exclusively returned for parameters not being present, or being of the wrong type.\n\tStructural problems with the expression (unexpected tokens, unexpected end of expression, etc) are discovered\n\tduring parsing of the expression in NewEvaluableExpression.\n\n\tIn all non-error circumstances, this returns the single value result of the expression and parameters given.\n\te.g., if the expression is \"1 + 1\", Evaluate will return 2.0.\n\te.g., if the expression is \"foo + 1\" and parameters contains \"foo\" = 2, Evaluate will return 3.0\n*\/\nfunc (this EvaluableExpression) Evaluate(parameters map[string]interface{}) (interface{}, error) {\n\n\tvar stream *tokenStream;\n\n\tstream = newTokenStream(this.tokens);\n\treturn evaluateTokens(stream, parameters);\n}\n\nfunc evaluateTokens(stream *tokenStream, parameters map[string]interface{}) (interface{}, error) {\n\n\tif(stream.hasNext()) {\n\t\treturn evaluateLogical(stream, parameters);\n\t}\n\treturn nil, nil;\n}\n\nfunc evaluateLogical(stream *tokenStream, parameters map[string]interface{}) (interface{}, error) {\n\n\tvar token ExpressionToken;\n\tvar value interface{};\n\tvar symbol OperatorSymbol;\n\tvar err error;\n\tvar keyFound bool;\n\n\tvalue, err = evaluateComparator(stream, parameters);\t\n\n\tif(err != nil) {\n\t\treturn nil, err;\n\t}\n\n\tfor stream.hasNext() {\n\n\t\ttoken = stream.next();\n\n\t\tif(!isString(token.Value)) {\n\t\t\tbreak;\n\t\t}\n\n\t\tsymbol, keyFound = LOGICAL_SYMBOLS[token.Value.(string)];\n\t\tif(!keyFound) {\n\t\t\tbreak;\n\t\t}\n\n\t\tswitch(symbol) {\n\n\t\t\tcase OR\t\t:\tif(value != nil) {\n\t\t\t\t\t\t\treturn evaluateLogical(stream, parameters);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tvalue, err = evaluateComparator(stream, parameters);\n\t\t\t\t\t\t}\n\t\t\tcase AND\t:\tif(value == nil) {\n\t\t\t\t\t\t\treturn evaluateLogical(stream, parameters);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tvalue, err = evaluateComparator(stream, parameters);\n\t\t\t\t\t\t}\n\t\t}\n\n\t\tif(err != nil) {\n\t\t\treturn nil, err;\n\t\t}\n\t}\n\n\tstream.rewind();\n\treturn value, nil;\n}\n\nfunc evaluateComparator(stream *tokenStream, parameters map[string]interface{}) (interface{}, error) {\n\n\tvar token ExpressionToken;\n\tvar value, rightValue interface{};\n\tvar symbol OperatorSymbol;\n\tvar err error;\n\tvar keyFound bool;\n\n\tvalue, err = evaluateAdditiveModifier(stream, parameters);\n\n\tif(err != nil) {\n\t\treturn nil, err;\n\t}\n\n\tfor stream.hasNext() {\n\n\t\ttoken = stream.next();\n\n\t\tif(!isString(token.Value)) {\n\t\t\tbreak;\n\t\t}\n\n\t\tsymbol, keyFound = COMPARATOR_SYMBOLS[token.Value.(string)];\n\t\tif(!keyFound) {\n\t\t\tbreak\n\t\t}\n\n\t\trightValue, err = evaluateAdditiveModifier(stream, parameters);\n\t\tif(err != nil) {\n\t\t\treturn nil, err;\n\t\t}\n\n\t\tswitch(symbol) {\n\n\t\t\tcase LT\t\t:\treturn (value.(float64) < rightValue.(float64)), nil;\n\t\t\tcase LTE\t:\treturn (value.(float64) <= rightValue.(float64)), nil;\n\t\t\tcase GT\t\t:\treturn (value.(float64) > rightValue.(float64)), nil;\n\t\t\tcase GTE\t:\treturn (value.(float64) >= rightValue.(float64)), nil;\n\t\t\tcase EQ\t\t:\treturn (value == rightValue), nil;\n\t\t\tcase NEQ\t:\treturn (value != rightValue), nil;\n\t\t}\n\t}\n\n\tstream.rewind();\n\treturn value, nil;\n}\n\nfunc evaluateAdditiveModifier(stream *tokenStream, parameters map[string]interface{}) (interface{}, error) {\n\n\tvar token ExpressionToken;\n\tvar value, rightValue interface{};\n\tvar symbol OperatorSymbol;\n\tvar err error;\n\tvar keyFound bool;\n\n\tvalue, err = evaluateMultiplicativeModifier(stream, parameters);\n\n\tif(err != nil) {\n\t\treturn nil, err;\n\t}\n\n\tfor stream.hasNext() {\n\t\t\n\t\ttoken = stream.next();\n\n\t\tif(!isString(token.Value)) {\n\t\t\tbreak;\n\t\t}\n\n\t\tsymbol, keyFound = MODIFIER_SYMBOLS[token.Value.(string)];\n\t\tif(!keyFound) {\n\t\t\tbreak;\n\t\t}\n\n\t\tswitch(symbol) {\n\n\t\t\tcase PLUS\t:\trightValue, err = evaluateMultiplicativeModifier(stream, parameters);\n\t\t\t\t\t\tif(err != nil) {\n\t\t\t\t\t\t\treturn nil, err;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tvalue = value.(float64) + rightValue.(float64);\n\n\t\t\tcase MINUS\t:\trightValue, err = evaluateMultiplicativeModifier(stream, parameters);\n\t\t\t\t\t\tif(err != nil) {\n\t\t\t\t\t\t\treturn nil, err;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn value.(float64) - rightValue.(float64), nil;\n\n\t\t\tdefault\t\t:\tstream.rewind();\n\t\t\t\t\t\treturn value, nil;\n\t\t}\n\t}\n\n\tstream.rewind();\n\treturn value, nil;\n}\n\nfunc evaluateMultiplicativeModifier(stream *tokenStream, parameters map[string]interface{}) (interface{}, error) {\n\n\tvar token ExpressionToken;\n\tvar value, rightValue interface{};\n\tvar symbol OperatorSymbol;\n\tvar err error;\n\tvar keyFound bool;\n\n\tvalue, err = evaluateExponentialModifier(stream, parameters);\n\n\tif(err != nil) {\n\t\treturn nil, err;\n\t}\n\n\tfor stream.hasNext() {\n\n\t\ttoken = stream.next();\n\n\t\tif(!isString(token.Value)) {\n\t\t\tbreak;\n\t\t}\n\n\t\tsymbol, keyFound = MODIFIER_SYMBOLS[token.Value.(string)];\n\t\tif(!keyFound) {\n\t\t\tbreak;\n\t\t}\n\n\t\tswitch(symbol) {\n\n\t\t\tcase MULTIPLY\t:\trightValue, err = evaluateMultiplicativeModifier(stream, parameters);\n\t\t\t\t\t\tif(err != nil) {\n\t\t\t\t\t\t\treturn nil, err;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn value.(float64) * rightValue.(float64), nil;\n\n\t\t\tcase DIVIDE\t:\trightValue, err = evaluateMultiplicativeModifier(stream, parameters);\n\t\t\t\t\t\tif(err != nil) {\n\t\t\t\t\t\t\treturn nil, err;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn value.(float64) \/ rightValue.(float64), nil;\n\n\t\t\tcase MODULUS\t:\trightValue, err = evaluateMultiplicativeModifier(stream, parameters);\n\t\t\t\t\t\tif(err != nil) {\n\t\t\t\t\t\t\treturn nil, err;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn math.Mod(value.(float64), rightValue.(float64)), nil;\n\n\t\t\tdefault\t\t:\tstream.rewind();\n\t\t\t\t\t\treturn value, nil;\n\t\t}\n\t}\n\n\tstream.rewind();\t\n\treturn value, nil;\n}\n\nfunc evaluateExponentialModifier(stream *tokenStream, parameters map[string]interface{}) (interface{}, error) {\n\n\tvar token ExpressionToken;\n\tvar value, rightValue interface{};\n\tvar symbol OperatorSymbol;\n\tvar err error;\n\tvar keyFound bool;\n\n\tvalue, err = evaluateValue(stream, parameters);\n\n\tif(err != nil) {\n\t\treturn nil, err;\n\t}\n\n\tfor stream.hasNext() {\n\n\t\ttoken = stream.next();\n\n\t\tif(!isString(token.Value)) {\n\t\t\tbreak;\n\t\t}\n\n\t\tsymbol, keyFound = MODIFIER_SYMBOLS[token.Value.(string)];\n\t\tif(!keyFound) {\n\t\t\tbreak;\n\t\t}\n\n\t\tswitch(symbol) {\n\n\t\t\tcase EXPONENT\t:\trightValue, err = evaluateExponentialModifier(stream, parameters);\n\t\t\t\t\t\tif(err != nil) {\n\t\t\t\t\t\t\treturn nil, err;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn math.Pow(value.(float64), rightValue.(float64)), nil;\n\n\t\t\tdefault\t\t:\tstream.rewind();\n\t\t\t\t\t\treturn value, nil;\n\t\t}\n\t}\n\n\tstream.rewind();\t\n\treturn value, nil;\n}\n\nfunc evaluateValue(stream *tokenStream, parameters map[string]interface{}) (interface{}, error) {\n\n\tvar token ExpressionToken;\n\tvar value interface{};\n\tvar errorMessage, variableName string;\n\tvar err error;\n\n\ttoken = stream.next();\n\n\tswitch(token.Kind) {\n\n\t\tcase CLAUSE\t:\tvalue, err = evaluateTokens(stream, parameters);\n\t\t\t\t\tif(err != nil) {\n\t\t\t\t\t\treturn nil, err;\n\t\t\t\t\t}\n\n\t\t\t\t\ttoken = stream.next();\n\t\t\t\t\tif(token.Kind != CLAUSE_CLOSE) {\n\n\t\t\t\t\t\treturn nil, errors.New(\"Unbalanced parenthesis\");\n\t\t\t\t\t}\n\n\t\t\t\t\treturn value, nil;\n\n\t\tcase VARIABLE\t:\tvariableName = token.Value.(string);\n\t\t\t\t\tvalue = parameters[variableName];\n\n\t\t\t\t\tif(value == nil) {\n\t\t\t\t\t\terrorMessage = \"No parameter '\"+ variableName +\"' found.\"\n\t\t\t\t\t\treturn nil, errors.New(errorMessage);\n\t\t\t\t\t}\n\n\t\t\t\t\treturn value, nil;\n\n\t\tcase NUMERIC\t:\tfallthrough\n\t\tcase STRING\t:\tfallthrough\n\t\tcase BOOLEAN\t:\treturn token.Value, nil;\n\t\tcase TIME\t:\treturn float64(token.Value.(time.Time).Unix()), nil;\n\t\tdefault\t\t:\tbreak;\n\t}\n\n\tstream.rewind();\n\treturn nil, errors.New(\"Unable to evaluate token kind: \" + GetTokenKindString(token.Kind));\n}\n\n\/*\n\tReturns an array representing the ExpressionTokens that make up this expression.\n*\/\nfunc (this EvaluableExpression) Tokens() []ExpressionToken {\n\n\treturn this.tokens;\n}\n\n\/*\n\tReturns the original expression used to create this EvaluableExpression.\n*\/\nfunc (this EvaluableExpression) String() string {\n\n\treturn this.inputExpression;\n}\n\nfunc isString(value interface{}) bool {\n\n\tswitch value.(type) {\n\t\tcase string\t:\treturn true;\n\t\tdefault\t\t:\tbreak;\n\t}\n\treturn false;\n}\n<commit_msg>First implementation of sql query output<commit_after>package govaluate\n\nimport (\n\t\"fmt\"\n\t\"errors\"\n\t\"bytes\"\n\t\"math\"\n\t\"time\"\n)\n\n\/*\n\tEvaluableExpression represents a set of ExpressionTokens which, taken together,\n\trepresent an arbitrary expression that can be evaluated down into a single value.\n*\/\ntype EvaluableExpression struct {\n\n\t\/*\n\t\tRepresents the query format used to output dates. Typically only used when creating SQL or Mongo queries from an expression.\n\t\tDefaults to the complete ISO8601 format, including nanoseconds.\n\t*\/\n\tQueryDateFormat string;\n\n\ttokens []ExpressionToken\n\tinputExpression string\n}\n\n\/*\n\tCreates a new EvaluableExpression from the given [expression] string.\n\tReturns an error if the given expression has invalid syntax.\n*\/\nfunc NewEvaluableExpression(expression string) (*EvaluableExpression, error) {\n\n\tvar ret *EvaluableExpression;\n\tvar err error\n\n\tret = new(EvaluableExpression)\n\tret.QueryDateFormat = \"2006-01-02T15:04:05.999999999Z0700\";\n\tret.inputExpression = expression;\n\tret.tokens, err = parseTokens(expression)\n\n\tif(err != nil) {\n\t\treturn nil, err\n\t}\n\treturn ret, nil\n}\n\n\/*\n\tEvaluate runs the entire expression using the given [parameters]. \n\tEach parameter is mapped from a string to a value, such as \"foo\" = 1.0. \n\tIf the expression contains a reference to the variable \"foo\", it will be taken from parameters[\"foo\"].\n\n\tThis function returns errors if the combination of expression and parameters cannot be run,\n\tsuch as if a string parameter is given in an expression that expects it to be a boolean. \n\te.g., \"foo == true\", where foo is any string.\n\tThese errors are almost exclusively returned for parameters not being present, or being of the wrong type.\n\tStructural problems with the expression (unexpected tokens, unexpected end of expression, etc) are discovered\n\tduring parsing of the expression in NewEvaluableExpression.\n\n\tIn all non-error circumstances, this returns the single value result of the expression and parameters given.\n\te.g., if the expression is \"1 + 1\", Evaluate will return 2.0.\n\te.g., if the expression is \"foo + 1\" and parameters contains \"foo\" = 2, Evaluate will return 3.0\n*\/\nfunc (this EvaluableExpression) Evaluate(parameters map[string]interface{}) (interface{}, error) {\n\n\tvar stream *tokenStream;\n\n\tstream = newTokenStream(this.tokens);\n\treturn evaluateTokens(stream, parameters);\n}\n\nfunc evaluateTokens(stream *tokenStream, parameters map[string]interface{}) (interface{}, error) {\n\n\tif(stream.hasNext()) {\n\t\treturn evaluateLogical(stream, parameters);\n\t}\n\treturn nil, nil;\n}\n\nfunc evaluateLogical(stream *tokenStream, parameters map[string]interface{}) (interface{}, error) {\n\n\tvar token ExpressionToken;\n\tvar value interface{};\n\tvar symbol OperatorSymbol;\n\tvar err error;\n\tvar keyFound bool;\n\n\tvalue, err = evaluateComparator(stream, parameters);\t\n\n\tif(err != nil) {\n\t\treturn nil, err;\n\t}\n\n\tfor stream.hasNext() {\n\n\t\ttoken = stream.next();\n\n\t\tif(!isString(token.Value)) {\n\t\t\tbreak;\n\t\t}\n\n\t\tsymbol, keyFound = LOGICAL_SYMBOLS[token.Value.(string)];\n\t\tif(!keyFound) {\n\t\t\tbreak;\n\t\t}\n\n\t\tswitch(symbol) {\n\n\t\t\tcase OR\t\t:\tif(value != nil) {\n\t\t\t\t\t\t\treturn evaluateLogical(stream, parameters);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tvalue, err = evaluateComparator(stream, parameters);\n\t\t\t\t\t\t}\n\t\t\tcase AND\t:\tif(value == nil) {\n\t\t\t\t\t\t\treturn evaluateLogical(stream, parameters);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tvalue, err = evaluateComparator(stream, parameters);\n\t\t\t\t\t\t}\n\t\t}\n\n\t\tif(err != nil) {\n\t\t\treturn nil, err;\n\t\t}\n\t}\n\n\tstream.rewind();\n\treturn value, nil;\n}\n\nfunc evaluateComparator(stream *tokenStream, parameters map[string]interface{}) (interface{}, error) {\n\n\tvar token ExpressionToken;\n\tvar value, rightValue interface{};\n\tvar symbol OperatorSymbol;\n\tvar err error;\n\tvar keyFound bool;\n\n\tvalue, err = evaluateAdditiveModifier(stream, parameters);\n\n\tif(err != nil) {\n\t\treturn nil, err;\n\t}\n\n\tfor stream.hasNext() {\n\n\t\ttoken = stream.next();\n\n\t\tif(!isString(token.Value)) {\n\t\t\tbreak;\n\t\t}\n\n\t\tsymbol, keyFound = COMPARATOR_SYMBOLS[token.Value.(string)];\n\t\tif(!keyFound) {\n\t\t\tbreak\n\t\t}\n\n\t\trightValue, err = evaluateAdditiveModifier(stream, parameters);\n\t\tif(err != nil) {\n\t\t\treturn nil, err;\n\t\t}\n\n\t\tswitch(symbol) {\n\n\t\t\tcase LT\t\t:\treturn (value.(float64) < rightValue.(float64)), nil;\n\t\t\tcase LTE\t:\treturn (value.(float64) <= rightValue.(float64)), nil;\n\t\t\tcase GT\t\t:\treturn (value.(float64) > rightValue.(float64)), nil;\n\t\t\tcase GTE\t:\treturn (value.(float64) >= rightValue.(float64)), nil;\n\t\t\tcase EQ\t\t:\treturn (value == rightValue), nil;\n\t\t\tcase NEQ\t:\treturn (value != rightValue), nil;\n\t\t}\n\t}\n\n\tstream.rewind();\n\treturn value, nil;\n}\n\nfunc evaluateAdditiveModifier(stream *tokenStream, parameters map[string]interface{}) (interface{}, error) {\n\n\tvar token ExpressionToken;\n\tvar value, rightValue interface{};\n\tvar symbol OperatorSymbol;\n\tvar err error;\n\tvar keyFound bool;\n\n\tvalue, err = evaluateMultiplicativeModifier(stream, parameters);\n\n\tif(err != nil) {\n\t\treturn nil, err;\n\t}\n\n\tfor stream.hasNext() {\n\t\t\n\t\ttoken = stream.next();\n\n\t\tif(!isString(token.Value)) {\n\t\t\tbreak;\n\t\t}\n\n\t\tsymbol, keyFound = MODIFIER_SYMBOLS[token.Value.(string)];\n\t\tif(!keyFound) {\n\t\t\tbreak;\n\t\t}\n\n\t\tswitch(symbol) {\n\n\t\t\tcase PLUS\t:\trightValue, err = evaluateMultiplicativeModifier(stream, parameters);\n\t\t\t\t\t\tif(err != nil) {\n\t\t\t\t\t\t\treturn nil, err;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tvalue = value.(float64) + rightValue.(float64);\n\n\t\t\tcase MINUS\t:\trightValue, err = evaluateMultiplicativeModifier(stream, parameters);\n\t\t\t\t\t\tif(err != nil) {\n\t\t\t\t\t\t\treturn nil, err;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn value.(float64) - rightValue.(float64), nil;\n\n\t\t\tdefault\t\t:\tstream.rewind();\n\t\t\t\t\t\treturn value, nil;\n\t\t}\n\t}\n\n\tstream.rewind();\n\treturn value, nil;\n}\n\nfunc evaluateMultiplicativeModifier(stream *tokenStream, parameters map[string]interface{}) (interface{}, error) {\n\n\tvar token ExpressionToken;\n\tvar value, rightValue interface{};\n\tvar symbol OperatorSymbol;\n\tvar err error;\n\tvar keyFound bool;\n\n\tvalue, err = evaluateExponentialModifier(stream, parameters);\n\n\tif(err != nil) {\n\t\treturn nil, err;\n\t}\n\n\tfor stream.hasNext() {\n\n\t\ttoken = stream.next();\n\n\t\tif(!isString(token.Value)) {\n\t\t\tbreak;\n\t\t}\n\n\t\tsymbol, keyFound = MODIFIER_SYMBOLS[token.Value.(string)];\n\t\tif(!keyFound) {\n\t\t\tbreak;\n\t\t}\n\n\t\tswitch(symbol) {\n\n\t\t\tcase MULTIPLY\t:\trightValue, err = evaluateMultiplicativeModifier(stream, parameters);\n\t\t\t\t\t\tif(err != nil) {\n\t\t\t\t\t\t\treturn nil, err;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn value.(float64) * rightValue.(float64), nil;\n\n\t\t\tcase DIVIDE\t:\trightValue, err = evaluateMultiplicativeModifier(stream, parameters);\n\t\t\t\t\t\tif(err != nil) {\n\t\t\t\t\t\t\treturn nil, err;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn value.(float64) \/ rightValue.(float64), nil;\n\n\t\t\tcase MODULUS\t:\trightValue, err = evaluateMultiplicativeModifier(stream, parameters);\n\t\t\t\t\t\tif(err != nil) {\n\t\t\t\t\t\t\treturn nil, err;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn math.Mod(value.(float64), rightValue.(float64)), nil;\n\n\t\t\tdefault\t\t:\tstream.rewind();\n\t\t\t\t\t\treturn value, nil;\n\t\t}\n\t}\n\n\tstream.rewind();\t\n\treturn value, nil;\n}\n\nfunc evaluateExponentialModifier(stream *tokenStream, parameters map[string]interface{}) (interface{}, error) {\n\n\tvar token ExpressionToken;\n\tvar value, rightValue interface{};\n\tvar symbol OperatorSymbol;\n\tvar err error;\n\tvar keyFound bool;\n\n\tvalue, err = evaluateValue(stream, parameters);\n\n\tif(err != nil) {\n\t\treturn nil, err;\n\t}\n\n\tfor stream.hasNext() {\n\n\t\ttoken = stream.next();\n\n\t\tif(!isString(token.Value)) {\n\t\t\tbreak;\n\t\t}\n\n\t\tsymbol, keyFound = MODIFIER_SYMBOLS[token.Value.(string)];\n\t\tif(!keyFound) {\n\t\t\tbreak;\n\t\t}\n\n\t\tswitch(symbol) {\n\n\t\t\tcase EXPONENT\t:\trightValue, err = evaluateExponentialModifier(stream, parameters);\n\t\t\t\t\t\tif(err != nil) {\n\t\t\t\t\t\t\treturn nil, err;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn math.Pow(value.(float64), rightValue.(float64)), nil;\n\n\t\t\tdefault\t\t:\tstream.rewind();\n\t\t\t\t\t\treturn value, nil;\n\t\t}\n\t}\n\n\tstream.rewind();\t\n\treturn value, nil;\n}\n\nfunc evaluateValue(stream *tokenStream, parameters map[string]interface{}) (interface{}, error) {\n\n\tvar token ExpressionToken;\n\tvar value interface{};\n\tvar errorMessage, variableName string;\n\tvar err error;\n\n\ttoken = stream.next();\n\n\tswitch(token.Kind) {\n\n\t\tcase CLAUSE\t:\tvalue, err = evaluateTokens(stream, parameters);\n\t\t\t\t\tif(err != nil) {\n\t\t\t\t\t\treturn nil, err;\n\t\t\t\t\t}\n\n\t\t\t\t\ttoken = stream.next();\n\t\t\t\t\tif(token.Kind != CLAUSE_CLOSE) {\n\n\t\t\t\t\t\treturn nil, errors.New(\"Unbalanced parenthesis\");\n\t\t\t\t\t}\n\n\t\t\t\t\treturn value, nil;\n\n\t\tcase VARIABLE\t:\tvariableName = token.Value.(string);\n\t\t\t\t\tvalue = parameters[variableName];\n\n\t\t\t\t\tif(value == nil) {\n\t\t\t\t\t\terrorMessage = \"No parameter '\"+ variableName +\"' found.\"\n\t\t\t\t\t\treturn nil, errors.New(errorMessage);\n\t\t\t\t\t}\n\n\t\t\t\t\treturn value, nil;\n\n\t\tcase NUMERIC\t:\tfallthrough\n\t\tcase STRING\t:\tfallthrough\n\t\tcase BOOLEAN\t:\treturn token.Value, nil;\n\t\tcase TIME\t:\treturn float64(token.Value.(time.Time).Unix()), nil;\n\t\tdefault\t\t:\tbreak;\n\t}\n\n\tstream.rewind();\n\treturn nil, errors.New(\"Unable to evaluate token kind: \" + GetTokenKindString(token.Kind));\n}\n\n\/*\n\tReturns a string representing this expression as if it were written in SQL.\n\tThis function assumes that all parameters exist within the same table, and that the table essentially represents\n\ta serialized object of some sort (e.g., hibernate).\n\tIf your data model is more normalized, you may need to consider iterating through each actual token given by `Tokens()`\n\tto create your query.\n\n\tBoolean values are considered to be \"1\" for true, \"0\" for false.\n\n\tTimes are formatted according to this.QueryDateFormat.\n*\/\nfunc (this EvaluableExpression) ToSqlQuery() (string, error) {\n\n\tvar stream *tokenStream;\n\tvar token ExpressionToken;\n\tvar retBuffer bytes.Buffer;\n\tvar toWrite string;\n\n\tstream = newTokenStream(this.tokens);\n\n\tfor(stream.hasNext()) {\n\n\t\ttoken = stream.next();\n\n\t\tswitch(token.Kind) {\n\n\t\t\tcase STRING\t\t:\ttoWrite = fmt.Sprintf(\"'%s'\", token.Value);\n\t\t\tcase TIME\t\t:\ttoWrite = fmt.Sprintf(\"'%s'\", token.Value.(time.Time).Format(this.QueryDateFormat));\n\t\t\t\n\t\t\tcase LOGICALOP\t\t:\tswitch(LOGICAL_SYMBOLS[token.Value.(string)]) {\n\n\t\t\t\t\t\t\t\tcase AND\t:\ttoWrite = \" AND \";\n\t\t\t\t\t\t\t\tcase OR\t\t:\ttoWrite = \" OR \";\n\t\t\t\t\t\t\t}\n\n\t\t\tcase BOOLEAN\t\t:\tif(token.Value.(bool)) {\n\t\t\t\t\t\t\t\ttoWrite = \"1\";\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\ttoWrite = \"0\";\n\t\t\t\t\t\t\t}\n\n\t\t\tcase VARIABLE\t\t:\tfallthrough\n\t\t\tcase COMPARATOR\t\t:\tfallthrough\t\n\t\t\tcase MODIFIER\t\t:\tfallthrough\n\t\t\tcase NUMERIC \t\t:\tfallthrough\n\t\t\tcase CLAUSE\t\t:\tfallthrough\n\t\t\tcase CLAUSE_CLOSE\t:\ttoWrite = token.Value.(string);\t\n\n\t\t\tdefault\t\t\t:\ttoWrite = fmt.Sprintf(\"Unrecognized query token '%s' of kind '%s'\", token.Value, token.Kind);\n\t\t\t\t\t\t\treturn \"\", errors.New(toWrite);\n\t\t}\n\n\t\tretBuffer.WriteString(toWrite);\n\t}\n\n\treturn retBuffer.String(), nil;\n}\n\n\/*\n\tReturns an array representing the ExpressionTokens that make up this expression.\n*\/\nfunc (this EvaluableExpression) Tokens() []ExpressionToken {\n\n\treturn this.tokens;\n}\n\n\/*\n\tReturns the original expression used to create this EvaluableExpression.\n*\/\nfunc (this EvaluableExpression) String() string {\n\n\treturn this.inputExpression;\n}\n\nfunc isString(value interface{}) bool {\n\n\tswitch value.(type) {\n\t\tcase string\t:\treturn true;\n\t\tdefault\t\t:\tbreak;\n\t}\n\treturn false;\n}\n<|endoftext|>"}
{"text":"<commit_before>package gelf\n\nimport (\n\t\"bytes\"\n\t\"compress\/zlib\"\n\t\"errors\"\n\t\"fmt\"\n\t\"math\/rand\"\n\t\"net\"\n\t\"os\"\n\t\"time\"\n)\n\n\/* ----- *\/\n\nconst (\n\tVERSION_1_1 = \"1.1\"\n)\n\n\/* ----- *\/\n\ntype Config struct {\n\tEnabled      bool   `json:\"enabled\"`\n\tNet          string `json:\"net\"`\n\tAddr         string `json:\"addr\"`\n\tWorkers      int    `json:\"workers\"`\n\tEcho         bool   `json:\"echo\"`\n\tHost         string `json:\"host\"`\n\tCompress     bool   `json:\"compress\"`\n\tMaxChunkSize int    `json:\"max_chunk_size\"`\n}\n\n\/* ----- *\/\n\ntype Event interface {\n\tToJson() ([]byte, error)\n}\n\ntype BaseEvent struct {\n\tVersion      string `json:\"version\"`\n\tHost         string `json:\"host\"`\n\tFacility     string `json:\"facility\",omitempty`\n\tShortMessage string `json:\"short_message\"`\n\tFullMessage  string `json:\"full_message,omitempty\"`\n}\n\nfunc (e *BaseEvent) Init(shortMessage string) {\n\te.Version = VERSION_1_1\n\te.Host = gHost\n\te.ShortMessage = shortMessage\n}\n\nfunc (e *BaseEvent) InitWithFacility(facility string, shortMessage string) {\n\te.Version = VERSION_1_1\n\te.Host = gHost\n\te.Facility = facility\n\te.ShortMessage = shortMessage\n}\n\n\/* ----- *\/\n\nfunc NewBaseEvent() BaseEvent {\n\treturn BaseEvent{Version: VERSION_1_1, Host: gHost}\n}\n\nfunc GetVersion() string {\n\treturn VERSION_1_1\n}\n\nfunc GetHost() string {\n\treturn gHost\n}\n\n\/* ----- *\/\n\nvar gSendChannel chan []byte\nvar gHost string\n\nfunc Start(config Config) (err error) {\n\tif !config.Enabled {\n\t\tfmt.Printf(\"GELF logging is disabled\\n\")\n\t\treturn nil\n\t}\n\n\tif len(config.Net) == 0 {\n\t\treturn errors.New(\"Missing network family\")\n\t}\n\n\tif len(config.Addr) == 0 {\n\t\treturn errors.New(\"Missing address\")\n\t}\n\n\tif config.Workers == 0 {\n\t\tconfig.Workers = 4\n\t} else if config.Workers < 1 || config.Workers > 16 {\n\t\treturn fmt.Errorf(\"Bad worker count %d\", config.Workers)\n\t}\n\n\tif config.MaxChunkSize == 0 {\n\t\tconfig.MaxChunkSize = 1400\n\t} else if config.MaxChunkSize < 100 || config.MaxChunkSize > 8192 {\n\t\treturn fmt.Errorf(\"Bad max chunk size %d\", config.MaxChunkSize)\n\t}\n\n\traddr, err := net.ResolveUDPAddr(config.Net, config.Addr)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tconn, err := net.DialUDP(config.Net, nil, raddr)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tfmt.Printf(\"GELF logger start, net = %s, addr = %s\\n\", config.Net, config.Addr)\n\n\tif len(config.Host) == 0 {\n\t\tconfig.Host, err = os.Hostname()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tfmt.Printf(\"GELF host = %q\\n\", config.Host)\n\t}\n\n\tgSendChannel = make(chan []byte, 16)\n\tgHost = config.Host\n\n\tfor i := 0; i < config.Workers; i++ {\n\t\tw, err := newWorker(gSendChannel, conn, config)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tgo w.run()\n\t}\n\n\terr = nil\n\treturn\n}\n\n\/* ----- *\/\n\nfunc SendBytes(packet []byte) {\n\tif gSendChannel != nil {\n\t\tselect {\n\t\tcase gSendChannel <- packet:\n\t\t}\n\t}\n}\n\nfunc SendString(packet string) {\n\tSendBytes([]byte(packet))\n}\n\nfunc SendEvent(event Event) {\n\tb, err := event.ToJson()\n\tif err != nil {\n\t\treportError(err)\n\t}\n\n\tSendBytes(b)\n}\n\n\/* ----- *\/\n\ntype worker struct {\n\tc      chan []byte\n\tconn   *net.UDPConn\n\tconfig Config\n\n\tzbuf    bytes.Buffer\n\tzwriter *zlib.Writer\n\n\trand *rand.Rand\n\tid   []byte\n\tcbuf bytes.Buffer\n}\n\nfunc newWorker(c chan []byte, conn *net.UDPConn, config Config) (*worker, error) {\n\tw := &worker{c: gSendChannel, conn: conn, config: config}\n\tw.zwriter = zlib.NewWriter(&w.zbuf)\n\tw.rand = rand.New(rand.NewSource(time.Now().UnixNano()))\n\tw.id = make([]byte, 8, 8)\n\treturn w, nil\n}\n\nfunc (w *worker) run() {\n\tfor {\n\t\tpacket := <-w.c\n\n\t\tif w.config.Echo {\n\t\t\tfmt.Printf(\"gelf <- [%d] %s\\n\", len(packet), string(packet))\n\t\t}\n\n\t\tvar err error\n\t\tvar tosend []byte\n\t\tif w.config.Compress {\n\t\t\ttosend, err = w.compress(packet)\n\t\t\tif err != nil {\n\t\t\t\treportError(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t} else {\n\t\t\ttosend = packet\n\t\t}\n\n\t\ttotal := len(tosend)\n\t\tmax := w.config.MaxChunkSize\n\n\t\tif total > max {\n\t\t\t\/\/ Need to break into chunks\n\t\t\tchunkCount := (total + max - 1) \/ max\n\n\t\t\tif chunkCount > 128 {\n\t\t\t\treportError(errors.New(\"packet has too many chunks\"))\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tchunkOffset := 0\n\t\t\tw.rand.Read(w.id)\n\n\t\t\tfor chunk := 0; chunk < chunkCount; chunk++ {\n\t\t\t\tw.cbuf.Reset()\n\t\t\t\t\/\/ magic header\n\t\t\t\tw.cbuf.WriteByte(0x1e)\n\t\t\t\tw.cbuf.WriteByte(0x0f)\n\t\t\t\t\/\/ id\n\t\t\t\tw.cbuf.Write(w.id)\n\t\t\t\t\/\/ chunk number and count\n\t\t\t\tw.cbuf.WriteByte(byte(chunk))\n\t\t\t\tw.cbuf.WriteByte(byte(chunkCount))\n\t\t\t\t\/\/ actual data\n\t\t\t\tchunkLen := total - chunkOffset\n\t\t\t\tif chunkLen > max {\n\t\t\t\t\tchunkLen = max\n\t\t\t\t}\n\t\t\t\tsl := tosend[chunkOffset : chunkOffset+chunkLen]\n\t\t\t\tw.cbuf.Write(sl)\n\t\t\t\t\/\/ send\n\t\t\t\tw.conn.Write(w.cbuf.Bytes())\n\t\t\t\t\/\/ next!\n\t\t\t\tchunkOffset = chunkOffset + max\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ Chunking is not needed\n\t\t\tw.conn.Write(tosend)\n\t\t}\n\t}\n}\n\nfunc (w *worker) compress(src []byte) ([]byte, error) {\n\tw.zbuf.Reset()\n\tw.zwriter.Reset(&w.zbuf)\n\n\tn, err := w.zwriter.Write(src)\n\tif n != len(src) {\n\t\treturn nil, fmt.Errorf(\"Could only write %d of %d bytes\", n, len(src))\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tw.zwriter.Close()\n\treturn w.zbuf.Bytes(), nil\n}\n\nfunc reportError(err error) {\n\tfmt.Println(err)\n}\n<commit_msg>show the host in the general startup message, not separate<commit_after>package gelf\n\nimport (\n\t\"bytes\"\n\t\"compress\/zlib\"\n\t\"errors\"\n\t\"fmt\"\n\t\"math\/rand\"\n\t\"net\"\n\t\"os\"\n\t\"time\"\n)\n\n\/* ----- *\/\n\nconst (\n\tVERSION_1_1 = \"1.1\"\n)\n\n\/* ----- *\/\n\ntype Config struct {\n\tEnabled      bool   `json:\"enabled\"`\n\tNet          string `json:\"net\"`\n\tAddr         string `json:\"addr\"`\n\tWorkers      int    `json:\"workers\"`\n\tEcho         bool   `json:\"echo\"`\n\tHost         string `json:\"host\"`\n\tCompress     bool   `json:\"compress\"`\n\tMaxChunkSize int    `json:\"max_chunk_size\"`\n}\n\n\/* ----- *\/\n\ntype Event interface {\n\tToJson() ([]byte, error)\n}\n\ntype BaseEvent struct {\n\tVersion      string `json:\"version\"`\n\tHost         string `json:\"host\"`\n\tFacility     string `json:\"facility\",omitempty`\n\tShortMessage string `json:\"short_message\"`\n\tFullMessage  string `json:\"full_message,omitempty\"`\n}\n\nfunc (e *BaseEvent) Init(shortMessage string) {\n\te.Version = VERSION_1_1\n\te.Host = gHost\n\te.ShortMessage = shortMessage\n}\n\nfunc (e *BaseEvent) InitWithFacility(facility string, shortMessage string) {\n\te.Version = VERSION_1_1\n\te.Host = gHost\n\te.Facility = facility\n\te.ShortMessage = shortMessage\n}\n\n\/* ----- *\/\n\nfunc NewBaseEvent() BaseEvent {\n\treturn BaseEvent{Version: VERSION_1_1, Host: gHost}\n}\n\nfunc GetVersion() string {\n\treturn VERSION_1_1\n}\n\nfunc GetHost() string {\n\treturn gHost\n}\n\n\/* ----- *\/\n\nvar gSendChannel chan []byte\nvar gHost string\n\nfunc Start(config Config) (err error) {\n\tif !config.Enabled {\n\t\tfmt.Printf(\"GELF logging is disabled\\n\")\n\t\treturn nil\n\t}\n\n\tif len(config.Net) == 0 {\n\t\treturn errors.New(\"Missing network family\")\n\t}\n\n\tif len(config.Addr) == 0 {\n\t\treturn errors.New(\"Missing address\")\n\t}\n\n\tif config.Workers == 0 {\n\t\tconfig.Workers = 4\n\t} else if config.Workers < 1 || config.Workers > 16 {\n\t\treturn fmt.Errorf(\"Bad worker count %d\", config.Workers)\n\t}\n\n\tif config.MaxChunkSize == 0 {\n\t\tconfig.MaxChunkSize = 1400\n\t} else if config.MaxChunkSize < 100 || config.MaxChunkSize > 8192 {\n\t\treturn fmt.Errorf(\"Bad max chunk size %d\", config.MaxChunkSize)\n\t}\n\n\traddr, err := net.ResolveUDPAddr(config.Net, config.Addr)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tconn, err := net.DialUDP(config.Net, nil, raddr)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif len(config.Host) == 0 {\n\t\tconfig.Host, err = os.Hostname()\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\n\tfmt.Printf(\"GELF logger start, host = %s, sending to to net = %s, addr = %s\\n\", config.Host, config.Net, config.Addr)\n\n\tgSendChannel = make(chan []byte, 16)\n\tgHost = config.Host\n\n\tfor i := 0; i < config.Workers; i++ {\n\t\tw, err := newWorker(gSendChannel, conn, config)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tgo w.run()\n\t}\n\n\terr = nil\n\treturn\n}\n\n\/* ----- *\/\n\nfunc SendBytes(packet []byte) {\n\tif gSendChannel != nil {\n\t\tselect {\n\t\tcase gSendChannel <- packet:\n\t\t}\n\t}\n}\n\nfunc SendString(packet string) {\n\tSendBytes([]byte(packet))\n}\n\nfunc SendEvent(event Event) {\n\tb, err := event.ToJson()\n\tif err != nil {\n\t\treportError(err)\n\t}\n\n\tSendBytes(b)\n}\n\n\/* ----- *\/\n\ntype worker struct {\n\tc      chan []byte\n\tconn   *net.UDPConn\n\tconfig Config\n\n\tzbuf    bytes.Buffer\n\tzwriter *zlib.Writer\n\n\trand *rand.Rand\n\tid   []byte\n\tcbuf bytes.Buffer\n}\n\nfunc newWorker(c chan []byte, conn *net.UDPConn, config Config) (*worker, error) {\n\tw := &worker{c: gSendChannel, conn: conn, config: config}\n\tw.zwriter = zlib.NewWriter(&w.zbuf)\n\tw.rand = rand.New(rand.NewSource(time.Now().UnixNano()))\n\tw.id = make([]byte, 8, 8)\n\treturn w, nil\n}\n\nfunc (w *worker) run() {\n\tfor {\n\t\tpacket := <-w.c\n\n\t\tif w.config.Echo {\n\t\t\tfmt.Printf(\"gelf <- [%d] %s\\n\", len(packet), string(packet))\n\t\t}\n\n\t\tvar err error\n\t\tvar tosend []byte\n\t\tif w.config.Compress {\n\t\t\ttosend, err = w.compress(packet)\n\t\t\tif err != nil {\n\t\t\t\treportError(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t} else {\n\t\t\ttosend = packet\n\t\t}\n\n\t\ttotal := len(tosend)\n\t\tmax := w.config.MaxChunkSize\n\n\t\tif total > max {\n\t\t\t\/\/ Need to break into chunks\n\t\t\tchunkCount := (total + max - 1) \/ max\n\n\t\t\tif chunkCount > 128 {\n\t\t\t\treportError(errors.New(\"packet has too many chunks\"))\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tchunkOffset := 0\n\t\t\tw.rand.Read(w.id)\n\n\t\t\tfor chunk := 0; chunk < chunkCount; chunk++ {\n\t\t\t\tw.cbuf.Reset()\n\t\t\t\t\/\/ magic header\n\t\t\t\tw.cbuf.WriteByte(0x1e)\n\t\t\t\tw.cbuf.WriteByte(0x0f)\n\t\t\t\t\/\/ id\n\t\t\t\tw.cbuf.Write(w.id)\n\t\t\t\t\/\/ chunk number and count\n\t\t\t\tw.cbuf.WriteByte(byte(chunk))\n\t\t\t\tw.cbuf.WriteByte(byte(chunkCount))\n\t\t\t\t\/\/ actual data\n\t\t\t\tchunkLen := total - chunkOffset\n\t\t\t\tif chunkLen > max {\n\t\t\t\t\tchunkLen = max\n\t\t\t\t}\n\t\t\t\tsl := tosend[chunkOffset : chunkOffset+chunkLen]\n\t\t\t\tw.cbuf.Write(sl)\n\t\t\t\t\/\/ send\n\t\t\t\tw.conn.Write(w.cbuf.Bytes())\n\t\t\t\t\/\/ next!\n\t\t\t\tchunkOffset = chunkOffset + max\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ Chunking is not needed\n\t\t\tw.conn.Write(tosend)\n\t\t}\n\t}\n}\n\nfunc (w *worker) compress(src []byte) ([]byte, error) {\n\tw.zbuf.Reset()\n\tw.zwriter.Reset(&w.zbuf)\n\n\tn, err := w.zwriter.Write(src)\n\tif n != len(src) {\n\t\treturn nil, fmt.Errorf(\"Could only write %d of %d bytes\", n, len(src))\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tw.zwriter.Close()\n\treturn w.zbuf.Bytes(), nil\n}\n\nfunc reportError(err error) {\n\tfmt.Println(err)\n}\n<|endoftext|>"}
{"text":"<commit_before>package xdebugproxy\n\nimport (\n\t\"github.com\/dfeyer\/flow-debugproxy\/config\"\n\t\"github.com\/dfeyer\/flow-debugproxy\/logger\"\n\t\"github.com\/dfeyer\/flow-debugproxy\/pathmapper\"\n\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n)\n\nconst h = \"%s\"\n\n\/\/ Proxy represents a pair of connections and their state\ntype Proxy struct {\n\tsentBytes     uint64\n\treceivedBytes uint64\n\tRaddr         *net.TCPAddr\n\tLconn, rconn  *net.TCPConn\n\tPathMapper    *pathmapper.PathMapper\n\tConfig        *config.Config\n\tpipeErrors    chan error\n}\n\nfunc (p *Proxy) log(s string, args ...interface{}) {\n\tif p.Config.Verbose {\n\t\tlogger.Info(s, args...)\n\t}\n}\n\n\/\/ Start the proxy\nfunc (p *Proxy) Start() {\n\tdefer p.Lconn.Close()\n\n\t\/\/ connect to remote\n\trconn, err := net.DialTCP(\"tcp\", nil, p.Raddr)\n\tif err != nil {\n\t\tp.log(h, \"Unable to connect to your IDE, please check if your editor listen to incoming connection\")\n\t\tp.log(\"Error message: %s\", err)\n\t\tp.log(h, \"Configure your IDE and reload the web page should solve this issue\")\n\t\tp.log(h, \"\\nHit Ctrl-C to exit the proxy if don't need it ...\")\n\t\tp.log(h, \"\\nYour fellow Umpa Lumpa\")\n\t\treturn\n\t}\n\n\tp.rconn = rconn\n\tdefer p.rconn.Close()\n\n\tp.pipeErrors = make(chan error)\n\tdefer close(p.pipeErrors)\n\n\t\/\/ display both ends\n\tp.log(\"Opened %s >>> %s\", p.Lconn.RemoteAddr().String(), p.rconn.RemoteAddr().String())\n\t\/\/ bidirectional copy\n\tgo p.pipe(p.Lconn, p.rconn)\n\tgo p.pipe(p.rconn, p.Lconn)\n\n\tif err = <-p.pipeErrors; err != io.EOF {\n\t\tlogger.Warn(h, err)\n\t}\n\t<-p.pipeErrors\n\n\tp.log(\"Closed (%d bytes sent, %d bytes recieved)\", p.sentBytes, p.receivedBytes)\n}\n\nfunc (p *Proxy) pipe(src, dst *net.TCPConn) {\n\t\/\/ data direction\n\tvar f, h string\n\tisFromDebugger := src == p.Lconn\n\tif isFromDebugger {\n\t\tf = \"\\nDebugger >>> IDE\\n================\"\n\t} else {\n\t\tf = \"\\nIDE >>> Debugger\\n================\"\n\t}\n\th = \"%s\"\n\t\/\/ directional copy (64k buffer)\n\tbuff := make([]byte, 0xffff)\n\tfor {\n\t\tn, err := src.Read(buff)\n\t\tif err != nil {\n\t\t\tp.pipeErrors <- err\n\t\t\t\/\/ make sure the other pipe will stop as well\n\t\t\tdst.Close()\n\t\t\treturn\n\t\t}\n\t\tb := buff[:n]\n\t\tp.log(h, f)\n\t\tif p.Config.VeryVerbose {\n\t\t\tif isFromDebugger {\n\t\t\t\tp.log(\"Raw protocol:\\n%s\\n\", logger.Colorize(fmt.Sprintf(h, b), \"blue\"))\n\t\t\t} else {\n\t\t\t\tp.log(\"Raw protocol:\\n%s\\n\", logger.Colorize(fmt.Sprintf(h, logger.FormatTextProtocol(b)), \"blue\"))\n\t\t\t}\n\t\t}\n\t\t\/\/ extract command name\n\t\tif isFromDebugger {\n\t\t\tb = p.PathMapper.ApplyMappingToXML(b)\n\t\t} else {\n\t\t\tb = p.PathMapper.ApplyMappingToTextProtocol(b)\n\t\t}\n\t\t\/\/ show output\n\t\tif p.Config.VeryVerbose {\n\t\t\tif isFromDebugger {\n\t\t\t\tp.log(\"Processed protocol:\\n%s\\n\", logger.Colorize(fmt.Sprintf(h, b), \"blue\"))\n\t\t\t} else {\n\t\t\t\tp.log(\"Processed protocol:\\n%s\\n\", logger.Colorize(fmt.Sprintf(h, logger.FormatTextProtocol(b)), \"blue\"))\n\t\t\t}\n\t\t} else {\n\t\t\tp.log(h, \"\")\n\t\t}\n\t\t\/\/ write out result\n\t\tn, err = dst.Write(b)\n\t\tif err != nil {\n\t\t\tp.pipeErrors <- err\n\t\t\t\/\/ make sure the other pipe will stop as well\n\t\t\tsrc.Close()\n\t\t\treturn\n\t\t}\n\t\tif isFromDebugger {\n\t\t\tp.sentBytes += uint64(n)\n\t\t} else {\n\t\t\tp.receivedBytes += uint64(n)\n\t\t}\n\t}\n}\n<commit_msg>[TASK] Code cleanup<commit_after>package xdebugproxy\n\nimport (\n\t\"github.com\/dfeyer\/flow-debugproxy\/config\"\n\t\"github.com\/dfeyer\/flow-debugproxy\/logger\"\n\t\"github.com\/dfeyer\/flow-debugproxy\/pathmapper\"\n\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n)\n\nconst h = \"%s\"\n\n\/\/ Proxy represents a pair of connections and their state\ntype Proxy struct {\n\tsentBytes     uint64\n\treceivedBytes uint64\n\tRaddr         *net.TCPAddr\n\tLconn, rconn  *net.TCPConn\n\tPathMapper    *pathmapper.PathMapper\n\tConfig        *config.Config\n\tpipeErrors    chan error\n}\n\nfunc (p *Proxy) log(s string, args ...interface{}) {\n\tif p.Config.Verbose {\n\t\tlogger.Info(s, args...)\n\t}\n}\n\n\/\/ Start the proxy\nfunc (p *Proxy) Start() {\n\tdefer p.Lconn.Close()\n\n\t\/\/ connect to remote\n\trconn, err := net.DialTCP(\"tcp\", nil, p.Raddr)\n\tif err != nil {\n\t\tp.log(h, \"Unable to connect to your IDE, please check if your editor listen to incoming connection\")\n\t\tp.log(\"Error message: %s\", err)\n\t\tp.log(h, \"Configure your IDE and reload the web page should solve this issue\")\n\t\tp.log(h, \"\\nHit Ctrl-C to exit the proxy if don't need it ...\")\n\t\tp.log(h, \"\\nYour fellow Umpa Lumpa\")\n\t\treturn\n\t}\n\n\tp.rconn = rconn\n\tdefer p.rconn.Close()\n\n\tp.pipeErrors = make(chan error)\n\tdefer close(p.pipeErrors)\n\n\t\/\/ display both ends\n\tp.log(\"Opened %s >>> %s\", p.Lconn.RemoteAddr().String(), p.rconn.RemoteAddr().String())\n\t\/\/ bidirectional copy\n\tgo p.pipe(p.Lconn, p.rconn)\n\tgo p.pipe(p.rconn, p.Lconn)\n\n\tif err = <-p.pipeErrors; err != io.EOF {\n\t\tlogger.Warn(h, err)\n\t}\n\t<-p.pipeErrors\n\n\tp.log(\"Closed (%d bytes sent, %d bytes recieved)\", p.sentBytes, p.receivedBytes)\n}\n\nfunc (p *Proxy) pipe(src, dst *net.TCPConn) {\n\t\/\/ data direction\n\tvar f, h string\n\tisFromDebugger := src == p.Lconn\n\tif isFromDebugger {\n\t\tf = \"\\nDebugger >>> IDE\\n================\"\n\t} else {\n\t\tf = \"\\nIDE >>> Debugger\\n================\"\n\t}\n\t\/\/ directional copy (64k buffer)\n\tbuff := make([]byte, 0xffff)\n\tfor {\n\t\tn, err := src.Read(buff)\n\t\tif err != nil {\n\t\t\tp.pipeErrors <- err\n\t\t\t\/\/ make sure the other pipe will stop as well\n\t\t\tdst.Close()\n\t\t\treturn\n\t\t}\n\t\tb := buff[:n]\n\t\tp.log(h, f)\n\t\tif p.Config.VeryVerbose {\n\t\t\tif isFromDebugger {\n\t\t\t\tp.log(\"Raw protocol:\\n%s\\n\", logger.Colorize(fmt.Sprintf(h, b), \"blue\"))\n\t\t\t} else {\n\t\t\t\tp.log(\"Raw protocol:\\n%s\\n\", logger.Colorize(fmt.Sprintf(h, logger.FormatTextProtocol(b)), \"blue\"))\n\t\t\t}\n\t\t}\n\t\t\/\/ extract command name\n\t\tif isFromDebugger {\n\t\t\tb = p.PathMapper.ApplyMappingToXML(b)\n\t\t} else {\n\t\t\tb = p.PathMapper.ApplyMappingToTextProtocol(b)\n\t\t}\n\t\t\/\/ show output\n\t\tif p.Config.VeryVerbose {\n\t\t\tif isFromDebugger {\n\t\t\t\tp.log(\"Processed protocol:\\n%s\\n\", logger.Colorize(fmt.Sprintf(h, b), \"blue\"))\n\t\t\t} else {\n\t\t\t\tp.log(\"Processed protocol:\\n%s\\n\", logger.Colorize(fmt.Sprintf(h, logger.FormatTextProtocol(b)), \"blue\"))\n\t\t\t}\n\t\t} else {\n\t\t\tp.log(h, \"\")\n\t\t}\n\t\t\/\/ write out result\n\t\tn, err = dst.Write(b)\n\t\tif err != nil {\n\t\t\tp.pipeErrors <- err\n\t\t\t\/\/ make sure the other pipe will stop as well\n\t\t\tsrc.Close()\n\t\t\treturn\n\t\t}\n\t\tif isFromDebugger {\n\t\t\tp.sentBytes += uint64(n)\n\t\t} else {\n\t\t\tp.receivedBytes += uint64(n)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package eval\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"io\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strconv\"\n\t\"strings\"\n)\n\ntype stream struct {\n\tin  io.Reader\n\tout io.Writer\n\terr io.Writer\n}\n\nvar builtins map[string]func(context.Context, stream, []string, *Evaluator, []string) error\n\nfunc init() {\n\tbuiltins = map[string]func(context.Context, stream, []string, *Evaluator, []string) error{\n\t\t\"cd\":      cd,\n\t\t\"echo\":    echo,\n\t\t\"exit\":    exit,\n\t\t\"setenv\":  setenv,\n\t\t\"setpath\": setpath,\n\t\t\"let\":     let,\n\t}\n}\n\nfunc cd(_ context.Context, _ stream, env []string, _ *Evaluator, args []string) error {\n\tvar dir string\n\tswitch len(args) {\n\tcase 0:\n\t\tdir = os.Getenv(\"HOME\")\n\tcase 1:\n\t\tdir = args[0]\n\tdefault:\n\t\treturn errors.New(\"too many arguments\")\n\t}\n\treturn os.Chdir(dir)\n}\n\nfunc echo(ctx context.Context, s stream, env []string, _ *Evaluator, args []string) error {\n\tif len(args) == 0 {\n\t\t_, err := s.out.Write([]byte{'\\n'})\n\t\treturn err\n\t}\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn nil\n\tdefault:\n\t}\n\t_, err := io.WriteString(s.out, args[0])\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(args) == 1 {\n\t\t_, err := s.out.Write([]byte{'\\n'})\n\t\treturn err\n\t}\n\targs = args[1:]\n\tfor _, arg := range args {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil\n\t\tdefault:\n\t\t}\n\t\t_, err := s.out.Write([]byte{' '})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = io.WriteString(s.out, arg)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t_, err = s.out.Write([]byte{'\\n'})\n\treturn err\n}\n\nfunc exit(_ context.Context, _ stream, env []string, e *Evaluator, args []string) error {\n\tvar code int\n\tswitch len(args) {\n\tcase 0:\n\t\t\/\/FIXME: exit with no args should use the exit code of the last command executed.\n\t\tcode = 0\n\tcase 1:\n\t\ti, err := strconv.Atoi(args[0])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcode = i\n\tdefault:\n\t\treturn errors.New(\"too many arguments\")\n\t}\n\te.ExitCh <- code\n\treturn nil\n}\n\nfunc setenv(_ context.Context, _ stream, env []string, _ *Evaluator, args []string) error {\n\tif len(args)%2 == 1 {\n\t\treturn errors.New(\"need even arguments\")\n\t}\n\tfor i := 0; i < len(args); i += 2 {\n\t\tos.Setenv(args[i], args[i+1])\n\t}\n\treturn nil\n}\n\nfunc setpath(_ context.Context, _ stream, env []string, _ *Evaluator, args []string) error {\n\tswitch len(args) {\n\tcase 0:\n\t\treturn errors.New(\"need 1 or more arguments\")\n\t}\n\tpaths := strings.Split(os.Getenv(\"PATH\"), \":\")\n\tvar newPaths []string\n\tfor _, path := range paths {\n\t\tif contains(args, path) {\n\t\t\tcontinue\n\t\t}\n\t\tnewPaths = append(newPaths, path)\n\t}\n\tnewPaths = append(args, newPaths...)\n\tos.Setenv(\"PATH\", strings.Join(newPaths, \":\"))\n\treturn nil\n}\n\nfunc let(ctx context.Context, s stream, env []string, e *Evaluator, args []string) error {\n\tn := getIndex(args, \"in\")\n\tif n < 0 {\n\t\treturn errors.New(\"expecting 'in', but not found\")\n\t}\n\tif n == len(args)-1 {\n\t\treturn errors.New(\"expecting command name after 'in'\")\n\t}\n\tif n%2 == 1 {\n\t\treturn errors.New(\"'let ... in' should have even number of arguments\")\n\t}\n\tnewEnv := make([]string, 0, n\/2)\n\tfor i := 0; i < n; i += 2 {\n\t\tnewEnv = append(newEnv, args[i]+\"=\"+args[i+1])\n\t}\n\tname := args[n+1]\n\t\/\/ Builtin command is not supported.\n\t\/\/ For instance, `let ... in cd` does actually execute \/usr\/bin\/cd.\n\tcmd := exec.CommandContext(ctx, name, args[n+2:]...)\n\tcmd.Env = append(env, newEnv...)\n\tcmd.Stdin = s.in\n\tcmd.Stdout = s.out\n\tcmd.Stderr = s.err\n\treturn cmd.Run()\n}\n\nfunc getIndex(x []string, s string) int {\n\tfor i := range x {\n\t\tif x[i] == s {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}\n\nfunc contains(x []string, s string) bool {\n\tfor i := range x {\n\t\tif x[i] == s {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n<commit_msg>Add 'exec' builtin command<commit_after>package eval\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"io\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strconv\"\n\t\"strings\"\n\t\"syscall\"\n)\n\ntype stream struct {\n\tin  io.Reader\n\tout io.Writer\n\terr io.Writer\n}\n\nvar builtins map[string]func(context.Context, stream, []string, *Evaluator, []string) error\n\nfunc init() {\n\tbuiltins = map[string]func(context.Context, stream, []string, *Evaluator, []string) error{\n\t\t\"cd\":      cd,\n\t\t\"echo\":    echo,\n\t\t\"exit\":    exit,\n\t\t\"setenv\":  setenv,\n\t\t\"setpath\": setpath,\n\t\t\"let\":     let,\n\t\t\"exec\":    execCmd,\n\t}\n}\n\nfunc cd(_ context.Context, _ stream, env []string, _ *Evaluator, args []string) error {\n\tvar dir string\n\tswitch len(args) {\n\tcase 0:\n\t\tdir = os.Getenv(\"HOME\")\n\tcase 1:\n\t\tdir = args[0]\n\tdefault:\n\t\treturn errors.New(\"too many arguments\")\n\t}\n\treturn os.Chdir(dir)\n}\n\nfunc echo(ctx context.Context, s stream, env []string, _ *Evaluator, args []string) error {\n\tif len(args) == 0 {\n\t\t_, err := s.out.Write([]byte{'\\n'})\n\t\treturn err\n\t}\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn nil\n\tdefault:\n\t}\n\t_, err := io.WriteString(s.out, args[0])\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(args) == 1 {\n\t\t_, err := s.out.Write([]byte{'\\n'})\n\t\treturn err\n\t}\n\targs = args[1:]\n\tfor _, arg := range args {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn nil\n\t\tdefault:\n\t\t}\n\t\t_, err := s.out.Write([]byte{' '})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = io.WriteString(s.out, arg)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\t_, err = s.out.Write([]byte{'\\n'})\n\treturn err\n}\n\nfunc exit(_ context.Context, _ stream, env []string, e *Evaluator, args []string) error {\n\tvar code int\n\tswitch len(args) {\n\tcase 0:\n\t\t\/\/FIXME: exit with no args should use the exit code of the last command executed.\n\t\tcode = 0\n\tcase 1:\n\t\ti, err := strconv.Atoi(args[0])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcode = i\n\tdefault:\n\t\treturn errors.New(\"too many arguments\")\n\t}\n\te.ExitCh <- code\n\treturn nil\n}\n\nfunc setenv(_ context.Context, _ stream, env []string, _ *Evaluator, args []string) error {\n\tif len(args)%2 == 1 {\n\t\treturn errors.New(\"need even arguments\")\n\t}\n\tfor i := 0; i < len(args); i += 2 {\n\t\tos.Setenv(args[i], args[i+1])\n\t}\n\treturn nil\n}\n\nfunc setpath(_ context.Context, _ stream, env []string, _ *Evaluator, args []string) error {\n\tswitch len(args) {\n\tcase 0:\n\t\treturn errors.New(\"need 1 or more arguments\")\n\t}\n\tpaths := strings.Split(os.Getenv(\"PATH\"), \":\")\n\tvar newPaths []string\n\tfor _, path := range paths {\n\t\tif contains(args, path) {\n\t\t\tcontinue\n\t\t}\n\t\tnewPaths = append(newPaths, path)\n\t}\n\tnewPaths = append(args, newPaths...)\n\tos.Setenv(\"PATH\", strings.Join(newPaths, \":\"))\n\treturn nil\n}\n\nfunc let(ctx context.Context, s stream, env []string, e *Evaluator, args []string) error {\n\tn := getIndex(args, \"in\")\n\tif n < 0 {\n\t\treturn errors.New(\"expecting 'in', but not found\")\n\t}\n\tif n == len(args)-1 {\n\t\treturn errors.New(\"expecting command name after 'in'\")\n\t}\n\tif n%2 == 1 {\n\t\treturn errors.New(\"'let ... in' should have even number of arguments\")\n\t}\n\tnewEnv := make([]string, 0, n\/2)\n\tfor i := 0; i < n; i += 2 {\n\t\tnewEnv = append(newEnv, args[i]+\"=\"+args[i+1])\n\t}\n\tname := args[n+1]\n\t\/\/ Builtin command is not supported.\n\t\/\/ For instance, `let ... in cd` does actually execute \/usr\/bin\/cd.\n\tcmd := exec.CommandContext(ctx, name, args[n+2:]...)\n\tcmd.Env = append(env, newEnv...)\n\tcmd.Stdin = s.in\n\tcmd.Stdout = s.out\n\tcmd.Stderr = s.err\n\treturn cmd.Run()\n}\n\nfunc getIndex(x []string, s string) int {\n\tfor i := range x {\n\t\tif x[i] == s {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}\n\nfunc contains(x []string, s string) bool {\n\tfor i := range x {\n\t\tif x[i] == s {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc execCmd(ctx context.Context, s stream, env []string, e *Evaluator, args []string) error {\n\tif len(args) == 0 {\n\t\treturn errors.New(\"1 or more arguments required\")\n\t}\n\tname, err := exec.LookPath(args[0])\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn syscall.Exec(name, append([]string{name}, args[1:]...), env)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"github.com\/hekmon\/transmissionrpc\"\n\tlog \"github.com\/sirupsen\/logrus\"\n\t\"gopkg.in\/h2non\/gock.v1\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"testing\"\n)\n\nfunc TestAdditionalLocationArguments(t *testing.T) {\n\ttables := []struct {\n\t\tinput            string\n\t\targs             additionalArguments\n\t\tstrippedLocation string\n\t\terr              error\n\t}{\n\t\t{\"\/home\/user\", additionalArguments{}, \"\/home\/user\", nil},\n\t\t{\"\/home\/user\/\", additionalArguments{}, \"\/home\/user\/\", nil},\n\t\t{\"\/home\/user\/+s\", additionalArguments{sequentialDownload: ARGUMENT_TRUE}, \"\/home\/user\/\", nil},\n\t\t{\"\/home\/user+s\", additionalArguments{sequentialDownload: ARGUMENT_TRUE}, \"\/home\/user\", nil},\n\t\t{\"\/home\/user+data\", additionalArguments{}, \"\/home\/user+data\", nil},\n\t\t{\"\/home\/user+data+s\", additionalArguments{sequentialDownload: ARGUMENT_TRUE}, \"\/home\/user+data\", nil},\n\t\t{\"\/home\/user+s\/\", additionalArguments{}, \"\/home\/user+s\/\", nil},\n\t\t{\"\/home\/user\/+f\", additionalArguments{firstLastPiecesFirst: ARGUMENT_TRUE}, \"\/home\/user\/\", nil},\n\t\t{\"\/home\/user\/+sf\", additionalArguments{sequentialDownload: ARGUMENT_TRUE, firstLastPiecesFirst: ARGUMENT_TRUE},\n\t\t\t\"\/home\/user\/\", nil},\n\t\t{\"\/home\/user\/+h\", additionalArguments{skipChecking: ARGUMENT_TRUE}, \"\/home\/user\/\", nil},\n\t\t{\"\/home\/user\/-s\", additionalArguments{sequentialDownload: ARGUMENT_FALSE}, \"\/home\/user\/\", nil},\n\t\t{\"\/home\/user\/-sh\", additionalArguments{sequentialDownload: ARGUMENT_FALSE, skipChecking: ARGUMENT_FALSE}, \"\/home\/user\/\", nil},\n\t\t{\"C:\\\\Users\\\\+s\\\\\", additionalArguments{}, \"C:\\\\Users\\\\+s\\\\\", nil},\n\t\t{\"C:\\\\Users\\\\+s\", additionalArguments{sequentialDownload: ARGUMENT_TRUE}, \"C:\\\\Users\\\\\", nil},\n\t}\n\n\tfor _, table := range tables {\n\t\targs, location, err := parseAdditionalLocationArguments(table.input)\n\t\tif args != table.args || location != table.strippedLocation || err != table.err {\n\t\t\tt.Errorf(\"Input %s, expected (%+v, %s, %v), got: (%+v, %s, %v)\", table.input,\n\t\t\t\ttable.args, table.strippedLocation, table.err,\n\t\t\t\targs, location, err)\n\t\t}\n\t}\n}\n\nfunc TestTorrentListing(t *testing.T) {\n\tconst apiAddr = \"http:\/\/localhost:8080\"\n\tlog.SetLevel(log.DebugLevel)\n\n\tdefer gock.Off()\n\n\tgock.New(apiAddr).\n\t\tGet(\"\/api\/v2\/torrents\/info\").\n\t\tReply(200).\n\t\tFile(\"testdata\/torrent_list.json\")\n\n\tgock.New(apiAddr).\n\t\tPost(\"\/api\/v2\/auth\/login\").\n\t\tReply(200).\n\t\tSetHeader(\"Set-Cookie\", \"SID=1\")\n\n\t\/\/ 1\n\tsetUpMocks(apiAddr, \"cf7da7ab4d4e6125567bd979994f13bb1f23dddd\", \"1\")\n\n\t\/\/ 2\n\tsetUpMocks(apiAddr, \"842783e3005495d5d1637f5364b59343c7844707\", \"2\")\n\n\tclient := &http.Client{Transport: &http.Transport{}}\n\tgock.InterceptClient(client)\n\n\tqBTConn.Init(apiAddr, client, false)\n\tserver := httptest.NewServer(http.HandlerFunc(handler))\n\tdefer server.Close()\n\tdefer server.CloseClientConnections()\n\tserverAddr := server.Listener.Addr().(*net.TCPAddr)\n\tprintln(serverAddr.IP.String())\n\n\ttransmissionbt, err := transmissionrpc.New(serverAddr.IP.String(), \"\", \"\",\n\t\t&transmissionrpc.AdvancedConfig{Port: uint16(serverAddr.Port)})\n\tCheck(err)\n\ttorrents, err := transmissionbt.TorrentGetAll()\n\tCheck(err)\n\tif len(torrents) != 2 {\n\t\tt.Fail()\n\t}\n\tif *torrents[0].Name != \"ubuntu-18.04.2-desktop-amd64.iso\" {\n\t\tt.Fail()\n\t}\n\tif *torrents[1].Name != \"ubuntu-18.04.2-live-server-amd64.iso\" {\n\t\tt.Fail()\n\t}\n}\n\nfunc TestSyncing(t *testing.T) {\n\tconst apiAddr = \"http:\/\/localhost:8080\"\n\tlog.SetLevel(log.DebugLevel)\n\n\tdefer gock.Off()\n\n\tgock.New(apiAddr).\n\t\tPost(\"\/api\/v2\/auth\/login\").\n\t\tReply(200).\n\t\tSetHeader(\"Set-Cookie\", \"SID=1\")\n\n\tgock.New(apiAddr).\n\t\tGet(\"\/api\/v2\/sync\/maindata\").\n\t\tMatchParam(\"rid\", \"0\").\n\t\tHeaderPresent(\"Cookie\").\n\t\tReply(200).\n\t\tFile(\"testdata\/sync_initial.json\")\n\n\tgock.New(apiAddr).\n\t\tGet(\"\/api\/v2\/sync\/maindata\").\n\t\tMatchParam(\"rid\", \"1\").\n\t\tHeaderPresent(\"Cookie\").\n\t\tReply(200).\n\t\tFile(\"testdata\/sync_1.json\")\n\n\tgock.New(apiAddr).\n\t\tGet(\"\/api\/v2\/sync\/maindata\").\n\t\tMatchParam(\"rid\", \"2\").\n\t\tHeaderPresent(\"Cookie\").\n\t\tReply(200).\n\t\tFile(\"testdata\/sync_2.json\")\n\n\tgock.New(apiAddr).\n\t\tGet(\"\/api\/v2\/sync\/maindata\").\n\t\tMatchParam(\"rid\", \"3\").\n\t\tHeaderPresent(\"Cookie\").\n\t\tReply(200).\n\t\tFile(\"testdata\/sync_3.json\")\n\n\tgock.New(apiAddr).\n\t\tGet(\"\/api\/v2\/sync\/maindata\").\n\t\tMatchParam(\"rid\", \"4\").\n\t\tHeaderPresent(\"Cookie\").\n\t\tReply(200).\n\t\tFile(\"testdata\/sync_4.json\")\n\n\t\/\/ 1\n\tsetUpMocks(apiAddr, \"cf7da7ab4d4e6125567bd979994f13bb1f23dddd\", \"1\")\n\n\t\/\/ 2\n\tsetUpMocks(apiAddr, \"842783e3005495d5d1637f5364b59343c7844707\", \"2\")\n\n\t\/\/ 3\n\tsetUpMocks(apiAddr, \"7a1448be6d15bcde08ee9915350d0725775b73a3\", \"3\")\n\n\tclient := &http.Client{Transport: &http.Transport{}}\n\tgock.InterceptClient(client)\n\n\tqBTConn.Init(apiAddr, client, true)\n\tserver := httptest.NewServer(http.HandlerFunc(handler))\n\tdefer server.Close()\n\tdefer server.CloseClientConnections()\n\tserverAddr := server.Listener.Addr().(*net.TCPAddr)\n\tprintln(serverAddr.IP.String())\n\n\ttransmissionbt, err := transmissionrpc.New(serverAddr.IP.String(), \"\", \"\",\n\t\t&transmissionrpc.AdvancedConfig{Port: uint16(serverAddr.Port)})\n\tCheck(err)\n\ttorrents, err := transmissionbt.TorrentGetAll()\n\tCheck(err)\n\tif len(torrents) != 2 {\n\t\tt.Error(\"Number of torrents is not equal to 2\")\n\t}\n\tif *torrents[0].Name != \"ubuntu-18.04.2-live-server-amd64.iso\" && *torrents[0].Name != \"ubuntu-18.04.2-desktop-amd64.iso\" {\n\t\tt.Error(\"Unexpected torrent 0\")\n\t}\n\tif *torrents[1].Name != \"ubuntu-18.04.2-desktop-amd64.iso\" && *torrents[1].Name != \"ubuntu-18.04.2-live-server-amd64.iso\" {\n\t\tt.Error(\"Unexpected torrent 1\")\n\t}\n\n\ttorrents, err = transmissionbt.TorrentGetAll()\n\tCheck(err)\n\tif len(torrents) != 2 {\n\t\tt.Error(\"Number of torrents is not equal to 2\")\n\t}\n\n\ttorrents, err = transmissionbt.TorrentGetAll()\n\tCheck(err)\n\tif len(torrents) != 3 {\n\t\tt.Error(\"Number of torrents is not equal to 3\")\n\t}\n\n\ttorrents, err = transmissionbt.TorrentGetAll()\n\tCheck(err)\n\tif len(torrents) != 3 {\n\t\tt.Error(\"Number of torrents is not equal to 3\")\n\t}\n\n\ttorrents, err = transmissionbt.TorrentGetAll()\n\tCheck(err)\n\tif len(torrents) != 2 {\n\t\tt.Error(\"Number of torrents is not equal to 2\")\n\t}\n}\n\nfunc setUpMocks(apiAddr string, hash string, name string) {\n\tgock.New(apiAddr).\n\t\tGet(\"\/api\/v2\/torrents\/properties\").\n\t\tMatchParam(\"hash\", hash).\n\t\tPersist().\n\t\tReply(200).\n\t\tFile(\"testdata\/torrent_\" + name + \"_properties.json\")\n\tgock.New(apiAddr).\n\t\tGet(\"\/api\/v2\/torrents\/trackers\").\n\t\tMatchParam(\"hash\", hash).\n\t\tPersist().\n\t\tReply(200).\n\t\tFile(\"testdata\/torrent_\" + name + \"_trackers.json\")\n\tgock.New(apiAddr).\n\t\tGet(\"\/api\/v2\/torrents\/pieceStates\").\n\t\tMatchParam(\"hash\", hash).\n\t\tPersist().\n\t\tReply(200).\n\t\tFile(\"testdata\/torrent_\" + name + \"_piecestates.json\")\n\tgock.New(apiAddr).\n\t\tGet(\"\/api\/v2\/torrents\/files\").\n\t\tMatchParam(\"hash\", hash).\n\t\tPersist().\n\t\tReply(200).\n\t\tFile(\"testdata\/torrent_\" + name + \"_files.json\")\n\tgock.New(apiAddr).\n\t\tGet(\"\/api\/v2\/sync\/torrentPeers\").\n\t\tMatchParam(\"hash\", hash).\n\t\tMatchParam(\"rid\", \"0\").\n\t\tPersist().\n\t\tReply(200).\n\t\tFile(\"testdata\/torrent_\" + name + \"_peers.json\")\n}\n<commit_msg>Test improvements<commit_after>package main\n\nimport (\n\t\"github.com\/hekmon\/transmissionrpc\"\n\tlog \"github.com\/sirupsen\/logrus\"\n\t\"gopkg.in\/h2non\/gock.v1\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"testing\"\n)\n\nfunc TestAdditionalLocationArguments(t *testing.T) {\n\ttables := []struct {\n\t\tinput            string\n\t\targs             additionalArguments\n\t\tstrippedLocation string\n\t\terr              error\n\t}{\n\t\t{\"\/home\/user\", additionalArguments{}, \"\/home\/user\", nil},\n\t\t{\"\/home\/user\/\", additionalArguments{}, \"\/home\/user\/\", nil},\n\t\t{\"\/home\/user\/+s\", additionalArguments{sequentialDownload: ARGUMENT_TRUE}, \"\/home\/user\/\", nil},\n\t\t{\"\/home\/user+s\", additionalArguments{sequentialDownload: ARGUMENT_TRUE}, \"\/home\/user\", nil},\n\t\t{\"\/home\/user+data\", additionalArguments{}, \"\/home\/user+data\", nil},\n\t\t{\"\/home\/user+data+s\", additionalArguments{sequentialDownload: ARGUMENT_TRUE}, \"\/home\/user+data\", nil},\n\t\t{\"\/home\/user+s\/\", additionalArguments{}, \"\/home\/user+s\/\", nil},\n\t\t{\"\/home\/user\/+f\", additionalArguments{firstLastPiecesFirst: ARGUMENT_TRUE}, \"\/home\/user\/\", nil},\n\t\t{\"\/home\/user\/+sf\", additionalArguments{sequentialDownload: ARGUMENT_TRUE, firstLastPiecesFirst: ARGUMENT_TRUE},\n\t\t\t\"\/home\/user\/\", nil},\n\t\t{\"\/home\/user\/+h\", additionalArguments{skipChecking: ARGUMENT_TRUE}, \"\/home\/user\/\", nil},\n\t\t{\"\/home\/user\/-s\", additionalArguments{sequentialDownload: ARGUMENT_FALSE}, \"\/home\/user\/\", nil},\n\t\t{\"\/home\/user\/-sh\", additionalArguments{sequentialDownload: ARGUMENT_FALSE, skipChecking: ARGUMENT_FALSE}, \"\/home\/user\/\", nil},\n\t\t{\"C:\\\\Users\\\\+s\\\\\", additionalArguments{}, \"C:\\\\Users\\\\+s\\\\\", nil},\n\t\t{\"C:\\\\Users\\\\+s\", additionalArguments{sequentialDownload: ARGUMENT_TRUE}, \"C:\\\\Users\\\\\", nil},\n\t}\n\n\tfor _, table := range tables {\n\t\targs, location, err := parseAdditionalLocationArguments(table.input)\n\t\tif args != table.args || location != table.strippedLocation || err != table.err {\n\t\t\tt.Errorf(\"Input %s, expected (%+v, %s, %v), got: (%+v, %s, %v)\", table.input,\n\t\t\t\ttable.args, table.strippedLocation, table.err,\n\t\t\t\targs, location, err)\n\t\t}\n\t}\n}\n\nfunc TestTorrentListing(t *testing.T) {\n\tconst apiAddr = \"http:\/\/localhost:8080\"\n\tlog.SetLevel(log.DebugLevel)\n\n\tdefer gock.Off()\n\n\tgock.New(apiAddr).\n\t\tGet(\"\/api\/v2\/torrents\/info\").\n\t\tReply(200).\n\t\tFile(\"testdata\/torrent_list.json\")\n\n\tgock.New(apiAddr).\n\t\tPost(\"\/api\/v2\/auth\/login\").\n\t\tReply(200).\n\t\tSetHeader(\"Set-Cookie\", \"SID=1\")\n\n\t\/\/ 1\n\tsetUpMocks(apiAddr, \"cf7da7ab4d4e6125567bd979994f13bb1f23dddd\", \"1\")\n\n\t\/\/ 2\n\tsetUpMocks(apiAddr, \"842783e3005495d5d1637f5364b59343c7844707\", \"2\")\n\n\tclient := &http.Client{Transport: &http.Transport{}}\n\tgock.InterceptClient(client)\n\n\tqBTConn.Init(apiAddr, client, false)\n\tserver := httptest.NewServer(http.HandlerFunc(handler))\n\tdefer server.Close()\n\tdefer server.CloseClientConnections()\n\tserverAddr := server.Listener.Addr().(*net.TCPAddr)\n\tprintln(serverAddr.IP.String())\n\n\ttransmissionbt, err := transmissionrpc.New(serverAddr.IP.String(), \"\", \"\",\n\t\t&transmissionrpc.AdvancedConfig{Port: uint16(serverAddr.Port)})\n\tCheck(err)\n\ttorrents, err := transmissionbt.TorrentGetAll()\n\tCheck(err)\n\tif len(torrents) != 2 {\n\t\tt.Error(\"Number of torrents is not equal to 2\")\n\t}\n\tif *torrents[0].Name != \"ubuntu-18.04.2-live-server-amd64.iso\" && *torrents[0].Name != \"ubuntu-18.04.2-desktop-amd64.iso\" {\n\t\tt.Error(\"Unexpected torrent 0\")\n\t}\n\tif *torrents[1].Name != \"ubuntu-18.04.2-desktop-amd64.iso\" && *torrents[1].Name != \"ubuntu-18.04.2-live-server-amd64.iso\" {\n\t\tt.Error(\"Unexpected torrent 1\")\n\t}\n}\n\nfunc TestSyncing(t *testing.T) {\n\tconst apiAddr = \"http:\/\/localhost:8080\"\n\tlog.SetLevel(log.DebugLevel)\n\n\tdefer gock.Off()\n\n\tgock.New(apiAddr).\n\t\tPost(\"\/api\/v2\/auth\/login\").\n\t\tReply(200).\n\t\tSetHeader(\"Set-Cookie\", \"SID=1\")\n\n\tgock.New(apiAddr).\n\t\tGet(\"\/api\/v2\/sync\/maindata\").\n\t\tMatchParam(\"rid\", \"0\").\n\t\tHeaderPresent(\"Cookie\").\n\t\tReply(200).\n\t\tFile(\"testdata\/sync_initial.json\")\n\n\tgock.New(apiAddr).\n\t\tGet(\"\/api\/v2\/sync\/maindata\").\n\t\tMatchParam(\"rid\", \"1\").\n\t\tHeaderPresent(\"Cookie\").\n\t\tReply(200).\n\t\tFile(\"testdata\/sync_1.json\")\n\n\tgock.New(apiAddr).\n\t\tGet(\"\/api\/v2\/sync\/maindata\").\n\t\tMatchParam(\"rid\", \"2\").\n\t\tHeaderPresent(\"Cookie\").\n\t\tReply(200).\n\t\tFile(\"testdata\/sync_2.json\")\n\n\tgock.New(apiAddr).\n\t\tGet(\"\/api\/v2\/sync\/maindata\").\n\t\tMatchParam(\"rid\", \"3\").\n\t\tHeaderPresent(\"Cookie\").\n\t\tReply(200).\n\t\tFile(\"testdata\/sync_3.json\")\n\n\tgock.New(apiAddr).\n\t\tGet(\"\/api\/v2\/sync\/maindata\").\n\t\tMatchParam(\"rid\", \"4\").\n\t\tHeaderPresent(\"Cookie\").\n\t\tReply(200).\n\t\tFile(\"testdata\/sync_4.json\")\n\n\t\/\/ 1\n\tsetUpMocks(apiAddr, \"cf7da7ab4d4e6125567bd979994f13bb1f23dddd\", \"1\")\n\n\t\/\/ 2\n\tsetUpMocks(apiAddr, \"842783e3005495d5d1637f5364b59343c7844707\", \"2\")\n\n\t\/\/ 3\n\tsetUpMocks(apiAddr, \"7a1448be6d15bcde08ee9915350d0725775b73a3\", \"3\")\n\n\tclient := &http.Client{Transport: &http.Transport{}}\n\tgock.InterceptClient(client)\n\n\tqBTConn.Init(apiAddr, client, true)\n\tserver := httptest.NewServer(http.HandlerFunc(handler))\n\tdefer server.Close()\n\tdefer server.CloseClientConnections()\n\tserverAddr := server.Listener.Addr().(*net.TCPAddr)\n\tprintln(serverAddr.IP.String())\n\n\ttransmissionbt, err := transmissionrpc.New(serverAddr.IP.String(), \"\", \"\",\n\t\t&transmissionrpc.AdvancedConfig{Port: uint16(serverAddr.Port)})\n\tCheck(err)\n\ttorrents, err := transmissionbt.TorrentGetAll()\n\tCheck(err)\n\tif len(torrents) != 2 {\n\t\tt.Error(\"Number of torrents is not equal to 2\")\n\t}\n\tif *torrents[0].Name != \"ubuntu-18.04.2-live-server-amd64.iso\" && *torrents[0].Name != \"ubuntu-18.04.2-desktop-amd64.iso\" {\n\t\tt.Error(\"Unexpected torrent 0\")\n\t}\n\tif *torrents[1].Name != \"ubuntu-18.04.2-desktop-amd64.iso\" && *torrents[1].Name != \"ubuntu-18.04.2-live-server-amd64.iso\" {\n\t\tt.Error(\"Unexpected torrent 1\")\n\t}\n\n\ttorrents, err = transmissionbt.TorrentGetAll()\n\tCheck(err)\n\tif len(torrents) != 2 {\n\t\tt.Error(\"Number of torrents is not equal to 2\")\n\t}\n\n\ttorrents, err = transmissionbt.TorrentGetAll()\n\tCheck(err)\n\tif len(torrents) != 3 {\n\t\tt.Error(\"Number of torrents is not equal to 3\")\n\t}\n\tif *torrents[2].Name != \"xubuntu-18.04.2-desktop-amd64.iso\" {\n\t\tt.Error(\"Unexpected torrent name\")\n\t}\n\n\ttorrents, err = transmissionbt.TorrentGetAll()\n\tCheck(err)\n\tif len(torrents) != 3 {\n\t\tt.Error(\"Number of torrents is not equal to 3\")\n\t}\n\n\ttorrents, err = transmissionbt.TorrentGetAll()\n\tCheck(err)\n\tif len(torrents) != 2 {\n\t\tt.Error(\"Number of torrents is not equal to 2\")\n\t}\n}\n\nfunc setUpMocks(apiAddr string, hash string, name string) {\n\tgock.New(apiAddr).\n\t\tGet(\"\/api\/v2\/torrents\/properties\").\n\t\tMatchParam(\"hash\", hash).\n\t\tPersist().\n\t\tReply(200).\n\t\tFile(\"testdata\/torrent_\" + name + \"_properties.json\")\n\tgock.New(apiAddr).\n\t\tGet(\"\/api\/v2\/torrents\/trackers\").\n\t\tMatchParam(\"hash\", hash).\n\t\tPersist().\n\t\tReply(200).\n\t\tFile(\"testdata\/torrent_\" + name + \"_trackers.json\")\n\tgock.New(apiAddr).\n\t\tGet(\"\/api\/v2\/torrents\/pieceStates\").\n\t\tMatchParam(\"hash\", hash).\n\t\tPersist().\n\t\tReply(200).\n\t\tFile(\"testdata\/torrent_\" + name + \"_piecestates.json\")\n\tgock.New(apiAddr).\n\t\tGet(\"\/api\/v2\/torrents\/files\").\n\t\tMatchParam(\"hash\", hash).\n\t\tPersist().\n\t\tReply(200).\n\t\tFile(\"testdata\/torrent_\" + name + \"_files.json\")\n\tgock.New(apiAddr).\n\t\tGet(\"\/api\/v2\/sync\/torrentPeers\").\n\t\tMatchParam(\"hash\", hash).\n\t\tMatchParam(\"rid\", \"0\").\n\t\tPersist().\n\t\tReply(200).\n\t\tFile(\"testdata\/torrent_\" + name + \"_peers.json\")\n}\n<|endoftext|>"}
{"text":"<commit_before><commit_msg>Update samp with useful features<commit_after><|endoftext|>"}
{"text":"<commit_before>\/\/ The MIT License (MIT)\n\/\/\n\/\/ Copyright (c) 2013-2015 Oryx(ossrs)\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy of\n\/\/ this software and associated documentation files (the \"Software\"), to deal in\n\/\/ the Software without restriction, including without limitation the rights to\n\/\/ use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\n\/\/ the Software, and to permit persons to whom the Software is furnished to do so,\n\/\/ subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n\/\/ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n\/\/ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n\/\/ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n\/\/ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\/\/ +build darwin dragonfly freebsd nacl netbsd openbsd solaris linux\n\npackage protocol\n\nimport (\n\t\"github.com\/ossrs\/go-oryx\/core\"\n\t\/\/\"net\"\n)\n\nfunc (v *RtmpStack) fastSendMessages(iovs ...[]byte) (err error) {\n\t\/\/ we can force to not use writev.\n\tif !core.Conf.Go.Writev {\n\t\treturn v.slowSendMessages(iovs...)\n\t}\n\n\t\/\/ wait for golang to implements the writev.\n\t\/\/ @see https:\/\/github.com\/golang\/go\/issues\/13451\n\t\/\/ private writev, @see https:\/\/github.com\/winlinvip\/go\/pull\/1.\n\t\/\/if c, ok := v.out.(*net.TCPConn); ok {\n\t\/\/\tif _, err = c.Writev(iovs); err != nil {\n\t\/\/\t\treturn\n\t\/\/\t}\n\t\/\/\treturn\n\t\/\/}\n\n\t\/\/ send by big-buffer or one-by-one\n\treturn v.slowSendMessages(iovs...)\n}\n<commit_msg>test build<commit_after>\/\/ The MIT License (MIT)\n\/\/\n\/\/ Copyright (c) 2013-2015 Oryx(ossrs)\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy of\n\/\/ this software and associated documentation files (the \"Software\"), to deal in\n\/\/ the Software without restriction, including without limitation the rights to\n\/\/ use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\n\/\/ the Software, and to permit persons to whom the Software is furnished to do so,\n\/\/ subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n\/\/ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n\/\/ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n\/\/ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n\/\/ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\/\/ +build darwin dragonfly freebsd nacl netbsd openbsd solaris linux\n\npackage protocol\n\nimport (\n\t\"github.com\/ossrs\/go-oryx\/core\"\n\t\/\/\"net\"\n)\n\nfunc (v *RtmpStack) fastSendMessages(iovs ...[]byte) (err error) {\n\t\/\/ we can force to not use writev.\n\tif !core.Conf.Go.Writev {\n\t\treturn v.slowSendMessages(iovs...)\n\t}\n\n\t\/\/ wait for golang to implements the writev.\n\t\/\/ @see https:\/\/github.com\/golang\/go\/issues\/13451\n\t\/\/ private writev, @see https:\/\/github.com\/winlinvip\/go\/pull\/1.\n\t\/\/if c, ok := v.out.(*net.TCPConn); ok {\n\t\/\/\tif _, err = c.Writev(iovs); err != nil {\n\t\/\/\t\treturn\n\t\/\/\t}\n\t\/\/\treturn\n\t\/\/}\n\n\t\/\/ send by big-buffer or one-by-one\n\treturn v.slowSendMessages(iovs...)\n}\n\n<|endoftext|>"}
{"text":"<commit_before>package glesys\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"encoding\/json\"\n\t\"io\"\n\t\"net\/http\"\n\t\"testing\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\ntype mockHTTPClient struct {\n\tbody        string\n\tlastRequest *http.Request\n\tstatusCode  int\n}\n\nfunc (c *mockHTTPClient) Do(request *http.Request) (*http.Response, error) {\n\tresponse := http.Response{\n\t\tStatusCode: c.statusCode,\n\t\tBody:       io.NopCloser(bytes.NewBufferString(c.body)),\n\t}\n\tc.lastRequest = request\n\treturn &response, nil\n}\n\nfunc TestRequestHasCorrectHeaders(t *testing.T) {\n\tclient := NewClient(\"project-id\", \"api-key\", \"test-application\/0.0.1\")\n\n\trequest, err := client.newRequest(context.Background(), \"GET\", \"\/\", nil)\n\tassert.NoError(t, err)\n\n\tassert.Equal(t, \"application\/json\", request.Header.Get(\"Content-Type\"), \"header Content-Type is correct\")\n\tassert.Equal(t, \"test-application\/0.0.1 glesys-go\/6.0.0\", request.Header.Get(\"User-Agent\"), \"header User-Agent is correct\")\n\n\tassert.NotEmpty(t, request.Header.Get(\"Authorization\"), \"header Authorization is not empty\")\n}\n\nfunc TestEmptyUserAgent(t *testing.T) {\n\tclient := NewClient(\"project-id\", \"api-key\", \"\")\n\n\trequest, err := client.newRequest(context.Background(), \"GET\", \"\/\", nil)\n\tassert.NoError(t, err)\n\tassert.Equal(t, \"glesys-go\/6.0.0\", request.Header.Get(\"User-Agent\"), \"header User-Agent is correct\")\n}\n\nfunc TestGetResponseErrorMessage(t *testing.T) {\n\tclient := NewClient(\"project-id\", \"api-key\", \"test-application\/0.0.1\")\n\n\tjson := `{ \"response\": {\"status\": { \"code\": 400, \"text\": \"Unauthorized\" } } }`\n\tresponse := http.Response{\n\t\tBody:       io.NopCloser(bytes.NewBufferString(json)),\n\t\tStatusCode: 400,\n\t}\n\terr := client.handleResponseError(&response)\n\tassert.Equal(t, \"Request failed with HTTP error: 400 (Unauthorized)\", err.Error(), \"error message is correct\")\n}\n\nfunc TestDoDoesNotReturnErrorIfStatusIs200(t *testing.T) {\n\tpayload := `{ \"response\": { \"hello\": \"world\" } }`\n\tclient := Client{httpClient: &mockHTTPClient{body: payload, statusCode: 200}}\n\n\trequest, _ := client.newRequest(context.Background(), \"GET\", \"\/\", nil)\n\terr := client.do(request, nil)\n\n\tassert.NoError(t, err, \"do does not return an error\")\n}\n\nfunc TestDoReturnsErrorIfStatusIsNot200(t *testing.T) {\n\tpayload := `{ \"response\": { \"foo\": \"bar\" } }`\n\tclient := Client{httpClient: &mockHTTPClient{body: payload, statusCode: 500}}\n\n\trequest, _ := client.newRequest(context.Background(), \"GET\", \"\/\", nil)\n\terr := client.do(request, nil)\n\n\tassert.Error(t, err, \"do returns an error\")\n}\n\nfunc TestDoDecodesTheJsonResponseIntoAStruct(t *testing.T) {\n\tpayload := `{ \"response\": { \"message\": \"Hello World\" } }`\n\tclient := Client{httpClient: &mockHTTPClient{body: payload, statusCode: 200}}\n\n\trequest, _ := client.newRequest(context.Background(), \"GET\", \"\/\", nil)\n\n\tdata := struct {\n\t\tResponse struct {\n\t\t\tMessage string\n\t\t}\n\t}{}\n\terr := client.do(request, &data)\n\n\tassert.NoError(t, err)\n\tassert.Equal(t, \"Hello World\", data.Response.Message, \"JSON was parsed correctly\")\n}\n\nfunc TestSetBaseURL(t *testing.T) {\n\tclient := NewClient(\"project-id\", \"api-key\", \"test-application\/0.0.1\")\n\n\turl := \"https:\/\/dev-api.glesys.local\"\n\terr := client.SetBaseURL(url)\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t}\n\n\tassert.Equal(t, client.BaseURL.String(), url, \"invalid baseurl returned\")\n}\n\nfunc TestGet(t *testing.T) {\n\tpayload := `{ \"response\": { \"message\": \"Hello World\" } }`\n\tmockClient := mockHTTPClient{body: payload, statusCode: 200}\n\tclient := Client{httpClient: &mockClient}\n\n\tdata := struct{}{}\n\tclient.get(context.Background(), \"\/foo\", data)\n\n\tassert.Equal(t, \"GET\", mockClient.lastRequest.Method, \"method used is correct\")\n}\n\nfunc TestPost(t *testing.T) {\n\tpayload := `{ \"response\": { \"message\": \"Hello World\" } }`\n\tmockClient := mockHTTPClient{body: payload, statusCode: 200}\n\tclient := Client{httpClient: &mockClient}\n\n\tclient.post(context.Background(), \"\/foo\", nil, struct{ Foo string }{Foo: \"bar\"})\n\n\tparams := struct{ Foo string }{}\n\tjson.NewDecoder(mockClient.lastRequest.Body).Decode(&params)\n\n\tassert.Equal(t, \"POST\", mockClient.lastRequest.Method, \"method used is correct\")\n\tassert.Equal(t, \"bar\", params.Foo, \"params are correct\")\n}\n<commit_msg>Update client_test.go with test url<commit_after>package glesys\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"encoding\/json\"\n\t\"io\"\n\t\"net\/http\"\n\t\"testing\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\ntype mockHTTPClient struct {\n\tbody        string\n\tlastRequest *http.Request\n\tstatusCode  int\n}\n\nfunc (c *mockHTTPClient) Do(request *http.Request) (*http.Response, error) {\n\tresponse := http.Response{\n\t\tStatusCode: c.statusCode,\n\t\tBody:       io.NopCloser(bytes.NewBufferString(c.body)),\n\t}\n\tc.lastRequest = request\n\treturn &response, nil\n}\n\nfunc TestRequestHasCorrectHeaders(t *testing.T) {\n\tclient := NewClient(\"project-id\", \"api-key\", \"test-application\/0.0.1\")\n\n\trequest, err := client.newRequest(context.Background(), \"GET\", \"\/\", nil)\n\tassert.NoError(t, err)\n\n\tassert.Equal(t, \"application\/json\", request.Header.Get(\"Content-Type\"), \"header Content-Type is correct\")\n\tassert.Equal(t, \"test-application\/0.0.1 glesys-go\/6.0.0\", request.Header.Get(\"User-Agent\"), \"header User-Agent is correct\")\n\n\tassert.NotEmpty(t, request.Header.Get(\"Authorization\"), \"header Authorization is not empty\")\n}\n\nfunc TestEmptyUserAgent(t *testing.T) {\n\tclient := NewClient(\"project-id\", \"api-key\", \"\")\n\n\trequest, err := client.newRequest(context.Background(), \"GET\", \"\/\", nil)\n\tassert.NoError(t, err)\n\tassert.Equal(t, \"glesys-go\/6.0.0\", request.Header.Get(\"User-Agent\"), \"header User-Agent is correct\")\n}\n\nfunc TestGetResponseErrorMessage(t *testing.T) {\n\tclient := NewClient(\"project-id\", \"api-key\", \"test-application\/0.0.1\")\n\n\tjson := `{ \"response\": {\"status\": { \"code\": 400, \"text\": \"Unauthorized\" } } }`\n\tresponse := http.Response{\n\t\tBody:       io.NopCloser(bytes.NewBufferString(json)),\n\t\tStatusCode: 400,\n\t}\n\terr := client.handleResponseError(&response)\n\tassert.Equal(t, \"Request failed with HTTP error: 400 (Unauthorized)\", err.Error(), \"error message is correct\")\n}\n\nfunc TestDoDoesNotReturnErrorIfStatusIs200(t *testing.T) {\n\tpayload := `{ \"response\": { \"hello\": \"world\" } }`\n\tclient := Client{httpClient: &mockHTTPClient{body: payload, statusCode: 200}}\n\n\trequest, _ := client.newRequest(context.Background(), \"GET\", \"\/\", nil)\n\terr := client.do(request, nil)\n\n\tassert.NoError(t, err, \"do does not return an error\")\n}\n\nfunc TestDoReturnsErrorIfStatusIsNot200(t *testing.T) {\n\tpayload := `{ \"response\": { \"foo\": \"bar\" } }`\n\tclient := Client{httpClient: &mockHTTPClient{body: payload, statusCode: 500}}\n\n\trequest, _ := client.newRequest(context.Background(), \"GET\", \"\/\", nil)\n\terr := client.do(request, nil)\n\n\tassert.Error(t, err, \"do returns an error\")\n}\n\nfunc TestDoDecodesTheJsonResponseIntoAStruct(t *testing.T) {\n\tpayload := `{ \"response\": { \"message\": \"Hello World\" } }`\n\tclient := Client{httpClient: &mockHTTPClient{body: payload, statusCode: 200}}\n\n\trequest, _ := client.newRequest(context.Background(), \"GET\", \"\/\", nil)\n\n\tdata := struct {\n\t\tResponse struct {\n\t\t\tMessage string\n\t\t}\n\t}{}\n\terr := client.do(request, &data)\n\n\tassert.NoError(t, err)\n\tassert.Equal(t, \"Hello World\", data.Response.Message, \"JSON was parsed correctly\")\n}\n\nfunc TestSetBaseURL(t *testing.T) {\n\tclient := NewClient(\"project-id\", \"api-key\", \"test-application\/0.0.1\")\n\n\turl := \"https:\/\/dev-api.glesys.test\"\n\terr := client.SetBaseURL(url)\n\tif err != nil {\n\t\tt.Error(err.Error())\n\t}\n\n\tassert.Equal(t, client.BaseURL.String(), url, \"invalid baseurl returned\")\n}\n\nfunc TestGet(t *testing.T) {\n\tpayload := `{ \"response\": { \"message\": \"Hello World\" } }`\n\tmockClient := mockHTTPClient{body: payload, statusCode: 200}\n\tclient := Client{httpClient: &mockClient}\n\n\tdata := struct{}{}\n\tclient.get(context.Background(), \"\/foo\", data)\n\n\tassert.Equal(t, \"GET\", mockClient.lastRequest.Method, \"method used is correct\")\n}\n\nfunc TestPost(t *testing.T) {\n\tpayload := `{ \"response\": { \"message\": \"Hello World\" } }`\n\tmockClient := mockHTTPClient{body: payload, statusCode: 200}\n\tclient := Client{httpClient: &mockClient}\n\n\tclient.post(context.Background(), \"\/foo\", nil, struct{ Foo string }{Foo: \"bar\"})\n\n\tparams := struct{ Foo string }{}\n\tjson.NewDecoder(mockClient.lastRequest.Body).Decode(&params)\n\n\tassert.Equal(t, \"POST\", mockClient.lastRequest.Method, \"method used is correct\")\n\tassert.Equal(t, \"bar\", params.Foo, \"params are correct\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package giftcollection\n\nimport (\n\t\"fmt\"\n\t\"regifted\/mp4boxes\"\n\t\"regifted\/ts\"\n)\n\ntype sample struct {\n\tsize     int\n\tduration uint32\n\tflags    uint32\n}\n\n\/\/Need a byte array to hold the boxes in a byte\n\/\/form for printing from the driver later\n\/\/type GiftCollection struct{\n\/\/    FileByte []byte\n\/\/}\n\n\/\/ This file could be used to add the ftyp box to the beginning of the\n\/\/ FileByte array. This may not be necessary based on the files provided\n\/\/ by Niell\n\/\/func InitializeFileByte(){}\n\nconst (\n\tAUDIO_STREAM_TYPE uint = 15\n\tVIDEO_STREAM_TYPE uint = 27\n)\n\nfunc Regift(AccessUnits []*ts.AccessUnit) bool {\n\tfmt.Println(\"\\nRegift()\\n\\n\")\n\n\t\/\/fmt.Println(\"AccessUnits[0]:\")\n\t\/\/fmt.Println(AccessUnits[0])\n\t\/\/fmt.Println(\"AccessUnits[0].PesMap:\")\n\t\/\/fmt.Println(AccessUnits[0].PesMap)\n\n\taudioByte := make([]byte, 0)\n\tvideoByte := make([]byte, 0)\n\taudioSamples := make([]mp4box.Sample, 0)\n\tvideoSamples := make([]mp4box.Sample, 0)\n\ttrackID := 1\n\t\/\/ Need a array of boxes to hold the boxes\n\t\/\/ until they are ready to print\n\t\/\/ boxes = make([]mpeg4boxes, 0)\n\t\/\/ IMPORTANT NOTE: To have a array of the boxes they all have to\n\t\/\/ be in the same interface. I think this means all the box files\n\t\/\/ will need to be in the same package.\n\n\t\/\/ Dave you will need to print to file in reverse order on the\n\tBoxes := make([]mp4box.Box, 0)\n\n\tvar audioSize int = 0\n\tvar videoSize int = 0\n\tvar pcrDelta uint32 = 0\n\n\tfor _, AccessUnit := range AccessUnits {\n\t\t\/\/ fmt.Println( \"for _, AccessUnit := \" )\n\t\t\/\/ fmt.Println( AccessUnit )\n\n\t\tdelta := 0\n\n\t\t\/\/ fmt.Println(\"VIDEO_STREAM_TYPE = \", AccessUnit.PesMap[VIDEO_STREAM_TYPE])\n\n\t\t\/\/fmt.Println(\"for_, pes := AUDIO_STREAM_TYPE\")\n\t\tfor _, pes := range AccessUnit.PesMap[AUDIO_STREAM_TYPE] {\n\t\t\t\/\/fmt.Println(\"audio pes payload= \", pes.Payload)\n\t\t\taudioByte = append(audioByte, pes.Payload...)\n\t\t}\n\t\t\/\/fmt.Println(\"AFTER for_, pes := AUDIO_STREAM_TYPE\")\n\n\t\tdelta = len(audioByte) - audioSize\n\n\t\taudioSize = len(audioByte)\n\n\t\taudioSamples = append(audioSamples, mp4box.Sample{uint32(AccessUnit.Pcr), uint32(delta), 0, 0})\n\n\t\t\/\/ fmt.Println(\"audioSamples = \", audioSamples)\n\n\t\tfor _, pes := range AccessUnit.PesMap[VIDEO_STREAM_TYPE] {\n\t\t\tvideoByte = append(videoByte, pes.Payload...)\n\t\t}\n\n\t\tdelta = len(videoByte) - videoSize\n\n\t\tvideoSize = len(videoByte)\n\n\t\tvideoSamples = append(videoSamples, mp4box.Sample{uint32(AccessUnit.Pcr), uint32(delta), 0, 0})\n\t}\n\n\tpcrDelta = (videoSamples[len(videoSamples)-1].SampleDuration) - (videoSamples[len(videoSamples)-2].SampleDuration)\n\n\tfmt.Println(\"pcrDelta\", pcrDelta)\n\n\tif (videoSamples[len(videoSamples)-1].SampleDuration % uint32(pcrDelta)) == 0 {\n\n\t\tfor i := 0; i < len(videoSamples); i++ {\n\n\t\t\tvideoSamples[i].SampleDuration = pcrDelta\n\n\t\t}\n\n\t}\n\n\tif (audioSamples[len(audioSamples)-1].SampleDuration % uint32(pcrDelta)) == 0 {\n\n\t\tfor i := 0; i < len(audioSamples); i++ {\n\n\t\t\taudioSamples[i].SampleDuration = pcrDelta\n\n\t\t}\n\n\t}\n\n\tfmt.Println(\"\\nvideoSamples = \", videoSamples)\n\n\tfmt.Println(\"\\naudioSamples = \", audioSamples)\n\n\t\/\/ Create mdat and add it to boxes array\n\tpayload := append(videoByte, audioByte...)\n\tmdat := mp4box.NewMdat(uint32(audioSize+videoSize+8), payload)\n\n\tBoxes = append(Boxes, mdat)\n\t\/\/ Setting Flags for the trun should be done programatically from the\n\t\/\/ PES data but that can come later\n\taudioTrunFlags := make([]byte, 0, 3)\n\taudioTrunFlags = append(audioTrunFlags, 0x00)\n\taudioTrunFlags = append(audioTrunFlags, 0x0B)\n\taudioTrunFlags = append(audioTrunFlags, 0x01)\n\t\/\/ Add audio Samples to boxes array. Append to front of boxes array\n\taudioTrun := mp4box.NewTrun(\n\t\t0, \/\/size is calculated later\n\t\t0, \/\/version will be zero until we have a reason to do otherwise\n\t\taudioTrunFlags,\n\t\t0, \/\/dataoffset = MOOF.SIZE + 8, must be calculated later\n\t\t0, \/\/no reason for first-sample-flags\n\t\tuint32(len(audioSamples)),\n\t\taudioSamples)\n\t\/\/ Add audio trun to boxes array. Append to front of boxes array\n\tBoxes = append(Boxes, audioTrun)\n\n\t\/\/ Add tfhd to boxes array. Append to front of boxes array\n\taudioTfhdFlags := make([]byte, 0, 3)\n\taudioTfhdFlags = append(audioTrunFlags, 0x00)\n\taudioTfhdFlags = append(audioTrunFlags, 0x00)\n\taudioTfhdFlags = append(audioTrunFlags, 0x20)\n\taudioTfhd := mp4box.NewTfhd(\n\t\t0, \/\/size is calculated later\n\t\t0, \/\/version is typically 0\n\t\taudioTfhdFlags,\n\t\tuint32(trackID),\n\t\t0, \/\/base-data-offset not obsevred in sample fragments\n\t\t0, \/\/sample-description-index not observed in sample fragments\n\t\t0, \/\/default-sample-duration not observed in sample fragments\n\t\t0, \/\/default-sample-size not observed in sample fragments\n\t\t0) \/\/default-sample-flags not observed in sample fragments\n\ttrackID++\n\t\/\/ Add audio traf to boxes array. Append to front of boxes array\n\tBoxes = append(Boxes, audioTfhd)\n\n\t\/\/ Add video samples to boxes array. Append to front of boxes array\n\n\t\/\/ Add video trun to boxes array. Append to front of boxes array\n\n\t\/\/ Add tfhd to boxes array. Append to front of boxes array\n\n\t\/\/ Add video traf to boxes array. Append to fron of boxes array\n\n\t\/\/ Add mfhd to boxes array. Append to front of boxes array\n\n\t\/\/ Add moof to boxes array. Append to front of boxes array\n\n\t\/\/ Call the write method for all boxes in boxes array.\n\t\/\/ And append the values to the end of the FileByte array.\n\n\treturn false\n\n}\n<commit_msg>added error handling<commit_after>package giftcollection\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"regifted\/mp4boxes\"\n\t\"regifted\/ts\"\n)\n\ntype sample struct {\n\tsize     int\n\tduration uint32\n\tflags    uint32\n}\n\n\/\/Need a byte array to hold the boxes in a byte\n\/\/form for printing from the driver later\n\/\/type GiftCollection struct{\n\/\/    FileByte []byte\n\/\/}\n\n\/\/ This file could be used to add the ftyp box to the beginning of the\n\/\/ FileByte array. This may not be necessary based on the files provided\n\/\/ by Niell\n\/\/func InitializeFileByte(){}\n\nconst (\n\tAUDIO_STREAM_TYPE uint = 15\n\tVIDEO_STREAM_TYPE uint = 27\n)\n\nfunc Regift(AccessUnits []*ts.AccessUnit) bool {\n\tfmt.Println(\"\\nRegift()\\n\\n\")\n\n\t\/\/fmt.Println(\"AccessUnits[0]:\")\n\t\/\/fmt.Println(AccessUnits[0])\n\t\/\/fmt.Println(\"AccessUnits[0].PesMap:\")\n\t\/\/fmt.Println(AccessUnits[0].PesMap)\n\n\taudioByte := make([]byte, 0)\n\tvideoByte := make([]byte, 0)\n\taudioSamples := make([]mp4box.Sample, 0)\n\tvideoSamples := make([]mp4box.Sample, 0)\n\ttrackID := 1\n\t\/\/ Need a array of boxes to hold the boxes\n\t\/\/ until they are ready to print\n\t\/\/ boxes = make([]mpeg4boxes, 0)\n\t\/\/ IMPORTANT NOTE: To have a array of the boxes they all have to\n\t\/\/ be in the same interface. I think this means all the box files\n\t\/\/ will need to be in the same package.\n\n\t\/\/ Dave you will need to print to file in reverse order on the\n\tBoxes := make([]mp4box.Box, 0)\n\n\tvar audioSize int = 0\n\tvar videoSize int = 0\n\tvar pcrDelta uint32 = 0\n\n\tfor _, AccessUnit := range AccessUnits {\n\t\t\/\/ fmt.Println( \"for _, AccessUnit := \" )\n\t\t\/\/ fmt.Println( AccessUnit )\n\n\t\tdelta := 0\n\n\t\t\/\/ fmt.Println(\"VIDEO_STREAM_TYPE = \", AccessUnit.PesMap[VIDEO_STREAM_TYPE])\n\n\t\t\/\/fmt.Println(\"for_, pes := AUDIO_STREAM_TYPE\")\n\t\tfor _, pes := range AccessUnit.PesMap[AUDIO_STREAM_TYPE] {\n\t\t\t\/\/fmt.Println(\"audio pes payload= \", pes.Payload)\n\t\t\taudioByte = append(audioByte, pes.Payload...)\n\t\t}\n\t\t\/\/fmt.Println(\"AFTER for_, pes := AUDIO_STREAM_TYPE\")\n\n\t\tdelta = len(audioByte) - audioSize\n\n\t\taudioSize = len(audioByte)\n\n\t\taudioSamples = append(audioSamples, mp4box.Sample{uint32(AccessUnit.Pcr), uint32(delta), 0, 0})\n\n\t\t\/\/ fmt.Println(\"audioSamples = \", audioSamples)\n\n\t\tfor _, pes := range AccessUnit.PesMap[VIDEO_STREAM_TYPE] {\n\t\t\tvideoByte = append(videoByte, pes.Payload...)\n\t\t}\n\n\t\tdelta = len(videoByte) - videoSize\n\n\t\tvideoSize = len(videoByte)\n\n\t\tvideoSamples = append(videoSamples, mp4box.Sample{uint32(AccessUnit.Pcr), uint32(delta), 0, 0})\n\t}\n\n\t\n\tif len(videoSamples) < 2 {\n\t\tlog.Fatal(\"Not enough data do genertae pcr delta\")\n\t\treturn false\n\t\t\n\t}\n\n\tpcrDelta = (videoSamples[len(videoSamples)-1].SampleDuration) - (videoSamples[len(videoSamples)-2].SampleDuration)\n\n\tif pcrDelta == 0 {\n\t\tlog.Fatal(\"pcrDelta is 0, cannot generate delta\")\n\t\treturn false\n\t\t\n\t}\n\n\tfmt.Println(\"pcrDelta\", pcrDelta)\n\n\tif (videoSamples[len(videoSamples)-1].SampleDuration % uint32(pcrDelta)) == 0 {\n\n\t\tfor i := 0; i < len(videoSamples); i++ {\n\n\t\t\tvideoSamples[i].SampleDuration = pcrDelta\n\n\t\t}\n\n\t}\n\n\tif (audioSamples[len(audioSamples)-1].SampleDuration % uint32(pcrDelta)) == 0 {\n\n\t\tfor i := 0; i < len(audioSamples); i++ {\n\n\t\t\taudioSamples[i].SampleDuration = pcrDelta\n\n\t\t}\n\n\t}\n\n\tfmt.Println(\"\\nvideoSamples = \", videoSamples)\n\n\tfmt.Println(\"\\naudioSamples = \", audioSamples)\n\n\t\/\/ Create mdat and add it to boxes array\n\tpayload := append(videoByte, audioByte...)\n\tmdat := mp4box.NewMdat(uint32(audioSize+videoSize+8), payload)\n\n\tBoxes = append(Boxes, mdat)\n\t\/\/ Setting Flags for the trun should be done programatically from the\n\t\/\/ PES data but that can come later\n\taudioTrunFlags := make([]byte, 0, 3)\n\taudioTrunFlags = append(audioTrunFlags, 0x00)\n\taudioTrunFlags = append(audioTrunFlags, 0x0B)\n\taudioTrunFlags = append(audioTrunFlags, 0x01)\n\t\/\/ Add audio Samples to boxes array. Append to front of boxes array\n\taudioTrun := mp4box.NewTrun(\n\t\t0, \/\/size is calculated later\n\t\t0, \/\/version will be zero until we have a reason to do otherwise\n\t\taudioTrunFlags,\n\t\t0, \/\/dataoffset = MOOF.SIZE + 8, must be calculated later\n\t\t0, \/\/no reason for first-sample-flags\n\t\tuint32(len(audioSamples)),\n\t\taudioSamples)\n\t\/\/ Add audio trun to boxes array. Append to front of boxes array\n\tBoxes = append(Boxes, audioTrun)\n\n\t\/\/ Add tfhd to boxes array. Append to front of boxes array\n\taudioTfhdFlags := make([]byte, 0, 3)\n\taudioTfhdFlags = append(audioTrunFlags, 0x00)\n\taudioTfhdFlags = append(audioTrunFlags, 0x00)\n\taudioTfhdFlags = append(audioTrunFlags, 0x20)\n\taudioTfhd := mp4box.NewTfhd(\n\t\t0, \/\/size is calculated later\n\t\t0, \/\/version is typically 0\n\t\taudioTfhdFlags,\n\t\tuint32(trackID),\n\t\t0, \/\/base-data-offset not obsevred in sample fragments\n\t\t0, \/\/sample-description-index not observed in sample fragments\n\t\t0, \/\/default-sample-duration not observed in sample fragments\n\t\t0, \/\/default-sample-size not observed in sample fragments\n\t\t0) \/\/default-sample-flags not observed in sample fragments\n\ttrackID++\n\t\/\/ Add audio traf to boxes array. Append to front of boxes array\n\tBoxes = append(Boxes, audioTfhd)\n\n\t\/\/ Add video samples to boxes array. Append to front of boxes array\n\n\t\/\/ Add video trun to boxes array. Append to front of boxes array\n\n\t\/\/ Add tfhd to boxes array. Append to front of boxes array\n\n\t\/\/ Add video traf to boxes array. Append to fron of boxes array\n\n\t\/\/ Add mfhd to boxes array. Append to front of boxes array\n\n\t\/\/ Add moof to boxes array. Append to front of boxes array\n\n\t\/\/ Call the write method for all boxes in boxes array.\n\t\/\/ And append the values to the end of the FileByte array.\n\n\treturn false\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2017 gf Author(https:\/\/github.com\/gogf\/gf). All Rights Reserved.\n\/\/\n\/\/ This Source Code Form is subject to the terms of the MIT License.\n\/\/ If a copy of the MIT was not distributed with this file,\n\/\/ You can obtain one at https:\/\/github.com\/gogf\/gf.\n\/\/\n\/\/ Note:\n\/\/ 1. It needs manually import: _ \"github.com\/denisenkom\/go-mssqldb\"\n\/\/ 2. It does not support Save\/Replace features.\n\/\/ 3. It does not support LastInsertId.\n\npackage gdb\n\nimport (\n\t\"database\/sql\"\n\t\"fmt\"\n\t\"github.com\/gogf\/gf\/internal\/intlog\"\n\t\"github.com\/gogf\/gf\/text\/gstr\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/gogf\/gf\/text\/gregex\"\n)\n\n\/\/ DriverMssql is the driver for SQL server database.\ntype DriverMssql struct {\n\t*Core\n}\n\n\/\/ New creates and returns a database object for SQL server.\n\/\/ It implements the interface of gdb.Driver for extra database driver installation.\nfunc (d *DriverMssql) New(core *Core, node *ConfigNode) (DB, error) {\n\treturn &DriverMssql{\n\t\tCore: core,\n\t}, nil\n}\n\n\/\/ Open creates and returns a underlying sql.DB object for mssql.\nfunc (d *DriverMssql) Open(config *ConfigNode) (*sql.DB, error) {\n\tsource := \"\"\n\tif config.LinkInfo != \"\" {\n\t\tsource = config.LinkInfo\n\t} else {\n\t\tsource = fmt.Sprintf(\n\t\t\t\"user id=%s;password=%s;server=%s;port=%s;database=%s;encrypt=disable\",\n\t\t\tconfig.User, config.Pass, config.Host, config.Port, config.Name,\n\t\t)\n\t}\n\tintlog.Printf(\"Open: %s\", source)\n\tif db, err := sql.Open(\"sqlserver\", source); err == nil {\n\t\treturn db, nil\n\t} else {\n\t\treturn nil, err\n\t}\n}\n\n\/\/ GetChars returns the security char for this type of database.\nfunc (d *DriverMssql) GetChars() (charLeft string, charRight string) {\n\treturn \"\\\"\", \"\\\"\"\n}\n\n\/\/ HandleSqlBeforeCommit deals with the sql string before commits it to underlying sql driver.\nfunc (d *DriverMssql) HandleSqlBeforeCommit(link Link, query string, args []interface{}) (string, []interface{}) {\n\tvar index int\n\t\/\/ Convert place holder char '?' to string \"@px\".\n\tstr, _ := gregex.ReplaceStringFunc(\"\\\\?\", query, func(s string) string {\n\t\tindex++\n\t\treturn fmt.Sprintf(\"@p%d\", index)\n\t})\n\tstr, _ = gregex.ReplaceString(\"\\\"\", \"\", str)\n\treturn d.parseSql(str), args\n}\n\nfunc (d *DriverMssql) parseSql(sql string) string {\n\t\/\/ SELECT * FROM USER WHERE ID=1 LIMIT 1\n\tif m, _ := gregex.MatchString(`^SELECT(.+)LIMIT 1$`, sql); len(m) > 1 {\n\t\treturn fmt.Sprintf(`SELECT TOP 1 %s`, m[1])\n\t}\n\t\/\/ SELECT * FROM USER WHERE AGE>18 ORDER BY ID DESC LIMIT 100, 200\n\tpatten := `^\\s*(?i)(SELECT)|(LIMIT\\s*(\\d+)\\s*,\\s*(\\d+))`\n\tif gregex.IsMatchString(patten, sql) == false {\n\t\treturn sql\n\t}\n\tres, err := gregex.MatchAllString(patten, sql)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\tindex := 0\n\tkeyword := strings.TrimSpace(res[index][0])\n\tkeyword = strings.ToUpper(keyword)\n\tindex++\n\tswitch keyword {\n\tcase \"SELECT\":\n\t\t\/\/ 不含LIMIT关键字则不处理\n\t\tif len(res) < 2 ||\n\t\t\t(strings.HasPrefix(res[index][0], \"LIMIT\") == false &&\n\t\t\t\tstrings.HasPrefix(res[index][0], \"limit\") == false) {\n\t\t\tbreak\n\t\t}\n\t\t\/\/ 不含LIMIT则不处理\n\t\tif gregex.IsMatchString(\"((?i)SELECT)(.+)((?i)LIMIT)\", sql) == false {\n\t\t\tbreak\n\t\t}\n\t\t\/\/ 判断SQL中是否含有order by\n\t\tselectStr := \"\"\n\t\torderStr := \"\"\n\t\thaveOrder := gregex.IsMatchString(\"((?i)SELECT)(.+)((?i)ORDER BY)\", sql)\n\t\tif haveOrder {\n\t\t\t\/\/ 取order by 前面的字符串\n\t\t\tqueryExpr, _ := gregex.MatchString(\"((?i)SELECT)(.+)((?i)ORDER BY)\", sql)\n\t\t\tif len(queryExpr) != 4 ||\n\t\t\t\tstrings.EqualFold(queryExpr[1], \"SELECT\") == false ||\n\t\t\t\tstrings.EqualFold(queryExpr[3], \"ORDER BY\") == false {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tselectStr = queryExpr[2]\n\n\t\t\t\/\/ 取order by表达式的值\n\t\t\torderExpr, _ := gregex.MatchString(\"((?i)ORDER BY)(.+)((?i)LIMIT)\", sql)\n\t\t\tif len(orderExpr) != 4 ||\n\t\t\t\tstrings.EqualFold(orderExpr[1], \"ORDER BY\") == false ||\n\t\t\t\tstrings.EqualFold(orderExpr[3], \"LIMIT\") == false {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\torderStr = orderExpr[2]\n\t\t} else {\n\t\t\tqueryExpr, _ := gregex.MatchString(\"((?i)SELECT)(.+)((?i)LIMIT)\", sql)\n\t\t\tif len(queryExpr) != 4 ||\n\t\t\t\tstrings.EqualFold(queryExpr[1], \"SELECT\") == false ||\n\t\t\t\tstrings.EqualFold(queryExpr[3], \"LIMIT\") == false {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tselectStr = queryExpr[2]\n\t\t}\n\n\t\t\/\/ 取limit后面的取值范围\n\t\tfirst, limit := 0, 0\n\t\tfor i := 1; i < len(res[index]); i++ {\n\t\t\tif len(strings.TrimSpace(res[index][i])) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif strings.HasPrefix(res[index][i], \"LIMIT\") ||\n\t\t\t\tstrings.HasPrefix(res[index][i], \"limit\") {\n\t\t\t\tfirst, _ = strconv.Atoi(res[index][i+1])\n\t\t\t\tlimit, _ = strconv.Atoi(res[index][i+2])\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif haveOrder {\n\t\t\tsql = fmt.Sprintf(\n\t\t\t\t\"SELECT * FROM \"+\n\t\t\t\t\t\"(SELECT ROW_NUMBER() OVER (ORDER BY %s) as ROWNUMBER_, %s ) as TMP_ \"+\n\t\t\t\t\t\"WHERE TMP_.ROWNUMBER_ > %d AND TMP_.ROWNUMBER_ <= %d\",\n\t\t\t\torderStr, selectStr, first, limit,\n\t\t\t)\n\t\t} else {\n\t\t\tif first == 0 {\n\t\t\t\tfirst = limit\n\t\t\t} else {\n\t\t\t\tfirst = limit - first\n\t\t\t}\n\t\t\tsql = fmt.Sprintf(\n\t\t\t\t\"SELECT * FROM (SELECT TOP %d * FROM (SELECT TOP %d %s) as TMP1_ ) as TMP2_ \",\n\t\t\t\tfirst, limit, selectStr,\n\t\t\t)\n\t\t}\n\tdefault:\n\t}\n\treturn sql\n}\n\n\/\/ Tables retrieves and returns the tables of current schema.\n\/\/ It's mainly used in cli tool chain for automatically generating the models.\nfunc (d *DriverMssql) Tables(schema ...string) (tables []string, err error) {\n\tvar result Result\n\tlink, err := d.DB.GetSlave(schema...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult, err = d.DB.DoGetAll(link, `SELECT NAME FROM SYSOBJECTS WHERE XTYPE='U' AND STATUS >= 0 ORDER BY NAME`)\n\tif err != nil {\n\t\treturn\n\t}\n\tfor _, m := range result {\n\t\tfor _, v := range m {\n\t\t\ttables = append(tables, v.String())\n\t\t}\n\t}\n\treturn\n}\n\n\/\/ TableFields retrieves and returns the fields information of specified table of current schema.\nfunc (d *DriverMssql) TableFields(table string, schema ...string) (fields map[string]*TableField, err error) {\n\ttable = gstr.Trim(table)\n\tif gstr.Contains(table, \" \") {\n\t\tpanic(\"function TableFields supports only single table operations\")\n\t}\n\tcheckSchema := d.DB.GetSchema()\n\tif len(schema) > 0 && schema[0] != \"\" {\n\t\tcheckSchema = schema[0]\n\t}\n\tv := d.DB.GetCache().GetOrSetFunc(\n\t\tfmt.Sprintf(`mssql_table_fields_%s_%s`, table, checkSchema), func() interface{} {\n\t\t\tvar result Result\n\t\t\tvar link *sql.DB\n\t\t\tlink, err = d.DB.GetSlave(checkSchema)\n\t\t\tif err != nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tresult, err = d.DB.DoGetAll(link, fmt.Sprintf(`\n\t\t\tSELECT c.name as FIELD, CASE t.name \n\t\t\t\tWHEN 'numeric' THEN t.name + '(' + convert(varchar(20),c.xprec) + ',' + convert(varchar(20),c.xscale) + ')' \n\t\t\t\tWHEN 'char' THEN t.name + '(' + convert(varchar(20),c.length)+ ')'\n\t\t\t\tWHEN 'varchar' THEN t.name + '(' + convert(varchar(20),c.length)+ ')'\n\t\t\t\tELSE t.name + '(' + convert(varchar(20),c.length)+ ')' END as TYPE\n\t\t\tFROM systypes t,syscolumns c WHERE t.xtype=c.xtype \n\t\t\tAND c.id = (SELECT id FROM sysobjects WHERE name='%s') \n\t\t\tORDER BY c.colid`, strings.ToUpper(table)))\n\t\t\tif err != nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tfields = make(map[string]*TableField)\n\t\t\tfor i, m := range result {\n\t\t\t\tfields[strings.ToLower(m[\"FIELD\"].String())] = &TableField{\n\t\t\t\t\tIndex: i,\n\t\t\t\t\tName:  strings.ToLower(m[\"FIELD\"].String()),\n\t\t\t\t\tType:  strings.ToLower(m[\"TYPE\"].String()),\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn fields\n\t\t}, 0)\n\tif err == nil {\n\t\tfields = v.(map[string]*TableField)\n\t}\n\treturn\n}\n<commit_msg>Fix the bug of MSSQL paging<commit_after>\/\/ Copyright 2017 gf Author(https:\/\/github.com\/gogf\/gf). All Rights Reserved.\n\/\/\n\/\/ This Source Code Form is subject to the terms of the MIT License.\n\/\/ If a copy of the MIT was not distributed with this file,\n\/\/ You can obtain one at https:\/\/github.com\/gogf\/gf.\n\/\/\n\/\/ Note:\n\/\/ 1. It needs manually import: _ \"github.com\/denisenkom\/go-mssqldb\"\n\/\/ 2. It does not support Save\/Replace features.\n\/\/ 3. It does not support LastInsertId.\n\npackage gdb\n\nimport (\n\t\"database\/sql\"\n\t\"fmt\"\n\t\"github.com\/gogf\/gf\/internal\/intlog\"\n\t\"github.com\/gogf\/gf\/text\/gstr\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/gogf\/gf\/text\/gregex\"\n)\n\n\/\/ DriverMssql is the driver for SQL server database.\ntype DriverMssql struct {\n\t*Core\n}\n\n\/\/ New creates and returns a database object for SQL server.\n\/\/ It implements the interface of gdb.Driver for extra database driver installation.\nfunc (d *DriverMssql) New(core *Core, node *ConfigNode) (DB, error) {\n\treturn &DriverMssql{\n\t\tCore: core,\n\t}, nil\n}\n\n\/\/ Open creates and returns a underlying sql.DB object for mssql.\nfunc (d *DriverMssql) Open(config *ConfigNode) (*sql.DB, error) {\n\tsource := \"\"\n\tif config.LinkInfo != \"\" {\n\t\tsource = config.LinkInfo\n\t} else {\n\t\tsource = fmt.Sprintf(\n\t\t\t\"user id=%s;password=%s;server=%s;port=%s;database=%s;encrypt=disable\",\n\t\t\tconfig.User, config.Pass, config.Host, config.Port, config.Name,\n\t\t)\n\t}\n\tintlog.Printf(\"Open: %s\", source)\n\tif db, err := sql.Open(\"sqlserver\", source); err == nil {\n\t\treturn db, nil\n\t} else {\n\t\treturn nil, err\n\t}\n}\n\n\/\/ GetChars returns the security char for this type of database.\nfunc (d *DriverMssql) GetChars() (charLeft string, charRight string) {\n\treturn \"\\\"\", \"\\\"\"\n}\n\n\/\/ HandleSqlBeforeCommit deals with the sql string before commits it to underlying sql driver.\nfunc (d *DriverMssql) HandleSqlBeforeCommit(link Link, query string, args []interface{}) (string, []interface{}) {\n\tvar index int\n\t\/\/ Convert place holder char '?' to string \"@px\".\n\tstr, _ := gregex.ReplaceStringFunc(\"\\\\?\", query, func(s string) string {\n\t\tindex++\n\t\treturn fmt.Sprintf(\"@p%d\", index)\n\t})\n\tstr, _ = gregex.ReplaceString(\"\\\"\", \"\", str)\n\treturn d.parseSql(str), args\n}\n\nfunc (d *DriverMssql) parseSql(sql string) string {\n\t\/\/ SELECT * FROM USER WHERE ID=1 LIMIT 1\n\tif m, _ := gregex.MatchString(`^SELECT(.+)LIMIT 1$`, sql); len(m) > 1 {\n\t\treturn fmt.Sprintf(`SELECT TOP 1 %s`, m[1])\n\t}\n\t\/\/ SELECT * FROM USER WHERE AGE>18 ORDER BY ID DESC LIMIT 100, 200\n\tpatten := `^\\s*(?i)(SELECT)|(LIMIT\\s*(\\d+)\\s*,\\s*(\\d+))`\n\tif gregex.IsMatchString(patten, sql) == false {\n\t\treturn sql\n\t}\n\tres, err := gregex.MatchAllString(patten, sql)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\tindex := 0\n\tkeyword := strings.TrimSpace(res[index][0])\n\tkeyword = strings.ToUpper(keyword)\n\tindex++\n\tswitch keyword {\n\tcase \"SELECT\":\n\t\t\/\/ 不含LIMIT关键字则不处理\n\t\tif len(res) < 2 ||\n\t\t\t(strings.HasPrefix(res[index][0], \"LIMIT\") == false &&\n\t\t\t\tstrings.HasPrefix(res[index][0], \"limit\") == false) {\n\t\t\tbreak\n\t\t}\n\t\t\/\/ 不含LIMIT则不处理\n\t\tif gregex.IsMatchString(\"((?i)SELECT)(.+)((?i)LIMIT)\", sql) == false {\n\t\t\tbreak\n\t\t}\n\t\t\/\/ 判断SQL中是否含有order by\n\t\tselectStr := \"\"\n\t\torderStr := \"\"\n\t\thaveOrder := gregex.IsMatchString(\"((?i)SELECT)(.+)((?i)ORDER BY)\", sql)\n\t\tif haveOrder {\n\t\t\t\/\/ 取order by 前面的字符串\n\t\t\tqueryExpr, _ := gregex.MatchString(\"((?i)SELECT)(.+)((?i)ORDER BY)\", sql)\n\t\t\tif len(queryExpr) != 4 ||\n\t\t\t\tstrings.EqualFold(queryExpr[1], \"SELECT\") == false ||\n\t\t\t\tstrings.EqualFold(queryExpr[3], \"ORDER BY\") == false {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tselectStr = queryExpr[2]\n\n\t\t\t\/\/ 取order by表达式的值\n\t\t\torderExpr, _ := gregex.MatchString(\"((?i)ORDER BY)(.+)((?i)LIMIT)\", sql)\n\t\t\tif len(orderExpr) != 4 ||\n\t\t\t\tstrings.EqualFold(orderExpr[1], \"ORDER BY\") == false ||\n\t\t\t\tstrings.EqualFold(orderExpr[3], \"LIMIT\") == false {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\torderStr = orderExpr[2]\n\t\t} else {\n\t\t\tqueryExpr, _ := gregex.MatchString(\"((?i)SELECT)(.+)((?i)LIMIT)\", sql)\n\t\t\tif len(queryExpr) != 4 ||\n\t\t\t\tstrings.EqualFold(queryExpr[1], \"SELECT\") == false ||\n\t\t\t\tstrings.EqualFold(queryExpr[3], \"LIMIT\") == false {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tselectStr = queryExpr[2]\n\t\t}\n\n\t\t\/\/ 取limit后面的取值范围\n\t\tfirst, limit := 0, 0\n\t\tfor i := 1; i < len(res[index]); i++ {\n\t\t\tif len(strings.TrimSpace(res[index][i])) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif strings.HasPrefix(res[index][i], \"LIMIT\") ||\n\t\t\t\tstrings.HasPrefix(res[index][i], \"limit\") {\n\t\t\t\tfirst, _ = strconv.Atoi(res[index][i+1])\n\t\t\t\tlimit, _ = strconv.Atoi(res[index][i+2])\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif haveOrder {\n\t\t\tsql = fmt.Sprintf(\n\t\t\t\t\"SELECT * FROM \"+\n\t\t\t\t\t\"(SELECT ROW_NUMBER() OVER (ORDER BY %s) as ROWNUMBER_, %s ) as TMP_ \"+\n\t\t\t\t\t\"WHERE TMP_.ROWNUMBER_ > %d AND TMP_.ROWNUMBER_ <= %d\",\n\t\t\t\torderStr, selectStr, first, first+limit,\n\t\t\t)\n\t\t} else {\n\t\t\tif first == 0 {\n\t\t\t\tfirst = limit\n\t\t\t}\n\t\t\tsql = fmt.Sprintf(\n\t\t\t\t\"SELECT * FROM (SELECT TOP %d * FROM (SELECT TOP %d %s) as TMP1_ ) as TMP2_ \",\n\t\t\t\tlimit, first+limit, selectStr,\n\t\t\t)\n\t\t}\n\tdefault:\n\t}\n\treturn sql\n}\n\n\/\/ Tables retrieves and returns the tables of current schema.\n\/\/ It's mainly used in cli tool chain for automatically generating the models.\nfunc (d *DriverMssql) Tables(schema ...string) (tables []string, err error) {\n\tvar result Result\n\tlink, err := d.DB.GetSlave(schema...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult, err = d.DB.DoGetAll(link, `SELECT NAME FROM SYSOBJECTS WHERE XTYPE='U' AND STATUS >= 0 ORDER BY NAME`)\n\tif err != nil {\n\t\treturn\n\t}\n\tfor _, m := range result {\n\t\tfor _, v := range m {\n\t\t\ttables = append(tables, v.String())\n\t\t}\n\t}\n\treturn\n}\n\n\/\/ TableFields retrieves and returns the fields information of specified table of current schema.\nfunc (d *DriverMssql) TableFields(table string, schema ...string) (fields map[string]*TableField, err error) {\n\ttable = gstr.Trim(table)\n\tif gstr.Contains(table, \" \") {\n\t\tpanic(\"function TableFields supports only single table operations\")\n\t}\n\tcheckSchema := d.DB.GetSchema()\n\tif len(schema) > 0 && schema[0] != \"\" {\n\t\tcheckSchema = schema[0]\n\t}\n\tv := d.DB.GetCache().GetOrSetFunc(\n\t\tfmt.Sprintf(`mssql_table_fields_%s_%s`, table, checkSchema), func() interface{} {\n\t\t\tvar result Result\n\t\t\tvar link *sql.DB\n\t\t\tlink, err = d.DB.GetSlave(checkSchema)\n\t\t\tif err != nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tresult, err = d.DB.DoGetAll(link, fmt.Sprintf(`\n\t\t\tSELECT c.name as FIELD, CASE t.name \n\t\t\t\tWHEN 'numeric' THEN t.name + '(' + convert(varchar(20),c.xprec) + ',' + convert(varchar(20),c.xscale) + ')' \n\t\t\t\tWHEN 'char' THEN t.name + '(' + convert(varchar(20),c.length)+ ')'\n\t\t\t\tWHEN 'varchar' THEN t.name + '(' + convert(varchar(20),c.length)+ ')'\n\t\t\t\tELSE t.name + '(' + convert(varchar(20),c.length)+ ')' END as TYPE\n\t\t\tFROM systypes t,syscolumns c WHERE t.xtype=c.xtype \n\t\t\tAND c.id = (SELECT id FROM sysobjects WHERE name='%s') \n\t\t\tORDER BY c.colid`, strings.ToUpper(table)))\n\t\t\tif err != nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tfields = make(map[string]*TableField)\n\t\t\tfor i, m := range result {\n\t\t\t\tfields[strings.ToLower(m[\"FIELD\"].String())] = &TableField{\n\t\t\t\t\tIndex: i,\n\t\t\t\t\tName:  strings.ToLower(m[\"FIELD\"].String()),\n\t\t\t\t\tType:  strings.ToLower(m[\"TYPE\"].String()),\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn fields\n\t\t}, 0)\n\tif err == nil {\n\t\tfields = v.(map[string]*TableField)\n\t}\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package providers\n\nimport (\n\t\"os\"\n\t\"strings\"\n\n\t\"golang.org\/x\/net\/context\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\tconplicity \"github.com\/camptocamp\/conplicity\/lib\"\n\t\"github.com\/docker\/engine-api\/types\"\n\t\"github.com\/fsouza\/go-dockerclient\"\n)\n\n\/\/ A Provider is an interface for providers\ntype Provider interface {\n\tGetName() string\n\tGetPrepareCommand(*types.MountPoint) []string\n\tGetHandler() *conplicity.Conplicity\n\tGetVolume() *types.Volume\n\tGetBackupDir() string\n\tBackupVolume(*types.Volume) error\n}\n\n\/\/ BaseProvider is a struct implementing the Provider interface\ntype BaseProvider struct {\n\thandler   *conplicity.Conplicity\n\tvol       *types.Volume\n\tbackupDir string\n}\n\n\/\/ GetProvider detects which provider suits the passed volume and returns it\nfunc GetProvider(c *conplicity.Conplicity, v *types.Volume) Provider {\n\tlog.WithFields(log.Fields{\n\t\t\"volume\": v.Name,\n\t}).Info(\"Detecting provider\")\n\tp := &BaseProvider{\n\t\thandler: c,\n\t\tvol:     v,\n\t}\n\tif f, err := os.Stat(v.Mountpoint + \"\/PG_VERSION\"); err == nil && f.Mode().IsRegular() {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"volume\": v.Name,\n\t\t}).Debug(\"PG_VERSION file found, this should be a PostgreSQL datadir\")\n\t\treturn &PostgreSQLProvider{\n\t\t\tBaseProvider: p,\n\t\t}\n\t} else if f, err := os.Stat(v.Mountpoint + \"\/mysql\"); err == nil && f.Mode().IsDir() {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"volume\": v.Name,\n\t\t}).Debug(\"mysql directory found, this should be MySQL datadir\")\n\t\treturn &MySQLProvider{\n\t\t\tBaseProvider: p,\n\t\t}\n\t} else if f, err := os.Stat(v.Mountpoint + \"\/DB_CONFIG\"); err == nil && f.Mode().IsRegular() {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"volume\": v.Name,\n\t\t}).Debug(\"DB_CONFIG file found, this should be and OpenLDAP datadir\")\n\t\treturn &OpenLDAPProvider{\n\t\t\tBaseProvider: p,\n\t\t}\n\t}\n\n\treturn &DefaultProvider{\n\t\tBaseProvider: p,\n\t}\n}\n\n\/\/ PrepareBackup sets up the data before backup\nfunc PrepareBackup(p Provider) (err error) {\n\tc := p.GetHandler()\n\tvol := p.GetVolume()\n\tcontainers, err := c.ContainerList(context.Background(), types.ContainerListOptions{})\n\tconplicity.CheckErr(err, \"Failed to list containers: %v\", \"fatal\")\n\n\t\/\/ Work around https:\/\/github.com\/docker\/engine-api\/issues\/303\n\tclient, err := docker.NewClient(c.Config.Docker.Endpoint, \"\", nil, nil)\n\tCheckErr(err, \"Failed to create new Docker client: %v\", \"fatal\")\n\n\tfor _, container := range containers {\n\t\tcontainer, err := client.ContainerInspect(context.Background(), container.ID)\n\t\tconplicity.CheckErr(err, \"Failed to inspect container \"+container.ID+\": %v\", \"fatal\")\n\t\tfor _, mount := range container.Mounts {\n\t\t\tif mount.Name == vol.Name {\n\t\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\t\"volume\":    vol.Name,\n\t\t\t\t\t\"container\": container.ID,\n\t\t\t\t}).Debug(\"Container found using volume\")\n\n\t\t\t\tcmd := p.GetPrepareCommand(&mount)\n\t\t\t\tif cmd != nil {\n\t\t\t\t\texec, err := client.ContainerExecCreate(context.Background(), container.ID, types.ExecConfig{\n\t\t\t\t\t\tCmd: p.GetPrepareCommand(&mount),\n\t\t\t\t\t},\n\t\t\t\t\t)\n\n\t\t\t\t\tconplicity.CheckErr(err, \"Failed to create exec: %v\", \"fatal\")\n\n\t\t\t\t\terr = client.ContainerExecStart(context.Background(), exec.ID, types.ExecStartCheck{})\n\n\t\t\t\t\tconplicity.CheckErr(err, \"Failed to start exec: %v\", \"fatal\")\n\t\t\t\t} else {\n\t\t\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\t\t\"volume\":    vol.Name,\n\t\t\t\t\t\t\"container\": container.ID,\n\t\t\t\t\t}).Info(\"No prepare command to execute in container\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\n\/\/ BackupVolume performs the backup of the passed volume\nfunc (p *BaseProvider) BackupVolume(vol *types.Volume) (err error) {\n\tlog.WithFields(log.Fields{\n\t\t\"volume\":     vol.Name,\n\t\t\"driver\":     vol.Driver,\n\t\t\"mountpoint\": vol.Mountpoint,\n\t}).Info(\"Creating duplicity container\")\n\n\tc := p.GetHandler()\n\n\tfullIfOlderThan, _ := conplicity.GetVolumeLabel(vol, \".full_if_older_than\")\n\tif fullIfOlderThan == \"\" {\n\t\tfullIfOlderThan = c.Config.Duplicity.FullIfOlderThan\n\t}\n\n\tremoveOlderThan, _ := conplicity.GetVolumeLabel(vol, \".remove_older_than\")\n\tif removeOlderThan == \"\" {\n\t\tremoveOlderThan = c.Config.Duplicity.RemoveOlderThan\n\t}\n\n\tpathSeparator := \"\/\"\n\tif strings.HasPrefix(c.Config.Duplicity.TargetURL, \"swift:\/\/\") {\n\t\t\/\/ Looks like I'm not the one to fall on this issue: http:\/\/stackoverflow.com\/questions\/27991960\/upload-to-swift-pseudo-folders-using-duplicity\n\t\tpathSeparator = \"_\"\n\t}\n\n\tbackupDir := p.GetBackupDir()\n\tfullTarget := c.Config.Duplicity.TargetURL + pathSeparator + c.Hostname + pathSeparator + vol.Name\n\tfullBackupDir := vol.Mountpoint + \"\/\" + backupDir\n\troMount := vol.Name + \":\" + vol.Mountpoint + \":ro\"\n\n\tvolume := &conplicity.Volume{\n\t\tName:            vol.Name,\n\t\tTarget:          fullTarget,\n\t\tBackupDir:       fullBackupDir,\n\t\tMount:           roMount,\n\t\tFullIfOlderThan: fullIfOlderThan,\n\t\tRemoveOlderThan: removeOlderThan,\n\t\tClient:          c,\n\t}\n\n\tvar newMetrics []string\n\n\tnewMetrics, err = volume.Backup()\n\tconplicity.CheckErr(err, \"Failed to backup volume \"+vol.Name+\" : %v\", \"fatal\")\n\tc.Metrics = append(c.Metrics, newMetrics...)\n\n\t_, err = volume.RemoveOld()\n\tconplicity.CheckErr(err, \"Failed to remove old backups for volume \"+vol.Name+\" : %v\", \"fatal\")\n\n\t_, err = volume.Cleanup()\n\tconplicity.CheckErr(err, \"Failed to cleanup extraneous duplicity files for volume \"+vol.Name+\" : %v\", \"fatal\")\n\n\tnoVerifyLbl, _ := conplicity.GetVolumeLabel(vol, \".no_verify\")\n\tnoVerify := c.Config.NoVerify || (noVerifyLbl == \"true\")\n\tif noVerify {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"volume\": vol.Name,\n\t\t}).Info(\"Skipping verification\")\n\t} else {\n\t\tnewMetrics, err = volume.Verify()\n\t\tconplicity.CheckErr(err, \"Failed to verify backup for volume \"+vol.Name+\" : %v\", \"fatal\")\n\t\tc.Metrics = append(c.Metrics, newMetrics...)\n\t}\n\n\tnewMetrics, err = volume.Status()\n\tconplicity.CheckErr(err, \"Failed to retrieve last backup info for volume \"+vol.Name+\" : %v\", \"fatal\")\n\tc.Metrics = append(c.Metrics, newMetrics...)\n\n\treturn\n}\n\n\/\/ GetHandler returns the handler associated with the provider\nfunc (p *BaseProvider) GetHandler() *conplicity.Conplicity {\n\treturn p.handler\n}\n\n\/\/ GetVolume returns the volume associated with the provider\nfunc (p *BaseProvider) GetVolume() *types.Volume {\n\treturn p.vol\n}\n\n\/\/ GetBackupDir returns the backup directory used by the provider\nfunc (p *BaseProvider) GetBackupDir() string {\n\treturn p.backupDir\n}\n<commit_msg>Fix previous commit<commit_after>package providers\n\nimport (\n\t\"os\"\n\t\"strings\"\n\n\t\"golang.org\/x\/net\/context\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\tconplicity \"github.com\/camptocamp\/conplicity\/lib\"\n\tdocker \"github.com\/docker\/engine-api\/client\"\n\t\"github.com\/docker\/engine-api\/types\"\n)\n\n\/\/ A Provider is an interface for providers\ntype Provider interface {\n\tGetName() string\n\tGetPrepareCommand(*types.MountPoint) []string\n\tGetHandler() *conplicity.Conplicity\n\tGetVolume() *types.Volume\n\tGetBackupDir() string\n\tBackupVolume(*types.Volume) error\n}\n\n\/\/ BaseProvider is a struct implementing the Provider interface\ntype BaseProvider struct {\n\thandler   *conplicity.Conplicity\n\tvol       *types.Volume\n\tbackupDir string\n}\n\n\/\/ GetProvider detects which provider suits the passed volume and returns it\nfunc GetProvider(c *conplicity.Conplicity, v *types.Volume) Provider {\n\tlog.WithFields(log.Fields{\n\t\t\"volume\": v.Name,\n\t}).Info(\"Detecting provider\")\n\tp := &BaseProvider{\n\t\thandler: c,\n\t\tvol:     v,\n\t}\n\tif f, err := os.Stat(v.Mountpoint + \"\/PG_VERSION\"); err == nil && f.Mode().IsRegular() {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"volume\": v.Name,\n\t\t}).Debug(\"PG_VERSION file found, this should be a PostgreSQL datadir\")\n\t\treturn &PostgreSQLProvider{\n\t\t\tBaseProvider: p,\n\t\t}\n\t} else if f, err := os.Stat(v.Mountpoint + \"\/mysql\"); err == nil && f.Mode().IsDir() {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"volume\": v.Name,\n\t\t}).Debug(\"mysql directory found, this should be MySQL datadir\")\n\t\treturn &MySQLProvider{\n\t\t\tBaseProvider: p,\n\t\t}\n\t} else if f, err := os.Stat(v.Mountpoint + \"\/DB_CONFIG\"); err == nil && f.Mode().IsRegular() {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"volume\": v.Name,\n\t\t}).Debug(\"DB_CONFIG file found, this should be and OpenLDAP datadir\")\n\t\treturn &OpenLDAPProvider{\n\t\t\tBaseProvider: p,\n\t\t}\n\t}\n\n\treturn &DefaultProvider{\n\t\tBaseProvider: p,\n\t}\n}\n\n\/\/ PrepareBackup sets up the data before backup\nfunc PrepareBackup(p Provider) (err error) {\n\tc := p.GetHandler()\n\tvol := p.GetVolume()\n\tcontainers, err := c.ContainerList(context.Background(), types.ContainerListOptions{})\n\tconplicity.CheckErr(err, \"Failed to list containers: %v\", \"fatal\")\n\n\t\/\/ Work around https:\/\/github.com\/docker\/engine-api\/issues\/303\n\tclient, err := docker.NewClient(c.Config.Docker.Endpoint, \"\", nil, nil)\n\tconplicity.CheckErr(err, \"Failed to create new Docker client: %v\", \"fatal\")\n\n\tfor _, container := range containers {\n\t\tcontainer, err := client.ContainerInspect(context.Background(), container.ID)\n\t\tconplicity.CheckErr(err, \"Failed to inspect container \"+container.ID+\": %v\", \"fatal\")\n\t\tfor _, mount := range container.Mounts {\n\t\t\tif mount.Name == vol.Name {\n\t\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\t\"volume\":    vol.Name,\n\t\t\t\t\t\"container\": container.ID,\n\t\t\t\t}).Debug(\"Container found using volume\")\n\n\t\t\t\tcmd := p.GetPrepareCommand(&mount)\n\t\t\t\tif cmd != nil {\n\t\t\t\t\texec, err := client.ContainerExecCreate(context.Background(), container.ID, types.ExecConfig{\n\t\t\t\t\t\tCmd: p.GetPrepareCommand(&mount),\n\t\t\t\t\t},\n\t\t\t\t\t)\n\n\t\t\t\t\tconplicity.CheckErr(err, \"Failed to create exec: %v\", \"fatal\")\n\n\t\t\t\t\terr = client.ContainerExecStart(context.Background(), exec.ID, types.ExecStartCheck{})\n\n\t\t\t\t\tconplicity.CheckErr(err, \"Failed to start exec: %v\", \"fatal\")\n\t\t\t\t} else {\n\t\t\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\t\t\"volume\":    vol.Name,\n\t\t\t\t\t\t\"container\": container.ID,\n\t\t\t\t\t}).Info(\"No prepare command to execute in container\")\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\n\n\/\/ BackupVolume performs the backup of the passed volume\nfunc (p *BaseProvider) BackupVolume(vol *types.Volume) (err error) {\n\tlog.WithFields(log.Fields{\n\t\t\"volume\":     vol.Name,\n\t\t\"driver\":     vol.Driver,\n\t\t\"mountpoint\": vol.Mountpoint,\n\t}).Info(\"Creating duplicity container\")\n\n\tc := p.GetHandler()\n\n\tfullIfOlderThan, _ := conplicity.GetVolumeLabel(vol, \".full_if_older_than\")\n\tif fullIfOlderThan == \"\" {\n\t\tfullIfOlderThan = c.Config.Duplicity.FullIfOlderThan\n\t}\n\n\tremoveOlderThan, _ := conplicity.GetVolumeLabel(vol, \".remove_older_than\")\n\tif removeOlderThan == \"\" {\n\t\tremoveOlderThan = c.Config.Duplicity.RemoveOlderThan\n\t}\n\n\tpathSeparator := \"\/\"\n\tif strings.HasPrefix(c.Config.Duplicity.TargetURL, \"swift:\/\/\") {\n\t\t\/\/ Looks like I'm not the one to fall on this issue: http:\/\/stackoverflow.com\/questions\/27991960\/upload-to-swift-pseudo-folders-using-duplicity\n\t\tpathSeparator = \"_\"\n\t}\n\n\tbackupDir := p.GetBackupDir()\n\tfullTarget := c.Config.Duplicity.TargetURL + pathSeparator + c.Hostname + pathSeparator + vol.Name\n\tfullBackupDir := vol.Mountpoint + \"\/\" + backupDir\n\troMount := vol.Name + \":\" + vol.Mountpoint + \":ro\"\n\n\tvolume := &conplicity.Volume{\n\t\tName:            vol.Name,\n\t\tTarget:          fullTarget,\n\t\tBackupDir:       fullBackupDir,\n\t\tMount:           roMount,\n\t\tFullIfOlderThan: fullIfOlderThan,\n\t\tRemoveOlderThan: removeOlderThan,\n\t\tClient:          c,\n\t}\n\n\tvar newMetrics []string\n\n\tnewMetrics, err = volume.Backup()\n\tconplicity.CheckErr(err, \"Failed to backup volume \"+vol.Name+\" : %v\", \"fatal\")\n\tc.Metrics = append(c.Metrics, newMetrics...)\n\n\t_, err = volume.RemoveOld()\n\tconplicity.CheckErr(err, \"Failed to remove old backups for volume \"+vol.Name+\" : %v\", \"fatal\")\n\n\t_, err = volume.Cleanup()\n\tconplicity.CheckErr(err, \"Failed to cleanup extraneous duplicity files for volume \"+vol.Name+\" : %v\", \"fatal\")\n\n\tnoVerifyLbl, _ := conplicity.GetVolumeLabel(vol, \".no_verify\")\n\tnoVerify := c.Config.NoVerify || (noVerifyLbl == \"true\")\n\tif noVerify {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"volume\": vol.Name,\n\t\t}).Info(\"Skipping verification\")\n\t} else {\n\t\tnewMetrics, err = volume.Verify()\n\t\tconplicity.CheckErr(err, \"Failed to verify backup for volume \"+vol.Name+\" : %v\", \"fatal\")\n\t\tc.Metrics = append(c.Metrics, newMetrics...)\n\t}\n\n\tnewMetrics, err = volume.Status()\n\tconplicity.CheckErr(err, \"Failed to retrieve last backup info for volume \"+vol.Name+\" : %v\", \"fatal\")\n\tc.Metrics = append(c.Metrics, newMetrics...)\n\n\treturn\n}\n\n\/\/ GetHandler returns the handler associated with the provider\nfunc (p *BaseProvider) GetHandler() *conplicity.Conplicity {\n\treturn p.handler\n}\n\n\/\/ GetVolume returns the volume associated with the provider\nfunc (p *BaseProvider) GetVolume() *types.Volume {\n\treturn p.vol\n}\n\n\/\/ GetBackupDir returns the backup directory used by the provider\nfunc (p *BaseProvider) GetBackupDir() string {\n\treturn p.backupDir\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ bulk_data_gen generates time series data from pre-specified use cases.\n\/\/\n\/\/ Supported formats:\n\/\/ InfluxDB bulk load format\n\/\/ ElasticSearch bulk load format\n\/\/ Cassandra query format\n\/\/ Mongo custom format\n\/\/ OpenTSDB bulk HTTP format\n\/\/ TimescaleDB SQL INSERT and binary COPY FROM\n\/\/ Graphite plaintext format\n\/\/ Splunk JSON format\n\/\/\n\/\/ Supported use cases:\n\/\/ Devops: scale_var is the number of hosts to simulate, with log messages\n\/\/         every 10 seconds.\npackage main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/influxdata\/influxdb-comparisons\/bulk_data_gen\/common\"\n\t\"github.com\/influxdata\/influxdb-comparisons\/bulk_data_gen\/dashboard\"\n\t\"github.com\/influxdata\/influxdb-comparisons\/bulk_data_gen\/devops\"\n\t\"github.com\/influxdata\/influxdb-comparisons\/bulk_data_gen\/iot\"\n\t\"log\"\n\t\"os\"\n\t\"runtime\/pprof\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ Output data format choices:\nvar formatChoices = []string{\"influx-bulk\", \"es-bulk\", \"es-bulk6x\", \"cassandra\", \"mongo\", \"opentsdb\", \"timescaledb-sql\", \"timescaledb-copyFrom\", \"graphite-line\", \"splunk-json\"}\n\n\/\/ Program option vars:\nvar (\n\tdaemonUrl string\n\tdbName    string\n\n\tformat           string\n\tuseCase          string\n\tconfigFile       string\n\tscaleVar         int64\n\tscaleVarOffset   int64\n\tsamplingInterval time.Duration\n\n\ttimestampStartStr string\n\ttimestampEndStr   string\n\n\ttimestampStart time.Time\n\ttimestampEnd   time.Time\n\n\tinterleavedGenerationGroupID uint\n\tinterleavedGenerationGroups  uint\n\n\tseed  int64\n\tdebug int\n\n\tcpuProfile string\n)\n\n\/\/ Parse args:\nfunc init() {\n\tflag.StringVar(&format, \"format\", formatChoices[0], fmt.Sprintf(\"Format to emit. (choices: %s)\", strings.Join(formatChoices, \", \")))\n\n\tflag.StringVar(&useCase, \"use-case\", common.UseCaseChoices[0], fmt.Sprintf(\"Use case to model. (choices: %s)\", strings.Join(common.UseCaseChoices, \", \")))\n\tflag.Int64Var(&scaleVar, \"scale-var\", 1, \"Scaling variable specific to the use case.\")\n\tflag.Int64Var(&scaleVarOffset, \"scale-var-offset\", 0, \"Scaling variable offset specific to the use case.\")\n\tflag.DurationVar(&samplingInterval, \"sampling-interval\", devops.EpochDuration, \"Simulated sampling interval.\")\n\tflag.StringVar(&configFile, \"config-file\", \"\", \"Simulator config file in TOML format (experimental)\")\n\n\tflag.StringVar(&timestampStartStr, \"timestamp-start\", common.DefaultDateTimeStart, \"Beginning timestamp (RFC3339).\")\n\tflag.StringVar(&timestampEndStr, \"timestamp-end\", common.DefaultDateTimeEnd, \"Ending timestamp (RFC3339).\")\n\n\tflag.Int64Var(&seed, \"seed\", 0, \"PRNG seed (default, or 0, uses the current timestamp).\")\n\tflag.IntVar(&debug, \"debug\", 0, \"Debug printing (choices: 0, 1, 2) (default 0).\")\n\n\tflag.UintVar(&interleavedGenerationGroupID, \"interleaved-generation-group-id\", 0, \"Group (0-indexed) to perform round-robin serialization within. Use this to scale up data generation to multiple processes.\")\n\tflag.UintVar(&interleavedGenerationGroups, \"interleaved-generation-groups\", 1, \"The number of round-robin serialization groups. Use this to scale up data generation to multiple processes.\")\n\n\tflag.StringVar(&cpuProfile, \"cpu-profile\", \"\", \"Write CPU profile to `file`\")\n\n\tflag.Parse()\n\n\tif !(interleavedGenerationGroupID < interleavedGenerationGroups) {\n\t\tlog.Fatal(\"incorrect interleaved groups configuration\")\n\t}\n\n\tvalidFormat := false\n\tfor _, s := range formatChoices {\n\t\tif s == format {\n\t\t\tvalidFormat = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !validFormat {\n\t\tlog.Fatalf(\"invalid format specifier: %v\", format)\n\t}\n\n\t\/\/ the default seed is the current timestamp:\n\tif seed == 0 {\n\t\tseed = int64(time.Now().Nanosecond())\n\t}\n\tfmt.Fprintf(os.Stderr, \"using random seed %d\\n\", seed)\n\n\t\/\/ Parse timestamps:\n\tvar err error\n\ttimestampStart, err = time.Parse(time.RFC3339, timestampStartStr)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\ttimestampStart = timestampStart.UTC()\n\ttimestampEnd, err = time.Parse(time.RFC3339, timestampEndStr)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\ttimestampEnd = timestampEnd.UTC()\n\n\tif samplingInterval <= 0 {\n\t\tlog.Fatal(\"Invalid sampling interval\")\n\t}\n\tdevops.EpochDuration = samplingInterval\n\tlog.Printf(\"Using sampling interval %v\\n\", devops.EpochDuration)\n}\n\nfunc main() {\n\tif cpuProfile != \"\" {\n\t\tf, err := os.Create(cpuProfile)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"could not create CPU profile: \", err)\n\t\t}\n\t\tif err := pprof.StartCPUProfile(f); err != nil {\n\t\t\tlog.Fatal(\"could not start CPU profile: \", err)\n\t\t}\n\t\tdefer pprof.StopCPUProfile()\n\t}\n\n\tcommon.Seed(seed)\n\n\tif configFile != \"\" {\n\t\tc, err := common.NewConfig(configFile)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"external config error: %v\", err)\n\t\t}\n\t\tcommon.Config = c\n\t\tlog.Printf(\"Using config file %s\\n\", configFile)\n\t}\n\n\tout := bufio.NewWriterSize(os.Stdout, 4<<20)\n\tdefer out.Flush()\n\n\tvar sim common.Simulator\n\n\tswitch useCase {\n\tcase common.UseCaseChoices[0]:\n\t\tcfg := &devops.DevopsSimulatorConfig{\n\t\t\tStart: timestampStart,\n\t\t\tEnd:   timestampEnd,\n\n\t\t\tHostCount:  scaleVar,\n\t\t\tHostOffset: scaleVarOffset,\n\t\t}\n\t\tsim = cfg.ToSimulator()\n\tcase common.UseCaseChoices[2]:\n\t\tcfg := &dashboard.DashboardSimulatorConfig{\n\t\t\tStart: timestampStart,\n\t\t\tEnd:   timestampEnd,\n\n\t\t\tHostCount:  scaleVar,\n\t\t\tHostOffset: scaleVarOffset,\n\t\t}\n\t\tsim = cfg.ToSimulator()\n\tcase common.UseCaseChoices[1]:\n\t\tcfg := &iot.IotSimulatorConfig{\n\t\t\tStart: timestampStart,\n\t\t\tEnd:   timestampEnd,\n\n\t\t\tSmartHomeCount:  scaleVar,\n\t\t\tSmartHomeOffset: scaleVarOffset,\n\t\t}\n\t\tsim = cfg.ToSimulator()\n\tdefault:\n\t\tpanic(\"unreachable\")\n\t}\n\n\tvar serializer common.Serializer\n\tswitch format {\n\tcase \"influx-bulk\":\n\t\tserializer = common.NewSerializerInflux()\n\tcase \"es-bulk\":\n\t\tserializer = common.NewSerializerElastic(\"5x\")\n\tcase \"es-bulk6x\":\n\t\tserializer = common.NewSerializerElastic(\"6x\")\n\tcase \"cassandra\":\n\t\tserializer = common.NewSerializerCassandra()\n\tcase \"mongo\":\n\t\tserializer = common.NewSerializerMongo()\n\tcase \"opentsdb\":\n\t\tserializer = common.NewSerializerOpenTSDB()\n\tcase \"timescaledb-sql\":\n\t\tserializer = common.NewSerializerTimescaleSql()\n\tcase \"timescaledb-copyFrom\":\n\t\tserializer = common.NewSerializerTimescaleBin()\n\tcase \"graphite-line\":\n\t\tserializer = common.NewSerializerGraphiteLine()\n\tcase \"splunk-json\":\n\t\tserializer = common.NewSerializerSplunkJson()\n\tdefault:\n\t\tpanic(\"unreachable\")\n\t}\n\n\tvar currentInterleavedGroup uint = 0\n\n\tt := time.Now()\n\tpoint := common.MakeUsablePoint()\n\tn := int64(0)\n\tfor !sim.Finished() {\n\t\tsim.Next(point)\n\t\tn++\n\t\t\/\/ in the default case this is always true\n\t\tif currentInterleavedGroup == interleavedGenerationGroupID {\n\t\t\t\/\/println(\"printing\")\n\t\t\terr := serializer.SerializePoint(out, point)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\n\t\t}\n\t\tpoint.Reset()\n\n\t\tcurrentInterleavedGroup++\n\t\tif currentInterleavedGroup == interleavedGenerationGroups {\n\t\t\tcurrentInterleavedGroup = 0\n\t\t}\n\t}\n\tif n != sim.SeenPoints() {\n\t\tpanic(fmt.Sprintf(\"Logic error, written %d points, generated %d points\", n, sim.SeenPoints()))\n\t}\n\tserializer.SerializeSize(out, sim.SeenPoints(), sim.SeenValues())\n\terr := out.Flush()\n\tdur := time.Now().Sub(t)\n\tlog.Printf(\"Written %d points, %d values, took %0f seconds\\n\", n, sim.SeenValues(), dur.Seconds())\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t}\n}\n<commit_msg>Added updates to track execution time of bulk data generator. Also added bonitoo toml file to repo.<commit_after>\/\/ bulk_data_gen generates time series data from pre-specified use cases.\n\/\/\n\/\/ Supported formats:\n\/\/ InfluxDB bulk load format\n\/\/ ElasticSearch bulk load format\n\/\/ Cassandra query format\n\/\/ Mongo custom format\n\/\/ OpenTSDB bulk HTTP format\n\/\/ TimescaleDB SQL INSERT and binary COPY FROM\n\/\/ Graphite plaintext format\n\/\/ Splunk JSON format\n\/\/\n\/\/ Supported use cases:\n\/\/ Devops: scale_var is the number of hosts to simulate, with log messages\n\/\/         every 10 seconds.\npackage main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/influxdata\/influxdb-comparisons\/bulk_data_gen\/common\"\n\t\"github.com\/influxdata\/influxdb-comparisons\/bulk_data_gen\/dashboard\"\n\t\"github.com\/influxdata\/influxdb-comparisons\/bulk_data_gen\/devops\"\n\t\"github.com\/influxdata\/influxdb-comparisons\/bulk_data_gen\/iot\"\n\t\"log\"\n\t\"os\"\n\t\"runtime\/pprof\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ Output data format choices:\nvar formatChoices = []string{\"influx-bulk\", \"es-bulk\", \"es-bulk6x\", \"cassandra\", \"mongo\", \"opentsdb\", \"timescaledb-sql\", \"timescaledb-copyFrom\", \"graphite-line\", \"splunk-json\"}\n\n\/\/ Program option vars:\nvar (\n\tdaemonUrl string\n\tdbName    string\n\n\tformat           string\n\tuseCase          string\n\tconfigFile       string\n\tscaleVar         int64\n\tscaleVarOffset   int64\n\tsamplingInterval time.Duration\n\n\ttimestampStartStr string\n\ttimestampEndStr   string\n\n\ttimestampStart time.Time\n\ttimestampEnd   time.Time\n\n\tinterleavedGenerationGroupID uint\n\tinterleavedGenerationGroups  uint\n\n\tseed  int64\n\tdebug int\n\n\tcpuProfile string\n)\n\n\/\/ Parse args:\nfunc init() {\n\tflag.StringVar(&format, \"format\", formatChoices[0], fmt.Sprintf(\"Format to emit. (choices: %s)\", strings.Join(formatChoices, \", \")))\n\n\tflag.StringVar(&useCase, \"use-case\", common.UseCaseChoices[0], fmt.Sprintf(\"Use case to model. (choices: %s)\", strings.Join(common.UseCaseChoices, \", \")))\n\tflag.Int64Var(&scaleVar, \"scale-var\", 1, \"Scaling variable specific to the use case.\")\n\tflag.Int64Var(&scaleVarOffset, \"scale-var-offset\", 0, \"Scaling variable offset specific to the use case.\")\n\tflag.DurationVar(&samplingInterval, \"sampling-interval\", devops.EpochDuration, \"Simulated sampling interval.\")\n\tflag.StringVar(&configFile, \"config-file\", \"\", \"Simulator config file in TOML format (experimental)\")\n\n\tflag.StringVar(&timestampStartStr, \"timestamp-start\", common.DefaultDateTimeStart, \"Beginning timestamp (RFC3339).\")\n\tflag.StringVar(&timestampEndStr, \"timestamp-end\", common.DefaultDateTimeEnd, \"Ending timestamp (RFC3339).\")\n\n\tflag.Int64Var(&seed, \"seed\", 0, \"PRNG seed (default, or 0, uses the current timestamp).\")\n\tflag.IntVar(&debug, \"debug\", 0, \"Debug printing (choices: 0, 1, 2) (default 0).\")\n\n\tflag.UintVar(&interleavedGenerationGroupID, \"interleaved-generation-group-id\", 0, \"Group (0-indexed) to perform round-robin serialization within. Use this to scale up data generation to multiple processes.\")\n\tflag.UintVar(&interleavedGenerationGroups, \"interleaved-generation-groups\", 1, \"The number of round-robin serialization groups. Use this to scale up data generation to multiple processes.\")\n\n\tflag.StringVar(&cpuProfile, \"cpu-profile\", \"\", \"Write CPU profile to `file`\")\n\n\tflag.Parse()\n\n\tif !(interleavedGenerationGroupID < interleavedGenerationGroups) {\n\t\tlog.Fatal(\"incorrect interleaved groups configuration\")\n\t}\n\n\tvalidFormat := false\n\tfor _, s := range formatChoices {\n\t\tif s == format {\n\t\t\tvalidFormat = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !validFormat {\n\t\tlog.Fatalf(\"invalid format specifier: %v\", format)\n\t}\n\n\t\/\/ the default seed is the current timestamp:\n\tif seed == 0 {\n\t\tseed = int64(time.Now().Nanosecond())\n\t}\n\tfmt.Fprintf(os.Stderr, \"using random seed %d\\n\", seed)\n\n\t\/\/ Parse timestamps:\n\tvar err error\n\ttimestampStart, err = time.Parse(time.RFC3339, timestampStartStr)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\ttimestampStart = timestampStart.UTC()\n\ttimestampEnd, err = time.Parse(time.RFC3339, timestampEndStr)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\ttimestampEnd = timestampEnd.UTC()\n\n\tif samplingInterval <= 0 {\n\t\tlog.Fatal(\"Invalid sampling interval\")\n\t}\n\tdevops.EpochDuration = samplingInterval\n\tlog.Printf(\"Using sampling interval %v\\n\", devops.EpochDuration)\n}\n\nfunc timeTrack(start time.Time, name string) {\n\telapsed := time.Since(start)\n\tlog.Printf(\"%s took %s\", name, elapsed)\n}\n\n\nfunc main() {\n\tdefer timeTrack(time.Now(), \"bulk_data_gen - main()\")\n\n\tif cpuProfile != \"\" {\n\t\tf, err := os.Create(cpuProfile)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"could not create CPU profile: \", err)\n\t\t}\n\t\tif err := pprof.StartCPUProfile(f); err != nil {\n\t\t\tlog.Fatal(\"could not start CPU profile: \", err)\n\t\t}\n\t\tdefer pprof.StopCPUProfile()\n\t}\n\n\tcommon.Seed(seed)\n\n\tif configFile != \"\" {\n\t\tc, err := common.NewConfig(configFile)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"external config error: %v\", err)\n\t\t}\n\t\tcommon.Config = c\n\t\tlog.Printf(\"Using config file %s\\n\", configFile)\n\t}\n\n\t\/\/out := bufio.NewWriterSize(os.Stdout, 4<<20)\n\tout := bufio.NewWriterSize(os.Stdout, 4<<22)\n\tdefer out.Flush()\n\n\tvar sim common.Simulator\n\n\tswitch useCase {\n\tcase common.UseCaseChoices[0]:\n\t\tcfg := &devops.DevopsSimulatorConfig{\n\t\t\tStart: timestampStart,\n\t\t\tEnd:   timestampEnd,\n\n\t\t\tHostCount:  scaleVar,\n\t\t\tHostOffset: scaleVarOffset,\n\t\t}\n\t\tsim = cfg.ToSimulator()\n\tcase common.UseCaseChoices[2]:\n\t\tcfg := &dashboard.DashboardSimulatorConfig{\n\t\t\tStart: timestampStart,\n\t\t\tEnd:   timestampEnd,\n\n\t\t\tHostCount:  scaleVar,\n\t\t\tHostOffset: scaleVarOffset,\n\t\t}\n\t\tsim = cfg.ToSimulator()\n\tcase common.UseCaseChoices[1]:\n\t\tcfg := &iot.IotSimulatorConfig{\n\t\t\tStart: timestampStart,\n\t\t\tEnd:   timestampEnd,\n\n\t\t\tSmartHomeCount:  scaleVar,\n\t\t\tSmartHomeOffset: scaleVarOffset,\n\t\t}\n\t\tsim = cfg.ToSimulator()\n\tdefault:\n\t\tpanic(\"unreachable\")\n\t}\n\n\tvar serializer common.Serializer\n\tswitch format {\n\tcase \"influx-bulk\":\n\t\tserializer = common.NewSerializerInflux()\n\tcase \"es-bulk\":\n\t\tserializer = common.NewSerializerElastic(\"5x\")\n\tcase \"es-bulk6x\":\n\t\tserializer = common.NewSerializerElastic(\"6x\")\n\tcase \"cassandra\":\n\t\tserializer = common.NewSerializerCassandra()\n\tcase \"mongo\":\n\t\tserializer = common.NewSerializerMongo()\n\tcase \"opentsdb\":\n\t\tserializer = common.NewSerializerOpenTSDB()\n\tcase \"timescaledb-sql\":\n\t\tserializer = common.NewSerializerTimescaleSql()\n\tcase \"timescaledb-copyFrom\":\n\t\tserializer = common.NewSerializerTimescaleBin()\n\tcase \"graphite-line\":\n\t\tserializer = common.NewSerializerGraphiteLine()\n\tcase \"splunk-json\":\n\t\tserializer = common.NewSerializerSplunkJson()\n\tdefault:\n\t\tpanic(\"unreachable\")\n\t}\n\n\tvar currentInterleavedGroup uint = 0\n\n\tt := time.Now()\n\tpoint := common.MakeUsablePoint()\n\tn := int64(0)\n\tfor !sim.Finished() {\n\t\tsim.Next(point)\n\t\tn++\n\t\t\/\/ in the default case this is always true\n\t\tif currentInterleavedGroup == interleavedGenerationGroupID {\n\t\t\t\/\/println(\"printing\")\n\t\t\terr := serializer.SerializePoint(out, point)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\n\t\t}\n\t\tpoint.Reset()\n\n\t\tcurrentInterleavedGroup++\n\t\tif currentInterleavedGroup == interleavedGenerationGroups {\n\t\t\tcurrentInterleavedGroup = 0\n\t\t}\n\t}\n\tif n != sim.SeenPoints() {\n\t\tpanic(fmt.Sprintf(\"Logic error, written %d points, generated %d points\", n, sim.SeenPoints()))\n\t}\n\tserializer.SerializeSize(out, sim.SeenPoints(), sim.SeenValues())\n\terr := out.Flush()\n\tdur := time.Now().Sub(t)\n\tlog.Printf(\"Written %d points, %d values, took %0f seconds\\n\", n, sim.SeenValues(), dur.Seconds())\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package somaproto\n\ntype DeploymentDetails struct {\n\tRepository         string                `json:\"repository\"`\n\tEnvironment        string                `json:\"environment\"`\n\tBucket             string                `json:\"bucket\"`\n\tObjectType         string                `json:\"object_type\"`\n\tView               string                `json:\"view\"`\n\tTask               string                `json:\"task\"`\n\tDatacenter         string                `json:\"datacenter\"`\n\tCapability         *ProtoCapability      `json:\"capability\"`\n\tMonitoring         *ProtoMonitoring      `json:\"monitoring_system\"`\n\tMetric             *ProtoMetric          `json:\"metric\"`\n\tTeam               *ProtoTeam            `json:\"organizational_team\"`\n\tOncall             *ProtoOncall          `json:\"oncall,omitempty\"`\n\tService            *TreePropertyService  `json:\"service,omitempty\"`\n\tProperties         *[]TreePropertySystem `json:\"properties,omitempty\"`\n\tCustomProperties   *[]TreePropertyCustom `json:\"custom_properties,omitempty\"`\n\tGroup              *ProtoGroup           `json:\"group,omitempty\"`\n\tCluster            *ProtoCluster         `json:\"cluster,omitempty\"`\n\tNode               *ProtoNode            `json:\"node,omitempty\"`\n\tServer             *ProtoServer          `json:\"server,omitempty\"`\n\tCheckConfiguration *CheckConfiguration   `json:\"check_configuration\"`\n\tCheck              *TreeCheck            `json:\"check\"`\n\tCheckInstance      *TreeCheckInstance    `json:\"check_instance\"`\n}\n\n\/\/ vim: ts=4 sw=4 sts=4 noet fenc=utf-8 ffs=unix\n<commit_msg>Start DeploymentDetails.DeepCompare<commit_after>package somaproto\n\ntype DeploymentDetails struct {\n\tRepository         string                `json:\"repository\"`\n\tEnvironment        string                `json:\"environment\"`\n\tBucket             string                `json:\"bucket\"`\n\tObjectType         string                `json:\"object_type\"`\n\tView               string                `json:\"view\"`\n\tTask               string                `json:\"task\"`\n\tDatacenter         string                `json:\"datacenter\"`\n\tCapability         *ProtoCapability      `json:\"capability\"`\n\tMonitoring         *ProtoMonitoring      `json:\"monitoring_system\"`\n\tMetric             *ProtoMetric          `json:\"metric\"`\n\tTeam               *ProtoTeam            `json:\"organizational_team\"`\n\tOncall             *ProtoOncall          `json:\"oncall,omitempty\"`\n\tService            *TreePropertyService  `json:\"service,omitempty\"`\n\tProperties         *[]TreePropertySystem `json:\"properties,omitempty\"`\n\tCustomProperties   *[]TreePropertyCustom `json:\"custom_properties,omitempty\"`\n\tGroup              *ProtoGroup           `json:\"group,omitempty\"`\n\tCluster            *ProtoCluster         `json:\"cluster,omitempty\"`\n\tNode               *ProtoNode            `json:\"node,omitempty\"`\n\tServer             *ProtoServer          `json:\"server,omitempty\"`\n\tCheckConfiguration *CheckConfiguration   `json:\"check_configuration\"`\n\tCheck              *TreeCheck            `json:\"check\"`\n\tCheckInstance      *TreeCheckInstance    `json:\"check_instance\"`\n}\n\nfunc (dd *DeploymentDetails) DeepCompare(alternate *DeploymentDetails) bool {\n\tif dd.Repository != alternate.Repository {\n\t\treturn false\n\t}\n\tif dd.Environment != alternate.Environment {\n\t\treturn false\n\t}\n\tif dd.Bucket != alternate.Bucket {\n\t\treturn false\n\t}\n\tif dd.ObjectType != alternate.ObjectType {\n\t\treturn false\n\t}\n\tif dd.View != alternate.View {\n\t\treturn false\n\t}\n\tif dd.Task != alternate.Task {\n\t\treturn false\n\t}\n\tif dd.Datacenter != alternate.Datacenter {\n\t\treturn false\n\t}\n\t\/\/if !dd.Capability.DeepCompare(alternate.Capability) {\n\t\/\/\treturn false\n\t\/\/}\n\treturn true\n}\n\n\/\/ vim: ts=4 sw=4 sts=4 noet fenc=utf-8 ffs=unix\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2018 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ +build aix solaris,!illumos\n\n\/\/ This code implements the filelock API using POSIX 'fcntl' locks, which attach\n\/\/ to an (inode, process) pair rather than a file descriptor. To avoid unlocking\n\/\/ files prematurely when the same file is opened through different descriptors,\n\/\/ we allow only one read-lock at a time.\n\/\/\n\/\/ Most platforms provide some alternative API, such as an 'flock' system call\n\/\/ or an F_OFD_SETLK command for 'fcntl', that allows for better concurrency and\n\/\/ does not require per-inode bookkeeping in the application.\n\/\/\n\/\/ TODO(golang.org\/issue\/35618): add a syscall.Flock binding for Illumos and\n\/\/ switch it over to use filelock_unix.go.\n\npackage filelock\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"math\/rand\"\n\t\"os\"\n\t\"sync\"\n\t\"syscall\"\n\t\"time\"\n)\n\ntype lockType int16\n\nconst (\n\treadLock  lockType = syscall.F_RDLCK\n\twriteLock lockType = syscall.F_WRLCK\n)\n\ntype inode = uint64 \/\/ type of syscall.Stat_t.Ino\n\ntype inodeLock struct {\n\towner File\n\tqueue []<-chan File\n}\n\ntype token struct{}\n\nvar (\n\tmu     sync.Mutex\n\tinodes = map[File]inode{}\n\tlocks  = map[inode]inodeLock{}\n)\n\nfunc lock(f File, lt lockType) (err error) {\n\t\/\/ POSIX locks apply per inode and process, and the lock for an inode is\n\t\/\/ released when *any* descriptor for that inode is closed. So we need to\n\t\/\/ synchronize access to each inode internally, and must serialize lock and\n\t\/\/ unlock calls that refer to the same inode through different descriptors.\n\tfi, err := f.Stat()\n\tif err != nil {\n\t\treturn err\n\t}\n\tino := fi.Sys().(*syscall.Stat_t).Ino\n\n\tmu.Lock()\n\tif i, dup := inodes[f]; dup && i != ino {\n\t\tmu.Unlock()\n\t\treturn &os.PathError{\n\t\t\tOp:   lt.String(),\n\t\t\tPath: f.Name(),\n\t\t\tErr:  errors.New(\"inode for file changed since last Lock or RLock\"),\n\t\t}\n\t}\n\tinodes[f] = ino\n\n\tvar wait chan File\n\tl := locks[ino]\n\tif l.owner == f {\n\t\t\/\/ This file already owns the lock, but the call may change its lock type.\n\t} else if l.owner == nil {\n\t\t\/\/ No owner: it's ours now.\n\t\tl.owner = f\n\t} else {\n\t\t\/\/ Already owned: add a channel to wait on.\n\t\twait = make(chan File)\n\t\tl.queue = append(l.queue, wait)\n\t}\n\tlocks[ino] = l\n\tmu.Unlock()\n\n\tif wait != nil {\n\t\twait <- f\n\t}\n\n\t\/\/ Spurious EDEADLK errors arise on platforms that compute deadlock graphs at\n\t\/\/ the process, rather than thread, level. Consider processes P and Q, with\n\t\/\/ threads P.1, P.2, and Q.3. The following trace is NOT a deadlock, but will be\n\t\/\/ reported as a deadlock on systems that consider only process granularity:\n\t\/\/\n\t\/\/ \tP.1 locks file A.\n\t\/\/ \tQ.3 locks file B.\n\t\/\/ \tQ.3 blocks on file A.\n\t\/\/ \tP.2 blocks on file B. (This is erroneously reported as a deadlock.)\n\t\/\/ \tP.1 unlocks file A.\n\t\/\/ \tQ.3 unblocks and locks file A.\n\t\/\/ \tQ.3 unlocks files A and B.\n\t\/\/ \tP.2 unblocks and locks file B.\n\t\/\/ \tP.2 unlocks file B.\n\t\/\/\n\t\/\/ These spurious errors were observed in practice on AIX and Solaris in\n\t\/\/ cmd\/go: see https:\/\/golang.org\/issue\/32817.\n\t\/\/\n\t\/\/ We work around this bug by treating EDEADLK as always spurious. If there\n\t\/\/ really is a lock-ordering bug between the interacting processes, it will\n\t\/\/ become a livelock instead, but that's not appreciably worse than if we had\n\t\/\/ a proper flock implementation (which generally does not even attempt to\n\t\/\/ diagnose deadlocks).\n\t\/\/\n\t\/\/ In the above example, that changes the trace to:\n\t\/\/\n\t\/\/ \tP.1 locks file A.\n\t\/\/ \tQ.3 locks file B.\n\t\/\/ \tQ.3 blocks on file A.\n\t\/\/ \tP.2 spuriously fails to lock file B and goes to sleep.\n\t\/\/ \tP.1 unlocks file A.\n\t\/\/ \tQ.3 unblocks and locks file A.\n\t\/\/ \tQ.3 unlocks files A and B.\n\t\/\/ \tP.2 wakes up and locks file B.\n\t\/\/ \tP.2 unlocks file B.\n\t\/\/\n\t\/\/ We know that the retry loop will not introduce a *spurious* livelock\n\t\/\/ because, according to the POSIX specification, EDEADLK is only to be\n\t\/\/ returned when “the lock is blocked by a lock from another process”.\n\t\/\/ If that process is blocked on some lock that we are holding, then the\n\t\/\/ resulting livelock is due to a real deadlock (and would manifest as such\n\t\/\/ when using, for example, the flock implementation of this package).\n\t\/\/ If the other process is *not* blocked on some other lock that we are\n\t\/\/ holding, then it will eventually release the requested lock.\n\n\tnextSleep := 1 * time.Millisecond\n\tconst maxSleep = 500 * time.Millisecond\n\tfor {\n\t\terr = setlkw(f.Fd(), lt)\n\t\tif err != syscall.EDEADLK {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(nextSleep)\n\n\t\tnextSleep += nextSleep\n\t\tif nextSleep > maxSleep {\n\t\t\tnextSleep = maxSleep\n\t\t}\n\t\t\/\/ Apply 10% jitter to avoid synchronizing collisions when we finally unblock.\n\t\tnextSleep += time.Duration((0.1*rand.Float64() - 0.05) * float64(nextSleep))\n\t}\n\n\tif err != nil {\n\t\tunlock(f)\n\t\treturn &os.PathError{\n\t\t\tOp:   lt.String(),\n\t\t\tPath: f.Name(),\n\t\t\tErr:  err,\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc unlock(f File) error {\n\tvar owner File\n\n\tmu.Lock()\n\tino, ok := inodes[f]\n\tif ok {\n\t\towner = locks[ino].owner\n\t}\n\tmu.Unlock()\n\n\tif owner != f {\n\t\tpanic(\"unlock called on a file that is not locked\")\n\t}\n\n\terr := setlkw(f.Fd(), syscall.F_UNLCK)\n\n\tmu.Lock()\n\tl := locks[ino]\n\tif len(l.queue) == 0 {\n\t\t\/\/ No waiters: remove the map entry.\n\t\tdelete(locks, ino)\n\t} else {\n\t\t\/\/ The first waiter is sending us their file now.\n\t\t\/\/ Receive it and update the queue.\n\t\tl.owner = <-l.queue[0]\n\t\tl.queue = l.queue[1:]\n\t\tlocks[ino] = l\n\t}\n\tdelete(inodes, f)\n\tmu.Unlock()\n\n\treturn err\n}\n\n\/\/ setlkw calls FcntlFlock with F_SETLKW for the entire file indicated by fd.\nfunc setlkw(fd uintptr, lt lockType) error {\n\tfor {\n\t\terr := syscall.FcntlFlock(fd, syscall.F_SETLKW, &syscall.Flock_t{\n\t\t\tType:   int16(lt),\n\t\t\tWhence: io.SeekStart,\n\t\t\tStart:  0,\n\t\t\tLen:    0, \/\/ All bytes.\n\t\t})\n\t\tif err != syscall.EINTR {\n\t\t\treturn err\n\t\t}\n\t}\n}\n\nfunc isNotSupported(err error) bool {\n\treturn err == syscall.ENOSYS || err == syscall.ENOTSUP || err == syscall.EOPNOTSUPP || err == ErrNotSupported\n}\n<commit_msg>cmd\/go\/internal\/lockedfile\/internal\/filelock: remove stale TODO comment<commit_after>\/\/ Copyright 2018 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ +build aix solaris,!illumos\n\n\/\/ This code implements the filelock API using POSIX 'fcntl' locks, which attach\n\/\/ to an (inode, process) pair rather than a file descriptor. To avoid unlocking\n\/\/ files prematurely when the same file is opened through different descriptors,\n\/\/ we allow only one read-lock at a time.\n\/\/\n\/\/ Most platforms provide some alternative API, such as an 'flock' system call\n\/\/ or an F_OFD_SETLK command for 'fcntl', that allows for better concurrency and\n\/\/ does not require per-inode bookkeeping in the application.\n\npackage filelock\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"math\/rand\"\n\t\"os\"\n\t\"sync\"\n\t\"syscall\"\n\t\"time\"\n)\n\ntype lockType int16\n\nconst (\n\treadLock  lockType = syscall.F_RDLCK\n\twriteLock lockType = syscall.F_WRLCK\n)\n\ntype inode = uint64 \/\/ type of syscall.Stat_t.Ino\n\ntype inodeLock struct {\n\towner File\n\tqueue []<-chan File\n}\n\ntype token struct{}\n\nvar (\n\tmu     sync.Mutex\n\tinodes = map[File]inode{}\n\tlocks  = map[inode]inodeLock{}\n)\n\nfunc lock(f File, lt lockType) (err error) {\n\t\/\/ POSIX locks apply per inode and process, and the lock for an inode is\n\t\/\/ released when *any* descriptor for that inode is closed. So we need to\n\t\/\/ synchronize access to each inode internally, and must serialize lock and\n\t\/\/ unlock calls that refer to the same inode through different descriptors.\n\tfi, err := f.Stat()\n\tif err != nil {\n\t\treturn err\n\t}\n\tino := fi.Sys().(*syscall.Stat_t).Ino\n\n\tmu.Lock()\n\tif i, dup := inodes[f]; dup && i != ino {\n\t\tmu.Unlock()\n\t\treturn &os.PathError{\n\t\t\tOp:   lt.String(),\n\t\t\tPath: f.Name(),\n\t\t\tErr:  errors.New(\"inode for file changed since last Lock or RLock\"),\n\t\t}\n\t}\n\tinodes[f] = ino\n\n\tvar wait chan File\n\tl := locks[ino]\n\tif l.owner == f {\n\t\t\/\/ This file already owns the lock, but the call may change its lock type.\n\t} else if l.owner == nil {\n\t\t\/\/ No owner: it's ours now.\n\t\tl.owner = f\n\t} else {\n\t\t\/\/ Already owned: add a channel to wait on.\n\t\twait = make(chan File)\n\t\tl.queue = append(l.queue, wait)\n\t}\n\tlocks[ino] = l\n\tmu.Unlock()\n\n\tif wait != nil {\n\t\twait <- f\n\t}\n\n\t\/\/ Spurious EDEADLK errors arise on platforms that compute deadlock graphs at\n\t\/\/ the process, rather than thread, level. Consider processes P and Q, with\n\t\/\/ threads P.1, P.2, and Q.3. The following trace is NOT a deadlock, but will be\n\t\/\/ reported as a deadlock on systems that consider only process granularity:\n\t\/\/\n\t\/\/ \tP.1 locks file A.\n\t\/\/ \tQ.3 locks file B.\n\t\/\/ \tQ.3 blocks on file A.\n\t\/\/ \tP.2 blocks on file B. (This is erroneously reported as a deadlock.)\n\t\/\/ \tP.1 unlocks file A.\n\t\/\/ \tQ.3 unblocks and locks file A.\n\t\/\/ \tQ.3 unlocks files A and B.\n\t\/\/ \tP.2 unblocks and locks file B.\n\t\/\/ \tP.2 unlocks file B.\n\t\/\/\n\t\/\/ These spurious errors were observed in practice on AIX and Solaris in\n\t\/\/ cmd\/go: see https:\/\/golang.org\/issue\/32817.\n\t\/\/\n\t\/\/ We work around this bug by treating EDEADLK as always spurious. If there\n\t\/\/ really is a lock-ordering bug between the interacting processes, it will\n\t\/\/ become a livelock instead, but that's not appreciably worse than if we had\n\t\/\/ a proper flock implementation (which generally does not even attempt to\n\t\/\/ diagnose deadlocks).\n\t\/\/\n\t\/\/ In the above example, that changes the trace to:\n\t\/\/\n\t\/\/ \tP.1 locks file A.\n\t\/\/ \tQ.3 locks file B.\n\t\/\/ \tQ.3 blocks on file A.\n\t\/\/ \tP.2 spuriously fails to lock file B and goes to sleep.\n\t\/\/ \tP.1 unlocks file A.\n\t\/\/ \tQ.3 unblocks and locks file A.\n\t\/\/ \tQ.3 unlocks files A and B.\n\t\/\/ \tP.2 wakes up and locks file B.\n\t\/\/ \tP.2 unlocks file B.\n\t\/\/\n\t\/\/ We know that the retry loop will not introduce a *spurious* livelock\n\t\/\/ because, according to the POSIX specification, EDEADLK is only to be\n\t\/\/ returned when “the lock is blocked by a lock from another process”.\n\t\/\/ If that process is blocked on some lock that we are holding, then the\n\t\/\/ resulting livelock is due to a real deadlock (and would manifest as such\n\t\/\/ when using, for example, the flock implementation of this package).\n\t\/\/ If the other process is *not* blocked on some other lock that we are\n\t\/\/ holding, then it will eventually release the requested lock.\n\n\tnextSleep := 1 * time.Millisecond\n\tconst maxSleep = 500 * time.Millisecond\n\tfor {\n\t\terr = setlkw(f.Fd(), lt)\n\t\tif err != syscall.EDEADLK {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(nextSleep)\n\n\t\tnextSleep += nextSleep\n\t\tif nextSleep > maxSleep {\n\t\t\tnextSleep = maxSleep\n\t\t}\n\t\t\/\/ Apply 10% jitter to avoid synchronizing collisions when we finally unblock.\n\t\tnextSleep += time.Duration((0.1*rand.Float64() - 0.05) * float64(nextSleep))\n\t}\n\n\tif err != nil {\n\t\tunlock(f)\n\t\treturn &os.PathError{\n\t\t\tOp:   lt.String(),\n\t\t\tPath: f.Name(),\n\t\t\tErr:  err,\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc unlock(f File) error {\n\tvar owner File\n\n\tmu.Lock()\n\tino, ok := inodes[f]\n\tif ok {\n\t\towner = locks[ino].owner\n\t}\n\tmu.Unlock()\n\n\tif owner != f {\n\t\tpanic(\"unlock called on a file that is not locked\")\n\t}\n\n\terr := setlkw(f.Fd(), syscall.F_UNLCK)\n\n\tmu.Lock()\n\tl := locks[ino]\n\tif len(l.queue) == 0 {\n\t\t\/\/ No waiters: remove the map entry.\n\t\tdelete(locks, ino)\n\t} else {\n\t\t\/\/ The first waiter is sending us their file now.\n\t\t\/\/ Receive it and update the queue.\n\t\tl.owner = <-l.queue[0]\n\t\tl.queue = l.queue[1:]\n\t\tlocks[ino] = l\n\t}\n\tdelete(inodes, f)\n\tmu.Unlock()\n\n\treturn err\n}\n\n\/\/ setlkw calls FcntlFlock with F_SETLKW for the entire file indicated by fd.\nfunc setlkw(fd uintptr, lt lockType) error {\n\tfor {\n\t\terr := syscall.FcntlFlock(fd, syscall.F_SETLKW, &syscall.Flock_t{\n\t\t\tType:   int16(lt),\n\t\t\tWhence: io.SeekStart,\n\t\t\tStart:  0,\n\t\t\tLen:    0, \/\/ All bytes.\n\t\t})\n\t\tif err != syscall.EINTR {\n\t\t\treturn err\n\t\t}\n\t}\n}\n\nfunc isNotSupported(err error) bool {\n\treturn err == syscall.ENOSYS || err == syscall.ENOTSUP || err == syscall.EOPNOTSUPP || err == ErrNotSupported\n}\n<|endoftext|>"}
{"text":"<commit_before>package channel\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"socialapi\/models\"\n\t\"socialapi\/request\"\n\t\"socialapi\/workers\/common\/response\"\n\n\t\"github.com\/koding\/bongo\"\n)\n\nfunc validateChannelRequest(c *models.Channel) error {\n\tif c.GroupName == \"\" {\n\t\treturn errors.New(\"Group name is not set\")\n\t}\n\n\tif c.Name == \"\" {\n\t\treturn errors.New(\"Channel name is not set\")\n\t}\n\n\tif c.CreatorId == 0 {\n\t\treturn errors.New(\"Creator id is not set\")\n\t}\n\n\treturn nil\n}\n\nfunc Create(u *url.URL, h http.Header, req *models.Channel) (int, http.Header, interface{}, error) {\n\tif req.GroupName == \"\" {\n\t\treq.GroupName = models.Channel_KODING_NAME\n\t}\n\n\tif req.PrivacyConstant == \"\" {\n\t\treq.PrivacyConstant = models.Channel_PRIVACY_PUBLIC\n\t}\n\n\tif err := validateChannelRequest(req); err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\tif err := req.Create(); err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\tif _, err := req.AddParticipant(req.CreatorId); err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\treturn response.NewOK(req)\n}\n\nfunc List(u *url.URL, h http.Header, _ interface{}) (int, http.Header, interface{}, error) {\n\tc := models.NewChannel()\n\tq := request.GetQuery(u)\n\tq.Type = models.Channel_TYPE_TOPIC\n\tchannelList, err := c.List(q)\n\tif err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\treturn response.HandleResultAndError(\n\t\tmodels.PopulateChannelContainers(\n\t\t\tchannelList,\n\t\t\tq.AccountId,\n\t\t),\n\t)\n}\n\nfunc Search(u *url.URL, h http.Header, _ interface{}) (int, http.Header, interface{}, error) {\n\tq := request.GetQuery(u)\n\tq.Type = models.Channel_TYPE_TOPIC\n\n\tchannelList, err := models.NewChannel().Search(q)\n\tif err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\treturn response.HandleResultAndError(\n\t\tmodels.PopulateChannelContainers(\n\t\t\tchannelList,\n\t\t\tq.AccountId,\n\t\t),\n\t)\n}\n\nfunc ByName(u *url.URL, h http.Header, _ interface{}) (int, http.Header, interface{}, error) {\n\tq := request.GetQuery(u)\n\tq.Type = models.Channel_TYPE_TOPIC\n\n\tchannel, err := models.NewChannel().ByName(q)\n\tif err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\tcanOpen, err := channel.CanOpen(q.AccountId)\n\tif err != nil {\n\t\t\/\/ if the channel can not be opened by the requester\n\t\t\/\/ do send an empty response\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\tif !canOpen {\n\t\treturn response.NewOK(nil)\n\t}\n\n\treturn response.HandleResultAndError(\n\t\tmodels.PopulateChannelContainer(\n\t\t\tchannel,\n\t\t\tq.AccountId,\n\t\t),\n\t)\n}\n\nfunc CheckParticipation(u *url.URL, h http.Header, _ interface{}) (int, http.Header, interface{}, error) {\n\tq := request.GetQuery(u)\n\tif q.Type == \"\" || q.AccountId == 0 {\n\t\treturn response.NewBadRequest(errors.New(\"type or accountid is not set\"))\n\t}\n\n\tchannel, err := models.NewChannel().ByName(q)\n\tif err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\tcanOpen, err := channel.CanOpen(q.AccountId)\n\tif err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\tif !canOpen {\n\t\treturn response.NewAccessDenied(\n\t\t\tfmt.Errorf(\n\t\t\t\t\"account (%d) tried to retrieve the unattended private channel (%d)\",\n\t\t\t\tq.AccountId,\n\t\t\t\tchannel.Id,\n\t\t\t))\n\t}\n\n\treturn response.NewOK(channel)\n}\n\nfunc Delete(u *url.URL, h http.Header, req *models.Channel) (int, http.Header, interface{}, error) {\n\n\tid, err := request.GetURIInt64(u, \"id\")\n\tif err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\tif err := req.ById(id); err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\tif req.TypeConstant == models.Channel_TYPE_GROUP {\n\t\treturn response.NewBadRequest(errors.New(\"You can not delete group channel\"))\n\t}\n\tif err := req.Delete(); err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\t\/\/ yes it is deleted but not removed completely from our system\n\treturn response.NewDeleted()\n}\n\nfunc Update(u *url.URL, h http.Header, req *models.Channel) (int, http.Header, interface{}, error) {\n\tid, err := request.GetURIInt64(u, \"id\")\n\tif err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\treq.Id = id\n\n\tif req.Id == 0 {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\texistingOne := models.NewChannel()\n\tif err := existingOne.ById(id); err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\tif existingOne.CreatorId != req.CreatorId {\n\t\treturn response.NewBadRequest(errors.New(\"CreatorId doesnt match\"))\n\t}\n\n\t\/\/ only allow purpose and name to be updated\n\tif req.Purpose != \"\" {\n\t\texistingOne.Purpose = req.Purpose\n\t}\n\n\tif req.Name != \"\" {\n\t\texistingOne.Name = req.Name\n\t}\n\n\tif err := req.Update(); err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\treturn response.NewOK(req)\n}\n\nfunc Get(u *url.URL, h http.Header, _ interface{}) (int, http.Header, interface{}, error) {\n\tid, err := request.GetURIInt64(u, \"id\")\n\tif err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\tq := request.GetQuery(u)\n\n\tc := models.NewChannel()\n\tif err := c.ById(id); err != nil {\n\t\tif err == bongo.RecordNotFound {\n\t\t\treturn response.NewNotFound()\n\t\t}\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\t\/\/ add troll mode filter\n\tif c.MetaBits.Is(models.Troll) && !q.ShowExempt {\n\t\treturn response.NewNotFound()\n\t}\n\n\treturn response.HandleResultAndError(\n\t\tmodels.PopulateChannelContainer(*c, q.AccountId),\n\t)\n}\n<commit_msg>Social: only open participated channels<commit_after>package channel\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"socialapi\/models\"\n\t\"socialapi\/request\"\n\t\"socialapi\/workers\/common\/response\"\n\n\t\"github.com\/koding\/bongo\"\n)\n\nfunc validateChannelRequest(c *models.Channel) error {\n\tif c.GroupName == \"\" {\n\t\treturn errors.New(\"Group name is not set\")\n\t}\n\n\tif c.Name == \"\" {\n\t\treturn errors.New(\"Channel name is not set\")\n\t}\n\n\tif c.CreatorId == 0 {\n\t\treturn errors.New(\"Creator id is not set\")\n\t}\n\n\treturn nil\n}\n\nfunc Create(u *url.URL, h http.Header, req *models.Channel) (int, http.Header, interface{}, error) {\n\tif req.GroupName == \"\" {\n\t\treq.GroupName = models.Channel_KODING_NAME\n\t}\n\n\tif req.PrivacyConstant == \"\" {\n\t\treq.PrivacyConstant = models.Channel_PRIVACY_PUBLIC\n\t}\n\n\tif err := validateChannelRequest(req); err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\tif err := req.Create(); err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\tif _, err := req.AddParticipant(req.CreatorId); err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\treturn response.NewOK(req)\n}\n\n\/\/ List lists only topic channels\nfunc List(u *url.URL, h http.Header, _ interface{}) (int, http.Header, interface{}, error) {\n\tc := models.NewChannel()\n\tq := request.GetQuery(u)\n\tq.Type = models.Channel_TYPE_TOPIC\n\tchannelList, err := c.List(q)\n\tif err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\treturn response.HandleResultAndError(\n\t\tmodels.PopulateChannelContainers(\n\t\t\tchannelList,\n\t\t\tq.AccountId,\n\t\t),\n\t)\n}\n\n\/\/ Search searchs database against given channel name\n\/\/ but only returns topic channels\nfunc Search(u *url.URL, h http.Header, _ interface{}) (int, http.Header, interface{}, error) {\n\tq := request.GetQuery(u)\n\tq.Type = models.Channel_TYPE_TOPIC\n\n\tchannelList, err := models.NewChannel().Search(q)\n\tif err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\treturn response.HandleResultAndError(\n\t\tmodels.PopulateChannelContainers(\n\t\t\tchannelList,\n\t\t\tq.AccountId,\n\t\t),\n\t)\n}\n\n\/\/ ByName finds topics by their name\nfunc ByName(u *url.URL, h http.Header, _ interface{}) (int, http.Header, interface{}, error) {\n\tq := request.GetQuery(u)\n\tq.Type = models.Channel_TYPE_TOPIC\n\n\tchannel, err := models.NewChannel().ByName(q)\n\tif err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\treturn handleChannelResponse(channel, q)\n}\n\nfunc Get(u *url.URL, h http.Header, _ interface{}) (int, http.Header, interface{}, error) {\n\tid, err := request.GetURIInt64(u, \"id\")\n\tif err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\tq := request.GetQuery(u)\n\n\tc := models.NewChannel()\n\tif err := c.ById(id); err != nil {\n\t\tif err == bongo.RecordNotFound {\n\t\t\treturn response.NewNotFound()\n\t\t}\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\treturn handleChannelResponse(*c, q)\n}\n\nfunc handleChannelResponse(c models.Channel, q *request.Query) (int, http.Header, interface{}, error) {\n\t\/\/ add troll mode filter\n\tif c.MetaBits.Is(models.Troll) && !q.ShowExempt {\n\t\treturn response.NewNotFound()\n\t}\n\n\tcanOpen, err := c.CanOpen(q.AccountId)\n\tif err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\tif !canOpen {\n\t\treturn response.NewAccessDenied(\n\t\t\tfmt.Errorf(\n\t\t\t\t\"account (%d) tried to retrieve the unattended channel (%d)\",\n\t\t\t\tq.AccountId,\n\t\t\t\tc.Id,\n\t\t\t),\n\t\t)\n\t}\n\n\treturn response.HandleResultAndError(\n\t\tmodels.PopulateChannelContainer(c, q.AccountId),\n\t)\n}\n\nfunc CheckParticipation(u *url.URL, h http.Header, _ interface{}) (int, http.Header, interface{}, error) {\n\tq := request.GetQuery(u)\n\tif q.Type == \"\" || q.AccountId == 0 {\n\t\treturn response.NewBadRequest(errors.New(\"type or accountid is not set\"))\n\t}\n\n\tchannel, err := models.NewChannel().ByName(q)\n\tif err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\tcanOpen, err := channel.CanOpen(q.AccountId)\n\tif err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\tif !canOpen {\n\t\treturn response.NewAccessDenied(\n\t\t\tfmt.Errorf(\n\t\t\t\t\"account (%d) tried to retrieve the unattended private channel (%d)\",\n\t\t\t\tq.AccountId,\n\t\t\t\tchannel.Id,\n\t\t\t))\n\t}\n\n\treturn response.NewOK(channel)\n}\n\nfunc Delete(u *url.URL, h http.Header, req *models.Channel) (int, http.Header, interface{}, error) {\n\n\tid, err := request.GetURIInt64(u, \"id\")\n\tif err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\tif err := req.ById(id); err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\tif req.TypeConstant == models.Channel_TYPE_GROUP {\n\t\treturn response.NewBadRequest(errors.New(\"You can not delete group channel\"))\n\t}\n\tif err := req.Delete(); err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\t\/\/ yes it is deleted but not removed completely from our system\n\treturn response.NewDeleted()\n}\n\nfunc Update(u *url.URL, h http.Header, req *models.Channel) (int, http.Header, interface{}, error) {\n\tid, err := request.GetURIInt64(u, \"id\")\n\tif err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\treq.Id = id\n\n\tif req.Id == 0 {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\texistingOne := models.NewChannel()\n\tif err := existingOne.ById(id); err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\tif existingOne.CreatorId != req.CreatorId {\n\t\treturn response.NewBadRequest(errors.New(\"CreatorId doesnt match\"))\n\t}\n\n\t\/\/ only allow purpose and name to be updated\n\tif req.Purpose != \"\" {\n\t\texistingOne.Purpose = req.Purpose\n\t}\n\n\tif req.Name != \"\" {\n\t\texistingOne.Name = req.Name\n\t}\n\n\tif err := req.Update(); err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\treturn response.NewOK(req)\n}\n<|endoftext|>"}
{"text":"<commit_before>package accessors\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\t\"math\/rand\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com\/kellydunn\/golang-geo\"\n)\n\nconst nearbyEnemyCap = 100\n\nfunc init() {\n\trand.Seed(time.Now().UTC().UnixNano())\n}\n\n\/\/ Returns an array of all loot locations and values to plot on the map in iOS\nfunc (ag *AccessorGroup) DumpDatabase(userLatitude float64, userLongitude float64, radius float64) (string, error) {\n\tcurrentEnemyCount, err := ag.CountNearbyEnemies(userLatitude, userLongitude, radius)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tif currentEnemyCount < nearbyEnemyCap {\n\t\t\/\/ Add enemies\n\t\tag.AddEnemies(userLatitude, userLongitude, radius, currentEnemyCount, nearbyEnemyCap)\n\t}\n\n\trows, err := ag.DB.Query(\"SELECT * FROM enemies\")\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tdefer rows.Close()\n\tcolumns, err := rows.Columns()\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tcount := len(columns)\n\ttableData := make([]map[string]string, 0)\n\tvalues := make([]interface{}, count)\n\tvaluePtrs := make([]interface{}, count)\n\n\tfor rows.Next() {\n\t\tfor i := 0; i < count; i++ {\n\t\t\tvaluePtrs[i] = &values[i]\n\t\t}\n\n\t\trows.Scan(valuePtrs...)\n\t\tentry := make(map[string]string)\n\n\t\tfor i, col := range columns {\n\t\t\tval := values[i]\n\t\t\tif val != nil {\n\t\t\t\tentry[col] = fmt.Sprintf(\"%s\", string(val.([]byte))) \/\/ Save the data as a string\n\t\t\t}\n\t\t}\n\n\t\tif len(entry[\"latitude\"]) > 0 && len(entry[\"latitude\"]) > 0 { \/\/ Make sure we don't have bad data\n\t\t\tlatitude, err := strconv.ParseFloat(entry[\"latitude\"], 64)\n\t\t\tif err == nil {\n\t\t\t\tlongitude, err := strconv.ParseFloat(entry[\"longitude\"], 64)\n\t\t\t\tif err == nil {\n\t\t\t\t\tif WithinRadius(latitude, longitude, userLatitude, userLongitude, radius) { \/\/ Only return enemies that are close to the player\n\t\t\t\t\t\ttableData = append(tableData, entry)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tlog.Panic(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlog.Panic(err)\n\t\t\t}\n\t\t}\n\t}\n\n\tjsonData, err := json.Marshal(tableData)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\treturn string(jsonData), nil\n}\n\nfunc (ag *AccessorGroup) CountNearbyEnemies(userLatitude float64, userLongitude float64, radius float64) (int, error) {\n\tenemyCount := 0\n\n\trows, err := ag.DB.Query(\"SELECT * FROM enemies\")\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tdefer rows.Close()\n\tcolumns, err := rows.Columns()\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tcount := len(columns)\n\tvalues := make([]interface{}, count)\n\tvaluePtrs := make([]interface{}, count)\n\n\tfor rows.Next() {\n\t\tfor i := 0; i < count; i++ {\n\t\t\tvaluePtrs[i] = &values[i]\n\t\t}\n\n\t\trows.Scan(valuePtrs...)\n\t\tentry := make(map[string]string)\n\n\t\tfor i, col := range columns {\n\t\t\tval := values[i]\n\t\t\tif val != nil {\n\t\t\t\tentry[col] = fmt.Sprintf(\"%s\", string(val.([]byte))) \/\/ Save the data as a string\n\t\t\t}\n\t\t}\n\n\t\tif len(entry[\"latitude\"]) > 0 && len(entry[\"latitude\"]) > 0 { \/\/ Make sure we don't have bad data\n\t\t\tlatitude, err := strconv.ParseFloat(entry[\"latitude\"], 64)\n\t\t\tif err == nil {\n\t\t\t\tlongitude, err := strconv.ParseFloat(entry[\"longitude\"], 64)\n\t\t\t\tif err == nil {\n\t\t\t\t\tif WithinRadius(latitude, longitude, userLatitude, userLongitude, radius) { \/\/ Only return enemies that are close to the player\n\t\t\t\t\t\tenemyCount++\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tlog.Panic(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlog.Panic(err)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn enemyCount, nil\n}\n\nfunc WithinRadius(lat1 float64, lon1 float64, lat2 float64, lon2 float64, radius float64) bool {\n\tp := geo.NewPoint(lat1, lon1)\n\tp2 := geo.NewPoint(lat2, lon2)\n\n\tdist := p.GreatCircleDistance(p2) \/\/ Find the great circle distance between points\n\n\tif dist < radius { \/\/ Return whether we're inside the radius or not\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}\n\nfunc (ag *AccessorGroup) AddEnemies(userLatitude float64, userLongitude float64, radius float64, currentEnemyCount int, enemyCap int) {\n\titerations := enemyCap - currentEnemyCount\n\n\tfor i := 0; i < iterations; i++ {\n\t\tw := radius \/ 111 * math.Sqrt(rand.Float64())\n\t\tt := 2 * math.Pi * rand.Float64()\n\t\tx := w * math.Cos(t)\n\t\ty := w * math.Sin(t)\n\n\t\trandomLatitude := userLatitude + x\n\t\trandomLongitude := userLongitude + y\n\n\t\t_, err := ag.DB.Exec(\"INSERT INTO enemies (latitude, longitude) VALUES (?,?)\", randomLatitude, randomLongitude)\n\t\tif err != nil {\n\t\t\tlog.Panic(err)\n\t\t}\n\t}\n}\n<commit_msg>Maybe this'll fix the random seed...?<commit_after>package accessors\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\t\"math\/rand\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com\/kellydunn\/golang-geo\"\n)\n\nconst nearbyEnemyCap = 100\n\n\/\/ Returns an array of all loot locations and values to plot on the map in iOS\nfunc (ag *AccessorGroup) DumpDatabase(userLatitude float64, userLongitude float64, radius float64) (string, error) {\n\tcurrentEnemyCount, err := ag.CountNearbyEnemies(userLatitude, userLongitude, radius)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tif currentEnemyCount < nearbyEnemyCap {\n\t\t\/\/ Add enemies\n\t\tag.AddEnemies(userLatitude, userLongitude, radius, currentEnemyCount, nearbyEnemyCap)\n\t}\n\n\trows, err := ag.DB.Query(\"SELECT * FROM enemies\")\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tdefer rows.Close()\n\tcolumns, err := rows.Columns()\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tcount := len(columns)\n\ttableData := make([]map[string]string, 0)\n\tvalues := make([]interface{}, count)\n\tvaluePtrs := make([]interface{}, count)\n\n\tfor rows.Next() {\n\t\tfor i := 0; i < count; i++ {\n\t\t\tvaluePtrs[i] = &values[i]\n\t\t}\n\n\t\trows.Scan(valuePtrs...)\n\t\tentry := make(map[string]string)\n\n\t\tfor i, col := range columns {\n\t\t\tval := values[i]\n\t\t\tif val != nil {\n\t\t\t\tentry[col] = fmt.Sprintf(\"%s\", string(val.([]byte))) \/\/ Save the data as a string\n\t\t\t}\n\t\t}\n\n\t\tif len(entry[\"latitude\"]) > 0 && len(entry[\"latitude\"]) > 0 { \/\/ Make sure we don't have bad data\n\t\t\tlatitude, err := strconv.ParseFloat(entry[\"latitude\"], 64)\n\t\t\tif err == nil {\n\t\t\t\tlongitude, err := strconv.ParseFloat(entry[\"longitude\"], 64)\n\t\t\t\tif err == nil {\n\t\t\t\t\tif WithinRadius(latitude, longitude, userLatitude, userLongitude, radius) { \/\/ Only return enemies that are close to the player\n\t\t\t\t\t\ttableData = append(tableData, entry)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tlog.Panic(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlog.Panic(err)\n\t\t\t}\n\t\t}\n\t}\n\n\tjsonData, err := json.Marshal(tableData)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\treturn string(jsonData), nil\n}\n\nfunc (ag *AccessorGroup) CountNearbyEnemies(userLatitude float64, userLongitude float64, radius float64) (int, error) {\n\tenemyCount := 0\n\n\trows, err := ag.DB.Query(\"SELECT * FROM enemies\")\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tdefer rows.Close()\n\tcolumns, err := rows.Columns()\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\tcount := len(columns)\n\tvalues := make([]interface{}, count)\n\tvaluePtrs := make([]interface{}, count)\n\n\tfor rows.Next() {\n\t\tfor i := 0; i < count; i++ {\n\t\t\tvaluePtrs[i] = &values[i]\n\t\t}\n\n\t\trows.Scan(valuePtrs...)\n\t\tentry := make(map[string]string)\n\n\t\tfor i, col := range columns {\n\t\t\tval := values[i]\n\t\t\tif val != nil {\n\t\t\t\tentry[col] = fmt.Sprintf(\"%s\", string(val.([]byte))) \/\/ Save the data as a string\n\t\t\t}\n\t\t}\n\n\t\tif len(entry[\"latitude\"]) > 0 && len(entry[\"latitude\"]) > 0 { \/\/ Make sure we don't have bad data\n\t\t\tlatitude, err := strconv.ParseFloat(entry[\"latitude\"], 64)\n\t\t\tif err == nil {\n\t\t\t\tlongitude, err := strconv.ParseFloat(entry[\"longitude\"], 64)\n\t\t\t\tif err == nil {\n\t\t\t\t\tif WithinRadius(latitude, longitude, userLatitude, userLongitude, radius) { \/\/ Only return enemies that are close to the player\n\t\t\t\t\t\tenemyCount++\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tlog.Panic(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlog.Panic(err)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn enemyCount, nil\n}\n\nfunc WithinRadius(lat1 float64, lon1 float64, lat2 float64, lon2 float64, radius float64) bool {\n\tp := geo.NewPoint(lat1, lon1)\n\tp2 := geo.NewPoint(lat2, lon2)\n\n\tdist := p.GreatCircleDistance(p2) \/\/ Find the great circle distance between points\n\n\tif dist < radius { \/\/ Return whether we're inside the radius or not\n\t\treturn true\n\t} else {\n\t\treturn false\n\t}\n}\n\nfunc (ag *AccessorGroup) AddEnemies(userLatitude float64, userLongitude float64, radius float64, currentEnemyCount int, enemyCap int) {\n\titerations := enemyCap - currentEnemyCount\n\trand.Seed(time.Now().UTC().UnixNano())\n\n\tfor i := 0; i < iterations; i++ {\n\t\tw := radius \/ 111 * math.Sqrt(rand.Float64())\n\t\tt := 2 * math.Pi * rand.Float64()\n\t\tx := w * math.Cos(t)\n\t\ty := w * math.Sin(t)\n\n\t\trandomLatitude := userLatitude + x\n\t\trandomLongitude := userLongitude + y\n\n\t\t_, err := ag.DB.Exec(\"INSERT INTO enemies (latitude, longitude) VALUES (?,?)\", randomLatitude, randomLongitude)\n\t\tif err != nil {\n\t\t\tlog.Panic(err)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"github.com\/emgee\/go-xmpp\/src\/xmpp\"\n\t\"log\"\n\t\"strings\"\n)\n\nfunc main() {\n\tgo connectHttpServer()\n\tconnectComponent()\n}\n\nfunc connectComponent() {\n\t\/\/ connect as component\n\tjid, _ := xmpp.ParseJID(\"jabmud.localhost\")\n\tstream, _ := xmpp.NewStream(\"localhost:5275\", nil)\n\tX, _ := xmpp.NewComponentXMPP(stream, jid, \"secret\")\n\tlog.Printf(\"created component JID %v at %v\\n\", jid, X)\n\n\tfor i := range X.In {\n\t\tswitch v := i.(type) {\n\t\tcase error:\n\t\t\tlog.Printf(\"error: %v\\n\", v)\n\n\t\tcase *xmpp.Message:\n\t\t\tlog.Printf(\"msg: %s says %s\\n\", v.From, v.Body)\n\t\t\t\/\/ for fun, send a response\n\t\t\tX.Out <- xmpp.Message{Body: \"hi!\", To: v.From, From: v.To, Type: \"chat\"}\n\n\t\tcase *xmpp.Iq:\n\t\t\tlog.Printf(\"iq: %T: %v\", v.Payload, v.Payload)\n\t\t\tif strings.HasPrefix(v.Payload, \"<command\") {\n\t\t\t\tcmd := ParseCommand(v.Payload)\n\t\t\t\tlog.Printf(\"cmd: %s\", cmd)\n\t\t\t\t\/\/ so now go do something with the command...\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"Not a command-iq: %s\", v.Payload)\n\t\t\t\t\/\/ now what?\n\t\t\t}\n\n\t\tdefault:\n\t\t\tlog.Printf(\"%T: %v\\n\", v, v)\n\t\t}\n\t}\n}\n<commit_msg>Organizing files is hard.<commit_after>package main\n\nimport (\n\t\"github.com\/emgee\/go-xmpp\/src\/xmpp\"\n\t\"log\"\n\t\"strings\"\n)\n\nfunc main() {\n\tgo connectHttpServer()\n\tconnectComponent()\n}\n\nfunc connectComponent() {\n\t\/\/ connect as component\n\tjid, _ := xmpp.ParseJID(\"jabmud.localhost\")\n\tstream, _ := xmpp.NewStream(\"localhost:5275\", nil)\n\tX, _ := xmpp.NewComponentXMPP(stream, jid, \"secret\")\n\tlog.Printf(\"created component JID %v at %v\\n\", jid, X)\n\n\tfor i := range X.In {\n\t\tswitch v := i.(type) {\n\t\tcase error:\n\t\t\tlog.Printf(\"error: %v\\n\", v)\n\n\t\tcase *xmpp.Message:\n\t\t\tlog.Printf(\"msg: %s says %s\\n\", v.From, v.Body)\n\t\t\t\/\/ for fun, send a response\n\t\t\tX.Out <- xmpp.Message{Body: \"hi!\", To: v.From, From: v.To, Type: \"chat\"}\n\n\t\tcase *xmpp.Iq:\n\t\t\tlog.Printf(\"iq: %T: %v\", v.Payload, v.Payload)\n\t\t\tif strings.HasPrefix(v.Payload, \"<command\") {\n\t\t\t\tcmd := ParseCommand(v.Payload)\n\t\t\t\tlog.Printf(\"cmd: %s\", cmd)\n\t\t\t\t\/\/ so now go do something with the command...\n\t\t\t\tRun(cmd.Name) \/\/ TODO args\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"Not a command-iq: %s\", v.Payload)\n\t\t\t\t\/\/ now what?\n\t\t\t}\n\n\t\tdefault:\n\t\t\tlog.Printf(\"%T: %v\\n\", v, v)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package gohaveazurestoragecommon\n\nimport (\n\t\"bytes\"\n\t\"crypto\/hmac\"\n\t\"crypto\/sha256\"\n\t\"encoding\/base64\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/http\/httputil\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype HTTP struct {\n\tbaseURL          string\n\tsecondaryBaseURL string\n\taccount          string\n\tkey              []byte\n\tdumpSessions     bool\n}\n\nfunc NewHTTP(storageType string, account string, key []byte, dumpSessions bool) *HTTP {\n\thttp := &HTTP{account: account, key: key, dumpSessions: dumpSessions}\n\thttp.baseURL = \"https:\/\/\" + account + \".\" + storageType + \".core.windows.net\/\"\n\thttp.secondaryBaseURL = \"https:\/\/\" + account + \"-secondary.\" + storageType + \".core.windows.net\/\"\n\n\treturn http\n}\n\nfunc (storagehttp *HTTP) Request(httpVerb string, target string, query string, json []byte, useIfMatch bool, useAccept bool, useContentTypeXML bool, useSecondary bool) ([]byte, int) {\n\txmsdate, Authentication := storagehttp.calculateDateAndAuthentication(target)\n\n\tbaseURL := \"\"\n\tif useSecondary {\n\t\tbaseURL = storagehttp.secondaryBaseURL\n\t} else {\n\t\tbaseURL = storagehttp.baseURL\n\t}\n\n\tclient := &http.Client{}\n\trequest, _ := http.NewRequest(httpVerb, baseURL+target+query, bytes.NewBuffer(json))\n\n\tif json != nil {\n\t\trequest.Header.Set(\"Content-Type\", \"application\/json\")\n\t\trequest.Header.Set(\"Content-Length\", string(len(json)))\n\t}\n\n\tif useContentTypeXML {\n\t\trequest.Header.Set(\"Content-Type\", \"application\/xml\")\n\t}\n\n\tif useIfMatch {\n\t\trequest.Header.Set(\"If-Match\", \"*\")\n\t}\n\n\tif useAccept {\n\t\trequest.Header.Set(\"Accept\", \"application\/json;odata=nometadata\")\n\t}\n\n\trequest.Header.Set(\"x-ms-date\", xmsdate)\n\trequest.Header.Set(\"x-ms-version\", \"2013-08-15\")\n\trequest.Header.Set(\"Authorization\", Authentication)\n\n\tresponse, err := client.Do(request)\n\tif err != nil {\n\t\treturn nil, http.StatusServiceUnavailable\n\t}\n\n\tif storagehttp.dumpSessions {\n\t\tresponseDump, _ := httputil.DumpResponse(response, true)\n\t\trequestDump, _ := httputil.DumpRequest(request, true)\n\n\t\tfmt.Printf(\"Request: %s\\n\", requestDump)\n\t\tfmt.Printf(\"%s\\n\", string(json))\n\t\tfmt.Printf(\"Response: %s\\n\", responseDump)\n\t}\n\n\tcontents, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn nil, http.StatusUnprocessableEntity\n\t}\n\n\treturn contents, response.StatusCode\n}\n\nfunc (storagehttp *HTTP) calculateDateAndAuthentication(target string) (string, string) {\n\txmsdate := strings.Replace(time.Now().UTC().Add(-time.Minute).Format(time.RFC1123), \"UTC\", \"GMT\", -1)\n\tSignatureString := xmsdate + \"\\n\/\" + storagehttp.account + \"\/\" + target\n\tAuthentication := \"SharedKeyLite \" + storagehttp.account + \":\" + computeHmac256(SignatureString, storagehttp.key)\n\treturn xmsdate, Authentication\n}\n\nfunc computeHmac256(message string, key []byte) string {\n\th := hmac.New(sha256.New, key)\n\th.Write([]byte(message))\n\treturn base64.StdEncoding.EncodeToString(h.Sum(nil))\n}\n<commit_msg>Reuse HTTP connection and close body<commit_after>package gohaveazurestoragecommon\n\nimport (\n\t\"bytes\"\n\t\"crypto\/hmac\"\n\t\"crypto\/sha256\"\n\t\"encoding\/base64\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/http\/httputil\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype HTTP struct {\n\tbaseURL          string\n\tsecondaryBaseURL string\n\taccount          string\n\tkey              []byte\n\tdumpSessions     bool\n\tclient           *http.Client\n}\n\nfunc NewHTTP(storageType string, account string, key []byte, dumpSessions bool) *HTTP {\n\th := &HTTP{account: account, key: key, dumpSessions: dumpSessions}\n\th.baseURL = \"https:\/\/\" + account + \".\" + storageType + \".core.windows.net\/\"\n\th.secondaryBaseURL = \"https:\/\/\" + account + \"-secondary.\" + storageType + \".core.windows.net\/\"\n\th.client = &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tMaxIdleConns:        2000,\n\t\t\tMaxIdleConnsPerHost: 2000,\n\t\t\tTLSHandshakeTimeout: 10 * time.Second,\n\t\t},\n\t\tTimeout: 15 * time.Second,\n\t}\n\n\treturn h\n}\n\nfunc (storagehttp *HTTP) Request(httpVerb string, target string, query string, json []byte, useIfMatch bool, useAccept bool, useContentTypeXML bool, useSecondary bool) ([]byte, int) {\n\txmsdate, Authentication := storagehttp.calculateDateAndAuthentication(target)\n\n\tbaseURL := \"\"\n\tif useSecondary {\n\t\tbaseURL = storagehttp.secondaryBaseURL\n\t} else {\n\t\tbaseURL = storagehttp.baseURL\n\t}\n\n\tclient := storagehttp.client\n\trequest, _ := http.NewRequest(httpVerb, baseURL+target+query, bytes.NewBuffer(json))\n\n\tif json != nil {\n\t\trequest.Header.Set(\"Content-Type\", \"application\/json\")\n\t\trequest.Header.Set(\"Content-Length\", string(len(json)))\n\t}\n\n\tif useContentTypeXML {\n\t\trequest.Header.Set(\"Content-Type\", \"application\/xml\")\n\t}\n\n\tif useIfMatch {\n\t\trequest.Header.Set(\"If-Match\", \"*\")\n\t}\n\n\tif useAccept {\n\t\trequest.Header.Set(\"Accept\", \"application\/json;odata=nometadata\")\n\t}\n\n\trequest.Header.Set(\"x-ms-date\", xmsdate)\n\trequest.Header.Set(\"x-ms-version\", \"2013-08-15\")\n\trequest.Header.Set(\"Authorization\", Authentication)\n\n\tresponse, err := client.Do(request)\n\tif err != nil {\n\t\treturn nil, http.StatusServiceUnavailable\n\t}\n\tdefer response.Body.Close()\n\n\tif storagehttp.dumpSessions {\n\t\tresponseDump, _ := httputil.DumpResponse(response, true)\n\t\trequestDump, _ := httputil.DumpRequest(request, true)\n\n\t\tfmt.Printf(\"Request: %s\\n\", requestDump)\n\t\tfmt.Printf(\"%s\\n\", string(json))\n\t\tfmt.Printf(\"Response: %s\\n\", responseDump)\n\t}\n\n\tcontents, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn nil, http.StatusUnprocessableEntity\n\t}\n\n\treturn contents, response.StatusCode\n}\n\nfunc (storagehttp *HTTP) calculateDateAndAuthentication(target string) (string, string) {\n\txmsdate := strings.Replace(time.Now().UTC().Add(-time.Minute).Format(time.RFC1123), \"UTC\", \"GMT\", -1)\n\tSignatureString := xmsdate + \"\\n\/\" + storagehttp.account + \"\/\" + target\n\tAuthentication := \"SharedKeyLite \" + storagehttp.account + \":\" + computeHmac256(SignatureString, storagehttp.key)\n\treturn xmsdate, Authentication\n}\n\nfunc computeHmac256(message string, key []byte) string {\n\th := hmac.New(sha256.New, key)\n\th.Write([]byte(message))\n\treturn base64.StdEncoding.EncodeToString(h.Sum(nil))\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build linux\n\npackage common\n\nimport (\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n)\n\nfunc DoSysctrl(mib string) ([]string, error) {\n\terr := os.Setenv(\"LC_ALL\", \"C\")\n\tif err != nil {\n\t\treturn []string{}, err\n\t}\n\tsysctl, err := exec.LookPath(\"\/sbin\/sysctl\")\n\tif err != nil {\n\t\treturn []string{}, err\n\t}\n\tout, err := exec.Command(sysctl, \"-n\", mib).Output()\n\tif err != nil {\n\t\treturn []string{}, err\n\t}\n\tv := strings.Replace(string(out), \"{ \", \"\", 1)\n\tv = strings.Replace(string(v), \" }\", \"\", 1)\n\tvalues := strings.Fields(string(v))\n\n\treturn values, nil\n}\n\nfunc NumProcs() (uint64, error) {\n\tf, err := os.Open(HostProc())\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer f.Close()\n\n\tlist, err := f.Readdirnames(-1)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn uint64(len(list)), err\n}\n<commit_msg>Alter subprocess's environment instead of the hosts<commit_after>\/\/ +build linux\n\npackage common\n\nimport (\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n)\n\nfunc DoSysctrl(mib string) ([]string, error) {\n\thostEnv := os.Environ()\n\tfoundLC := false\n\tfor i, line := range hostEnv {\n\t\tif strings.HasPrefix(line, \"LC_ALL\") {\n\t\t\thostEnv[i] = \"LC_ALL=C\"\n\t\t\tfoundLC = true\n\t\t}\n\t}\n\tif !foundLC {\n\t\thostEnv = append(hostEnv, \"LC_ALL=C\")\n\t}\n\tsysctl, err := exec.LookPath(\"\/sbin\/sysctl\")\n\tif err != nil {\n\t\treturn []string{}, err\n\t}\n\tcmd := exec.Command(sysctl, \"-n\", mib)\n\tcmd.Env = hostEnv\n\tout, err := cmd.Output()\n\tif err != nil {\n\t\treturn []string{}, err\n\t}\n\tv := strings.Replace(string(out), \"{ \", \"\", 1)\n\tv = strings.Replace(string(v), \" }\", \"\", 1)\n\tvalues := strings.Fields(string(v))\n\n\treturn values, nil\n}\n\nfunc NumProcs() (uint64, error) {\n\tf, err := os.Open(HostProc())\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer f.Close()\n\n\tlist, err := f.Readdirnames(-1)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn uint64(len(list)), err\n}\n<|endoftext|>"}
{"text":"<commit_before>package api\n\nimport (\n\t\"testing\"\n)\n\nfunc Test_extractModeratorChanges(t *testing.T) {\n\tcurrentModList := []string{\"a\", \"b\", \"c\"}\n\tnewModList := []string{\"a\", \"x\", \"c\"}\n\n\ttoAdd, toDelete := extractModeratorChanges(newModList, &currentModList)\n\tif len(toAdd) != 1 {\n\t\tt.Errorf(\"Test_extractModeratorChanges returned incorrect number of additions: expected %d got %d\", 1, len(toAdd))\n\t}\n\tif len(toDelete) != 1 {\n\t\tt.Errorf(\"Test_extractModeratorChanges returned incorrect number of deletions: expected %d got %d\", 1, len(toDelete))\n\t}\n\n\tif toAdd[0] != \"x\" {\n\t\tt.Errorf(\"Test_extractModeratorChanges returned incorrect addition: expected a got %s\", toAdd[0])\n\t}\n\tif toDelete[0] != \"b\" {\n\t\tt.Errorf(\"Test_extractModeratorChanges returned incorrect deletion: expected b got %s\", toDelete[0])\n\t}\n}\n<commit_msg>Update error string<commit_after>package api\n\nimport (\n\t\"testing\"\n)\n\nfunc Test_extractModeratorChanges(t *testing.T) {\n\tcurrentModList := []string{\"a\", \"b\", \"c\"}\n\tnewModList := []string{\"a\", \"x\", \"c\"}\n\n\ttoAdd, toDelete := extractModeratorChanges(newModList, &currentModList)\n\tif len(toAdd) != 1 {\n\t\tt.Errorf(\"Returned incorrect number of additions: expected %d got %d\", 1, len(toAdd))\n\t}\n\tif len(toDelete) != 1 {\n\t\tt.Errorf(\"Returned incorrect number of deletions: expected %d got %d\", 1, len(toDelete))\n\t}\n\n\tif toAdd[0] != \"x\" {\n\t\tt.Errorf(\"Returned incorrect addition: expected a got %s\", toAdd[0])\n\t}\n\tif toDelete[0] != \"b\" {\n\t\tt.Errorf(\"Returned incorrect deletion: expected b got %s\", toDelete[0])\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"code.google.com\/p\/getopt\"\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/colinmarc\/hdfs\"\n\t\"os\"\n)\n\n\/\/ TODO: put, du, df, tree, test, trash\n\nvar (\n\tusage = fmt.Sprintf(`Usage: %s COMMAND\nThe flags available are a subset of the POSIX ones, but should behave similarly.\n\nValid commands:\n  ls [-lah] [FILE]...\n  rm [-rf] FILE...\n  mv [-fT] SOURCE... DEST\n  mkdir [-p] FILE...\n  touch [-amc] FILE...\n  chmod [-R] OCTAL-MODE FILE...\n  chown [-R] OWNER[:GROUP] FILE...\n  cat SOURCE...\n  head [-n LINES | -c BYTES] SOURCE...\n  tail [-n LINES | -c BYTES] SOURCE...\n  checksum FILE...\n  get SOURCE [DEST]\n  getmerge SOURCE DEST\n`, os.Args[0])\n\n\tlsOpts = getopt.New()\n\tlsl    = lsOpts.Bool('l')\n\tlsa    = lsOpts.Bool('a')\n\tlsh    = lsOpts.Bool('h')\n\n\trmOpts = getopt.New()\n\trmr    = rmOpts.Bool('r')\n\trmf    = rmOpts.Bool('f')\n\n\tmvOpts = getopt.New()\n\tmvf    = mvOpts.Bool('f')\n\tmvT    = mvOpts.Bool('T')\n\n\tmkdirOpts = getopt.New()\n\tmkdirp    = mkdirOpts.Bool('p')\n\n\ttouchOpts = getopt.New()\n\ttouchc    = touchOpts.Bool('c')\n\n\tchmodOpts = getopt.New()\n\tchmodR    = chmodOpts.Bool('R')\n\n\tchownOpts = getopt.New()\n\tchownR    = chownOpts.Bool('R')\n\n\theadTailOpts = getopt.New()\n\theadtailn    = headTailOpts.Int64('n', -1)\n\theadtailc    = headTailOpts.Int64('c', -1)\n\n\tgetmergeOpts = getopt.New()\n\tgetmergen    = getmergeOpts.Bool('n')\n\n\tcachedClient *hdfs.Client\n\tstatus = 0\n)\n\nfunc init() {\n\tlsOpts.SetUsage(printHelp)\n\trmOpts.SetUsage(printHelp)\n\tmvOpts.SetUsage(printHelp)\n\ttouchOpts.SetUsage(printHelp)\n\tchmodOpts.SetUsage(printHelp)\n\tchownOpts.SetUsage(printHelp)\n}\n\nfunc main() {\n\tif len(os.Args) < 2 {\n\t\tprintHelp()\n\t}\n\n\tcommand := os.Args[1]\n\targv := os.Args[1:]\n\tswitch command {\n\tcase \"ls\":\n\t\tlsOpts.Parse(argv)\n\t\tls(lsOpts.Args(), *lsl, *lsa, *lsh)\n\tcase \"rm\":\n\t\trmOpts.Parse(argv)\n\t\trm(rmOpts.Args(), *rmr, *rmf)\n\tcase \"mv\":\n\t\tmvOpts.Parse(argv)\n\t\tmv(mvOpts.Args(), *mvf, *mvT)\n\tcase \"mkdir\":\n\t\tmkdirOpts.Parse(argv)\n\t\tmkdir(mkdirOpts.Args(), *mkdirp)\n\tcase \"touch\":\n\t\ttouchOpts.Parse(argv)\n\t\ttouch(touchOpts.Args(), *touchc)\n\tcase \"chown\":\n\t\tchownOpts.Parse(argv)\n\t\tchown(chownOpts.Args(), *chownR)\n\tcase \"chmod\":\n\t\tchmodOpts.Parse(argv)\n\t\tchmod(chmodOpts.Args(), *chmodR)\n\tcase \"cat\":\n\t\tcat(argv[1:])\n\tcase \"head\", \"tail\":\n\t\theadTailOpts.Parse(argv)\n\t\tprintSection(headTailOpts.Args(), *headtailn, *headtailc, (command == \"tail\"))\n\tcase \"checksum\":\n\t\tchecksum(argv[1:])\n\tcase \"get\":\n\t\tget(argv[1:])\n\tcase \"getmerge\":\n\t\tgetmergeOpts.Parse(argv)\n\t\tgetmerge(getmergeOpts.Args(), *getmergen)\n\t\/\/ it's a seeeeecret command\n\tcase \"complete\":\n\t\tcomplete(argv)\n\tcase \"help\", \"-h\", \"-help\", \"--help\":\n\t\tprintHelp()\n\tdefault:\n\t\tfatalWithUsage(\"Unknown command:\", command)\n\t}\n\n\tos.Exit(status)\n}\n\nfunc printHelp() {\n\tfmt.Fprintln(os.Stderr, usage)\n\tos.Exit(0)\n}\n\nfunc fatal(msg ...interface{}) {\n\tfmt.Fprintln(os.Stderr, msg...)\n\tos.Exit(1)\n}\n\nfunc fatalWithUsage(msg ...interface{}) {\n\tmsg = append(msg, \"\\n\"+usage)\n\tfatal(msg...)\n}\n\nfunc getClient(namenode string) (*hdfs.Client, error) {\n\tif cachedClient != nil {\n\t\treturn cachedClient, nil\n\t}\n\n\tif namenode == \"\" {\n\t\tnamenode = os.Getenv(\"HADOOP_NAMENODE\")\n\t}\n\n\tif namenode == \"\" {\n\t\treturn nil, errors.New(\"Couldn't find a namenode to connect to. You should specify hdfs:\/\/<namenode>:<port> in your paths, or set HADOOP_NAMENODE in your environment.\")\n\t}\n\n\tc, err := hdfs.New(namenode)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcachedClient = c\n\treturn cachedClient, nil\n}\n<commit_msg>gofmt<commit_after>package main\n\nimport (\n\t\"code.google.com\/p\/getopt\"\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/colinmarc\/hdfs\"\n\t\"os\"\n)\n\n\/\/ TODO: put, du, df, tree, test, trash\n\nvar (\n\tusage = fmt.Sprintf(`Usage: %s COMMAND\nThe flags available are a subset of the POSIX ones, but should behave similarly.\n\nValid commands:\n  ls [-lah] [FILE]...\n  rm [-rf] FILE...\n  mv [-fT] SOURCE... DEST\n  mkdir [-p] FILE...\n  touch [-amc] FILE...\n  chmod [-R] OCTAL-MODE FILE...\n  chown [-R] OWNER[:GROUP] FILE...\n  cat SOURCE...\n  head [-n LINES | -c BYTES] SOURCE...\n  tail [-n LINES | -c BYTES] SOURCE...\n  checksum FILE...\n  get SOURCE [DEST]\n  getmerge SOURCE DEST\n`, os.Args[0])\n\n\tlsOpts = getopt.New()\n\tlsl    = lsOpts.Bool('l')\n\tlsa    = lsOpts.Bool('a')\n\tlsh    = lsOpts.Bool('h')\n\n\trmOpts = getopt.New()\n\trmr    = rmOpts.Bool('r')\n\trmf    = rmOpts.Bool('f')\n\n\tmvOpts = getopt.New()\n\tmvf    = mvOpts.Bool('f')\n\tmvT    = mvOpts.Bool('T')\n\n\tmkdirOpts = getopt.New()\n\tmkdirp    = mkdirOpts.Bool('p')\n\n\ttouchOpts = getopt.New()\n\ttouchc    = touchOpts.Bool('c')\n\n\tchmodOpts = getopt.New()\n\tchmodR    = chmodOpts.Bool('R')\n\n\tchownOpts = getopt.New()\n\tchownR    = chownOpts.Bool('R')\n\n\theadTailOpts = getopt.New()\n\theadtailn    = headTailOpts.Int64('n', -1)\n\theadtailc    = headTailOpts.Int64('c', -1)\n\n\tgetmergeOpts = getopt.New()\n\tgetmergen    = getmergeOpts.Bool('n')\n\n\tcachedClient *hdfs.Client\n\tstatus       = 0\n)\n\nfunc init() {\n\tlsOpts.SetUsage(printHelp)\n\trmOpts.SetUsage(printHelp)\n\tmvOpts.SetUsage(printHelp)\n\ttouchOpts.SetUsage(printHelp)\n\tchmodOpts.SetUsage(printHelp)\n\tchownOpts.SetUsage(printHelp)\n}\n\nfunc main() {\n\tif len(os.Args) < 2 {\n\t\tprintHelp()\n\t}\n\n\tcommand := os.Args[1]\n\targv := os.Args[1:]\n\tswitch command {\n\tcase \"ls\":\n\t\tlsOpts.Parse(argv)\n\t\tls(lsOpts.Args(), *lsl, *lsa, *lsh)\n\tcase \"rm\":\n\t\trmOpts.Parse(argv)\n\t\trm(rmOpts.Args(), *rmr, *rmf)\n\tcase \"mv\":\n\t\tmvOpts.Parse(argv)\n\t\tmv(mvOpts.Args(), *mvf, *mvT)\n\tcase \"mkdir\":\n\t\tmkdirOpts.Parse(argv)\n\t\tmkdir(mkdirOpts.Args(), *mkdirp)\n\tcase \"touch\":\n\t\ttouchOpts.Parse(argv)\n\t\ttouch(touchOpts.Args(), *touchc)\n\tcase \"chown\":\n\t\tchownOpts.Parse(argv)\n\t\tchown(chownOpts.Args(), *chownR)\n\tcase \"chmod\":\n\t\tchmodOpts.Parse(argv)\n\t\tchmod(chmodOpts.Args(), *chmodR)\n\tcase \"cat\":\n\t\tcat(argv[1:])\n\tcase \"head\", \"tail\":\n\t\theadTailOpts.Parse(argv)\n\t\tprintSection(headTailOpts.Args(), *headtailn, *headtailc, (command == \"tail\"))\n\tcase \"checksum\":\n\t\tchecksum(argv[1:])\n\tcase \"get\":\n\t\tget(argv[1:])\n\tcase \"getmerge\":\n\t\tgetmergeOpts.Parse(argv)\n\t\tgetmerge(getmergeOpts.Args(), *getmergen)\n\t\/\/ it's a seeeeecret command\n\tcase \"complete\":\n\t\tcomplete(argv)\n\tcase \"help\", \"-h\", \"-help\", \"--help\":\n\t\tprintHelp()\n\tdefault:\n\t\tfatalWithUsage(\"Unknown command:\", command)\n\t}\n\n\tos.Exit(status)\n}\n\nfunc printHelp() {\n\tfmt.Fprintln(os.Stderr, usage)\n\tos.Exit(0)\n}\n\nfunc fatal(msg ...interface{}) {\n\tfmt.Fprintln(os.Stderr, msg...)\n\tos.Exit(1)\n}\n\nfunc fatalWithUsage(msg ...interface{}) {\n\tmsg = append(msg, \"\\n\"+usage)\n\tfatal(msg...)\n}\n\nfunc getClient(namenode string) (*hdfs.Client, error) {\n\tif cachedClient != nil {\n\t\treturn cachedClient, nil\n\t}\n\n\tif namenode == \"\" {\n\t\tnamenode = os.Getenv(\"HADOOP_NAMENODE\")\n\t}\n\n\tif namenode == \"\" {\n\t\treturn nil, errors.New(\"Couldn't find a namenode to connect to. You should specify hdfs:\/\/<namenode>:<port> in your paths, or set HADOOP_NAMENODE in your environment.\")\n\t}\n\n\tc, err := hdfs.New(namenode)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcachedClient = c\n\treturn cachedClient, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package frame\n\nimport (\n\t\"errors\"\n\t\"image\"\n\t\"image\/draw\"\n\n\t. \"github.com\/as\/font\"\n\t\"github.com\/as\/frame\/box\"\n\t\"golang.org\/x\/image\/font\"\n)\n\nvar (\n\tForceElastic bool\n\tForceUTF8    bool\n)\n\nconst (\n\tFrElastic = 1 << iota\n\tFrUTF8\n)\n\nvar (\n\tErrBadDst = errors.New(\"bad dst\")\n)\n\nfunc (f *Frame) Config() *Config {\n\treturn &Config{\n\t\tFlag:   f.flags,\n\t\tColor:  f.Color,\n\t\tFace:   f.Face,\n\t\tDrawer: f.Drawer,\n\t}\n}\n\nvar zc Color\n\nfunc (c *Config) check() *Config {\n\tif c.Color == zc {\n\t\tc.Color = A\n\t}\n\tif c.Face == nil {\n\t\tc.Face = NewFace(11)\n\t}\n\tif c.Drawer == nil {\n\t\tc.Drawer = &defaultDrawer{}\n\t}\n\treturn c\n}\n\nfunc negotiateFace(f font.Face, flags int) Face {\n\tif flags&FrUTF8 != 0 {\n\t\treturn NewCache(NewRune(f))\n\t}\n\tswitch f := f.(type) {\n\tcase Face:\n\t\treturn f\n\tcase font.Face:\n\t\treturn Open(f)\n\t}\n\treturn Open(f)\n}\n\n\/\/ Frame is a write-only container for editable text\ntype Frame struct {\n\tbox.Run\n\tp0 int64\n\tp1 int64\n\tb  draw.Image\n\tr  image.Rectangle\n\tir *box.Run\n\n\tFace Face\n\tColor\n\tTicked bool\n\tScroll func(int)\n\tDrawer\n\top draw.Op\n\n\tmintab int\n\tmaxtab int\n\tfull   int\n\n\ttick     draw.Image\n\ttickback draw.Image\n\ttickoff  bool\n\tmaxlines int\n\tmodified bool\n\n\tpts [][2]image.Point\n\n\tflags int\n}\n\nfunc New(dst draw.Image, r image.Rectangle, conf *Config) *Frame {\n\tif dst == nil {\n\t\treturn nil\n\t}\n\tif conf == nil {\n\t\tconf = &Config{}\n\t}\n\tconf.check()\n\tfl := conf.Flag\n\tface := negotiateFace(conf.Face, fl)\n\tmintab, maxtab := tabMinMax(face, fl&FrElastic != 0)\n\tf := &Frame{\n\t\tFace:   face,\n\t\tColor:  conf.Color,\n\t\tDrawer: conf.Drawer,\n\t\tRun:    box.NewRun(mintab, 5000, face),\n\t\top:     draw.Src,\n\t\tmintab: mintab,\n\t\tmaxtab: maxtab,\n\t\tflags:  fl,\n\t}\n\tf.setrects(r, dst)\n\tf.inittick()\n\trun := box.NewRun(mintab, 5000, face)\n\tf.ir = &run\n\treturn f\n}\n\n\/\/ Flags returns the flags currently set for the frame\nfunc (f *Frame) Flags() int {\n\treturn f.flags\n}\n\n\/\/ Flag sets the flags for the frame. At this time\n\/\/ only FrElastic is supported.\nfunc (f *Frame) SetFlags(flags int) {\n\tfl := getflag(flags)\n\tf.flags = fl\n\tf.mintab, f.maxtab = tabMinMax(f.Face, f.elastic())\n\t\/\/\tf.Reset( f.r, f.RGBA(),f.Font)\n\t\/\/\tf.mintab, f.maxtab = tabMinMax(f.Font, f.elastic())\n}\n\nfunc (f *Frame) elastic() bool {\n\treturn f.flags&FrElastic != 0\n}\n\nfunc tabMinMax(ft Face, elastic bool) (min, max int) {\n\tmintab := ft.Dx([]byte{' '})\n\tmaxtab := mintab * 4\n\tif elastic {\n\t\tmintab = maxtab\n\t}\n\treturn mintab, maxtab\n}\n\nfunc getflag(flag ...int) (fl int) {\n\tif len(flag) != 0 {\n\t\tfl = flag[0]\n\t}\n\tif ForceElastic {\n\t\tfl |= FrElastic\n\t}\n\tif ForceUTF8 {\n\t\tfl |= FrUTF8\n\t}\n\treturn fl\n}\n\nfunc (f *Frame) RGBA() *image.RGBA {\n\trgba, _ := f.b.(*image.RGBA)\n\treturn rgba\n}\nfunc (f *Frame) Size() image.Point {\n\tr := f.RGBA().Bounds()\n\treturn image.Pt(r.Dx(), r.Dy())\n}\n\n\/\/ Dirty returns true if the contents of the frame have changes since the last redraw\nfunc (f *Frame) Dirty() bool {\n\treturn f.modified\n}\n\n\/\/ SetDirty alters the frame's internal state\nfunc (f *Frame) SetDirty(dirty bool) {\n\tf.modified = dirty\n}\n\nfunc (f *Frame) SetOp(op draw.Op) {\n\tf.op = op\n\n}\n\n\/\/ Close closes the frame\nfunc (f *Frame) Close() error {\n\treturn nil\n}\n\n\/\/ Reset resets the frame to display on image b with bounds r and font ft.\nfunc (f *Frame) Reset(r image.Rectangle, b *image.RGBA, ft font.Face) {\n\tf.r = r\n\tf.b = b\n\tf.SetFont(ft)\n}\n\nfunc (f *Frame) SetFont(ft font.Face) {\n\tf.Face = Open(ft)\n\tf.Run.Reset(f.Face)\n\tf.Refresh()\n}\n\n\/\/ Bounds returns the frame's clipping rectangle\nfunc (f *Frame) Bounds() image.Rectangle {\n\treturn f.r.Bounds()\n}\n\n\/\/ Full returns true if the last line in the frame is full.\nfunc (f *Frame) Full() bool {\n\tif f == nil{\n\t\treturn true\n\t}\n\treturn f.full == 1\n}\n\n\/\/ Maxline returns the max number of wrapped lines fitting on the frame\nfunc (f *Frame) MaxLine() int {\n\tif f == nil{\n\t\treturn 0\n\t}\n\treturn f.maxlines\n}\n\n\/\/ Line returns the number of wrapped lines currently in the frame\nfunc (f *Frame) Line() int {\n\tif f == nil{\n\t\treturn 0\n\t}\n\treturn f.Nlines\n}\n\n\/\/ Len returns the number of bytes currently in the frame\nfunc (f *Frame) Len() int64 {\n\tif f == nil{\n\t\treturn 0\n\t}\n\treturn f.Nchars\n}\n\n\/\/ Dot returns the range of the selected text\nfunc (f *Frame) Dot() (p0, p1 int64) {\n\treturn f.p0, f.p1\n}\n\nfunc (f *Frame) setrects(r image.Rectangle, b draw.Image) {\n\tf.b = b\n\tf.r = r\n\th := f.Face.Dy()\n\tf.r.Max.Y -= f.r.Dy() % h\n\tf.maxlines = f.r.Dy() \/ h\n}\n<commit_msg>frame: make Size() do the correct thing and return r.Size() instead of delta<commit_after>package frame\n\nimport (\n\t\"errors\"\n\t\"image\"\n\t\"image\/draw\"\n\n\t. \"github.com\/as\/font\"\n\t\"github.com\/as\/frame\/box\"\n\t\"golang.org\/x\/image\/font\"\n)\n\nvar (\n\tForceElastic bool\n\tForceUTF8    bool\n)\n\nconst (\n\tFrElastic = 1 << iota\n\tFrUTF8\n)\n\nvar (\n\tErrBadDst = errors.New(\"bad dst\")\n)\n\nfunc (f *Frame) Config() *Config {\n\treturn &Config{\n\t\tFlag:   f.flags,\n\t\tColor:  f.Color,\n\t\tFace:   f.Face,\n\t\tDrawer: f.Drawer,\n\t}\n}\n\nvar zc Color\n\nfunc (c *Config) check() *Config {\n\tif c.Color == zc {\n\t\tc.Color = A\n\t}\n\tif c.Face == nil {\n\t\tc.Face = NewFace(11)\n\t}\n\tif c.Drawer == nil {\n\t\tc.Drawer = &defaultDrawer{}\n\t}\n\treturn c\n}\n\nfunc negotiateFace(f font.Face, flags int) Face {\n\tif flags&FrUTF8 != 0 {\n\t\treturn NewCache(NewRune(f))\n\t}\n\tswitch f := f.(type) {\n\tcase Face:\n\t\treturn f\n\tcase font.Face:\n\t\treturn Open(f)\n\t}\n\treturn Open(f)\n}\n\n\/\/ Frame is a write-only container for editable text\ntype Frame struct {\n\tbox.Run\n\tp0 int64\n\tp1 int64\n\tb  draw.Image\n\tr  image.Rectangle\n\tir *box.Run\n\n\tFace Face\n\tColor\n\tTicked bool\n\tScroll func(int)\n\tDrawer\n\top draw.Op\n\n\tmintab int\n\tmaxtab int\n\tfull   int\n\n\ttick     draw.Image\n\ttickback draw.Image\n\ttickoff  bool\n\tmaxlines int\n\tmodified bool\n\n\tpts [][2]image.Point\n\n\tflags int\n}\n\nfunc New(dst draw.Image, r image.Rectangle, conf *Config) *Frame {\n\tif dst == nil {\n\t\treturn nil\n\t}\n\tif conf == nil {\n\t\tconf = &Config{}\n\t}\n\tconf.check()\n\tfl := conf.Flag\n\tface := negotiateFace(conf.Face, fl)\n\tmintab, maxtab := tabMinMax(face, fl&FrElastic != 0)\n\tf := &Frame{\n\t\tFace:   face,\n\t\tColor:  conf.Color,\n\t\tDrawer: conf.Drawer,\n\t\tRun:    box.NewRun(mintab, 5000, face),\n\t\top:     draw.Src,\n\t\tmintab: mintab,\n\t\tmaxtab: maxtab,\n\t\tflags:  fl,\n\t}\n\tf.setrects(r, dst)\n\tf.inittick()\n\trun := box.NewRun(mintab, 5000, face)\n\tf.ir = &run\n\treturn f\n}\n\n\/\/ Flags returns the flags currently set for the frame\nfunc (f *Frame) Flags() int {\n\treturn f.flags\n}\n\n\/\/ Flag sets the flags for the frame. At this time\n\/\/ only FrElastic is supported.\nfunc (f *Frame) SetFlags(flags int) {\n\tfl := getflag(flags)\n\tf.flags = fl\n\tf.mintab, f.maxtab = tabMinMax(f.Face, f.elastic())\n\t\/\/\tf.Reset( f.r, f.RGBA(),f.Font)\n\t\/\/\tf.mintab, f.maxtab = tabMinMax(f.Font, f.elastic())\n}\n\nfunc (f *Frame) elastic() bool {\n\treturn f.flags&FrElastic != 0\n}\n\nfunc tabMinMax(ft Face, elastic bool) (min, max int) {\n\tmintab := ft.Dx([]byte{' '})\n\tmaxtab := mintab * 4\n\tif elastic {\n\t\tmintab = maxtab\n\t}\n\treturn mintab, maxtab\n}\n\nfunc getflag(flag ...int) (fl int) {\n\tif len(flag) != 0 {\n\t\tfl = flag[0]\n\t}\n\tif ForceElastic {\n\t\tfl |= FrElastic\n\t}\n\tif ForceUTF8 {\n\t\tfl |= FrUTF8\n\t}\n\treturn fl\n}\n\nfunc (f *Frame) RGBA() *image.RGBA {\n\trgba, _ := f.b.(*image.RGBA)\n\treturn rgba\n}\nfunc (f *Frame) Size() image.Point {\n\treturn f.r.Size()\n}\n\n\/\/ Dirty returns true if the contents of the frame have changes since the last redraw\nfunc (f *Frame) Dirty() bool {\n\treturn f.modified\n}\n\n\/\/ SetDirty alters the frame's internal state\nfunc (f *Frame) SetDirty(dirty bool) {\n\tf.modified = dirty\n}\n\nfunc (f *Frame) SetOp(op draw.Op) {\n\tf.op = op\n\n}\n\n\/\/ Close closes the frame\nfunc (f *Frame) Close() error {\n\treturn nil\n}\n\n\/\/ Reset resets the frame to display on image b with bounds r and font ft.\nfunc (f *Frame) Reset(r image.Rectangle, b *image.RGBA, ft font.Face) {\n\tf.r = r\n\tf.b = b\n\tf.SetFont(ft)\n}\n\nfunc (f *Frame) SetFont(ft font.Face) {\n\tf.Face = Open(ft)\n\tf.Run.Reset(f.Face)\n\tf.Refresh()\n}\n\n\/\/ Bounds returns the frame's clipping rectangle\nfunc (f *Frame) Bounds() image.Rectangle {\n\treturn f.r.Bounds()\n}\n\n\/\/ Full returns true if the last line in the frame is full.\nfunc (f *Frame) Full() bool {\n\tif f == nil{\n\t\treturn true\n\t}\n\treturn f.full == 1\n}\n\n\/\/ Maxline returns the max number of wrapped lines fitting on the frame\nfunc (f *Frame) MaxLine() int {\n\tif f == nil{\n\t\treturn 0\n\t}\n\treturn f.maxlines\n}\n\n\/\/ Line returns the number of wrapped lines currently in the frame\nfunc (f *Frame) Line() int {\n\tif f == nil{\n\t\treturn 0\n\t}\n\treturn f.Nlines\n}\n\n\/\/ Len returns the number of bytes currently in the frame\nfunc (f *Frame) Len() int64 {\n\tif f == nil{\n\t\treturn 0\n\t}\n\treturn f.Nchars\n}\n\n\/\/ Dot returns the range of the selected text\nfunc (f *Frame) Dot() (p0, p1 int64) {\n\treturn f.p0, f.p1\n}\n\nfunc (f *Frame) setrects(r image.Rectangle, b draw.Image) {\n\tf.b = b\n\tf.r = r\n\th := f.Face.Dy()\n\tf.r.Max.Y -= f.r.Dy() % h\n\tf.maxlines = f.r.Dy() \/ h\n}\n<|endoftext|>"}
{"text":"<commit_before>package crawler\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"github.com\/dokterbob\/ipfs-search\/indexer\"\n\t\"github.com\/dokterbob\/ipfs-search\/queue\"\n\t\"gopkg.in\/ipfs\/go-ipfs-api.v1\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\/\/ \"path\"\n\t\"strings\"\n\t\"syscall\"\n\t\"time\"\n)\n\nconst (\n\t\/\/ Reconnect time in seconds\n\tRECONNECT_WAIT    = 2\n\tTIKA_TIMEOUT      = 120\n\tMETADATA_MAX_SIZE = 50 * 1024 * 1024\n)\n\ntype CrawlerArgs struct {\n\tHash       string\n\tName       string\n\tSize       uint64\n\tParentHash string\n\tParentName string \/\/ This is legacy, should be removed\n}\n\ntype Crawler struct {\n\tsh *shell.Shell\n\tid *indexer.Indexer\n\tfq *queue.TaskQueue\n\thq *queue.TaskQueue\n}\n\nfunc NewCrawler(sh *shell.Shell, id *indexer.Indexer, fq *queue.TaskQueue, hq *queue.TaskQueue) *Crawler {\n\treturn &Crawler{\n\t\tsh: sh,\n\t\tid: id,\n\t\tfq: fq,\n\t\thq: hq,\n\t}\n}\n\nfunc hashUrl(hash string) string {\n\treturn fmt.Sprintf(\"\/ipfs\/%s\", hash)\n}\n\n\/\/ Update references with name, parent_hash and parent_name. Returns true when updated\nfunc update_references(references []indexer.Reference, name string, parent_hash string) ([]indexer.Reference, bool) {\n\tif references == nil {\n\t\t\/\/ Initialize empty references when none have been found\n\t\treferences = []indexer.Reference{}\n\t}\n\n\tif parent_hash == \"\" {\n\t\t\/\/ No parent hash, don't bother adding reference\n\t\treturn references, false\n\t}\n\n\tfor i := range references {\n\t\tif references[i].ParentHash == parent_hash {\n\t\t\tlog.Printf(\"Reference '%s' for %s exists, not updating\", name, parent_hash)\n\t\t\treturn references, false\n\t\t}\n\t}\n\n\treferences = append(references, indexer.Reference{\n\t\tName:       name,\n\t\tParentHash: parent_hash,\n\t})\n\n\treturn references, true\n}\n\n\/\/ Handle IPFS errors graceously, returns try again bool and original error\nfunc (c Crawler) handleError(err error, hash string) (bool, error) {\n\tif _, ok := err.(*shell.Error); ok && strings.Contains(err.Error(), \"proto\") {\n\t\t\/\/ We're not recovering from protocol errors, so panic\n\n\t\t\/\/ Attempt to index panic to prevent re-indexing\n\t\tmetadata := map[string]interface{}{\n\t\t\t\"error\": err.Error(),\n\t\t}\n\n\t\tc.id.IndexItem(\"invalid\", hash, metadata)\n\n\t\tpanic(err)\n\t}\n\n\tif uerr, ok := err.(*url.Error); ok {\n\t\t\/\/ URL errors\n\n\t\tlog.Printf(\"URL error %v\", uerr)\n\n\t\tif uerr.Timeout() {\n\t\t\t\/\/ Fail on timeouts\n\t\t\treturn false, err\n\t\t}\n\n\t\tif uerr.Temporary() {\n\t\t\t\/\/ Retry on other temp errors\n\t\t\treturn true, nil\n\t\t}\n\n\t\t\/\/ Somehow, the errors below are not temp errors !?\n\t\tswitch t := uerr.Err.(type) {\n\t\tcase *net.OpError:\n\t\t\tif t.Op == \"dial\" {\n\t\t\t\tlog.Printf(\"Unknown host %v\", t)\n\t\t\t\treturn true, nil\n\n\t\t\t} else if t.Op == \"read\" {\n\t\t\t\tlog.Printf(\"Connection refused %v\", t)\n\t\t\t\treturn true, nil\n\t\t\t}\n\n\t\tcase syscall.Errno:\n\t\t\tif t == syscall.ECONNREFUSED {\n\t\t\t\tlog.Printf(\"Connection refused %v\", t)\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false, err\n}\n\nfunc (c Crawler) index_references(hash string, name string, parent_hash string) ([]indexer.Reference, bool, error) {\n\tvar already_indexed bool\n\n\treferences, item_type, err := c.id.GetReferences(hash)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\n\t\/\/ TODO: Handle this more explicitly, use and detect NotFound\n\tif references == nil {\n\t\talready_indexed = false\n\t} else {\n\t\talready_indexed = true\n\t}\n\n\treferences, references_updated := update_references(references, name, parent_hash)\n\n\tif already_indexed {\n\t\tif references_updated {\n\t\t\tlog.Printf(\"Found %s, adding reference '%s' from %s\", hash, name, parent_hash)\n\n\t\t\tproperties := map[string]interface{}{\n\t\t\t\t\"references\": references,\n\t\t\t}\n\n\t\t\terr := c.id.IndexItem(item_type, hash, properties)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, false, err\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Printf(\"Found %s, not updating references.\", hash)\n\t\t}\n\t}\n\n\treturn references, already_indexed, nil\n}\n\n\/\/ Given a particular hash (file or directory), start crawling\nfunc (c Crawler) CrawlHash(hash string, name string, parent_hash string, parent_name string) error {\n\treferences, already_indexed, err := c.index_references(hash, name, parent_hash)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif already_indexed {\n\t\treturn nil\n\t}\n\n\tlog.Printf(\"Crawling hash '%s' (%s)\", hash, name)\n\n\turl := hashUrl(hash)\n\n\tvar list *shell.UnixLsObject\n\n\ttry_again := true\n\tfor try_again {\n\t\tlist, err = c.sh.FileList(url)\n\n\t\ttry_again, err = c.handleError(err, hash)\n\n\t\tif try_again {\n\t\t\tlog.Printf(\"Retrying in %d seconds\", RECONNECT_WAIT)\n\t\t\ttime.Sleep(RECONNECT_WAIT * time.Duration(time.Second))\n\t\t}\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch list.Type {\n\tcase \"File\":\n\t\t\/\/ Add to file crawl queue\n\t\targs := CrawlerArgs{\n\t\t\tHash:       hash,\n\t\t\tName:       name,\n\t\t\tSize:       list.Size,\n\t\t\tParentHash: parent_hash,\n\t\t}\n\n\t\terr = c.fq.AddTask(args)\n\t\tif err != nil {\n\t\t\t\/\/ failed to send the task\n\t\t\treturn err\n\t\t}\n\tcase \"Directory\":\n\t\t\/\/ Index name and size for directory and directory items\n\t\tproperties := map[string]interface{}{\n\t\t\t\"links\":      list.Links,\n\t\t\t\"size\":       list.Size,\n\t\t\t\"references\": references,\n\t\t}\n\n\t\terr := c.id.IndexItem(\"directory\", hash, properties)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfor _, link := range list.Links {\n\t\t\targs := CrawlerArgs{\n\t\t\t\tHash:       link.Hash,\n\t\t\t\tName:       link.Name,\n\t\t\t\tSize:       link.Size,\n\t\t\t\tParentHash: hash,\n\t\t\t}\n\n\t\t\tswitch link.Type {\n\t\t\tcase \"File\":\n\t\t\t\t\/\/ Add file to crawl queue\n\t\t\t\terr = c.fq.AddTask(args)\n\t\t\t\tif err != nil {\n\t\t\t\t\t\/\/ failed to send the task\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\tcase \"Directory\":\n\t\t\t\t\/\/ Add directory to crawl queue\n\t\t\t\tc.hq.AddTask(args)\n\t\t\t\tif err != nil {\n\t\t\t\t\t\/\/ failed to send the task\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tlog.Printf(\"Type '%s' skipped for '%s'\", list.Type, hash)\n\t\t\t}\n\t\t}\n\tdefault:\n\t\tlog.Printf(\"Type '%s' skipped for '%s'\", list.Type, hash)\n\t}\n\n\tlog.Printf(\"Finished hash %s\", hash)\n\n\treturn nil\n}\n\nfunc getMetadata(path string, metadata *map[string]interface{}) error {\n\tconst ipfs_tika_url = \"http:\/\/localhost:8081\"\n\n\tclient := http.Client{\n\t\tTimeout: TIKA_TIMEOUT * time.Duration(time.Second),\n\t}\n\n\tresp, err := client.Get(ipfs_tika_url + path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != 200 {\n\t\treturn fmt.Errorf(\"Undesired status '%s' from ipfs-tika.\", resp.Status)\n\t}\n\n\t\/\/ Parse resulting JSON\n\tif err := json.NewDecoder(resp.Body).Decode(&metadata); err != nil {\n\t\treturn err\n\t}\n\n\treturn err\n}\n\n\/\/ Crawl a single object, known to be a file\nfunc (c Crawler) CrawlFile(hash string, name string, parent_hash string, parent_name string, size uint64) error {\n\tif size == 262144 && parent_hash == \"\" {\n\t\t\/\/ Assertion error.\n\t\t\/\/ REMOVE ME!\n\t\tlog.Printf(\"Skipping unreferenced partial content for %s\", hash)\n\t\treturn nil\n\t}\n\n\treferences, already_indexed, err := c.index_references(hash, name, parent_hash)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif already_indexed {\n\t\treturn nil\n\t}\n\n\tlog.Printf(\"Crawling file %s (%s)\\n\", hash, name)\n\n\tmetadata := make(map[string]interface{})\n\n\tif size > 0 {\n\t\tif size > METADATA_MAX_SIZE {\n\t\t\t\/\/ Fail hard for really large files, for now\n\t\t\treturn fmt.Errorf(\"%s (%s) too large, not indexing (for now).\", hash, name)\n\t\t}\n\n\t\tvar path string\n\t\tif name != \"\" && parent_hash != \"\" {\n\t\t\tpath = fmt.Sprintf(\"\/ipfs\/%s\/%s\", parent_hash, name)\n\t\t} else {\n\t\t\tpath = fmt.Sprintf(\"\/ipfs\/%s\", hash)\n\t\t}\n\n\t\ttry_again := true\n\t\tfor try_again {\n\t\t\terr = getMetadata(path, &metadata)\n\n\t\t\ttry_again, err = c.handleError(err, hash)\n\n\t\t\tif try_again {\n\t\t\t\tlog.Printf(\"Retrying in %d seconds\", RECONNECT_WAIT)\n\t\t\t\ttime.Sleep(RECONNECT_WAIT * time.Duration(time.Second))\n\t\t\t}\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Check for IPFS links in content\n\t\t\/*\n\t\t\tfor raw_url := range metadata.urls {\n\t\t\t\turl, err := URL.Parse(raw_url)\n\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 strings.HasPrefix(url.Path, \"\/ipfs\/\") {\n\t\t\t\t\t\/\/ Found IPFS link!\n\t\t\t\t\targs := CrawlerArgs{\n\t\t\t\t\t\tHash:       link.Hash,\n\t\t\t\t\t\tName:       link.Name,\n\t\t\t\t\t\tSize:       link.Size,\n\t\t\t\t\t\tParentHash: hash,\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t}\n\t\t*\/\n\t}\n\n\tmetadata[\"size\"] = size\n\tmetadata[\"references\"] = references\n\n\terr = c.id.IndexItem(\"file\", hash, metadata)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"Finished file %s\", hash)\n\n\treturn nil\n}\n<commit_msg>Better logging for references update.<commit_after>package crawler\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"github.com\/dokterbob\/ipfs-search\/indexer\"\n\t\"github.com\/dokterbob\/ipfs-search\/queue\"\n\t\"gopkg.in\/ipfs\/go-ipfs-api.v1\"\n\t\"log\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\/\/ \"path\"\n\t\"strings\"\n\t\"syscall\"\n\t\"time\"\n)\n\nconst (\n\t\/\/ Reconnect time in seconds\n\tRECONNECT_WAIT    = 2\n\tTIKA_TIMEOUT      = 120\n\tMETADATA_MAX_SIZE = 50 * 1024 * 1024\n)\n\ntype CrawlerArgs struct {\n\tHash       string\n\tName       string\n\tSize       uint64\n\tParentHash string\n\tParentName string \/\/ This is legacy, should be removed\n}\n\ntype Crawler struct {\n\tsh *shell.Shell\n\tid *indexer.Indexer\n\tfq *queue.TaskQueue\n\thq *queue.TaskQueue\n}\n\nfunc NewCrawler(sh *shell.Shell, id *indexer.Indexer, fq *queue.TaskQueue, hq *queue.TaskQueue) *Crawler {\n\treturn &Crawler{\n\t\tsh: sh,\n\t\tid: id,\n\t\tfq: fq,\n\t\thq: hq,\n\t}\n}\n\nfunc hashUrl(hash string) string {\n\treturn fmt.Sprintf(\"\/ipfs\/%s\", hash)\n}\n\n\/\/ Update references with name, parent_hash and parent_name. Returns true when updated\nfunc update_references(references []indexer.Reference, name string, parent_hash string) ([]indexer.Reference, bool) {\n\tif references == nil {\n\t\t\/\/ Initialize empty references when none have been found\n\t\treferences = []indexer.Reference{}\n\t}\n\n\tif parent_hash == \"\" {\n\t\tlog.Printf(\"No parent hash for item, not adding reference\")\n\t\treturn references, false\n\t}\n\n\tfor i := range references {\n\t\tif references[i].ParentHash == parent_hash {\n\t\t\tlog.Printf(\"Reference '%s' for %s exists, not updating\", name, parent_hash)\n\t\t\treturn references, false\n\t\t}\n\t}\n\n\treferences = append(references, indexer.Reference{\n\t\tName:       name,\n\t\tParentHash: parent_hash,\n\t})\n\n\treturn references, true\n}\n\n\/\/ Handle IPFS errors graceously, returns try again bool and original error\nfunc (c Crawler) handleError(err error, hash string) (bool, error) {\n\tif _, ok := err.(*shell.Error); ok && strings.Contains(err.Error(), \"proto\") {\n\t\t\/\/ We're not recovering from protocol errors, so panic\n\n\t\t\/\/ Attempt to index panic to prevent re-indexing\n\t\tmetadata := map[string]interface{}{\n\t\t\t\"error\": err.Error(),\n\t\t}\n\n\t\tc.id.IndexItem(\"invalid\", hash, metadata)\n\n\t\tpanic(err)\n\t}\n\n\tif uerr, ok := err.(*url.Error); ok {\n\t\t\/\/ URL errors\n\n\t\tlog.Printf(\"URL error %v\", uerr)\n\n\t\tif uerr.Timeout() {\n\t\t\t\/\/ Fail on timeouts\n\t\t\treturn false, err\n\t\t}\n\n\t\tif uerr.Temporary() {\n\t\t\t\/\/ Retry on other temp errors\n\t\t\treturn true, nil\n\t\t}\n\n\t\t\/\/ Somehow, the errors below are not temp errors !?\n\t\tswitch t := uerr.Err.(type) {\n\t\tcase *net.OpError:\n\t\t\tif t.Op == \"dial\" {\n\t\t\t\tlog.Printf(\"Unknown host %v\", t)\n\t\t\t\treturn true, nil\n\n\t\t\t} else if t.Op == \"read\" {\n\t\t\t\tlog.Printf(\"Connection refused %v\", t)\n\t\t\t\treturn true, nil\n\t\t\t}\n\n\t\tcase syscall.Errno:\n\t\t\tif t == syscall.ECONNREFUSED {\n\t\t\t\tlog.Printf(\"Connection refused %v\", t)\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false, err\n}\n\nfunc (c Crawler) index_references(hash string, name string, parent_hash string) ([]indexer.Reference, bool, error) {\n\tvar already_indexed bool\n\n\treferences, item_type, err := c.id.GetReferences(hash)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\n\t\/\/ TODO: Handle this more explicitly, use and detect NotFound\n\tif references == nil {\n\t\talready_indexed = false\n\t} else {\n\t\talready_indexed = true\n\t}\n\n\treferences, references_updated := update_references(references, name, parent_hash)\n\n\tif already_indexed {\n\t\tif references_updated {\n\t\t\tlog.Printf(\"Found %s, reference added: '%s' from %s\", hash, name, parent_hash)\n\n\t\t\tproperties := map[string]interface{}{\n\t\t\t\t\"references\": references,\n\t\t\t}\n\n\t\t\terr := c.id.IndexItem(item_type, hash, properties)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, false, err\n\t\t\t}\n\t\t} else {\n\t\t\tlog.Printf(\"Found %s, references not updated.\", hash)\n\t\t}\n\t} else if references_updated {\n\t\tlog.Printf(\"Adding %s, reference '%s' from %s\", hash, name, parent_hash)\n\t}\n\n\treturn references, already_indexed, nil\n}\n\n\/\/ Given a particular hash (file or directory), start crawling\nfunc (c Crawler) CrawlHash(hash string, name string, parent_hash string, parent_name string) error {\n\treferences, already_indexed, err := c.index_references(hash, name, parent_hash)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif already_indexed {\n\t\treturn nil\n\t}\n\n\tlog.Printf(\"Crawling hash '%s' (%s)\", hash, name)\n\n\turl := hashUrl(hash)\n\n\tvar list *shell.UnixLsObject\n\n\ttry_again := true\n\tfor try_again {\n\t\tlist, err = c.sh.FileList(url)\n\n\t\ttry_again, err = c.handleError(err, hash)\n\n\t\tif try_again {\n\t\t\tlog.Printf(\"Retrying in %d seconds\", RECONNECT_WAIT)\n\t\t\ttime.Sleep(RECONNECT_WAIT * time.Duration(time.Second))\n\t\t}\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch list.Type {\n\tcase \"File\":\n\t\t\/\/ Add to file crawl queue\n\t\targs := CrawlerArgs{\n\t\t\tHash:       hash,\n\t\t\tName:       name,\n\t\t\tSize:       list.Size,\n\t\t\tParentHash: parent_hash,\n\t\t}\n\n\t\terr = c.fq.AddTask(args)\n\t\tif err != nil {\n\t\t\t\/\/ failed to send the task\n\t\t\treturn err\n\t\t}\n\tcase \"Directory\":\n\t\t\/\/ Index name and size for directory and directory items\n\t\tproperties := map[string]interface{}{\n\t\t\t\"links\":      list.Links,\n\t\t\t\"size\":       list.Size,\n\t\t\t\"references\": references,\n\t\t}\n\n\t\terr := c.id.IndexItem(\"directory\", hash, properties)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfor _, link := range list.Links {\n\t\t\targs := CrawlerArgs{\n\t\t\t\tHash:       link.Hash,\n\t\t\t\tName:       link.Name,\n\t\t\t\tSize:       link.Size,\n\t\t\t\tParentHash: hash,\n\t\t\t}\n\n\t\t\tswitch link.Type {\n\t\t\tcase \"File\":\n\t\t\t\t\/\/ Add file to crawl queue\n\t\t\t\terr = c.fq.AddTask(args)\n\t\t\t\tif err != nil {\n\t\t\t\t\t\/\/ failed to send the task\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\tcase \"Directory\":\n\t\t\t\t\/\/ Add directory to crawl queue\n\t\t\t\tc.hq.AddTask(args)\n\t\t\t\tif err != nil {\n\t\t\t\t\t\/\/ failed to send the task\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tlog.Printf(\"Type '%s' skipped for '%s'\", list.Type, hash)\n\t\t\t}\n\t\t}\n\tdefault:\n\t\tlog.Printf(\"Type '%s' skipped for '%s'\", list.Type, hash)\n\t}\n\n\tlog.Printf(\"Finished hash %s\", hash)\n\n\treturn nil\n}\n\nfunc getMetadata(path string, metadata *map[string]interface{}) error {\n\tconst ipfs_tika_url = \"http:\/\/localhost:8081\"\n\n\tclient := http.Client{\n\t\tTimeout: TIKA_TIMEOUT * time.Duration(time.Second),\n\t}\n\n\tresp, err := client.Get(ipfs_tika_url + path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode != 200 {\n\t\treturn fmt.Errorf(\"Undesired status '%s' from ipfs-tika.\", resp.Status)\n\t}\n\n\t\/\/ Parse resulting JSON\n\tif err := json.NewDecoder(resp.Body).Decode(&metadata); err != nil {\n\t\treturn err\n\t}\n\n\treturn err\n}\n\n\/\/ Crawl a single object, known to be a file\nfunc (c Crawler) CrawlFile(hash string, name string, parent_hash string, parent_name string, size uint64) error {\n\tif size == 262144 && parent_hash == \"\" {\n\t\t\/\/ Assertion error.\n\t\t\/\/ REMOVE ME!\n\t\tlog.Printf(\"Skipping unreferenced partial content for %s\", hash)\n\t\treturn nil\n\t}\n\n\treferences, already_indexed, err := c.index_references(hash, name, parent_hash)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif already_indexed {\n\t\treturn nil\n\t}\n\n\tlog.Printf(\"Crawling file %s (%s)\\n\", hash, name)\n\n\tmetadata := make(map[string]interface{})\n\n\tif size > 0 {\n\t\tif size > METADATA_MAX_SIZE {\n\t\t\t\/\/ Fail hard for really large files, for now\n\t\t\treturn fmt.Errorf(\"%s (%s) too large, not indexing (for now).\", hash, name)\n\t\t}\n\n\t\tvar path string\n\t\tif name != \"\" && parent_hash != \"\" {\n\t\t\tpath = fmt.Sprintf(\"\/ipfs\/%s\/%s\", parent_hash, name)\n\t\t} else {\n\t\t\tpath = fmt.Sprintf(\"\/ipfs\/%s\", hash)\n\t\t}\n\n\t\ttry_again := true\n\t\tfor try_again {\n\t\t\terr = getMetadata(path, &metadata)\n\n\t\t\ttry_again, err = c.handleError(err, hash)\n\n\t\t\tif try_again {\n\t\t\t\tlog.Printf(\"Retrying in %d seconds\", RECONNECT_WAIT)\n\t\t\t\ttime.Sleep(RECONNECT_WAIT * time.Duration(time.Second))\n\t\t\t}\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Check for IPFS links in content\n\t\t\/*\n\t\t\tfor raw_url := range metadata.urls {\n\t\t\t\turl, err := URL.Parse(raw_url)\n\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 strings.HasPrefix(url.Path, \"\/ipfs\/\") {\n\t\t\t\t\t\/\/ Found IPFS link!\n\t\t\t\t\targs := CrawlerArgs{\n\t\t\t\t\t\tHash:       link.Hash,\n\t\t\t\t\t\tName:       link.Name,\n\t\t\t\t\t\tSize:       link.Size,\n\t\t\t\t\t\tParentHash: hash,\n\t\t\t\t\t}\n\n\t\t\t\t}\n\t\t\t}\n\t\t*\/\n\t}\n\n\tmetadata[\"size\"] = size\n\tmetadata[\"references\"] = references\n\n\terr = c.id.IndexItem(\"file\", hash, metadata)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"Finished file %s\", hash)\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2012 Daniel Connelly.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage rtreego\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"strings\"\n)\n\n\/\/ DimError represents a failure due to mismatched dimensions.\ntype DimError struct {\n\tExpected int\n\tActual   int\n}\n\nfunc (err DimError) Error() string {\n\treturn \"rtreego: dimension mismatch\"\n}\n\n\/\/ DistError is an improper distance measurement.  It implements the error\n\/\/ and is generated when a distance-related assertion fails.\ntype DistError float64\n\nfunc (err DistError) Error() string {\n\treturn \"rtreego: improper distance\"\n}\n\n\/\/ Point represents a point in n-dimensional Euclidean space.\ntype Point []float64\n\n\/\/ Dist computes the Euclidean distance between two points p and q.\nfunc (p Point) dist(q Point) float64 {\n\tif len(p) != len(q) {\n\t\tpanic(DimError{len(p), len(q)})\n\t}\n\tsum := 0.0\n\tfor i := range p {\n\t\tdx := p[i] - q[i]\n\t\tsum += dx * dx\n\t}\n\treturn math.Sqrt(sum)\n}\n\n\/\/ minDist computes the square of the distance from a point to a rectangle.\n\/\/ If the point is contained in the rectangle then the distance is zero.\n\/\/\n\/\/ Implemented per Definition 2 of \"Nearest Neighbor Queries\" by\n\/\/ N. Roussopoulos, S. Kelley and F. Vincent, ACM SIGMOD, pages 71-79, 1995.\nfunc (p Point) minDist(r *Rect) float64 {\n\tif len(p) != len(r.p) {\n\t\tpanic(DimError{len(p), len(r.p)})\n\t}\n\n\tsum := 0.0\n\tfor i, pi := range p {\n\t\tif pi < r.p[i] {\n\t\t\td := pi - r.p[i]\n\t\t\tsum += d * d\n\t\t} else if pi > r.q[i] {\n\t\t\td := pi - r.q[i]\n\t\t\tsum += d * d\n\t\t} else {\n\t\t\tsum += 0\n\t\t}\n\t}\n\treturn sum\n}\n\n\/\/ minMaxDist computes the minimum of the maximum distances from p to points\n\/\/ on r.  If r is the bounding box of some geometric objects, then there is\n\/\/ at least one object contained in r within minMaxDist(p, r) of p.\n\/\/\n\/\/ Implemented per Definition 4 of \"Nearest Neighbor Queries\" by\n\/\/ N. Roussopoulos, S. Kelley and F. Vincent, ACM SIGMOD, pages 71-79, 1995.\nfunc (p Point) minMaxDist(r *Rect) float64 {\n\tif len(p) != len(r.p) {\n\t\tpanic(DimError{len(p), len(r.p)})\n\t}\n\n\t\/\/ by definition, MinMaxDist(p, r) =\n\t\/\/ min{1<=k<=n}(|pk - rmk|^2 + sum{1<=i<=n, i != k}(|pi - rMi|^2))\n\t\/\/ where rmk and rMk are defined as follows:\n\n\trm := func(k int) float64 {\n\t\tif p[k] <= (r.p[k]+r.q[k])\/2 {\n\t\t\treturn r.p[k]\n\t\t}\n\t\treturn r.q[k]\n\t}\n\n\trM := func(k int) float64 {\n\t\tif p[k] >= (r.p[k]+r.q[k])\/2 {\n\t\t\treturn r.p[k]\n\t\t}\n\t\treturn r.q[k]\n\t}\n\n\t\/\/ This formula can be computed in linear time by precomputing\n\t\/\/ S = sum{1<=i<=n}(|pi - rMi|^2).\n\n\tS := 0.0\n\tfor i := range p {\n\t\td := p[i] - rM(i)\n\t\tS += d * d\n\t}\n\n\t\/\/ Compute MinMaxDist using the precomputed S.\n\tmin := math.MaxFloat64\n\tfor k := range p {\n\t\td1 := p[k] - rM(k)\n\t\td2 := p[k] - rm(k)\n\t\td := S - d1*d1 + d2*d2\n\t\tif d < min {\n\t\t\tmin = d\n\t\t}\n\t}\n\n\treturn min\n}\n\n\/\/ Rect represents a subset of n-dimensional Euclidean space of the form\n\/\/ [a1, b1] x [a2, b2] x ... x [an, bn], where ai < bi for all 1 <= i <= n.\ntype Rect struct {\n\tp, q Point \/\/ Enforced by NewRect: p[i] <= q[i] for all i.\n}\n\n\/\/ PointCoord returns the coordinate of the point of the rectangle at i\nfunc (r *Rect) PointCoord(i int) float64 {\n\treturn r.p[i]\n}\n\n\/\/ LengthsCoord returns the coordinate of the lengths of the rectangle at i\nfunc (r *Rect) LengthsCoord(i int) float64 {\n\treturn r.q[i] - r.p[i]\n}\n\n\/\/ Equal returns true if the two rectangles are equal\nfunc (r *Rect) Equal(other *Rect) bool {\n\tfor i, e := range r.p {\n\t\tif e != other.p[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\tfor i, e := range r.q {\n\t\tif e != other.q[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc (r *Rect) String() string {\n\ts := make([]string, len(r.p))\n\tfor i, a := range r.p {\n\t\tb := r.q[i]\n\t\ts[i] = fmt.Sprintf(\"[%.2f, %.2f]\", a, b)\n\t}\n\treturn strings.Join(s, \"x\")\n}\n\n\/\/ NewRect constructs and returns a pointer to a Rect given a corner point and\n\/\/ the lengths of each dimension.  The point p should be the most-negative point\n\/\/ on the rectangle (in every dimension) and every length should be positive.\nfunc NewRect(p Point, lengths []float64) (r *Rect, err error) {\n\tr = new(Rect)\n\tr.p = p\n\tif len(p) != len(lengths) {\n\t\terr = &DimError{len(p), len(lengths)}\n\t\treturn\n\t}\n\tr.q = make([]float64, len(p))\n\tfor i := range p {\n\t\tif lengths[i] <= 0 {\n\t\t\terr = DistError(lengths[i])\n\t\t\treturn\n\t\t}\n\t\tr.q[i] = p[i] + lengths[i]\n\t}\n\treturn\n}\n\n\/\/ NewRectFromPoints constructs and returns a pointer to a Rect given a corner points.\nfunc NewRectFromPoints(minPoint, maxPoint Point) (r *Rect, err error) {\n\tif len(minPoint) != len(maxPoint) {\n\t\terr = &DimError{len(minPoint), len(maxPoint)}\n\t\treturn\n\t}\n\n\tr = new(Rect)\n\tr.p = minPoint\n\tr.q = maxPoint\n\n\treturn\n}\n\n\/\/ Size computes the measure of a rectangle (the product of its side lengths).\nfunc (r *Rect) Size() float64 {\n\tsize := 1.0\n\tfor i, a := range r.p {\n\t\tb := r.q[i]\n\t\tsize *= b - a\n\t}\n\treturn size\n}\n\n\/\/ margin computes the sum of the edge lengths of a rectangle.\nfunc (r *Rect) margin() float64 {\n\t\/\/ The number of edges in an n-dimensional rectangle is n * 2^(n-1)\n\t\/\/ (http:\/\/en.wikipedia.org\/wiki\/Hypercube_graph).  Thus the number\n\t\/\/ of edges of length (ai - bi), where the rectangle is determined\n\t\/\/ by p = (a1, a2, ..., an) and q = (b1, b2, ..., bn), is 2^(n-1).\n\t\/\/\n\t\/\/ The margin of the rectangle, then, is given by the formula\n\t\/\/ 2^(n-1) * [(b1 - a1) + (b2 - a2) + ... + (bn - an)].\n\tdim := len(r.p)\n\tsum := 0.0\n\tfor i, a := range r.p {\n\t\tb := r.q[i]\n\t\tsum += b - a\n\t}\n\treturn math.Pow(2, float64(dim-1)) * sum\n}\n\n\/\/ containsPoint tests whether p is located inside or on the boundary of r.\nfunc (r *Rect) containsPoint(p Point) bool {\n\tif len(p) != len(r.p) {\n\t\tpanic(DimError{len(r.p), len(p)})\n\t}\n\n\tfor i, a := range p {\n\t\t\/\/ p is contained in (or on) r if and only if p <= a <= q for\n\t\t\/\/ every dimension.\n\t\tif a < r.p[i] || a > r.q[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\n\/\/ containsRect tests whether r2 is is located inside r1.\nfunc (r *Rect) containsRect(r2 *Rect) bool {\n\tif len(r.p) != len(r2.p) {\n\t\tpanic(DimError{len(r.p), len(r2.p)})\n\t}\n\n\tfor i, a1 := range r.p {\n\t\tb1, a2, b2 := r.q[i], r2.p[i], r2.q[i]\n\t\t\/\/ enforced by constructor: a1 <= b1 and a2 <= b2.\n\t\t\/\/ so containment holds if and only if a1 <= a2 <= b2 <= b1\n\t\t\/\/ for every dimension.\n\t\tif a1 > a2 || b2 > b1 {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\n\/\/ intersect computes the intersection of two rectangles.  If no intersection\n\/\/ exists, the intersection is nil.\nfunc intersect(r1, r2 *Rect) bool {\n\tdim := len(r1.p)\n\tif len(r2.p) != dim {\n\t\tpanic(DimError{dim, len(r2.p)})\n\t}\n\n\t\/\/ There are four cases of overlap:\n\t\/\/\n\t\/\/     1.  a1------------b1\n\t\/\/              a2------------b2\n\t\/\/              p--------q\n\t\/\/\n\t\/\/     2.       a1------------b1\n\t\/\/         a2------------b2\n\t\/\/              p--------q\n\t\/\/\n\t\/\/     3.  a1-----------------b1\n\t\/\/              a2-------b2\n\t\/\/              p--------q\n\t\/\/\n\t\/\/     4.       a1-------b1\n\t\/\/         a2-----------------b2\n\t\/\/              p--------q\n\t\/\/\n\t\/\/ Thus there are only two cases of non-overlap:\n\t\/\/\n\t\/\/     1. a1------b1\n\t\/\/                    a2------b2\n\t\/\/\n\t\/\/     2.             a1------b1\n\t\/\/        a2------b2\n\t\/\/\n\t\/\/ Enforced by constructor: a1 <= b1 and a2 <= b2.  So we can just\n\t\/\/ check the endpoints.\n\n\tfor i := range r1.p {\n\t\ta1, b1, a2, b2 := r1.p[i], r1.q[i], r2.p[i], r2.q[i]\n\t\tif b2 <= a1 || b1 <= a2 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\/\/ ToRect constructs a rectangle containing p with side lengths 2*tol.\nfunc (p Point) ToRect(tol float64) *Rect {\n\tdim := len(p)\n\ta, b := make([]float64, dim), make([]float64, dim)\n\tfor i := range p {\n\t\ta[i] = p[i] - tol\n\t\tb[i] = p[i] + tol\n\t}\n\treturn &Rect{a, b}\n}\n\n\/\/ boundingBox constructs the smallest rectangle containing both r1 and r2.\nfunc boundingBox(r1, r2 *Rect) (bb *Rect) {\n\tbb = new(Rect)\n\tdim := len(r1.p)\n\tbb.p = make([]float64, dim)\n\tbb.q = make([]float64, dim)\n\tif len(r2.p) != dim {\n\t\tpanic(DimError{dim, len(r2.p)})\n\t}\n\tfor i := 0; i < dim; i++ {\n\t\tif r1.p[i] <= r2.p[i] {\n\t\t\tbb.p[i] = r1.p[i]\n\t\t} else {\n\t\t\tbb.p[i] = r2.p[i]\n\t\t}\n\t\tif r1.q[i] <= r2.q[i] {\n\t\t\tbb.q[i] = r2.q[i]\n\t\t} else {\n\t\t\tbb.q[i] = r1.q[i]\n\t\t}\n\t}\n\treturn\n}\n\n\/\/ boundingBoxN constructs the smallest rectangle containing all of r...\nfunc boundingBoxN(rects ...*Rect) (bb *Rect) {\n\tif len(rects) == 1 {\n\t\tbb = rects[0]\n\t\treturn\n\t}\n\tbb = boundingBox(rects[0], rects[1])\n\tfor _, rect := range rects[2:] {\n\t\tbb = boundingBox(bb, rect)\n\t}\n\treturn\n}\n<commit_msg>fix code style<commit_after>\/\/ Copyright 2012 Daniel Connelly.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage rtreego\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"strings\"\n)\n\n\/\/ DimError represents a failure due to mismatched dimensions.\ntype DimError struct {\n\tExpected int\n\tActual   int\n}\n\nfunc (err DimError) Error() string {\n\treturn \"rtreego: dimension mismatch\"\n}\n\n\/\/ DistError is an improper distance measurement.  It implements the error\n\/\/ and is generated when a distance-related assertion fails.\ntype DistError float64\n\nfunc (err DistError) Error() string {\n\treturn \"rtreego: improper distance\"\n}\n\n\/\/ Point represents a point in n-dimensional Euclidean space.\ntype Point []float64\n\n\/\/ Dist computes the Euclidean distance between two points p and q.\nfunc (p Point) dist(q Point) float64 {\n\tif len(p) != len(q) {\n\t\tpanic(DimError{len(p), len(q)})\n\t}\n\tsum := 0.0\n\tfor i := range p {\n\t\tdx := p[i] - q[i]\n\t\tsum += dx * dx\n\t}\n\treturn math.Sqrt(sum)\n}\n\n\/\/ minDist computes the square of the distance from a point to a rectangle.\n\/\/ If the point is contained in the rectangle then the distance is zero.\n\/\/\n\/\/ Implemented per Definition 2 of \"Nearest Neighbor Queries\" by\n\/\/ N. Roussopoulos, S. Kelley and F. Vincent, ACM SIGMOD, pages 71-79, 1995.\nfunc (p Point) minDist(r *Rect) float64 {\n\tif len(p) != len(r.p) {\n\t\tpanic(DimError{len(p), len(r.p)})\n\t}\n\n\tsum := 0.0\n\tfor i, pi := range p {\n\t\tif pi < r.p[i] {\n\t\t\td := pi - r.p[i]\n\t\t\tsum += d * d\n\t\t} else if pi > r.q[i] {\n\t\t\td := pi - r.q[i]\n\t\t\tsum += d * d\n\t\t} else {\n\t\t\tsum += 0\n\t\t}\n\t}\n\treturn sum\n}\n\n\/\/ minMaxDist computes the minimum of the maximum distances from p to points\n\/\/ on r.  If r is the bounding box of some geometric objects, then there is\n\/\/ at least one object contained in r within minMaxDist(p, r) of p.\n\/\/\n\/\/ Implemented per Definition 4 of \"Nearest Neighbor Queries\" by\n\/\/ N. Roussopoulos, S. Kelley and F. Vincent, ACM SIGMOD, pages 71-79, 1995.\nfunc (p Point) minMaxDist(r *Rect) float64 {\n\tif len(p) != len(r.p) {\n\t\tpanic(DimError{len(p), len(r.p)})\n\t}\n\n\t\/\/ by definition, MinMaxDist(p, r) =\n\t\/\/ min{1<=k<=n}(|pk - rmk|^2 + sum{1<=i<=n, i != k}(|pi - rMi|^2))\n\t\/\/ where rmk and rMk are defined as follows:\n\n\trm := func(k int) float64 {\n\t\tif p[k] <= (r.p[k]+r.q[k])\/2 {\n\t\t\treturn r.p[k]\n\t\t}\n\t\treturn r.q[k]\n\t}\n\n\trM := func(k int) float64 {\n\t\tif p[k] >= (r.p[k]+r.q[k])\/2 {\n\t\t\treturn r.p[k]\n\t\t}\n\t\treturn r.q[k]\n\t}\n\n\t\/\/ This formula can be computed in linear time by precomputing\n\t\/\/ S = sum{1<=i<=n}(|pi - rMi|^2).\n\n\tS := 0.0\n\tfor i := range p {\n\t\td := p[i] - rM(i)\n\t\tS += d * d\n\t}\n\n\t\/\/ Compute MinMaxDist using the precomputed S.\n\tmin := math.MaxFloat64\n\tfor k := range p {\n\t\td1 := p[k] - rM(k)\n\t\td2 := p[k] - rm(k)\n\t\td := S - d1*d1 + d2*d2\n\t\tif d < min {\n\t\t\tmin = d\n\t\t}\n\t}\n\n\treturn min\n}\n\n\/\/ Rect represents a subset of n-dimensional Euclidean space of the form\n\/\/ [a1, b1] x [a2, b2] x ... x [an, bn], where ai < bi for all 1 <= i <= n.\ntype Rect struct {\n\tp, q Point \/\/ Enforced by NewRect: p[i] <= q[i] for all i.\n}\n\n\/\/ PointCoord returns the coordinate of the point of the rectangle at i\nfunc (r *Rect) PointCoord(i int) float64 {\n\treturn r.p[i]\n}\n\n\/\/ LengthsCoord returns the coordinate of the lengths of the rectangle at i\nfunc (r *Rect) LengthsCoord(i int) float64 {\n\treturn r.q[i] - r.p[i]\n}\n\n\/\/ Equal returns true if the two rectangles are equal\nfunc (r *Rect) Equal(other *Rect) bool {\n\tfor i, e := range r.p {\n\t\tif e != other.p[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\tfor i, e := range r.q {\n\t\tif e != other.q[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc (r *Rect) String() string {\n\ts := make([]string, len(r.p))\n\tfor i, a := range r.p {\n\t\tb := r.q[i]\n\t\ts[i] = fmt.Sprintf(\"[%.2f, %.2f]\", a, b)\n\t}\n\treturn strings.Join(s, \"x\")\n}\n\n\/\/ NewRect constructs and returns a pointer to a Rect given a corner point and\n\/\/ the lengths of each dimension.  The point p should be the most-negative point\n\/\/ on the rectangle (in every dimension) and every length should be positive.\nfunc NewRect(p Point, lengths []float64) (r *Rect, err error) {\n\tr = new(Rect)\n\tr.p = p\n\tif len(p) != len(lengths) {\n\t\terr = &DimError{len(p), len(lengths)}\n\t\treturn\n\t}\n\tr.q = make([]float64, len(p))\n\tfor i := range p {\n\t\tif lengths[i] <= 0 {\n\t\t\terr = DistError(lengths[i])\n\t\t\treturn\n\t\t}\n\t\tr.q[i] = p[i] + lengths[i]\n\t}\n\treturn\n}\n\n\/\/ NewRectFromPoints constructs and returns a pointer to a Rect given a corner points.\nfunc NewRectFromPoints(minPoint, maxPoint Point) (r *Rect, err error) {\n\tif len(minPoint) != len(maxPoint) {\n\t\terr = &DimError{len(minPoint), len(maxPoint)}\n\t\treturn\n\t}\n\n\tr = &Rect{p: minPoint, q: maxPoint}\n\treturn\n}\n\n\/\/ Size computes the measure of a rectangle (the product of its side lengths).\nfunc (r *Rect) Size() float64 {\n\tsize := 1.0\n\tfor i, a := range r.p {\n\t\tb := r.q[i]\n\t\tsize *= b - a\n\t}\n\treturn size\n}\n\n\/\/ margin computes the sum of the edge lengths of a rectangle.\nfunc (r *Rect) margin() float64 {\n\t\/\/ The number of edges in an n-dimensional rectangle is n * 2^(n-1)\n\t\/\/ (http:\/\/en.wikipedia.org\/wiki\/Hypercube_graph).  Thus the number\n\t\/\/ of edges of length (ai - bi), where the rectangle is determined\n\t\/\/ by p = (a1, a2, ..., an) and q = (b1, b2, ..., bn), is 2^(n-1).\n\t\/\/\n\t\/\/ The margin of the rectangle, then, is given by the formula\n\t\/\/ 2^(n-1) * [(b1 - a1) + (b2 - a2) + ... + (bn - an)].\n\tdim := len(r.p)\n\tsum := 0.0\n\tfor i, a := range r.p {\n\t\tb := r.q[i]\n\t\tsum += b - a\n\t}\n\treturn math.Pow(2, float64(dim-1)) * sum\n}\n\n\/\/ containsPoint tests whether p is located inside or on the boundary of r.\nfunc (r *Rect) containsPoint(p Point) bool {\n\tif len(p) != len(r.p) {\n\t\tpanic(DimError{len(r.p), len(p)})\n\t}\n\n\tfor i, a := range p {\n\t\t\/\/ p is contained in (or on) r if and only if p <= a <= q for\n\t\t\/\/ every dimension.\n\t\tif a < r.p[i] || a > r.q[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\n\/\/ containsRect tests whether r2 is is located inside r1.\nfunc (r *Rect) containsRect(r2 *Rect) bool {\n\tif len(r.p) != len(r2.p) {\n\t\tpanic(DimError{len(r.p), len(r2.p)})\n\t}\n\n\tfor i, a1 := range r.p {\n\t\tb1, a2, b2 := r.q[i], r2.p[i], r2.q[i]\n\t\t\/\/ enforced by constructor: a1 <= b1 and a2 <= b2.\n\t\t\/\/ so containment holds if and only if a1 <= a2 <= b2 <= b1\n\t\t\/\/ for every dimension.\n\t\tif a1 > a2 || b2 > b1 {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\n\/\/ intersect computes the intersection of two rectangles.  If no intersection\n\/\/ exists, the intersection is nil.\nfunc intersect(r1, r2 *Rect) bool {\n\tdim := len(r1.p)\n\tif len(r2.p) != dim {\n\t\tpanic(DimError{dim, len(r2.p)})\n\t}\n\n\t\/\/ There are four cases of overlap:\n\t\/\/\n\t\/\/     1.  a1------------b1\n\t\/\/              a2------------b2\n\t\/\/              p--------q\n\t\/\/\n\t\/\/     2.       a1------------b1\n\t\/\/         a2------------b2\n\t\/\/              p--------q\n\t\/\/\n\t\/\/     3.  a1-----------------b1\n\t\/\/              a2-------b2\n\t\/\/              p--------q\n\t\/\/\n\t\/\/     4.       a1-------b1\n\t\/\/         a2-----------------b2\n\t\/\/              p--------q\n\t\/\/\n\t\/\/ Thus there are only two cases of non-overlap:\n\t\/\/\n\t\/\/     1. a1------b1\n\t\/\/                    a2------b2\n\t\/\/\n\t\/\/     2.             a1------b1\n\t\/\/        a2------b2\n\t\/\/\n\t\/\/ Enforced by constructor: a1 <= b1 and a2 <= b2.  So we can just\n\t\/\/ check the endpoints.\n\n\tfor i := range r1.p {\n\t\ta1, b1, a2, b2 := r1.p[i], r1.q[i], r2.p[i], r2.q[i]\n\t\tif b2 <= a1 || b1 <= a2 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\/\/ ToRect constructs a rectangle containing p with side lengths 2*tol.\nfunc (p Point) ToRect(tol float64) *Rect {\n\tdim := len(p)\n\ta, b := make([]float64, dim), make([]float64, dim)\n\tfor i := range p {\n\t\ta[i] = p[i] - tol\n\t\tb[i] = p[i] + tol\n\t}\n\treturn &Rect{a, b}\n}\n\n\/\/ boundingBox constructs the smallest rectangle containing both r1 and r2.\nfunc boundingBox(r1, r2 *Rect) (bb *Rect) {\n\tbb = new(Rect)\n\tdim := len(r1.p)\n\tbb.p = make([]float64, dim)\n\tbb.q = make([]float64, dim)\n\tif len(r2.p) != dim {\n\t\tpanic(DimError{dim, len(r2.p)})\n\t}\n\tfor i := 0; i < dim; i++ {\n\t\tif r1.p[i] <= r2.p[i] {\n\t\t\tbb.p[i] = r1.p[i]\n\t\t} else {\n\t\t\tbb.p[i] = r2.p[i]\n\t\t}\n\t\tif r1.q[i] <= r2.q[i] {\n\t\t\tbb.q[i] = r2.q[i]\n\t\t} else {\n\t\t\tbb.q[i] = r1.q[i]\n\t\t}\n\t}\n\treturn\n}\n\n\/\/ boundingBoxN constructs the smallest rectangle containing all of r...\nfunc boundingBoxN(rects ...*Rect) (bb *Rect) {\n\tif len(rects) == 1 {\n\t\tbb = rects[0]\n\t\treturn\n\t}\n\tbb = boundingBox(rects[0], rects[1])\n\tfor _, rect := range rects[2:] {\n\t\tbb = boundingBox(bb, rect)\n\t}\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2018 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage dynamic\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"k8s.io\/apimachinery\/pkg\/api\/meta\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\/unstructured\"\n\t\"k8s.io\/apimachinery\/pkg\/runtime\"\n\t\"k8s.io\/apimachinery\/pkg\/runtime\/schema\"\n\t\"k8s.io\/apimachinery\/pkg\/types\"\n\t\"k8s.io\/apimachinery\/pkg\/watch\"\n\t\"k8s.io\/client-go\/rest\"\n)\n\ntype dynamicClient struct {\n\tclient *rest.RESTClient\n}\n\nvar _ Interface = &dynamicClient{}\n\n\/\/ ConfigFor returns a copy of the provided config with the\n\/\/ appropriate dynamic client defaults set.\nfunc ConfigFor(inConfig *rest.Config) *rest.Config {\n\tconfig := rest.CopyConfig(inConfig)\n\tconfig.AcceptContentTypes = \"application\/json\"\n\tconfig.ContentType = \"application\/json\"\n\tconfig.NegotiatedSerializer = basicNegotiatedSerializer{} \/\/ this gets used for discovery and error handling types\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\treturn config\n}\n\n\/\/ NewForConfigOrDie creates a new Interface for the given config and\n\/\/ panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) Interface {\n\tret, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn ret\n}\n\n\/\/ NewForConfig creates a new dynamic client or returns an error.\nfunc NewForConfig(inConfig *rest.Config) (Interface, error) {\n\tconfig := ConfigFor(inConfig)\n\t\/\/ for serializing the options\n\tconfig.GroupVersion = &schema.GroupVersion{}\n\tconfig.APIPath = \"\/if-you-see-this-search-for-the-break\"\n\n\trestClient, err := rest.RESTClientFor(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &dynamicClient{client: restClient}, nil\n}\n\ntype dynamicResourceClient struct {\n\tclient    *dynamicClient\n\tnamespace string\n\tresource  schema.GroupVersionResource\n}\n\nfunc (c *dynamicClient) Resource(resource schema.GroupVersionResource) NamespaceableResourceInterface {\n\treturn &dynamicResourceClient{client: c, resource: resource}\n}\n\nfunc (c *dynamicResourceClient) Namespace(ns string) ResourceInterface {\n\tret := *c\n\tret.namespace = ns\n\treturn &ret\n}\n\nfunc (c *dynamicResourceClient) Create(ctx context.Context, obj *unstructured.Unstructured, opts metav1.CreateOptions, subresources ...string) (*unstructured.Unstructured, error) {\n\toutBytes, err := runtime.Encode(unstructured.UnstructuredJSONScheme, obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := \"\"\n\tif len(subresources) > 0 {\n\t\taccessor, err := meta.Accessor(obj)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tname = accessor.GetName()\n\t\tif len(name) == 0 {\n\t\t\treturn nil, fmt.Errorf(\"name is required\")\n\t\t}\n\t}\n\n\tresult := c.client.client.\n\t\tPost().\n\t\tAbsPath(append(c.makeURLSegments(name), subresources...)...).\n\t\tSetHeader(\"Content-Type\", runtime.ContentTypeJSON).\n\t\tBody(outBytes).\n\t\tSpecificallyVersionedParams(&opts, dynamicParameterCodec, versionV1).\n\t\tDo(ctx)\n\tif err := result.Error(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tretBytes, err := result.Raw()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tuncastObj, err := runtime.Decode(unstructured.UnstructuredJSONScheme, retBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn uncastObj.(*unstructured.Unstructured), nil\n}\n\nfunc (c *dynamicResourceClient) Update(ctx context.Context, obj *unstructured.Unstructured, opts metav1.UpdateOptions, subresources ...string) (*unstructured.Unstructured, error) {\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := accessor.GetName()\n\tif len(name) == 0 {\n\t\treturn nil, fmt.Errorf(\"name is required\")\n\t}\n\toutBytes, err := runtime.Encode(unstructured.UnstructuredJSONScheme, obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := c.client.client.\n\t\tPut().\n\t\tAbsPath(append(c.makeURLSegments(name), subresources...)...).\n\t\tSetHeader(\"Content-Type\", runtime.ContentTypeJSON).\n\t\tBody(outBytes).\n\t\tSpecificallyVersionedParams(&opts, dynamicParameterCodec, versionV1).\n\t\tDo(ctx)\n\tif err := result.Error(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tretBytes, err := result.Raw()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tuncastObj, err := runtime.Decode(unstructured.UnstructuredJSONScheme, retBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn uncastObj.(*unstructured.Unstructured), nil\n}\n\nfunc (c *dynamicResourceClient) UpdateStatus(ctx context.Context, obj *unstructured.Unstructured, opts metav1.UpdateOptions) (*unstructured.Unstructured, error) {\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := accessor.GetName()\n\tif len(name) == 0 {\n\t\treturn nil, fmt.Errorf(\"name is required\")\n\t}\n\n\toutBytes, err := runtime.Encode(unstructured.UnstructuredJSONScheme, obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := c.client.client.\n\t\tPut().\n\t\tAbsPath(append(c.makeURLSegments(name), \"status\")...).\n\t\tSetHeader(\"Content-Type\", runtime.ContentTypeJSON).\n\t\tBody(outBytes).\n\t\tSpecificallyVersionedParams(&opts, dynamicParameterCodec, versionV1).\n\t\tDo(ctx)\n\tif err := result.Error(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tretBytes, err := result.Raw()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tuncastObj, err := runtime.Decode(unstructured.UnstructuredJSONScheme, retBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn uncastObj.(*unstructured.Unstructured), nil\n}\n\nfunc (c *dynamicResourceClient) Delete(ctx context.Context, name string, opts metav1.DeleteOptions, subresources ...string) error {\n\tif len(name) == 0 {\n\t\treturn fmt.Errorf(\"name is required\")\n\t}\n\tdeleteOptionsByte, err := runtime.Encode(deleteOptionsCodec.LegacyCodec(schema.GroupVersion{Version: \"v1\"}), &opts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tresult := c.client.client.\n\t\tDelete().\n\t\tAbsPath(append(c.makeURLSegments(name), subresources...)...).\n\t\tSetHeader(\"Content-Type\", runtime.ContentTypeJSON).\n\t\tBody(deleteOptionsByte).\n\t\tDo(ctx)\n\treturn result.Error()\n}\n\nfunc (c *dynamicResourceClient) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOptions metav1.ListOptions) error {\n\tdeleteOptionsByte, err := runtime.Encode(deleteOptionsCodec.LegacyCodec(schema.GroupVersion{Version: \"v1\"}), &opts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tresult := c.client.client.\n\t\tDelete().\n\t\tAbsPath(c.makeURLSegments(\"\")...).\n\t\tSetHeader(\"Content-Type\", runtime.ContentTypeJSON).\n\t\tBody(deleteOptionsByte).\n\t\tSpecificallyVersionedParams(&listOptions, dynamicParameterCodec, versionV1).\n\t\tDo(ctx)\n\treturn result.Error()\n}\n\nfunc (c *dynamicResourceClient) Get(ctx context.Context, name string, opts metav1.GetOptions, subresources ...string) (*unstructured.Unstructured, error) {\n\tif len(name) == 0 {\n\t\treturn nil, fmt.Errorf(\"name is required\")\n\t}\n\tresult := c.client.client.Get().AbsPath(append(c.makeURLSegments(name), subresources...)...).SpecificallyVersionedParams(&opts, dynamicParameterCodec, versionV1).Do(ctx)\n\tif err := result.Error(); err != nil {\n\t\treturn nil, err\n\t}\n\tretBytes, err := result.Raw()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tuncastObj, err := runtime.Decode(unstructured.UnstructuredJSONScheme, retBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn uncastObj.(*unstructured.Unstructured), nil\n}\n\nfunc (c *dynamicResourceClient) List(ctx context.Context, opts metav1.ListOptions) (*unstructured.UnstructuredList, error) {\n\tresult := c.client.client.Get().AbsPath(c.makeURLSegments(\"\")...).SpecificallyVersionedParams(&opts, dynamicParameterCodec, versionV1).Do(ctx)\n\tif err := result.Error(); err != nil {\n\t\treturn nil, err\n\t}\n\tretBytes, err := result.Raw()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tuncastObj, err := runtime.Decode(unstructured.UnstructuredJSONScheme, retBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif list, ok := uncastObj.(*unstructured.UnstructuredList); ok {\n\t\treturn list, nil\n\t}\n\n\tlist, err := uncastObj.(*unstructured.Unstructured).ToList()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn list, nil\n}\n\nfunc (c *dynamicResourceClient) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\topts.Watch = true\n\treturn c.client.client.Get().AbsPath(c.makeURLSegments(\"\")...).\n\t\tSpecificallyVersionedParams(&opts, dynamicParameterCodec, versionV1).\n\t\tWatch(ctx)\n}\n\nfunc (c *dynamicResourceClient) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (*unstructured.Unstructured, error) {\n\tif len(name) == 0 {\n\t\treturn nil, fmt.Errorf(\"name is required\")\n\t}\n\tresult := c.client.client.\n\t\tPatch(pt).\n\t\tAbsPath(append(c.makeURLSegments(name), subresources...)...).\n\t\tBody(data).\n\t\tSpecificallyVersionedParams(&opts, dynamicParameterCodec, versionV1).\n\t\tDo(ctx)\n\tif err := result.Error(); err != nil {\n\t\treturn nil, err\n\t}\n\tretBytes, err := result.Raw()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tuncastObj, err := runtime.Decode(unstructured.UnstructuredJSONScheme, retBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn uncastObj.(*unstructured.Unstructured), nil\n}\n\nfunc (c *dynamicResourceClient) makeURLSegments(name string) []string {\n\turl := []string{}\n\tif len(c.resource.Group) == 0 {\n\t\turl = append(url, \"api\")\n\t} else {\n\t\turl = append(url, \"apis\", c.resource.Group)\n\t}\n\turl = append(url, c.resource.Version)\n\n\tif len(c.namespace) > 0 {\n\t\turl = append(url, \"namespaces\", c.namespace)\n\t}\n\turl = append(url, c.resource.Resource)\n\n\tif len(name) > 0 {\n\t\turl = append(url, name)\n\t}\n\n\treturn url\n}\n<commit_msg>expose NewForConfigAndClient for the dynamic client<commit_after>\/*\nCopyright 2018 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage dynamic\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net\/http\"\n\n\t\"k8s.io\/apimachinery\/pkg\/api\/meta\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\/unstructured\"\n\t\"k8s.io\/apimachinery\/pkg\/runtime\"\n\t\"k8s.io\/apimachinery\/pkg\/runtime\/schema\"\n\t\"k8s.io\/apimachinery\/pkg\/types\"\n\t\"k8s.io\/apimachinery\/pkg\/watch\"\n\t\"k8s.io\/client-go\/rest\"\n)\n\ntype dynamicClient struct {\n\tclient *rest.RESTClient\n}\n\nvar _ Interface = &dynamicClient{}\n\n\/\/ ConfigFor returns a copy of the provided config with the\n\/\/ appropriate dynamic client defaults set.\nfunc ConfigFor(inConfig *rest.Config) *rest.Config {\n\tconfig := rest.CopyConfig(inConfig)\n\tconfig.AcceptContentTypes = \"application\/json\"\n\tconfig.ContentType = \"application\/json\"\n\tconfig.NegotiatedSerializer = basicNegotiatedSerializer{} \/\/ this gets used for discovery and error handling types\n\tif config.UserAgent == \"\" {\n\t\tconfig.UserAgent = rest.DefaultKubernetesUserAgent()\n\t}\n\treturn config\n}\n\n\/\/ NewForConfigOrDie creates a new Interface for the given config and\n\/\/ panics if there is an error in the config.\nfunc NewForConfigOrDie(c *rest.Config) Interface {\n\tret, err := NewForConfig(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn ret\n}\n\n\/\/ NewForConfig creates a new dynamic client or returns an error.\n\/\/ NewForConfig is equivalent to NewForConfigAndClient(c, httpClient),\n\/\/ where httpClient was generated with rest.HTTPClientFor(c).\nfunc NewForConfig(inConfig *rest.Config) (Interface, error) {\n\tconfig := ConfigFor(inConfig)\n\n\thttpClient, err := rest.HTTPClientFor(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewForConfigAndClient(config, httpClient)\n}\n\n\/\/ NewForConfigAndClient creates a new dynamic client for the given config and http client.\n\/\/ Note the http client provided takes precedence over the configured transport values.\nfunc NewForConfigAndClient(inConfig *rest.Config, h *http.Client) (Interface, error) {\n\tconfig := ConfigFor(inConfig)\n\t\/\/ for serializing the options\n\tconfig.GroupVersion = &schema.GroupVersion{}\n\tconfig.APIPath = \"\/if-you-see-this-search-for-the-break\"\n\n\trestClient, err := rest.RESTClientForConfigAndClient(config, h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &dynamicClient{client: restClient}, nil\n}\n\ntype dynamicResourceClient struct {\n\tclient    *dynamicClient\n\tnamespace string\n\tresource  schema.GroupVersionResource\n}\n\nfunc (c *dynamicClient) Resource(resource schema.GroupVersionResource) NamespaceableResourceInterface {\n\treturn &dynamicResourceClient{client: c, resource: resource}\n}\n\nfunc (c *dynamicResourceClient) Namespace(ns string) ResourceInterface {\n\tret := *c\n\tret.namespace = ns\n\treturn &ret\n}\n\nfunc (c *dynamicResourceClient) Create(ctx context.Context, obj *unstructured.Unstructured, opts metav1.CreateOptions, subresources ...string) (*unstructured.Unstructured, error) {\n\toutBytes, err := runtime.Encode(unstructured.UnstructuredJSONScheme, obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := \"\"\n\tif len(subresources) > 0 {\n\t\taccessor, err := meta.Accessor(obj)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tname = accessor.GetName()\n\t\tif len(name) == 0 {\n\t\t\treturn nil, fmt.Errorf(\"name is required\")\n\t\t}\n\t}\n\n\tresult := c.client.client.\n\t\tPost().\n\t\tAbsPath(append(c.makeURLSegments(name), subresources...)...).\n\t\tSetHeader(\"Content-Type\", runtime.ContentTypeJSON).\n\t\tBody(outBytes).\n\t\tSpecificallyVersionedParams(&opts, dynamicParameterCodec, versionV1).\n\t\tDo(ctx)\n\tif err := result.Error(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tretBytes, err := result.Raw()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tuncastObj, err := runtime.Decode(unstructured.UnstructuredJSONScheme, retBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn uncastObj.(*unstructured.Unstructured), nil\n}\n\nfunc (c *dynamicResourceClient) Update(ctx context.Context, obj *unstructured.Unstructured, opts metav1.UpdateOptions, subresources ...string) (*unstructured.Unstructured, error) {\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := accessor.GetName()\n\tif len(name) == 0 {\n\t\treturn nil, fmt.Errorf(\"name is required\")\n\t}\n\toutBytes, err := runtime.Encode(unstructured.UnstructuredJSONScheme, obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := c.client.client.\n\t\tPut().\n\t\tAbsPath(append(c.makeURLSegments(name), subresources...)...).\n\t\tSetHeader(\"Content-Type\", runtime.ContentTypeJSON).\n\t\tBody(outBytes).\n\t\tSpecificallyVersionedParams(&opts, dynamicParameterCodec, versionV1).\n\t\tDo(ctx)\n\tif err := result.Error(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tretBytes, err := result.Raw()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tuncastObj, err := runtime.Decode(unstructured.UnstructuredJSONScheme, retBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn uncastObj.(*unstructured.Unstructured), nil\n}\n\nfunc (c *dynamicResourceClient) UpdateStatus(ctx context.Context, obj *unstructured.Unstructured, opts metav1.UpdateOptions) (*unstructured.Unstructured, error) {\n\taccessor, err := meta.Accessor(obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tname := accessor.GetName()\n\tif len(name) == 0 {\n\t\treturn nil, fmt.Errorf(\"name is required\")\n\t}\n\n\toutBytes, err := runtime.Encode(unstructured.UnstructuredJSONScheme, obj)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresult := c.client.client.\n\t\tPut().\n\t\tAbsPath(append(c.makeURLSegments(name), \"status\")...).\n\t\tSetHeader(\"Content-Type\", runtime.ContentTypeJSON).\n\t\tBody(outBytes).\n\t\tSpecificallyVersionedParams(&opts, dynamicParameterCodec, versionV1).\n\t\tDo(ctx)\n\tif err := result.Error(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tretBytes, err := result.Raw()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tuncastObj, err := runtime.Decode(unstructured.UnstructuredJSONScheme, retBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn uncastObj.(*unstructured.Unstructured), nil\n}\n\nfunc (c *dynamicResourceClient) Delete(ctx context.Context, name string, opts metav1.DeleteOptions, subresources ...string) error {\n\tif len(name) == 0 {\n\t\treturn fmt.Errorf(\"name is required\")\n\t}\n\tdeleteOptionsByte, err := runtime.Encode(deleteOptionsCodec.LegacyCodec(schema.GroupVersion{Version: \"v1\"}), &opts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tresult := c.client.client.\n\t\tDelete().\n\t\tAbsPath(append(c.makeURLSegments(name), subresources...)...).\n\t\tSetHeader(\"Content-Type\", runtime.ContentTypeJSON).\n\t\tBody(deleteOptionsByte).\n\t\tDo(ctx)\n\treturn result.Error()\n}\n\nfunc (c *dynamicResourceClient) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOptions metav1.ListOptions) error {\n\tdeleteOptionsByte, err := runtime.Encode(deleteOptionsCodec.LegacyCodec(schema.GroupVersion{Version: \"v1\"}), &opts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tresult := c.client.client.\n\t\tDelete().\n\t\tAbsPath(c.makeURLSegments(\"\")...).\n\t\tSetHeader(\"Content-Type\", runtime.ContentTypeJSON).\n\t\tBody(deleteOptionsByte).\n\t\tSpecificallyVersionedParams(&listOptions, dynamicParameterCodec, versionV1).\n\t\tDo(ctx)\n\treturn result.Error()\n}\n\nfunc (c *dynamicResourceClient) Get(ctx context.Context, name string, opts metav1.GetOptions, subresources ...string) (*unstructured.Unstructured, error) {\n\tif len(name) == 0 {\n\t\treturn nil, fmt.Errorf(\"name is required\")\n\t}\n\tresult := c.client.client.Get().AbsPath(append(c.makeURLSegments(name), subresources...)...).SpecificallyVersionedParams(&opts, dynamicParameterCodec, versionV1).Do(ctx)\n\tif err := result.Error(); err != nil {\n\t\treturn nil, err\n\t}\n\tretBytes, err := result.Raw()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tuncastObj, err := runtime.Decode(unstructured.UnstructuredJSONScheme, retBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn uncastObj.(*unstructured.Unstructured), nil\n}\n\nfunc (c *dynamicResourceClient) List(ctx context.Context, opts metav1.ListOptions) (*unstructured.UnstructuredList, error) {\n\tresult := c.client.client.Get().AbsPath(c.makeURLSegments(\"\")...).SpecificallyVersionedParams(&opts, dynamicParameterCodec, versionV1).Do(ctx)\n\tif err := result.Error(); err != nil {\n\t\treturn nil, err\n\t}\n\tretBytes, err := result.Raw()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tuncastObj, err := runtime.Decode(unstructured.UnstructuredJSONScheme, retBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif list, ok := uncastObj.(*unstructured.UnstructuredList); ok {\n\t\treturn list, nil\n\t}\n\n\tlist, err := uncastObj.(*unstructured.Unstructured).ToList()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn list, nil\n}\n\nfunc (c *dynamicResourceClient) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {\n\topts.Watch = true\n\treturn c.client.client.Get().AbsPath(c.makeURLSegments(\"\")...).\n\t\tSpecificallyVersionedParams(&opts, dynamicParameterCodec, versionV1).\n\t\tWatch(ctx)\n}\n\nfunc (c *dynamicResourceClient) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (*unstructured.Unstructured, error) {\n\tif len(name) == 0 {\n\t\treturn nil, fmt.Errorf(\"name is required\")\n\t}\n\tresult := c.client.client.\n\t\tPatch(pt).\n\t\tAbsPath(append(c.makeURLSegments(name), subresources...)...).\n\t\tBody(data).\n\t\tSpecificallyVersionedParams(&opts, dynamicParameterCodec, versionV1).\n\t\tDo(ctx)\n\tif err := result.Error(); err != nil {\n\t\treturn nil, err\n\t}\n\tretBytes, err := result.Raw()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tuncastObj, err := runtime.Decode(unstructured.UnstructuredJSONScheme, retBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn uncastObj.(*unstructured.Unstructured), nil\n}\n\nfunc (c *dynamicResourceClient) makeURLSegments(name string) []string {\n\turl := []string{}\n\tif len(c.resource.Group) == 0 {\n\t\turl = append(url, \"api\")\n\t} else {\n\t\turl = append(url, \"apis\", c.resource.Group)\n\t}\n\turl = append(url, c.resource.Version)\n\n\tif len(c.namespace) > 0 {\n\t\turl = append(url, \"namespaces\", c.namespace)\n\t}\n\turl = append(url, c.resource.Resource)\n\n\tif len(name) > 0 {\n\t\turl = append(url, name)\n\t}\n\n\treturn url\n}\n<|endoftext|>"}
{"text":"<commit_before>package ordpool\n\nimport (\n\t\"errors\"\n\t\"github.com\/bmizerany\/assert\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestOneWorkItem(t *testing.T) {\n\to := New(10, passthroughWorkFunc)\n\n\to.Start()\n\tdefer func() {\n\t\to.Stop()\n\t\to.WaitForShutdown()\n\t}()\n\n\to.GetInputCh() <- \"abc\"\n\troundTrip := <-o.GetOutputCh()\n\tassert.Equal(t, \"abc\", roundTrip)\n}\n\nfunc TestFailure(t *testing.T) {\n\to := New(10, failWorkFunc)\n\n\to.Start()\n\tdefer func() {\n\t\to.Stop()\n\t\to.WaitForShutdown()\n\t}()\n\n\to.GetInputCh() <- \"abc\"\n\t_, ok := <-o.GetOutputCh()\n\tassert.T(t, !ok)\n\tassert.Equal(t, 1, len(o.GetErrs()))\n}\n\nfunc TestMaxThroughput(t *testing.T) {\n\tconst NUM_WORKERS = 2\n\to := New(NUM_WORKERS, passthroughWorkFunc)\n\n\to.Start()\n\tdefer func() {\n\t\to.Stop()\n\t\to.WaitForShutdown()\n\t}()\n\n\toutCh := o.GetOutputCh()\n\n\tconst NUM_MSGS = 10000\n\t\/\/ Start a background goroutine to read the pool output and check it\n\tgo func() {\n\t\tfor i := 0; i < NUM_MSGS; i++ {\n\t\t\tmsg, ok := <-outCh\n\t\t\tassert.T(t, ok)\n\t\t\tassert.Equal(t, i, msg.(int))\n\t\t}\n\t}()\n\n\tinCh := o.GetInputCh()\n\tfor i := 0; i < NUM_MSGS; i++ {\n\t\tinCh <- i\n\t}\n\to.Stop()\n}\n\n\/\/ Test that output order is the same as input order even when work items take different\n\/\/ amounts of time to compute.\nfunc TestSequential(t *testing.T) {\n\to := New(10, func(i interface{}) (interface{}, error) {\n\t\t\/\/ Sleep for 0 or 1 millisecond\n\t\ttime.Sleep(time.Duration((i.(int) % 2)) * time.Millisecond)\n\t\treturn i, nil\n\t})\n\n\to.Start()\n\tdefer func() {\n\t\to.Stop()\n\t}()\n\n\tinChan := o.GetInputCh()\n\n\tconst NUM_MSGS = 10000\n\n\tgo func() {\n\t\tfor i := 0; i < NUM_MSGS; i++ {\n\t\t\tinChan <- i\n\t\t}\n\t\to.Stop()\n\t}()\n\n\toutChan := o.GetOutputCh()\n\tfor i := 0; i < NUM_MSGS; i++ {\n\t\troundTrip := <-outChan\n\t\tassert.Equal(t, i, roundTrip)\n\t}\n\to.WaitForShutdown()\n}\n\nfunc TestNoWork(t *testing.T) {\n\to := New(10, passthroughWorkFunc)\n\n\to.Start()\n\to.Stop()\n\to.WaitForShutdown()\n}\n\nfunc passthroughWorkFunc(i interface{}) (interface{}, error) {\n\treturn i, nil\n}\n\nfunc failWorkFunc(i interface{}) (interface{}, error) {\n\treturn nil, errors.New(\"Intentional failure for testing\")\n}\n\n\/\/ Results 2013-4-26: the pool overhead is on the order of 2us with GOMAXPROCS=1 to 10us \n\/\/ with GOMAXPROCS=20.\nfunc BenchmarkPassthrough(b *testing.B) {\n\tconst NUM_WORKERS = 5\n\to := New(NUM_WORKERS, passthroughWorkFunc)\n\n\to.Start()\n\tdefer func() {\n\t\to.Stop()\n\t\to.WaitForShutdown()\n\t}()\n\n\toutCh := o.GetOutputCh()\n\n\t\/\/ Start a background goroutine to read the pool output and discard it\n\tgo func() {\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\tif _, ok := <-outCh; !ok {\n\t\t\t\tpanic(\"unexpected output channel close\")\n\t\t\t}\n\t\t}\n\t}()\n\n\tinCh := o.GetInputCh()\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tinCh <- i\n\t}\n\to.Stop()\n\tb.StopTimer()\n}\n<commit_msg>Pool shutdown time should be part of benchmark<commit_after>package ordpool\n\nimport (\n\t\"errors\"\n\t\"github.com\/bmizerany\/assert\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestOneWorkItem(t *testing.T) {\n\to := New(10, passthroughWorkFunc)\n\n\to.Start()\n\tdefer func() {\n\t\to.Stop()\n\t\to.WaitForShutdown()\n\t}()\n\n\to.GetInputCh() <- \"abc\"\n\troundTrip := <-o.GetOutputCh()\n\tassert.Equal(t, \"abc\", roundTrip)\n}\n\nfunc TestFailure(t *testing.T) {\n\to := New(10, failWorkFunc)\n\n\to.Start()\n\tdefer func() {\n\t\to.Stop()\n\t\to.WaitForShutdown()\n\t}()\n\n\to.GetInputCh() <- \"abc\"\n\t_, ok := <-o.GetOutputCh()\n\tassert.T(t, !ok)\n\tassert.Equal(t, 1, len(o.GetErrs()))\n}\n\nfunc TestMaxThroughput(t *testing.T) {\n\tconst NUM_WORKERS = 2\n\to := New(NUM_WORKERS, passthroughWorkFunc)\n\n\to.Start()\n\tdefer func() {\n\t\to.Stop()\n\t\to.WaitForShutdown()\n\t}()\n\n\toutCh := o.GetOutputCh()\n\n\tconst NUM_MSGS = 10000\n\t\/\/ Start a background goroutine to read the pool output and check it\n\tgo func() {\n\t\tfor i := 0; i < NUM_MSGS; i++ {\n\t\t\tmsg, ok := <-outCh\n\t\t\tassert.T(t, ok)\n\t\t\tassert.Equal(t, i, msg.(int))\n\t\t}\n\t}()\n\n\tinCh := o.GetInputCh()\n\tfor i := 0; i < NUM_MSGS; i++ {\n\t\tinCh <- i\n\t}\n\to.Stop()\n}\n\n\/\/ Test that output order is the same as input order even when work items take different\n\/\/ amounts of time to compute.\nfunc TestSequential(t *testing.T) {\n\to := New(10, func(i interface{}) (interface{}, error) {\n\t\t\/\/ Sleep for 0 or 1 millisecond\n\t\ttime.Sleep(time.Duration((i.(int) % 2)) * time.Millisecond)\n\t\treturn i, nil\n\t})\n\n\to.Start()\n\tdefer func() {\n\t\to.Stop()\n\t}()\n\n\tinChan := o.GetInputCh()\n\n\tconst NUM_MSGS = 10000\n\n\tgo func() {\n\t\tfor i := 0; i < NUM_MSGS; i++ {\n\t\t\tinChan <- i\n\t\t}\n\t\to.Stop()\n\t}()\n\n\toutChan := o.GetOutputCh()\n\tfor i := 0; i < NUM_MSGS; i++ {\n\t\troundTrip := <-outChan\n\t\tassert.Equal(t, i, roundTrip)\n\t}\n\to.WaitForShutdown()\n}\n\nfunc TestNoWork(t *testing.T) {\n\to := New(10, passthroughWorkFunc)\n\n\to.Start()\n\to.Stop()\n\to.WaitForShutdown()\n}\n\nfunc passthroughWorkFunc(i interface{}) (interface{}, error) {\n\treturn i, nil\n}\n\nfunc failWorkFunc(i interface{}) (interface{}, error) {\n\treturn nil, errors.New(\"Intentional failure for testing\")\n}\n\n\/\/ Results 2013-4-26: the pool overhead is on the order of 2us with GOMAXPROCS=1 to 10us \n\/\/ with GOMAXPROCS=20.\nfunc BenchmarkPassthrough(b *testing.B) {\n\tconst NUM_WORKERS = 5\n\to := New(NUM_WORKERS, passthroughWorkFunc)\n\n\to.Start()\n\tdefer func() {\n\t\to.Stop()\n\t\to.WaitForShutdown()\n\t}()\n\n\toutCh := o.GetOutputCh()\n\n\t\/\/ Start a background goroutine to read the pool output and discard it\n\tgo func() {\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\tif _, ok := <-outCh; !ok {\n\t\t\t\tpanic(\"unexpected output channel close\")\n\t\t\t}\n\t\t}\n\t}()\n\n\tinCh := o.GetInputCh()\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tinCh <- i\n\t}\n\to.Stop()\n\to.WaitForShutdown()\n\tb.StopTimer()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage availabilityset\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/r3labs\/terraform\/helper\/schema\"\n\n\taes \"github.com\/ernestio\/crypto\/aes\"\n\t\"github.com\/ernestio\/ernestprovider\/event\"\n\t\"github.com\/ernestio\/ernestprovider\/providers\/azure\"\n)\n\n\/\/ Event : This is the Ernest representation of an azure availability setb\ntype Event struct {\n\tevent.Base\n\tID                        string            `json:\"id\"`\n\tName                      string            `json:\"name\" validate:\"required\"`\n\tResourceGroupName         string            `json:\"resource_group_name\" validate:\"required\"`\n\tLocation                  string            `json:\"location\"`\n\tPlatformUpdateDomainCount int               `json:\"platform_update_domain_count\"`\n\tPlatformFaultDomainCount  int               `json:\"platform_fault_domain_count\"`\n\tManaged                   bool              `json:\"managed\"`\n\tTags                      map[string]string `json:\"tags\"`\n\tClientID                  string            `json:\"azure_client_id\"`\n\tClientSecret              string            `json:\"azure_client_secret\"`\n\tTenantID                  string            `json:\"azure_tenant_id\"`\n\tSubscriptionID            string            `json:\"azure_subscription_id\"`\n\tEnvironment               string            `json:\"environment\"`\n\tErrorMessage              string            `json:\"error,omitempty\"`\n\tComponents                []json.RawMessage `json:\"components\"`\n\tCryptoKey                 string            `json:\"-\"`\n\tValidator                 *event.Validator  `json:\"-\"`\n}\n\n\/\/ New : Constructor\nfunc New(subject, cryptoKey string, body []byte, val *event.Validator) (event.Event, error) {\n\tvar ev event.Resource\n\tev = &Event{CryptoKey: cryptoKey, Validator: val}\n\tbody = []byte(strings.Replace(string(body), `\"_component\":\"availability_sets\"`, `\"_component\":\"availability_set\"`, 1))\n\tif err := json.Unmarshal(body, &ev); err != nil {\n\t\terr := fmt.Errorf(\"Error on input message : %s\", err)\n\t\treturn nil, err\n\t}\n\n\treturn azure.New(subject, \"azurerm_availability_set\", body, val, ev)\n}\n\n\/\/ SetComponents : ....\nfunc (ev *Event) SetComponents(components []event.Event) {\n\tfor _, v := range components {\n\t\tev.Components = append(ev.Components, v.GetBody())\n\t}\n}\n\n\/\/ ValidateID : determines if the given id is valid for this resource type\nfunc (ev *Event) ValidateID(id string) bool {\n\tparts := strings.Split(strings.ToLower(id), \"\/\")\n\tif len(parts) != 8 {\n\t\treturn false\n\t}\n\tif parts[6] != \"microsoft.compute\" {\n\t\treturn false\n\t}\n\tif parts[7] != \"availabilitysets\" {\n\t\treturn false\n\t}\n\treturn true\n}\n\n\/\/ SetID : id setter\nfunc (ev *Event) SetID(id string) {\n\tev.ID = id\n}\n\n\/\/ GetID : id getter\nfunc (ev *Event) GetID() string {\n\treturn ev.ID\n}\n\n\/\/ SetState : state setter\nfunc (ev *Event) SetState(state string) {\n\tev.State = state\n}\n\n\/\/ ResourceDataToEvent : Translates a ResourceData on a valid Ernest Event\nfunc (ev *Event) ResourceDataToEvent(d *schema.ResourceData) error {\n\tidParts := strings.Split(d.Id(), \"\/\")\n\tev.ID = d.Id()\n\tev.Name = idParts[len(idParts)-1]\n\tev.ComponentID = \"availability_set::\" + ev.Name\n\tev.ResourceGroupName = d.Get(\"resource_group_name\").(string)\n\tev.Location = d.Get(\"location\").(string)\n\tev.PlatformUpdateDomainCount = d.Get(\"platform_update_domain_count\").(int)\n\tev.PlatformFaultDomainCount = d.Get(\"platform_fault_domain_count\").(int)\n\tev.Managed = d.Get(\"managed\").(bool)\n\n\ttags := make(map[string]string, 0)\n\tfor k, v := range d.Get(\"tags\").(map[string]interface{}) {\n\t\ttags[k] = v.(string)\n\t}\n\tev.Tags = tags\n\treturn nil\n}\n\n\/\/ EventToResourceData : Translates the current event on a valid ResourceData\nfunc (ev *Event) EventToResourceData(d *schema.ResourceData) error {\n\tcrypto := aes.New()\n\n\tencFields := make(map[string]string)\n\tencFields[\"subscription_id\"] = ev.SubscriptionID\n\tencFields[\"client_id\"] = ev.ClientID\n\tencFields[\"client_secret\"] = ev.ClientSecret\n\tencFields[\"tenant_id\"] = ev.TenantID\n\tencFields[\"environment\"] = ev.Environment\n\tfor k, v := range encFields {\n\t\tdec, err := crypto.Decrypt(v, ev.CryptoKey)\n\t\tif err != nil {\n\t\t\terr := fmt.Errorf(\"Field '%s' not valid : %s\", k, err)\n\t\t\tev.Log(\"error\", err.Error())\n\t\t\treturn err\n\t\t}\n\t\tif err := d.Set(k, dec); err != nil {\n\t\t\terr := fmt.Errorf(\"Field '%s' not valid : %s\", k, err)\n\t\t\tev.Log(\"error\", err.Error())\n\t\t\treturn err\n\t\t}\n\t}\n\n\tfields := make(map[string]interface{})\n\tfields[\"name\"] = ev.Name\n\tfields[\"resource_group_name\"] = ev.ResourceGroupName\n\tfields[\"location\"] = ev.Location\n\tfields[\"platform_update_domain_count\"] = ev.PlatformUpdateDomainCount\n\tfields[\"platform_fault_domain_count\"] = ev.PlatformFaultDomainCount\n\tfields[\"managed\"] = ev.Managed\n\tfields[\"tags\"] = ev.Tags\n\tfor k, v := range fields {\n\t\tif err := d.Set(k, v); err != nil {\n\t\t\terr := fmt.Errorf(\"Field '%s' not valid : %s\", k, err)\n\t\t\tev.Log(\"error\", err.Error())\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ Clone : will mark the event as errored\nfunc (ev *Event) Clone() (event.Event, error) {\n\tbody, _ := json.Marshal(ev)\n\treturn New(ev.Subject, ev.CryptoKey, body, ev.Validator)\n}\n\n\/\/ Error : will mark the event as errored\nfunc (ev *Event) Error(err error) {\n\tev.ErrorMessage = err.Error()\n\tev.Body, err = json.Marshal(ev)\n}\n<commit_msg>removed managed field<commit_after>\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage availabilityset\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/r3labs\/terraform\/helper\/schema\"\n\n\taes \"github.com\/ernestio\/crypto\/aes\"\n\t\"github.com\/ernestio\/ernestprovider\/event\"\n\t\"github.com\/ernestio\/ernestprovider\/providers\/azure\"\n)\n\n\/\/ Event : This is the Ernest representation of an azure availability setb\ntype Event struct {\n\tevent.Base\n\tID                        string            `json:\"id\"`\n\tName                      string            `json:\"name\" validate:\"required\"`\n\tResourceGroupName         string            `json:\"resource_group_name\" validate:\"required\"`\n\tLocation                  string            `json:\"location\"`\n\tPlatformUpdateDomainCount int               `json:\"platform_update_domain_count\"`\n\tPlatformFaultDomainCount  int               `json:\"platform_fault_domain_count\"`\n\tManaged                   bool              `json:\"managed\"`\n\tTags                      map[string]string `json:\"tags\"`\n\tClientID                  string            `json:\"azure_client_id\"`\n\tClientSecret              string            `json:\"azure_client_secret\"`\n\tTenantID                  string            `json:\"azure_tenant_id\"`\n\tSubscriptionID            string            `json:\"azure_subscription_id\"`\n\tEnvironment               string            `json:\"environment\"`\n\tErrorMessage              string            `json:\"error,omitempty\"`\n\tComponents                []json.RawMessage `json:\"components\"`\n\tCryptoKey                 string            `json:\"-\"`\n\tValidator                 *event.Validator  `json:\"-\"`\n}\n\n\/\/ New : Constructor\nfunc New(subject, cryptoKey string, body []byte, val *event.Validator) (event.Event, error) {\n\tvar ev event.Resource\n\tev = &Event{CryptoKey: cryptoKey, Validator: val}\n\tbody = []byte(strings.Replace(string(body), `\"_component\":\"availability_sets\"`, `\"_component\":\"availability_set\"`, 1))\n\tif err := json.Unmarshal(body, &ev); err != nil {\n\t\terr := fmt.Errorf(\"Error on input message : %s\", err)\n\t\treturn nil, err\n\t}\n\n\treturn azure.New(subject, \"azurerm_availability_set\", body, val, ev)\n}\n\n\/\/ SetComponents : ....\nfunc (ev *Event) SetComponents(components []event.Event) {\n\tfor _, v := range components {\n\t\tev.Components = append(ev.Components, v.GetBody())\n\t}\n}\n\n\/\/ ValidateID : determines if the given id is valid for this resource type\nfunc (ev *Event) ValidateID(id string) bool {\n\tparts := strings.Split(strings.ToLower(id), \"\/\")\n\tif len(parts) != 8 {\n\t\treturn false\n\t}\n\tif parts[6] != \"microsoft.compute\" {\n\t\treturn false\n\t}\n\tif parts[7] != \"availabilitysets\" {\n\t\treturn false\n\t}\n\treturn true\n}\n\n\/\/ SetID : id setter\nfunc (ev *Event) SetID(id string) {\n\tev.ID = id\n}\n\n\/\/ GetID : id getter\nfunc (ev *Event) GetID() string {\n\treturn ev.ID\n}\n\n\/\/ SetState : state setter\nfunc (ev *Event) SetState(state string) {\n\tev.State = state\n}\n\n\/\/ ResourceDataToEvent : Translates a ResourceData on a valid Ernest Event\nfunc (ev *Event) ResourceDataToEvent(d *schema.ResourceData) error {\n\tidParts := strings.Split(d.Id(), \"\/\")\n\tev.ID = d.Id()\n\tev.Name = idParts[len(idParts)-1]\n\tev.ComponentID = \"availability_set::\" + ev.Name\n\tev.ResourceGroupName = d.Get(\"resource_group_name\").(string)\n\tev.Location = d.Get(\"location\").(string)\n\tev.PlatformUpdateDomainCount = d.Get(\"platform_update_domain_count\").(int)\n\tev.PlatformFaultDomainCount = d.Get(\"platform_fault_domain_count\").(int)\n\n\ttags := make(map[string]string, 0)\n\tfor k, v := range d.Get(\"tags\").(map[string]interface{}) {\n\t\ttags[k] = v.(string)\n\t}\n\tev.Tags = tags\n\treturn nil\n}\n\n\/\/ EventToResourceData : Translates the current event on a valid ResourceData\nfunc (ev *Event) EventToResourceData(d *schema.ResourceData) error {\n\tcrypto := aes.New()\n\n\tencFields := make(map[string]string)\n\tencFields[\"subscription_id\"] = ev.SubscriptionID\n\tencFields[\"client_id\"] = ev.ClientID\n\tencFields[\"client_secret\"] = ev.ClientSecret\n\tencFields[\"tenant_id\"] = ev.TenantID\n\tencFields[\"environment\"] = ev.Environment\n\tfor k, v := range encFields {\n\t\tdec, err := crypto.Decrypt(v, ev.CryptoKey)\n\t\tif err != nil {\n\t\t\terr := fmt.Errorf(\"Field '%s' not valid : %s\", k, err)\n\t\t\tev.Log(\"error\", err.Error())\n\t\t\treturn err\n\t\t}\n\t\tif err := d.Set(k, dec); err != nil {\n\t\t\terr := fmt.Errorf(\"Field '%s' not valid : %s\", k, err)\n\t\t\tev.Log(\"error\", err.Error())\n\t\t\treturn err\n\t\t}\n\t}\n\n\tfields := make(map[string]interface{})\n\tfields[\"name\"] = ev.Name\n\tfields[\"resource_group_name\"] = ev.ResourceGroupName\n\tfields[\"location\"] = ev.Location\n\tfields[\"platform_update_domain_count\"] = ev.PlatformUpdateDomainCount\n\tfields[\"platform_fault_domain_count\"] = ev.PlatformFaultDomainCount\n\tfields[\"tags\"] = ev.Tags\n\tfor k, v := range fields {\n\t\tif err := d.Set(k, v); err != nil {\n\t\t\terr := fmt.Errorf(\"Field '%s' not valid : %s\", k, err)\n\t\t\tev.Log(\"error\", err.Error())\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ Clone : will mark the event as errored\nfunc (ev *Event) Clone() (event.Event, error) {\n\tbody, _ := json.Marshal(ev)\n\treturn New(ev.Subject, ev.CryptoKey, body, ev.Validator)\n}\n\n\/\/ Error : will mark the event as errored\nfunc (ev *Event) Error(err error) {\n\tev.ErrorMessage = err.Error()\n\tev.Body, err = json.Marshal(ev)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"bytes\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"strings\"\n)\n\nconst templatePath = \"atomic-template.swift\"\nconst destinationPath = \"..\/Source\/atomic.swift\"\n\nfunc main() {\n\tb, err := ioutil.ReadFile(templatePath)\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t}\n\n\tboolTypes := []string{\"Bool\"}\n\tstringTypes := []string{\"String\"}\n\tsignedTypes := []string{\"Int\", \"Int64\", \"Int32\", \"Int16\", \"Int8\"}\n\tunsignedTypes := []string{\"UInt\", \"UInt64\", \"UInt32\", \"UInt16\", \"UInt8\"}\n    floatTypes := []string{\"Double\", \"Float\"}\n\tnumberTypes := append(append(signedTypes, unsignedTypes...), floatTypes...)\n\tallTypes := append(append(numberTypes, boolTypes...), stringTypes...)\n\n\t\/\/ parse\n\ttemplates := make(map[string]string)\n\ttparts := strings.Split(string(b), \"\/\/ TEMPLATE:\")\n\ttemplates[\"base\"] = strings.TrimSpace(tparts[0])\n\ttparts = tparts[1:]\n\tfor _, tpart := range tparts {\n\t\tvar idx = strings.Index(tpart, \"\\n\")\n\t\tvar title = strings.TrimSpace(tpart[:idx])\n\t\ttemplates[title] = strings.TrimSpace(tpart[idx+1:])\n\t}\n\n\trepl := func(key string, op string, t string) string {\n\t\ts := templates[key]\n\t\ts = strings.Replace(s, \"{{O}}\", op, -1)\n\t\ts = strings.Replace(s, \"{{T}}\", t, -1)\n\n\t\tif op != t+\"A\" {\n\t\t\tfor {\n\t\t\t\tidx := strings.Index(s, \"Atomic<\")\n\t\t\t\tif idx == -1 {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tidxe := strings.Index(s[idx:], \">\") + idx\n\t\t\t\ts = s[:idx] + s[idx+7:idxe] + \"A\" + s[idxe+1:]\n\t\t\t}\n\t\t}\n\t\treturn s\n\t}\n\n\tsource := templates[\"base\"] + \"\\n\\n\"\n\n\t\/\/ typealias\n\tfor _, t := range allTypes {\n\t\tsource += repl(\"typealias\", t+\"A\", t) + \"\\n\"\n\t}\n\tsource += \"\\n\"\n\n\t\/\/ initialize\n\tfor _, t := range allTypes {\n\t\tsource += repl(\"initialize-head\", \"\", t) + \"\\n\"\n\t\tsource += \"\\t\" + repl(\"initialize-body\", t, t) + \"\\n\"\n\t\tfor _, it := range numberTypes {\n\t\t\tif t == it {\n\t\t\t\tfor _, ot := range numberTypes {\n\t\t\t\t\tif ot != t {\n\t\t\t\t\t\tsource += \"\\t\" + repl(\"initialize-body\", ot, t) + \"\\n\"\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\tsource += repl(\"initialize-foot\", \"\", t) + \"\\n\"\n\t}\n\tsource += \"\\n\"\n\n\t\/\/ arithmetic\n\tfor _, op := range []string{\"+\", \"-\", \"*\", \"\/\", \"%\"} {\n\t\tfor _, t := range append(append(signedTypes, unsignedTypes...), floatTypes...) {\n\t\t\tsource += repl(\"arithmetic\", op, t) + \"\\n\"\n\t\t}\n\t}\n\tfor _, op := range []string{\"<<\", \">>\", \"^\", \"&\", \"&+\", \"&-\", \"&*\"} {\n\t\tfor _, t := range append(signedTypes, unsignedTypes...) {\n\t\t\tsource += repl(\"arithmetic\", op, t) + \"\\n\"\n\t\t}\n\t}\n\tfor _, op := range []string{\"+\"} {\n\t\tfor _, t := range stringTypes {\n\t\t\tsource += repl(\"arithmetic\", op, t) + \"\\n\"\n\t\t}\n\t}\n\n\t\/\/ prefix\n\tfor _, op := range []string{\"++\", \"--\"} {\n\t\tfor _, t := range append(append(signedTypes, unsignedTypes...), floatTypes...) {\n\t\t\tsource += repl(\"prefix\", op, t) + \"\\n\"\n\t\t}\n\t}\n\tfor _, op := range []string{\"+\", \"-\"} {\n\t\tfor _, t := range append(signedTypes, floatTypes...) {\n\t\t\tsource += repl(\"prefix\", op, t) + \"\\n\"\n\t\t}\n\t}\n\tfor _, op := range []string{\"~\"} {\n\t\tfor _, t := range signedTypes {\n\t\t\tsource += repl(\"prefix\", op, t) + \"\\n\"\n\t\t}\n\t}\n\n\t\/\/ postfix\n\tfor _, op := range []string{\"++\", \"--\"} {\n\t\tfor _, t := range append(append(signedTypes, unsignedTypes...), floatTypes...) {\n\t\t\tsource += repl(\"postfix\", op, t) + \"\\n\"\n\t\t}\n\t}\n\n\t\/\/ modify\n\tfor _, op := range []string{\"+=\", \"-=\", \"*=\", \"\/=\", \"%=\"} {\n\t\tfor _, t := range append(append(signedTypes, unsignedTypes...), floatTypes...) {\n\t\t\tsource += repl(\"modify\", op, t) + \"\\n\"\n\t\t}\n\t}\n\tfor _, op := range []string{\"+=\"} {\n\t\tfor _, t := range stringTypes {\n\t\t\tsource += repl(\"modify\", op, t) + \"\\n\"\n\t\t}\n\t}\n\tfor _, op := range []string{\"<<=\", \">>=\", \"^=\", \"&=\"} {\n\t\tfor _, t := range append(signedTypes, unsignedTypes...) {\n\t\t\tsource += repl(\"modify\", op, t) + \"\\n\"\n\t\t}\n\t}\n\n\tmatch := false\n\tsourceb := []byte(source)\n\tdestb, err := ioutil.ReadFile(destinationPath)\n\tif err == nil {\n\t\tmatch = bytes.Compare(destb, sourceb) == 0\n\t}\n\tif !match {\n\t\terr = ioutil.WriteFile(destinationPath, sourceb, 0666)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err.Error())\n\t\t}\n\t}\n\n}\n<commit_msg>format change<commit_after>package main\n\nimport (\n\t\"bytes\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"strings\"\n)\n\nconst templatePath = \"atomic-template.swift\"\nconst destinationPath = \"..\/Source\/atomic.swift\"\n\nfunc main() {\n\tb, err := ioutil.ReadFile(templatePath)\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t}\n\n\tboolTypes := []string{\"Bool\"}\n\tstringTypes := []string{\"String\"}\n\tsignedTypes := []string{\"Int\", \"Int64\", \"Int32\", \"Int16\", \"Int8\"}\n\tunsignedTypes := []string{\"UInt\", \"UInt64\", \"UInt32\", \"UInt16\", \"UInt8\"}\n\tfloatTypes := []string{\"Double\", \"Float\"}\n\tnumberTypes := append(append(signedTypes, unsignedTypes...), floatTypes...)\n\tallTypes := append(append(numberTypes, boolTypes...), stringTypes...)\n\n\t\/\/ parse\n\ttemplates := make(map[string]string)\n\ttparts := strings.Split(string(b), \"\/\/ TEMPLATE:\")\n\ttemplates[\"base\"] = strings.TrimSpace(tparts[0])\n\ttparts = tparts[1:]\n\tfor _, tpart := range tparts {\n\t\tvar idx = strings.Index(tpart, \"\\n\")\n\t\tvar title = strings.TrimSpace(tpart[:idx])\n\t\ttemplates[title] = strings.TrimSpace(tpart[idx+1:])\n\t}\n\n\trepl := func(key string, op string, t string) string {\n\t\ts := templates[key]\n\t\ts = strings.Replace(s, \"{{O}}\", op, -1)\n\t\ts = strings.Replace(s, \"{{T}}\", t, -1)\n\n\t\tif op != t+\"A\" {\n\t\t\tfor {\n\t\t\t\tidx := strings.Index(s, \"Atomic<\")\n\t\t\t\tif idx == -1 {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tidxe := strings.Index(s[idx:], \">\") + idx\n\t\t\t\ts = s[:idx] + s[idx+7:idxe] + \"A\" + s[idxe+1:]\n\t\t\t}\n\t\t}\n\t\treturn s\n\t}\n\n\tsource := templates[\"base\"] + \"\\n\\n\"\n\n\t\/\/ typealias\n\tfor _, t := range allTypes {\n\t\tsource += repl(\"typealias\", t+\"A\", t) + \"\\n\"\n\t}\n\tsource += \"\\n\"\n\n\t\/\/ initialize\n\tfor _, t := range allTypes {\n\t\tsource += repl(\"initialize-head\", \"\", t) + \"\\n\"\n\t\tsource += \"\\t\" + repl(\"initialize-body\", t, t) + \"\\n\"\n\t\tfor _, it := range numberTypes {\n\t\t\tif t == it {\n\t\t\t\tfor _, ot := range numberTypes {\n\t\t\t\t\tif ot != t {\n\t\t\t\t\t\tsource += \"\\t\" + repl(\"initialize-body\", ot, t) + \"\\n\"\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\tsource += repl(\"initialize-foot\", \"\", t) + \"\\n\"\n\t}\n\tsource += \"\\n\"\n\n\t\/\/ arithmetic\n\tfor _, op := range []string{\"+\", \"-\", \"*\", \"\/\", \"%\"} {\n\t\tfor _, t := range append(append(signedTypes, unsignedTypes...), floatTypes...) {\n\t\t\tsource += repl(\"arithmetic\", op, t) + \"\\n\"\n\t\t}\n\t}\n\tfor _, op := range []string{\"<<\", \">>\", \"^\", \"&\", \"&+\", \"&-\", \"&*\"} {\n\t\tfor _, t := range append(signedTypes, unsignedTypes...) {\n\t\t\tsource += repl(\"arithmetic\", op, t) + \"\\n\"\n\t\t}\n\t}\n\tfor _, op := range []string{\"+\"} {\n\t\tfor _, t := range stringTypes {\n\t\t\tsource += repl(\"arithmetic\", op, t) + \"\\n\"\n\t\t}\n\t}\n\n\t\/\/ prefix\n\tfor _, op := range []string{\"++\", \"--\"} {\n\t\tfor _, t := range append(append(signedTypes, unsignedTypes...), floatTypes...) {\n\t\t\tsource += repl(\"prefix\", op, t) + \"\\n\"\n\t\t}\n\t}\n\tfor _, op := range []string{\"+\", \"-\"} {\n\t\tfor _, t := range append(signedTypes, floatTypes...) {\n\t\t\tsource += repl(\"prefix\", op, t) + \"\\n\"\n\t\t}\n\t}\n\tfor _, op := range []string{\"~\"} {\n\t\tfor _, t := range signedTypes {\n\t\t\tsource += repl(\"prefix\", op, t) + \"\\n\"\n\t\t}\n\t}\n\n\t\/\/ postfix\n\tfor _, op := range []string{\"++\", \"--\"} {\n\t\tfor _, t := range append(append(signedTypes, unsignedTypes...), floatTypes...) {\n\t\t\tsource += repl(\"postfix\", op, t) + \"\\n\"\n\t\t}\n\t}\n\n\t\/\/ modify\n\tfor _, op := range []string{\"+=\", \"-=\", \"*=\", \"\/=\", \"%=\"} {\n\t\tfor _, t := range append(append(signedTypes, unsignedTypes...), floatTypes...) {\n\t\t\tsource += repl(\"modify\", op, t) + \"\\n\"\n\t\t}\n\t}\n\tfor _, op := range []string{\"+=\"} {\n\t\tfor _, t := range stringTypes {\n\t\t\tsource += repl(\"modify\", op, t) + \"\\n\"\n\t\t}\n\t}\n\tfor _, op := range []string{\"<<=\", \">>=\", \"^=\", \"&=\"} {\n\t\tfor _, t := range append(signedTypes, unsignedTypes...) {\n\t\t\tsource += repl(\"modify\", op, t) + \"\\n\"\n\t\t}\n\t}\n\n\tmatch := false\n\tsourceb := []byte(source)\n\tdestb, err := ioutil.ReadFile(destinationPath)\n\tif err == nil {\n\t\tmatch = bytes.Compare(destb, sourceb) == 0\n\t}\n\tif !match {\n\t\terr = ioutil.WriteFile(destinationPath, sourceb, 0666)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err.Error())\n\t\t}\n\t}\n\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/hex\"\n\t\"flag\"\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/k-sone\/snmpgo\"\n)\n\nvar hexPrefix *regexp.Regexp = regexp.MustCompile(`^0[xX]`)\nvar inform bool\nvar errMessage string\n\nfunc usage(msg string, code int) {\n\terrMessage = msg\n\tflag.Usage()\n\tos.Exit(code)\n}\n\nfunc parseArgs() (*snmpgo.SNMPArguments, []string) {\n\tflag.Usage = func() {\n\t\tif errMessage != \"\" {\n\t\t\tfmt.Fprintf(os.Stderr, \"%s\\n\", errMessage)\n\t\t}\n\t\tfmt.Fprintf(os.Stderr,\n\t\t\t\"Usage of %s: [OPTIONS] AGENT UPTIME TRAP-OID [OID TYPE VALUE]..\\n\\n\", os.Args[0])\n\t\tfmt.Fprintf(os.Stderr, \"AGENT:\\n  hostname:port or ip-address:port\\n\")\n\t\tfmt.Fprintf(os.Stderr, \"UPTIME:\\n  system uptime\\n\")\n\t\tfmt.Fprintf(os.Stderr, \"TYPE:\\n\")\n\t\tfmt.Fprintf(os.Stderr, \"  i - INTEGER   u - UNSIGNED   c - COUNTER32 C - COUNTER64\\n\")\n\t\tfmt.Fprintf(os.Stderr, \"  t - TIMETICKS a - IPADDRESS  o - OID       n - NULL\\n\")\n\t\tfmt.Fprintf(os.Stderr, \"  s - STRING    x - HEX STRING d - DECIMAL STRING\\n\")\n\t\tfmt.Fprintf(os.Stderr, \"OPTIONS:\\n\")\n\t\tflag.PrintDefaults()\n\t}\n\n\tprotocol := flag.String(\"p\", \"udp\", \"Protocol (udp|udp6|tcp|tcp6)\")\n\ttimeout := flag.Uint(\"t\", 5, \"Request timeout (number of seconds)\")\n\tretries := flag.Uint(\"r\", 1, \"Number of retries\")\n\tversion := flag.String(\"v\", \"1\", \"SNMP version to use (1|2c|3)\")\n\tcommunity := flag.String(\"c\", \"\", \"Community\")\n\tusername := flag.String(\"u\", \"\", \"Security name\")\n\tseclevel := flag.String(\"l\", \"NoAuthNoPriv\", \"Security level (NoAuthNoPriv|AuthNoPriv|AuthPriv)\")\n\tauthproto := flag.String(\"a\", \"\", \"Authentication protocol (MD5|SHA)\")\n\tauthpass := flag.String(\"A\", \"\", \"Authentication protocol pass phrase\")\n\tprivproto := flag.String(\"x\", \"\", \"Privacy protocol (DES|AES)\")\n\tprivpass := flag.String(\"X\", \"\", \"Privacy protocol pass phrase\")\n\tsecengine := flag.String(\"e\", \"\", \"Security engine ID\")\n\tcontextengine := flag.String(\"E\", \"\", \"Context engine ID\")\n\tcontextname := flag.String(\"n\", \"\", \"Context name\")\n\tflag.BoolVar(&inform, \"Ci\", false, \"Send an Inform\")\n\n\tflag.Parse()\n\n\targs := &snmpgo.SNMPArguments{\n\t\tNetwork:          *protocol,\n\t\tAddress:          flag.Arg(0),\n\t\tTimeout:          time.Duration(*timeout) * time.Second,\n\t\tRetries:          *retries,\n\t\tCommunity:        *community,\n\t\tUserName:         *username,\n\t\tAuthPassword:     *authpass,\n\t\tAuthProtocol:     snmpgo.AuthProtocol(*authproto),\n\t\tPrivPassword:     *privpass,\n\t\tPrivProtocol:     snmpgo.PrivProtocol(*privproto),\n\t\tSecurityEngineId: *secengine,\n\t\tContextEngineId:  *contextengine,\n\t\tContextName:      *contextname,\n\t}\n\n\tswitch *version {\n\tcase \"1\":\n\t\targs.Version = snmpgo.V1\n\tcase \"2c\":\n\t\targs.Version = snmpgo.V2c\n\tcase \"3\":\n\t\targs.Version = snmpgo.V3\n\tdefault:\n\t\tusage(fmt.Sprintf(\"Illegal Version, value `%s`\", *version), 2)\n\t}\n\n\tswitch *seclevel {\n\tcase \"NoAuthNoPriv\":\n\t\targs.SecurityLevel = snmpgo.NoAuthNoPriv\n\tcase \"AuthNoPriv\":\n\t\targs.SecurityLevel = snmpgo.AuthNoPriv\n\tcase \"AuthPriv\":\n\t\targs.SecurityLevel = snmpgo.AuthPriv\n\tdefault:\n\t\tusage(fmt.Sprintf(\"Illegal SecurityLevel, value `%s`\", *seclevel), 2)\n\t}\n\n\treturn args, flag.Args()\n}\n\nfunc getUptime(s string) uint32 {\n\tif uptime, err := strconv.ParseUint(s, 10, 32); err == nil {\n\t\treturn uint32(uptime)\n\t}\n\n\t\/\/ The syscall.Sysinfo only works on Linux\n\t\/\/\tvar info syscall.Sysinfo_t\n\t\/\/\tif err := syscall.Sysinfo(&info); err == nil {\n\t\/\/\t\treturn uint32(info.Uptime * 100)\n\t\/\/\t}\n\n\treturn 0\n}\n\nfunc buildVariable(kind string, value string) (val snmpgo.Variable, err error) {\n\tswitch kind {\n\tcase \"i\":\n\t\tvar num int64\n\t\tif num, err = strconv.ParseInt(value, 10, 32); err == nil {\n\t\t\tval = snmpgo.NewInteger(int32(num))\n\t\t}\n\tcase \"u\":\n\t\tvar num uint64\n\t\tif num, err = strconv.ParseUint(value, 10, 32); err == nil {\n\t\t\tval = snmpgo.NewGauge32(uint32(num))\n\t\t}\n\tcase \"c\":\n\t\tvar num uint64\n\t\tif num, err = strconv.ParseUint(value, 10, 32); err == nil {\n\t\t\tval = snmpgo.NewCounter32(uint32(num))\n\t\t}\n\tcase \"C\":\n\t\tvar num uint64\n\t\tif num, err = strconv.ParseUint(value, 10, 64); err == nil {\n\t\t\tval = snmpgo.NewCounter64(num)\n\t\t}\n\tcase \"t\":\n\t\tvar num uint64\n\t\tif num, err = strconv.ParseUint(value, 10, 32); err == nil {\n\t\t\tval = snmpgo.NewTimeTicks(uint32(num))\n\t\t}\n\tcase \"a\":\n\t\tif ip := net.ParseIP(value); ip != nil && len(ip) == 4 {\n\t\t\tval = snmpgo.NewIpaddress(ip[0], ip[1], ip[2], ip[3])\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"%s: no valid IP Address\", value)\n\t\t}\n\tcase \"o\":\n\t\tval, err = snmpgo.NewOid(value)\n\tcase \"n\":\n\t\tval = snmpgo.NewNull()\n\tcase \"s\":\n\t\tval = snmpgo.NewOctetString([]byte(value))\n\tcase \"x\":\n\t\tvar b []byte\n\t\thx := hexPrefix.ReplaceAllString(value, \"\")\n\t\tif b, err = hex.DecodeString(hx); err == nil {\n\t\t\tval = snmpgo.NewOctetString(b)\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"%s: no valid Hex String\", value)\n\t\t}\n\tcase \"d\":\n\t\ts := strings.Split(value, \".\")\n\t\tb := make([]byte, len(s))\n\t\tfor i, piece := range s {\n\t\t\tvar num int\n\t\t\tif num, err = strconv.Atoi(piece); err != nil || num > 0xff {\n\t\t\t\treturn nil, fmt.Errorf(\"%s: no valid Decimal String\", value)\n\t\t\t}\n\t\t\tb[i] = byte(num)\n\t\t}\n\t\tval = snmpgo.NewOctetString(b)\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"%s: unknown TYPE\", kind)\n\t}\n\n\treturn\n}\n\nfunc buildVarBinds(cmdArgs []string) (snmpgo.VarBinds, error) {\n\tvar varBinds snmpgo.VarBinds\n\n\tuptime := snmpgo.NewTimeTicks(getUptime(cmdArgs[1]))\n\tvarBinds = append(varBinds, snmpgo.NewVarBind(snmpgo.OidSysUpTime, uptime))\n\n\toid, err := snmpgo.NewOid(cmdArgs[2])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvarBinds = append(varBinds, snmpgo.NewVarBind(snmpgo.OidSnmpTrap, oid))\n\n\tfor i := 3; i < len(cmdArgs); i += 3 {\n\t\toid, err := snmpgo.NewOid(cmdArgs[i])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tval, err := buildVariable(cmdArgs[i+1], cmdArgs[i+2])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvarBinds = append(varBinds, snmpgo.NewVarBind(oid, val))\n\t}\n\n\treturn varBinds, nil\n}\n\nfunc main() {\n\tsnmpArgs, cmdArgs := parseArgs()\n\tif l := len(cmdArgs); l < 3 {\n\t\tusage(\"required AGENT and UPTIME and TRAP-OID\", 2)\n\t} else if l%3 != 0 {\n\t\tusage(fmt.Sprintf(\"%s: missing TYPE\/VALUE for variable\", cmdArgs[l\/3*3]), 2)\n\t}\n\n\tvarBinds, err := buildVarBinds(cmdArgs)\n\tif err != nil {\n\t\tusage(err.Error(), 2)\n\t}\n\n\tsnmp, err := snmpgo.NewSNMP(*snmpArgs)\n\tif err != nil {\n\t\tusage(err.Error(), 2)\n\t}\n\tif err = snmp.Open(); err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n\tdefer snmp.Close()\n\n\tif inform {\n\t\terr = snmp.InformRequest(varBinds)\n\t} else {\n\t\terr = snmp.V2Trap(varBinds)\n\t}\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n}\n<commit_msg>fix selectable snmp version<commit_after>package main\n\nimport (\n\t\"encoding\/hex\"\n\t\"flag\"\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/k-sone\/snmpgo\"\n)\n\nvar hexPrefix *regexp.Regexp = regexp.MustCompile(`^0[xX]`)\nvar inform bool\nvar errMessage string\n\nfunc usage(msg string, code int) {\n\terrMessage = msg\n\tflag.Usage()\n\tos.Exit(code)\n}\n\nfunc parseArgs() (*snmpgo.SNMPArguments, []string) {\n\tflag.Usage = func() {\n\t\tif errMessage != \"\" {\n\t\t\tfmt.Fprintf(os.Stderr, \"%s\\n\", errMessage)\n\t\t}\n\t\tfmt.Fprintf(os.Stderr,\n\t\t\t\"Usage of %s: [OPTIONS] AGENT UPTIME TRAP-OID [OID TYPE VALUE]..\\n\\n\", os.Args[0])\n\t\tfmt.Fprintf(os.Stderr, \"AGENT:\\n  hostname:port or ip-address:port\\n\")\n\t\tfmt.Fprintf(os.Stderr, \"UPTIME:\\n  system uptime\\n\")\n\t\tfmt.Fprintf(os.Stderr, \"TYPE:\\n\")\n\t\tfmt.Fprintf(os.Stderr, \"  i - INTEGER   u - UNSIGNED   c - COUNTER32 C - COUNTER64\\n\")\n\t\tfmt.Fprintf(os.Stderr, \"  t - TIMETICKS a - IPADDRESS  o - OID       n - NULL\\n\")\n\t\tfmt.Fprintf(os.Stderr, \"  s - STRING    x - HEX STRING d - DECIMAL STRING\\n\")\n\t\tfmt.Fprintf(os.Stderr, \"OPTIONS:\\n\")\n\t\tflag.PrintDefaults()\n\t}\n\n\tprotocol := flag.String(\"p\", \"udp\", \"Protocol (udp|udp6|tcp|tcp6)\")\n\ttimeout := flag.Uint(\"t\", 5, \"Request timeout (number of seconds)\")\n\tretries := flag.Uint(\"r\", 1, \"Number of retries\")\n\tversion := flag.String(\"v\", \"2c\", \"SNMP version to use (2c|3)\")\n\tcommunity := flag.String(\"c\", \"\", \"Community\")\n\tusername := flag.String(\"u\", \"\", \"Security name\")\n\tseclevel := flag.String(\"l\", \"NoAuthNoPriv\", \"Security level (NoAuthNoPriv|AuthNoPriv|AuthPriv)\")\n\tauthproto := flag.String(\"a\", \"\", \"Authentication protocol (MD5|SHA)\")\n\tauthpass := flag.String(\"A\", \"\", \"Authentication protocol pass phrase\")\n\tprivproto := flag.String(\"x\", \"\", \"Privacy protocol (DES|AES)\")\n\tprivpass := flag.String(\"X\", \"\", \"Privacy protocol pass phrase\")\n\tsecengine := flag.String(\"e\", \"\", \"Security engine ID\")\n\tcontextengine := flag.String(\"E\", \"\", \"Context engine ID\")\n\tcontextname := flag.String(\"n\", \"\", \"Context name\")\n\tflag.BoolVar(&inform, \"Ci\", false, \"Send an Inform\")\n\n\tflag.Parse()\n\n\targs := &snmpgo.SNMPArguments{\n\t\tNetwork:          *protocol,\n\t\tAddress:          flag.Arg(0),\n\t\tTimeout:          time.Duration(*timeout) * time.Second,\n\t\tRetries:          *retries,\n\t\tCommunity:        *community,\n\t\tUserName:         *username,\n\t\tAuthPassword:     *authpass,\n\t\tAuthProtocol:     snmpgo.AuthProtocol(*authproto),\n\t\tPrivPassword:     *privpass,\n\t\tPrivProtocol:     snmpgo.PrivProtocol(*privproto),\n\t\tSecurityEngineId: *secengine,\n\t\tContextEngineId:  *contextengine,\n\t\tContextName:      *contextname,\n\t}\n\n\tswitch *version {\n\tcase \"2c\":\n\t\targs.Version = snmpgo.V2c\n\tcase \"3\":\n\t\targs.Version = snmpgo.V3\n\tdefault:\n\t\tusage(fmt.Sprintf(\"Illegal Version, value `%s`\", *version), 2)\n\t}\n\n\tswitch *seclevel {\n\tcase \"NoAuthNoPriv\":\n\t\targs.SecurityLevel = snmpgo.NoAuthNoPriv\n\tcase \"AuthNoPriv\":\n\t\targs.SecurityLevel = snmpgo.AuthNoPriv\n\tcase \"AuthPriv\":\n\t\targs.SecurityLevel = snmpgo.AuthPriv\n\tdefault:\n\t\tusage(fmt.Sprintf(\"Illegal SecurityLevel, value `%s`\", *seclevel), 2)\n\t}\n\n\treturn args, flag.Args()\n}\n\nfunc getUptime(s string) uint32 {\n\tif uptime, err := strconv.ParseUint(s, 10, 32); err == nil {\n\t\treturn uint32(uptime)\n\t}\n\n\t\/\/ The syscall.Sysinfo only works on Linux\n\t\/\/\tvar info syscall.Sysinfo_t\n\t\/\/\tif err := syscall.Sysinfo(&info); err == nil {\n\t\/\/\t\treturn uint32(info.Uptime * 100)\n\t\/\/\t}\n\n\treturn 0\n}\n\nfunc buildVariable(kind string, value string) (val snmpgo.Variable, err error) {\n\tswitch kind {\n\tcase \"i\":\n\t\tvar num int64\n\t\tif num, err = strconv.ParseInt(value, 10, 32); err == nil {\n\t\t\tval = snmpgo.NewInteger(int32(num))\n\t\t}\n\tcase \"u\":\n\t\tvar num uint64\n\t\tif num, err = strconv.ParseUint(value, 10, 32); err == nil {\n\t\t\tval = snmpgo.NewGauge32(uint32(num))\n\t\t}\n\tcase \"c\":\n\t\tvar num uint64\n\t\tif num, err = strconv.ParseUint(value, 10, 32); err == nil {\n\t\t\tval = snmpgo.NewCounter32(uint32(num))\n\t\t}\n\tcase \"C\":\n\t\tvar num uint64\n\t\tif num, err = strconv.ParseUint(value, 10, 64); err == nil {\n\t\t\tval = snmpgo.NewCounter64(num)\n\t\t}\n\tcase \"t\":\n\t\tvar num uint64\n\t\tif num, err = strconv.ParseUint(value, 10, 32); err == nil {\n\t\t\tval = snmpgo.NewTimeTicks(uint32(num))\n\t\t}\n\tcase \"a\":\n\t\tif ip := net.ParseIP(value); ip != nil && len(ip) == 4 {\n\t\t\tval = snmpgo.NewIpaddress(ip[0], ip[1], ip[2], ip[3])\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"%s: no valid IP Address\", value)\n\t\t}\n\tcase \"o\":\n\t\tval, err = snmpgo.NewOid(value)\n\tcase \"n\":\n\t\tval = snmpgo.NewNull()\n\tcase \"s\":\n\t\tval = snmpgo.NewOctetString([]byte(value))\n\tcase \"x\":\n\t\tvar b []byte\n\t\thx := hexPrefix.ReplaceAllString(value, \"\")\n\t\tif b, err = hex.DecodeString(hx); err == nil {\n\t\t\tval = snmpgo.NewOctetString(b)\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"%s: no valid Hex String\", value)\n\t\t}\n\tcase \"d\":\n\t\ts := strings.Split(value, \".\")\n\t\tb := make([]byte, len(s))\n\t\tfor i, piece := range s {\n\t\t\tvar num int\n\t\t\tif num, err = strconv.Atoi(piece); err != nil || num > 0xff {\n\t\t\t\treturn nil, fmt.Errorf(\"%s: no valid Decimal String\", value)\n\t\t\t}\n\t\t\tb[i] = byte(num)\n\t\t}\n\t\tval = snmpgo.NewOctetString(b)\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"%s: unknown TYPE\", kind)\n\t}\n\n\treturn\n}\n\nfunc buildVarBinds(cmdArgs []string) (snmpgo.VarBinds, error) {\n\tvar varBinds snmpgo.VarBinds\n\n\tuptime := snmpgo.NewTimeTicks(getUptime(cmdArgs[1]))\n\tvarBinds = append(varBinds, snmpgo.NewVarBind(snmpgo.OidSysUpTime, uptime))\n\n\toid, err := snmpgo.NewOid(cmdArgs[2])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvarBinds = append(varBinds, snmpgo.NewVarBind(snmpgo.OidSnmpTrap, oid))\n\n\tfor i := 3; i < len(cmdArgs); i += 3 {\n\t\toid, err := snmpgo.NewOid(cmdArgs[i])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tval, err := buildVariable(cmdArgs[i+1], cmdArgs[i+2])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvarBinds = append(varBinds, snmpgo.NewVarBind(oid, val))\n\t}\n\n\treturn varBinds, nil\n}\n\nfunc main() {\n\tsnmpArgs, cmdArgs := parseArgs()\n\tif l := len(cmdArgs); l < 3 {\n\t\tusage(\"required AGENT and UPTIME and TRAP-OID\", 2)\n\t} else if l%3 != 0 {\n\t\tusage(fmt.Sprintf(\"%s: missing TYPE\/VALUE for variable\", cmdArgs[l\/3*3]), 2)\n\t}\n\n\tvarBinds, err := buildVarBinds(cmdArgs)\n\tif err != nil {\n\t\tusage(err.Error(), 2)\n\t}\n\n\tsnmp, err := snmpgo.NewSNMP(*snmpArgs)\n\tif err != nil {\n\t\tusage(err.Error(), 2)\n\t}\n\tif err = snmp.Open(); err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n\tdefer snmp.Close()\n\n\tif inform {\n\t\terr = snmp.InformRequest(varBinds)\n\t} else {\n\t\terr = snmp.V2Trap(varBinds)\n\t}\n\tif err != nil {\n\t\tfmt.Fprintln(os.Stderr, err)\n\t\tos.Exit(1)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package cdsclient\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"context\"\n\t\"encoding\/base64\"\n\t\"io\"\n\t\"net\/http\"\n\t\"strings\"\n)\n\nconst (\n\tsseEvent = \"event\"\n\tsseData  = \"data\"\n)\n\n\/\/SSEvent is a go representation of an http server-sent event\ntype SSEvent struct {\n\tURI  string\n\tType string\n\tData io.Reader\n}\n\n\/\/ RequestSSEGet takes the uri of an SSE stream and channel, and will send an Event\n\/\/ down the channel when received, until the stream is closed. It will then\n\/\/ close the stream. This is blocking, and so you will likely want to call this\n\/\/ in a new goroutine (via `go c.RequestSSEGet(..)`)\nfunc (c *client) RequestSSEGet(ctx context.Context, path string, evCh chan<- SSEvent, mods ...RequestModifier) error {\n\turi := c.config.Host + path\n\tif strings.HasPrefix(path, \"http\") {\n\t\turi = path\n\t}\n\n\treq, err := http.NewRequest(http.MethodGet, uri, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor i := range mods {\n\t\tif mods[i] != nil {\n\t\t\tmods[i](req)\n\t\t}\n\t}\n\n\treq.Header.Set(\"Accept\", \"text\/event-stream\")\n\treq.Header.Set(\"User-Agent\", c.config.userAgent)\n\treq.Header.Set(\"Connection\", \"close\")\n\treq.Header.Add(RequestedWithHeader, RequestedWithValue)\n\tif c.name != \"\" {\n\t\treq.Header.Add(RequestedNameHeader, c.name)\n\t}\n\tif c.isProvider {\n\t\treq.Header.Add(\"X-Provider-Name\", c.config.User)\n\t\treq.Header.Add(\"X-Provider-Token\", c.config.Token)\n\t}\n\n\tif c.config.Hash != \"\" {\n\t\tbasedHash := base64.StdEncoding.EncodeToString([]byte(c.config.Hash))\n\t\treq.Header.Set(AuthHeader, basedHash)\n\t}\n\tif c.config.User != \"\" && c.config.Token != \"\" {\n\t\treq.Header.Add(SessionTokenHeader, c.config.Token)\n\t\treq.SetBasicAuth(c.config.User, c.config.Token)\n\t}\n\n\tresp, err := NoTimeout(c.HTTPClient).Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbr := bufio.NewReader(resp.Body)\n\tdefer resp.Body.Close() \/\/ nolint\n\n\tdelim := []byte{':', ' '}\n\n\tvar currEvent *SSEvent\n\tvar EOF bool\n\n\tfor !EOF {\n\t\tif ctx.Err() != nil {\n\t\t\tbreak\n\t\t}\n\n\t\tbs, err := br.ReadBytes('\\n')\n\n\t\tif err != nil && err != io.EOF {\n\t\t\treturn err\n\t\t}\n\n\t\tif len(bs) < 2 {\n\t\t\tcontinue\n\t\t}\n\n\t\tspl := bytes.Split(bs, delim)\n\n\t\tif len(spl) < 2 {\n\t\t\tcontinue\n\t\t}\n\n\t\tcurrEvent = &SSEvent{URI: uri}\n\t\tswitch string(spl[0]) {\n\t\tcase sseEvent:\n\t\t\tcurrEvent.Type = string(bytes.TrimSpace(spl[1]))\n\t\tcase sseData:\n\t\t\tcurrEvent.Data = bytes.NewBuffer(bytes.TrimSpace(spl[1]))\n\t\t\tevCh <- *currEvent\n\t\t}\n\t\tif err == io.EOF {\n\t\t\tEOF = true\n\t\t}\n\t}\n\n\treturn nil\n\n}\n<commit_msg>fix(sdk): no more ctx.Err() in queue polling (#3425)<commit_after>package cdsclient\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"context\"\n\t\"encoding\/base64\"\n\t\"io\"\n\t\"net\/http\"\n\t\"strings\"\n)\n\nconst (\n\tsseEvent = \"event\"\n\tsseData  = \"data\"\n)\n\n\/\/SSEvent is a go representation of an http server-sent event\ntype SSEvent struct {\n\tURI  string\n\tType string\n\tData io.Reader\n}\n\n\/\/ RequestSSEGet takes the uri of an SSE stream and channel, and will send an Event\n\/\/ down the channel when received, until the stream is closed. It will then\n\/\/ close the stream. This is blocking, and so you will likely want to call this\n\/\/ in a new goroutine (via `go c.RequestSSEGet(..)`)\nfunc (c *client) RequestSSEGet(ctx context.Context, path string, evCh chan<- SSEvent, mods ...RequestModifier) error {\n\turi := c.config.Host + path\n\tif strings.HasPrefix(path, \"http\") {\n\t\turi = path\n\t}\n\n\treq, err := http.NewRequest(http.MethodGet, uri, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor i := range mods {\n\t\tif mods[i] != nil {\n\t\t\tmods[i](req)\n\t\t}\n\t}\n\n\treq.Header.Set(\"Accept\", \"text\/event-stream\")\n\treq.Header.Set(\"User-Agent\", c.config.userAgent)\n\treq.Header.Set(\"Connection\", \"close\")\n\treq.Header.Add(RequestedWithHeader, RequestedWithValue)\n\tif c.name != \"\" {\n\t\treq.Header.Add(RequestedNameHeader, c.name)\n\t}\n\tif c.isProvider {\n\t\treq.Header.Add(\"X-Provider-Name\", c.config.User)\n\t\treq.Header.Add(\"X-Provider-Token\", c.config.Token)\n\t}\n\n\tif c.config.Hash != \"\" {\n\t\tbasedHash := base64.StdEncoding.EncodeToString([]byte(c.config.Hash))\n\t\treq.Header.Set(AuthHeader, basedHash)\n\t}\n\tif c.config.User != \"\" && c.config.Token != \"\" {\n\t\treq.Header.Add(SessionTokenHeader, c.config.Token)\n\t\treq.SetBasicAuth(c.config.User, c.config.Token)\n\t}\n\n\tresp, err := NoTimeout(c.HTTPClient).Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbr := bufio.NewReader(resp.Body)\n\tdefer resp.Body.Close() \/\/ nolint\n\n\tdelim := []byte{':', ' '}\n\n\tvar currEvent *SSEvent\n\tvar EOF bool\n\n\tgo func(stop *bool) {\n\t\t<-ctx.Done()\n\t\t*stop = true\n\t}(&EOF)\n\n\tfor !EOF {\n\t\tbs, err := br.ReadBytes('\\n')\n\t\tif err != nil && err != io.EOF {\n\t\t\treturn err\n\t\t}\n\n\t\tif len(bs) < 2 {\n\t\t\tcontinue\n\t\t}\n\n\t\tspl := bytes.Split(bs, delim)\n\n\t\tif len(spl) < 2 {\n\t\t\tcontinue\n\t\t}\n\n\t\tcurrEvent = &SSEvent{URI: uri}\n\t\tswitch string(spl[0]) {\n\t\tcase sseEvent:\n\t\t\tcurrEvent.Type = string(bytes.TrimSpace(spl[1]))\n\t\tcase sseData:\n\t\t\tcurrEvent.Data = bytes.NewBuffer(bytes.TrimSpace(spl[1]))\n\t\t\tevCh <- *currEvent\n\t\t}\n\t\tif err == io.EOF {\n\t\t\tEOF = true\n\t\t}\n\t}\n\n\treturn nil\n\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n * ZGrab Copyright 2015 Regents of the University of Michigan\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy\n * of the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n * implied. See the License for the specific language governing\n * permissions and limitations under the License.\n *\/\n\npackage processing\n\nimport (\n\t\"io\"\n\t\"sync\"\n)\n\ntype Decoder interface {\n\tDecodeNext() (interface{}, error)\n}\n\ntype Marshaler interface {\n\tMarshal(interface{}) ([]byte, error)\n}\n\ntype Worker interface {\n\tMakeHandler(uint) Handler\n\tSuccess() uint\n\tFailure() uint\n\tTotal() uint\n\tDone()\n\tRunCount() uint\n}\n\ntype Handler func(interface{}) interface{}\n\nfunc Process(in Decoder, out io.Writer, w Worker, m Marshaler, workers uint) {\n\tprocessQueue := make(chan interface{}, workers*4)\n\toutputQueue := make(chan []byte, workers*4)\n\n\t\/\/ Create wait groups\n\tvar workerDone sync.WaitGroup\n\tvar outputDone sync.WaitGroup\n\tworkerDone.Add(int(workers))\n\toutputDone.Add(1)\n\n\t\/\/ Start the output encoder\n\tgo func() {\n\t\tfor result := range outputQueue {\n\t\t\tif _, err := out.Write(result); err != nil {\n\t\t\t\tpanic(err.Error())\n\t\t\t}\n\t\t\tif _, err := out.Write([]byte(\"\\n\")); err != nil {\n\t\t\t\tpanic(err.Error())\n\t\t\t}\n\t\t}\n\t\toutputDone.Done()\n\t}()\n\t\/\/ Start all the workers\n\tfor i := uint(0); i < workers; i++ {\n\t\thandler := w.MakeHandler(i)\n\t\trunCount := w.RunCount()\n\t\tgo func(handler Handler) {\n\t\t\tfor obj := range processQueue {\n\t\t\t\tfor run := uint(0); run < runCount; run++ {\n\t\t\t\t\tresult := handler(obj)\n\t\t\t\t\tenc, err := m.Marshal(result)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tpanic(err.Error())\n\t\t\t\t\t}\n\t\t\t\t\toutputQueue <- enc\n\t\t\t\t}\n\t\t\t}\n\t\t\tworkerDone.Done()\n\t\t}(handler)\n\t}\n\t\/\/ Read the input, send to workers\n\tfor {\n\t\tobj, err := in.DecodeNext()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tprocessQueue <- obj\n\t}\n\tclose(processQueue)\n\tworkerDone.Wait()\n\tclose(outputQueue)\n\toutputDone.Wait()\n\tw.Done()\n}\n<commit_msg>log decoding errors (previously being swallowed)<commit_after>\/*\n * ZGrab Copyright 2015 Regents of the University of Michigan\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy\n * of the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n * implied. See the License for the specific language governing\n * permissions and limitations under the License.\n *\/\n\npackage processing\n\nimport (\n\t\"github.com\/zmap\/zgrab\/ztools\/zlog\"\n\t\"io\"\n\t\"sync\"\n)\n\ntype Decoder interface {\n\tDecodeNext() (interface{}, error)\n}\n\ntype Marshaler interface {\n\tMarshal(interface{}) ([]byte, error)\n}\n\ntype Worker interface {\n\tMakeHandler(uint) Handler\n\tSuccess() uint\n\tFailure() uint\n\tTotal() uint\n\tDone()\n\tRunCount() uint\n}\n\ntype Handler func(interface{}) interface{}\n\nfunc Process(in Decoder, out io.Writer, w Worker, m Marshaler, workers uint) {\n\tprocessQueue := make(chan interface{}, workers*4)\n\toutputQueue := make(chan []byte, workers*4)\n\n\t\/\/ Create wait groups\n\tvar workerDone sync.WaitGroup\n\tvar outputDone sync.WaitGroup\n\tworkerDone.Add(int(workers))\n\toutputDone.Add(1)\n\n\t\/\/ Start the output encoder\n\tgo func() {\n\t\tfor result := range outputQueue {\n\t\t\tif _, err := out.Write(result); err != nil {\n\t\t\t\tpanic(err.Error())\n\t\t\t}\n\t\t\tif _, err := out.Write([]byte(\"\\n\")); err != nil {\n\t\t\t\tpanic(err.Error())\n\t\t\t}\n\t\t}\n\t\toutputDone.Done()\n\t}()\n\t\/\/ Start all the workers\n\tfor i := uint(0); i < workers; i++ {\n\t\thandler := w.MakeHandler(i)\n\t\trunCount := w.RunCount()\n\t\tgo func(handler Handler) {\n\t\t\tfor obj := range processQueue {\n\t\t\t\tfor run := uint(0); run < runCount; run++ {\n\t\t\t\t\tresult := handler(obj)\n\t\t\t\t\tenc, err := m.Marshal(result)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tpanic(err.Error())\n\t\t\t\t\t}\n\t\t\t\t\toutputQueue <- enc\n\t\t\t\t}\n\t\t\t}\n\t\t\tworkerDone.Done()\n\t\t}(handler)\n\t}\n\t\/\/ Read the input, send to workers\n\tfor {\n\t\tobj, err := in.DecodeNext()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\tzlog.Error(err)\n\t\t}\n\t\tprocessQueue <- obj\n\t}\n\tclose(processQueue)\n\tworkerDone.Wait()\n\tclose(outputQueue)\n\toutputDone.Wait()\n\tw.Done()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2017 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ report is a demo application that displays information about an\n\/\/ OpenAPI description.\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\n\t\"github.com\/golang\/protobuf\/proto\"\n\t\"github.com\/googleapis\/gnostic\/printer\"\n\n\tpb \"github.com\/googleapis\/gnostic\/OpenAPIv2\"\n)\n\nfunc readDocumentFromFileWithName(filename string) *pb.Document {\n\tdata, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\tfmt.Printf(\"File error: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\tdocument := &pb.Document{}\n\terr = proto.Unmarshal(data, document)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn document\n}\n\nfunc printDocument(code *printer.Code, document *pb.Document) {\n\tcode.Print(\"BasePath: %+v\", document.BasePath)\n\tcode.Print(\"Consumes: %+v\", document.Consumes)\n\tcode.Print(\"Definitions:\")\n\tcode.Indent()\n\tif document.Definitions != nil && document.Definitions.AdditionalProperties != nil {\n\t\tfor _, pair := range document.Definitions.AdditionalProperties {\n\t\t\tcode.Print(\"%s\", pair.Name)\n\t\t\tcode.Indent()\n\t\t\tprintSchema(code, pair.Value)\n\t\t\tcode.Outdent()\n\t\t}\n\t}\n\tcode.Outdent()\n\tcode.Print(\"ExternalDocs: %+v\", document.ExternalDocs)\n\tcode.Print(\"Host: %+v\", document.Host)\n\tif document.Info != nil {\n\t\tcode.Print(\"Info:\")\n\t\tcode.Indent()\n\t\tcode.Print(\"Title: %s\", document.Info.Title)\n\t\tcode.Print(\"Description: %s\", document.Info.Description)\n\t\tcode.Print(\"Version: %s\", document.Info.Version)\n\t\tcode.Print(\"TermsOfService: %s\", document.Info.TermsOfService)\n\t\tif document.Info.Contact != nil {\n\t\t\tcode.Print(\"Contact Email: %s\", document.Info.Contact.Email)\n\t\t}\n\t\tif document.Info.License != nil {\n\t\t\tcode.Print(\"License Name: %s\", document.Info.License.Name)\n\t\t\tcode.Print(\"License URL: %s\", document.Info.License.Url)\n\t\t}\n\t\tcode.Outdent()\n\t}\n\tcode.Print(\"Parameters: %+v\", document.Parameters)\n\tcode.Print(\"Paths:\")\n\tcode.Indent()\n\tfor _, pair := range document.Paths.Path {\n\t\tcode.Print(\"%+v\", pair.Name)\n\t\tcode.Indent()\n\t\tv := pair.Value\n\t\tif v.Get != nil {\n\t\t\tcode.Print(\"GET\")\n\t\t\tcode.Indent()\n\t\t\tprintOperation(code, v.Get)\n\t\t\tcode.Outdent()\n\t\t}\n\t\tif v.Post != nil {\n\t\t\tcode.Print(\"POST\")\n\t\t\tcode.Indent()\n\t\t\tprintOperation(code, v.Post)\n\t\t\tcode.Outdent()\n\t\t}\n\t\tcode.Outdent()\n\t}\n\tcode.Outdent()\n\tcode.Print(\"Produces: %+v\", document.Produces)\n\tcode.Print(\"Responses: %+v\", document.Responses)\n\tcode.Print(\"Schemes: %+v\", document.Schemes)\n\tcode.Print(\"Security: %+v\", document.Security)\n\tif document.SecurityDefinitions != nil {\n\t\tcode.Print(\"SecurityDefinitions:\")\n\t\tcode.Indent()\n\t\tfor _, pair := range document.SecurityDefinitions.AdditionalProperties {\n\t\t\tcode.Print(\"%s\", pair.Name)\n\t\t\tcode.Indent()\n\t\t\tv := pair.Value\n\t\t\tswitch t := v.Oneof.(type) {\n\t\t\tdefault:\n\t\t\t\tcode.Print(\"unexpected type %T\", t) \/\/ %T prints whatever type t has\n\t\t\tcase *pb.SecurityDefinitionsItem_ApiKeySecurity:\n\t\t\t\tcode.Print(\"ApiKeySecurity: %+v\", t)\n\t\t\tcase *pb.SecurityDefinitionsItem_BasicAuthenticationSecurity:\n\t\t\t\tcode.Print(\"BasicAuthenticationSecurity: %+v\", t)\n\t\t\tcase *pb.SecurityDefinitionsItem_Oauth2AccessCodeSecurity:\n\t\t\t\tcode.Print(\"Oauth2AccessCodeSecurity: %+v\", t)\n\t\t\tcase *pb.SecurityDefinitionsItem_Oauth2ApplicationSecurity:\n\t\t\t\tcode.Print(\"Oauth2ApplicationSecurity: %+v\", t)\n\t\t\tcase *pb.SecurityDefinitionsItem_Oauth2ImplicitSecurity:\n\t\t\t\tcode.Print(\"Oauth2ImplicitSecurity\")\n\t\t\t\tcode.Indent()\n\t\t\t\tcode.Print(\"AuthorizationUrl: %+v\", t.Oauth2ImplicitSecurity.AuthorizationUrl)\n\t\t\t\tcode.Print(\"Flow: %+v\", t.Oauth2ImplicitSecurity.Flow)\n\t\t\t\tcode.Print(\"Scopes:\")\n\t\t\t\tcode.Indent()\n\t\t\t\tfor _, pair := range t.Oauth2ImplicitSecurity.Scopes.AdditionalProperties {\n\t\t\t\t\tcode.Print(\"%s -> %s\", pair.Name, pair.Value)\n\t\t\t\t}\n\t\t\t\tcode.Outdent()\n\t\t\t\tcode.Outdent()\n\t\t\tcase *pb.SecurityDefinitionsItem_Oauth2PasswordSecurity:\n\t\t\t\tcode.Print(\"Oauth2PasswordSecurity: %+v\", t)\n\t\t\t}\n\t\t\tcode.Outdent()\n\t\t}\n\t\tcode.Outdent()\n\t}\n\tcode.Print(\"Swagger: %+v\", document.Swagger)\n\tcode.Print(\"Tags:\")\n\tcode.Indent()\n\tfor _, tag := range document.Tags {\n\t\tcode.Print(\"Tag:\")\n\t\tcode.Indent()\n\t\tcode.Print(\"Name: %s\", tag.Name)\n\t\tcode.Print(\"Description: %s\", tag.Description)\n\t\tcode.Print(\"ExternalDocs: %s\", tag.ExternalDocs)\n\t\tprintVendorExtension(code, tag.VendorExtension)\n\t\tcode.Outdent()\n\t}\n\tcode.Outdent()\n}\n\nfunc printOperation(code *printer.Code, operation *pb.Operation) {\n\tcode.Print(\"Consumes: %+v\", operation.Consumes)\n\tcode.Print(\"Deprecated: %+v\", operation.Deprecated)\n\tcode.Print(\"Description: %+v\", operation.Description)\n\tcode.Print(\"ExternalDocs: %+v\", operation.ExternalDocs)\n\tcode.Print(\"OperationId: %+v\", operation.OperationId)\n\tcode.Print(\"Parameters:\")\n\tcode.Indent()\n\tfor _, item := range operation.Parameters {\n\t\tswitch t := item.Oneof.(type) {\n\t\tdefault:\n\t\t\tcode.Print(\"unexpected type %T\", t) \/\/ %T prints whatever type t has\n\t\tcase *pb.ParametersItem_JsonReference:\n\t\t\tcode.Print(\"JsonReference: %+v\", t)\n\t\tcase *pb.ParametersItem_Parameter:\n\t\t\tcode.Print(\"Parameter: %+v\", t)\n\t\t}\n\t}\n\tcode.Outdent()\n\tcode.Print(\"Produces: %+v\", operation.Produces)\n\tcode.Print(\"Responses:\")\n\tcode.Indent()\n\tcode.Print(\"ResponseCode:\")\n\tcode.Indent()\n\tfor _, pair := range operation.Responses.ResponseCode {\n\t\tcode.Print(\"%s %s\", pair.Name, pair.Value)\n\t}\n\tcode.Outdent()\n\tprintVendorExtension(code, operation.Responses.VendorExtension)\n\tcode.Outdent()\n\tcode.Print(\"Schemes: %+v\", operation.Schemes)\n\tcode.Print(\"Security: %+v\", operation.Security)\n\tcode.Print(\"Summary: %+v\", operation.Summary)\n\tcode.Print(\"Tags: %+v\", operation.Tags)\n\tprintVendorExtension(code, operation.VendorExtension)\n}\n\nfunc printSchema(code *printer.Code, schema *pb.Schema) {\n\t\/\/code.Print(\"%+v\", schema)\n\tif schema.Format != \"\" {\n\t\tcode.Print(\"Format: %+v\", schema.Format)\n\t}\n\tif schema.Properties != nil {\n\t\tcode.Print(\"Properties\")\n\t\tcode.Indent()\n\t\tfor _, pair := range schema.Properties.AdditionalProperties {\n\t\t\tcode.Print(\"%s\", pair.Name)\n\t\t\tcode.Indent()\n\t\t\tprintSchema(code, pair.Value)\n\t\t\tcode.Outdent()\n\t\t}\n\t\tcode.Outdent()\n\t}\n\tif schema.Type != nil {\n\t\tcode.Print(\"Type: %+v\", schema.Type)\n\t}\n\tif schema.Xml != nil {\n\t\tcode.Print(\"Xml: %+v\", schema.Xml)\n\t}\n\tprintVendorExtension(code, schema.VendorExtension)\n}\n\nfunc printVendorExtension(code *printer.Code, vendorExtension []*pb.NamedAny) {\n\tif len(vendorExtension) > 0 {\n\t\tcode.Print(\"VendorExtension: %+v\", vendorExtension)\n\t}\n}\n\nfunc main() {\n\tflag.Parse()\n\targs := flag.Args()\n\n\tif len(args) != 1 {\n\t\tfmt.Printf(\"Usage: report <file.pb>\\n\")\n\t\treturn\n\t}\n\n\tdocument := readDocumentFromFileWithName(args[0])\n\n\tcode := &printer.Code{}\n\tcode.Print(\"API REPORT\")\n\tcode.Print(\"----------\")\n\tprintDocument(code, document)\n\tfmt.Printf(\"%s\", code)\n}\n<commit_msg>Update apps\/report sample to report better errors for non-OpenAPIv2 input.<commit_after>\/\/ Copyright 2017 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ report is a demo application that displays information about an\n\/\/ OpenAPI description.\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com\/golang\/protobuf\/proto\"\n\t\"github.com\/googleapis\/gnostic\/printer\"\n\n\tpb \"github.com\/googleapis\/gnostic\/OpenAPIv2\"\n)\n\nfunc readDocumentFromFileWithName(filename string) (*pb.Document, error) {\n\tdata, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdocument := &pb.Document{}\n\terr = proto.Unmarshal(data, document)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn document, nil\n}\n\nfunc printDocument(code *printer.Code, document *pb.Document) {\n\tcode.Print(\"BasePath: %+v\", document.BasePath)\n\tcode.Print(\"Consumes: %+v\", document.Consumes)\n\tcode.Print(\"Definitions:\")\n\tcode.Indent()\n\tif document.Definitions != nil && document.Definitions.AdditionalProperties != nil {\n\t\tfor _, pair := range document.Definitions.AdditionalProperties {\n\t\t\tcode.Print(\"%s\", pair.Name)\n\t\t\tcode.Indent()\n\t\t\tprintSchema(code, pair.Value)\n\t\t\tcode.Outdent()\n\t\t}\n\t}\n\tcode.Outdent()\n\tcode.Print(\"ExternalDocs: %+v\", document.ExternalDocs)\n\tcode.Print(\"Host: %+v\", document.Host)\n\tif document.Info != nil {\n\t\tcode.Print(\"Info:\")\n\t\tcode.Indent()\n\t\tcode.Print(\"Title: %s\", document.Info.Title)\n\t\tcode.Print(\"Description: %s\", document.Info.Description)\n\t\tcode.Print(\"Version: %s\", document.Info.Version)\n\t\tcode.Print(\"TermsOfService: %s\", document.Info.TermsOfService)\n\t\tif document.Info.Contact != nil {\n\t\t\tcode.Print(\"Contact Email: %s\", document.Info.Contact.Email)\n\t\t}\n\t\tif document.Info.License != nil {\n\t\t\tcode.Print(\"License Name: %s\", document.Info.License.Name)\n\t\t\tcode.Print(\"License URL: %s\", document.Info.License.Url)\n\t\t}\n\t\tcode.Outdent()\n\t}\n\tcode.Print(\"Parameters: %+v\", document.Parameters)\n\tcode.Print(\"Paths:\")\n\tcode.Indent()\n\tfor _, pair := range document.Paths.Path {\n\t\tcode.Print(\"%+v\", pair.Name)\n\t\tcode.Indent()\n\t\tv := pair.Value\n\t\tif v.Get != nil {\n\t\t\tcode.Print(\"GET\")\n\t\t\tcode.Indent()\n\t\t\tprintOperation(code, v.Get)\n\t\t\tcode.Outdent()\n\t\t}\n\t\tif v.Post != nil {\n\t\t\tcode.Print(\"POST\")\n\t\t\tcode.Indent()\n\t\t\tprintOperation(code, v.Post)\n\t\t\tcode.Outdent()\n\t\t}\n\t\tcode.Outdent()\n\t}\n\tcode.Outdent()\n\tcode.Print(\"Produces: %+v\", document.Produces)\n\tcode.Print(\"Responses: %+v\", document.Responses)\n\tcode.Print(\"Schemes: %+v\", document.Schemes)\n\tcode.Print(\"Security: %+v\", document.Security)\n\tif document.SecurityDefinitions != nil {\n\t\tcode.Print(\"SecurityDefinitions:\")\n\t\tcode.Indent()\n\t\tfor _, pair := range document.SecurityDefinitions.AdditionalProperties {\n\t\t\tcode.Print(\"%s\", pair.Name)\n\t\t\tcode.Indent()\n\t\t\tv := pair.Value\n\t\t\tswitch t := v.Oneof.(type) {\n\t\t\tdefault:\n\t\t\t\tcode.Print(\"unexpected type %T\", t) \/\/ %T prints whatever type t has\n\t\t\tcase *pb.SecurityDefinitionsItem_ApiKeySecurity:\n\t\t\t\tcode.Print(\"ApiKeySecurity: %+v\", t)\n\t\t\tcase *pb.SecurityDefinitionsItem_BasicAuthenticationSecurity:\n\t\t\t\tcode.Print(\"BasicAuthenticationSecurity: %+v\", t)\n\t\t\tcase *pb.SecurityDefinitionsItem_Oauth2AccessCodeSecurity:\n\t\t\t\tcode.Print(\"Oauth2AccessCodeSecurity: %+v\", t)\n\t\t\tcase *pb.SecurityDefinitionsItem_Oauth2ApplicationSecurity:\n\t\t\t\tcode.Print(\"Oauth2ApplicationSecurity: %+v\", t)\n\t\t\tcase *pb.SecurityDefinitionsItem_Oauth2ImplicitSecurity:\n\t\t\t\tcode.Print(\"Oauth2ImplicitSecurity\")\n\t\t\t\tcode.Indent()\n\t\t\t\tcode.Print(\"AuthorizationUrl: %+v\", t.Oauth2ImplicitSecurity.AuthorizationUrl)\n\t\t\t\tcode.Print(\"Flow: %+v\", t.Oauth2ImplicitSecurity.Flow)\n\t\t\t\tcode.Print(\"Scopes:\")\n\t\t\t\tcode.Indent()\n\t\t\t\tfor _, pair := range t.Oauth2ImplicitSecurity.Scopes.AdditionalProperties {\n\t\t\t\t\tcode.Print(\"%s -> %s\", pair.Name, pair.Value)\n\t\t\t\t}\n\t\t\t\tcode.Outdent()\n\t\t\t\tcode.Outdent()\n\t\t\tcase *pb.SecurityDefinitionsItem_Oauth2PasswordSecurity:\n\t\t\t\tcode.Print(\"Oauth2PasswordSecurity: %+v\", t)\n\t\t\t}\n\t\t\tcode.Outdent()\n\t\t}\n\t\tcode.Outdent()\n\t}\n\tcode.Print(\"Swagger: %+v\", document.Swagger)\n\tcode.Print(\"Tags:\")\n\tcode.Indent()\n\tfor _, tag := range document.Tags {\n\t\tcode.Print(\"Tag:\")\n\t\tcode.Indent()\n\t\tcode.Print(\"Name: %s\", tag.Name)\n\t\tcode.Print(\"Description: %s\", tag.Description)\n\t\tcode.Print(\"ExternalDocs: %s\", tag.ExternalDocs)\n\t\tprintVendorExtension(code, tag.VendorExtension)\n\t\tcode.Outdent()\n\t}\n\tcode.Outdent()\n}\n\nfunc printOperation(code *printer.Code, operation *pb.Operation) {\n\tcode.Print(\"Consumes: %+v\", operation.Consumes)\n\tcode.Print(\"Deprecated: %+v\", operation.Deprecated)\n\tcode.Print(\"Description: %+v\", operation.Description)\n\tcode.Print(\"ExternalDocs: %+v\", operation.ExternalDocs)\n\tcode.Print(\"OperationId: %+v\", operation.OperationId)\n\tcode.Print(\"Parameters:\")\n\tcode.Indent()\n\tfor _, item := range operation.Parameters {\n\t\tswitch t := item.Oneof.(type) {\n\t\tdefault:\n\t\t\tcode.Print(\"unexpected type %T\", t) \/\/ %T prints whatever type t has\n\t\tcase *pb.ParametersItem_JsonReference:\n\t\t\tcode.Print(\"JsonReference: %+v\", t)\n\t\tcase *pb.ParametersItem_Parameter:\n\t\t\tcode.Print(\"Parameter: %+v\", t)\n\t\t}\n\t}\n\tcode.Outdent()\n\tcode.Print(\"Produces: %+v\", operation.Produces)\n\tcode.Print(\"Responses:\")\n\tcode.Indent()\n\tcode.Print(\"ResponseCode:\")\n\tcode.Indent()\n\tfor _, pair := range operation.Responses.ResponseCode {\n\t\tcode.Print(\"%s %s\", pair.Name, pair.Value)\n\t}\n\tcode.Outdent()\n\tprintVendorExtension(code, operation.Responses.VendorExtension)\n\tcode.Outdent()\n\tcode.Print(\"Schemes: %+v\", operation.Schemes)\n\tcode.Print(\"Security: %+v\", operation.Security)\n\tcode.Print(\"Summary: %+v\", operation.Summary)\n\tcode.Print(\"Tags: %+v\", operation.Tags)\n\tprintVendorExtension(code, operation.VendorExtension)\n}\n\nfunc printSchema(code *printer.Code, schema *pb.Schema) {\n\t\/\/code.Print(\"%+v\", schema)\n\tif schema.Format != \"\" {\n\t\tcode.Print(\"Format: %+v\", schema.Format)\n\t}\n\tif schema.Properties != nil {\n\t\tcode.Print(\"Properties\")\n\t\tcode.Indent()\n\t\tfor _, pair := range schema.Properties.AdditionalProperties {\n\t\t\tcode.Print(\"%s\", pair.Name)\n\t\t\tcode.Indent()\n\t\t\tprintSchema(code, pair.Value)\n\t\t\tcode.Outdent()\n\t\t}\n\t\tcode.Outdent()\n\t}\n\tif schema.Type != nil {\n\t\tcode.Print(\"Type: %+v\", schema.Type)\n\t}\n\tif schema.Xml != nil {\n\t\tcode.Print(\"Xml: %+v\", schema.Xml)\n\t}\n\tprintVendorExtension(code, schema.VendorExtension)\n}\n\nfunc printVendorExtension(code *printer.Code, vendorExtension []*pb.NamedAny) {\n\tif len(vendorExtension) > 0 {\n\t\tcode.Print(\"VendorExtension: %+v\", vendorExtension)\n\t}\n}\n\nfunc main() {\n\tflag.Parse()\n\targs := flag.Args()\n\n\tif len(args) != 1 {\n\t\tfmt.Printf(\"Usage: report <file.pb>\\n\")\n\t\treturn\n\t}\n\n\tdocument, err := readDocumentFromFileWithName(args[0])\n\n\tif err != nil {\n\t\tlog.Printf(\"Error reading %s. This sample expects OpenAPI v2.\", args[0])\n\t\tos.Exit(-1)\n\t}\n\tcode := &printer.Code{}\n\tcode.Print(\"API REPORT\")\n\tcode.Print(\"----------\")\n\tprintDocument(code, document)\n\tfmt.Printf(\"%s\", code)\n}\n<|endoftext|>"}
{"text":"<commit_before>package aviator\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com\/JulzDiverse\/aviator\/spruce\"\n\n\t\"gopkg.in\/yaml.v2\"\n)\n\nvar Warnings []string\nvar Silent bool\nvar Verbose bool\n\ntype Aviator struct {\n\tSpruce  []SpruceConfig `yaml:\"spruce\"`\n\tFly     FlyConfig      `yaml:\"fly\"`\n\tAviator AviatorConfig  `yaml:\"aviator\"`\n}\n\ntype AviatorConfig struct {\n\tVerbose bool `yaml:\"verbose`\n\tSilent  bool `yaml:\"silent\"`\n}\n\ntype SpruceConfig struct {\n\tBase           string   `yaml:\"base\"`\n\tPrune          []string `yaml:\"prune\"`\n\tChain          []Chain  `yaml:\"merge\"`\n\tWithIn         string   `yaml:\"with_in\"`\n\tFolder         string   `yaml:\"dir\"`\n\tForEach        []string `yaml:\"for_each\"`\n\tForEachIn      string   `yaml:\"for_each_in\"`\n\tWalk           string   `yaml:\"walk_through\"`\n\tIncludeAllIn   string   `yaml:\"include_all_in\"`\n\tForAll         string   `yaml:\"for_all\"`\n\tCopyParents    bool     `yaml:\"copy_parents\"`\n\tEnableMatching bool     `yaml:\"enable_matching\"`\n\tSkipEval       bool     `yaml:\"skip_eval\"`\n\tCherryPicks    []string `yaml:\"cherry_pick\"`\n\tDestFile       string   `yaml:\"to\"`\n\tDestDir        string   `yaml:\"to_dir\"`\n\tExcept         []string `yaml:\"except\"`\n\tRegexp         string   `yaml:\"regexp\"`\n}\n\ntype Chain struct {\n\tWith   With     `yaml:\"with\"`\n\tWithIn string   `yaml:\"with_in\"`\n\tExcept []string `yaml:\"except\"`\n\tRegexp string   `yaml:\"regexp\"`\n}\n\ntype With struct {\n\tFiles    []string `yaml:\"files\"`\n\tInDir    string   `yaml:\"in_dir\"`\n\tExisting bool     `yaml:\"skip_non_existing\"`\n}\n\ntype FlyConfig struct {\n\tName   string   `yaml:\"name\"`\n\tTarget string   `yaml:\"target\"`\n\tConfig string   `yaml:\"config\"`\n\tVars   []string `yaml:\"vars\"`\n}\n\nfunc ReadYaml(ymlBytes []byte) Aviator {\n\tvar yml Aviator\n\n\tymlBytes = quoteBraces(ymlBytes)\n\terr := yaml.Unmarshal(ymlBytes, &yml)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn yml\n}\n\nvar quoteRegex = `\\{\\{([-\\w\\p{L}]+)\\}\\}`\nvar re = regexp.MustCompile(\"(\" + quoteRegex + \")\")\n\nfunc quoteBraces(input []byte) []byte {\n\treturn re.ReplaceAll(input, []byte(\"\\\"$1\\\"\"))\n}\n\nfunc FlyPipeline(fly FlyConfig) {\n\n\tflyCmd := []string{\"-t\", fly.Target, \"set-pipeline\", \"-p\", fly.Name, \"-c\", fly.Config}\n\tfor _, val := range fly.Vars {\n\t\tflyCmd = append(flyCmd, \"-l\", val)\n\t}\n\n\tcmd := exec.Command(\"fly\", flyCmd...)\n\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tcmd.Stdin = os.Stdin\n\n\terr := cmd.Run()\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to run fly. %s\\n\", err.Error())\n\t\tos.Exit(1)\n\t}\n}\n\nfunc ProcessSprucePlan(spruce []SpruceConfig, verbose bool, silent bool) error {\n\tSilent = silent\n\tVerbose = verbose\n\n\tfor _, conf := range spruce {\n\n\t\tverifySpruceConfig(conf)\n\n\t\tif conf.ForEachIn == \"\" && len(conf.ForEach) == 0 && conf.Walk == \"\" {\n\t\t\terr := simpleMerge(conf)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif len(conf.ForEach) != 0 {\n\t\t\terr := ForEachFile(conf)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif conf.ForEachIn != \"\" {\n\t\t\terr := ForEachIn(conf)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif conf.Walk != \"\" {\n\t\t\tif conf.ForAll != \"\" {\n\t\t\t\terr := ForAll(conf)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\terr := Walk(conf, \"\")\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\tif conf.IncludeAllIn != \"\" {\n\t\t\terr := WalkInclude(conf)\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\nfunc simpleMerge(conf SpruceConfig) error {\n\tfiles := collectFiles(conf)\n\tmergeConf := spruce.MergeOpts{\n\t\tFiles:       files,\n\t\tPrune:       conf.Prune,\n\t\tSkipEval:    conf.SkipEval,\n\t\tCherryPicks: conf.CherryPicks,\n\t}\n\terr := spruceToFile(mergeConf, conf.DestFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc collectFiles(conf SpruceConfig) []string {\n\tfiles := []string{conf.Base}\n\tfor _, val := range conf.Chain {\n\t\ttmp := collectFromMergeSection(val)\n\t\tfor _, str := range tmp {\n\t\t\tfiles = append(files, str)\n\t\t}\n\t}\n\treturn files\n}\n\nfunc ForEachFile(conf SpruceConfig) error {\n\tfor _, val := range conf.ForEach {\n\t\tfiles := collectFiles(conf)\n\t\tfileName, _ := ConcatFileName(val)\n\t\tfiles = append(files, val)\n\t\tmergeConf := spruce.MergeOpts{\n\t\t\tFiles:       files,\n\t\t\tPrune:       conf.Prune,\n\t\t\tSkipEval:    conf.SkipEval,\n\t\t\tCherryPicks: conf.CherryPicks,\n\t\t}\n\t\terr := spruceToFile(mergeConf, conf.DestDir+fileName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t}\n\treturn nil\n}\n\nfunc ForEachIn(conf SpruceConfig) error {\n\tfilePaths, _ := ioutil.ReadDir(conf.ForEachIn)\n\tregex := getRegexp(conf)\n\tfiles := collectFiles(conf)\n\tfor _, f := range filePaths {\n\t\tif except(conf.Except, f.Name()) {\n\t\t\tWarnings = append(Warnings, \"SKIPPED: \"+f.Name())\n\t\t\tcontinue\n\t\t}\n\t\tmatched, _ := regexp.MatchString(regex, f.Name())\n\t\tif matched {\n\t\t\tprefix := Chunk(conf.ForEachIn)\n\t\t\tfilesTmp := append(files, conf.ForEachIn+f.Name())\n\t\t\tmergeConf := spruce.MergeOpts{\n\t\t\t\tFiles:       filesTmp,\n\t\t\t\tSkipEval:    conf.SkipEval,\n\t\t\t\tPrune:       conf.Prune,\n\t\t\t\tCherryPicks: conf.CherryPicks,\n\t\t\t}\n\t\t\tCreateDir(conf.DestDir)\n\t\t\terr := spruceToFile(mergeConf, conf.DestDir+prefix+\"_\"+f.Name())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tWarnings = append(Warnings, \"EXCLUDED BY REGEXP \"+regex+\": \"+conf.ForEachIn+f.Name())\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc ForEachInner(conf SpruceConfig, outer string) error {\n\tfilePaths, _ := ioutil.ReadDir(conf.ForEachIn)\n\tregex := getRegexp(conf)\n\tfor _, f := range filePaths {\n\t\tfiles := collectFiles(conf)\n\t\tmatched, _ := regexp.MatchString(regex, f.Name())\n\t\tif matched {\n\t\t\tprefix := Chunk(conf.ForEachIn)\n\t\t\tfiles = append(files, conf.ForEachIn+f.Name())\n\t\t\tfiles = append(files, outer)\n\t\t\tmergeConf := spruce.MergeOpts{\n\t\t\t\tFiles:       files,\n\t\t\t\tPrune:       conf.Prune,\n\t\t\t\tSkipEval:    conf.SkipEval,\n\t\t\t\tCherryPicks: conf.CherryPicks,\n\t\t\t}\n\t\t\terr := spruceToFile(mergeConf, conf.DestDir+prefix+\"_\"+f.Name())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc ForAll(conf SpruceConfig) error {\n\tif conf.ForAll != \"\" {\n\t\tfiles, _ := ioutil.ReadDir(conf.ForAll)\n\t\tfor _, f := range files {\n\t\t\terr := Walk(conf, conf.ForAll+f.Name())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc Walk(conf SpruceConfig, outer string) error {\n\tsl := getAllFilesInSubDirs(conf.Walk)\n\tregex := getRegexp(conf)\n\n\tfor _, f := range sl {\n\t\tfilename, parent := ConcatFileName(f)\n\t\tmatch := isMatchingEnabled(conf, parent)\n\t\tif strings.Contains(outer, match) {\n\t\t\tmatched, _ := regexp.MatchString(regex, filename)\n\t\t\tif matched {\n\t\t\t\tfiles := collectFiles(conf)\n\t\t\t\tfiles = append(files, f)\n\t\t\t\tfiles = append(files, outer)\n\t\t\t\tif conf.CopyParents {\n\t\t\t\t\tCreateDir(conf.DestDir + parent)\n\t\t\t\t} else {\n\t\t\t\t\tparent = \"\"\n\t\t\t\t}\n\t\t\t\tmergeConf := spruce.MergeOpts{\n\t\t\t\t\tFiles:       files,\n\t\t\t\t\tPrune:       conf.Prune,\n\t\t\t\t\tSkipEval:    conf.SkipEval,\n\t\t\t\t\tCherryPicks: conf.CherryPicks,\n\t\t\t\t}\n\t\t\t\terr := spruceToFile(mergeConf, conf.DestDir+parent+\"\/\"+filename)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc WalkInclude(conf SpruceConfig) error {\n\tallFiles := getAllFilesInSubDirs(conf.IncludeAllIn)\n\tregex := getRegexp(conf)\n\tfiles := []string{}\n\tfor _, file := range allFiles {\n\t\tfilename, _ := ConcatFileName(file)\n\t\tmatched, _ := regexp.MatchString(regex, filename)\n\t\tif matched {\n\t\t\tfiles = append(files, file)\n\t\t}\n\t}\n\tmergeConf := spruce.MergeOpts{\n\t\tFiles:       files,\n\t\tPrune:       conf.Prune,\n\t\tSkipEval:    conf.SkipEval,\n\t\tCherryPicks: conf.CherryPicks,\n\t}\n\terr := spruceToFile(mergeConf, conf.DestFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc collectFromMergeSection(chain Chain) []string {\n\tvar result []string\n\tfor _, file := range chain.With.Files {\n\t\tif chain.With.InDir != \"\" {\n\t\t\tdir := chain.With.InDir\n\t\t\tfile = dir + file\n\t\t}\n\t\tif !chain.With.Existing || fileExists(file) {\n\t\t\tresult = append(result, file)\n\t\t}\n\t}\n\n\tif chain.WithIn != \"\" {\n\t\twithin := chain.WithIn\n\t\tfiles, _ := ioutil.ReadDir(within)\n\t\tregex := getChainRegexp(chain)\n\t\tfor _, f := range files {\n\t\t\tif except(chain.Except, f.Name()) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tmatched, _ := regexp.MatchString(regex, f.Name())\n\t\t\tif matched {\n\t\t\t\tresult = append(result, within+f.Name())\n\t\t\t} else {\n\t\t\t\tWarnings = append(Warnings, \"EXCLUDED BY REGEXP \"+regex+\": \"+chain.WithIn+f.Name())\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result\n}\n\nfunc except(except []string, file string) bool {\n\tfor _, f := range except {\n\t\tif f == file {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc spruceToFile(opts spruce.MergeOpts, fileName string) error {\n\tif !Silent {\n\t\tbeautifyPrint(opts, fileName)\n\t}\n\tWarnings = []string{}\n\n\trawYml, err := spruce.CmdMergeEval(opts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tresultYml, err := yaml.Marshal(rawYml)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tspruce.WriteYamlToPathOrStore(fileName, resultYml)\n\treturn nil\n}\n\nfunc Cleanup(path string) {\n\td, err := os.Open(path)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer d.Close()\n\tnames, err := d.Readdirnames(-1)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfor _, name := range names {\n\t\terr = os.RemoveAll(filepath.Join(path, name))\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}\n<commit_msg>adding fix to walkinclude merging feature<commit_after>package aviator\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com\/JulzDiverse\/aviator\/spruce\"\n\n\t\"gopkg.in\/yaml.v2\"\n)\n\nvar Warnings []string\nvar Silent bool\nvar Verbose bool\n\ntype Aviator struct {\n\tSpruce  []SpruceConfig `yaml:\"spruce\"`\n\tFly     FlyConfig      `yaml:\"fly\"`\n\tAviator AviatorConfig  `yaml:\"aviator\"`\n}\n\ntype AviatorConfig struct {\n\tVerbose bool `yaml:\"verbose`\n\tSilent  bool `yaml:\"silent\"`\n}\n\ntype SpruceConfig struct {\n\tBase           string   `yaml:\"base\"`\n\tPrune          []string `yaml:\"prune\"`\n\tChain          []Chain  `yaml:\"merge\"`\n\tWithIn         string   `yaml:\"with_in\"`\n\tFolder         string   `yaml:\"dir\"`\n\tForEach        []string `yaml:\"for_each\"`\n\tForEachIn      string   `yaml:\"for_each_in\"`\n\tWalk           string   `yaml:\"walk_through\"`\n\tIncludeAllIn   string   `yaml:\"include_all_in\"`\n\tForAll         string   `yaml:\"for_all\"`\n\tCopyParents    bool     `yaml:\"copy_parents\"`\n\tEnableMatching bool     `yaml:\"enable_matching\"`\n\tSkipEval       bool     `yaml:\"skip_eval\"`\n\tCherryPicks    []string `yaml:\"cherry_pick\"`\n\tDestFile       string   `yaml:\"to\"`\n\tDestDir        string   `yaml:\"to_dir\"`\n\tExcept         []string `yaml:\"except\"`\n\tRegexp         string   `yaml:\"regexp\"`\n}\n\ntype Chain struct {\n\tWith   With     `yaml:\"with\"`\n\tWithIn string   `yaml:\"with_in\"`\n\tExcept []string `yaml:\"except\"`\n\tRegexp string   `yaml:\"regexp\"`\n}\n\ntype With struct {\n\tFiles    []string `yaml:\"files\"`\n\tInDir    string   `yaml:\"in_dir\"`\n\tExisting bool     `yaml:\"skip_non_existing\"`\n}\n\ntype FlyConfig struct {\n\tName   string   `yaml:\"name\"`\n\tTarget string   `yaml:\"target\"`\n\tConfig string   `yaml:\"config\"`\n\tVars   []string `yaml:\"vars\"`\n}\n\nfunc ReadYaml(ymlBytes []byte) Aviator {\n\tvar yml Aviator\n\n\tymlBytes = quoteBraces(ymlBytes)\n\terr := yaml.Unmarshal(ymlBytes, &yml)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn yml\n}\n\nvar quoteRegex = `\\{\\{([-\\w\\p{L}]+)\\}\\}`\nvar re = regexp.MustCompile(\"(\" + quoteRegex + \")\")\n\nfunc quoteBraces(input []byte) []byte {\n\treturn re.ReplaceAll(input, []byte(\"\\\"$1\\\"\"))\n}\n\nfunc FlyPipeline(fly FlyConfig) {\n\n\tflyCmd := []string{\"-t\", fly.Target, \"set-pipeline\", \"-p\", fly.Name, \"-c\", fly.Config}\n\tfor _, val := range fly.Vars {\n\t\tflyCmd = append(flyCmd, \"-l\", val)\n\t}\n\n\tcmd := exec.Command(\"fly\", flyCmd...)\n\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tcmd.Stdin = os.Stdin\n\n\terr := cmd.Run()\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to run fly. %s\\n\", err.Error())\n\t\tos.Exit(1)\n\t}\n}\n\nfunc ProcessSprucePlan(spruce []SpruceConfig, verbose bool, silent bool) error {\n\tSilent = silent\n\tVerbose = verbose\n\n\tfor _, conf := range spruce {\n\n\t\tverifySpruceConfig(conf)\n\n\t\tif conf.ForEachIn == \"\" && len(conf.ForEach) == 0 && conf.Walk == \"\"  && conf.IncludeAllIn == \"\" {\n\t\t\terr := simpleMerge(conf)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif len(conf.ForEach) != 0 {\n\t\t\terr := ForEachFile(conf)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif conf.ForEachIn != \"\" {\n\t\t\terr := ForEachIn(conf)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif conf.Walk != \"\" {\n\t\t\tif conf.ForAll != \"\" {\n\t\t\t\terr := ForAll(conf)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\terr := Walk(conf, \"\")\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\tif conf.IncludeAllIn != \"\" {\n\t\t\terr := WalkInclude(conf)\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\nfunc simpleMerge(conf SpruceConfig) error {\n\tfiles := collectFiles(conf)\n\tmergeConf := spruce.MergeOpts{\n\t\tFiles:       files,\n\t\tPrune:       conf.Prune,\n\t\tSkipEval:    conf.SkipEval,\n\t\tCherryPicks: conf.CherryPicks,\n\t}\n\terr := spruceToFile(mergeConf, conf.DestFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc collectFiles(conf SpruceConfig) []string {\n\tfiles := []string{conf.Base}\n\tfor _, val := range conf.Chain {\n\t\ttmp := collectFromMergeSection(val)\n\t\tfor _, str := range tmp {\n\t\t\tfiles = append(files, str)\n\t\t}\n\t}\n\treturn files\n}\n\nfunc ForEachFile(conf SpruceConfig) error {\n\tfor _, val := range conf.ForEach {\n\t\tfiles := collectFiles(conf)\n\t\tfileName, _ := ConcatFileName(val)\n\t\tfiles = append(files, val)\n\t\tmergeConf := spruce.MergeOpts{\n\t\t\tFiles:       files,\n\t\t\tPrune:       conf.Prune,\n\t\t\tSkipEval:    conf.SkipEval,\n\t\t\tCherryPicks: conf.CherryPicks,\n\t\t}\n\t\terr := spruceToFile(mergeConf, conf.DestDir+fileName)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t}\n\treturn nil\n}\n\nfunc ForEachIn(conf SpruceConfig) error {\n\tfilePaths, _ := ioutil.ReadDir(conf.ForEachIn)\n\tregex := getRegexp(conf)\n\tfiles := collectFiles(conf)\n\tfor _, f := range filePaths {\n\t\tif except(conf.Except, f.Name()) {\n\t\t\tWarnings = append(Warnings, \"SKIPPED: \"+f.Name())\n\t\t\tcontinue\n\t\t}\n\t\tmatched, _ := regexp.MatchString(regex, f.Name())\n\t\tif matched {\n\t\t\tprefix := Chunk(conf.ForEachIn)\n\t\t\tfilesTmp := append(files, conf.ForEachIn+f.Name())\n\t\t\tmergeConf := spruce.MergeOpts{\n\t\t\t\tFiles:       filesTmp,\n\t\t\t\tSkipEval:    conf.SkipEval,\n\t\t\t\tPrune:       conf.Prune,\n\t\t\t\tCherryPicks: conf.CherryPicks,\n\t\t\t}\n\t\t\tCreateDir(conf.DestDir)\n\t\t\terr := spruceToFile(mergeConf, conf.DestDir+prefix+\"_\"+f.Name())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tWarnings = append(Warnings, \"EXCLUDED BY REGEXP \"+regex+\": \"+conf.ForEachIn+f.Name())\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc ForEachInner(conf SpruceConfig, outer string) error {\n\tfilePaths, _ := ioutil.ReadDir(conf.ForEachIn)\n\tregex := getRegexp(conf)\n\tfor _, f := range filePaths {\n\t\tfiles := collectFiles(conf)\n\t\tmatched, _ := regexp.MatchString(regex, f.Name())\n\t\tif matched {\n\t\t\tprefix := Chunk(conf.ForEachIn)\n\t\t\tfiles = append(files, conf.ForEachIn+f.Name())\n\t\t\tfiles = append(files, outer)\n\t\t\tmergeConf := spruce.MergeOpts{\n\t\t\t\tFiles:       files,\n\t\t\t\tPrune:       conf.Prune,\n\t\t\t\tSkipEval:    conf.SkipEval,\n\t\t\t\tCherryPicks: conf.CherryPicks,\n\t\t\t}\n\t\t\terr := spruceToFile(mergeConf, conf.DestDir+prefix+\"_\"+f.Name())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc ForAll(conf SpruceConfig) error {\n\tif conf.ForAll != \"\" {\n\t\tfiles, _ := ioutil.ReadDir(conf.ForAll)\n\t\tfor _, f := range files {\n\t\t\terr := Walk(conf, conf.ForAll+f.Name())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc Walk(conf SpruceConfig, outer string) error {\n\tsl := getAllFilesInSubDirs(conf.Walk)\n\tregex := getRegexp(conf)\n\n\tfor _, f := range sl {\n\t\tfilename, parent := ConcatFileName(f)\n\t\tmatch := isMatchingEnabled(conf, parent)\n\t\tif strings.Contains(outer, match) {\n\t\t\tmatched, _ := regexp.MatchString(regex, filename)\n\t\t\tif matched {\n\t\t\t\tfiles := collectFiles(conf)\n\t\t\t\tfiles = append(files, f)\n\t\t\t\tfiles = append(files, outer)\n\t\t\t\tif conf.CopyParents {\n\t\t\t\t\tCreateDir(conf.DestDir + parent)\n\t\t\t\t} else {\n\t\t\t\t\tparent = \"\"\n\t\t\t\t}\n\t\t\t\tmergeConf := spruce.MergeOpts{\n\t\t\t\t\tFiles:       files,\n\t\t\t\t\tPrune:       conf.Prune,\n\t\t\t\t\tSkipEval:    conf.SkipEval,\n\t\t\t\t\tCherryPicks: conf.CherryPicks,\n\t\t\t\t}\n\t\t\t\terr := spruceToFile(mergeConf, conf.DestDir+parent+\"\/\"+filename)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc WalkInclude(conf SpruceConfig) error {\n\tallFiles := getAllFilesInSubDirs(conf.IncludeAllIn)\n\tregex := getRegexp(conf)\n\tfiles := []string{}\n\tfor _, file := range allFiles {\n\t\tmatched, _ := regexp.MatchString(regex, file)\n\t\tif matched {\n\t\t\tfiles = append(files, file)\n\t\t}\n\t}\n\tmergeConf := spruce.MergeOpts{\n\t\tFiles:       files,\n\t\tPrune:       conf.Prune,\n\t\tSkipEval:    conf.SkipEval,\n\t\tCherryPicks: conf.CherryPicks,\n\t}\n\terr := spruceToFile(mergeConf, conf.DestFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc collectFromMergeSection(chain Chain) []string {\n\tvar result []string\n\tfor _, file := range chain.With.Files {\n\t\tif chain.With.InDir != \"\" {\n\t\t\tdir := chain.With.InDir\n\t\t\tfile = dir + file\n\t\t}\n\t\tif !chain.With.Existing || fileExists(file) {\n\t\t\tresult = append(result, file)\n\t\t}\n\t}\n\n\tif chain.WithIn != \"\" {\n\t\twithin := chain.WithIn\n\t\tfiles, _ := ioutil.ReadDir(within)\n\t\tregex := getChainRegexp(chain)\n\t\tfor _, f := range files {\n\t\t\tif except(chain.Except, f.Name()) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tmatched, _ := regexp.MatchString(regex, f.Name())\n\t\t\tif matched {\n\t\t\t\tresult = append(result, within+f.Name())\n\t\t\t} else {\n\t\t\t\tWarnings = append(Warnings, \"EXCLUDED BY REGEXP \"+regex+\": \"+chain.WithIn+f.Name())\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result\n}\n\nfunc except(except []string, file string) bool {\n\tfor _, f := range except {\n\t\tif f == file {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc spruceToFile(opts spruce.MergeOpts, fileName string) error {\n\tif !Silent {\n\t\tbeautifyPrint(opts, fileName)\n\t}\n\tWarnings = []string{}\n\n\trawYml, err := spruce.CmdMergeEval(opts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tresultYml, err := yaml.Marshal(rawYml)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tspruce.WriteYamlToPathOrStore(fileName, resultYml)\n\treturn nil\n}\n\nfunc Cleanup(path string) {\n\td, err := os.Open(path)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer d.Close()\n\tnames, err := d.Readdirnames(-1)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfor _, name := range names {\n\t\terr = os.RemoveAll(filepath.Join(path, name))\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\n   Copyright 2014 CoreOS, Inc.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*\/\n\npackage etcdhttp\n\nimport (\n\t\"errors\"\n\t\"log\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"time\"\n\n\tetcdErr \"github.com\/coreos\/etcd\/error\"\n\t\"github.com\/coreos\/etcd\/etcdserver\/etcdhttp\/httptypes\"\n)\n\nconst (\n\t\/\/ time to wait for response from EtcdServer requests\n\tdefaultServerTimeout = 5 * time.Minute\n\n\t\/\/ time to wait for a Watch request\n\tdefaultWatchTimeout = 5 * time.Minute\n)\n\nvar errClosed = errors.New(\"etcdhttp: client closed connection\")\n\n\/\/ writeError logs and writes the given Error to the ResponseWriter\n\/\/ If Error is an etcdErr, it is rendered to the ResponseWriter\n\/\/ Otherwise, it is assumed to be an InternalServerError\nfunc writeError(w http.ResponseWriter, err error) {\n\tif err == nil {\n\t\treturn\n\t}\n\tswitch e := err.(type) {\n\tcase *etcdErr.Error:\n\t\te.WriteTo(w)\n\tcase *httptypes.HTTPError:\n\t\te.WriteTo(w)\n\tdefault:\n\t\tlog.Printf(\"etcdhttp: unexpected error: %v\", err)\n\t\therr := httptypes.NewHTTPError(http.StatusInternalServerError, \"Internal Server Error\")\n\t\therr.WriteTo(w)\n\t}\n}\n\n\/\/ allowMethod verifies that the given method is one of the allowed methods,\n\/\/ and if not, it writes an error to w.  A boolean is returned indicating\n\/\/ whether or not the method is allowed.\nfunc allowMethod(w http.ResponseWriter, m string, ms ...string) bool {\n\tfor _, meth := range ms {\n\t\tif m == meth {\n\t\t\treturn true\n\t\t}\n\t}\n\tw.Header().Set(\"Allow\", strings.Join(ms, \",\"))\n\thttp.Error(w, \"Method Not Allowed\", http.StatusMethodNotAllowed)\n\treturn false\n}\n<commit_msg>etcdhttp: reset serve and watch timeout<commit_after>\/*\n   Copyright 2014 CoreOS, Inc.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n*\/\n\npackage etcdhttp\n\nimport (\n\t\"errors\"\n\t\"log\"\n\t\"math\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"time\"\n\n\tetcdErr \"github.com\/coreos\/etcd\/error\"\n\t\"github.com\/coreos\/etcd\/etcdserver\/etcdhttp\/httptypes\"\n)\n\nconst (\n\t\/\/ time to wait for response from EtcdServer requests\n\t\/\/ 5s for disk and network delay + 10*heartbeat for commit and possible\n\t\/\/ leader switch\n\t\/\/ TODO: use heartbeat set in etcdserver\n\tdefaultServerTimeout = 5*time.Second + 10*(100*time.Millisecond)\n\n\t\/\/ time to wait for a Watch request\n\tdefaultWatchTimeout = time.Duration(math.MaxInt64)\n)\n\nvar errClosed = errors.New(\"etcdhttp: client closed connection\")\n\n\/\/ writeError logs and writes the given Error to the ResponseWriter\n\/\/ If Error is an etcdErr, it is rendered to the ResponseWriter\n\/\/ Otherwise, it is assumed to be an InternalServerError\nfunc writeError(w http.ResponseWriter, err error) {\n\tif err == nil {\n\t\treturn\n\t}\n\tswitch e := err.(type) {\n\tcase *etcdErr.Error:\n\t\te.WriteTo(w)\n\tcase *httptypes.HTTPError:\n\t\te.WriteTo(w)\n\tdefault:\n\t\tlog.Printf(\"etcdhttp: unexpected error: %v\", err)\n\t\therr := httptypes.NewHTTPError(http.StatusInternalServerError, \"Internal Server Error\")\n\t\therr.WriteTo(w)\n\t}\n}\n\n\/\/ allowMethod verifies that the given method is one of the allowed methods,\n\/\/ and if not, it writes an error to w.  A boolean is returned indicating\n\/\/ whether or not the method is allowed.\nfunc allowMethod(w http.ResponseWriter, m string, ms ...string) bool {\n\tfor _, meth := range ms {\n\t\tif m == meth {\n\t\t\treturn true\n\t\t}\n\t}\n\tw.Header().Set(\"Allow\", strings.Join(ms, \",\"))\n\thttp.Error(w, \"Method Not Allowed\", http.StatusMethodNotAllowed)\n\treturn false\n}\n<|endoftext|>"}
{"text":"<commit_before>package Handlers\n\nimport (\n\t\"Gate\/Manager\"\n)\n\ntype UserLoginHander struct {\n}\n\nfunc (hander *UserLoginHander) GetMessage() {\n\treturn nil\n}\n\nfunc (hander *UserLoginHander) Action() {\n\tvar msg = hander.GetMessage()\n\tManager.GetInstance().UserManager.UserLogin(msg.GetSession(), msg.GetUserName(), msg.GetUserPass())\n}\n<commit_msg>Modify UserLoginHandler<commit_after>package Handlers\n\nimport (\n\t\"Gate\"\n\t\"Gate\/Manager\"\n)\n\ntype UserLoginHander struct {\n\tmessage *Gate.Messager\n}\n\nfunc (hander *UserLoginHander) GetMessage() *Gate.Messager {\n\treturn hander.message\n}\n\nfunc (hander *UserLoginHander) Action() {\n\tvar msg = hander.GetMessage()\n\tManager.GetInstance().UserManager.UserLogin(msg.GetSession(), msg.GetUserName(), msg.GetUserPass())\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ File deduplication\npackage main\n\nimport (\n\t\"crypto\/sha256\"\n\t\"hash\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n)\n\n\/\/ File attributes.\ntype FileAttr struct {\n\tPath       string   \/\/ Full path.\n\tName       string   \/\/ Name.\n\tModTime    int64    \/\/ the number of nanoseconds elapsed since January 1, 1970 UTC\n\tSize       int64    \/\/ File size, in bytes.\n\tSHA256     [32]byte \/\/ SHA256 checksum.\n\tStillExist bool     \/\/ Indicates if the file still exists.\n}\n\n\/\/ Update status.\ntype Updater interface {\n\tError() error                          \/\/ Any error happened or job was cancelled.\n\tSetError(err error)                    \/\/ Set error code.\n\tPrint(format string, a ...interface{}) \/\/ Print status message.\n}\n\n\/\/ Scan a path (could be file or folder).\nfunc ScanPath(path string, files map[string]*FileAttr,\n\tupdater Updater) error {\n\n\t\/\/ Check if it's file or folder.\n\tinfo, err := os.Stat(path)\n\tif err != nil {\n\t\tupdater.Print(\"Path %v might not exist. Error:%v\", path, err)\n\t\tupdater.SetError(err)\n\t\treturn err\n\t}\n\n\t\/\/ Create hash engine and allocate buffer to read file.\n\thash := sha256.New()\n\tbuffer := make([]byte, 16*1024)\n\n\tif info.IsDir() {\n\t\tif err = scanFolder_i(path, files,\n\t\t\tupdater, hash, buffer); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tif err = scanFile_i(path, files,\n\t\t\tupdater, hash, buffer, info); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Some files do not exist in disk any more,\n\t\/\/ let's remove them from the map.\n\tremoveNonExistFiles(files)\n\n\treturn nil\n}\n\n\/\/ Scan a folder and its sub-folders recursively.\nfunc scanFolder_i(path string, files map[string]*FileAttr,\n\tupdater Updater, hash hash.Hash, buffer []byte) error {\n\tfp, err := os.Open(path)\n\tif err != nil {\n\t\tupdater.Print(\"Could not open folder %v. Error:%v\", path, err)\n\t\tupdater.SetError(err)\n\t\treturn err\n\t}\n\tdefer fp.Close()\n\n\tfor {\n\t\tlist, err := fp.Readdir(256)\n\t\tif err != nil && err != io.EOF {\n\t\t\tupdater.Print(\"Could not enumerate folder %v. Error:%v\", path, err)\n\t\t\tupdater.SetError(err)\n\t\t\treturn err\n\t\t}\n\n\t\tfor i := 0; i < len(list); i++ {\n\t\t\t\/\/ Check if job was cancelled or an error ever happened.\n\t\t\tif err := updater.Error(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t\/\/ Get full path.\n\t\t\tvar fullPath string\n\n\t\t\tif len(path) == 1 && path == \"\/\" {\n\t\t\t\tfullPath = path + list[i].Name()\n\t\t\t} else {\n\t\t\t\tfullPath = path + string(os.PathSeparator) + list[i].Name()\n\t\t\t}\n\n\t\t\tif list[i].IsDir() {\n\t\t\t\tif tmp := scanFolder_i(fullPath, files,\n\t\t\t\t\tupdater, hash, buffer); tmp != nil {\n\t\t\t\t\treturn tmp\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif tmp := scanFile_i(fullPath, files,\n\t\t\t\t\tupdater, hash, buffer, list[i]); tmp != nil {\n\t\t\t\t\treturn tmp\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ If reaching end of the folder, then break.\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ Calculate single file checksum.\nfunc scanFile_i(path string, files map[string]*FileAttr,\n\tupdater Updater, hash hash.Hash, buffer []byte,\n\tinfo os.FileInfo) error {\n\n\tvar key string = path\n\n\t\/\/ Case insensitive on Windows.\n\tif os.PathSeparator != '\/' {\n\t\tkey = strings.ToLower(key)\n\t}\n\n\t\/\/ If the file already exists in the map,\n\t\/\/ and file size & last modification time are the same,\n\t\/\/ then skip to read it to enhance performance.\n\tif value, found := files[key]; found {\n\t\tif value.Size == info.Size() && value.ModTime == info.ModTime().UnixNano() {\n\t\t\tvalue.StillExist = true\n\t\t\treturn nil\n\t\t}\n\t}\n\n\t\/\/ Open file.\n\tfp, err := os.Open(path)\n\tif err != nil {\n\t\tupdater.Print(\"Could not open file %v. Error:%v\", path, err)\n\t\treturn err\n\t}\n\tdefer fp.Close()\n\n\t\/\/ Reset hash engine\n\thash.Reset()\n\n\t\/\/ Read file content\n\tfor {\n\t\t\/\/ Check if job was cancelled or an error ever happened.\n\t\tif err := updater.Error(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tn, err := fp.Read(buffer)\n\t\tif err != nil && err != io.EOF {\n\t\t\tupdater.Print(\"Could not read file %v. Error:%v\", path, err)\n\t\t\treturn err\n\t\t}\n\t\thash.Write(buffer[0:n])\n\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t\/\/ Create a new object.\n\tnewValue := &FileAttr{\n\t\tPath:       path,\n\t\tModTime:    info.ModTime().UnixNano(),\n\t\tSize:       info.Size(),\n\t\tStillExist: true,\n\t}\n\tcopy(newValue.SHA256[:], hash.Sum(nil))\n\n\t\/\/ Add the new object to map.\n\tfiles[key] = newValue\n\n\treturn nil\n}\n\n\/\/ Some files do not exist in disk any more, let's remove them from the map.\nfunc removeNonExistFiles(files map[string]*FileAttr) {\n\tfor key, value := range files {\n\t\tif !value.StillExist {\n\t\t\tdelete(files, key)\n\t\t}\n\t}\n}\n<commit_msg>Save file name in FileAttr<commit_after>\/\/ File deduplication\npackage main\n\nimport (\n\t\"crypto\/sha256\"\n\t\"hash\"\n\t\"io\"\n\t\"os\"\n\t\"strings\"\n)\n\n\/\/ File attributes.\ntype FileAttr struct {\n\tPath       string   \/\/ Full path.\n\tName       string   \/\/ Name.\n\tModTime    int64    \/\/ the number of nanoseconds elapsed since January 1, 1970 UTC\n\tSize       int64    \/\/ File size, in bytes.\n\tSHA256     [32]byte \/\/ SHA256 checksum.\n\tStillExist bool     \/\/ Indicates if the file still exists.\n}\n\n\/\/ Update status.\ntype Updater interface {\n\tError() error                          \/\/ Any error happened or job was cancelled.\n\tSetError(err error)                    \/\/ Set error code.\n\tPrint(format string, a ...interface{}) \/\/ Print status message.\n}\n\n\/\/ Scan a path (could be file or folder).\nfunc ScanPath(path string, files map[string]*FileAttr,\n\tupdater Updater) error {\n\n\t\/\/ Check if it's file or folder.\n\tinfo, err := os.Stat(path)\n\tif err != nil {\n\t\tupdater.Print(\"Path %v might not exist. Error:%v\", path, err)\n\t\tupdater.SetError(err)\n\t\treturn err\n\t}\n\n\t\/\/ Create hash engine and allocate buffer to read file.\n\thash := sha256.New()\n\tbuffer := make([]byte, 16*1024)\n\n\tif info.IsDir() {\n\t\tif err = scanFolder_i(path, files,\n\t\t\tupdater, hash, buffer); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tif err = scanFile_i(path, files,\n\t\t\tupdater, hash, buffer, info); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t\/\/ Some files do not exist in disk any more,\n\t\/\/ let's remove them from the map.\n\tremoveNonExistFiles(files)\n\n\treturn nil\n}\n\n\/\/ Scan a folder and its sub-folders recursively.\nfunc scanFolder_i(path string, files map[string]*FileAttr,\n\tupdater Updater, hash hash.Hash, buffer []byte) error {\n\tfp, err := os.Open(path)\n\tif err != nil {\n\t\tupdater.Print(\"Could not open folder %v. Error:%v\", path, err)\n\t\tupdater.SetError(err)\n\t\treturn err\n\t}\n\tdefer fp.Close()\n\n\tfor {\n\t\tlist, err := fp.Readdir(256)\n\t\tif err != nil && err != io.EOF {\n\t\t\tupdater.Print(\"Could not enumerate folder %v. Error:%v\", path, err)\n\t\t\tupdater.SetError(err)\n\t\t\treturn err\n\t\t}\n\n\t\tfor i := 0; i < len(list); i++ {\n\t\t\t\/\/ Check if job was cancelled or an error ever happened.\n\t\t\tif err := updater.Error(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t\/\/ Get full path.\n\t\t\tvar fullPath string\n\n\t\t\tif len(path) == 1 && path == \"\/\" {\n\t\t\t\tfullPath = path + list[i].Name()\n\t\t\t} else {\n\t\t\t\tfullPath = path + string(os.PathSeparator) + list[i].Name()\n\t\t\t}\n\n\t\t\tif list[i].IsDir() {\n\t\t\t\tif tmp := scanFolder_i(fullPath, files,\n\t\t\t\t\tupdater, hash, buffer); tmp != nil {\n\t\t\t\t\treturn tmp\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif tmp := scanFile_i(fullPath, files,\n\t\t\t\t\tupdater, hash, buffer, list[i]); tmp != nil {\n\t\t\t\t\treturn tmp\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ If reaching end of the folder, then break.\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ Calculate single file checksum.\nfunc scanFile_i(path string, files map[string]*FileAttr,\n\tupdater Updater, hash hash.Hash, buffer []byte,\n\tinfo os.FileInfo) error {\n\n\tvar key string = path\n\n\t\/\/ Case insensitive on Windows.\n\tif os.PathSeparator != '\/' {\n\t\tkey = strings.ToLower(key)\n\t}\n\n\t\/\/ If the file already exists in the map,\n\t\/\/ and file size & last modification time are the same,\n\t\/\/ then skip to read it to enhance performance.\n\tif value, found := files[key]; found {\n\t\tif value.Size == info.Size() && value.ModTime == info.ModTime().UnixNano() {\n\t\t\tvalue.StillExist = true\n\t\t\treturn nil\n\t\t}\n\t}\n\n\t\/\/ Open file.\n\tfp, err := os.Open(path)\n\tif err != nil {\n\t\tupdater.Print(\"Could not open file %v. Error:%v\", path, err)\n\t\treturn err\n\t}\n\tdefer fp.Close()\n\n\t\/\/ Reset hash engine\n\thash.Reset()\n\n\t\/\/ Read file content\n\tfor {\n\t\t\/\/ Check if job was cancelled or an error ever happened.\n\t\tif err := updater.Error(); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tn, err := fp.Read(buffer)\n\t\tif err != nil && err != io.EOF {\n\t\t\tupdater.Print(\"Could not read file %v. Error:%v\", path, err)\n\t\t\treturn err\n\t\t}\n\t\thash.Write(buffer[0:n])\n\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t\/\/ Create a new object.\n\tnewValue := &FileAttr{\n\t\tPath:       path,\n\t\tName:       info.Name(),\n\t\tModTime:    info.ModTime().UnixNano(),\n\t\tSize:       info.Size(),\n\t\tStillExist: true,\n\t}\n\tcopy(newValue.SHA256[:], hash.Sum(nil))\n\n\t\/\/ Add the new object to map.\n\tfiles[key] = newValue\n\n\treturn nil\n}\n\n\/\/ Some files do not exist in disk any more, let's remove them from the map.\nfunc removeNonExistFiles(files map[string]*FileAttr) {\n\tfor key, value := range files {\n\t\tif !value.StillExist {\n\t\t\tdelete(files, key)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package apixu\n\nimport (\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n)\n\nconst InvalidCityName = \"INVALID-CITY-NAME\"\n\nvar cities = []string{\n\t\"Cairo\",\n\t\"London\",\n\t\"Paris\",\n\t\"Berlin\",\n\t\"New York\",\n}\n\nfunc getAPIKey() string {\n\treturn os.Getenv(\"APIXU_KEY\")\n}\n\nfunc TestInvalidAPIKey(t *testing.T) {\n\tclient := NewClient(\"Invalid_Key\")\n\t_, err := client.Current(\"Paris\")\n\n\tif err == nil {\n\t\tt.Error(\"Worked with invalid key\")\n\t}\n}\n\nfunc TestCurrentWeatherValidCities(t *testing.T) {\n\tclient := NewClient(getAPIKey())\n\n\tfor _, city := range cities {\n\t\t_, err := client.Current(city)\n\n\t\tif err != nil {\n\t\t\tt.Errorf(\"There was an error getting current weather of %s: %v\", city, err)\n\t\t}\n\t}\n}\n\nfunc TestCurrentWeatherInValidCity(t *testing.T) {\n\tclient := NewClient(getAPIKey())\n\t_, err := client.Current(InvalidCityName)\n\n\tif err == nil {\n\t\tt.Error(\"No errors getting current weather of invalid city name\")\n\t}\n}\n\nfunc TestForecastWeatherValidCities(t *testing.T) {\n\tdays := []int{1, 5, 10}\n\tclient := NewClient(getAPIKey())\n\n\tfor _, day := range days {\n\t\tfor _, city := range cities {\n\t\t\t_, err := client.Forecast(city, day)\n\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"There was an error getting forecast weather of %s days %d: %v\", city, day, err)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestForecastWeatherInValidCity(t *testing.T) {\n\tdays := []int{1, 5, 10}\n\tclient := NewClient(getAPIKey())\n\n\tfor _, day := range days {\n\t\t_, err := client.Forecast(InvalidCityName, day)\n\n\t\tif err == nil {\n\t\t\tt.Error(\"No errors getting forecast weather of invalid city name\")\n\t\t}\n\t}\n}\n\nfunc TestHistoryWeatherValidCities(t *testing.T) {\n\tyesterday := time.Now().AddDate(0, 0, -1)\n\tclient := NewClient(getAPIKey())\n\n\tfor _, city := range cities {\n\t\t_, err := client.History(city, yesterday.Format(\"2006-01-2\"))\n\n\t\tif err != nil {\n\t\t\tt.Errorf(\"There was an error getting current weather of %s: %v\", city, err)\n\t\t}\n\t}\n}\n\nfunc TestHistoryWeatherInValidCity(t *testing.T) {\n\tyesterday := time.Now().AddDate(0, 0, -1)\n\tclient := NewClient(getAPIKey())\n\n\t_, err := client.History(InvalidCityName, yesterday.Format(\"2006-01-2\"))\n\n\tif err == nil {\n\t\tt.Error(\"No errors getting history weather of invalid city name\")\n\t}\n\n}\n\nfunc TestSearchValidCities(t *testing.T) {\n\tclient := NewClient(getAPIKey())\n\n\tfor _, city := range cities {\n\t\t_, err := client.Search(city)\n\n\t\tif err != nil {\n\t\t\tt.Errorf(\"There was an error getting current weather of %s: %v\", city, err)\n\t\t}\n\t}\n}\n\nfunc TestSearchInValidCity(t *testing.T) {\n\tclient := NewClient(getAPIKey())\n\n\tmatchedCities, err := client.Search(InvalidCityName)\n\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif len(*matchedCities) != 0 {\n\t\tt.Error(\"Non-Empty array of matched cities for invalid city name\")\n\t}\n}\n<commit_msg>test: update InvalidCityName<commit_after>package apixu\n\nimport (\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n)\n\nconst InvalidCityName = \"INVALIDCITYNAME\"\n\nvar cities = []string{\n\t\"Cairo\",\n\t\"London\",\n\t\"Paris\",\n\t\"Berlin\",\n\t\"New York\",\n}\n\nfunc getAPIKey() string {\n\treturn os.Getenv(\"APIXU_KEY\")\n}\n\nfunc TestInvalidAPIKey(t *testing.T) {\n\tclient := NewClient(\"Invalid_Key\")\n\t_, err := client.Current(\"Paris\")\n\n\tif err == nil {\n\t\tt.Error(\"Worked with invalid key\")\n\t}\n}\n\nfunc TestCurrentWeatherValidCities(t *testing.T) {\n\tclient := NewClient(getAPIKey())\n\n\tfor _, city := range cities {\n\t\t_, err := client.Current(city)\n\n\t\tif err != nil {\n\t\t\tt.Errorf(\"There was an error getting current weather of %s: %v\", city, err)\n\t\t}\n\t}\n}\n\nfunc TestCurrentWeatherInValidCity(t *testing.T) {\n\tclient := NewClient(getAPIKey())\n\t_, err := client.Current(InvalidCityName)\n\n\tif err == nil {\n\t\tt.Error(\"No errors getting current weather of invalid city name\")\n\t}\n}\n\nfunc TestForecastWeatherValidCities(t *testing.T) {\n\tdays := []int{1, 5, 10}\n\tclient := NewClient(getAPIKey())\n\n\tfor _, day := range days {\n\t\tfor _, city := range cities {\n\t\t\t_, err := client.Forecast(city, day)\n\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"There was an error getting forecast weather of %s days %d: %v\", city, day, err)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestForecastWeatherInValidCity(t *testing.T) {\n\tdays := []int{1, 5, 10}\n\tclient := NewClient(getAPIKey())\n\n\tfor _, day := range days {\n\t\t_, err := client.Forecast(InvalidCityName, day)\n\n\t\tif err == nil {\n\t\t\tt.Error(\"No errors getting forecast weather of invalid city name\")\n\t\t}\n\t}\n}\n\nfunc TestHistoryWeatherValidCities(t *testing.T) {\n\tyesterday := time.Now().AddDate(0, 0, -1)\n\tclient := NewClient(getAPIKey())\n\n\tfor _, city := range cities {\n\t\t_, err := client.History(city, yesterday.Format(\"2006-01-2\"))\n\n\t\tif err != nil {\n\t\t\tt.Errorf(\"There was an error getting current weather of %s: %v\", city, err)\n\t\t}\n\t}\n}\n\nfunc TestHistoryWeatherInValidCity(t *testing.T) {\n\tyesterday := time.Now().AddDate(0, 0, -1)\n\tclient := NewClient(getAPIKey())\n\n\t_, err := client.History(InvalidCityName, yesterday.Format(\"2006-01-2\"))\n\n\tif err == nil {\n\t\tt.Error(\"No errors getting history weather of invalid city name\")\n\t}\n\n}\n\nfunc TestSearchValidCities(t *testing.T) {\n\tclient := NewClient(getAPIKey())\n\n\tfor _, city := range cities {\n\t\t_, err := client.Search(city)\n\n\t\tif err != nil {\n\t\t\tt.Errorf(\"There was an error getting current weather of %s: %v\", city, err)\n\t\t}\n\t}\n}\n\nfunc TestSearchInValidCity(t *testing.T) {\n\tclient := NewClient(getAPIKey())\n\n\tmatchedCities, err := client.Search(InvalidCityName)\n\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif len(*matchedCities) != 0 {\n\t\tt.Error(\"Non-Empty array of matched cities for invalid city name\")\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n\t\"time\"\n\n\t\"github.com\/smartystreets\/go-disruptor\"\n)\n\nconst (\n\tBufferSize = 1024 * 64\n\tBufferMask = BufferSize - 1\n\tIterations = 1000000 * 100\n)\n\nvar ringBuffer = [BufferSize]int64{}\n\nfunc main() {\n\truntime.GOMAXPROCS(2)\n\n\twritten, read := disruptor.NewCursor(), disruptor.NewCursor()\n\treader := disruptor.NewReader(read, written, written, SampleConsumer{})\n\n\tstarted := time.Now()\n\treader.Start()\n\tpublish(written, read)\n\t\/\/ publish(disruptor.NewWriter(written, read, BufferSize))\n\treader.Stop()\n\tfinished := time.Now()\n\tfmt.Println(Iterations, finished.Sub(started))\n}\n\n\/\/ func publish(writer *disruptor.Writer) {\n\/\/ \tfor sequence := disruptor.InitialSequenceValue; sequence <= Iterations; {\n\/\/ \t\tsequence = writer.Reserve()\n\/\/ \t\t\/\/ ringBuffer[sequence&BufferMask] = sequence\n\/\/ \t\twriter.Commit(sequence)\n\/\/ \t}\n\/\/ }\n\nfunc publish(written, read *disruptor.Cursor) {\n\tprevious := disruptor.InitialSequenceValue\n\tgate := disruptor.InitialSequenceValue\n\n\tfor previous <= Iterations {\n\t\tnext := previous + 1\n\t\twrap := next - BufferSize\n\n\t\tfor wrap > gate {\n\t\t\tgate = read.Sequence\n\t\t}\n\n\t\t\/\/ ringBuffer[next&BufferMask] = next\n\t\twritten.Sequence = next\n\t\tprevious = next\n\t}\n}\n\ntype SampleConsumer struct{}\n\nfunc (this SampleConsumer) Consume(lower, upper int64) {\n\tfor lower <= upper {\n\t\t\/\/ message := ringBuffer[lower&BufferMask]\n\t\t\/\/ if message != lower {\n\t\t\/\/ \tfmt.Println(\"Race condition\", message, lower)\n\t\t\/\/ \tpanic(\"Race condition\")\n\t\t\/\/ }\n\t\tlower++\n\t}\n}\n<commit_msg>4.59ms per operation when writing to ring buffer and using \"cleaner\" API.<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"runtime\"\n\t\"time\"\n\n\t\"github.com\/smartystreets\/go-disruptor\"\n)\n\nconst (\n\tBufferSize = 1024 * 64\n\tBufferMask = BufferSize - 1\n\tIterations = 1000000 * 100\n)\n\nvar ringBuffer = [BufferSize]int64{}\n\nfunc main() {\n\truntime.GOMAXPROCS(2)\n\n\twritten, read := disruptor.NewCursor(), disruptor.NewCursor()\n\treader := disruptor.NewReader(read, written, written, SampleConsumer{})\n\n\tstarted := time.Now()\n\treader.Start()\n\t\/\/ publish(written, read)\n\tpublish(disruptor.NewWriter(written, read, BufferSize))\n\treader.Stop()\n\tfinished := time.Now()\n\tfmt.Println(Iterations, finished.Sub(started))\n}\n\nfunc publish(writer *disruptor.Writer) {\n\tfor sequence := disruptor.InitialSequenceValue; sequence <= Iterations; {\n\t\tsequence = writer.Reserve()\n\t\tringBuffer[sequence&BufferMask] = sequence\n\t\twriter.Commit(sequence)\n\t}\n}\n\n\/\/ func publish(written, read *disruptor.Cursor) {\n\/\/ \tprevious := disruptor.InitialSequenceValue\n\/\/ \tgate := disruptor.InitialSequenceValue\n\n\/\/ \tfor previous <= Iterations {\n\/\/ \t\tnext := previous + 1\n\/\/ \t\twrap := next - BufferSize\n\n\/\/ \t\tfor wrap > gate {\n\/\/ \t\t\tgate = read.Sequence\n\/\/ \t\t}\n\n\/\/ \t\tringBuffer[next&BufferMask] = next\n\/\/ \t\twritten.Sequence = next\n\/\/ \t\tprevious = next\n\/\/ \t}\n\/\/ }\n\ntype SampleConsumer struct{}\n\nfunc (this SampleConsumer) Consume(lower, upper int64) {\n\tfor lower <= upper {\n\t\tmessage := ringBuffer[lower&BufferMask]\n\t\tif message != lower {\n\t\t\tfmt.Println(\"Race condition\", message, lower)\n\t\t\tpanic(\"Race condition\")\n\t\t}\n\t\tlower++\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package app\n\nimport (\n\t\"errors\"\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/Tapjoy\/lane\"\n\t\"github.com\/hashicorp\/memberlist\"\n\t\"math\"\n\t\"math\/rand\"\n\t\"sort\"\n\t\"sync\"\n\t\"time\"\n)\n\ntype Partitions struct {\n\tpartitions     *lane.PQueue\n\tpartitionCount int\n\tsync.RWMutex\n}\n\ntype Partition struct {\n\tId       int\n\tLastUsed time.Time\n}\n\nfunc InitPartitions(cfg *Config, queueName string) *Partitions {\n\tpart := &Partitions{\n\t\tpartitions:     lane.NewPQueue(lane.MINPQ),\n\t\tpartitionCount: 0,\n\t}\n\t\/\/ We'll initially allocate the minimum amount\n\tminPartitions, _ := cfg.GetMinPartitions(queueName)\n\tpart.Lock()\n\tpart.makePartitions(cfg, queueName, minPartitions)\n\tpart.Unlock()\n\treturn part\n}\n\nfunc (part *Partitions) PartitionCount() int {\n\treturn part.partitionCount\n}\nfunc (part *Partitions) GetPartition(cfg *Config, queueName string, list *memberlist.Memberlist) (int, int, *Partition, error) {\n\n\t\/\/get the node position and the node count\n\tnodePosition, nodeCount := getNodePosition(list)\n\n\t\/\/calculate the range that our node is responsible for\n\tstep := math.MaxInt64 \/ nodeCount\n\tnodeBottom := nodePosition * step\n\tnodeTop := (nodePosition + 1) * step\n\tmyPartition, partition, totalPartitions, err := part.getPartitionPosition(cfg, queueName)\n\tif err != nil {\n\t\tlogrus.Println(err)\n\t}\n\n\t\/\/ calculate my range for the given number\n\tnode_range := nodeTop - nodeBottom\n\tnodeStep := node_range \/ totalPartitions\n\tpartitionBottom := nodeStep*myPartition + nodeBottom\n\tpartitionTop := nodeStep*(myPartition+1) + nodeBottom\n\treturn partitionBottom, partitionTop, partition, err\n}\n\n\/\/helper method to get the node position\nfunc getNodePosition(list *memberlist.Memberlist) (int, int) {\n\t\/\/ figure out which node we are\n\t\/\/ grab and sort the node names\n\tnodes := list.Members()\n\tvar nodeNames []string\n\tfor _, node := range nodes {\n\t\tnodeNames = append(nodeNames, node.Name)\n\t}\n\t\/\/ sort our nodes so that we have a canonical ordering\n\t\/\/ node failure will cause more dupes\n\tsort.Strings(nodeNames)\n\t\/\/ find our index position\n\tnodePosition := sort.SearchStrings(nodeNames, list.LocalNode().Name)\n\tnodeCount := len(nodeNames)\n\treturn nodePosition, nodeCount\n}\n\nfunc (part *Partitions) getPartitionPosition(cfg *Config, queueName string) (int, *Partition, int, error) {\n\t\/\/iterate over the partitions and then increase or decrease the number of partitions\n\n\t\/\/TODO move loging out of the sync operation for better throughput\n\tmyPartition := -1\n\n\tvar err error\n\tpoppedPartition, _ := part.partitions.Pop()\n\tvar workingPartition *Partition\n\tif poppedPartition != nil {\n\t\tworkingPartition = poppedPartition.(*Partition)\n\t} else {\n\t\t\/\/ this seems a little scary\n\t\treturn myPartition, workingPartition, part.partitionCount, errors.New(\"no available partitions\")\n\t}\n\tvisTimeout, _ := cfg.GetVisibilityTimeout(queueName)\n\tif time.Since(workingPartition.LastUsed).Seconds() > visTimeout {\n\t\tmyPartition = workingPartition.Id\n\t} else {\n\t\tpart.partitions.Push(workingPartition, workingPartition.LastUsed.UnixNano())\n\t\tpart.Lock()\n\t\tmaxPartitions, _ := cfg.GetMaxPartitions(queueName)\n\t\tif part.partitionCount < maxPartitions {\n\t\t\tworkingPartition := new(Partition)\n\t\t\tworkingPartition.Id = part.partitionCount\n\t\t\tmyPartition = workingPartition.Id\n\t\t\tpart.partitionCount = part.partitionCount + 1\n\t\t} else {\n\t\t\terr = errors.New(\"no available partitions\")\n\t\t}\n\t\tpart.Unlock()\n\t}\n\treturn myPartition, workingPartition, part.partitionCount, err\n}\nfunc (part *Partitions) PushPartition(cfg *Config, queueName string, partition *Partition, lock bool) {\n\tif lock {\n\t\tpartition.LastUsed = time.Now()\n\t\tpart.partitions.Push(partition, partition.LastUsed.UnixNano())\n\t} else {\n\t\tvisTimeout, _ := cfg.GetVisibilityTimeout(queueName)\n\t\tunlockTime := int(visTimeout)\n\t\tpartition.LastUsed = time.Now().Add(-(time.Duration(unlockTime) * time.Second))\n\t\tpart.partitions.Push(partition, partition.LastUsed.UnixNano())\n\t}\n}\n\nfunc (part *Partitions) makePartitions(cfg *Config, queueName string, partitionsToMake int) {\n\tvar initialTime time.Time\n\tmaxPartitions, _ := cfg.GetMaxPartitions(queueName)\n\toffset := part.partitionCount\n\tfor partitionId := offset; partitionId < offset+partitionsToMake; partitionId++ {\n\t\tif maxPartitions > partitionId {\n\t\t\tpartition := new(Partition)\n\t\t\tpartition.Id = partitionId\n\t\t\tpartition.LastUsed = initialTime\n\t\t\tpart.partitions.Push(partition, rand.Int63n(100000))\n\t\t\tpart.partitionCount = part.partitionCount + 1\n\t\t}\n\t}\n}\nfunc (part *Partitions) syncPartitions(cfg *Config, queueName string) {\n\n\tpart.Lock()\n\tmaxPartitions, _ := cfg.GetMaxPartitions(queueName)\n\tminPartitions, _ := cfg.GetMinPartitions(queueName)\n\tmaxPartitionAge, _ := cfg.GetMaxPartitionAge(queueName)\n\n\tvar partsRemoved int\n\tfor partsRemoved = 0; maxPartitions < part.partitionCount; partsRemoved++ {\n\t\t_, _ = part.partitions.Pop()\n\t}\n\tpart.partitionCount = part.partitionCount - partsRemoved\n\n\tif part.partitionCount < minPartitions {\n\t\tpart.makePartitions(cfg, queueName, minPartitions-part.partitionCount)\n\t}\n\n\t\/\/ Partition Aging logic\n\t\/\/ pop a partition\n\tvar workingPartition *Partition\n\tpoppedPartition, _ := part.partitions.Pop()\n\tif poppedPartition != nil {\n\t\tworkingPartition = poppedPartition.(*Partition)\n\t} else {\n\t\t\/\/ this seems a little scary. we do a similiar thing in getPartitionPosition\n\t\treturn\n\t}\n\tpart.partitionCount = part.partitionCount - 1\n\n\t\/\/ check if the partition is older than the max age ( but not a fresh partition )\n\t\/\/ if true pop the next partition, continue until this condition\n\tfor time.Since(workingPartition.LastUsed).Seconds() > maxPartitionAge && part.partitionCount >= minPartitions {\n\t\tpoppedPartition, _ = part.partitions.Pop()\n\t\tif poppedPartition != nil {\n\t\t\tworkingPartition = poppedPartition.(*Partition)\n\t\t}\n\t\tpart.partitionCount = part.partitionCount - 1\n\t}\n\t\/\/when false push the last popped partition\n\tpart.partitions.Push(workingPartition, workingPartition.LastUsed.UnixNano())\n\tpart.partitionCount = part.partitionCount + 1\n\tpart.Unlock()\n}\n<commit_msg>Fixing logrus print statement<commit_after>package app\n\nimport (\n\t\"errors\"\n\t\"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/Tapjoy\/lane\"\n\t\"github.com\/hashicorp\/memberlist\"\n\t\"math\"\n\t\"math\/rand\"\n\t\"sort\"\n\t\"sync\"\n\t\"time\"\n)\n\ntype Partitions struct {\n\tpartitions     *lane.PQueue\n\tpartitionCount int\n\tsync.RWMutex\n}\n\ntype Partition struct {\n\tId       int\n\tLastUsed time.Time\n}\n\nfunc InitPartitions(cfg *Config, queueName string) *Partitions {\n\tpart := &Partitions{\n\t\tpartitions:     lane.NewPQueue(lane.MINPQ),\n\t\tpartitionCount: 0,\n\t}\n\t\/\/ We'll initially allocate the minimum amount\n\tminPartitions, _ := cfg.GetMinPartitions(queueName)\n\tpart.Lock()\n\tpart.makePartitions(cfg, queueName, minPartitions)\n\tpart.Unlock()\n\treturn part\n}\n\nfunc (part *Partitions) PartitionCount() int {\n\treturn part.partitionCount\n}\nfunc (part *Partitions) GetPartition(cfg *Config, queueName string, list *memberlist.Memberlist) (int, int, *Partition, error) {\n\n\t\/\/get the node position and the node count\n\tnodePosition, nodeCount := getNodePosition(list)\n\n\t\/\/calculate the range that our node is responsible for\n\tstep := math.MaxInt64 \/ nodeCount\n\tnodeBottom := nodePosition * step\n\tnodeTop := (nodePosition + 1) * step\n\tmyPartition, partition, totalPartitions, err := part.getPartitionPosition(cfg, queueName)\n\tif err != nil {\n\t\tlogrus.Error(err)\n\t}\n\n\t\/\/ calculate my range for the given number\n\tnode_range := nodeTop - nodeBottom\n\tnodeStep := node_range \/ totalPartitions\n\tpartitionBottom := nodeStep*myPartition + nodeBottom\n\tpartitionTop := nodeStep*(myPartition+1) + nodeBottom\n\treturn partitionBottom, partitionTop, partition, err\n}\n\n\/\/helper method to get the node position\nfunc getNodePosition(list *memberlist.Memberlist) (int, int) {\n\t\/\/ figure out which node we are\n\t\/\/ grab and sort the node names\n\tnodes := list.Members()\n\tvar nodeNames []string\n\tfor _, node := range nodes {\n\t\tnodeNames = append(nodeNames, node.Name)\n\t}\n\t\/\/ sort our nodes so that we have a canonical ordering\n\t\/\/ node failure will cause more dupes\n\tsort.Strings(nodeNames)\n\t\/\/ find our index position\n\tnodePosition := sort.SearchStrings(nodeNames, list.LocalNode().Name)\n\tnodeCount := len(nodeNames)\n\treturn nodePosition, nodeCount\n}\n\nfunc (part *Partitions) getPartitionPosition(cfg *Config, queueName string) (int, *Partition, int, error) {\n\t\/\/iterate over the partitions and then increase or decrease the number of partitions\n\n\t\/\/TODO move loging out of the sync operation for better throughput\n\tmyPartition := -1\n\n\tvar err error\n\tpoppedPartition, _ := part.partitions.Pop()\n\tvar workingPartition *Partition\n\tif poppedPartition != nil {\n\t\tworkingPartition = poppedPartition.(*Partition)\n\t} else {\n\t\t\/\/ this seems a little scary\n\t\treturn myPartition, workingPartition, part.partitionCount, errors.New(\"no available partitions\")\n\t}\n\tvisTimeout, _ := cfg.GetVisibilityTimeout(queueName)\n\tif time.Since(workingPartition.LastUsed).Seconds() > visTimeout {\n\t\tmyPartition = workingPartition.Id\n\t} else {\n\t\tpart.partitions.Push(workingPartition, workingPartition.LastUsed.UnixNano())\n\t\tpart.Lock()\n\t\tmaxPartitions, _ := cfg.GetMaxPartitions(queueName)\n\t\tif part.partitionCount < maxPartitions {\n\t\t\tworkingPartition := new(Partition)\n\t\t\tworkingPartition.Id = part.partitionCount\n\t\t\tmyPartition = workingPartition.Id\n\t\t\tpart.partitionCount = part.partitionCount + 1\n\t\t} else {\n\t\t\terr = errors.New(\"no available partitions\")\n\t\t}\n\t\tpart.Unlock()\n\t}\n\treturn myPartition, workingPartition, part.partitionCount, err\n}\nfunc (part *Partitions) PushPartition(cfg *Config, queueName string, partition *Partition, lock bool) {\n\tif lock {\n\t\tpartition.LastUsed = time.Now()\n\t\tpart.partitions.Push(partition, partition.LastUsed.UnixNano())\n\t} else {\n\t\tvisTimeout, _ := cfg.GetVisibilityTimeout(queueName)\n\t\tunlockTime := int(visTimeout)\n\t\tpartition.LastUsed = time.Now().Add(-(time.Duration(unlockTime) * time.Second))\n\t\tpart.partitions.Push(partition, partition.LastUsed.UnixNano())\n\t}\n}\n\nfunc (part *Partitions) makePartitions(cfg *Config, queueName string, partitionsToMake int) {\n\tvar initialTime time.Time\n\tmaxPartitions, _ := cfg.GetMaxPartitions(queueName)\n\toffset := part.partitionCount\n\tfor partitionId := offset; partitionId < offset+partitionsToMake; partitionId++ {\n\t\tif maxPartitions > partitionId {\n\t\t\tpartition := new(Partition)\n\t\t\tpartition.Id = partitionId\n\t\t\tpartition.LastUsed = initialTime\n\t\t\tpart.partitions.Push(partition, rand.Int63n(100000))\n\t\t\tpart.partitionCount = part.partitionCount + 1\n\t\t}\n\t}\n}\nfunc (part *Partitions) syncPartitions(cfg *Config, queueName string) {\n\n\tpart.Lock()\n\tmaxPartitions, _ := cfg.GetMaxPartitions(queueName)\n\tminPartitions, _ := cfg.GetMinPartitions(queueName)\n\tmaxPartitionAge, _ := cfg.GetMaxPartitionAge(queueName)\n\n\tvar partsRemoved int\n\tfor partsRemoved = 0; maxPartitions < part.partitionCount; partsRemoved++ {\n\t\t_, _ = part.partitions.Pop()\n\t}\n\tpart.partitionCount = part.partitionCount - partsRemoved\n\n\tif part.partitionCount < minPartitions {\n\t\tpart.makePartitions(cfg, queueName, minPartitions-part.partitionCount)\n\t}\n\n\t\/\/ Partition Aging logic\n\t\/\/ pop a partition\n\tvar workingPartition *Partition\n\tpoppedPartition, _ := part.partitions.Pop()\n\tif poppedPartition != nil {\n\t\tworkingPartition = poppedPartition.(*Partition)\n\t} else {\n\t\t\/\/ this seems a little scary. we do a similiar thing in getPartitionPosition\n\t\treturn\n\t}\n\tpart.partitionCount = part.partitionCount - 1\n\n\t\/\/ check if the partition is older than the max age ( but not a fresh partition )\n\t\/\/ if true pop the next partition, continue until this condition\n\tfor time.Since(workingPartition.LastUsed).Seconds() > maxPartitionAge && part.partitionCount >= minPartitions {\n\t\tpoppedPartition, _ = part.partitions.Pop()\n\t\tif poppedPartition != nil {\n\t\t\tworkingPartition = poppedPartition.(*Partition)\n\t\t}\n\t\tpart.partitionCount = part.partitionCount - 1\n\t}\n\t\/\/when false push the last popped partition\n\tpart.partitions.Push(workingPartition, workingPartition.LastUsed.UnixNano())\n\tpart.partitionCount = part.partitionCount + 1\n\tpart.Unlock()\n}\n<|endoftext|>"}
{"text":"<commit_before>package providers\n\nimport (\n\t\"os\"\n\t\"strings\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/camptocamp\/conplicity\/handler\"\n\t\"github.com\/fgrehm\/go-dockerpty\"\n\t\"github.com\/fsouza\/go-dockerclient\"\n)\n\ntype Provider interface {\n\tGetName() string\n\tGetHandler() *handler.Conplicity\n\tGetBackupDir() string\n\tPrepareBackup() error\n}\n\nfunc GetProvider(c *handler.Conplicity, v *docker.Volume) Provider {\n\tlog.Infof(\"Detecting provider for volume %v\", v.Name)\n\tif f, err := os.Stat(v.Mountpoint + \"\/PG_VERSION\"); err == nil && f.Mode().IsRegular() {\n\t\tlog.Infof(\"PG_VERSION file found, this should be a PostgreSQL datadir\")\n\t\treturn &PostgreSQLProvider{\n\t\t\thandler: c,\n\t\t\tvol:     v,\n\t\t}\n\t} else if f, err := os.Stat(v.Mountpoint + \"\/mysql\"); err == nil && f.Mode().IsDir() {\n\t\tlog.Infof(\"mysql directory found, this should be MySQL datadir\")\n\t\treturn &MySQLProvider{\n\t\t\thandler: c,\n\t\t\tvol:     v,\n\t\t}\n\t} else if f, err := os.Stat(v.Mountpoint + \"\/DB_CONFIG\"); err == nil && f.Mode().IsRegular() {\n\t\tlog.Infof(\"DB_CONFIG file found, this should be and OpenLDAP datadir\")\n\t\treturn &OpenLDAPProvider{\n\t\t\thandler: c,\n\t\t\tvol:     v,\n\t\t}\n\t} else {\n\t\treturn &DefaultProvider{\n\t\t\thandler: c,\n\t\t\tvol:     v,\n\t\t}\n\t}\n}\n\nfunc BackupVolume(p Provider, vol *docker.Volume) (err error) {\n\tlog.Infof(\"ID: \" + vol.Name)\n\tlog.Infof(\"Driver: \" + vol.Driver)\n\tlog.Infof(\"Mountpoint: \" + vol.Mountpoint)\n\n\tlog.Infof(\"Creating duplicity container...\")\n\n\tc := p.GetHandler()\n\n\tfullIfOlderThan := getVolumeLabel(vol, \".full_if_older_than\")\n\tif fullIfOlderThan == \"\" {\n\t\tfullIfOlderThan = c.FullIfOlderThan\n\t}\n\n\tpathSeparator := \"\/\"\n\tif strings.HasPrefix(c.DuplicityTargetURL, \"swift:\/\/\") {\n\t\t\/\/ Looks like I'm not the one to fall on this issue: http:\/\/stackoverflow.com\/questions\/27991960\/upload-to-swift-pseudo-folders-using-duplicity\n\t\tpathSeparator = \"_\"\n\t}\n\n\tbackupDir := p.GetBackupDir()\n\n\tcontainer, err := c.CreateContainer(\n\t\tdocker.CreateContainerOptions{\n\t\t\tConfig: &docker.Config{\n\t\t\t\tCmd: []string{\n\t\t\t\t\t\"--full-if-older-than\", fullIfOlderThan,\n\t\t\t\t\t\"--s3-use-new-style\",\n\t\t\t\t\t\"--no-encryption\",\n\t\t\t\t\t\"--allow-source-mismatch\",\n\t\t\t\t\tvol.Mountpoint + \"\/\" + backupDir,\n\t\t\t\t\tc.DuplicityTargetURL + pathSeparator + c.Hostname + pathSeparator + vol.Name,\n\t\t\t\t},\n\t\t\t\tEnv: []string{\n\t\t\t\t\t\"AWS_ACCESS_KEY_ID=\" + c.AWSAccessKeyID,\n\t\t\t\t\t\"AWS_SECRET_ACCESS_KEY=\" + c.AWSSecretAccessKey,\n\t\t\t\t\t\"SWIFT_USERNAME=\" + c.SwiftUsername,\n\t\t\t\t\t\"SWIFT_PASSWORD=\" + c.SwiftPassword,\n\t\t\t\t\t\"SWIFT_AUTHURL=\" + c.SwiftAuthURL,\n\t\t\t\t\t\"SWIFT_TENANTNAME=\" + c.SwiftTenantName,\n\t\t\t\t\t\"SWIFT_REGIONNAME=\" + c.SwiftRegionName,\n\t\t\t\t\t\"SWIFT_AUTHVERSION=2\",\n\t\t\t\t},\n\t\t\t\tImage:        c.Image,\n\t\t\t\tOpenStdin:    true,\n\t\t\t\tStdinOnce:    true,\n\t\t\t\tAttachStdin:  true,\n\t\t\t\tAttachStdout: true,\n\t\t\t\tAttachStderr: true,\n\t\t\t\tTty:          true,\n\t\t\t},\n\t\t},\n\t)\n\n\tcheckErr(err, \"Failed to create container for volume \"+vol.Name+\": %v\", 1)\n\n\tdefer func() {\n\t\tc.RemoveContainer(docker.RemoveContainerOptions{\n\t\t\tID:    container.ID,\n\t\t\tForce: true,\n\t\t})\n\t}()\n\n\tbinds := []string{\n\t\tvol.Name + \":\" + vol.Mountpoint + \":ro\",\n\t}\n\n\terr = dockerpty.Start(c.Client, container, &docker.HostConfig{\n\t\tBinds: binds,\n\t})\n\tcheckErr(err, \"Failed to start container for volume \"+vol.Name+\": %v\", -1)\n\treturn\n\treturn nil\n}\n\nfunc checkErr(err error, msg string, exit int) {\n\tif err != nil {\n\t\tlog.Errorf(msg, err)\n\n\t\tif exit != -1 {\n\t\t\tos.Exit(exit)\n\t\t}\n\t}\n}\n\nfunc getVolumeLabel(vol *docker.Volume, key string) (value string) {\n\tvalue = vol.Labels[labelPrefix+key]\n\treturn\n}\n<commit_msg>Persist duplicity cache (Fixes #12)<commit_after>package providers\n\nimport (\n\t\"os\"\n\t\"strings\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/camptocamp\/conplicity\/handler\"\n\t\"github.com\/fgrehm\/go-dockerpty\"\n\t\"github.com\/fsouza\/go-dockerclient\"\n)\n\ntype Provider interface {\n\tGetName() string\n\tGetHandler() *handler.Conplicity\n\tGetBackupDir() string\n\tPrepareBackup() error\n}\n\nfunc GetProvider(c *handler.Conplicity, v *docker.Volume) Provider {\n\tlog.Infof(\"Detecting provider for volume %v\", v.Name)\n\tif f, err := os.Stat(v.Mountpoint + \"\/PG_VERSION\"); err == nil && f.Mode().IsRegular() {\n\t\tlog.Infof(\"PG_VERSION file found, this should be a PostgreSQL datadir\")\n\t\treturn &PostgreSQLProvider{\n\t\t\thandler: c,\n\t\t\tvol:     v,\n\t\t}\n\t} else if f, err := os.Stat(v.Mountpoint + \"\/mysql\"); err == nil && f.Mode().IsDir() {\n\t\tlog.Infof(\"mysql directory found, this should be MySQL datadir\")\n\t\treturn &MySQLProvider{\n\t\t\thandler: c,\n\t\t\tvol:     v,\n\t\t}\n\t} else if f, err := os.Stat(v.Mountpoint + \"\/DB_CONFIG\"); err == nil && f.Mode().IsRegular() {\n\t\tlog.Infof(\"DB_CONFIG file found, this should be and OpenLDAP datadir\")\n\t\treturn &OpenLDAPProvider{\n\t\t\thandler: c,\n\t\t\tvol:     v,\n\t\t}\n\t} else {\n\t\treturn &DefaultProvider{\n\t\t\thandler: c,\n\t\t\tvol:     v,\n\t\t}\n\t}\n}\n\nfunc BackupVolume(p Provider, vol *docker.Volume) (err error) {\n\tlog.Infof(\"ID: \" + vol.Name)\n\tlog.Infof(\"Driver: \" + vol.Driver)\n\tlog.Infof(\"Mountpoint: \" + vol.Mountpoint)\n\n\tlog.Infof(\"Creating duplicity container...\")\n\n\tc := p.GetHandler()\n\n\tfullIfOlderThan := getVolumeLabel(vol, \".full_if_older_than\")\n\tif fullIfOlderThan == \"\" {\n\t\tfullIfOlderThan = c.FullIfOlderThan\n\t}\n\n\tpathSeparator := \"\/\"\n\tif strings.HasPrefix(c.DuplicityTargetURL, \"swift:\/\/\") {\n\t\t\/\/ Looks like I'm not the one to fall on this issue: http:\/\/stackoverflow.com\/questions\/27991960\/upload-to-swift-pseudo-folders-using-duplicity\n\t\tpathSeparator = \"_\"\n\t}\n\n\tbackupDir := p.GetBackupDir()\n\n\tcontainer, err := c.CreateContainer(\n\t\tdocker.CreateContainerOptions{\n\t\t\tConfig: &docker.Config{\n\t\t\t\tCmd: []string{\n\t\t\t\t\t\"--full-if-older-than\", fullIfOlderThan,\n\t\t\t\t\t\"--s3-use-new-style\",\n\t\t\t\t\t\"--no-encryption\",\n\t\t\t\t\t\"--allow-source-mismatch\",\n\t\t\t\t\tvol.Mountpoint + \"\/\" + backupDir,\n\t\t\t\t\tc.DuplicityTargetURL + pathSeparator + c.Hostname + pathSeparator + vol.Name,\n\t\t\t\t},\n\t\t\t\tEnv: []string{\n\t\t\t\t\t\"AWS_ACCESS_KEY_ID=\" + c.AWSAccessKeyID,\n\t\t\t\t\t\"AWS_SECRET_ACCESS_KEY=\" + c.AWSSecretAccessKey,\n\t\t\t\t\t\"SWIFT_USERNAME=\" + c.SwiftUsername,\n\t\t\t\t\t\"SWIFT_PASSWORD=\" + c.SwiftPassword,\n\t\t\t\t\t\"SWIFT_AUTHURL=\" + c.SwiftAuthURL,\n\t\t\t\t\t\"SWIFT_TENANTNAME=\" + c.SwiftTenantName,\n\t\t\t\t\t\"SWIFT_REGIONNAME=\" + c.SwiftRegionName,\n\t\t\t\t\t\"SWIFT_AUTHVERSION=2\",\n\t\t\t\t},\n\t\t\t\tImage:        c.Image,\n\t\t\t\tOpenStdin:    true,\n\t\t\t\tStdinOnce:    true,\n\t\t\t\tAttachStdin:  true,\n\t\t\t\tAttachStdout: true,\n\t\t\t\tAttachStderr: true,\n\t\t\t\tTty:          true,\n\t\t\t},\n\t\t},\n\t)\n\n\tcheckErr(err, \"Failed to create container for volume \"+vol.Name+\": %v\", 1)\n\n\tdefer func() {\n\t\tc.RemoveContainer(docker.RemoveContainerOptions{\n\t\t\tID:    container.ID,\n\t\t\tForce: true,\n\t\t})\n\t}()\n\n\tbinds := []string{\n\t\tvol.Name + \":\" + vol.Mountpoint + \":ro\",\n\t\t\"duplicity_cache:\/root\/.cache\/duplicity\",\n\t}\n\n\terr = dockerpty.Start(c.Client, container, &docker.HostConfig{\n\t\tBinds: binds,\n\t})\n\tcheckErr(err, \"Failed to start container for volume \"+vol.Name+\": %v\", -1)\n\treturn\n\treturn nil\n}\n\nfunc checkErr(err error, msg string, exit int) {\n\tif err != nil {\n\t\tlog.Errorf(msg, err)\n\n\t\tif exit != -1 {\n\t\t\tos.Exit(exit)\n\t\t}\n\t}\n}\n\nfunc getVolumeLabel(vol *docker.Volume, key string) (value string) {\n\tvalue = vol.Labels[labelPrefix+key]\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>\/*\nCopyright 2018 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage patch\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\n\t\"github.com\/evanphx\/json-patch\"\n\t\"k8s.io\/apimachinery\/pkg\/runtime\"\n\t\"k8s.io\/apimachinery\/pkg\/runtime\/schema\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/strategicpatch\"\n\t\"k8s.io\/client-go\/kubernetes\/scheme\"\n\t\"sigs.k8s.io\/kustomize\/pkg\/gvk\"\n\t\"sigs.k8s.io\/kustomize\/pkg\/resmap\"\n\t\"sigs.k8s.io\/kustomize\/pkg\/resource\"\n\t\"sigs.k8s.io\/kustomize\/pkg\/transformers\"\n)\n\n\/\/ patchTransformer applies patches.\ntype patchTransformer struct {\n\tpatches []*resource.Resource\n\trf      *resource.Factory\n}\n\nvar _ transformers.Transformer = &patchTransformer{}\n\n\/\/ NewPatchTransformer constructs a patchTransformer.\nfunc NewPatchTransformer(\n\tslice []*resource.Resource, rf *resource.Factory) (transformers.Transformer, error) {\n\tif len(slice) == 0 {\n\t\treturn transformers.NewNoOpTransformer(), nil\n\t}\n\treturn &patchTransformer{patches: slice, rf: rf}, nil\n}\n\n\/\/ Transform apply the patches on top of the base resources.\nfunc (pt *patchTransformer) Transform(baseResourceMap resmap.ResMap) error {\n\t\/\/ Merge and then index the patches by Id.\n\tpatches, err := pt.mergePatches()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Strategic merge the resources exist in both base and patches.\n\tfor _, patch := range patches {\n\t\t\/\/ Merge patches with base resource.\n\t\tid := patch.Id()\n\t\tmatchedIds := baseResourceMap.FindByGVKN(id)\n\t\tif len(matchedIds) == 0 {\n\t\t\treturn fmt.Errorf(\"failed to find an object with %#v to apply the patch\", id.Gvk())\n\t\t}\n\t\tif len(matchedIds) > 1 {\n\t\t\treturn fmt.Errorf(\"found multiple objects %#v targeted by patch %#v (ambiguous)\", matchedIds, id)\n\t\t}\n\t\tid = matchedIds[0]\n\t\tbase := baseResourceMap[id]\n\t\tmerged := map[string]interface{}{}\n\t\tversionedObj, err := scheme.Scheme.New(toSchemaGvk(id.Gvk()))\n\t\tbaseName := base.GetName()\n\t\tswitch {\n\t\tcase runtime.IsNotRegisteredError(err):\n\t\t\t\/\/ Use JSON merge patch to handle types w\/o schema\n\t\t\tbaseBytes, err := json.Marshal(base.Map())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tpatchBytes, err := json.Marshal(patch.Map())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tmergedBytes, err := jsonpatch.MergePatch(baseBytes, patchBytes)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\terr = json.Unmarshal(mergedBytes, &merged)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase err != nil:\n\t\t\treturn err\n\t\tdefault:\n\t\t\t\/\/ Use Strategic-Merge-Patch to handle types w\/ schema\n\t\t\t\/\/ TODO: Change this to use the new Merge package.\n\t\t\t\/\/ Store the name of the base object, because this name may have been munged.\n\t\t\t\/\/ Apply this name to the patched object.\n\t\t\tlookupPatchMeta, err := strategicpatch.NewPatchMetaFromStruct(versionedObj)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tmerged, err = strategicpatch.StrategicMergeMapPatchUsingLookupPatchMeta(\n\t\t\t\tbase.Map(),\n\t\t\t\tpatch.Map(),\n\t\t\t\tlookupPatchMeta)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tbase.SetName(baseName)\n\t\tbaseResourceMap[id].SetMap(merged)\n\t}\n\treturn nil\n}\n\n\/\/ mergePatches merge and index patches by Id.\n\/\/ It errors out if there is conflict between patches.\nfunc (pt *patchTransformer) mergePatches() (resmap.ResMap, error) {\n\trc := resmap.ResMap{}\n\tfor ix, patch := range pt.patches {\n\t\tid := patch.Id()\n\t\texisting, found := rc[id]\n\t\tif !found {\n\t\t\trc[id] = patch\n\t\t\tcontinue\n\t\t}\n\n\t\tversionedObj, err := scheme.Scheme.New(toSchemaGvk(id.Gvk()))\n\t\tif err != nil && !runtime.IsNotRegisteredError(err) {\n\t\t\treturn nil, err\n\t\t}\n\t\tvar cd conflictDetector\n\t\tif err != nil {\n\t\t\tcd = newJMPConflictDetector(pt.rf)\n\t\t} else {\n\t\t\tcd, err = newSMPConflictDetector(versionedObj, pt.rf)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\tconflict, err := cd.hasConflict(existing, patch)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif conflict {\n\t\t\tconflictingPatch, err := cd.findConflict(ix, pt.patches)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\"conflict between %#v and %#v\",\n\t\t\t\tconflictingPatch.Map(), patch.Map())\n\t\t}\n\t\tmerged, err := cd.mergePatches(existing, patch)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trc[id] = merged\n\t}\n\treturn rc, nil\n}\n\n\/\/ toSchemaGvk converts to a schema.GroupVersionKind.\nfunc toSchemaGvk(x gvk.Gvk) schema.GroupVersionKind {\n\treturn schema.GroupVersionKind{\n\t\tGroup:   x.Group,\n\t\tVersion: x.Version,\n\t\tKind:    x.Kind,\n\t}\n}\n<commit_msg>improve error message when failing to find an object to patch<commit_after>\/*\nCopyright 2018 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage patch\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\n\t\"github.com\/evanphx\/json-patch\"\n\t\"k8s.io\/apimachinery\/pkg\/runtime\"\n\t\"k8s.io\/apimachinery\/pkg\/runtime\/schema\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/strategicpatch\"\n\t\"k8s.io\/client-go\/kubernetes\/scheme\"\n\t\"sigs.k8s.io\/kustomize\/pkg\/gvk\"\n\t\"sigs.k8s.io\/kustomize\/pkg\/resmap\"\n\t\"sigs.k8s.io\/kustomize\/pkg\/resource\"\n\t\"sigs.k8s.io\/kustomize\/pkg\/transformers\"\n)\n\n\/\/ patchTransformer applies patches.\ntype patchTransformer struct {\n\tpatches []*resource.Resource\n\trf      *resource.Factory\n}\n\nvar _ transformers.Transformer = &patchTransformer{}\n\n\/\/ NewPatchTransformer constructs a patchTransformer.\nfunc NewPatchTransformer(\n\tslice []*resource.Resource, rf *resource.Factory) (transformers.Transformer, error) {\n\tif len(slice) == 0 {\n\t\treturn transformers.NewNoOpTransformer(), nil\n\t}\n\treturn &patchTransformer{patches: slice, rf: rf}, nil\n}\n\n\/\/ Transform apply the patches on top of the base resources.\nfunc (pt *patchTransformer) Transform(baseResourceMap resmap.ResMap) error {\n\t\/\/ Merge and then index the patches by Id.\n\tpatches, err := pt.mergePatches()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Strategic merge the resources exist in both base and patches.\n\tfor _, patch := range patches {\n\t\t\/\/ Merge patches with base resource.\n\t\tid := patch.Id()\n\t\tmatchedIds := baseResourceMap.FindByGVKN(id)\n\t\tif len(matchedIds) == 0 {\n\t\t\treturn fmt.Errorf(\"failed to find an object with %s to apply the patch\", id.GvknString())\n\t\t}\n\t\tif len(matchedIds) > 1 {\n\t\t\treturn fmt.Errorf(\"found multiple objects %#v targeted by patch %#v (ambiguous)\", matchedIds, id)\n\t\t}\n\t\tid = matchedIds[0]\n\t\tbase := baseResourceMap[id]\n\t\tmerged := map[string]interface{}{}\n\t\tversionedObj, err := scheme.Scheme.New(toSchemaGvk(id.Gvk()))\n\t\tbaseName := base.GetName()\n\t\tswitch {\n\t\tcase runtime.IsNotRegisteredError(err):\n\t\t\t\/\/ Use JSON merge patch to handle types w\/o schema\n\t\t\tbaseBytes, err := json.Marshal(base.Map())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tpatchBytes, err := json.Marshal(patch.Map())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tmergedBytes, err := jsonpatch.MergePatch(baseBytes, patchBytes)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\terr = json.Unmarshal(mergedBytes, &merged)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase err != nil:\n\t\t\treturn err\n\t\tdefault:\n\t\t\t\/\/ Use Strategic-Merge-Patch to handle types w\/ schema\n\t\t\t\/\/ TODO: Change this to use the new Merge package.\n\t\t\t\/\/ Store the name of the base object, because this name may have been munged.\n\t\t\t\/\/ Apply this name to the patched object.\n\t\t\tlookupPatchMeta, err := strategicpatch.NewPatchMetaFromStruct(versionedObj)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tmerged, err = strategicpatch.StrategicMergeMapPatchUsingLookupPatchMeta(\n\t\t\t\tbase.Map(),\n\t\t\t\tpatch.Map(),\n\t\t\t\tlookupPatchMeta)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tbase.SetName(baseName)\n\t\tbaseResourceMap[id].SetMap(merged)\n\t}\n\treturn nil\n}\n\n\/\/ mergePatches merge and index patches by Id.\n\/\/ It errors out if there is conflict between patches.\nfunc (pt *patchTransformer) mergePatches() (resmap.ResMap, error) {\n\trc := resmap.ResMap{}\n\tfor ix, patch := range pt.patches {\n\t\tid := patch.Id()\n\t\texisting, found := rc[id]\n\t\tif !found {\n\t\t\trc[id] = patch\n\t\t\tcontinue\n\t\t}\n\n\t\tversionedObj, err := scheme.Scheme.New(toSchemaGvk(id.Gvk()))\n\t\tif err != nil && !runtime.IsNotRegisteredError(err) {\n\t\t\treturn nil, err\n\t\t}\n\t\tvar cd conflictDetector\n\t\tif err != nil {\n\t\t\tcd = newJMPConflictDetector(pt.rf)\n\t\t} else {\n\t\t\tcd, err = newSMPConflictDetector(versionedObj, pt.rf)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\tconflict, err := cd.hasConflict(existing, patch)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif conflict {\n\t\t\tconflictingPatch, err := cd.findConflict(ix, pt.patches)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\n\t\t\t\t\"conflict between %#v and %#v\",\n\t\t\t\tconflictingPatch.Map(), patch.Map())\n\t\t}\n\t\tmerged, err := cd.mergePatches(existing, patch)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\trc[id] = merged\n\t}\n\treturn rc, nil\n}\n\n\/\/ toSchemaGvk converts to a schema.GroupVersionKind.\nfunc toSchemaGvk(x gvk.Gvk) schema.GroupVersionKind {\n\treturn schema.GroupVersionKind{\n\t\tGroup:   x.Group,\n\t\tVersion: x.Version,\n\t\tKind:    x.Kind,\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package command\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"net\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com\/funkygao\/gafka\/ctx\"\n\t\"github.com\/funkygao\/gafka\/zk\"\n\t\"github.com\/funkygao\/gocli\"\n\t\"github.com\/funkygao\/golib\/color\"\n\t\"github.com\/funkygao\/golib\/pipestream\"\n\tconsulapi \"github.com\/hashicorp\/consul\/api\"\n\t\"github.com\/ryanuber\/columnize\"\n)\n\n\/\/ consul members will include:\n\/\/ - zk cluster as server\n\/\/ - agents\n\/\/   - brokers\n\/\/   - kateway\ntype Members struct {\n\tUi  cli.Ui\n\tCmd string\n\n\tbrokerHosts, zkHosts, katewayHosts map[string]struct{}\n\tnodeHostMap                        map[string]string \/\/ consul members node->ip\n}\n\nfunc (this *Members) Run(args []string) (exitCode int) {\n\tvar (\n\t\tzone        string\n\t\tshowLoadAvg bool\n\t\texec        string\n\t\tnode        string\n\t\trole        string\n\t)\n\tcmdFlags := flag.NewFlagSet(\"members\", flag.ContinueOnError)\n\tcmdFlags.Usage = func() { this.Ui.Output(this.Help()) }\n\tcmdFlags.StringVar(&zone, \"z\", ctx.ZkDefaultZone(), \"\")\n\tcmdFlags.BoolVar(&showLoadAvg, \"l\", false, \"\")\n\tcmdFlags.StringVar(&exec, \"exec\", \"\", \"\")\n\tcmdFlags.StringVar(&node, \"n\", \"\", \"\")\n\tcmdFlags.StringVar(&role, \"r\", \"\", \"\")\n\tif err := cmdFlags.Parse(args); err != nil {\n\t\treturn 1\n\t}\n\n\tif validateArgs(this, this.Ui).\n\t\trequireAdminRights(\"-exec\").\n\t\tinvalid(args) {\n\t\treturn 2\n\t}\n\n\tzkzone := zk.NewZkZone(zk.DefaultConfig(zone, ctx.ZoneZkAddrs(zone)))\n\tthis.fetchAllRunningHostsFromZk(zkzone)\n\n\tmembers := this.consulMembers()\n\tconsulLiveNode := make([]string, 0, len(members))\n\tfor _, member := range members {\n\t\tif member.Status == 1 {\n\t\t\tconsulLiveNode = append(consulLiveNode, member.Addr)\n\t\t} else {\n\t\t\tthis.Ui.Warn(fmt.Sprintf(\"%s %s status:%d\", member.Name, member.Addr, member.Status))\n\t\t}\n\t}\n\n\tconsulLiveMap := make(map[string]struct{})\n\tbrokerN, zkN, katewayN, unknownN := 0, 0, 0, 0\n\tfor _, node := range consulLiveNode {\n\t\t_, presentInBroker := this.brokerHosts[node]\n\t\t_, presentInZk := this.zkHosts[node]\n\t\t_, presentInKateway := this.katewayHosts[node]\n\t\tif presentInBroker {\n\t\t\tbrokerN++\n\t\t}\n\t\tif presentInZk {\n\t\t\tzkN++\n\t\t}\n\t\tif presentInKateway {\n\t\t\tkatewayN++\n\t\t}\n\n\t\tif !presentInBroker && !presentInZk && !presentInKateway {\n\t\t\tunknownN++\n\t\t}\n\n\t\tconsulLiveMap[node] = struct{}{}\n\t}\n\n\t\/\/ all brokers should run consul\n\tfor broker, _ := range this.brokerHosts {\n\t\tif _, present := consulLiveMap[broker]; !present {\n\t\t\tthis.Ui.Warn(fmt.Sprintf(\"- %s\", broker))\n\t\t}\n\t}\n\n\tswitch {\n\tcase showLoadAvg:\n\t\tthis.displayLoadAvg(role)\n\n\tcase exec != \"\":\n\t\tthis.executeOnAll(exec, role, node)\n\n\tdefault:\n\t\tthis.displayMembers(members, role)\n\t}\n\n\t\/\/ summary\n\tthis.Ui.Output(fmt.Sprintf(\"Zk:%d Broker:%d Kateway:%d ?:%s => %d\",\n\t\tzkN, brokerN, katewayN, color.Yellow(\"%d\", unknownN), zkN+brokerN+katewayN+unknownN))\n\n\treturn\n}\n\nfunc (this *Members) fetchAllRunningHostsFromZk(zkzone *zk.ZkZone) {\n\tthis.brokerHosts = make(map[string]struct{})\n\tzkzone.ForSortedBrokers(func(cluster string, brokers map[string]*zk.BrokerZnode) {\n\t\tfor _, brokerInfo := range brokers {\n\t\t\tthis.brokerHosts[brokerInfo.Host] = struct{}{}\n\t\t}\n\t})\n\n\tthis.zkHosts = make(map[string]struct{})\n\tfor _, addr := range zkzone.ZkAddrList() {\n\t\tzkNode, _, err := net.SplitHostPort(addr)\n\t\tswallow(err)\n\t\tthis.zkHosts[zkNode] = struct{}{}\n\t}\n\n\tthis.katewayHosts = make(map[string]struct{})\n\tkws, err := zkzone.KatewayInfos()\n\tswallow(err)\n\tfor _, kw := range kws {\n\t\thost, _, err := net.SplitHostPort(kw.PubAddr)\n\t\tswallow(err)\n\t\tthis.katewayHosts[host] = struct{}{}\n\t}\n}\n\n\/\/ TODO role is ignored\nfunc (this *Members) executeOnAll(execCmd string, role string, node string) {\n\targs := []string{\"exec\"}\n\tif node != \"\" {\n\t\targs = append(args, fmt.Sprintf(\"-node=%s\", node))\n\t}\n\targs = append(args, strings.Split(execCmd, \" \")...)\n\tcmd := pipestream.New(\"consul\", args...)\n\terr := cmd.Open()\n\tswallow(err)\n\tdefer cmd.Close()\n\n\tthis.Ui.Info(fmt.Sprintf(\"%s ...\", execCmd))\n\n\tlines := make([]string, 0)\n\theader := \"Node|Host|Role|Result\"\n\tlines = append(lines, header)\n\n\tscanner := bufio.NewScanner(cmd.Reader())\n\tscanner.Split(bufio.ScanLines)\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tif strings.Contains(line, \"finished with exit code 0\") ||\n\t\t\tstrings.Contains(line, \"completed \/ acknowledged\") {\n\t\t\tcontinue\n\t\t}\n\t\tfields := strings.Fields(line)\n\t\tif len(fields) == 1 {\n\t\t\tcontinue\n\t\t}\n\n\t\tnode := fields[0]\n\t\tif strings.HasSuffix(node, \":\") {\n\t\t\tnode = strings.TrimRight(node, \":\")\n\t\t}\n\n\t\thost := this.nodeHostMap[node]\n\t\tlines = append(lines, fmt.Sprintf(\"%s|%s|%s|%s\", node, host, this.roleOfHost(host),\n\t\t\tstrings.Join(fields[1:], \" \")))\n\t}\n\n\tif len(lines) > 1 {\n\t\tsort.Strings(lines[1:])\n\t\tthis.Ui.Output(columnize.SimpleFormat(lines))\n\t}\n}\n\nfunc (this *Members) displayMembers(members []*consulapi.AgentMember, role string) {\n\tlines := make([]string, 0)\n\theader := \"Node|Host|Role\"\n\tlines = append(lines, header)\n\tfor _, member := range members {\n\t\thostRole := this.roleOfHost(member.Addr)\n\t\tif role != \"\" && role != hostRole {\n\t\t\tcontinue\n\t\t}\n\n\t\tlines = append(lines, fmt.Sprintf(\"%s|%s|%s\", member.Name, member.Addr, hostRole))\n\t}\n\n\tif len(lines) > 1 {\n\t\tsort.Strings(lines[1:])\n\t\tthis.Ui.Output(columnize.SimpleFormat(lines))\n\t}\n}\n\nfunc (this *Members) displayLoadAvg(role string) {\n\tcmd := pipestream.New(\"consul\", \"exec\",\n\t\t\"uptime\", \"|\", \"grep\", \"load\")\n\terr := cmd.Open()\n\tswallow(err)\n\tdefer cmd.Close()\n\n\tlines := make([]string, 0)\n\theader := \"Node|Host|Role|Load Avg\"\n\tlines = append(lines, header)\n\n\tscanner := bufio.NewScanner(cmd.Reader())\n\tscanner.Split(bufio.ScanLines)\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tfields := strings.Fields(line)\n\t\tnode := fields[0]\n\t\tparts := strings.Split(line, \"load average:\")\n\t\tif len(parts) < 2 {\n\t\t\tcontinue\n\t\t}\n\t\tif strings.HasSuffix(node, \":\") {\n\t\t\tnode = strings.TrimRight(node, \":\")\n\t\t}\n\n\t\tloadAvg := strings.TrimSpace(parts[1])\n\t\tif loadAvg[0] > '0' {\n\t\t\tloadAvg += \" !\"\n\t\t\tif loadAvg[0] > '1' {\n\t\t\t\tloadAvg += \"!\"\n\t\t\t}\n\t\t}\n\n\t\thost := this.nodeHostMap[node]\n\t\thostRole := this.roleOfHost(host)\n\t\tif role != \"\" && hostRole != role {\n\t\t\tcontinue\n\t\t}\n\n\t\tlines = append(lines, fmt.Sprintf(\"%s|%s|%s|%s\", node, host, hostRole, loadAvg))\n\t}\n\n\tif len(lines) > 1 {\n\t\tsort.Strings(lines[1:])\n\t\tthis.Ui.Output(columnize.SimpleFormat(lines))\n\t}\n}\n\nfunc (this *Members) roleOfHost(host string) string {\n\tif _, present := this.brokerHosts[host]; present {\n\t\treturn \"B\"\n\t}\n\tif _, present := this.zkHosts[host]; present {\n\t\treturn \"Z\"\n\t}\n\tif _, present := this.katewayHosts[host]; present {\n\t\treturn \"K\"\n\t}\n\treturn \"?\"\n}\n\nfunc (this *Members) consulMembers() []*consulapi.AgentMember {\n\tcf := consulapi.DefaultConfig()\n\tclient, err := consulapi.NewClient(cf)\n\tswallow(err)\n\tmembers, err := client.Agent().Members(false)\n\tswallow(err)\n\n\tm := make(map[string]*consulapi.AgentMember, len(members))\n\tsortedName := make([]string, 0, len(members))\n\tthis.nodeHostMap = make(map[string]string, len(members))\n\tfor _, member := range members {\n\t\tm[member.Name] = member\n\t\tthis.nodeHostMap[member.Name] = member.Addr\n\n\t\tsortedName = append(sortedName, member.Name)\n\t}\n\tsort.Strings(sortedName)\n\n\tr := make([]*consulapi.AgentMember, 0, len(sortedName))\n\tfor _, name := range sortedName {\n\t\tr = append(r, m[name])\n\t}\n\n\treturn r\n}\n\nfunc (*Members) Synopsis() string {\n\treturn \"Verify consul members match kafka zone\"\n}\n\nfunc (this *Members) Help() string {\n\thelp := fmt.Sprintf(`\nUsage: %s members [options]\n\n    Verify consul members match kafka zone\n\n    -z zone\n\n    -r role\n\n    -l\n      Display each member load average\n\n    -exec <cmd>\n      Execute cmd on all members and print the result by host\n      e,g. gk members -exec \"ifconfig bond0 | grep 'TX bytes'\"\n\n    -n node\n      Execute cmd on a single node\n\n`, this.Cmd)\n\treturn strings.TrimSpace(help)\n}\n<commit_msg>tweak of the load avg highlight<commit_after>package command\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"net\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com\/funkygao\/gafka\/ctx\"\n\t\"github.com\/funkygao\/gafka\/zk\"\n\t\"github.com\/funkygao\/gocli\"\n\t\"github.com\/funkygao\/golib\/color\"\n\t\"github.com\/funkygao\/golib\/pipestream\"\n\tconsulapi \"github.com\/hashicorp\/consul\/api\"\n\t\"github.com\/ryanuber\/columnize\"\n)\n\n\/\/ consul members will include:\n\/\/ - zk cluster as server\n\/\/ - agents\n\/\/   - brokers\n\/\/   - kateway\ntype Members struct {\n\tUi  cli.Ui\n\tCmd string\n\n\tbrokerHosts, zkHosts, katewayHosts map[string]struct{}\n\tnodeHostMap                        map[string]string \/\/ consul members node->ip\n}\n\nfunc (this *Members) Run(args []string) (exitCode int) {\n\tvar (\n\t\tzone        string\n\t\tshowLoadAvg bool\n\t\texec        string\n\t\tnode        string\n\t\trole        string\n\t)\n\tcmdFlags := flag.NewFlagSet(\"members\", flag.ContinueOnError)\n\tcmdFlags.Usage = func() { this.Ui.Output(this.Help()) }\n\tcmdFlags.StringVar(&zone, \"z\", ctx.ZkDefaultZone(), \"\")\n\tcmdFlags.BoolVar(&showLoadAvg, \"l\", false, \"\")\n\tcmdFlags.StringVar(&exec, \"exec\", \"\", \"\")\n\tcmdFlags.StringVar(&node, \"n\", \"\", \"\")\n\tcmdFlags.StringVar(&role, \"r\", \"\", \"\")\n\tif err := cmdFlags.Parse(args); err != nil {\n\t\treturn 1\n\t}\n\n\tif validateArgs(this, this.Ui).\n\t\trequireAdminRights(\"-exec\").\n\t\tinvalid(args) {\n\t\treturn 2\n\t}\n\n\tzkzone := zk.NewZkZone(zk.DefaultConfig(zone, ctx.ZoneZkAddrs(zone)))\n\tthis.fetchAllRunningHostsFromZk(zkzone)\n\n\tmembers := this.consulMembers()\n\tconsulLiveNode := make([]string, 0, len(members))\n\tfor _, member := range members {\n\t\tif member.Status == 1 {\n\t\t\tconsulLiveNode = append(consulLiveNode, member.Addr)\n\t\t} else {\n\t\t\tthis.Ui.Warn(fmt.Sprintf(\"%s %s status:%d\", member.Name, member.Addr, member.Status))\n\t\t}\n\t}\n\n\tconsulLiveMap := make(map[string]struct{})\n\tbrokerN, zkN, katewayN, unknownN := 0, 0, 0, 0\n\tfor _, node := range consulLiveNode {\n\t\t_, presentInBroker := this.brokerHosts[node]\n\t\t_, presentInZk := this.zkHosts[node]\n\t\t_, presentInKateway := this.katewayHosts[node]\n\t\tif presentInBroker {\n\t\t\tbrokerN++\n\t\t}\n\t\tif presentInZk {\n\t\t\tzkN++\n\t\t}\n\t\tif presentInKateway {\n\t\t\tkatewayN++\n\t\t}\n\n\t\tif !presentInBroker && !presentInZk && !presentInKateway {\n\t\t\tunknownN++\n\t\t}\n\n\t\tconsulLiveMap[node] = struct{}{}\n\t}\n\n\t\/\/ all brokers should run consul\n\tfor broker, _ := range this.brokerHosts {\n\t\tif _, present := consulLiveMap[broker]; !present {\n\t\t\tthis.Ui.Warn(fmt.Sprintf(\"- %s\", broker))\n\t\t}\n\t}\n\n\tswitch {\n\tcase showLoadAvg:\n\t\tthis.displayLoadAvg(role)\n\n\tcase exec != \"\":\n\t\tthis.executeOnAll(exec, role, node)\n\n\tdefault:\n\t\tthis.displayMembers(members, role)\n\t}\n\n\t\/\/ summary\n\tthis.Ui.Output(fmt.Sprintf(\"Zk:%d Broker:%d Kateway:%d ?:%s => %d\",\n\t\tzkN, brokerN, katewayN, color.Yellow(\"%d\", unknownN), zkN+brokerN+katewayN+unknownN))\n\n\treturn\n}\n\nfunc (this *Members) fetchAllRunningHostsFromZk(zkzone *zk.ZkZone) {\n\tthis.brokerHosts = make(map[string]struct{})\n\tzkzone.ForSortedBrokers(func(cluster string, brokers map[string]*zk.BrokerZnode) {\n\t\tfor _, brokerInfo := range brokers {\n\t\t\tthis.brokerHosts[brokerInfo.Host] = struct{}{}\n\t\t}\n\t})\n\n\tthis.zkHosts = make(map[string]struct{})\n\tfor _, addr := range zkzone.ZkAddrList() {\n\t\tzkNode, _, err := net.SplitHostPort(addr)\n\t\tswallow(err)\n\t\tthis.zkHosts[zkNode] = struct{}{}\n\t}\n\n\tthis.katewayHosts = make(map[string]struct{})\n\tkws, err := zkzone.KatewayInfos()\n\tswallow(err)\n\tfor _, kw := range kws {\n\t\thost, _, err := net.SplitHostPort(kw.PubAddr)\n\t\tswallow(err)\n\t\tthis.katewayHosts[host] = struct{}{}\n\t}\n}\n\n\/\/ TODO role is ignored\nfunc (this *Members) executeOnAll(execCmd string, role string, node string) {\n\targs := []string{\"exec\"}\n\tif node != \"\" {\n\t\targs = append(args, fmt.Sprintf(\"-node=%s\", node))\n\t}\n\targs = append(args, strings.Split(execCmd, \" \")...)\n\tcmd := pipestream.New(\"consul\", args...)\n\terr := cmd.Open()\n\tswallow(err)\n\tdefer cmd.Close()\n\n\tthis.Ui.Info(fmt.Sprintf(\"%s ...\", execCmd))\n\n\tlines := make([]string, 0)\n\theader := \"Node|Host|Role|Result\"\n\tlines = append(lines, header)\n\n\tscanner := bufio.NewScanner(cmd.Reader())\n\tscanner.Split(bufio.ScanLines)\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tif strings.Contains(line, \"finished with exit code 0\") ||\n\t\t\tstrings.Contains(line, \"completed \/ acknowledged\") {\n\t\t\tcontinue\n\t\t}\n\t\tfields := strings.Fields(line)\n\t\tif len(fields) == 1 {\n\t\t\tcontinue\n\t\t}\n\n\t\tnode := fields[0]\n\t\tif strings.HasSuffix(node, \":\") {\n\t\t\tnode = strings.TrimRight(node, \":\")\n\t\t}\n\n\t\thost := this.nodeHostMap[node]\n\t\tlines = append(lines, fmt.Sprintf(\"%s|%s|%s|%s\", node, host, this.roleOfHost(host),\n\t\t\tstrings.Join(fields[1:], \" \")))\n\t}\n\n\tif len(lines) > 1 {\n\t\tsort.Strings(lines[1:])\n\t\tthis.Ui.Output(columnize.SimpleFormat(lines))\n\t}\n}\n\nfunc (this *Members) displayMembers(members []*consulapi.AgentMember, role string) {\n\tlines := make([]string, 0)\n\theader := \"Node|Host|Role\"\n\tlines = append(lines, header)\n\tfor _, member := range members {\n\t\thostRole := this.roleOfHost(member.Addr)\n\t\tif role != \"\" && role != hostRole {\n\t\t\tcontinue\n\t\t}\n\n\t\tlines = append(lines, fmt.Sprintf(\"%s|%s|%s\", member.Name, member.Addr, hostRole))\n\t}\n\n\tif len(lines) > 1 {\n\t\tsort.Strings(lines[1:])\n\t\tthis.Ui.Output(columnize.SimpleFormat(lines))\n\t}\n}\n\nfunc (this *Members) displayLoadAvg(role string) {\n\tcmd := pipestream.New(\"consul\", \"exec\",\n\t\t\"uptime\", \"|\", \"grep\", \"load\")\n\terr := cmd.Open()\n\tswallow(err)\n\tdefer cmd.Close()\n\n\tlines := make([]string, 0)\n\theader := \"Node|Host|Role|Load Avg\"\n\tlines = append(lines, header)\n\n\tscanner := bufio.NewScanner(cmd.Reader())\n\tscanner.Split(bufio.ScanLines)\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tfields := strings.Fields(line)\n\t\tnode := fields[0]\n\t\tparts := strings.Split(line, \"load average:\")\n\t\tif len(parts) < 2 {\n\t\t\tcontinue\n\t\t}\n\t\tif strings.HasSuffix(node, \":\") {\n\t\t\tnode = strings.TrimRight(node, \":\")\n\t\t}\n\n\t\tloadAvg := strings.TrimSpace(parts[1])\n\t\tif loadAvg[0] > '0' {\n\t\t\tloadAvg += \" !\"\n\t\t\tif loadAvg[0] > '2' {\n\t\t\t\tloadAvg += \"!\"\n\t\t\t}\n\t\t\tif loadAvg[0] > '4' {\n\t\t\t\tloadAvg += \"!\"\n\t\t\t}\n\t\t}\n\n\t\thost := this.nodeHostMap[node]\n\t\thostRole := this.roleOfHost(host)\n\t\tif role != \"\" && hostRole != role {\n\t\t\tcontinue\n\t\t}\n\n\t\tlines = append(lines, fmt.Sprintf(\"%s|%s|%s|%s\", node, host, hostRole, loadAvg))\n\t}\n\n\tif len(lines) > 1 {\n\t\tsort.Strings(lines[1:])\n\t\tthis.Ui.Output(columnize.SimpleFormat(lines))\n\t}\n}\n\nfunc (this *Members) roleOfHost(host string) string {\n\tif _, present := this.brokerHosts[host]; present {\n\t\treturn \"B\"\n\t}\n\tif _, present := this.zkHosts[host]; present {\n\t\treturn \"Z\"\n\t}\n\tif _, present := this.katewayHosts[host]; present {\n\t\treturn \"K\"\n\t}\n\treturn \"?\"\n}\n\nfunc (this *Members) consulMembers() []*consulapi.AgentMember {\n\tcf := consulapi.DefaultConfig()\n\tclient, err := consulapi.NewClient(cf)\n\tswallow(err)\n\tmembers, err := client.Agent().Members(false)\n\tswallow(err)\n\n\tm := make(map[string]*consulapi.AgentMember, len(members))\n\tsortedName := make([]string, 0, len(members))\n\tthis.nodeHostMap = make(map[string]string, len(members))\n\tfor _, member := range members {\n\t\tm[member.Name] = member\n\t\tthis.nodeHostMap[member.Name] = member.Addr\n\n\t\tsortedName = append(sortedName, member.Name)\n\t}\n\tsort.Strings(sortedName)\n\n\tr := make([]*consulapi.AgentMember, 0, len(sortedName))\n\tfor _, name := range sortedName {\n\t\tr = append(r, m[name])\n\t}\n\n\treturn r\n}\n\nfunc (*Members) Synopsis() string {\n\treturn \"Verify consul members match kafka zone\"\n}\n\nfunc (this *Members) Help() string {\n\thelp := fmt.Sprintf(`\nUsage: %s members [options]\n\n    Verify consul members match kafka zone\n\n    -z zone\n\n    -r role\n\n    -l\n      Display each member load average\n\n    -exec <cmd>\n      Execute cmd on all members and print the result by host\n      e,g. gk members -exec \"ifconfig bond0 | grep 'TX bytes'\"\n\n    -n node\n      Execute cmd on a single node\n\n`, this.Cmd)\n\treturn strings.TrimSpace(help)\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"flag\"\n\t\"koding\/tools\/config\"\n\t\"os\"\n\t\"socialapi\/db\"\n\tfollowingfeed \"socialapi\/workers\/followingfeed\/lib\"\n\t\"github.com\/koding\/rabbitmq\"\n\n\t\"github.com\/jinzhu\/gorm\"\n\t\"github.com\/koding\/bongo\"\n\t\"github.com\/koding\/broker\"\n\t\"github.com\/koding\/logging\"\n\t\"github.com\/streadway\/amqp\"\n)\n\nfunc init() {\n\tlogHandler = logging.NewWriterHandler(os.Stderr)\n\tlogHandler.Colorize = true\n\tlog.SetHandler(logHandler)\n}\n\nvar (\n\tBongo       *bongo.Bongo\n\tlog         = logging.NewLogger(\"FollowingFeedWorker\")\n\tlogHandler  *logging.WriterHandler\n\tconf        *config.Config\n\tflagProfile = flag.String(\"c\", \"\", \"Configuration profile from file\")\n\tflagDebug   = flag.Bool(\"d\", false, \"Debug mode\")\n\thandler     = followingfeed.NewFollowingFeedController(log)\n)\n\nfunc main() {\n\tflag.Parse()\n\tif *flagProfile == \"\" {\n\t\tlog.Fatal(\"Please define config file with -c\", \"\")\n\t}\n\n\tconf = config.MustConfig(*flagProfile)\n\tsetLogLevel()\n\n\trmqConf := &rabbitmq.Config{\n\t\tHost:     conf.Mq.Host,\n\t\tPort:     conf.Mq.Port,\n\t\tUsername: conf.Mq.ComponentUser,\n\t\tPassword: conf.Mq.Password,\n\t\tVhost:    conf.Mq.Vhost,\n\t}\n\n\tinitBongo(rmqConf)\n\n\t\/\/ blocking\n\tfollowingfeed.Listen(rabbitmq.New(rmqConf, log), startHandler)\n\tdefer followingfeed.Consumer.Shutdown()\n}\n\nfunc startHandler() func(delivery amqp.Delivery) {\n\tlog.Info(\"Worker Started to Consume\")\n\treturn func(delivery amqp.Delivery) {\n\t\terr := handler.HandleEvent(delivery.Type, delivery.Body)\n\t\tswitch err {\n\t\tcase nil:\n\t\t\tdelivery.Ack(false)\n\t\tcase followingfeed.HandlerNotFoundErr:\n\t\t\tlog.Notice(\"unknown event type (%s) recieved, \\n deleting message from RMQ\", delivery.Type)\n\t\t\tdelivery.Ack(false)\n\t\tcase gorm.RecordNotFound:\n\t\t\tlog.Warning(\"Record not found in our db (%s) recieved, \\n deleting message from RMQ\", string(delivery.Body))\n\t\t\tdelivery.Ack(false)\n\t\tdefault:\n\t\t\t\/\/ add proper error handling\n\t\t\t\/\/ instead of puttting message back to same queue, it is better\n\t\t\t\/\/ to put it to another maintenance queue\/exchange\n\t\t\tlog.Error(\"an error occured %s, \\n putting message back to queue\", err)\n\t\t\t\/\/ multiple false\n\t\t\t\/\/ reque true\n\t\t\tdelivery.Nack(false, true)\n\t\t}\n\t}\n}\n\nfunc initBongo(c *rabbitmq.Config) {\n\tbConf := &broker.Config{\n\t\tRMQConfig: c,\n\t}\n\tbroker := broker.New(bConf, log)\n\tBongo = bongo.New(broker, db.DB, log)\n\tBongo.Connect()\n}\n\nfunc setLogLevel() {\n\tvar logLevel logging.Level\n\n\tif *flagDebug {\n\t\tlogLevel = logging.DEBUG\n\t} else {\n\t\tlogLevel = logging.INFO\n\t}\n\tlog.SetLevel(logLevel)\n\tlogHandler.SetLevel(logLevel)\n}\n<commit_msg>Social: use log helper in order to init log package<commit_after>package main\n\nimport (\n\t\"flag\"\n\t\"koding\/tools\/config\"\n\tfollowingfeed \"socialapi\/workers\/followingfeed\/lib\"\n\t\"socialapi\/workers\/helper\"\n\n\t\"github.com\/jinzhu\/gorm\"\n\t\"github.com\/koding\/bongo\"\n\t\"github.com\/koding\/logging\"\n\t\"github.com\/streadway\/amqp\"\n)\n\nvar (\n\tBongo       *bongo.Bongo\n\tlog         logging.Logger\n\tconf        *config.Config\n\tflagProfile = flag.String(\"c\", \"\", \"Configuration profile from file\")\n\tflagDebug   = flag.Bool(\"d\", false, \"Debug mode\")\n\thandler     *followingfeed.FollowingFeedController\n)\n\nfunc main() {\n\tflag.Parse()\n\tif *flagProfile == \"\" {\n\t\tlog.Fatal(\"Please define config file with -c\", \"\")\n\t}\n\n\tconf = config.MustConfig(*flagProfile)\n\n\trmqConf := &rabbitmq.Config{\n\t\tHost:     conf.Mq.Host,\n\t\tPort:     conf.Mq.Port,\n\t\tUsername: conf.Mq.ComponentUser,\n\t\tPassword: conf.Mq.Password,\n\t\tVhost:    conf.Mq.Vhost,\n\t}\n\t\/\/ create logger for our package\n\tlog = helper.CreateLogger(\"TopicFeedWorker\", *flagDebug)\n\n\tinitBongo(rmqConf)\n\n\t\/\/ blocking\n\tfollowingfeed.Listen(rabbitmq.New(rmqConf, log), startHandler)\n\tdefer followingfeed.Consumer.Shutdown()\n}\n\nfunc startHandler() func(delivery amqp.Delivery) {\n\tlog.Info(\"Worker Started to Consume\")\n\treturn func(delivery amqp.Delivery) {\n\t\terr := handler.HandleEvent(delivery.Type, delivery.Body)\n\t\tswitch err {\n\t\tcase nil:\n\t\t\tdelivery.Ack(false)\n\t\tcase followingfeed.HandlerNotFoundErr:\n\t\t\tlog.Notice(\"unknown event type (%s) recieved, \\n deleting message from RMQ\", delivery.Type)\n\t\t\tdelivery.Ack(false)\n\t\tcase gorm.RecordNotFound:\n\t\t\tlog.Warning(\"Record not found in our db (%s) recieved, \\n deleting message from RMQ\", string(delivery.Body))\n\t\t\tdelivery.Ack(false)\n\t\tdefault:\n\t\t\t\/\/ add proper error handling\n\t\t\t\/\/ instead of puttting message back to same queue, it is better\n\t\t\t\/\/ to put it to another maintenance queue\/exchange\n\t\t\tlog.Error(\"an error occured %s, \\n putting message back to queue\", err)\n\t\t\t\/\/ multiple false\n\t\t\t\/\/ reque true\n\t\t\tdelivery.Nack(false, true)\n\t\t}\n\t}\n}\n\nfunc initBongo(c *rabbitmq.Config) {\n\tbConf := &broker.Config{\n\t\tRMQConfig: c,\n\t}\n\tbroker := broker.New(bConf, log)\n\tBongo = bongo.New(broker, db.DB, log)\n\tBongo.Connect()\n}\n\n<|endoftext|>"}
{"text":"<commit_before>package jar\n\nimport (\n\t\"github.com\/headzoo\/ut\"\n\t\"os\"\n\t\"testing\"\n)\n\nfunc TestMemoryBookmarks(t *testing.T) {\n\tut.Run(t)\n\n\tb := NewMemoryBookmarks()\n\tassertBookmarks(b)\n}\n\nfunc TestFileBookmarks(t *testing.T) {\n\tut.Run(t)\n\n\tb, err := NewFileBookmarks(\".\/bookmarks.json\")\n\tut.AssertNil(err)\n\tdefer func() {\n\t\terr = os.Remove(\".\/bookmarks.json\")\n\t}()\n\tassertBookmarks(b)\n}\n\n\/\/ assertBookmarks tests the given bookmark jar.\nfunc assertBookmarks(b BookmarksJar) {\n\terr := b.Save(\"test1\", \"http:\/\/localhost\")\n\tut.AssertNil(err)\n\terr = b.Save(\"test2\", \"http:\/\/127.0.0.1\")\n\tut.AssertNil(err)\n\terr = b.Save(\"test1\", \"http:\/\/localhost\")\n\tut.AssertNotNil(err)\n\n\turl, err := b.Read(\"test1\")\n\tut.AssertNil(err)\n\tut.AssertEquals(\"http:\/\/localhost\", url)\n\turl, err = b.Read(\"test2\")\n\tut.AssertEquals(\"http:\/\/127.0.0.1\", url)\n\turl, err = b.Read(\"test3\")\n\tut.AssertNotNil(err)\n\n\tr := b.Remove(\"test2\")\n\tut.AssertTrue(r)\n\tr = b.Remove(\"test3\")\n\tut.AssertFalse(r)\n\n\tr = b.Has(\"test1\")\n\tut.AssertTrue(r)\n\tr = b.Has(\"test4\")\n\tut.AssertFalse(r)\n}\n<commit_msg>Avoid staticcheck warning<commit_after>package jar\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com\/headzoo\/ut\"\n)\n\nfunc TestMemoryBookmarks(t *testing.T) {\n\tut.Run(t)\n\n\tb := NewMemoryBookmarks()\n\tassertBookmarks(b)\n}\n\nfunc TestFileBookmarks(t *testing.T) {\n\tut.Run(t)\n\n\tb, err := NewFileBookmarks(\".\/bookmarks.json\")\n\tut.AssertNil(err)\n\tdefer func() {\n\t\terr = os.Remove(\".\/bookmarks.json\")\n\t}()\n\tassertBookmarks(b)\n}\n\n\/\/ assertBookmarks tests the given bookmark jar.\nfunc assertBookmarks(b BookmarksJar) {\n\terr := b.Save(\"test1\", \"http:\/\/localhost\")\n\tut.AssertNil(err)\n\terr = b.Save(\"test2\", \"http:\/\/127.0.0.1\")\n\tut.AssertNil(err)\n\terr = b.Save(\"test1\", \"http:\/\/localhost\")\n\tut.AssertNotNil(err)\n\n\turl, err := b.Read(\"test1\")\n\tut.AssertNil(err)\n\tut.AssertEquals(\"http:\/\/localhost\", url)\n\turl, err = b.Read(\"test2\")\n\tut.AssertNil(err)\n\tut.AssertEquals(\"http:\/\/127.0.0.1\", url)\n\t_, err = b.Read(\"test3\")\n\tut.AssertNotNil(err)\n\n\tr := b.Remove(\"test2\")\n\tut.AssertTrue(r)\n\tr = b.Remove(\"test3\")\n\tut.AssertFalse(r)\n\n\tr = b.Has(\"test1\")\n\tut.AssertTrue(r)\n\tr = b.Has(\"test4\")\n\tut.AssertFalse(r)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2017 Vector Creations Ltd\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage routing\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"strings\"\n\n\t\"github.com\/matrix-org\/dendrite\/roomserver\/api\"\n\n\t\"github.com\/matrix-org\/dendrite\/clientapi\/auth\/authtypes\"\n\t\"github.com\/matrix-org\/dendrite\/clientapi\/auth\/storage\/accounts\"\n\t\"github.com\/matrix-org\/dendrite\/clientapi\/httputil\"\n\t\"github.com\/matrix-org\/dendrite\/clientapi\/jsonerror\"\n\t\"github.com\/matrix-org\/dendrite\/clientapi\/producers\"\n\t\"github.com\/matrix-org\/dendrite\/common\"\n\t\"github.com\/matrix-org\/dendrite\/common\/config\"\n\t\"github.com\/matrix-org\/gomatrixserverlib\"\n\t\"github.com\/matrix-org\/util\"\n\tlog \"github.com\/sirupsen\/logrus\"\n)\n\n\/\/ https:\/\/matrix.org\/docs\/spec\/client_server\/r0.2.0.html#post-matrix-client-r0-createroom\ntype createRoomRequest struct {\n\tInvite          []string               `json:\"invite\"`\n\tName            string                 `json:\"name\"`\n\tVisibility      string                 `json:\"visibility\"`\n\tTopic           string                 `json:\"topic\"`\n\tPreset          string                 `json:\"preset\"`\n\tCreationContent map[string]interface{} `json:\"creation_content\"`\n\tInitialState    []fledglingEvent       `json:\"initial_state\"`\n\tRoomAliasName   string                 `json:\"room_alias_name\"`\n\tGuestCanJoin    bool                   `json:\"guest_can_join\"`\n}\n\nconst (\n\tpresetPrivateChat        = \"private_chat\"\n\tpresetTrustedPrivateChat = \"trusted_private_chat\"\n\tpresetPublicChat         = \"public_chat\"\n)\n\nconst (\n\tjoinRulePublic = \"public\"\n\tjoinRuleInvite = \"invite\"\n)\nconst (\n\thistoryVisibilityShared = \"shared\"\n\t\/\/ TODO: These should be implemented once history visibility is implemented\n\t\/\/ historyVisibilityWorldReadable = \"world_readable\"\n\t\/\/ historyVisibilityInvited       = \"invited\"\n)\n\nfunc (r createRoomRequest) Validate() *util.JSONResponse {\n\twhitespace := \"\\t\\n\\x0b\\x0c\\r \" \/\/ https:\/\/docs.python.org\/2\/library\/string.html#string.whitespace\n\t\/\/ https:\/\/github.com\/matrix-org\/synapse\/blob\/v0.19.2\/synapse\/handlers\/room.py#L81\n\t\/\/ Synapse doesn't check for ':' but we will else it will break parsers badly which split things into 2 segments.\n\tif strings.ContainsAny(r.RoomAliasName, whitespace+\":\") {\n\t\treturn &util.JSONResponse{\n\t\t\tCode: http.StatusBadRequest,\n\t\t\tJSON: jsonerror.BadJSON(\"room_alias_name cannot contain whitespace\"),\n\t\t}\n\t}\n\tfor _, userID := range r.Invite {\n\t\t\/\/ TODO: We should put user ID parsing code into gomatrixserverlib and use that instead\n\t\t\/\/       (see https:\/\/github.com\/matrix-org\/gomatrixserverlib\/blob\/3394e7c7003312043208aa73727d2256eea3d1f6\/eventcontent.go#L347 )\n\t\t\/\/       It should be a struct (with pointers into a single string to avoid copying) and\n\t\t\/\/       we should update all refs to use UserID types rather than strings.\n\t\t\/\/ https:\/\/github.com\/matrix-org\/synapse\/blob\/v0.19.2\/synapse\/types.py#L92\n\t\tif _, _, err := gomatrixserverlib.SplitID('@', userID); err != nil {\n\t\t\treturn &util.JSONResponse{\n\t\t\t\tCode: http.StatusBadRequest,\n\t\t\t\tJSON: jsonerror.BadJSON(\"user id must be in the form @localpart:domain\"),\n\t\t\t}\n\t\t}\n\t}\n\tswitch r.Preset {\n\tcase presetPrivateChat, presetTrustedPrivateChat, presetPublicChat, \"\":\n\tdefault:\n\t\treturn &util.JSONResponse{\n\t\t\tCode: http.StatusBadRequest,\n\t\t\tJSON: jsonerror.BadJSON(\"preset must be any of 'private_chat', 'trusted_private_chat', 'public_chat'\"),\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ https:\/\/matrix.org\/docs\/spec\/client_server\/r0.2.0.html#post-matrix-client-r0-createroom\ntype createRoomResponse struct {\n\tRoomID    string `json:\"room_id\"`\n\tRoomAlias string `json:\"room_alias,omitempty\"` \/\/ in synapse not spec\n}\n\n\/\/ fledglingEvent is a helper representation of an event used when creating many events in succession.\ntype fledglingEvent struct {\n\tType     string      `json:\"type\"`\n\tStateKey string      `json:\"state_key\"`\n\tContent  interface{} `json:\"content\"`\n}\n\n\/\/ CreateRoom implements \/createRoom\nfunc CreateRoom(\n\treq *http.Request, device *authtypes.Device,\n\tcfg config.Dendrite, producer *producers.RoomserverProducer,\n\taccountDB *accounts.Database, aliasAPI api.RoomserverAliasAPI,\n) util.JSONResponse {\n\t\/\/ TODO (#267): Check room ID doesn't clash with an existing one, and we\n\t\/\/              probably shouldn't be using pseudo-random strings, maybe GUIDs?\n\troomID := fmt.Sprintf(\"!%s:%s\", util.RandomString(16), cfg.Matrix.ServerName)\n\treturn createRoom(req, device, cfg, roomID, producer, accountDB, aliasAPI)\n}\n\n\/\/ createRoom implements \/createRoom\n\/\/ nolint: gocyclo\nfunc createRoom(\n\treq *http.Request, device *authtypes.Device,\n\tcfg config.Dendrite, roomID string, producer *producers.RoomserverProducer,\n\taccountDB *accounts.Database, aliasAPI api.RoomserverAliasAPI,\n) util.JSONResponse {\n\tlogger := util.GetLogger(req.Context())\n\tuserID := device.UserID\n\tvar r createRoomRequest\n\tresErr := httputil.UnmarshalJSONRequest(req, &r)\n\tif resErr != nil {\n\t\treturn *resErr\n\t}\n\t\/\/ TODO: apply rate-limit\n\n\tif resErr = r.Validate(); resErr != nil {\n\t\treturn *resErr\n\t}\n\n\t\/\/ TODO: visibility\/presets\/raw initial state\/creation content\n\n\t\/\/ TODO: Create room alias association\n\t\/\/ Make sure this doesn't fall into an application service's namespace though!\n\n\tlogger.WithFields(log.Fields{\n\t\t\"userID\": userID,\n\t\t\"roomID\": roomID,\n\t}).Info(\"Creating new room\")\n\n\tlocalpart, _, err := gomatrixserverlib.SplitID('@', userID)\n\tif err != nil {\n\t\treturn httputil.LogThenError(req, err)\n\t}\n\n\tprofile, err := accountDB.GetProfileByLocalpart(req.Context(), localpart)\n\tif err != nil {\n\t\treturn httputil.LogThenError(req, err)\n\t}\n\n\tmembershipContent := common.MemberContent{\n\t\tMembership:  \"join\",\n\t\tDisplayName: profile.DisplayName,\n\t\tAvatarURL:   profile.AvatarURL,\n\t}\n\n\tvar joinRules, historyVisibility string\n\tswitch r.Preset {\n\tcase presetPrivateChat:\n\t\tjoinRules = joinRuleInvite\n\t\thistoryVisibility = historyVisibilityShared\n\tcase presetTrustedPrivateChat:\n\t\tjoinRules = joinRuleInvite\n\t\thistoryVisibility = historyVisibilityShared\n\t\t\/\/ TODO If trusted_private_chat, all invitees are given the same power level as the room creator.\n\tcase presetPublicChat:\n\t\tjoinRules = joinRulePublic\n\t\thistoryVisibility = historyVisibilityShared\n\tdefault:\n\t\t\/\/ Default room rules, r.Preset was previously checked for valid values so\n\t\t\/\/ only a request with no preset should end up here.\n\t\tjoinRules = joinRuleInvite\n\t\thistoryVisibility = historyVisibilityShared\n\t}\n\n\tvar builtEvents []gomatrixserverlib.Event\n\n\t\/\/ send events into the room in order of:\n\t\/\/  1- m.room.create\n\t\/\/  2- room creator join member\n\t\/\/  3- m.room.power_levels\n\t\/\/  4- m.room.canonical_alias (opt) TODO\n\t\/\/  5- m.room.join_rules\n\t\/\/  6- m.room.history_visibility\n\t\/\/  7- m.room.guest_access (opt)\n\t\/\/  8- other initial state items\n\t\/\/  9- m.room.name (opt)\n\t\/\/  10- m.room.topic (opt)\n\t\/\/  11- invite events (opt) - with is_direct flag if applicable TODO\n\t\/\/  12- 3pid invite events (opt) TODO\n\t\/\/  13- m.room.aliases event for HS (if alias specified) TODO\n\t\/\/ This differs from Synapse slightly. Synapse would vary the ordering of 3-7\n\t\/\/ depending on if those events were in \"initial_state\" or not. This made it\n\t\/\/ harder to reason about, hence sticking to a strict static ordering.\n\t\/\/ TODO: Synapse has txn\/token ID on each event. Do we need to do this here?\n\teventsToMake := []fledglingEvent{\n\t\t{\"m.room.create\", \"\", common.CreateContent{Creator: userID}},\n\t\t{\"m.room.member\", userID, membershipContent},\n\t\t{\"m.room.power_levels\", \"\", common.InitialPowerLevelsContent(userID)},\n\t\t\/\/ TODO: m.room.canonical_alias\n\t\t{\"m.room.join_rules\", \"\", common.JoinRulesContent{JoinRule: joinRules}},\n\t\t{\"m.room.history_visibility\", \"\", common.HistoryVisibilityContent{HistoryVisibility: historyVisibility}},\n\t}\n\tif r.GuestCanJoin {\n\t\teventsToMake = append(eventsToMake, fledglingEvent{\"m.room.guest_access\", \"\", common.GuestAccessContent{GuestAccess: \"can_join\"}})\n\t}\n\teventsToMake = append(eventsToMake, r.InitialState...)\n\tif r.Name != \"\" {\n\t\teventsToMake = append(eventsToMake, fledglingEvent{\"m.room.name\", \"\", common.NameContent{Name: r.Name}})\n\t}\n\tif r.Topic != \"\" {\n\t\teventsToMake = append(eventsToMake, fledglingEvent{\"m.room.topic\", \"\", common.TopicContent{Topic: r.Topic}})\n\t}\n\t\/\/ TODO: invite events\n\t\/\/ TODO: 3pid invite events\n\t\/\/ TODO: m.room.aliases\n\n\tauthEvents := gomatrixserverlib.NewAuthEvents(nil)\n\tfor i, e := range eventsToMake {\n\t\tdepth := i + 1 \/\/ depth starts at 1\n\n\t\tbuilder := gomatrixserverlib.EventBuilder{\n\t\t\tSender:   userID,\n\t\t\tRoomID:   roomID,\n\t\t\tType:     e.Type,\n\t\t\tStateKey: &e.StateKey,\n\t\t\tDepth:    int64(depth),\n\t\t}\n\t\terr = builder.SetContent(e.Content)\n\t\tif err != nil {\n\t\t\treturn httputil.LogThenError(req, err)\n\t\t}\n\t\tif i > 0 {\n\t\t\tbuilder.PrevEvents = []gomatrixserverlib.EventReference{builtEvents[i-1].EventReference()}\n\t\t}\n\t\tvar ev *gomatrixserverlib.Event\n\t\tev, err = buildEvent(req, &builder, &authEvents, cfg)\n\t\tif err != nil {\n\t\t\treturn httputil.LogThenError(req, err)\n\t\t}\n\n\t\tif err = gomatrixserverlib.Allowed(*ev, &authEvents); err != nil {\n\t\t\treturn httputil.LogThenError(req, err)\n\t\t}\n\n\t\t\/\/ Add the event to the list of auth events\n\t\tbuiltEvents = append(builtEvents, *ev)\n\t\terr = authEvents.AddEvent(ev)\n\t\tif err != nil {\n\t\t\treturn httputil.LogThenError(req, err)\n\t\t}\n\t}\n\n\t\/\/ send events to the room server\n\t_, err = producer.SendEvents(req.Context(), builtEvents, cfg.Matrix.ServerName, nil)\n\tif err != nil {\n\t\treturn httputil.LogThenError(req, err)\n\t}\n\n\t\/\/ TODO(#269): Reserve room alias while we create the room. This stops us\n\t\/\/ from creating the room but still failing due to the alias having already\n\t\/\/ been taken.\n\tvar roomAlias string\n\tif r.RoomAliasName != \"\" {\n\t\troomAlias = fmt.Sprintf(\"#%s:%s\", r.RoomAliasName, cfg.Matrix.ServerName)\n\n\t\taliasReq := api.SetRoomAliasRequest{\n\t\t\tAlias:  roomAlias,\n\t\t\tRoomID: roomID,\n\t\t\tUserID: userID,\n\t\t}\n\n\t\tvar aliasResp api.SetRoomAliasResponse\n\t\terr = aliasAPI.SetRoomAlias(req.Context(), &aliasReq, &aliasResp)\n\t\tif err != nil {\n\t\t\treturn httputil.LogThenError(req, err)\n\t\t}\n\n\t\tif aliasResp.AliasExists {\n\t\t\treturn util.MessageResponse(400, \"Alias already exists\")\n\t\t}\n\t}\n\n\tresponse := createRoomResponse{\n\t\tRoomID:    roomID,\n\t\tRoomAlias: roomAlias,\n\t}\n\n\treturn util.JSONResponse{\n\t\tCode: 200,\n\t\tJSON: response,\n\t}\n}\n\n\/\/ buildEvent fills out auth_events for the builder then builds the event\nfunc buildEvent(\n\treq *http.Request,\n\tbuilder *gomatrixserverlib.EventBuilder,\n\tprovider gomatrixserverlib.AuthEventProvider,\n\tcfg config.Dendrite,\n) (*gomatrixserverlib.Event, error) {\n\n\teventsNeeded, err := gomatrixserverlib.StateNeededForEventBuilder(builder)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trefs, err := eventsNeeded.AuthEventReferences(provider)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbuilder.AuthEvents = refs\n\teventID := fmt.Sprintf(\"$%s:%s\", util.RandomString(16), cfg.Matrix.ServerName)\n\teventTime := common.ParseTSParam(req)\n\tevent, err := builder.Build(eventID, eventTime, cfg.Matrix.ServerName, cfg.Matrix.KeyID, cfg.Matrix.PrivateKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot build event %s : Builder failed to build. %s\", builder.Type, err)\n\t}\n\treturn &event, nil\n}\n<commit_msg>Add detail to room alias name error message (#565)<commit_after>\/\/ Copyright 2017 Vector Creations Ltd\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage routing\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"strings\"\n\n\t\"github.com\/matrix-org\/dendrite\/roomserver\/api\"\n\n\t\"github.com\/matrix-org\/dendrite\/clientapi\/auth\/authtypes\"\n\t\"github.com\/matrix-org\/dendrite\/clientapi\/auth\/storage\/accounts\"\n\t\"github.com\/matrix-org\/dendrite\/clientapi\/httputil\"\n\t\"github.com\/matrix-org\/dendrite\/clientapi\/jsonerror\"\n\t\"github.com\/matrix-org\/dendrite\/clientapi\/producers\"\n\t\"github.com\/matrix-org\/dendrite\/common\"\n\t\"github.com\/matrix-org\/dendrite\/common\/config\"\n\t\"github.com\/matrix-org\/gomatrixserverlib\"\n\t\"github.com\/matrix-org\/util\"\n\tlog \"github.com\/sirupsen\/logrus\"\n)\n\n\/\/ https:\/\/matrix.org\/docs\/spec\/client_server\/r0.2.0.html#post-matrix-client-r0-createroom\ntype createRoomRequest struct {\n\tInvite          []string               `json:\"invite\"`\n\tName            string                 `json:\"name\"`\n\tVisibility      string                 `json:\"visibility\"`\n\tTopic           string                 `json:\"topic\"`\n\tPreset          string                 `json:\"preset\"`\n\tCreationContent map[string]interface{} `json:\"creation_content\"`\n\tInitialState    []fledglingEvent       `json:\"initial_state\"`\n\tRoomAliasName   string                 `json:\"room_alias_name\"`\n\tGuestCanJoin    bool                   `json:\"guest_can_join\"`\n}\n\nconst (\n\tpresetPrivateChat        = \"private_chat\"\n\tpresetTrustedPrivateChat = \"trusted_private_chat\"\n\tpresetPublicChat         = \"public_chat\"\n)\n\nconst (\n\tjoinRulePublic = \"public\"\n\tjoinRuleInvite = \"invite\"\n)\nconst (\n\thistoryVisibilityShared = \"shared\"\n\t\/\/ TODO: These should be implemented once history visibility is implemented\n\t\/\/ historyVisibilityWorldReadable = \"world_readable\"\n\t\/\/ historyVisibilityInvited       = \"invited\"\n)\n\nfunc (r createRoomRequest) Validate() *util.JSONResponse {\n\twhitespace := \"\\t\\n\\x0b\\x0c\\r \" \/\/ https:\/\/docs.python.org\/2\/library\/string.html#string.whitespace\n\t\/\/ https:\/\/github.com\/matrix-org\/synapse\/blob\/v0.19.2\/synapse\/handlers\/room.py#L81\n\t\/\/ Synapse doesn't check for ':' but we will else it will break parsers badly which split things into 2 segments.\n\tif strings.ContainsAny(r.RoomAliasName, whitespace+\":\") {\n\t\treturn &util.JSONResponse{\n\t\t\tCode: http.StatusBadRequest,\n\t\t\tJSON: jsonerror.BadJSON(\"room_alias_name cannot contain whitespace or ':'\"),\n\t\t}\n\t}\n\tfor _, userID := range r.Invite {\n\t\t\/\/ TODO: We should put user ID parsing code into gomatrixserverlib and use that instead\n\t\t\/\/       (see https:\/\/github.com\/matrix-org\/gomatrixserverlib\/blob\/3394e7c7003312043208aa73727d2256eea3d1f6\/eventcontent.go#L347 )\n\t\t\/\/       It should be a struct (with pointers into a single string to avoid copying) and\n\t\t\/\/       we should update all refs to use UserID types rather than strings.\n\t\t\/\/ https:\/\/github.com\/matrix-org\/synapse\/blob\/v0.19.2\/synapse\/types.py#L92\n\t\tif _, _, err := gomatrixserverlib.SplitID('@', userID); err != nil {\n\t\t\treturn &util.JSONResponse{\n\t\t\t\tCode: http.StatusBadRequest,\n\t\t\t\tJSON: jsonerror.BadJSON(\"user id must be in the form @localpart:domain\"),\n\t\t\t}\n\t\t}\n\t}\n\tswitch r.Preset {\n\tcase presetPrivateChat, presetTrustedPrivateChat, presetPublicChat, \"\":\n\tdefault:\n\t\treturn &util.JSONResponse{\n\t\t\tCode: http.StatusBadRequest,\n\t\t\tJSON: jsonerror.BadJSON(\"preset must be any of 'private_chat', 'trusted_private_chat', 'public_chat'\"),\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ https:\/\/matrix.org\/docs\/spec\/client_server\/r0.2.0.html#post-matrix-client-r0-createroom\ntype createRoomResponse struct {\n\tRoomID    string `json:\"room_id\"`\n\tRoomAlias string `json:\"room_alias,omitempty\"` \/\/ in synapse not spec\n}\n\n\/\/ fledglingEvent is a helper representation of an event used when creating many events in succession.\ntype fledglingEvent struct {\n\tType     string      `json:\"type\"`\n\tStateKey string      `json:\"state_key\"`\n\tContent  interface{} `json:\"content\"`\n}\n\n\/\/ CreateRoom implements \/createRoom\nfunc CreateRoom(\n\treq *http.Request, device *authtypes.Device,\n\tcfg config.Dendrite, producer *producers.RoomserverProducer,\n\taccountDB *accounts.Database, aliasAPI api.RoomserverAliasAPI,\n) util.JSONResponse {\n\t\/\/ TODO (#267): Check room ID doesn't clash with an existing one, and we\n\t\/\/              probably shouldn't be using pseudo-random strings, maybe GUIDs?\n\troomID := fmt.Sprintf(\"!%s:%s\", util.RandomString(16), cfg.Matrix.ServerName)\n\treturn createRoom(req, device, cfg, roomID, producer, accountDB, aliasAPI)\n}\n\n\/\/ createRoom implements \/createRoom\n\/\/ nolint: gocyclo\nfunc createRoom(\n\treq *http.Request, device *authtypes.Device,\n\tcfg config.Dendrite, roomID string, producer *producers.RoomserverProducer,\n\taccountDB *accounts.Database, aliasAPI api.RoomserverAliasAPI,\n) util.JSONResponse {\n\tlogger := util.GetLogger(req.Context())\n\tuserID := device.UserID\n\tvar r createRoomRequest\n\tresErr := httputil.UnmarshalJSONRequest(req, &r)\n\tif resErr != nil {\n\t\treturn *resErr\n\t}\n\t\/\/ TODO: apply rate-limit\n\n\tif resErr = r.Validate(); resErr != nil {\n\t\treturn *resErr\n\t}\n\n\t\/\/ TODO: visibility\/presets\/raw initial state\/creation content\n\n\t\/\/ TODO: Create room alias association\n\t\/\/ Make sure this doesn't fall into an application service's namespace though!\n\n\tlogger.WithFields(log.Fields{\n\t\t\"userID\": userID,\n\t\t\"roomID\": roomID,\n\t}).Info(\"Creating new room\")\n\n\tlocalpart, _, err := gomatrixserverlib.SplitID('@', userID)\n\tif err != nil {\n\t\treturn httputil.LogThenError(req, err)\n\t}\n\n\tprofile, err := accountDB.GetProfileByLocalpart(req.Context(), localpart)\n\tif err != nil {\n\t\treturn httputil.LogThenError(req, err)\n\t}\n\n\tmembershipContent := common.MemberContent{\n\t\tMembership:  \"join\",\n\t\tDisplayName: profile.DisplayName,\n\t\tAvatarURL:   profile.AvatarURL,\n\t}\n\n\tvar joinRules, historyVisibility string\n\tswitch r.Preset {\n\tcase presetPrivateChat:\n\t\tjoinRules = joinRuleInvite\n\t\thistoryVisibility = historyVisibilityShared\n\tcase presetTrustedPrivateChat:\n\t\tjoinRules = joinRuleInvite\n\t\thistoryVisibility = historyVisibilityShared\n\t\t\/\/ TODO If trusted_private_chat, all invitees are given the same power level as the room creator.\n\tcase presetPublicChat:\n\t\tjoinRules = joinRulePublic\n\t\thistoryVisibility = historyVisibilityShared\n\tdefault:\n\t\t\/\/ Default room rules, r.Preset was previously checked for valid values so\n\t\t\/\/ only a request with no preset should end up here.\n\t\tjoinRules = joinRuleInvite\n\t\thistoryVisibility = historyVisibilityShared\n\t}\n\n\tvar builtEvents []gomatrixserverlib.Event\n\n\t\/\/ send events into the room in order of:\n\t\/\/  1- m.room.create\n\t\/\/  2- room creator join member\n\t\/\/  3- m.room.power_levels\n\t\/\/  4- m.room.canonical_alias (opt) TODO\n\t\/\/  5- m.room.join_rules\n\t\/\/  6- m.room.history_visibility\n\t\/\/  7- m.room.guest_access (opt)\n\t\/\/  8- other initial state items\n\t\/\/  9- m.room.name (opt)\n\t\/\/  10- m.room.topic (opt)\n\t\/\/  11- invite events (opt) - with is_direct flag if applicable TODO\n\t\/\/  12- 3pid invite events (opt) TODO\n\t\/\/  13- m.room.aliases event for HS (if alias specified) TODO\n\t\/\/ This differs from Synapse slightly. Synapse would vary the ordering of 3-7\n\t\/\/ depending on if those events were in \"initial_state\" or not. This made it\n\t\/\/ harder to reason about, hence sticking to a strict static ordering.\n\t\/\/ TODO: Synapse has txn\/token ID on each event. Do we need to do this here?\n\teventsToMake := []fledglingEvent{\n\t\t{\"m.room.create\", \"\", common.CreateContent{Creator: userID}},\n\t\t{\"m.room.member\", userID, membershipContent},\n\t\t{\"m.room.power_levels\", \"\", common.InitialPowerLevelsContent(userID)},\n\t\t\/\/ TODO: m.room.canonical_alias\n\t\t{\"m.room.join_rules\", \"\", common.JoinRulesContent{JoinRule: joinRules}},\n\t\t{\"m.room.history_visibility\", \"\", common.HistoryVisibilityContent{HistoryVisibility: historyVisibility}},\n\t}\n\tif r.GuestCanJoin {\n\t\teventsToMake = append(eventsToMake, fledglingEvent{\"m.room.guest_access\", \"\", common.GuestAccessContent{GuestAccess: \"can_join\"}})\n\t}\n\teventsToMake = append(eventsToMake, r.InitialState...)\n\tif r.Name != \"\" {\n\t\teventsToMake = append(eventsToMake, fledglingEvent{\"m.room.name\", \"\", common.NameContent{Name: r.Name}})\n\t}\n\tif r.Topic != \"\" {\n\t\teventsToMake = append(eventsToMake, fledglingEvent{\"m.room.topic\", \"\", common.TopicContent{Topic: r.Topic}})\n\t}\n\t\/\/ TODO: invite events\n\t\/\/ TODO: 3pid invite events\n\t\/\/ TODO: m.room.aliases\n\n\tauthEvents := gomatrixserverlib.NewAuthEvents(nil)\n\tfor i, e := range eventsToMake {\n\t\tdepth := i + 1 \/\/ depth starts at 1\n\n\t\tbuilder := gomatrixserverlib.EventBuilder{\n\t\t\tSender:   userID,\n\t\t\tRoomID:   roomID,\n\t\t\tType:     e.Type,\n\t\t\tStateKey: &e.StateKey,\n\t\t\tDepth:    int64(depth),\n\t\t}\n\t\terr = builder.SetContent(e.Content)\n\t\tif err != nil {\n\t\t\treturn httputil.LogThenError(req, err)\n\t\t}\n\t\tif i > 0 {\n\t\t\tbuilder.PrevEvents = []gomatrixserverlib.EventReference{builtEvents[i-1].EventReference()}\n\t\t}\n\t\tvar ev *gomatrixserverlib.Event\n\t\tev, err = buildEvent(req, &builder, &authEvents, cfg)\n\t\tif err != nil {\n\t\t\treturn httputil.LogThenError(req, err)\n\t\t}\n\n\t\tif err = gomatrixserverlib.Allowed(*ev, &authEvents); err != nil {\n\t\t\treturn httputil.LogThenError(req, err)\n\t\t}\n\n\t\t\/\/ Add the event to the list of auth events\n\t\tbuiltEvents = append(builtEvents, *ev)\n\t\terr = authEvents.AddEvent(ev)\n\t\tif err != nil {\n\t\t\treturn httputil.LogThenError(req, err)\n\t\t}\n\t}\n\n\t\/\/ send events to the room server\n\t_, err = producer.SendEvents(req.Context(), builtEvents, cfg.Matrix.ServerName, nil)\n\tif err != nil {\n\t\treturn httputil.LogThenError(req, err)\n\t}\n\n\t\/\/ TODO(#269): Reserve room alias while we create the room. This stops us\n\t\/\/ from creating the room but still failing due to the alias having already\n\t\/\/ been taken.\n\tvar roomAlias string\n\tif r.RoomAliasName != \"\" {\n\t\troomAlias = fmt.Sprintf(\"#%s:%s\", r.RoomAliasName, cfg.Matrix.ServerName)\n\n\t\taliasReq := api.SetRoomAliasRequest{\n\t\t\tAlias:  roomAlias,\n\t\t\tRoomID: roomID,\n\t\t\tUserID: userID,\n\t\t}\n\n\t\tvar aliasResp api.SetRoomAliasResponse\n\t\terr = aliasAPI.SetRoomAlias(req.Context(), &aliasReq, &aliasResp)\n\t\tif err != nil {\n\t\t\treturn httputil.LogThenError(req, err)\n\t\t}\n\n\t\tif aliasResp.AliasExists {\n\t\t\treturn util.MessageResponse(400, \"Alias already exists\")\n\t\t}\n\t}\n\n\tresponse := createRoomResponse{\n\t\tRoomID:    roomID,\n\t\tRoomAlias: roomAlias,\n\t}\n\n\treturn util.JSONResponse{\n\t\tCode: 200,\n\t\tJSON: response,\n\t}\n}\n\n\/\/ buildEvent fills out auth_events for the builder then builds the event\nfunc buildEvent(\n\treq *http.Request,\n\tbuilder *gomatrixserverlib.EventBuilder,\n\tprovider gomatrixserverlib.AuthEventProvider,\n\tcfg config.Dendrite,\n) (*gomatrixserverlib.Event, error) {\n\n\teventsNeeded, err := gomatrixserverlib.StateNeededForEventBuilder(builder)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trefs, err := eventsNeeded.AuthEventReferences(provider)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbuilder.AuthEvents = refs\n\teventID := fmt.Sprintf(\"$%s:%s\", util.RandomString(16), cfg.Matrix.ServerName)\n\teventTime := common.ParseTSParam(req)\n\tevent, err := builder.Build(eventID, eventTime, cfg.Matrix.ServerName, cfg.Matrix.KeyID, cfg.Matrix.PrivateKey)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot build event %s : Builder failed to build. %s\", builder.Type, err)\n\t}\n\treturn &event, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ $G $D\/$F.go && $L $F.$A && .\/$A.out\n\n\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Implicit methods for embedded types.\n\/\/ Mixed pointer and non-pointer receivers.\n\npackage main\n\ntype T int\nvar nv, np int\n\nfunc (t T) V() {\n\tif t != 42 {\n\t\tpanic(t)\n\t}\n\tnv++\n}\n\nfunc (t *T) P() {\n\tif *t != 42 {\n\t\tpanic(t, *t)\n\t}\n\tnp++\n}\n\ntype V interface { V() }\ntype P interface { P(); V() }\n\ntype S struct {\n\tT;\n}\n\ntype SP struct {\n\t*T;\n}\n\nfunc main() {\n\tvar t T;\n\tvar v V;\n\tvar p P;\n\n\tt = 42;\n\n\tt.P();\n\tt.V();\n\n\tv = t;\n\tv.V();\n\n\tp = &t;\n\tp.P();\n\tp.V();\n\n\tv = &t;\n\tv.V();\n\n\/\/\tp = t;\t\/\/ ERROR\n\n\/\/\tprintln(\"--struct--\");\n\tvar s S;\n\ts.T = 42;\n\ts.P();\n\ts.V();\n\n\tv = s;\n\ts.V();\n\n\tp = &s;\n\tp.P();\n\tp.V();\n\n\tv = &s;\n\tv.V();\n\n\/\/\tp = s;\t\/\/ ERROR\n\n\/\/\tprintln(\"--struct pointer--\");\n\tvar sp SP;\n\tsp.T = &t;\n\tsp.P();\n\tsp.V();\n\n\tv = sp;\n\tsp.V();\n\n\tp = &sp;\n\tp.P();\n\tp.V();\n\n\tv = &sp;\n\tv.V();\n\n\tp = sp;\t\/\/ not error\n\tp.P();\n\tp.V();\n\n\tif nv != 13 || np != 7 {\n\t\tpanicln(\"bad count\", nv, np)\n\t}\n}\n\n<commit_msg>test\/interface\/receiver.go: expand to do dynamic \tversions of static checks in receiver1.go<commit_after>\/\/ $G $D\/$F.go && $L $F.$A && .\/$A.out\n\n\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ Implicit methods for embedded types.\n\/\/ Mixed pointer and non-pointer receivers.\n\npackage main\n\ntype T int\nvar nv, np int\n\nfunc (t T) V() {\n\tif t != 42 {\n\t\tpanic(t)\n\t}\n\tnv++\n}\n\nfunc (t *T) P() {\n\tif *t != 42 {\n\t\tpanic(t, *t)\n\t}\n\tnp++\n}\n\ntype V interface { V() }\ntype P interface { P(); V() }\n\ntype S struct {\n\tT;\n}\n\ntype SP struct {\n\t*T;\n}\n\nfunc main() {\n\tvar t T;\n\tvar v V;\n\tvar p P;\n\n\tt = 42;\n\n\tt.P();\n\tt.V();\n\n\tv = t;\n\tv.V();\n\n\tp = &t;\n\tp.P();\n\tp.V();\n\n\tv = &t;\n\tv.V();\n\n\/\/\tp = t;\t\/\/ ERROR\n\tvar i interface{} = t;\n\tif _, ok := i.(P); ok {\n\t\tpanicln(\"dynamic i.(P) succeeded incorrectly\");\n\t}\n\n\/\/\tprintln(\"--struct--\");\n\tvar s S;\n\ts.T = 42;\n\ts.P();\n\ts.V();\n\n\tv = s;\n\ts.V();\n\n\tp = &s;\n\tp.P();\n\tp.V();\n\n\tv = &s;\n\tv.V();\n\n\/\/\tp = s;\t\/\/ ERROR\n\tvar j interface{} = s;\n\tif _, ok := j.(P); ok {\n\t\tpanicln(\"dynamic j.(P) succeeded incorrectly\");\n\t}\n\n\/\/\tprintln(\"--struct pointer--\");\n\tvar sp SP;\n\tsp.T = &t;\n\tsp.P();\n\tsp.V();\n\n\tv = sp;\n\tsp.V();\n\n\tp = &sp;\n\tp.P();\n\tp.V();\n\n\tv = &sp;\n\tv.V();\n\n\tp = sp;\t\/\/ not error\n\tp.P();\n\tp.V();\n\n\tif nv != 13 || np != 7 {\n\t\tpanicln(\"bad count\", nv, np)\n\t}\n}\n\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2013 The Go Authors.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage ipv6_test\n\nimport (\n\t\"net\"\n\t\"os\"\n\t\"runtime\"\n\t\"testing\"\n\n\t\"golang.org\/x\/net\/internal\/nettest\"\n\t\"golang.org\/x\/net\/ipv6\"\n)\n\nvar supportsIPv6 bool = nettest.SupportsIPv6()\n\nfunc TestConnInitiatorPathMTU(t *testing.T) {\n\tswitch runtime.GOOS {\n\tcase \"nacl\", \"plan9\", \"solaris\", \"windows\":\n\t\tt.Skipf(\"not supported on %q\", runtime.GOOS)\n\t}\n\tif !supportsIPv6 {\n\t\tt.Skip(\"ipv6 is not supported\")\n\t}\n\n\tln, err := net.Listen(\"tcp6\", \"[::1]:0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer ln.Close()\n\n\tdone := make(chan bool)\n\tgo acceptor(t, ln, done)\n\n\tc, err := net.Dial(\"tcp6\", ln.Addr().String())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer c.Close()\n\n\tif pmtu, err := ipv6.NewConn(c).PathMTU(); err != nil {\n\t\tswitch runtime.GOOS {\n\t\tcase \"darwin\": \/\/ older darwin kernels don't support IPV6_PATHMTU option\n\t\t\tt.Logf(\"not supported on %q\", runtime.GOOS)\n\t\tdefault:\n\t\t\tt.Fatal(err)\n\t\t}\n\t} else {\n\t\tt.Logf(\"path mtu for %v: %v\", c.RemoteAddr(), pmtu)\n\t}\n\n\t<-done\n}\n\nfunc TestConnResponderPathMTU(t *testing.T) {\n\tswitch runtime.GOOS {\n\tcase \"nacl\", \"plan9\", \"solaris\", \"windows\":\n\t\tt.Skipf(\"not supported on %q\", runtime.GOOS)\n\t}\n\tif !supportsIPv6 {\n\t\tt.Skip(\"ipv6 is not supported\")\n\t}\n\n\tln, err := net.Listen(\"tcp6\", \"[::1]:0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer ln.Close()\n\n\tdone := make(chan bool)\n\tgo connector(t, \"tcp6\", ln.Addr().String(), done)\n\n\tc, err := ln.Accept()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer c.Close()\n\n\tif pmtu, err := ipv6.NewConn(c).PathMTU(); err != nil {\n\t\tswitch runtime.GOOS {\n\t\tcase \"darwin\": \/\/ older darwin kernels don't support IPV6_PATHMTU option\n\t\t\tt.Logf(\"not supported on %q\", runtime.GOOS)\n\t\tdefault:\n\t\t\tt.Fatal(err)\n\t\t}\n\t} else {\n\t\tt.Logf(\"path mtu for %v: %v\", c.RemoteAddr(), pmtu)\n\t}\n\n\t<-done\n}\n\nfunc TestPacketConnChecksum(t *testing.T) {\n\tswitch runtime.GOOS {\n\tcase \"nacl\", \"plan9\", \"solaris\", \"windows\":\n\t\tt.Skipf(\"not supported on %q\", runtime.GOOS)\n\t}\n\tif !supportsIPv6 {\n\t\tt.Skip(\"ipv6 is not supported\")\n\t}\n\tif os.Getuid() != 0 {\n\t\tt.Skip(\"must be root\")\n\t}\n\n\tc, err := net.ListenPacket(\"ip6:89\", \"::\") \/\/ OSPF for IPv6\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer c.Close()\n\n\tp := ipv6.NewPacketConn(c)\n\toffset := 12 \/\/ see RFC 5340\n\n\tfor _, toggle := range []bool{false, true} {\n\t\tif err := p.SetChecksum(toggle, offset); err != nil {\n\t\t\tif toggle {\n\t\t\t\tt.Fatalf(\"ipv6.PacketConn.SetChecksum(%v, %v) failed: %v\", toggle, offset, err)\n\t\t\t} else {\n\t\t\t\t\/\/ Some platforms never allow to disable the kernel\n\t\t\t\t\/\/ checksum processing.\n\t\t\t\tt.Logf(\"ipv6.PacketConn.SetChecksum(%v, %v) failed: %v\", toggle, offset, err)\n\t\t\t}\n\t\t}\n\t\tif on, offset, err := p.Checksum(); err != nil {\n\t\t\tt.Fatal(err)\n\t\t} else {\n\t\t\tt.Logf(\"kernel checksum processing enabled=%v, offset=%v\", on, offset)\n\t\t}\n\t}\n}\n<commit_msg>x\/net\/ipv6: replace a magic number with an iana constant<commit_after>\/\/ Copyright 2013 The Go Authors.  All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage ipv6_test\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n\t\"runtime\"\n\t\"testing\"\n\n\t\"golang.org\/x\/net\/internal\/iana\"\n\t\"golang.org\/x\/net\/internal\/nettest\"\n\t\"golang.org\/x\/net\/ipv6\"\n)\n\nvar supportsIPv6 bool = nettest.SupportsIPv6()\n\nfunc TestConnInitiatorPathMTU(t *testing.T) {\n\tswitch runtime.GOOS {\n\tcase \"nacl\", \"plan9\", \"solaris\", \"windows\":\n\t\tt.Skipf(\"not supported on %q\", runtime.GOOS)\n\t}\n\tif !supportsIPv6 {\n\t\tt.Skip(\"ipv6 is not supported\")\n\t}\n\n\tln, err := net.Listen(\"tcp6\", \"[::1]:0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer ln.Close()\n\n\tdone := make(chan bool)\n\tgo acceptor(t, ln, done)\n\n\tc, err := net.Dial(\"tcp6\", ln.Addr().String())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer c.Close()\n\n\tif pmtu, err := ipv6.NewConn(c).PathMTU(); err != nil {\n\t\tswitch runtime.GOOS {\n\t\tcase \"darwin\": \/\/ older darwin kernels don't support IPV6_PATHMTU option\n\t\t\tt.Logf(\"not supported on %q\", runtime.GOOS)\n\t\tdefault:\n\t\t\tt.Fatal(err)\n\t\t}\n\t} else {\n\t\tt.Logf(\"path mtu for %v: %v\", c.RemoteAddr(), pmtu)\n\t}\n\n\t<-done\n}\n\nfunc TestConnResponderPathMTU(t *testing.T) {\n\tswitch runtime.GOOS {\n\tcase \"nacl\", \"plan9\", \"solaris\", \"windows\":\n\t\tt.Skipf(\"not supported on %q\", runtime.GOOS)\n\t}\n\tif !supportsIPv6 {\n\t\tt.Skip(\"ipv6 is not supported\")\n\t}\n\n\tln, err := net.Listen(\"tcp6\", \"[::1]:0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer ln.Close()\n\n\tdone := make(chan bool)\n\tgo connector(t, \"tcp6\", ln.Addr().String(), done)\n\n\tc, err := ln.Accept()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer c.Close()\n\n\tif pmtu, err := ipv6.NewConn(c).PathMTU(); err != nil {\n\t\tswitch runtime.GOOS {\n\t\tcase \"darwin\": \/\/ older darwin kernels don't support IPV6_PATHMTU option\n\t\t\tt.Logf(\"not supported on %q\", runtime.GOOS)\n\t\tdefault:\n\t\t\tt.Fatal(err)\n\t\t}\n\t} else {\n\t\tt.Logf(\"path mtu for %v: %v\", c.RemoteAddr(), pmtu)\n\t}\n\n\t<-done\n}\n\nfunc TestPacketConnChecksum(t *testing.T) {\n\tswitch runtime.GOOS {\n\tcase \"nacl\", \"plan9\", \"solaris\", \"windows\":\n\t\tt.Skipf(\"not supported on %q\", runtime.GOOS)\n\t}\n\tif !supportsIPv6 {\n\t\tt.Skip(\"ipv6 is not supported\")\n\t}\n\tif os.Getuid() != 0 {\n\t\tt.Skip(\"must be root\")\n\t}\n\n\tc, err := net.ListenPacket(fmt.Sprintf(\"ip6:%d\", iana.ProtocolIPv6ICMP), \"::\") \/\/ OSPF for IPv6\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer c.Close()\n\n\tp := ipv6.NewPacketConn(c)\n\toffset := 12 \/\/ see RFC 5340\n\n\tfor _, toggle := range []bool{false, true} {\n\t\tif err := p.SetChecksum(toggle, offset); err != nil {\n\t\t\tif toggle {\n\t\t\t\tt.Fatalf(\"ipv6.PacketConn.SetChecksum(%v, %v) failed: %v\", toggle, offset, err)\n\t\t\t} else {\n\t\t\t\t\/\/ Some platforms never allow to disable the kernel\n\t\t\t\t\/\/ checksum processing.\n\t\t\t\tt.Logf(\"ipv6.PacketConn.SetChecksum(%v, %v) failed: %v\", toggle, offset, err)\n\t\t\t}\n\t\t}\n\t\tif on, offset, err := p.Checksum(); err != nil {\n\t\t\tt.Fatal(err)\n\t\t} else {\n\t\t\tt.Logf(\"kernel checksum processing enabled=%v, offset=%v\", on, offset)\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\"\n\t\"runtime\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/fukata\/golang-stats-api-handler\"\n\t\"github.com\/jessevdk\/go-flags\"\n\t\"github.com\/kazeburo\/chocon\/proxy\"\n\t\"github.com\/lestrrat\/go-apache-logformat\"\n\t\"github.com\/lestrrat\/go-file-rotatelogs\"\n\t\"github.com\/lestrrat\/go-server-starter-listener\"\n)\n\nvar (\n\tVersion string\n)\n\ntype cmdOpts struct {\n\tListen           string `short:\"l\" long:\"listen\" default:\"0.0.0.0\" description:\"address to bind\"`\n\tPort             string `short:\"p\" long:\"port\" default:\"3000\" description:\"Port number to bind\"`\n\tLogDir           string `long:\"access-log-dir\" default:\"\" description:\"directory to store logfiles\"`\n\tLogRotate        int64  `long:\"access-log-rotate\" default:\"30\" description:\"Number of day before remove logs\"`\n\tVersion          bool   `short:\"v\" long:\"version\" description:\"Show version\"`\n\tKeepaliveConns   int    `short:\"c\" default:\"2\" long:\"keepalive-conns\" description:\"maximum keepalive connections for upstream\"`\n\tReadTimeout      int    `long:\"read-timeout\" default:\"30\" description:\"timeout of reading request\"`\n\tWriteTimeout     int    `long:\"write-timeout\" default:\"90\" description:\"timeout of writing response\"`\n\tProxyReadTimeout int    `long:\"proxy-read-timeout\" default:\"60\" description:\"timeout of reading response from upstream\"`\n}\n\nfunc addStatsHandler(h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif strings.Index(r.URL.Path, \"\/.api\/stats\") == 0 {\n\t\t\tstats_api.Handler(w, r)\n\t\t} else {\n\t\t\th.ServeHTTP(w, r)\n\t\t}\n\t})\n}\n\nfunc addLogHandler(h http.Handler, logDir string, logRotate int64) http.Server {\n\tapacheLog, err := apachelog.New(`%h %l %u %t \"%r\" %>s %b \"%v\" %T.%{msec_frac}t %{X-Chocon-Req}i`)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"could not create logger: %v\", err))\n\t}\n\n\tif logDir == \"stdout\" {\n\t\treturn http.Server{\n\t\t\tHandler: apacheLog.Wrap(h, os.Stdout),\n\t\t}\n\t} else if logDir == \"\" {\n\t\treturn http.Server{\n\t\t\tHandler: apacheLog.Wrap(h, os.Stderr),\n\t\t}\n\t} else if logDir == \"none\" {\n\t\treturn http.Server{\n\t\t\tHandler: h,\n\t\t}\n\t}\n\n\tlogFile := logDir\n\tlinkName := logDir\n\tif !strings.HasSuffix(logDir, \"\/\") {\n\t\tlogFile += \"\/\"\n\t\tlinkName += \"\/\"\n\n\t}\n\tlogFile += \"access_log.%Y%m%d%H%M\"\n\tlinkName += \"current\"\n\n\trl, err := rotatelogs.New(\n\t\tlogFile,\n\t\trotatelogs.WithLinkName(linkName),\n\t\trotatelogs.WithMaxAge(time.Duration(logRotate)*86400*time.Second),\n\t\trotatelogs.WithRotationTime(time.Second*86400),\n\t)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"rotatelogs.New failed: %v\", err))\n\t}\n\n\treturn http.Server{\n\t\tHandler: apacheLog.Wrap(h, rl),\n\t}\n}\n\nfunc main() {\n\topts := cmdOpts{}\n\tpsr := flags.NewParser(&opts, flags.Default)\n\t_, err := psr.Parse()\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n\n\tif opts.Version {\n\t\tfmt.Printf(`chocon %s\nCompiler: %s %s\n`,\n\t\t\tVersion,\n\t\t\truntime.Compiler,\n\t\t\truntime.Version())\n\t\treturn\n\n\t}\n\n\trequestConverter := func(r *http.Request, pr *http.Request, ps *proxy.ProxyStatus) {\n\t\tif r.Host == \"\" {\n\t\t\tps.Status = http.StatusBadRequest\n\t\t\treturn\n\t\t}\n\t\thost := strings.Split(r.Host, \":\")[0]\n\t\thostSplit := strings.Split(host, \".\")\n\t\tlastPartIndex := 0\n\t\tfor i, hostPart := range hostSplit {\n\t\t\tif hostPart == \"ccnproxy-ssl\" || hostPart == \"ccnproxy-secure\" || hostPart == \"ccnproxy-https\" || hostPart == \"ccnproxy\" {\n\t\t\t\tlastPartIndex = i\n\t\t\t}\n\t\t}\n\t\tif lastPartIndex == 0 {\n\t\t\tps.Status = http.StatusBadRequest\n\t\t\treturn\n\t\t}\n\n\t\tpr.URL.Host = strings.Join(hostSplit[0:lastPartIndex], \".\")\n\t\tpr.Host = pr.URL.Host\n\t\tif hostSplit[lastPartIndex] == \"ccnproxy-https\" || hostSplit[lastPartIndex] == \"ccnproxy-secure\" || hostSplit[lastPartIndex] == \"ccnproxy-ssl\" {\n\t\t\tpr.URL.Scheme = \"https\"\n\t\t}\n\t}\n\n\tvar transport http.RoundTripper = &http.Transport{\n\t\t\/\/ inherited http.DefaultTransport\n\t\tProxy: http.ProxyFromEnvironment,\n\t\tDialContext: (&net.Dialer{\n\t\t\tTimeout:   30 * time.Second,\n\t\t\tKeepAlive: 30 * time.Second,\n\t\t}).DialContext,\n\t\tIdleConnTimeout:       90 * time.Second,\n\t\tTLSHandshakeTimeout:   10 * time.Second,\n\t\tExpectContinueTimeout: 1 * time.Second,\n\t\t\/\/ self-customized values\n\t\tMaxIdleConnsPerHost:   opts.KeepaliveConns,\n\t\tResponseHeaderTimeout: time.Duration(opts.ProxyReadTimeout) * time.Second,\n\t}\n\n\tproxyHandler := addStatsHandler(proxy.NewProxyWithRequestConverter(requestConverter, &transport))\n\n\tl, err := ss.NewListener()\n\tif l == nil || err != nil {\n\t\t\/\/ Fallback if not running under Server::Starter\n\t\tl, err = net.Listen(\"tcp\", fmt.Sprintf(\"%s:%s\", opts.Listen, opts.Port))\n\t\tif err != nil {\n\t\t\tpanic(fmt.Sprintf(\"Failed to listen to port %s:%s\", opts.Listen, opts.Port))\n\t\t}\n\t}\n\n\tserver := addLogHandler(proxyHandler, opts.LogDir, opts.LogRotate)\n\tserver.ReadTimeout = time.Duration(opts.ReadTimeout) * time.Second\n\tserver.WriteTimeout = time.Duration(opts.WriteTimeout) * time.Second\n\tserver.Serve(l)\n}\n<commit_msg>Support optional custom port number in Host header<commit_after>package main\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"net\/http\"\n\t\"os\"\n\t\"runtime\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/fukata\/golang-stats-api-handler\"\n\t\"github.com\/jessevdk\/go-flags\"\n\t\"github.com\/kazeburo\/chocon\/proxy\"\n\t\"github.com\/lestrrat\/go-apache-logformat\"\n\t\"github.com\/lestrrat\/go-file-rotatelogs\"\n\t\"github.com\/lestrrat\/go-server-starter-listener\"\n)\n\nvar (\n\tVersion string\n)\n\ntype cmdOpts struct {\n\tListen           string `short:\"l\" long:\"listen\" default:\"0.0.0.0\" description:\"address to bind\"`\n\tPort             string `short:\"p\" long:\"port\" default:\"3000\" description:\"Port number to bind\"`\n\tLogDir           string `long:\"access-log-dir\" default:\"\" description:\"directory to store logfiles\"`\n\tLogRotate        int64  `long:\"access-log-rotate\" default:\"30\" description:\"Number of day before remove logs\"`\n\tVersion          bool   `short:\"v\" long:\"version\" description:\"Show version\"`\n\tKeepaliveConns   int    `short:\"c\" default:\"2\" long:\"keepalive-conns\" description:\"maximum keepalive connections for upstream\"`\n\tReadTimeout      int    `long:\"read-timeout\" default:\"30\" description:\"timeout of reading request\"`\n\tWriteTimeout     int    `long:\"write-timeout\" default:\"90\" description:\"timeout of writing response\"`\n\tProxyReadTimeout int    `long:\"proxy-read-timeout\" default:\"60\" description:\"timeout of reading response from upstream\"`\n}\n\nfunc addStatsHandler(h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif strings.Index(r.URL.Path, \"\/.api\/stats\") == 0 {\n\t\t\tstats_api.Handler(w, r)\n\t\t} else {\n\t\t\th.ServeHTTP(w, r)\n\t\t}\n\t})\n}\n\nfunc addLogHandler(h http.Handler, logDir string, logRotate int64) http.Server {\n\tapacheLog, err := apachelog.New(`%h %l %u %t \"%r\" %>s %b \"%v\" %T.%{msec_frac}t %{X-Chocon-Req}i`)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"could not create logger: %v\", err))\n\t}\n\n\tif logDir == \"stdout\" {\n\t\treturn http.Server{\n\t\t\tHandler: apacheLog.Wrap(h, os.Stdout),\n\t\t}\n\t} else if logDir == \"\" {\n\t\treturn http.Server{\n\t\t\tHandler: apacheLog.Wrap(h, os.Stderr),\n\t\t}\n\t} else if logDir == \"none\" {\n\t\treturn http.Server{\n\t\t\tHandler: h,\n\t\t}\n\t}\n\n\tlogFile := logDir\n\tlinkName := logDir\n\tif !strings.HasSuffix(logDir, \"\/\") {\n\t\tlogFile += \"\/\"\n\t\tlinkName += \"\/\"\n\n\t}\n\tlogFile += \"access_log.%Y%m%d%H%M\"\n\tlinkName += \"current\"\n\n\trl, err := rotatelogs.New(\n\t\tlogFile,\n\t\trotatelogs.WithLinkName(linkName),\n\t\trotatelogs.WithMaxAge(time.Duration(logRotate)*86400*time.Second),\n\t\trotatelogs.WithRotationTime(time.Second*86400),\n\t)\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"rotatelogs.New failed: %v\", err))\n\t}\n\n\treturn http.Server{\n\t\tHandler: apacheLog.Wrap(h, rl),\n\t}\n}\n\nfunc main() {\n\topts := cmdOpts{}\n\tpsr := flags.NewParser(&opts, flags.Default)\n\t_, err := psr.Parse()\n\tif err != nil {\n\t\tos.Exit(1)\n\t}\n\n\tif opts.Version {\n\t\tfmt.Printf(`chocon %s\nCompiler: %s %s\n`,\n\t\t\tVersion,\n\t\t\truntime.Compiler,\n\t\t\truntime.Version())\n\t\treturn\n\n\t}\n\n\trequestConverter := func(r *http.Request, pr *http.Request, ps *proxy.ProxyStatus) {\n\t\tif r.Host == \"\" {\n\t\t\tps.Status = http.StatusBadRequest\n\t\t\treturn\n\t\t}\n\t\thostPortSplit := strings.Split(r.Host, \":\")\n\t\thost := hostPortSplit[0]\n\t\tport := \"\"\n\t\tif len(hostPortSplit) > 1 {\n\t\t\tport = \":\" + hostPortSplit[1]\n\t\t}\n\t\thostSplit := strings.Split(host, \".\")\n\t\tlastPartIndex := 0\n\t\tfor i, hostPart := range hostSplit {\n\t\t\tif hostPart == \"ccnproxy-ssl\" || hostPart == \"ccnproxy-secure\" || hostPart == \"ccnproxy-https\" || hostPart == \"ccnproxy\" {\n\t\t\t\tlastPartIndex = i\n\t\t\t}\n\t\t}\n\t\tif lastPartIndex == 0 {\n\t\t\tps.Status = http.StatusBadRequest\n\t\t\treturn\n\t\t}\n\n\t\tpr.URL.Host = strings.Join(hostSplit[0:lastPartIndex], \".\") + port\n\t\tpr.Host = pr.URL.Host\n\t\tif hostSplit[lastPartIndex] == \"ccnproxy-https\" || hostSplit[lastPartIndex] == \"ccnproxy-secure\" || hostSplit[lastPartIndex] == \"ccnproxy-ssl\" {\n\t\t\tpr.URL.Scheme = \"https\"\n\t\t}\n\t}\n\n\tvar transport http.RoundTripper = &http.Transport{\n\t\t\/\/ inherited http.DefaultTransport\n\t\tProxy: http.ProxyFromEnvironment,\n\t\tDialContext: (&net.Dialer{\n\t\t\tTimeout:   30 * time.Second,\n\t\t\tKeepAlive: 30 * time.Second,\n\t\t}).DialContext,\n\t\tIdleConnTimeout:       90 * time.Second,\n\t\tTLSHandshakeTimeout:   10 * time.Second,\n\t\tExpectContinueTimeout: 1 * time.Second,\n\t\t\/\/ self-customized values\n\t\tMaxIdleConnsPerHost:   opts.KeepaliveConns,\n\t\tResponseHeaderTimeout: time.Duration(opts.ProxyReadTimeout) * time.Second,\n\t}\n\n\tproxyHandler := addStatsHandler(proxy.NewProxyWithRequestConverter(requestConverter, &transport))\n\n\tl, err := ss.NewListener()\n\tif l == nil || err != nil {\n\t\t\/\/ Fallback if not running under Server::Starter\n\t\tl, err = net.Listen(\"tcp\", fmt.Sprintf(\"%s:%s\", opts.Listen, opts.Port))\n\t\tif err != nil {\n\t\t\tpanic(fmt.Sprintf(\"Failed to listen to port %s:%s\", opts.Listen, opts.Port))\n\t\t}\n\t}\n\n\tserver := addLogHandler(proxyHandler, opts.LogDir, opts.LogRotate)\n\tserver.ReadTimeout = time.Duration(opts.ReadTimeout) * time.Second\n\tserver.WriteTimeout = time.Duration(opts.WriteTimeout) * time.Second\n\tserver.Serve(l)\n}\n<|endoftext|>"}
{"text":"<commit_before>package discovery\n\nimport (\n\t\"fmt\"\n\t\"github.com\/golang\/glog\"\n\t\"net\/url\"\n\t\"strings\"\n)\n\ntype Service interface {\n\tGet(key string) ([]string, error)\n}\n\ntype NoopDiscovery struct{}\n\nfunc NewNoopDiscovery() *NoopDiscovery {\n\treturn &NoopDiscovery{}\n}\n\nfunc (d *NoopDiscovery) Get(serviceName string) ([]string, error) {\n\treturn []string{}, nil\n}\n\nfunc New(discoveryUrl string) (Service, error) {\n\n\tif !strings.Contains(discoveryUrl, \":\") {\n\t\tdiscoveryUrl = discoveryUrl + \":\/\/\"\n\t}\n\n\tu, err := url.Parse(discoveryUrl)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tswitch u.Scheme {\n\tcase \"noop\":\n\t\treturn NewNoopDiscovery(), nil\n\tcase \"disabled\":\n\t\treturn NewNoopDiscovery(), nil\n\tcase \"rackspace\":\n\t\treturn NewRackspaceFromUrl(u)\n\tcase \"etcd\":\n\t\thosts := strings.Split(u.Host, \",\")\n\t\treturn NewEtcd(hosts), nil\n\tdefault:\n\t\tglog.Errorf(\"Bad URL for discovery: %s\", discoveryUrl)\n\t\treturn nil, fmt.Errorf(\"invalid configuration: Unknown discovery scheme: %s\", u.Scheme)\n\t}\n\n\treturn nil, nil\n}\n<commit_msg>Remove dead return.<commit_after>package discovery\n\nimport (\n\t\"fmt\"\n\t\"github.com\/golang\/glog\"\n\t\"net\/url\"\n\t\"strings\"\n)\n\ntype Service interface {\n\tGet(key string) ([]string, error)\n}\n\ntype NoopDiscovery struct{}\n\nfunc NewNoopDiscovery() *NoopDiscovery {\n\treturn &NoopDiscovery{}\n}\n\nfunc (d *NoopDiscovery) Get(serviceName string) ([]string, error) {\n\treturn []string{}, nil\n}\n\nfunc New(discoveryUrl string) (Service, error) {\n\n\tif !strings.Contains(discoveryUrl, \":\") {\n\t\tdiscoveryUrl = discoveryUrl + \":\/\/\"\n\t}\n\n\tu, err := url.Parse(discoveryUrl)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tswitch u.Scheme {\n\tcase \"noop\":\n\t\treturn NewNoopDiscovery(), nil\n\tcase \"disabled\":\n\t\treturn NewNoopDiscovery(), nil\n\tcase \"rackspace\":\n\t\treturn NewRackspaceFromUrl(u)\n\tcase \"etcd\":\n\t\thosts := strings.Split(u.Host, \",\")\n\t\treturn NewEtcd(hosts), nil\n\tdefault:\n\t\tglog.Errorf(\"Bad URL for discovery: %s\", discoveryUrl)\n\t\treturn nil, fmt.Errorf(\"invalid configuration: Unknown discovery scheme: %s\", u.Scheme)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport (\n\t\"encoding\/base64\"\n\t\"path\/filepath\"\n\t\"errors\"\n\t\"os\"\n\n\t\"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/github.com\/gonuts\/flag\"\n\t\"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/github.com\/jbenet\/commander\"\n\tconfig \"github.com\/jbenet\/go-ipfs\/config\"\n\tci \"github.com\/jbenet\/go-ipfs\/crypto\"\n\tspipe \"github.com\/jbenet\/go-ipfs\/crypto\/spipe\"\n\tu \"github.com\/jbenet\/go-ipfs\/util\"\n)\n\nvar cmdIpfsInit = &commander.Command{\n\tUsageLine: \"init\",\n\tShort:     \"Initialize ipfs local configuration\",\n\tLong: `ipfs init\n\n\tInitializes ipfs configuration files and generates a\n\tnew keypair.\n`,\n\tRun:  initCmd,\n\tFlag: *flag.NewFlagSet(\"ipfs-init\", flag.ExitOnError),\n}\n\nfunc init() {\n\tcmdIpfsInit.Flag.Int(\"b\", 4096, \"number of bits for keypair\")\n\tcmdIpfsInit.Flag.String(\"p\", \"\", \"passphrase for encrypting keys\")\n\tcmdIpfsInit.Flag.Bool(\"f\", false, \"force overwrite of existing config\")\n\tcmdIpfsInit.Flag.String(\"d\", \"\", \"Change default datastore location\")\n}\n\nfunc initCmd(c *commander.Command, inp []string) error {\n\tconfigpath, err := getConfigDir(c.Parent)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tu.POut(\"initializing ipfs node at %s\\n\", configpath)\n\tfilename, err := config.Filename(configpath)\n\tif err != nil {\n\t\treturn errors.New(\"Couldn't get home directory path\")\n\t}\n\n\tdspath, ok := c.Flag.Lookup(\"d\").Value.Get().(string)\n\tif !ok {\n\t\treturn errors.New(\"failed to parse datastore flag\")\n\t}\n\n\tfi, err := os.Lstat(filename)\n\tforce, ok := c.Flag.Lookup(\"f\").Value.Get().(bool)\n\tif !ok {\n\t\treturn errors.New(\"failed to parse force flag\")\n\t}\n\tif fi != nil || (err != nil && !os.IsNotExist(err)) {\n\t\tif !force {\n\t\t\treturn errors.New(\"ipfs configuration file already exists!\\nReinitializing would overwrite your keys.\\n(use -f to force overwrite)\")\n\t\t}\n\t}\n\tcfg := new(config.Config)\n\n\tcfg.Datastore = config.Datastore{}\n\tif len(dspath) == 0 {\n\t\tdspath, err = config.DataStorePath(\"\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tcfg.Datastore.Path = dspath\n\tcfg.Datastore.Type = \"leveldb\"\n\n\t\/\/ Construct the data store if missing\n\tif err := os.MkdirAll(dspath, os.ModeDir); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Check the directory is writeable\n\tif f, err := os.Create(filepath.Join(dspath, \"._check_writeable\")); err == nil {\n\t\tos.Remove(f.Name())\n\t} else {\n\t\treturn errors.New(\"Datastore '\" + dspath + \"' is not writeable\")\n\t}\n\n\tcfg.Identity = config.Identity{}\n\n\t\/\/ setup the node addresses.\n\tcfg.Addresses = config.Addresses{\n\t\tSwarm: \"\/ip4\/0.0.0.0\/tcp\/4001\",\n\t\tAPI:   \"\/ip4\/127.0.0.1\/tcp\/5001\",\n\t}\n\n\tnbits, ok := c.Flag.Lookup(\"b\").Value.Get().(int)\n\tif !ok {\n\t\treturn errors.New(\"failed to get bits flag\")\n\t}\n\tif nbits < 1024 {\n\t\treturn errors.New(\"Bitsize less than 1024 is considered unsafe.\")\n\t}\n\n\tu.POut(\"generating key pair\\n\")\n\tsk, pk, err := ci.GenerateKeyPair(ci.RSA, nbits)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ currently storing key unencrypted. in the future we need to encrypt it.\n\t\/\/ TODO(security)\n\tskbytes, err := sk.Bytes()\n\tif err != nil {\n\t\treturn err\n\t}\n\tcfg.Identity.PrivKey = base64.StdEncoding.EncodeToString(skbytes)\n\n\tid, err := spipe.IDFromPubKey(pk)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcfg.Identity.PeerID = id.Pretty()\n\n\t\/\/ Use these hardcoded bootstrap peers for now.\n\tcfg.Bootstrap = []*config.BootstrapPeer{\n\t\t&config.BootstrapPeer{\n\t\t\t\/\/ mars.i.ipfs.io\n\t\t\tPeerID:  \"QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ\",\n\t\t\tAddress: \"\/ip4\/104.131.131.82\/tcp\/4001\",\n\t\t},\n\t}\n\n\terr = config.WriteConfigFile(filename, cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n<commit_msg>When initializing datastore, create directory with correct permissions.<commit_after>package main\n\nimport (\n\t\"encoding\/base64\"\n\t\"path\/filepath\"\n\t\"errors\"\n\t\"os\"\n\n\t\"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/github.com\/gonuts\/flag\"\n\t\"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/github.com\/jbenet\/commander\"\n\tconfig \"github.com\/jbenet\/go-ipfs\/config\"\n\tci \"github.com\/jbenet\/go-ipfs\/crypto\"\n\tspipe \"github.com\/jbenet\/go-ipfs\/crypto\/spipe\"\n\tu \"github.com\/jbenet\/go-ipfs\/util\"\n)\n\nvar cmdIpfsInit = &commander.Command{\n\tUsageLine: \"init\",\n\tShort:     \"Initialize ipfs local configuration\",\n\tLong: `ipfs init\n\n\tInitializes ipfs configuration files and generates a\n\tnew keypair.\n`,\n\tRun:  initCmd,\n\tFlag: *flag.NewFlagSet(\"ipfs-init\", flag.ExitOnError),\n}\n\nfunc init() {\n\tcmdIpfsInit.Flag.Int(\"b\", 4096, \"number of bits for keypair\")\n\tcmdIpfsInit.Flag.String(\"p\", \"\", \"passphrase for encrypting keys\")\n\tcmdIpfsInit.Flag.Bool(\"f\", false, \"force overwrite of existing config\")\n\tcmdIpfsInit.Flag.String(\"d\", \"\", \"Change default datastore location\")\n}\n\nfunc initCmd(c *commander.Command, inp []string) error {\n\tconfigpath, err := getConfigDir(c.Parent)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tu.POut(\"initializing ipfs node at %s\\n\", configpath)\n\tfilename, err := config.Filename(configpath)\n\tif err != nil {\n\t\treturn errors.New(\"Couldn't get home directory path\")\n\t}\n\n\tdspath, ok := c.Flag.Lookup(\"d\").Value.Get().(string)\n\tif !ok {\n\t\treturn errors.New(\"failed to parse datastore flag\")\n\t}\n\n\tfi, err := os.Lstat(filename)\n\tforce, ok := c.Flag.Lookup(\"f\").Value.Get().(bool)\n\tif !ok {\n\t\treturn errors.New(\"failed to parse force flag\")\n\t}\n\tif fi != nil || (err != nil && !os.IsNotExist(err)) {\n\t\tif !force {\n\t\t\treturn errors.New(\"ipfs configuration file already exists!\\nReinitializing would overwrite your keys.\\n(use -f to force overwrite)\")\n\t\t}\n\t}\n\tcfg := new(config.Config)\n\n\tcfg.Datastore = config.Datastore{}\n\tif len(dspath) == 0 {\n\t\tdspath, err = config.DataStorePath(\"\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tcfg.Datastore.Path = dspath\n\tcfg.Datastore.Type = \"leveldb\"\n\n\t\/\/ Construct the data store if missing\n\tif err := os.MkdirAll(dspath, os.ModePerm); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Check the directory is writeable\n\tif f, err := os.Create(filepath.Join(dspath, \"._check_writeable\")); err == nil {\n\t\tos.Remove(f.Name())\n\t} else {\n\t\treturn errors.New(\"Datastore '\" + dspath + \"' is not writeable\")\n\t}\n\n\tcfg.Identity = config.Identity{}\n\n\t\/\/ setup the node addresses.\n\tcfg.Addresses = config.Addresses{\n\t\tSwarm: \"\/ip4\/0.0.0.0\/tcp\/4001\",\n\t\tAPI:   \"\/ip4\/127.0.0.1\/tcp\/5001\",\n\t}\n\n\tnbits, ok := c.Flag.Lookup(\"b\").Value.Get().(int)\n\tif !ok {\n\t\treturn errors.New(\"failed to get bits flag\")\n\t}\n\tif nbits < 1024 {\n\t\treturn errors.New(\"Bitsize less than 1024 is considered unsafe.\")\n\t}\n\n\tu.POut(\"generating key pair\\n\")\n\tsk, pk, err := ci.GenerateKeyPair(ci.RSA, nbits)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ currently storing key unencrypted. in the future we need to encrypt it.\n\t\/\/ TODO(security)\n\tskbytes, err := sk.Bytes()\n\tif err != nil {\n\t\treturn err\n\t}\n\tcfg.Identity.PrivKey = base64.StdEncoding.EncodeToString(skbytes)\n\n\tid, err := spipe.IDFromPubKey(pk)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcfg.Identity.PeerID = id.Pretty()\n\n\t\/\/ Use these hardcoded bootstrap peers for now.\n\tcfg.Bootstrap = []*config.BootstrapPeer{\n\t\t&config.BootstrapPeer{\n\t\t\t\/\/ mars.i.ipfs.io\n\t\t\tPeerID:  \"QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ\",\n\t\t\tAddress: \"\/ip4\/104.131.131.82\/tcp\/4001\",\n\t\t},\n\t}\n\n\terr = config.WriteConfigFile(filename, cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package glfw3\n\n\/\/ Not sure about the darwin flag\n\n\/\/ Windows users: If you download the GLFW 64-bit binaries, when you copy over the contents of the lib folder make sure to rename\n\/\/ glfw3dll.a to libglfw3dll.a, it doesn't work otherwise.\n\n\/\/#cgo windows LDFLAGS: -lglfw3dll -lopengl32 -lgdi32\n\/\/#cgo linux LDGLAGS: -lglfw\n\/\/#cgo darwin LDFLAGS: -lglfw\n\/\/#ifdef _WIN32\n\/\/  #define GLFW_DLL\n\/\/#endif\n\/\/#include <GLFW\/glfw3.h>\nimport \"C\"\n\nconst (\n\tVersionMajor    = C.GLFW_VERSION_MAJOR    \/\/This is incremented when the API is changed in non-compatible ways.\n\tVersionMinor    = C.GLFW_VERSION_MINOR    \/\/This is incremented when features are added to the API but it remains backward-compatible.\n\tVersionRevision = C.GLFW_VERSION_REVISION \/\/This is incremented when a bug fix release is made that does not contain any API changes.\n)\n\n\/\/Init initializes the GLFW library. Before most GLFW functions can be used,\n\/\/GLFW must be initialized, and before a program terminates GLFW should be\n\/\/terminated in order to free any resources allocated during or after\n\/\/initialization.\n\/\/\n\/\/If this function fails, it calls Terminate before returning. If it succeeds,\n\/\/you should call Terminate before the program exits.\n\/\/\n\/\/Additional calls to this function after successful initialization but before\n\/\/termination will succeed but will do nothing.\n\/\/\n\/\/This function may take several seconds to complete on some systems, while on\n\/\/other systems it may take only a fraction of a second to complete.\n\/\/\n\/\/On Mac OS X, this function will change the current directory of the\n\/\/application to the Contents\/Resources subdirectory of the application's\n\/\/bundle, if present.\nfunc Init() bool {\n\tr := C.glfwInit()\n\n\tif r == C.GL_TRUE {\n\t\treturn true\n\t}\n\treturn false\n}\n\n\/\/Terminate destroys all remaining windows, frees any allocated resources and\n\/\/sets the library to an uninitialized state. Once this is called, you must\n\/\/again call Init successfully before you will be able to use most GLFW\n\/\/functions.\n\/\/\n\/\/If GLFW has been successfully initialized, this function should be called\n\/\/before the program exits. If initialization fails, there is no need to call\n\/\/this function, as it is called by Init before it returns failure.\nfunc Terminate() {\n\tC.glfwTerminate()\n}\n\n\/\/GetVersion retrieves the major, minor and revision numbers of the GLFW\n\/\/library. It is intended for when you are using GLFW as a shared library and\n\/\/want to ensure that you are using the minimum required version.\n\/\/\n\/\/This function may be called before Init.\nfunc GetVersion() (int, int, int) {\n\tvar (\n\t\tmajor C.int\n\t\tminor C.int\n\t\trev   C.int\n\t)\n\n\tC.glfwGetVersion(&major, &minor, &rev)\n\treturn int(major), int(minor), int(rev)\n}\n\n\/\/GetVersionString returns a static string generated at compile-time according\n\/\/to which configuration macros were defined. This is intended for use when\n\/\/submitting bug reports, to allow developers to see which code paths are\n\/\/enabled in a binary.\n\/\/\n\/\/This function may be called before Init.\nfunc GetVersionString() string {\n\treturn C.GoString(C.glfwGetVersionString())\n}\n<commit_msg>Fix typo in #cgo directives.<commit_after>package glfw3\n\n\/\/ Not sure about the darwin flag\n\n\/\/ Windows users: If you download the GLFW 64-bit binaries, when you copy over the contents of the lib folder make sure to rename\n\/\/ glfw3dll.a to libglfw3dll.a, it doesn't work otherwise.\n\n\/\/#cgo windows LDFLAGS: -lglfw3dll -lopengl32 -lgdi32\n\/\/#cgo linux LDFLAGS: -lglfw\n\/\/#cgo darwin LDFLAGS: -lglfw\n\/\/#ifdef _WIN32\n\/\/  #define GLFW_DLL\n\/\/#endif\n\/\/#include <GLFW\/glfw3.h>\nimport \"C\"\n\nconst (\n\tVersionMajor    = C.GLFW_VERSION_MAJOR    \/\/This is incremented when the API is changed in non-compatible ways.\n\tVersionMinor    = C.GLFW_VERSION_MINOR    \/\/This is incremented when features are added to the API but it remains backward-compatible.\n\tVersionRevision = C.GLFW_VERSION_REVISION \/\/This is incremented when a bug fix release is made that does not contain any API changes.\n)\n\n\/\/Init initializes the GLFW library. Before most GLFW functions can be used,\n\/\/GLFW must be initialized, and before a program terminates GLFW should be\n\/\/terminated in order to free any resources allocated during or after\n\/\/initialization.\n\/\/\n\/\/If this function fails, it calls Terminate before returning. If it succeeds,\n\/\/you should call Terminate before the program exits.\n\/\/\n\/\/Additional calls to this function after successful initialization but before\n\/\/termination will succeed but will do nothing.\n\/\/\n\/\/This function may take several seconds to complete on some systems, while on\n\/\/other systems it may take only a fraction of a second to complete.\n\/\/\n\/\/On Mac OS X, this function will change the current directory of the\n\/\/application to the Contents\/Resources subdirectory of the application's\n\/\/bundle, if present.\nfunc Init() bool {\n\tr := C.glfwInit()\n\n\tif r == C.GL_TRUE {\n\t\treturn true\n\t}\n\treturn false\n}\n\n\/\/Terminate destroys all remaining windows, frees any allocated resources and\n\/\/sets the library to an uninitialized state. Once this is called, you must\n\/\/again call Init successfully before you will be able to use most GLFW\n\/\/functions.\n\/\/\n\/\/If GLFW has been successfully initialized, this function should be called\n\/\/before the program exits. If initialization fails, there is no need to call\n\/\/this function, as it is called by Init before it returns failure.\nfunc Terminate() {\n\tC.glfwTerminate()\n}\n\n\/\/GetVersion retrieves the major, minor and revision numbers of the GLFW\n\/\/library. It is intended for when you are using GLFW as a shared library and\n\/\/want to ensure that you are using the minimum required version.\n\/\/\n\/\/This function may be called before Init.\nfunc GetVersion() (int, int, int) {\n\tvar (\n\t\tmajor C.int\n\t\tminor C.int\n\t\trev   C.int\n\t)\n\n\tC.glfwGetVersion(&major, &minor, &rev)\n\treturn int(major), int(minor), int(rev)\n}\n\n\/\/GetVersionString returns a static string generated at compile-time according\n\/\/to which configuration macros were defined. This is intended for use when\n\/\/submitting bug reports, to allow developers to see which code paths are\n\/\/enabled in a binary.\n\/\/\n\/\/This function may be called before Init.\nfunc GetVersionString() string {\n\treturn C.GoString(C.glfwGetVersionString())\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2015 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage fs\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"reflect\"\n\n\t\"github.com\/jacobsa\/fuse\"\n\t\"github.com\/jacobsa\/fuse\/fuseutil\"\n\t\"github.com\/jacobsa\/gcloud\/gcs\"\n\t\"github.com\/jacobsa\/gcloud\/syncutil\"\n\t\"github.com\/jacobsa\/gcsfuse\/fs\/inode\"\n\t\"github.com\/jacobsa\/gcsfuse\/timeutil\"\n\t\"golang.org\/x\/net\/context\"\n\t\"google.golang.org\/cloud\/storage\"\n)\n\ntype fileSystem struct {\n\tfuseutil.NotImplementedFileSystem\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Dependencies\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tclock  timeutil.Clock\n\tbucket gcs.Bucket\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Mutable state\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\/\/ When acquiring this lock, the caller must hold no inode or dir handle\n\t\/\/ locks.\n\tmu syncutil.InvariantMutex\n\n\t\/\/ The user and group owning everything in the file system.\n\t\/\/\n\t\/\/ GUARDED_BY(Mu)\n\tuid uint32\n\tgid uint32\n\n\t\/\/ The collection of live inodes, keyed by inode ID. No ID less than\n\t\/\/ fuse.RootInodeID is ever used.\n\t\/\/\n\t\/\/ TODO(jacobsa): Implement ForgetInode support in the fuse package, then\n\t\/\/ implement the method here and clean up these maps.\n\t\/\/\n\t\/\/ INVARIANT: All values are of type *inode.DirInode or *inode.FileInode\n\t\/\/ INVARIANT: For all keys k, k >= fuse.RootInodeID\n\t\/\/ INVARIANT: For all keys k, inodes[k].ID() == k\n\t\/\/ INVARIANT: inodes[fuse.RootInodeID] is of type *inode.DirInode\n\t\/\/\n\t\/\/ GUARDED_BY(mu)\n\tinodes map[fuse.InodeID]inode.Inode\n\n\t\/\/ The next inode ID to hand out. We assume that this will never overflow,\n\t\/\/ since even if we were handing out inode IDs at 4 GHz, it would still take\n\t\/\/ over a century to do so.\n\t\/\/\n\t\/\/ INVARIANT: For all keys k in inodes, k < nextInodeID\n\t\/\/\n\t\/\/ GUARDED_BY(mu)\n\tnextInodeID fuse.InodeID\n\n\t\/\/ An index of all directory inodes by Name().\n\t\/\/\n\t\/\/ INVARIANT: For each key k, isDirName(k)\n\t\/\/ INVARIANT: For each key k, dirIndex[k].Name() == k\n\t\/\/ INVARIANT: The values are all and only the values of the inodes map of\n\t\/\/ type *inode.DirInode.\n\t\/\/\n\t\/\/ GUARDED_BY(mu)\n\tdirIndex map[string]*inode.DirInode\n\n\t\/\/ An index of all file inodes by (Name(), SourceGeneration()) pairs.\n\t\/\/\n\t\/\/ INVARIANT: For each key k, !isDirName(k)\n\t\/\/ INVARIANT: For each key k, fileIndex[k].Name() == k.name\n\t\/\/ INVARIANT: For each key k, fileIndex[k].SourceGeneration() == k.gen\n\t\/\/ INVARIANT: The values are all and only the values of the inodes map of\n\t\/\/ type *inode.FileInode.\n\t\/\/\n\t\/\/ GUARDED_BY(mu)\n\tfileIndex map[nameAndGen]*inode.FileInode\n\n\t\/\/ The collection of live handles, keyed by handle ID.\n\t\/\/\n\t\/\/ INVARIANT: All values are of type *dirHandle\n\t\/\/\n\t\/\/ GUARDED_BY(mu)\n\thandles map[fuse.HandleID]interface{}\n\n\t\/\/ The next handle ID to hand out. We assume that this will never overflow.\n\t\/\/\n\t\/\/ INVARIANT: For all keys k in handles, k < nextHandleID\n\t\/\/\n\t\/\/ GUARDED_BY(mu)\n\tnextHandleID fuse.HandleID\n}\n\ntype nameAndGen struct {\n\tname string\n\tgen  int64\n}\n\n\/\/ Create a fuse file system whose root directory is the root of the supplied\n\/\/ bucket. The supplied clock will be used for cache invalidation, modification\n\/\/ times, etc.\nfunc NewFileSystem(\n\tclock timeutil.Clock,\n\tbucket gcs.Bucket) (ffs fuse.FileSystem, err error) {\n\t\/\/ Set up the basic struct.\n\tfs := &fileSystem{\n\t\tclock:       clock,\n\t\tbucket:      bucket,\n\t\tinodes:      make(map[fuse.InodeID]inode.Inode),\n\t\tnextInodeID: fuse.RootInodeID + 1,\n\t\tdirIndex:    make(map[string]*inode.DirInode),\n\t\tfileIndex:   make(map[nameAndGen]*inode.FileInode),\n\t\thandles:     make(map[fuse.HandleID]interface{}),\n\t}\n\n\t\/\/ Set up the root inode.\n\troot := inode.NewDirInode(bucket, fuse.RootInodeID, \"\")\n\tfs.inodes[fuse.RootInodeID] = root\n\tfs.dirIndex[\"\"] = root\n\n\t\/\/ Set up invariant checking.\n\tfs.mu = syncutil.NewInvariantMutex(fs.checkInvariants)\n\n\tffs = fs\n\treturn\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Helpers\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nfunc isDirName(name string) bool {\n\treturn name == \"\" || name[len(name)-1] == '\/'\n}\n\nfunc (fs *fileSystem) checkInvariants() {\n\t\/\/ Check inode keys.\n\tfor id, _ := range fs.inodes {\n\t\tif id < fuse.RootInodeID || id >= fs.nextInodeID {\n\t\t\tpanic(fmt.Sprintf(\"Illegal inode ID: %v\", id))\n\t\t}\n\t}\n\n\t\/\/ Check the root inode.\n\t_ = fs.inodes[fuse.RootInodeID].(*inode.DirInode)\n\n\t\/\/ Check each inode, and the indexes over them. Keep a count of each type\n\t\/\/ seen.\n\tdirsSeen := 0\n\tfilesSeen := 0\n\tfor id, in := range fs.inodes {\n\t\t\/\/ Check the ID.\n\t\tif in.ID() != id {\n\t\t\tpanic(fmt.Sprintf(\"ID mismatch: %v vs. %v\", in.ID(), id))\n\t\t}\n\n\t\t\/\/ Check type-specific stuff.\n\t\tswitch typed := in.(type) {\n\t\tcase *inode.DirInode:\n\t\t\tdirsSeen++\n\n\t\t\tif !isDirName(typed.Name()) {\n\t\t\t\tpanic(fmt.Sprintf(\"Unexpected directory name: %s\", typed.Name()))\n\t\t\t}\n\n\t\t\tif fs.dirIndex[typed.Name()] != typed {\n\t\t\t\tpanic(fmt.Sprintf(\"dirIndex mismatch: %s\", typed.Name()))\n\t\t\t}\n\n\t\tcase *inode.FileInode:\n\t\t\tfilesSeen++\n\n\t\t\tif isDirName(typed.Name()) {\n\t\t\t\tpanic(fmt.Sprintf(\"Unexpected file name: %s\", typed.Name()))\n\t\t\t}\n\n\t\t\tnandg := nameAndGen{typed.Name(), typed.SourceGeneration()}\n\t\t\tif fs.fileIndex[nandg] != typed {\n\t\t\t\tpanic(\n\t\t\t\t\tfmt.Sprintf(\n\t\t\t\t\t\t\"fileIndex mismatch: %s, %v\",\n\t\t\t\t\t\ttyped.Name(),\n\t\t\t\t\t\ttyped.SourceGeneration()))\n\t\t\t}\n\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"Unexpected inode type: %v\", reflect.TypeOf(in)))\n\t\t}\n\t}\n\n\t\/\/ Make sure that the indexes are exhaustive.\n\tif len(fs.dirIndex) != dirsSeen {\n\t\tpanic(\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"dirIndex length mismatch: %v vs. %v\",\n\t\t\t\tlen(fs.dirIndex),\n\t\t\t\tdirsSeen))\n\t}\n\n\tif len(fs.fileIndex) != filesSeen {\n\t\tpanic(\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"fileIndex length mismatch: %v vs. %v\",\n\t\t\t\tlen(fs.fileIndex),\n\t\t\t\tdirsSeen))\n\t}\n\n\t\/\/ Check handles.\n\tfor id, h := range fs.handles {\n\t\tif id >= fs.nextHandleID {\n\t\t\tpanic(fmt.Sprintf(\"Illegal handle ID: %v\", id))\n\t\t}\n\n\t\t_ = h.(*dirHandle)\n\t}\n}\n\n\/\/ Get attributes for the inode, fixing up ownership information.\n\/\/\n\/\/ SHARED_LOCKS_REQUIRED(fs.mu)\n\/\/ EXCLUSIVE_LOCKS_REQUIRED(in)\nfunc (fs *fileSystem) getAttributes(\n\tctx context.Context,\n\tin inode.Inode) (attrs fuse.InodeAttributes, err error) {\n\tattrs, err = in.Attributes(ctx)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tattrs.Uid = fs.uid\n\tattrs.Gid = fs.gid\n\n\treturn\n}\n\n\/\/ Find a directory inode for the given object record. Create one if there\n\/\/ isn't already one available.\n\/\/\n\/\/ EXCLUSIVE_LOCKS_REQUIRED(fs.mu)\nfunc (fs *fileSystem) lookUpOrCreateDirInode(\n\tctx context.Context,\n\to *storage.Object) (in *inode.DirInode, err error) {\n\t\/\/ Do we already have an inode for this name?\n\tif in = fs.dirIndex[o.Name]; in != nil {\n\t\treturn\n\t}\n\n\t\/\/ Mint an ID.\n\tid := fs.nextInodeID\n\tfs.nextInodeID++\n\n\t\/\/ Create and index an inode.\n\tin = inode.NewDirInode(fs.bucket, id, o.Name)\n\tfs.inodes[id] = in\n\tfs.dirIndex[in.Name()] = in\n\n\treturn\n}\n\n\/\/ Find a file inode for the given object record. Create one if there isn't\n\/\/ already one available.\n\/\/\n\/\/ EXCLUSIVE_LOCKS_REQUIRED(fs.mu)\nfunc (fs *fileSystem) lookUpOrCreateFileInode(\n\tctx context.Context,\n\to *storage.Object) (in *inode.FileInode, err error) {\n\tnandg := nameAndGen{\n\t\tname: o.Name,\n\t\tgen:  o.Generation,\n\t}\n\n\t\/\/ Do we already have an inode for this (name, generation) pair?\n\tif in = fs.fileIndex[nandg]; in != nil {\n\t\treturn\n\t}\n\n\t\/\/ Mint an ID.\n\tid := fs.nextInodeID\n\tfs.nextInodeID++\n\n\t\/\/ Create and index an inode.\n\tin = inode.NewFileInode(fs.bucket, id, o)\n\tfs.inodes[id] = in\n\tfs.fileIndex[nandg] = in\n\n\treturn\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ fuse.FileSystem methods\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ LOCKS_EXCLUDED(fs.mu)\nfunc (fs *fileSystem) Init(\n\tctx context.Context,\n\treq *fuse.InitRequest) (resp *fuse.InitResponse, err error) {\n\tresp = &fuse.InitResponse{}\n\n\tfs.mu.Lock()\n\tdefer fs.mu.Unlock()\n\n\t\/\/ Store the mounting user's info for later.\n\tfs.uid = req.Header.Uid\n\tfs.gid = req.Header.Gid\n\n\treturn\n}\n\n\/\/ LOCKS_EXCLUDED(fs.mu)\nfunc (fs *fileSystem) LookUpInode(\n\tctx context.Context,\n\treq *fuse.LookUpInodeRequest) (resp *fuse.LookUpInodeResponse, err error) {\n\tresp = &fuse.LookUpInodeResponse{}\n\n\tfs.mu.Lock()\n\tdefer fs.mu.Unlock()\n\n\t\/\/ Find the parent directory in question.\n\tparent := fs.inodes[req.Parent].(*inode.DirInode)\n\n\t\/\/ Find a record for the child with the given name.\n\to, err := parent.LookUpChild(ctx, req.Name)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Is the child a directory or a file?\n\tvar in inode.Inode\n\tif isDirName(o.Name) {\n\t\tin, err = fs.lookUpOrCreateDirInode(ctx, o)\n\t} else {\n\t\tin, err = fs.lookUpOrCreateFileInode(ctx, o)\n\t}\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tin.Lock()\n\tdefer in.Unlock()\n\n\t\/\/ Fill out the response.\n\tresp.Entry.Child = in.ID()\n\tif resp.Entry.Attributes, err = fs.getAttributes(ctx, in); err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\n\/\/ LOCKS_EXCLUDED(fs.mu)\nfunc (fs *fileSystem) GetInodeAttributes(\n\tctx context.Context,\n\treq *fuse.GetInodeAttributesRequest) (\n\tresp *fuse.GetInodeAttributesResponse, err error) {\n\tresp = &fuse.GetInodeAttributesResponse{}\n\n\tfs.mu.RLock()\n\tdefer fs.mu.RUnlock()\n\n\t\/\/ Find the inode.\n\tin := fs.inodes[req.Inode]\n\n\tin.Lock()\n\tdefer in.Unlock()\n\n\t\/\/ Grab its attributes.\n\tresp.Attributes, err = fs.getAttributes(ctx, in)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\n\/\/ LOCKS_EXCLUDED(fs.mu)\nfunc (fs *fileSystem) OpenDir(\n\tctx context.Context,\n\treq *fuse.OpenDirRequest) (resp *fuse.OpenDirResponse, err error) {\n\tresp = &fuse.OpenDirResponse{}\n\n\tfs.mu.Lock()\n\tdefer fs.mu.Unlock()\n\n\t\/\/ Make sure the inode still exists and is a directory. If not, something has\n\t\/\/ screwed up because the VFS layer shouldn't have let us forget the inode\n\t\/\/ before opening it.\n\tin := fs.inodes[req.Inode].(*inode.DirInode)\n\tin.Lock()\n\tdefer in.Unlock()\n\n\t\/\/ Allocate a handle.\n\thandleID := fs.nextHandleID\n\tfs.nextHandleID++\n\n\tfs.handles[handleID] = newDirHandle(in)\n\tresp.Handle = handleID\n\n\treturn\n}\n\n\/\/ LOCKS_EXCLUDED(fs.mu)\nfunc (fs *fileSystem) ReadDir(\n\tctx context.Context,\n\treq *fuse.ReadDirRequest) (resp *fuse.ReadDirResponse, err error) {\n\tfs.mu.RLock()\n\tdefer fs.mu.RUnlock()\n\n\t\/\/ Find the handle.\n\tdh := fs.handles[req.Handle].(*dirHandle)\n\tdh.Mu.Lock()\n\tdefer dh.Mu.Unlock()\n\n\t\/\/ Serve the request.\n\tresp, err = dh.ReadDir(ctx, req)\n\n\treturn\n}\n\n\/\/ LOCKS_EXCLUDED(fs.mu)\nfunc (fs *fileSystem) ReleaseDirHandle(\n\tctx context.Context,\n\treq *fuse.ReleaseDirHandleRequest) (\n\tresp *fuse.ReleaseDirHandleResponse, err error) {\n\tresp = &fuse.ReleaseDirHandleResponse{}\n\n\tfs.mu.Lock()\n\tdefer fs.mu.Unlock()\n\n\t\/\/ Sanity check that this handle exists and is of the correct type.\n\t_ = fs.handles[req.Handle].(*dirHandle)\n\n\t\/\/ Clear the entry from the map.\n\tdelete(fs.handles, req.Handle)\n\n\treturn\n}\n\n\/\/ TODO(jacobsa): Make sure we have failing tests for O_CREAT and O_TRUNC\n\/\/ behavior, then implement those.\n\/\/\n\/\/ LOCKS_EXCLUDED(fs.mu)\nfunc (fs *fileSystem) OpenFile(\n\tctx context.Context,\n\treq *fuse.OpenFileRequest) (\n\tresp *fuse.OpenFileResponse, err error) {\n\tresp = &fuse.OpenFileResponse{}\n\n\terr = errors.New(\"TODO(jacobsa): Implement OpenFile.\")\n\treturn\n}\n<commit_msg>Implemented fileSystem.OpenFile.<commit_after>\/\/ Copyright 2015 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage fs\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\n\t\"github.com\/jacobsa\/fuse\"\n\t\"github.com\/jacobsa\/fuse\/fuseutil\"\n\t\"github.com\/jacobsa\/gcloud\/gcs\"\n\t\"github.com\/jacobsa\/gcloud\/syncutil\"\n\t\"github.com\/jacobsa\/gcsfuse\/fs\/inode\"\n\t\"github.com\/jacobsa\/gcsfuse\/timeutil\"\n\t\"golang.org\/x\/net\/context\"\n\t\"google.golang.org\/cloud\/storage\"\n)\n\ntype fileSystem struct {\n\tfuseutil.NotImplementedFileSystem\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Dependencies\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\tclock  timeutil.Clock\n\tbucket gcs.Bucket\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ Mutable state\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\/\/ When acquiring this lock, the caller must hold no inode or dir handle\n\t\/\/ locks.\n\tmu syncutil.InvariantMutex\n\n\t\/\/ The user and group owning everything in the file system.\n\t\/\/\n\t\/\/ GUARDED_BY(Mu)\n\tuid uint32\n\tgid uint32\n\n\t\/\/ The collection of live inodes, keyed by inode ID. No ID less than\n\t\/\/ fuse.RootInodeID is ever used.\n\t\/\/\n\t\/\/ TODO(jacobsa): Implement ForgetInode support in the fuse package, then\n\t\/\/ implement the method here and clean up these maps.\n\t\/\/\n\t\/\/ INVARIANT: All values are of type *inode.DirInode or *inode.FileInode\n\t\/\/ INVARIANT: For all keys k, k >= fuse.RootInodeID\n\t\/\/ INVARIANT: For all keys k, inodes[k].ID() == k\n\t\/\/ INVARIANT: inodes[fuse.RootInodeID] is of type *inode.DirInode\n\t\/\/\n\t\/\/ GUARDED_BY(mu)\n\tinodes map[fuse.InodeID]inode.Inode\n\n\t\/\/ The next inode ID to hand out. We assume that this will never overflow,\n\t\/\/ since even if we were handing out inode IDs at 4 GHz, it would still take\n\t\/\/ over a century to do so.\n\t\/\/\n\t\/\/ INVARIANT: For all keys k in inodes, k < nextInodeID\n\t\/\/\n\t\/\/ GUARDED_BY(mu)\n\tnextInodeID fuse.InodeID\n\n\t\/\/ An index of all directory inodes by Name().\n\t\/\/\n\t\/\/ INVARIANT: For each key k, isDirName(k)\n\t\/\/ INVARIANT: For each key k, dirIndex[k].Name() == k\n\t\/\/ INVARIANT: The values are all and only the values of the inodes map of\n\t\/\/ type *inode.DirInode.\n\t\/\/\n\t\/\/ GUARDED_BY(mu)\n\tdirIndex map[string]*inode.DirInode\n\n\t\/\/ An index of all file inodes by (Name(), SourceGeneration()) pairs.\n\t\/\/\n\t\/\/ INVARIANT: For each key k, !isDirName(k)\n\t\/\/ INVARIANT: For each key k, fileIndex[k].Name() == k.name\n\t\/\/ INVARIANT: For each key k, fileIndex[k].SourceGeneration() == k.gen\n\t\/\/ INVARIANT: The values are all and only the values of the inodes map of\n\t\/\/ type *inode.FileInode.\n\t\/\/\n\t\/\/ GUARDED_BY(mu)\n\tfileIndex map[nameAndGen]*inode.FileInode\n\n\t\/\/ The collection of live handles, keyed by handle ID.\n\t\/\/\n\t\/\/ INVARIANT: All values are of type *dirHandle\n\t\/\/\n\t\/\/ GUARDED_BY(mu)\n\thandles map[fuse.HandleID]interface{}\n\n\t\/\/ The next handle ID to hand out. We assume that this will never overflow.\n\t\/\/\n\t\/\/ INVARIANT: For all keys k in handles, k < nextHandleID\n\t\/\/\n\t\/\/ GUARDED_BY(mu)\n\tnextHandleID fuse.HandleID\n}\n\ntype nameAndGen struct {\n\tname string\n\tgen  int64\n}\n\n\/\/ Create a fuse file system whose root directory is the root of the supplied\n\/\/ bucket. The supplied clock will be used for cache invalidation, modification\n\/\/ times, etc.\nfunc NewFileSystem(\n\tclock timeutil.Clock,\n\tbucket gcs.Bucket) (ffs fuse.FileSystem, err error) {\n\t\/\/ Set up the basic struct.\n\tfs := &fileSystem{\n\t\tclock:       clock,\n\t\tbucket:      bucket,\n\t\tinodes:      make(map[fuse.InodeID]inode.Inode),\n\t\tnextInodeID: fuse.RootInodeID + 1,\n\t\tdirIndex:    make(map[string]*inode.DirInode),\n\t\tfileIndex:   make(map[nameAndGen]*inode.FileInode),\n\t\thandles:     make(map[fuse.HandleID]interface{}),\n\t}\n\n\t\/\/ Set up the root inode.\n\troot := inode.NewDirInode(bucket, fuse.RootInodeID, \"\")\n\tfs.inodes[fuse.RootInodeID] = root\n\tfs.dirIndex[\"\"] = root\n\n\t\/\/ Set up invariant checking.\n\tfs.mu = syncutil.NewInvariantMutex(fs.checkInvariants)\n\n\tffs = fs\n\treturn\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Helpers\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nfunc isDirName(name string) bool {\n\treturn name == \"\" || name[len(name)-1] == '\/'\n}\n\nfunc (fs *fileSystem) checkInvariants() {\n\t\/\/ Check inode keys.\n\tfor id, _ := range fs.inodes {\n\t\tif id < fuse.RootInodeID || id >= fs.nextInodeID {\n\t\t\tpanic(fmt.Sprintf(\"Illegal inode ID: %v\", id))\n\t\t}\n\t}\n\n\t\/\/ Check the root inode.\n\t_ = fs.inodes[fuse.RootInodeID].(*inode.DirInode)\n\n\t\/\/ Check each inode, and the indexes over them. Keep a count of each type\n\t\/\/ seen.\n\tdirsSeen := 0\n\tfilesSeen := 0\n\tfor id, in := range fs.inodes {\n\t\t\/\/ Check the ID.\n\t\tif in.ID() != id {\n\t\t\tpanic(fmt.Sprintf(\"ID mismatch: %v vs. %v\", in.ID(), id))\n\t\t}\n\n\t\t\/\/ Check type-specific stuff.\n\t\tswitch typed := in.(type) {\n\t\tcase *inode.DirInode:\n\t\t\tdirsSeen++\n\n\t\t\tif !isDirName(typed.Name()) {\n\t\t\t\tpanic(fmt.Sprintf(\"Unexpected directory name: %s\", typed.Name()))\n\t\t\t}\n\n\t\t\tif fs.dirIndex[typed.Name()] != typed {\n\t\t\t\tpanic(fmt.Sprintf(\"dirIndex mismatch: %s\", typed.Name()))\n\t\t\t}\n\n\t\tcase *inode.FileInode:\n\t\t\tfilesSeen++\n\n\t\t\tif isDirName(typed.Name()) {\n\t\t\t\tpanic(fmt.Sprintf(\"Unexpected file name: %s\", typed.Name()))\n\t\t\t}\n\n\t\t\tnandg := nameAndGen{typed.Name(), typed.SourceGeneration()}\n\t\t\tif fs.fileIndex[nandg] != typed {\n\t\t\t\tpanic(\n\t\t\t\t\tfmt.Sprintf(\n\t\t\t\t\t\t\"fileIndex mismatch: %s, %v\",\n\t\t\t\t\t\ttyped.Name(),\n\t\t\t\t\t\ttyped.SourceGeneration()))\n\t\t\t}\n\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"Unexpected inode type: %v\", reflect.TypeOf(in)))\n\t\t}\n\t}\n\n\t\/\/ Make sure that the indexes are exhaustive.\n\tif len(fs.dirIndex) != dirsSeen {\n\t\tpanic(\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"dirIndex length mismatch: %v vs. %v\",\n\t\t\t\tlen(fs.dirIndex),\n\t\t\t\tdirsSeen))\n\t}\n\n\tif len(fs.fileIndex) != filesSeen {\n\t\tpanic(\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"fileIndex length mismatch: %v vs. %v\",\n\t\t\t\tlen(fs.fileIndex),\n\t\t\t\tdirsSeen))\n\t}\n\n\t\/\/ Check handles.\n\tfor id, h := range fs.handles {\n\t\tif id >= fs.nextHandleID {\n\t\t\tpanic(fmt.Sprintf(\"Illegal handle ID: %v\", id))\n\t\t}\n\n\t\t_ = h.(*dirHandle)\n\t}\n}\n\n\/\/ Get attributes for the inode, fixing up ownership information.\n\/\/\n\/\/ SHARED_LOCKS_REQUIRED(fs.mu)\n\/\/ EXCLUSIVE_LOCKS_REQUIRED(in)\nfunc (fs *fileSystem) getAttributes(\n\tctx context.Context,\n\tin inode.Inode) (attrs fuse.InodeAttributes, err error) {\n\tattrs, err = in.Attributes(ctx)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tattrs.Uid = fs.uid\n\tattrs.Gid = fs.gid\n\n\treturn\n}\n\n\/\/ Find a directory inode for the given object record. Create one if there\n\/\/ isn't already one available.\n\/\/\n\/\/ EXCLUSIVE_LOCKS_REQUIRED(fs.mu)\nfunc (fs *fileSystem) lookUpOrCreateDirInode(\n\tctx context.Context,\n\to *storage.Object) (in *inode.DirInode, err error) {\n\t\/\/ Do we already have an inode for this name?\n\tif in = fs.dirIndex[o.Name]; in != nil {\n\t\treturn\n\t}\n\n\t\/\/ Mint an ID.\n\tid := fs.nextInodeID\n\tfs.nextInodeID++\n\n\t\/\/ Create and index an inode.\n\tin = inode.NewDirInode(fs.bucket, id, o.Name)\n\tfs.inodes[id] = in\n\tfs.dirIndex[in.Name()] = in\n\n\treturn\n}\n\n\/\/ Find a file inode for the given object record. Create one if there isn't\n\/\/ already one available.\n\/\/\n\/\/ EXCLUSIVE_LOCKS_REQUIRED(fs.mu)\nfunc (fs *fileSystem) lookUpOrCreateFileInode(\n\tctx context.Context,\n\to *storage.Object) (in *inode.FileInode, err error) {\n\tnandg := nameAndGen{\n\t\tname: o.Name,\n\t\tgen:  o.Generation,\n\t}\n\n\t\/\/ Do we already have an inode for this (name, generation) pair?\n\tif in = fs.fileIndex[nandg]; in != nil {\n\t\treturn\n\t}\n\n\t\/\/ Mint an ID.\n\tid := fs.nextInodeID\n\tfs.nextInodeID++\n\n\t\/\/ Create and index an inode.\n\tin = inode.NewFileInode(fs.bucket, id, o)\n\tfs.inodes[id] = in\n\tfs.fileIndex[nandg] = in\n\n\treturn\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ fuse.FileSystem methods\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ LOCKS_EXCLUDED(fs.mu)\nfunc (fs *fileSystem) Init(\n\tctx context.Context,\n\treq *fuse.InitRequest) (resp *fuse.InitResponse, err error) {\n\tresp = &fuse.InitResponse{}\n\n\tfs.mu.Lock()\n\tdefer fs.mu.Unlock()\n\n\t\/\/ Store the mounting user's info for later.\n\tfs.uid = req.Header.Uid\n\tfs.gid = req.Header.Gid\n\n\treturn\n}\n\n\/\/ LOCKS_EXCLUDED(fs.mu)\nfunc (fs *fileSystem) LookUpInode(\n\tctx context.Context,\n\treq *fuse.LookUpInodeRequest) (resp *fuse.LookUpInodeResponse, err error) {\n\tresp = &fuse.LookUpInodeResponse{}\n\n\tfs.mu.Lock()\n\tdefer fs.mu.Unlock()\n\n\t\/\/ Find the parent directory in question.\n\tparent := fs.inodes[req.Parent].(*inode.DirInode)\n\n\t\/\/ Find a record for the child with the given name.\n\to, err := parent.LookUpChild(ctx, req.Name)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Is the child a directory or a file?\n\tvar in inode.Inode\n\tif isDirName(o.Name) {\n\t\tin, err = fs.lookUpOrCreateDirInode(ctx, o)\n\t} else {\n\t\tin, err = fs.lookUpOrCreateFileInode(ctx, o)\n\t}\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tin.Lock()\n\tdefer in.Unlock()\n\n\t\/\/ Fill out the response.\n\tresp.Entry.Child = in.ID()\n\tif resp.Entry.Attributes, err = fs.getAttributes(ctx, in); err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\n\/\/ LOCKS_EXCLUDED(fs.mu)\nfunc (fs *fileSystem) GetInodeAttributes(\n\tctx context.Context,\n\treq *fuse.GetInodeAttributesRequest) (\n\tresp *fuse.GetInodeAttributesResponse, err error) {\n\tresp = &fuse.GetInodeAttributesResponse{}\n\n\tfs.mu.RLock()\n\tdefer fs.mu.RUnlock()\n\n\t\/\/ Find the inode.\n\tin := fs.inodes[req.Inode]\n\n\tin.Lock()\n\tdefer in.Unlock()\n\n\t\/\/ Grab its attributes.\n\tresp.Attributes, err = fs.getAttributes(ctx, in)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\n\/\/ LOCKS_EXCLUDED(fs.mu)\nfunc (fs *fileSystem) OpenDir(\n\tctx context.Context,\n\treq *fuse.OpenDirRequest) (resp *fuse.OpenDirResponse, err error) {\n\tresp = &fuse.OpenDirResponse{}\n\n\tfs.mu.Lock()\n\tdefer fs.mu.Unlock()\n\n\t\/\/ Make sure the inode still exists and is a directory. If not, something has\n\t\/\/ screwed up because the VFS layer shouldn't have let us forget the inode\n\t\/\/ before opening it.\n\tin := fs.inodes[req.Inode].(*inode.DirInode)\n\tin.Lock()\n\tdefer in.Unlock()\n\n\t\/\/ Allocate a handle.\n\thandleID := fs.nextHandleID\n\tfs.nextHandleID++\n\n\tfs.handles[handleID] = newDirHandle(in)\n\tresp.Handle = handleID\n\n\treturn\n}\n\n\/\/ LOCKS_EXCLUDED(fs.mu)\nfunc (fs *fileSystem) ReadDir(\n\tctx context.Context,\n\treq *fuse.ReadDirRequest) (resp *fuse.ReadDirResponse, err error) {\n\tfs.mu.RLock()\n\tdefer fs.mu.RUnlock()\n\n\t\/\/ Find the handle.\n\tdh := fs.handles[req.Handle].(*dirHandle)\n\tdh.Mu.Lock()\n\tdefer dh.Mu.Unlock()\n\n\t\/\/ Serve the request.\n\tresp, err = dh.ReadDir(ctx, req)\n\n\treturn\n}\n\n\/\/ LOCKS_EXCLUDED(fs.mu)\nfunc (fs *fileSystem) ReleaseDirHandle(\n\tctx context.Context,\n\treq *fuse.ReleaseDirHandleRequest) (\n\tresp *fuse.ReleaseDirHandleResponse, err error) {\n\tresp = &fuse.ReleaseDirHandleResponse{}\n\n\tfs.mu.Lock()\n\tdefer fs.mu.Unlock()\n\n\t\/\/ Sanity check that this handle exists and is of the correct type.\n\t_ = fs.handles[req.Handle].(*dirHandle)\n\n\t\/\/ Clear the entry from the map.\n\tdelete(fs.handles, req.Handle)\n\n\treturn\n}\n\n\/\/ TODO(jacobsa): Make sure we have failing tests for O_CREAT and O_TRUNC\n\/\/ behavior, then implement those.\n\/\/\n\/\/ LOCKS_EXCLUDED(fs.mu)\nfunc (fs *fileSystem) OpenFile(\n\tctx context.Context,\n\treq *fuse.OpenFileRequest) (\n\tresp *fuse.OpenFileResponse, err error) {\n\tresp = &fuse.OpenFileResponse{}\n\n\tfs.mu.RLock()\n\tdefer fs.mu.RUnlock()\n\n\t\/\/ Sanity check that this inode exists and is of the correct type.\n\t_ = fs.inodes[req.Inode].(*inode.FileInode)\n\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>package parser\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/wellington\/sass\/ast\"\n\t\"github.com\/wellington\/sass\/token\"\n)\n\nvar validFiles = []string{\n\t\"..\/sass-spec\/spec\/basic\/00_empty\/input.scss\",\n\t\"..\/sass-spec\/spec\/basic\/01_simple_css\/input.scss\",\n\t\"..\/sass-spec\/spec\/basic\/02_simple_nesting\/input.scss\",\n\t\"..\/sass-spec\/spec\/basic\/03_simple_variable\/input.scss\",\n\t\"..\/sass-spec\/spec\/basic\/04_basic_variables\/input.scss\",\n\t\"..\/sass-spec\/spec\/basic\/05_empty_levels\/input.scss\",\n\t\"..\/sass-spec\/spec\/basic\/06_nesting_and_comments\/input.scss\",\n\t\"..\/sass-spec\/spec\/basic\/07_nested_simple_selector_groups\/input.scss\",\n}\n\nfunc TestParse_files(t *testing.T) {\n\tmode := DeclarationErrors\n\tmode = AllErrors + Trace\n\tfor _, name := range validFiles {\n\t\t_, err := ParseFile(token.NewFileSet(), name, nil, mode)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"ParseFile(%s): %v\", name, err)\n\t\t}\n\t}\n}\n\nfunc TestParseDir(t *testing.T) {\n\t\/\/ paths := \"..\/sass-spec\/spec\/basic\/00_empty\"\n}\n\nfunc TestVarScope_list2(t *testing.T) {\n\tt.Skip(\"Parser will have to split rhs lists\")\n\tf, err := ParseFile(token.NewFileSet(), \"main.scss\", `$zz : x,y;`, Trace)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif e := \"main.scss\"; e != f.Name.Name {\n\t\tt.Fatalf(\"got: %s wanted: %s\", f.Name, e)\n\t}\n\n\tvals := f.Decls[0].(*ast.GenDecl).Specs[0].(*ast.ValueSpec).Values\n\n\tif e := 2; len(vals) != e {\n\t\tt.Fatalf(\"got: %d wanted: %d\", len(vals), e)\n\t}\n}\n\nfunc TestVarScope_quotes(t *testing.T) {\n\tf, err := ParseFile(token.NewFileSet(), \"main.scss\", `$zz : word;`, 0)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tvals := f.Decls[0].(*ast.GenDecl).Specs[0].(*ast.ValueSpec).Values\n\n\tif e := 1; len(vals) != e {\n\t\tfor _, v := range vals {\n\t\t\tt.Logf(\"%s % #v\\n\", v.(*ast.BasicLit).Kind, v)\n\t\t}\n\t\tt.Fatalf(\"got: %d wanted: %d\", len(vals), e)\n\t}\n\n\tlit := vals[0].(*ast.BasicLit)\n\tif e := token.QSSTRING; e != lit.Kind {\n\t\t\/\/ t.Fatalf(\"got: %s wanted: %s\", lit.Kind, e)\n\t}\n\n\tf, err = ParseFile(token.NewFileSet(), \"main.scss\", `$zz : \"word\";`, 0)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tvals = f.Decls[0].(*ast.GenDecl).Specs[0].(*ast.ValueSpec).Values\n\tif e := 1; len(vals) != e {\n\t\tt.Fatalf(\"got: %d wanted: %d\", len(vals), e)\n\t}\n\n\tlit = vals[0].(*ast.BasicLit)\n\tif e := token.QSTRING; e != lit.Kind {\n\t\tt.Fatalf(\"got: %s wanted: %s\", lit.Kind, e)\n\t}\n}\n<commit_msg>parse all the basic inputs<commit_after>package parser\n\nimport (\n\t\"fmt\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com\/wellington\/sass\/ast\"\n\t\"github.com\/wellington\/sass\/token\"\n)\n\nfunc TestParse_files(t *testing.T) {\n\tinputs, err := filepath.Glob(\"..\/sass-spec\/spec\/basic\/*\/input.scss\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tmode := DeclarationErrors\n\tmode = AllErrors + Trace\n\tfor _, name := range inputs {\n\t\t\/\/ These are fucked things in Sass like lists\n\t\tif strings.Contains(name, \"15\") {\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Println(\"Parsing\", name)\n\t\t_, err := ParseFile(token.NewFileSet(), name, nil, mode)\n\t\tfmt.Println(\"Done\", name)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"ParseFile(%s): %v\", name, err)\n\t\t}\n\t}\n\tfmt.Println(\"done\")\n}\n\nfunc TestParseDir(t *testing.T) {\n\n}\n\nfunc TestVarScope_list2(t *testing.T) {\n\tt.Skip(\"Parser will have to split rhs lists\")\n\tf, err := ParseFile(token.NewFileSet(), \"main.scss\", `$zz : x,y;`, Trace)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif e := \"main.scss\"; e != f.Name.Name {\n\t\tt.Fatalf(\"got: %s wanted: %s\", f.Name, e)\n\t}\n\n\tvals := f.Decls[0].(*ast.GenDecl).Specs[0].(*ast.ValueSpec).Values\n\n\tif e := 2; len(vals) != e {\n\t\tt.Fatalf(\"got: %d wanted: %d\", len(vals), e)\n\t}\n}\n\nfunc TestVarScope_quotes(t *testing.T) {\n\tf, err := ParseFile(token.NewFileSet(), \"main.scss\", `$zz : word;`, 0)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tvals := f.Decls[0].(*ast.GenDecl).Specs[0].(*ast.ValueSpec).Values\n\n\tif e := 1; len(vals) != e {\n\t\tfor _, v := range vals {\n\t\t\tt.Logf(\"%s % #v\\n\", v.(*ast.BasicLit).Kind, v)\n\t\t}\n\t\tt.Fatalf(\"got: %d wanted: %d\", len(vals), e)\n\t}\n\n\tlit := vals[0].(*ast.BasicLit)\n\tif e := token.QSSTRING; e != lit.Kind {\n\t\t\/\/ t.Fatalf(\"got: %s wanted: %s\", lit.Kind, e)\n\t}\n\n\tf, err = ParseFile(token.NewFileSet(), \"main.scss\", `$zz : \"word\";`, 0)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tvals = f.Decls[0].(*ast.GenDecl).Specs[0].(*ast.ValueSpec).Values\n\tif e := 1; len(vals) != e {\n\t\tt.Fatalf(\"got: %d wanted: %d\", len(vals), e)\n\t}\n\n\tlit = vals[0].(*ast.BasicLit)\n\tif e := token.QSTRING; e != lit.Kind {\n\t\tt.Fatalf(\"got: %s wanted: %s\", lit.Kind, e)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2018 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/    https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage mapper\n\nimport (\n\t\"context\"\n\t\"crypto\/sha256\"\n\t\"fmt\"\n\t\"math\/big\"\n\t\"time\"\n\n\t\"github.com\/ethereum\/go-ethereum\/core\/types\"\n\t\"github.com\/ethereum\/go-ethereum\/rlp\"\n\t\"github.com\/golang\/glog\"\n\t\"github.com\/google\/trillian\"\n)\n\nconst (\n\toneEther int64 = 1000000000000000000\n)\n\nvar oneEtherRatio = big.NewFloat(float64(1) \/ float64(oneEther))\n\ntype Mapper struct {\n\tlogID, mapID int64\n\ttlog         trillian.TrillianLogClient\n\ttmap         trillian.TrillianMapClient\n\n\tunsortedBlocks chan *types.Block\n\tsortedBlocks   chan *types.Block\n}\n\nfunc New(tl trillian.TrillianLogClient, logID int64, tm trillian.TrillianMapClient, mapID int64) *Mapper {\n\treturn &Mapper{\n\t\tlogID: logID,\n\t\tmapID: mapID,\n\t\ttlog:  tl,\n\t\ttmap:  tm,\n\n\t\tunsortedBlocks: make(chan *types.Block, 100000),\n\t\tsortedBlocks:   make(chan *types.Block, 100000),\n\t}\n}\n\nfunc (m *Mapper) fetchBlocks(ctx context.Context, from int64) {\n\tticker := time.NewTicker(time.Second)\n\nnextAttempt:\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase <-ticker.C:\n\t\t}\n\n\t\tnum := int64(200)\n\t\tleaves := make([]int64, num)\n\t\tfor i := int64(0); i < num; i++ {\n\t\t\tleaves[i] = from + i\n\t\t}\n\n\t\tentries, err := m.tlog.GetLeavesByIndex(ctx, &trillian.GetLeavesByIndexRequest{LogId: m.logID, LeafIndex: leaves})\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"Failed to get %d leaves starting at index %d: %v\", num, from, err)\n\t\t\tcontinue nextAttempt\n\t\t}\n\n\t\tfor _, l := range entries.Leaves {\n\t\t\tblock := &types.Block{}\n\t\t\tif err := rlp.DecodeBytes(l.LeafValue, block); err != nil {\n\t\t\t\tglog.Errorf(\"Failed to decode block from log at index %d: %v\", l.LeafIndex, err)\n\t\t\t\tcontinue nextAttempt\n\t\t\t}\n\t\t\tm.unsortedBlocks <- block\n\t\t}\n\n\t\tfrom += num\n\t}\n}\n\nfunc (m *Mapper) pipelineBlocks(ctx context.Context, from int64) {\n\tticker := time.NewTicker(time.Second)\n\tblocksByNumber := make(map[int64]*types.Block)\n\n\tgo m.fetchBlocks(ctx, from)\n\nnextAttempt:\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tfor range m.unsortedBlocks {\n\t\t\t}\n\t\t\treturn\n\t\tcase b := <-m.unsortedBlocks:\n\t\t\tblocksByNumber[b.Number().Int64()] = b\n\t\tcase <-ticker.C:\n\t\t}\n\n\t\t\/\/ try to sort some blocks:\n\t\tfor {\n\t\t\tb, found := blocksByNumber[from]\n\t\t\tif !found {\n\t\t\t\tcontinue nextAttempt\n\t\t\t}\n\t\t\tm.sortedBlocks <- b\n\t\t\tfrom++\n\t\t}\n\n\t}\n}\n\nfunc isProtectedV(V *big.Int) bool {\n\tif V.BitLen() <= 8 {\n\t\tv := V.Uint64()\n\t\treturn v != 27 && v != 28\n\t}\n\t\/\/ anything not 27 or 28 are considered unprotected\n\treturn true\n}\n\n\/\/ deriveChainId derives the chain id from the given v parameter\nfunc deriveChainId(v *big.Int) *big.Int {\n\tif v.BitLen() <= 64 {\n\t\tv := v.Uint64()\n\t\tif v == 27 || v == 28 {\n\t\t\treturn new(big.Int)\n\t\t}\n\t\treturn new(big.Int).SetUint64((v - 35) \/ 2)\n\t}\n\tv = new(big.Int).Sub(v, big.NewInt(35))\n\treturn v.Div(v, big.NewInt(2))\n}\n\nfunc ethBalance(b *big.Int) string {\n\ta := &big.Float{}\n\ta.SetInt(b)\n\ta = a.Mul(a, oneEtherRatio)\n\treturn fmt.Sprintf(\"Ξ%s\", a.String())\n}\n\n\/\/ deriveSigner makes a *best* guess about which signer to use.\nfunc deriveSigner(V *big.Int) types.Signer {\n\tif V.Sign() != 0 && isProtectedV(V) {\n\t\treturn types.NewEIP155Signer(deriveChainId(V))\n\t} else {\n\t\treturn types.HomesteadSigner{}\n\t}\n}\n\nfunc fmtAddress(a []byte) string {\n\treturn fmt.Sprintf(\"%x\", a[:])\n}\n\nfunc index(a []byte) string {\n\tr := sha256.Sum256(a)\n\treturn string(r[:])\n}\n\nfunc (m *Mapper) mapTransactionsFrom(ctx context.Context, b *types.Block) error {\n\tnumTX := len(b.Transactions())\n\tif numTX == 0 {\n\t\treturn nil\n\t}\n\tglog.Infof(\"Mapping %d transactions from block @ %v\", len(b.Transactions()), b.Number())\n\tglog.V(1).Infof(\"Block: %v\", b.String())\n\n\tdeltas := make(map[string]*big.Int)\n\n\t\/\/ Add miner credit\n\tminerIndex := index(b.Coinbase().Bytes())\n\tcredit := big.NewInt(int64(5) * int64(1+len(b.Uncles())\/32))\n\tglog.Infof(\"Miner credit: %s\", credit.String())\n\tcredit.Mul(credit, big.NewInt(oneEther))\n\tdeltas[minerIndex] = credit\n\n\tfor i, tx := range b.Transactions() {\n\t\tv, _, _ := tx.RawSignatureValues()\n\t\tif v == nil {\n\t\t\treturn fmt.Errorf(\"nil signature on tx@%d@%v\", i, b.Number())\n\t\t}\n\t\tsigner := deriveSigner(v)\n\t\tfrom, err := types.Sender(signer, tx)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to derive sender on tx@%d@%v\", i, b.Number())\n\t\t}\n\n\t\t\/\/ Handle sender costs\n\t\tsIndex := index(from.Bytes())\n\t\tsBal, ok := deltas[sIndex]\n\t\tif !ok {\n\t\t\tsBal = big.NewInt(0)\n\t\t}\n\t\tsBal.Sub(sBal, tx.Cost())\n\t\tdeltas[sIndex] = sBal\n\n\t\tto := tx.To()\n\t\tif to == nil {\n\t\t\tglog.Infof(\"start-contract TX with nil To: address %d@%v\", i, b.Number())\n\t\t\tcontinue\n\t\t}\n\n\t\trIndex := index(to.Bytes())\n\t\trBal, ok := deltas[rIndex]\n\t\tif !ok {\n\t\t\trBal = big.NewInt(0)\n\t\t}\n\t\trBal.Add(rBal, tx.Value())\n\t\tdeltas[rIndex] = rBal\n\n\t\t{\n\t\t\t\/\/ only using floats for printing, map should use the fixed point representation!\n\t\t\tsender := fmtAddress(from.Bytes())\n\t\t\trecipient := fmtAddress(to.Bytes())\n\t\t\tamount := float64(tx.Value().Int64()) \/ float64(oneEther)\n\t\t\tcost := float64(tx.Cost().Int64()) \/ float64(oneEther)\n\t\t\tglog.Infof(\"Ξ%f from %s... (%x...) -> %s... (%x...), costing Ξ%f\", amount, sender[:5], sIndex[:5], recipient[:5], rIndex[:5], cost)\n\t\t}\n\t}\n\tglog.V(1).Infof(\"Have %d deltas\", len(deltas))\n\tif len(deltas) == 0 {\n\t\treturn nil\n\t}\n\n\tgetRequest := &trillian.GetMapLeavesRequest{\n\t\tMapId: m.mapID,\n\t}\n\tfor k := range deltas {\n\t\tgetRequest.Index = append(getRequest.Index, []byte(k))\n\t}\n\n\tglog.V(1).Info(\"Get map leaves...\")\n\tget, err := m.tmap.GetLeaves(ctx, getRequest)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get current balances: %v\", err)\n\t}\n\tglog.V(1).Infof(\"Got %d map leaves.\", len(get.MapLeafInclusion))\n\n\tif ld, ll := len(deltas), len(get.MapLeafInclusion); ld != ll {\n\t\tglog.Exitf(\"Got %d leaves, expected %d\", ll, ld)\n\t}\n\n\tsetRequest := &trillian.SetMapLeavesRequest{\n\t\tMapId:  m.mapID,\n\t\tLeaves: make([]*trillian.MapLeaf, 0),\n\t}\n\n\tfor _, l := range get.MapLeafInclusion {\n\t\tbal := big.NewInt(0)\n\t\tif len(l.Leaf.LeafValue) > 0 {\n\t\t\tvar ok bool\n\t\t\tbal, ok = bal.SetString(string(l.Leaf.LeafValue), 10)\n\t\t\tif !ok {\n\t\t\t\tglog.Warningf(\"Leaf value for %x... (%s) is corrupt, resetting to zero balance\", l.Leaf.Index[:5], string(l.Leaf.LeafValue))\n\t\t\t\tbal = big.NewInt(0)\n\t\t\t}\n\t\t}\n\t\tk := string(l.Leaf.Index)\n\t\td, ok := deltas[k]\n\t\tif !ok {\n\t\t\tglog.Warning(\"No delta for leaf index %x\", l.Leaf.Index)\n\t\t\tcontinue\n\t\t}\n\t\tdelete(deltas, k)\n\t\tglog.V(1).Infof(\"index %x... had: %s\", l.Leaf.Index[:5], ethBalance(bal))\n\t\tbal.Add(bal, d)\n\t\tl.Leaf.LeafValue = []byte(bal.String())\n\t\tsetRequest.Leaves = append(setRequest.Leaves, l.Leaf)\n\t\tglog.Infof(\"index %x... now has: %s\", l.Leaf.Index[:5], ethBalance(bal))\n\t}\n\n\tif len(deltas) != 0 {\n\t\tglog.Exitf(\"Arg, didn't use all deltas, still have:\\n%+v\", deltas)\n\t}\n\n\tglog.V(1).Infof(\"Setting %d map leaves.\", len(setRequest.Leaves))\n\t_, err = m.tmap.SetLeaves(ctx, setRequest)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to update balances: %v\", err)\n\t}\n\n\treturn nil\n}\n\nfunc (m *Mapper) Map(ctx context.Context) {\n\tfrom := int64(0)\n\tgo m.pipelineBlocks(ctx, from)\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase nextBlock := <-m.sortedBlocks:\n\t\t\tif nextBlock.Number().Int64() != from {\n\t\t\t\tglog.Exitf(\"Got unexpected block number %s, wanted %d\", nextBlock.Number(), from)\n\t\t\t}\n\t\t\t\/\/ TODO(al): batching...\n\t\t\tif err := m.mapTransactionsFrom(ctx, nextBlock); err != nil {\n\t\t\t\tglog.Exitf(\"Couldn't map transactions from block %v\", err)\n\t\t\t}\n\t\t\tfrom++\n\t\t}\n\t}\n}\n<commit_msg>Backoff if trying to fetch blocks from the log fails.<commit_after>\/\/ Copyright 2018 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/    https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage mapper\n\nimport (\n\t\"context\"\n\t\"crypto\/sha256\"\n\t\"fmt\"\n\t\"math\/big\"\n\t\"time\"\n\n\t\"github.com\/ethereum\/go-ethereum\/core\/types\"\n\t\"github.com\/ethereum\/go-ethereum\/rlp\"\n\t\"github.com\/golang\/glog\"\n\t\"github.com\/google\/trillian\"\n)\n\nconst (\n\toneEther int64 = 1000000000000000000\n)\n\nvar oneEtherRatio = big.NewFloat(float64(1) \/ float64(oneEther))\n\ntype Mapper struct {\n\tlogID, mapID int64\n\ttlog         trillian.TrillianLogClient\n\ttmap         trillian.TrillianMapClient\n\n\tunsortedBlocks chan *types.Block\n\tsortedBlocks   chan *types.Block\n}\n\nfunc New(tl trillian.TrillianLogClient, logID int64, tm trillian.TrillianMapClient, mapID int64) *Mapper {\n\treturn &Mapper{\n\t\tlogID: logID,\n\t\tmapID: mapID,\n\t\ttlog:  tl,\n\t\ttmap:  tm,\n\n\t\tunsortedBlocks: make(chan *types.Block, 100000),\n\t\tsortedBlocks:   make(chan *types.Block, 100000),\n\t}\n}\n\nconst maxNumBlocks int64 = 100\n\nvar numBlocks = maxNumBlocks\n\nfunc (m *Mapper) fetchBlocks(ctx context.Context, from int64) {\n\tticker := time.NewTicker(time.Second)\n\nnextAttempt:\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase <-ticker.C:\n\t\t}\n\n\t\tleaves := make([]int64, numBlocks)\n\t\tfor i := int64(0); i < numBlocks; i++ {\n\t\t\tleaves[i] = from + i\n\t\t}\n\n\t\tentries, err := m.tlog.GetLeavesByIndex(ctx, &trillian.GetLeavesByIndexRequest{LogId: m.logID, LeafIndex: leaves})\n\t\tif err != nil {\n\t\t\tglog.Errorf(\"Failed to get %d leaves starting at index %d: %v\", numBlocks, from, err)\n\t\t\tnumBlocks \/= 2\n\t\t\tcontinue nextAttempt\n\t\t}\n\t\tif numBlocks < maxNumBlocks {\n\t\t\tnumBlocks += (maxNumBlocks - numBlocks) \/ 2\n\t\t}\n\n\t\tfor _, l := range entries.Leaves {\n\t\t\tblock := &types.Block{}\n\t\t\tif err := rlp.DecodeBytes(l.LeafValue, block); err != nil {\n\t\t\t\tglog.Errorf(\"Failed to decode block from log at index %d: %v\", l.LeafIndex, err)\n\t\t\t\tcontinue nextAttempt\n\t\t\t}\n\t\t\tm.unsortedBlocks <- block\n\t\t}\n\n\t\tfrom += numBlocks\n\t}\n}\n\nfunc (m *Mapper) pipelineBlocks(ctx context.Context, from int64) {\n\tticker := time.NewTicker(time.Second)\n\tblocksByNumber := make(map[int64]*types.Block)\n\n\tgo m.fetchBlocks(ctx, from)\n\nnextAttempt:\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tfor range m.unsortedBlocks {\n\t\t\t}\n\t\t\treturn\n\t\tcase b := <-m.unsortedBlocks:\n\t\t\tblocksByNumber[b.Number().Int64()] = b\n\t\tcase <-ticker.C:\n\t\t}\n\n\t\t\/\/ try to sort some blocks:\n\t\tfor {\n\t\t\tb, found := blocksByNumber[from]\n\t\t\tif !found {\n\t\t\t\tcontinue nextAttempt\n\t\t\t}\n\t\t\tm.sortedBlocks <- b\n\t\t\tfrom++\n\t\t}\n\n\t}\n}\n\nfunc isProtectedV(V *big.Int) bool {\n\tif V.BitLen() <= 8 {\n\t\tv := V.Uint64()\n\t\treturn v != 27 && v != 28\n\t}\n\t\/\/ anything not 27 or 28 are considered unprotected\n\treturn true\n}\n\n\/\/ deriveChainId derives the chain id from the given v parameter\nfunc deriveChainId(v *big.Int) *big.Int {\n\tif v.BitLen() <= 64 {\n\t\tv := v.Uint64()\n\t\tif v == 27 || v == 28 {\n\t\t\treturn new(big.Int)\n\t\t}\n\t\treturn new(big.Int).SetUint64((v - 35) \/ 2)\n\t}\n\tv = new(big.Int).Sub(v, big.NewInt(35))\n\treturn v.Div(v, big.NewInt(2))\n}\n\nfunc ethBalance(b *big.Int) string {\n\ta := &big.Float{}\n\ta.SetInt(b)\n\ta = a.Mul(a, oneEtherRatio)\n\treturn fmt.Sprintf(\"Ξ%s\", a.String())\n}\n\n\/\/ deriveSigner makes a *best* guess about which signer to use.\nfunc deriveSigner(V *big.Int) types.Signer {\n\tif V.Sign() != 0 && isProtectedV(V) {\n\t\treturn types.NewEIP155Signer(deriveChainId(V))\n\t} else {\n\t\treturn types.HomesteadSigner{}\n\t}\n}\n\nfunc fmtAddress(a []byte) string {\n\treturn fmt.Sprintf(\"%x\", a[:])\n}\n\nfunc index(a []byte) string {\n\tr := sha256.Sum256(a)\n\treturn string(r[:])\n}\n\nfunc (m *Mapper) mapTransactionsFrom(ctx context.Context, b *types.Block) error {\n\tnumTX := len(b.Transactions())\n\tif numTX == 0 {\n\t\treturn nil\n\t}\n\tglog.Infof(\"Mapping %d transactions from block @ %v\", len(b.Transactions()), b.Number())\n\tglog.V(1).Infof(\"Block: %v\", b.String())\n\n\tdeltas := make(map[string]*big.Int)\n\n\t\/\/ Add miner credit\n\tminerIndex := index(b.Coinbase().Bytes())\n\tcredit := big.NewInt(int64(5) * int64(1+len(b.Uncles())\/32))\n\tglog.Infof(\"Miner credit: %s\", credit.String())\n\tcredit.Mul(credit, big.NewInt(oneEther))\n\tdeltas[minerIndex] = credit\n\n\tfor i, tx := range b.Transactions() {\n\t\tv, _, _ := tx.RawSignatureValues()\n\t\tif v == nil {\n\t\t\treturn fmt.Errorf(\"nil signature on tx@%d@%v\", i, b.Number())\n\t\t}\n\t\tsigner := deriveSigner(v)\n\t\tfrom, err := types.Sender(signer, tx)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to derive sender on tx@%d@%v\", i, b.Number())\n\t\t}\n\n\t\t\/\/ Handle sender costs\n\t\tsIndex := index(from.Bytes())\n\t\tsBal, ok := deltas[sIndex]\n\t\tif !ok {\n\t\t\tsBal = big.NewInt(0)\n\t\t}\n\t\tsBal.Sub(sBal, tx.Cost())\n\t\tdeltas[sIndex] = sBal\n\n\t\tto := tx.To()\n\t\tif to == nil {\n\t\t\tglog.Infof(\"start-contract TX with nil To: address %d@%v\", i, b.Number())\n\t\t\tcontinue\n\t\t}\n\n\t\trIndex := index(to.Bytes())\n\t\trBal, ok := deltas[rIndex]\n\t\tif !ok {\n\t\t\trBal = big.NewInt(0)\n\t\t}\n\t\trBal.Add(rBal, tx.Value())\n\t\tdeltas[rIndex] = rBal\n\n\t\t{\n\t\t\t\/\/ only using floats for printing, map should use the fixed point representation!\n\t\t\tsender := fmtAddress(from.Bytes())\n\t\t\trecipient := fmtAddress(to.Bytes())\n\t\t\tamount := float64(tx.Value().Int64()) \/ float64(oneEther)\n\t\t\tcost := float64(tx.Cost().Int64()) \/ float64(oneEther)\n\t\t\tglog.Infof(\"Ξ%f from %s... (%x...) -> %s... (%x...), costing Ξ%f\", amount, sender[:5], sIndex[:5], recipient[:5], rIndex[:5], cost)\n\t\t}\n\t}\n\tglog.V(1).Infof(\"Have %d deltas\", len(deltas))\n\tif len(deltas) == 0 {\n\t\treturn nil\n\t}\n\n\tgetRequest := &trillian.GetMapLeavesRequest{\n\t\tMapId: m.mapID,\n\t}\n\tfor k := range deltas {\n\t\tgetRequest.Index = append(getRequest.Index, []byte(k))\n\t}\n\n\tglog.V(1).Info(\"Get map leaves...\")\n\tget, err := m.tmap.GetLeaves(ctx, getRequest)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get current balances: %v\", err)\n\t}\n\tglog.V(1).Infof(\"Got %d map leaves.\", len(get.MapLeafInclusion))\n\n\tif ld, ll := len(deltas), len(get.MapLeafInclusion); ld != ll {\n\t\tglog.Exitf(\"Got %d leaves, expected %d\", ll, ld)\n\t}\n\n\tsetRequest := &trillian.SetMapLeavesRequest{\n\t\tMapId:  m.mapID,\n\t\tLeaves: make([]*trillian.MapLeaf, 0),\n\t}\n\n\tfor _, l := range get.MapLeafInclusion {\n\t\tbal := big.NewInt(0)\n\t\tif len(l.Leaf.LeafValue) > 0 {\n\t\t\tvar ok bool\n\t\t\tbal, ok = bal.SetString(string(l.Leaf.LeafValue), 10)\n\t\t\tif !ok {\n\t\t\t\tglog.Warningf(\"Leaf value for %x... (%s) is corrupt, resetting to zero balance\", l.Leaf.Index[:5], string(l.Leaf.LeafValue))\n\t\t\t\tbal = big.NewInt(0)\n\t\t\t}\n\t\t}\n\t\tk := string(l.Leaf.Index)\n\t\td, ok := deltas[k]\n\t\tif !ok {\n\t\t\tglog.Warning(\"No delta for leaf index %x\", l.Leaf.Index)\n\t\t\tcontinue\n\t\t}\n\t\tdelete(deltas, k)\n\t\tglog.V(1).Infof(\"index %x... had: %s\", l.Leaf.Index[:5], ethBalance(bal))\n\t\tbal.Add(bal, d)\n\t\tl.Leaf.LeafValue = []byte(bal.String())\n\t\tsetRequest.Leaves = append(setRequest.Leaves, l.Leaf)\n\t\tglog.Infof(\"index %x... now has: %s\", l.Leaf.Index[:5], ethBalance(bal))\n\t}\n\n\tif len(deltas) != 0 {\n\t\tglog.Exitf(\"Arg, didn't use all deltas, still have:\\n%+v\", deltas)\n\t}\n\n\tglog.V(1).Infof(\"Setting %d map leaves.\", len(setRequest.Leaves))\n\t_, err = m.tmap.SetLeaves(ctx, setRequest)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to update balances: %v\", err)\n\t}\n\n\treturn nil\n}\n\nfunc (m *Mapper) Map(ctx context.Context) {\n\tfrom := int64(0)\n\tgo m.pipelineBlocks(ctx, from)\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase nextBlock := <-m.sortedBlocks:\n\t\t\tif nextBlock.Number().Int64() != from {\n\t\t\t\tglog.Exitf(\"Got unexpected block number %s, wanted %d\", nextBlock.Number(), from)\n\t\t\t}\n\t\t\t\/\/ TODO(al): batching...\n\t\t\tif err := m.mapTransactionsFrom(ctx, nextBlock); err != nil {\n\t\t\t\tglog.Exitf(\"Couldn't map transactions from block %v\", err)\n\t\t\t}\n\t\t\tfrom++\n\t\t}\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2018 The Ebiten Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ +build example jsgo\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"image\/color\"\n\t\"log\"\n\n\t\"github.com\/hajimehoshi\/ebiten\"\n\t\"github.com\/hajimehoshi\/ebiten\/ebitenutil\"\n)\n\nvar pointerImage *ebiten.Image\n\nfunc init() {\n\tpointerImage, _ = ebiten.NewImage(4, 4, ebiten.FilterDefault)\n\tpointerImage.Fill(color.RGBA{0xff, 0, 0, 0xff})\n}\n\nconst (\n\tscreenWidth  = 320\n\tscreenHeight = 240\n)\n\nvar (\n\tx = 0.0\n\ty = 0.0\n)\n\nfunc update(screen *ebiten.Image) error {\n\tdx, dy := ebiten.Wheel()\n\tx += dx\n\ty += dy\n\n\tif ebiten.IsDrawingSkipped() {\n\t\treturn nil\n\t}\n\n\top := &ebiten.DrawImageOptions{}\n\top.GeoM.Translate(x, y)\n\top.GeoM.Translate(screenWidth\/2, screenHeight\/2)\n\tscreen.DrawImage(pointerImage, op)\n\n\tebitenutil.DebugPrint(screen,\n\t\tfmt.Sprintf(\"Move the red point by mouse wheel\\n(%0.2f, %0.2f)\", x, y))\n\n\treturn nil\n}\n\nfunc main() {\n\tif err := ebiten.Run(update, screenWidth, screenHeight, 2, \"Wheel (Ebiten Demo)\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n<commit_msg>examples\/wheel: Use RunGame (#1182)<commit_after>\/\/ Copyright 2018 The Ebiten Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ +build example jsgo\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"image\/color\"\n\t\"log\"\n\n\t\"github.com\/hajimehoshi\/ebiten\"\n\t\"github.com\/hajimehoshi\/ebiten\/ebitenutil\"\n)\n\nvar pointerImage *ebiten.Image\n\nfunc init() {\n\tpointerImage, _ = ebiten.NewImage(4, 4, ebiten.FilterDefault)\n\tpointerImage.Fill(color.RGBA{0xff, 0, 0, 0xff})\n}\n\nconst (\n\tscreenWidth  = 320\n\tscreenHeight = 240\n)\n\ntype Game struct {\n\tx float64\n\ty float64\n}\n\nfunc (g *Game) Update(screen *ebiten.Image) error {\n\tdx, dy := ebiten.Wheel()\n\tg.x += dx\n\tg.y += dy\n\treturn nil\n}\n\nfunc (g *Game) Draw(screen *ebiten.Image) {\n\top := &ebiten.DrawImageOptions{}\n\top.GeoM.Translate(g.x, g.y)\n\top.GeoM.Translate(screenWidth\/2, screenHeight\/2)\n\tscreen.DrawImage(pointerImage, op)\n\n\tebitenutil.DebugPrint(screen,\n\t\tfmt.Sprintf(\"Move the red point by mouse wheel\\n(%0.2f, %0.2f)\", g.x, g.y))\n}\n\nfunc (g *Game) Layout(outsideWidth, outsideHeight int) (int, int) {\n\treturn screenWidth, screenHeight\n}\n\nfunc main() {\n\tg := &Game{x: 0.0, y: 0.0}\n\n\tebiten.SetWindowSize(screenWidth*2, screenHeight*2)\n\tebiten.SetWindowTitle(\"Wheel (Ebiten Demo)\")\n\tif err := ebiten.RunGame(g); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package virtualmachinedisk\n\nimport (\n\t\"encoding\/xml\"\n\n\t\"github.com\/Azure\/azure-sdk-for-go\/management\"\n)\n\n\/\/ DiskClient is used to perform operations on Azure Disks\ntype DiskClient struct {\n\tclient management.Client\n}\n\n\/\/ CreateDiskParameters represents a disk\n\/\/\n\/\/ https:\/\/msdn.microsoft.com\/en-us\/library\/azure\/jj157188.aspx\ntype CreateDiskParameters struct {\n\tXMLName   xml.Name            `xml:\"http:\/\/schemas.microsoft.com\/windowsazure Disk\"`\n\tOS        OperatingSystemType `xml:\",omitempty\"`\n\tLabel     string\n\tMediaLink string `xml:\",omitempty\"`\n\tName      string\n}\n\n\/\/ UpdateDiskParameters represents a disk\n\/\/\n\/\/ https:\/\/msdn.microsoft.com\/en-us\/library\/azure\/jj157188.aspx\ntype UpdateDiskParameters struct {\n\tXMLName         xml.Name `xml:\"http:\/\/schemas.microsoft.com\/windowsazure Disk\"`\n\tName            string\n\tLabel           string `xml:\",omitempty\"`\n\tResizedSizeInGB int    `xml:\",omitempty\"`\n}\n\n\/\/ ListDiskResponse represents a disk\n\/\/\n\/\/ https:\/\/msdn.microsoft.com\/en-us\/library\/azure\/jj157188.aspx\ntype ListDiskResponse struct {\n\tXMLName xml.Name `xml:\"http:\/\/schemas.microsoft.com\/windowsazure Disks\"`\n\tDisk    []DiskResponse\n}\n\n\/\/ DiskResponse represents a disk\n\/\/\n\/\/ https:\/\/msdn.microsoft.com\/en-us\/library\/azure\/jj157188.aspx\ntype DiskResponse struct {\n\tXMLName             xml.Name `xml:\"http:\/\/schemas.microsoft.com\/windowsazure Disk\"`\n\tAffinityGroup       string\n\tAttachedTo          Resource\n\tIsCorrupted         bool\n\tOS                  OperatingSystemType\n\tLocation            string\n\tLogicalDiskSizeInGB int\n\tMediaLink           string\n\tName                string\n\tSourceImageName     string\n\tCreatedTime         string\n\tIOType              IOType\n}\n\n\/\/ Resource describes the resource details a disk is currently attached to\ntype Resource struct {\n\tXMLName           xml.Name `xml:\"http:\/\/schemas.microsoft.com\/windowsazure AttachedTo\"`\n\tDeploymentName    string\n\tHostedServiceName string\n\tRoleName          string\n}\n\n\/\/ IOType represents an IO type\ntype IOType string\n\n\/\/ These constants represent the possible IO types\nconst (\n\tIOTypeProvisioned IOType = \"Provisioned\"\n\tIOTypeStandard    IOType = \"Standard\"\n)\n\n\/\/ OperatingSystemType represents an operating system type\ntype OperatingSystemType string\n\n\/\/ These constants represent the valid operating system types\nconst (\n\tOperatingSystemTypeNull    OperatingSystemType = \"NULL\"\n\tOperatingSystemTypeLinux   OperatingSystemType = \"Linux\"\n\tOperatingSystemTypeWindows OperatingSystemType = \"Windows\"\n)\n\n\/\/ CreateDataDiskParameters represents a data disk\n\/\/\n\/\/ https:\/\/msdn.microsoft.com\/en-us\/library\/azure\/jj157188.aspx\ntype CreateDataDiskParameters struct {\n\tXMLName             xml.Name        `xml:\"http:\/\/schemas.microsoft.com\/windowsazure DataVirtualHardDisk\"`\n\tHostCaching         HostCachingType `xml:\",omitempty\"`\n\tDiskLabel           string          `xml:\",omitempty\"`\n\tDiskName            string          `xml:\",omitempty\"`\n\tLun                 int             `xml:\",omitempty\"`\n\tLogicalDiskSizeInGB int             `xml:\",omitempty\"`\n\tMediaLink           string\n\tSourceMediaLink     string `xml:\",omitempty\"`\n}\n\n\/\/ UpdateDataDiskParameters represents a data disk\n\/\/\n\/\/ https:\/\/msdn.microsoft.com\/en-us\/library\/azure\/jj157188.aspx\ntype UpdateDataDiskParameters struct {\n\tXMLName     xml.Name        `xml:\"http:\/\/schemas.microsoft.com\/windowsazure DataVirtualHardDisk\"`\n\tHostCaching HostCachingType `xml:\",omitempty\"`\n\tDiskName    string\n\tLun         int\n\tMediaLink   string\n}\n\n\/\/ DataDiskResponse represents a data disk\n\/\/\n\/\/ https:\/\/msdn.microsoft.com\/en-us\/library\/azure\/jj157188.aspx\ntype DataDiskResponse struct {\n\tXMLName             xml.Name `xml:\"http:\/\/schemas.microsoft.com\/windowsazure DataVirtualHardDisk\"`\n\tHostCaching         HostCachingType\n\tDiskLabel           string\n\tDiskName            string\n\tLun                 int\n\tLogicalDiskSizeInGB int\n\tMediaLink           string\n}\n\n\/\/ HostCachingType represents a host caching type\ntype HostCachingType string\n\n\/\/ These constants represent the valid host caching types\nconst (\n\tHostCachingTypeNone      HostCachingType = \"None\"\n\tHostCachingTypeReadOnly  HostCachingType = \"ReadOnly\"\n\tHostCachingTypeReadWrite HostCachingType = \"ReadWrite\"\n)\n<commit_msg>Updating bad struct field name<commit_after>package virtualmachinedisk\n\nimport (\n\t\"encoding\/xml\"\n\n\t\"github.com\/Azure\/azure-sdk-for-go\/management\"\n)\n\n\/\/ DiskClient is used to perform operations on Azure Disks\ntype DiskClient struct {\n\tclient management.Client\n}\n\n\/\/ CreateDiskParameters represents a disk\n\/\/\n\/\/ https:\/\/msdn.microsoft.com\/en-us\/library\/azure\/jj157188.aspx\ntype CreateDiskParameters struct {\n\tXMLName   xml.Name            `xml:\"http:\/\/schemas.microsoft.com\/windowsazure Disk\"`\n\tOS        OperatingSystemType `xml:\",omitempty\"`\n\tLabel     string\n\tMediaLink string `xml:\",omitempty\"`\n\tName      string\n}\n\n\/\/ UpdateDiskParameters represents a disk\n\/\/\n\/\/ https:\/\/msdn.microsoft.com\/en-us\/library\/azure\/jj157188.aspx\ntype UpdateDiskParameters struct {\n\tXMLName         xml.Name `xml:\"http:\/\/schemas.microsoft.com\/windowsazure Disk\"`\n\tDiskName        string\n\tLabel           string `xml:\",omitempty\"`\n\tResizedSizeInGB int    `xml:\",omitempty\"`\n}\n\n\/\/ ListDiskResponse represents a disk\n\/\/\n\/\/ https:\/\/msdn.microsoft.com\/en-us\/library\/azure\/jj157188.aspx\ntype ListDiskResponse struct {\n\tXMLName xml.Name `xml:\"http:\/\/schemas.microsoft.com\/windowsazure Disks\"`\n\tDisk    []DiskResponse\n}\n\n\/\/ DiskResponse represents a disk\n\/\/\n\/\/ https:\/\/msdn.microsoft.com\/en-us\/library\/azure\/jj157188.aspx\ntype DiskResponse struct {\n\tXMLName             xml.Name `xml:\"http:\/\/schemas.microsoft.com\/windowsazure Disk\"`\n\tAffinityGroup       string\n\tAttachedTo          Resource\n\tIsCorrupted         bool\n\tOS                  OperatingSystemType\n\tLocation            string\n\tLogicalDiskSizeInGB int\n\tMediaLink           string\n\tName                string\n\tSourceImageName     string\n\tCreatedTime         string\n\tIOType              IOType\n}\n\n\/\/ Resource describes the resource details a disk is currently attached to\ntype Resource struct {\n\tXMLName           xml.Name `xml:\"http:\/\/schemas.microsoft.com\/windowsazure AttachedTo\"`\n\tDeploymentName    string\n\tHostedServiceName string\n\tRoleName          string\n}\n\n\/\/ IOType represents an IO type\ntype IOType string\n\n\/\/ These constants represent the possible IO types\nconst (\n\tIOTypeProvisioned IOType = \"Provisioned\"\n\tIOTypeStandard    IOType = \"Standard\"\n)\n\n\/\/ OperatingSystemType represents an operating system type\ntype OperatingSystemType string\n\n\/\/ These constants represent the valid operating system types\nconst (\n\tOperatingSystemTypeNull    OperatingSystemType = \"NULL\"\n\tOperatingSystemTypeLinux   OperatingSystemType = \"Linux\"\n\tOperatingSystemTypeWindows OperatingSystemType = \"Windows\"\n)\n\n\/\/ CreateDataDiskParameters represents a data disk\n\/\/\n\/\/ https:\/\/msdn.microsoft.com\/en-us\/library\/azure\/jj157188.aspx\ntype CreateDataDiskParameters struct {\n\tXMLName             xml.Name        `xml:\"http:\/\/schemas.microsoft.com\/windowsazure DataVirtualHardDisk\"`\n\tHostCaching         HostCachingType `xml:\",omitempty\"`\n\tDiskLabel           string          `xml:\",omitempty\"`\n\tDiskName            string          `xml:\",omitempty\"`\n\tLun                 int             `xml:\",omitempty\"`\n\tLogicalDiskSizeInGB int             `xml:\",omitempty\"`\n\tMediaLink           string\n\tSourceMediaLink     string `xml:\",omitempty\"`\n}\n\n\/\/ UpdateDataDiskParameters represents a data disk\n\/\/\n\/\/ https:\/\/msdn.microsoft.com\/en-us\/library\/azure\/jj157188.aspx\ntype UpdateDataDiskParameters struct {\n\tXMLName     xml.Name        `xml:\"http:\/\/schemas.microsoft.com\/windowsazure DataVirtualHardDisk\"`\n\tHostCaching HostCachingType `xml:\",omitempty\"`\n\tDiskName    string\n\tLun         int\n\tMediaLink   string\n}\n\n\/\/ DataDiskResponse represents a data disk\n\/\/\n\/\/ https:\/\/msdn.microsoft.com\/en-us\/library\/azure\/jj157188.aspx\ntype DataDiskResponse struct {\n\tXMLName             xml.Name `xml:\"http:\/\/schemas.microsoft.com\/windowsazure DataVirtualHardDisk\"`\n\tHostCaching         HostCachingType\n\tDiskLabel           string\n\tDiskName            string\n\tLun                 int\n\tLogicalDiskSizeInGB int\n\tMediaLink           string\n}\n\n\/\/ HostCachingType represents a host caching type\ntype HostCachingType string\n\n\/\/ These constants represent the valid host caching types\nconst (\n\tHostCachingTypeNone      HostCachingType = \"None\"\n\tHostCachingTypeReadOnly  HostCachingType = \"ReadOnly\"\n\tHostCachingTypeReadWrite HostCachingType = \"ReadWrite\"\n)\n<|endoftext|>"}
{"text":"<commit_before>package asciidocgo\n\nimport (\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\t. \"github.com\/smartystreets\/goconvey\/convey\"\n)\n\nfunc TestAbstractNode(t *testing.T) {\n\n\tConvey(\"An abstractNode can be initialized\", t, func() {\n\n\t\tConvey(\"By default, an AbstractNode can be created\", func() {\n\t\t\tSo(&abstractNode{}, ShouldNotBeNil)\n\t\t})\n\t\tConvey(\"An AbstractNode takes a parent and a context\", func() {\n\t\t\tSo(newAbstractNode(nil, document), ShouldNotBeNil)\n\t\t})\n\t\tConvey(\"If context is a document, then parent is nil and document is parent\", func() {\n\t\t\tparent := &abstractNode{}\n\t\t\tan := newAbstractNode(parent, document)\n\t\t\tSo(an.Context(), ShouldEqual, document)\n\t\t\tSo(an.Parent(), ShouldBeNil)\n\t\t\tSo(an.Document(), ShouldEqual, parent)\n\t\t})\n\t\tConvey(\"If context is not document, then parent is parent and document is parent document\", func() {\n\t\t\tparent := &abstractNode{nil, document, &abstractNode{}, nil, &substitutors{}}\n\t\t\tan := newAbstractNode(parent, section)\n\t\t\tSo(an.Context(), ShouldEqual, section)\n\t\t\tSo(an.Parent(), ShouldEqual, parent)\n\t\t\tSo(an.Document(), ShouldEqual, parent.Document())\n\t\t})\n\t\tConvey(\"If context is not document, and parent is nil, then document is nil\", func() {\n\t\t\tan := newAbstractNode(nil, section)\n\t\t\tSo(an.Context(), ShouldEqual, section)\n\t\t\tSo(an.Parent(), ShouldBeNil)\n\t\t\tSo(an.Document(), ShouldBeNil)\n\t\t})\n\n\t\tConvey(\"An abstractNode has an empty attributes map\", func() {\n\t\t\tan := newAbstractNode(nil, section)\n\t\t\tSo(len(an.Attributes()), ShouldEqual, 0)\n\t\t})\n\t})\n\n\tConvey(\"An abstractNode can be associated to a parent\", t, func() {\n\t\tan := newAbstractNode(nil, section)\n\t\tdocumentParent := &abstractNode{}\n\t\tparent := &abstractNode{nil, document, documentParent, nil, &substitutors{}}\n\t\tan.SetParent(parent)\n\t\tSo(an.Parent(), ShouldEqual, parent)\n\t\tSo(an.Document(), ShouldEqual, parent.Document())\n\t})\n\n\tConvey(\"An abstractNode can retrieve an attribute\", t, func() {\n\n\t\tparentDocument := newAbstractNode(nil, document)\n\t\tparentDocument.setAttr(\"key\", \"val1\", true)\n\t\tparent := newAbstractNode(parentDocument, document)\n\t\tan := newAbstractNode(nil, document)\n\t\tConvey(\"If inherited, it is the attribute if there, or the document attribute, or default value\", func() {\n\t\t\tSo(an.Attr(\"key\", nil, true), ShouldBeNil)\n\t\t\tan.setAttr(\"key\", \"val\", false)\n\t\t\tSo(an.Attr(\"key\", nil, true), ShouldEqual, \"val\")\n\t\t\tan.SetParent(parent)\n\t\t\tSo(an.Attr(\"key\", nil, true), ShouldEqual, \"val\")\n\t\t\tdelete(an.attributes, \"key\")\n\t\t\tSo(an.Attr(\"key\", nil, true), ShouldEqual, \"val1\")\n\t\t\t\/\/ an should have for parent a child, which has an as a document\n\t\t\t\/\/ then an.document would be \"parent\".document, meaning an, when\n\t\t\t\/\/ setting an.setParent(child)\n\t\t\tan.document = an\n\t\t\tan.setAttr(\"key\", \"val\", false)\n\t\t\tSo(an.Attr(\"key\", nil, true), ShouldEqual, \"val\")\n\t\t})\n\t\tConvey(\"If not inherited, it is the attribute if there, or default value\", func() {\n\t\t\tan.SetParent(parent)\n\t\t\tSo(an.Document(), ShouldEqual, parentDocument)\n\t\t\tSo(an.Document(), ShouldEqual, parent.Document())\n\t\t\tSo(parentDocument.Attr(\"key\", nil, false), ShouldEqual, \"val1\")\n\t\t\tSo(an.Attr(\"key\", nil, false), ShouldEqual, \"val\")\n\t\t})\n\t})\n\tConvey(\"An abstractNode can set an attribute\", t, func() {\n\t\tan := newAbstractNode(nil, document)\n\t\tan.setAttr(\"key\", \"val\", true)\n\t\tSo(an.Attr(\"key\", nil, true), ShouldEqual, \"val\")\n\t\tConvey(\"If not override and already present, the value should not change\", func() {\n\t\t\tres := an.setAttr(\"key\", \"val1\", false)\n\t\t\tSo(an.Attr(\"key\", nil, true), ShouldEqual, \"val\")\n\t\t\tSo(res, ShouldBeFalse)\n\t\t})\n\t})\n\n\tConvey(\"An abstractNode can set an option attribute\", t, func() {\n\t\tan := newAbstractNode(nil, document)\n\t\tConvey(\"First option means options attributes has len 1\", func() {\n\t\t\tan.SetOption(\"opt1\")\n\t\t\tSo(len(an.attributes[\"options\"].(map[string]bool)), ShouldEqual, 1)\n\t\t\tSo(an.Attr(\"opt1-option\", nil, false), ShouldEqual, true)\n\t\t})\n\t\tConvey(\"Second option means options attributes has len 2\", func() {\n\t\t\tan.SetOption(\"opt2\")\n\t\t\tSo(len(an.attributes[\"options\"].(map[string]bool)), ShouldEqual, 2)\n\t\t\tSo(an.Attr(\"opt2-option\", nil, false), ShouldEqual, true)\n\t\t})\n\t})\n\n\tConvey(\"An abstractNode can get an option attribute\", t, func() {\n\t\tan := newAbstractNode(nil, document)\n\t\tConvey(\"Zero option means Option returns false\", func() {\n\t\t\tSo(an.Option(\"opt1\"), ShouldBeFalse)\n\t\t\tan.SetOption(\"opt1\")\n\t\t})\n\t\tConvey(\"One option means Option returns true\", func() {\n\t\t\tSo(an.Option(\"opt1\"), ShouldBeTrue)\n\t\t})\n\t})\n\n\tConvey(\"An abstractNode update option attributes with other attributes\", t, func() {\n\t\tan := newAbstractNode(nil, document)\n\t\tan.setAttr(\"key1\", \"val1\", true)\n\t\tan.setAttr(\"key2\", \"val2\", true)\n\t\tConvey(\"New Attributes are added during an update\", func() {\n\t\t\tattrs := map[string]interface{}{\"key3\": \"val3\", \"key4\": \"val4\"}\n\t\t\tan.Update(attrs)\n\t\t\tSo(an.Attr(\"key1\", nil, false), ShouldEqual, \"val1\")\n\t\t\tSo(an.Attr(\"key2\", nil, false), ShouldEqual, \"val2\")\n\t\t\tSo(an.Attr(\"key3\", nil, false), ShouldEqual, \"val3\")\n\t\t\tSo(an.Attr(\"key4\", nil, false), ShouldEqual, \"val4\")\n\t\t})\n\t\tConvey(\"Common Attributes are overrriden during an update\", func() {\n\t\t\tattrs := map[string]interface{}{\"key2\": \"val2b\", \"key3\": \"val3\"}\n\t\t\tan.Update(attrs)\n\t\t\tSo(an.Attr(\"key1\", nil, false), ShouldEqual, \"val1\")\n\t\t\tSo(an.Attr(\"key2\", nil, false), ShouldEqual, \"val2b\")\n\t\t\tSo(an.Attr(\"key3\", nil, false), ShouldEqual, \"val3\")\n\t\t})\n\t})\n\tConvey(\"An abstractNode attributes can check for a role\", t, func() {\n\t\tan := newAbstractNode(nil, document)\n\t\tparentDocument := newAbstractNode(nil, document)\n\t\tparentDocument.setAttr(\"role\", \"roleFromParentDocument\", true)\n\t\tparent := newAbstractNode(parentDocument, document)\n\t\tConvey(\"A role can be checked, whatever its value is\", func() {\n\t\t\tSo(an.HasRole(nil), ShouldBeFalse)\n\t\t\tSo(parentDocument.HasRole(nil), ShouldBeTrue)\n\t\t\tan.SetParent(parent)\n\t\t\tSo(an.HasRole(nil), ShouldBeTrue)\n\t\t})\n\t\tConvey(\"A role can be checked against an expected value\", func() {\n\t\t\tan := newAbstractNode(nil, document)\n\t\t\tan.SetParent(parent)\n\t\t\tSo(an.HasRole(\"roleFromAN\"), ShouldBeFalse)\n\t\t\tSo(an.HasRole(\"roleFromParentDocument\"), ShouldBeTrue)\n\t\t\tan.setAttr(\"role\", \"roleFromAN\", true)\n\t\t\tSo(an.HasRole(\"roleFromAN\"), ShouldBeTrue)\n\t\t\tSo(an.HasRole(\"roleFromParentDocument\"), ShouldBeFalse)\n\t\t})\n\t})\n\tConvey(\"An abstractNode attributes can check for a role name\", t, func() {\n\t\tan := newAbstractNode(nil, document)\n\t\tparentDocument := newAbstractNode(nil, document)\n\t\tparentDocument.setAttr(\"role\", \"role1FromParentDocument role2FromParentDocument role3FromParentDocument\", true)\n\t\tparent := newAbstractNode(parentDocument, document)\n\n\t\tConvey(\"A role name can be checked on the document\", func() {\n\t\t\tSo(an.HasARole(\"role3FromAN\"), ShouldBeFalse)\n\t\t\tSo(an.HasARole(\"role2FromParentDocument\"), ShouldBeFalse)\n\t\t\tan.SetParent(parent)\n\t\t\tSo(an.Document(), ShouldEqual, parentDocument)\n\t\t\t\/\/So(an.Document().Attr(\"role\", nil, true), ShouldEqual, \"test\")\n\t\t\tSo(an.HasARole(\"role2FromParentDocument\"), ShouldBeTrue)\n\t\t\tSo(an.HasARole(\"role4FromParentDocument\"), ShouldBeFalse)\n\t\t})\n\t\tConvey(\"A role name can be checked on the abstractNode itself\", func() {\n\t\t\tan.setAttr(\"role\", \"role1FromAN role2FromAN role3FromAN\", true)\n\t\t\tSo(an.HasARole(\"role3FromAN\"), ShouldBeTrue)\n\t\t})\n\t\tConvey(\"An empty role name is always false=\", func() {\n\t\t\tSo(an.HasARole(\"\"), ShouldBeFalse)\n\t\t})\n\t})\n\tConvey(\"An abstractNode attributes can access role\", t, func() {\n\t\tan := newAbstractNode(nil, document)\n\t\tparentDocument := newAbstractNode(nil, document)\n\t\tparentDocument.setAttr(\"role\", \"roleFromParentDocument\", true)\n\t\tparent := newAbstractNode(parentDocument, document)\n\t\tConvey(\"A role can be access from an document, when an has no role\", func() {\n\t\t\tSo(an.Role(), ShouldBeNil)\n\t\t\tSo(parentDocument.Role(), ShouldEqual, \"roleFromParentDocument\")\n\t\t\tan.SetParent(parent)\n\t\t\tSo(an.Role(), ShouldEqual, \"roleFromParentDocument\")\n\t\t})\n\t\tConvey(\"A role can be access from an itself\", func() {\n\t\t\tan.setAttr(\"role\", \"roleFromAN\", true)\n\t\t\tSo(an.Role(), ShouldEqual, \"roleFromAN\")\n\t\t})\n\t})\n\tConvey(\"An abstractNode attributes can access role names\", t, func() {\n\t\tan := newAbstractNode(nil, document)\n\t\tparentDocument := newAbstractNode(nil, document)\n\t\tparentDocument.setAttr(\"role\", \"role1FromParentDocument role2FromParentDocument role3FromParentDocument\", true)\n\t\tparent := newAbstractNode(parentDocument, document)\n\n\t\tConvey(\"A role name can be accessed on the document\", func() {\n\t\t\tSo(len(an.RoleNames()), ShouldBeZeroValue)\n\t\t\tan.SetParent(parent)\n\t\t\tSo(an.Document(), ShouldEqual, parentDocument)\n\t\t\tSo(len(an.RoleNames()), ShouldEqual, 3)\n\t\t})\n\t\tConvey(\"A role name can be accessed on the abstractNode itself\", func() {\n\t\t\tan.setAttr(\"role\", \"role1FromAN role2FromAN role3FromAN role5FromAN role4FromAN\", true)\n\t\t\tSo(len(an.RoleNames()), ShouldEqual, 5)\n\t\t})\n\t})\n\n\tConvey(\"An abstractNode attributes can check for a reftext\", t, func() {\n\t\tan := newAbstractNode(nil, document)\n\t\tparentDocument := newAbstractNode(nil, document)\n\t\tparentDocument.setAttr(\"reftext\", \"reftextFromParentDocument\", true)\n\t\tparent := newAbstractNode(parentDocument, document)\n\t\tConvey(\"A reftext can be checked on the document\", func() {\n\t\t\tSo(an.HasReftext(), ShouldBeFalse)\n\t\t\tSo(parentDocument.HasReftext(), ShouldBeTrue)\n\t\t\tan.SetParent(parent)\n\t\t\tSo(an.HasReftext(), ShouldBeTrue)\n\t\t})\n\t\tConvey(\"A reftext can be checked directly on the abstractNode\", func() {\n\t\t\tan := newAbstractNode(nil, document)\n\t\t\tparentDocument := newAbstractNode(nil, document)\n\t\t\tparent := newAbstractNode(parentDocument, document)\n\t\t\tSo(an.HasReftext(), ShouldBeFalse)\n\t\t\tan.SetParent(parent)\n\t\t\tSo(an.HasReftext(), ShouldBeFalse)\n\t\t\tan.setAttr(\"reftext\", \"reftextFromAN\", true)\n\t\t\tSo(an.HasReftext(), ShouldBeTrue)\n\t\t\tSo(an.Document().HasReftext(), ShouldBeFalse)\n\t\t})\n\t})\n\n\tConvey(\"An abstractNode attributes can access reftext\", t, func() {\n\t\tan := newAbstractNode(nil, document)\n\t\tparentDocument := newAbstractNode(nil, document)\n\t\tparentDocument.setAttr(\"reftext\", \"reftextFromParentDocument\", true)\n\t\tparent := newAbstractNode(parentDocument, document)\n\t\tConvey(\"A reftext can be access from an document, when an has no reftext\", func() {\n\t\t\tSo(an.Reftext(), ShouldBeNil)\n\t\t\tSo(parentDocument.Reftext(), ShouldEqual, \"reftextFromParentDocument\")\n\t\t\tan.SetParent(parent)\n\t\t\tSo(an.Reftext(), ShouldEqual, \"reftextFromParentDocument\")\n\t\t})\n\t\tConvey(\"A reftext can be access from an itself\", func() {\n\t\t\tan.setAttr(\"reftext\", \"reftextFromAN\", true)\n\t\t\tSo(an.Reftext(), ShouldEqual, \"reftextFromAN\")\n\t\t})\n\t})\n\n\tConvey(\"An abstractNode attributes can check for Slash Usage\", t, func() {\n\t\tan := newAbstractNode(nil, section)\n\t\tparentDocument := newAbstractNode(nil, document)\n\t\tConvey(\"A abstractNode without document won't use slash\", func() {\n\t\t\tSo(an.ShortTagSlash(), ShouldBeNil)\n\t\t})\n\t\tConvey(\"A abstractNode with document htmlsyntax set to not xml won't use slash\", func() {\n\t\t\tparentDocument.setAttr(\"htmlsyntax\", \"notxml\", true)\n\t\t\tparent := newAbstractNode(parentDocument, document)\n\t\t\tan.SetParent(parent)\n\t\t\tSo(an.ShortTagSlash(), ShouldBeNil)\n\t\t})\n\t\tConvey(\"A abstractNode with document htmlsyntax set to not xml will use slash\", func() {\n\t\t\tparentDocument.setAttr(\"htmlsyntax\", \"xml\", true)\n\t\t\tSo(strings.Trim(strconv.QuoteRune(*an.ShortTagSlash()), \"'\"), ShouldEqual, \"\/\")\n\t\t})\n\t})\n\tConvey(\"An abstractNode attributes can build media uri\", t, func() {\n\t\tan := newAbstractNode(nil, section)\n\t\ttarget := \"\"\n\t\tConvey(\"If the target media is a URI reference, then leave it untouched.\", func() {\n\t\t\ttarget = \"data:info\"\n\t\t\t\/\/ So(REGEXP[\":uri_sniff\"].String(), ShouldEqual, \"^[a-zA-Z][a-zA-Z0-9.+-]*:\/{0,2}.*\")\n\t\t\t\/\/ So(REGEXP[\":uri_sniff\"].MatchString(target), ShouldBeTrue)\n\t\t\tSo(an.MediaUri(target, \"dummy\"), ShouldEqual, target)\n\t\t})\n\t})\n}\n<commit_msg>Rename Option() calls into HasOption() calls.<commit_after>package asciidocgo\n\nimport (\n\t. \"github.com\/smartystreets\/goconvey\/convey\"\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestAbstractNode(t *testing.T) {\n\n\tConvey(\"An abstractNode can be initialized\", t, func() {\n\n\t\tConvey(\"By default, an AbstractNode can be created\", func() {\n\t\t\tSo(&abstractNode{}, ShouldNotBeNil)\n\t\t})\n\t\tConvey(\"An AbstractNode takes a parent and a context\", func() {\n\t\t\tSo(newAbstractNode(nil, document), ShouldNotBeNil)\n\t\t})\n\t\tConvey(\"If context is a document, then parent is nil and document is parent\", func() {\n\t\t\tparent := &abstractNode{}\n\t\t\tan := newAbstractNode(parent, document)\n\t\t\tSo(an.Context(), ShouldEqual, document)\n\t\t\tSo(an.Parent(), ShouldBeNil)\n\t\t\tSo(an.Document(), ShouldEqual, parent)\n\t\t})\n\t\tConvey(\"If context is not document, then parent is parent and document is parent document\", func() {\n\t\t\tparent := &abstractNode{nil, document, &abstractNode{}, nil, &substitutors{}}\n\t\t\tan := newAbstractNode(parent, section)\n\t\t\tSo(an.Context(), ShouldEqual, section)\n\t\t\tSo(an.Parent(), ShouldEqual, parent)\n\t\t\tSo(an.Document(), ShouldEqual, parent.Document())\n\t\t})\n\t\tConvey(\"If context is not document, and parent is nil, then document is nil\", func() {\n\t\t\tan := newAbstractNode(nil, section)\n\t\t\tSo(an.Context(), ShouldEqual, section)\n\t\t\tSo(an.Parent(), ShouldBeNil)\n\t\t\tSo(an.Document(), ShouldBeNil)\n\t\t})\n\n\t\tConvey(\"An abstractNode has an empty attributes map\", func() {\n\t\t\tan := newAbstractNode(nil, section)\n\t\t\tSo(len(an.Attributes()), ShouldEqual, 0)\n\t\t})\n\t})\n\n\tConvey(\"An abstractNode can be associated to a parent\", t, func() {\n\t\tan := newAbstractNode(nil, section)\n\t\tdocumentParent := &abstractNode{}\n\t\tparent := &abstractNode{nil, document, documentParent, nil, &substitutors{}}\n\t\tan.SetParent(parent)\n\t\tSo(an.Parent(), ShouldEqual, parent)\n\t\tSo(an.Document(), ShouldEqual, parent.Document())\n\t})\n\n\tConvey(\"An abstractNode can retrieve an attribute\", t, func() {\n\n\t\tparentDocument := newAbstractNode(nil, document)\n\t\tparentDocument.setAttr(\"key\", \"val1\", true)\n\t\tparent := newAbstractNode(parentDocument, document)\n\t\tan := newAbstractNode(nil, document)\n\t\tConvey(\"If inherited, it is the attribute if there, or the document attribute, or default value\", func() {\n\t\t\tSo(an.Attr(\"key\", nil, true), ShouldBeNil)\n\t\t\tan.setAttr(\"key\", \"val\", false)\n\t\t\tSo(an.Attr(\"key\", nil, true), ShouldEqual, \"val\")\n\t\t\tan.SetParent(parent)\n\t\t\tSo(an.Attr(\"key\", nil, true), ShouldEqual, \"val\")\n\t\t\tdelete(an.attributes, \"key\")\n\t\t\tSo(an.Attr(\"key\", nil, true), ShouldEqual, \"val1\")\n\t\t\t\/\/ an should have for parent a child, which has an as a document\n\t\t\t\/\/ then an.document would be \"parent\".document, meaning an, when\n\t\t\t\/\/ setting an.setParent(child)\n\t\t\tan.document = an\n\t\t\tan.setAttr(\"key\", \"val\", false)\n\t\t\tSo(an.Attr(\"key\", nil, true), ShouldEqual, \"val\")\n\t\t})\n\t\tConvey(\"If not inherited, it is the attribute if there, or default value\", func() {\n\t\t\tan.SetParent(parent)\n\t\t\tSo(an.Document(), ShouldEqual, parentDocument)\n\t\t\tSo(an.Document(), ShouldEqual, parent.Document())\n\t\t\tSo(parentDocument.Attr(\"key\", nil, false), ShouldEqual, \"val1\")\n\t\t\tSo(an.Attr(\"key\", nil, false), ShouldEqual, \"val\")\n\t\t})\n\t})\n\tConvey(\"An abstractNode can set an attribute\", t, func() {\n\t\tan := newAbstractNode(nil, document)\n\t\tan.setAttr(\"key\", \"val\", true)\n\t\tSo(an.Attr(\"key\", nil, true), ShouldEqual, \"val\")\n\t\tConvey(\"If not override and already present, the value should not change\", func() {\n\t\t\tres := an.setAttr(\"key\", \"val1\", false)\n\t\t\tSo(an.Attr(\"key\", nil, true), ShouldEqual, \"val\")\n\t\t\tSo(res, ShouldBeFalse)\n\t\t})\n\t})\n\n\tConvey(\"An abstractNode can set an option attribute\", t, func() {\n\t\tan := newAbstractNode(nil, document)\n\t\tConvey(\"First option means options attributes has len 1\", func() {\n\t\t\tan.SetOption(\"opt1\")\n\t\t\tSo(len(an.attributes[\"options\"].(map[string]bool)), ShouldEqual, 1)\n\t\t\tSo(an.Attr(\"opt1-option\", nil, false), ShouldEqual, true)\n\t\t})\n\t\tConvey(\"Second option means options attributes has len 2\", func() {\n\t\t\tan.SetOption(\"opt2\")\n\t\t\tSo(len(an.attributes[\"options\"].(map[string]bool)), ShouldEqual, 2)\n\t\t\tSo(an.Attr(\"opt2-option\", nil, false), ShouldEqual, true)\n\t\t})\n\t})\n\n\tConvey(\"An abstractNode can get an option attribute\", t, func() {\n\t\tan := newAbstractNode(nil, document)\n\t\tConvey(\"Zero option means Option returns false\", func() {\n\t\t\tSo(an.HasOption(\"opt1\"), ShouldBeFalse)\n\t\t\tan.SetOption(\"opt1\")\n\t\t})\n\t\tConvey(\"One option means Option returns true\", func() {\n\t\t\tSo(an.HasOption(\"opt1\"), ShouldBeTrue)\n\t\t})\n\t})\n\n\tConvey(\"An abstractNode update option attributes with other attributes\", t, func() {\n\t\tan := newAbstractNode(nil, document)\n\t\tan.setAttr(\"key1\", \"val1\", true)\n\t\tan.setAttr(\"key2\", \"val2\", true)\n\t\tConvey(\"New Attributes are added during an update\", func() {\n\t\t\tattrs := map[string]interface{}{\"key3\": \"val3\", \"key4\": \"val4\"}\n\t\t\tan.Update(attrs)\n\t\t\tSo(an.Attr(\"key1\", nil, false), ShouldEqual, \"val1\")\n\t\t\tSo(an.Attr(\"key2\", nil, false), ShouldEqual, \"val2\")\n\t\t\tSo(an.Attr(\"key3\", nil, false), ShouldEqual, \"val3\")\n\t\t\tSo(an.Attr(\"key4\", nil, false), ShouldEqual, \"val4\")\n\t\t})\n\t\tConvey(\"Common Attributes are overrriden during an update\", func() {\n\t\t\tattrs := map[string]interface{}{\"key2\": \"val2b\", \"key3\": \"val3\"}\n\t\t\tan.Update(attrs)\n\t\t\tSo(an.Attr(\"key1\", nil, false), ShouldEqual, \"val1\")\n\t\t\tSo(an.Attr(\"key2\", nil, false), ShouldEqual, \"val2b\")\n\t\t\tSo(an.Attr(\"key3\", nil, false), ShouldEqual, \"val3\")\n\t\t})\n\t})\n\tConvey(\"An abstractNode attributes can check for a role\", t, func() {\n\t\tan := newAbstractNode(nil, document)\n\t\tparentDocument := newAbstractNode(nil, document)\n\t\tparentDocument.setAttr(\"role\", \"roleFromParentDocument\", true)\n\t\tparent := newAbstractNode(parentDocument, document)\n\t\tConvey(\"A role can be checked, whatever its value is\", func() {\n\t\t\tSo(an.HasRole(nil), ShouldBeFalse)\n\t\t\tSo(parentDocument.HasRole(nil), ShouldBeTrue)\n\t\t\tan.SetParent(parent)\n\t\t\tSo(an.HasRole(nil), ShouldBeTrue)\n\t\t})\n\t\tConvey(\"A role can be checked against an expected value\", func() {\n\t\t\tan := newAbstractNode(nil, document)\n\t\t\tan.SetParent(parent)\n\t\t\tSo(an.HasRole(\"roleFromAN\"), ShouldBeFalse)\n\t\t\tSo(an.HasRole(\"roleFromParentDocument\"), ShouldBeTrue)\n\t\t\tan.setAttr(\"role\", \"roleFromAN\", true)\n\t\t\tSo(an.HasRole(\"roleFromAN\"), ShouldBeTrue)\n\t\t\tSo(an.HasRole(\"roleFromParentDocument\"), ShouldBeFalse)\n\t\t})\n\t})\n\tConvey(\"An abstractNode attributes can check for a role name\", t, func() {\n\t\tan := newAbstractNode(nil, document)\n\t\tparentDocument := newAbstractNode(nil, document)\n\t\tparentDocument.setAttr(\"role\", \"role1FromParentDocument role2FromParentDocument role3FromParentDocument\", true)\n\t\tparent := newAbstractNode(parentDocument, document)\n\n\t\tConvey(\"A role name can be checked on the document\", func() {\n\t\t\tSo(an.HasARole(\"role3FromAN\"), ShouldBeFalse)\n\t\t\tSo(an.HasARole(\"role2FromParentDocument\"), ShouldBeFalse)\n\t\t\tan.SetParent(parent)\n\t\t\tSo(an.Document(), ShouldEqual, parentDocument)\n\t\t\t\/\/So(an.Document().Attr(\"role\", nil, true), ShouldEqual, \"test\")\n\t\t\tSo(an.HasARole(\"role2FromParentDocument\"), ShouldBeTrue)\n\t\t\tSo(an.HasARole(\"role4FromParentDocument\"), ShouldBeFalse)\n\t\t})\n\t\tConvey(\"A role name can be checked on the abstractNode itself\", func() {\n\t\t\tan.setAttr(\"role\", \"role1FromAN role2FromAN role3FromAN\", true)\n\t\t\tSo(an.HasARole(\"role3FromAN\"), ShouldBeTrue)\n\t\t})\n\t\tConvey(\"An empty role name is always false=\", func() {\n\t\t\tSo(an.HasARole(\"\"), ShouldBeFalse)\n\t\t})\n\t})\n\tConvey(\"An abstractNode attributes can access role\", t, func() {\n\t\tan := newAbstractNode(nil, document)\n\t\tparentDocument := newAbstractNode(nil, document)\n\t\tparentDocument.setAttr(\"role\", \"roleFromParentDocument\", true)\n\t\tparent := newAbstractNode(parentDocument, document)\n\t\tConvey(\"A role can be access from an document, when an has no role\", func() {\n\t\t\tSo(an.Role(), ShouldBeNil)\n\t\t\tSo(parentDocument.Role(), ShouldEqual, \"roleFromParentDocument\")\n\t\t\tan.SetParent(parent)\n\t\t\tSo(an.Role(), ShouldEqual, \"roleFromParentDocument\")\n\t\t})\n\t\tConvey(\"A role can be access from an itself\", func() {\n\t\t\tan.setAttr(\"role\", \"roleFromAN\", true)\n\t\t\tSo(an.Role(), ShouldEqual, \"roleFromAN\")\n\t\t})\n\t})\n\tConvey(\"An abstractNode attributes can access role names\", t, func() {\n\t\tan := newAbstractNode(nil, document)\n\t\tparentDocument := newAbstractNode(nil, document)\n\t\tparentDocument.setAttr(\"role\", \"role1FromParentDocument role2FromParentDocument role3FromParentDocument\", true)\n\t\tparent := newAbstractNode(parentDocument, document)\n\n\t\tConvey(\"A role name can be accessed on the document\", func() {\n\t\t\tSo(len(an.RoleNames()), ShouldBeZeroValue)\n\t\t\tan.SetParent(parent)\n\t\t\tSo(an.Document(), ShouldEqual, parentDocument)\n\t\t\tSo(len(an.RoleNames()), ShouldEqual, 3)\n\t\t})\n\t\tConvey(\"A role name can be accessed on the abstractNode itself\", func() {\n\t\t\tan.setAttr(\"role\", \"role1FromAN role2FromAN role3FromAN role5FromAN role4FromAN\", true)\n\t\t\tSo(len(an.RoleNames()), ShouldEqual, 5)\n\t\t})\n\t})\n\n\tConvey(\"An abstractNode attributes can check for a reftext\", t, func() {\n\t\tan := newAbstractNode(nil, document)\n\t\tparentDocument := newAbstractNode(nil, document)\n\t\tparentDocument.setAttr(\"reftext\", \"reftextFromParentDocument\", true)\n\t\tparent := newAbstractNode(parentDocument, document)\n\t\tConvey(\"A reftext can be checked on the document\", func() {\n\t\t\tSo(an.HasReftext(), ShouldBeFalse)\n\t\t\tSo(parentDocument.HasReftext(), ShouldBeTrue)\n\t\t\tan.SetParent(parent)\n\t\t\tSo(an.HasReftext(), ShouldBeTrue)\n\t\t})\n\t\tConvey(\"A reftext can be checked directly on the abstractNode\", func() {\n\t\t\tan := newAbstractNode(nil, document)\n\t\t\tparentDocument := newAbstractNode(nil, document)\n\t\t\tparent := newAbstractNode(parentDocument, document)\n\t\t\tSo(an.HasReftext(), ShouldBeFalse)\n\t\t\tan.SetParent(parent)\n\t\t\tSo(an.HasReftext(), ShouldBeFalse)\n\t\t\tan.setAttr(\"reftext\", \"reftextFromAN\", true)\n\t\t\tSo(an.HasReftext(), ShouldBeTrue)\n\t\t\tSo(an.Document().HasReftext(), ShouldBeFalse)\n\t\t})\n\t})\n\n\tConvey(\"An abstractNode attributes can access reftext\", t, func() {\n\t\tan := newAbstractNode(nil, document)\n\t\tparentDocument := newAbstractNode(nil, document)\n\t\tparentDocument.setAttr(\"reftext\", \"reftextFromParentDocument\", true)\n\t\tparent := newAbstractNode(parentDocument, document)\n\t\tConvey(\"A reftext can be access from an document, when an has no reftext\", func() {\n\t\t\tSo(an.Reftext(), ShouldBeNil)\n\t\t\tSo(parentDocument.Reftext(), ShouldEqual, \"reftextFromParentDocument\")\n\t\t\tan.SetParent(parent)\n\t\t\tSo(an.Reftext(), ShouldEqual, \"reftextFromParentDocument\")\n\t\t})\n\t\tConvey(\"A reftext can be access from an itself\", func() {\n\t\t\tan.setAttr(\"reftext\", \"reftextFromAN\", true)\n\t\t\tSo(an.Reftext(), ShouldEqual, \"reftextFromAN\")\n\t\t})\n\t})\n\n\tConvey(\"An abstractNode attributes can check for Slash Usage\", t, func() {\n\t\tan := newAbstractNode(nil, section)\n\t\tparentDocument := newAbstractNode(nil, document)\n\t\tConvey(\"A abstractNode without document won't use slash\", func() {\n\t\t\tSo(an.ShortTagSlash(), ShouldBeNil)\n\t\t})\n\t\tConvey(\"A abstractNode with document htmlsyntax set to not xml won't use slash\", func() {\n\t\t\tparentDocument.setAttr(\"htmlsyntax\", \"notxml\", true)\n\t\t\tparent := newAbstractNode(parentDocument, document)\n\t\t\tan.SetParent(parent)\n\t\t\tSo(an.ShortTagSlash(), ShouldBeNil)\n\t\t})\n\t\tConvey(\"A abstractNode with document htmlsyntax set to not xml will use slash\", func() {\n\t\t\tparentDocument.setAttr(\"htmlsyntax\", \"xml\", true)\n\t\t\tSo(strings.Trim(strconv.QuoteRune(*an.ShortTagSlash()), \"'\"), ShouldEqual, \"\/\")\n\t\t})\n\t})\n\tConvey(\"An abstractNode attributes can build media uri\", t, func() {\n\t\tan := newAbstractNode(nil, section)\n\t\ttarget := \"\"\n\t\tConvey(\"If the target media is a URI reference, then leave it untouched.\", func() {\n\t\t\ttarget = \"data:info\"\n\t\t\t\/\/ So(REGEXP[\":uri_sniff\"].String(), ShouldEqual, \"^[a-zA-Z][a-zA-Z0-9.+-]*:\/{0,2}.*\")\n\t\t\t\/\/ So(REGEXP[\":uri_sniff\"].MatchString(target), ShouldBeTrue)\n\t\t\tSo(an.MediaUri(target, \"dummy\"), ShouldEqual, target)\n\t\t})\n\t})\n}\n<|endoftext|>"}
{"text":"<commit_before>package run\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/influxdb\/influxdb\/cluster\"\n\t\"github.com\/influxdb\/influxdb\/meta\"\n\t\"github.com\/influxdb\/influxdb\/services\/admin\"\n\t\"github.com\/influxdb\/influxdb\/services\/collectd\"\n\t\"github.com\/influxdb\/influxdb\/services\/continuous_querier\"\n\t\"github.com\/influxdb\/influxdb\/services\/graphite\"\n\t\"github.com\/influxdb\/influxdb\/services\/httpd\"\n\t\"github.com\/influxdb\/influxdb\/services\/opentsdb\"\n\t\"github.com\/influxdb\/influxdb\/services\/retention\"\n\t\"github.com\/influxdb\/influxdb\/services\/udp\"\n\t\"github.com\/influxdb\/influxdb\/tsdb\"\n)\n\n\/\/ Server represents a container for the metadata and storage data and services.\n\/\/ It is built using a Config and it manages the startup and shutdown of all\n\/\/ services in the proper order.\ntype Server struct {\n\terr     chan error\n\tclosing chan struct{}\n\n\tMetaStore     *meta.Store\n\tTSDBStore     *tsdb.Store\n\tQueryExecutor *tsdb.QueryExecutor\n\tPointsWriter  *cluster.PointsWriter\n\tShardWriter   *cluster.ShardWriter\n\n\tServices []Service\n}\n\n\/\/ NewServer returns a new instance of Server built from a config.\nfunc NewServer(c *Config) *Server {\n\t\/\/ Construct base meta store and data store.\n\ts := &Server{\n\t\terr:       make(chan error),\n\t\tclosing:   make(chan struct{}),\n\t\tMetaStore: meta.NewStore(c.Meta),\n\t\tTSDBStore: tsdb.NewStore(c.Data.Dir),\n\t}\n\n\t\/\/ Initialize query executor.\n\ts.QueryExecutor = tsdb.NewQueryExecutor(s.TSDBStore)\n\ts.QueryExecutor.MetaStore = s.MetaStore\n\ts.QueryExecutor.MetaStatementExecutor = &meta.StatementExecutor{Store: s.MetaStore}\n\n\t\/\/ Set the shard writer\n\ts.ShardWriter = cluster.NewShardWriter(time.Duration(c.Cluster.ShardWriterTimeout))\n\ts.ShardWriter.MetaStore = s.MetaStore\n\n\t\/\/ Initialize points writer.\n\ts.PointsWriter = cluster.NewPointsWriter()\n\ts.PointsWriter.MetaStore = s.MetaStore\n\ts.PointsWriter.TSDBStore = s.TSDBStore\n\ts.PointsWriter.ShardWriter = s.ShardWriter\n\n\t\/\/ Append services.\n\ts.appendClusterService(c.Cluster)\n\ts.appendAdminService(c.Admin)\n\ts.appendHTTPDService(c.HTTPD)\n\ts.appendCollectdService(c.Collectd)\n\ts.appendOpenTSDBService(c.OpenTSDB)\n\ts.appendUDPService(c.UDP)\n\ts.appendRetentionPolicyService(c.Retention)\n\ts.appendContinuousQueryService(c.ContinuousQuery)\n\tfor _, g := range c.Graphites {\n\t\ts.appendGraphiteService(g)\n\t}\n\n\treturn s\n}\n\nfunc (s *Server) appendClusterService(c cluster.Config) {\n\tsrv := cluster.NewService(c)\n\tsrv.TSDBStore = s.TSDBStore\n\ts.Services = append(s.Services, srv)\n}\n\nfunc (s *Server) appendRetentionPolicyService(c retention.Config) {\n\tif !c.Enabled {\n\t\treturn\n\t}\n\tsrv := retention.NewService(c)\n\tsrv.MetaStore = s.MetaStore\n\tsrv.TSDBStore = s.TSDBStore\n\ts.Services = append(s.Services, srv)\n}\n\nfunc (s *Server) appendAdminService(c admin.Config) {\n\tif !c.Enabled {\n\t\treturn\n\t}\n\tsrv := admin.NewService(c)\n\ts.Services = append(s.Services, srv)\n}\n\nfunc (s *Server) appendHTTPDService(c httpd.Config) {\n\tif !c.Enabled {\n\t\treturn\n\t}\n\tsrv := httpd.NewService(c)\n\tsrv.Handler.MetaStore = s.MetaStore\n\tsrv.Handler.QueryExecutor = s.QueryExecutor\n\tsrv.Handler.PointsWriter = s.PointsWriter\n\ts.Services = append(s.Services, srv)\n}\n\nfunc (s *Server) appendCollectdService(c collectd.Config) {\n\tif !c.Enabled {\n\t\treturn\n\t}\n\tsrv := collectd.NewService(c)\n\ts.Services = append(s.Services, srv)\n}\n\nfunc (s *Server) appendOpenTSDBService(c opentsdb.Config) {\n\tif !c.Enabled {\n\t\treturn\n\t}\n\tsrv := opentsdb.NewService(c)\n\ts.Services = append(s.Services, srv)\n}\n\nfunc (s *Server) appendGraphiteService(c graphite.Config) {\n\tif !c.Enabled {\n\t\treturn\n\t}\n\tsrv := graphite.NewService(c)\n\ts.Services = append(s.Services, srv)\n}\n\nfunc (s *Server) appendUDPService(c udp.Config) {\n\tif !c.Enabled {\n\t\treturn\n\t}\n\tsrv := udp.NewService(c)\n\tsrv.Server.PointsWriter = s.PointsWriter\n}\n\nfunc (s *Server) appendContinuousQueryService(c continuous_querier.Config) {\n\tsrv := continuous_querier.NewService(c)\n\tsrv.MetaStore = s.MetaStore\n\tsrv.QueryExecutor = s.QueryExecutor\n\tsrv.PointsWriter = s.PointsWriter\n\ts.Services = append(s.Services, srv)\n}\n\n\/\/ Err returns an error channel that multiplexes all out of band errors received from all services.\nfunc (s *Server) Err() <-chan error { return s.err }\n\n\/\/ Open opens the meta and data store and all services.\nfunc (s *Server) Open() error {\n\tif err := func() error {\n\t\t\/\/ Open meta store.\n\t\tif err := s.MetaStore.Open(); err != nil {\n\t\t\treturn fmt.Errorf(\"open meta store: %s\", err)\n\t\t}\n\t\tgo s.monitorErrorChan(s.MetaStore.Err())\n\n\t\t\/\/ Wait for the store to initialize.\n\t\t<-s.MetaStore.Ready()\n\n\t\t\/\/ Open TSDB store.\n\t\tif err := s.TSDBStore.Open(); err != nil {\n\t\t\treturn fmt.Errorf(\"open tsdb store: %s\", err)\n\t\t}\n\n\t\tfor _, service := range s.Services {\n\t\t\tif err := service.Open(); err != nil {\n\t\t\t\treturn fmt.Errorf(\"open service: %s\", err)\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\n\t}(); err != nil {\n\t\ts.Close()\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ Close shuts down the meta and data stores and all services.\nfunc (s *Server) Close() error {\n\tif s.MetaStore != nil {\n\t\ts.MetaStore.Close()\n\t}\n\tif s.TSDBStore != nil {\n\t\ts.TSDBStore.Close()\n\t}\n\tfor _, service := range s.Services {\n\t\tservice.Close()\n\t}\n\tclose(s.closing)\n\treturn nil\n}\n\n\/\/ monitorErrorChan reads an error channel and resends it through the server.\nfunc (s *Server) monitorErrorChan(ch <-chan error) {\n\tfor {\n\t\tselect {\n\t\tcase err, ok := <-ch:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\t\t\ts.err <- err\n\t\tcase <-s.closing:\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/ Service represents a service attached to the server.\ntype Service interface {\n\tOpen() error\n\tClose() error\n}\n<commit_msg>fix #2733: check config before enabling CQ service<commit_after>package run\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/influxdb\/influxdb\/cluster\"\n\t\"github.com\/influxdb\/influxdb\/meta\"\n\t\"github.com\/influxdb\/influxdb\/services\/admin\"\n\t\"github.com\/influxdb\/influxdb\/services\/collectd\"\n\t\"github.com\/influxdb\/influxdb\/services\/continuous_querier\"\n\t\"github.com\/influxdb\/influxdb\/services\/graphite\"\n\t\"github.com\/influxdb\/influxdb\/services\/httpd\"\n\t\"github.com\/influxdb\/influxdb\/services\/opentsdb\"\n\t\"github.com\/influxdb\/influxdb\/services\/retention\"\n\t\"github.com\/influxdb\/influxdb\/services\/udp\"\n\t\"github.com\/influxdb\/influxdb\/tsdb\"\n)\n\n\/\/ Server represents a container for the metadata and storage data and services.\n\/\/ It is built using a Config and it manages the startup and shutdown of all\n\/\/ services in the proper order.\ntype Server struct {\n\terr     chan error\n\tclosing chan struct{}\n\n\tMetaStore     *meta.Store\n\tTSDBStore     *tsdb.Store\n\tQueryExecutor *tsdb.QueryExecutor\n\tPointsWriter  *cluster.PointsWriter\n\tShardWriter   *cluster.ShardWriter\n\n\tServices []Service\n}\n\n\/\/ NewServer returns a new instance of Server built from a config.\nfunc NewServer(c *Config) *Server {\n\t\/\/ Construct base meta store and data store.\n\ts := &Server{\n\t\terr:       make(chan error),\n\t\tclosing:   make(chan struct{}),\n\t\tMetaStore: meta.NewStore(c.Meta),\n\t\tTSDBStore: tsdb.NewStore(c.Data.Dir),\n\t}\n\n\t\/\/ Initialize query executor.\n\ts.QueryExecutor = tsdb.NewQueryExecutor(s.TSDBStore)\n\ts.QueryExecutor.MetaStore = s.MetaStore\n\ts.QueryExecutor.MetaStatementExecutor = &meta.StatementExecutor{Store: s.MetaStore}\n\n\t\/\/ Set the shard writer\n\ts.ShardWriter = cluster.NewShardWriter(time.Duration(c.Cluster.ShardWriterTimeout))\n\ts.ShardWriter.MetaStore = s.MetaStore\n\n\t\/\/ Initialize points writer.\n\ts.PointsWriter = cluster.NewPointsWriter()\n\ts.PointsWriter.MetaStore = s.MetaStore\n\ts.PointsWriter.TSDBStore = s.TSDBStore\n\ts.PointsWriter.ShardWriter = s.ShardWriter\n\n\t\/\/ Append services.\n\ts.appendClusterService(c.Cluster)\n\ts.appendAdminService(c.Admin)\n\ts.appendHTTPDService(c.HTTPD)\n\ts.appendCollectdService(c.Collectd)\n\ts.appendOpenTSDBService(c.OpenTSDB)\n\ts.appendUDPService(c.UDP)\n\ts.appendRetentionPolicyService(c.Retention)\n\ts.appendContinuousQueryService(c.ContinuousQuery)\n\tfor _, g := range c.Graphites {\n\t\ts.appendGraphiteService(g)\n\t}\n\n\treturn s\n}\n\nfunc (s *Server) appendClusterService(c cluster.Config) {\n\tsrv := cluster.NewService(c)\n\tsrv.TSDBStore = s.TSDBStore\n\ts.Services = append(s.Services, srv)\n}\n\nfunc (s *Server) appendRetentionPolicyService(c retention.Config) {\n\tif !c.Enabled {\n\t\treturn\n\t}\n\tsrv := retention.NewService(c)\n\tsrv.MetaStore = s.MetaStore\n\tsrv.TSDBStore = s.TSDBStore\n\ts.Services = append(s.Services, srv)\n}\n\nfunc (s *Server) appendAdminService(c admin.Config) {\n\tif !c.Enabled {\n\t\treturn\n\t}\n\tsrv := admin.NewService(c)\n\ts.Services = append(s.Services, srv)\n}\n\nfunc (s *Server) appendHTTPDService(c httpd.Config) {\n\tif !c.Enabled {\n\t\treturn\n\t}\n\tsrv := httpd.NewService(c)\n\tsrv.Handler.MetaStore = s.MetaStore\n\tsrv.Handler.QueryExecutor = s.QueryExecutor\n\tsrv.Handler.PointsWriter = s.PointsWriter\n\ts.Services = append(s.Services, srv)\n}\n\nfunc (s *Server) appendCollectdService(c collectd.Config) {\n\tif !c.Enabled {\n\t\treturn\n\t}\n\tsrv := collectd.NewService(c)\n\ts.Services = append(s.Services, srv)\n}\n\nfunc (s *Server) appendOpenTSDBService(c opentsdb.Config) {\n\tif !c.Enabled {\n\t\treturn\n\t}\n\tsrv := opentsdb.NewService(c)\n\ts.Services = append(s.Services, srv)\n}\n\nfunc (s *Server) appendGraphiteService(c graphite.Config) {\n\tif !c.Enabled {\n\t\treturn\n\t}\n\tsrv := graphite.NewService(c)\n\ts.Services = append(s.Services, srv)\n}\n\nfunc (s *Server) appendUDPService(c udp.Config) {\n\tif !c.Enabled {\n\t\treturn\n\t}\n\tsrv := udp.NewService(c)\n\tsrv.Server.PointsWriter = s.PointsWriter\n}\n\nfunc (s *Server) appendContinuousQueryService(c continuous_querier.Config) {\n\tif !c.Enabled {\n\t\treturn\n\t}\n\tsrv := continuous_querier.NewService(c)\n\tsrv.MetaStore = s.MetaStore\n\tsrv.QueryExecutor = s.QueryExecutor\n\tsrv.PointsWriter = s.PointsWriter\n\ts.Services = append(s.Services, srv)\n}\n\n\/\/ Err returns an error channel that multiplexes all out of band errors received from all services.\nfunc (s *Server) Err() <-chan error { return s.err }\n\n\/\/ Open opens the meta and data store and all services.\nfunc (s *Server) Open() error {\n\tif err := func() error {\n\t\t\/\/ Open meta store.\n\t\tif err := s.MetaStore.Open(); err != nil {\n\t\t\treturn fmt.Errorf(\"open meta store: %s\", err)\n\t\t}\n\t\tgo s.monitorErrorChan(s.MetaStore.Err())\n\n\t\t\/\/ Wait for the store to initialize.\n\t\t<-s.MetaStore.Ready()\n\n\t\t\/\/ Open TSDB store.\n\t\tif err := s.TSDBStore.Open(); err != nil {\n\t\t\treturn fmt.Errorf(\"open tsdb store: %s\", err)\n\t\t}\n\n\t\tfor _, service := range s.Services {\n\t\t\tif err := service.Open(); err != nil {\n\t\t\t\treturn fmt.Errorf(\"open service: %s\", err)\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\n\t}(); err != nil {\n\t\ts.Close()\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ Close shuts down the meta and data stores and all services.\nfunc (s *Server) Close() error {\n\tif s.MetaStore != nil {\n\t\ts.MetaStore.Close()\n\t}\n\tif s.TSDBStore != nil {\n\t\ts.TSDBStore.Close()\n\t}\n\tfor _, service := range s.Services {\n\t\tservice.Close()\n\t}\n\tclose(s.closing)\n\treturn nil\n}\n\n\/\/ monitorErrorChan reads an error channel and resends it through the server.\nfunc (s *Server) monitorErrorChan(ch <-chan error) {\n\tfor {\n\t\tselect {\n\t\tcase err, ok := <-ch:\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\t\t\ts.err <- err\n\t\tcase <-s.closing:\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/ Service represents a service attached to the server.\ntype Service interface {\n\tOpen() error\n\tClose() error\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/go:generate mapstructure-to-hcl2 -type Config\n\npackage dockerimport\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com\/hashicorp\/hcl\/v2\/hcldec\"\n\t\"github.com\/hashicorp\/packer\/builder\/docker\"\n\t\"github.com\/hashicorp\/packer\/common\"\n\t\"github.com\/hashicorp\/packer\/helper\/config\"\n\t\"github.com\/hashicorp\/packer\/packer\"\n\t\"github.com\/hashicorp\/packer\/post-processor\/artifice\"\n\t\"github.com\/hashicorp\/packer\/template\/interpolate\"\n)\n\nconst BuilderId = \"packer.post-processor.docker-import\"\n\ntype Config struct {\n\tcommon.PackerConfig `mapstructure:\",squash\"`\n\n\tRepository string   `mapstructure:\"repository\"`\n\tTag        string   `mapstructure:\"tag\"`\n\tChanges    []string `mapstructure:\"changes\"`\n\n\tctx interpolate.Context\n}\n\ntype PostProcessor struct {\n\tconfig Config\n}\n\nfunc (p *PostProcessor) ConfigSpec() hcldec.ObjectSpec { return p.config.FlatMapstructure().HCL2Spec() }\n\nfunc (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\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n\n}\n\nfunc (p *PostProcessor) PostProcess(ctx context.Context, ui packer.Ui, artifact packer.Artifact) (packer.Artifact, bool, bool, error) {\n\tswitch artifact.BuilderId() {\n\tcase docker.BuilderId, artifice.BuilderId:\n\t\tbreak\n\tdefault:\n\t\terr := fmt.Errorf(\n\t\t\t\"Unknown artifact type: %s\\nCan only import from Docker builder and Artifice post-processor artifacts.\",\n\t\t\tartifact.BuilderId())\n\t\treturn nil, false, false, err\n\t}\n\n\timportRepo := p.config.Repository\n\tif p.config.Tag != \"\" {\n\t\timportRepo += \":\" + p.config.Tag\n\t}\n\n\tdriver := &docker.DockerDriver{Ctx: &p.config.ctx, Ui: ui}\n\n\tui.Message(\"Importing image: \" + artifact.Id())\n\tui.Message(\"Repository: \" + importRepo)\n\tid, err := driver.Import(artifact.Files()[0], p.config.Changes, importRepo)\n\tif err != nil {\n\t\treturn nil, false, false, err\n\t}\n\n\tui.Message(\"Imported ID: \" + id)\n\n\t\/\/ Build the artifact\n\tartifact = &docker.ImportArtifact{\n\t\tBuilderIdValue: BuilderId,\n\t\tDriver:         driver,\n\t\tIdValue:        importRepo,\n\t}\n\n\treturn artifact, false, false, nil\n}\n<commit_msg>make friendly error message (#9605)<commit_after>\/\/go:generate mapstructure-to-hcl2 -type Config\n\npackage dockerimport\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com\/hashicorp\/hcl\/v2\/hcldec\"\n\t\"github.com\/hashicorp\/packer\/builder\/docker\"\n\t\"github.com\/hashicorp\/packer\/common\"\n\t\"github.com\/hashicorp\/packer\/helper\/config\"\n\t\"github.com\/hashicorp\/packer\/packer\"\n\t\"github.com\/hashicorp\/packer\/post-processor\/artifice\"\n\t\"github.com\/hashicorp\/packer\/template\/interpolate\"\n)\n\nconst BuilderId = \"packer.post-processor.docker-import\"\n\ntype Config struct {\n\tcommon.PackerConfig `mapstructure:\",squash\"`\n\n\tRepository string   `mapstructure:\"repository\"`\n\tTag        string   `mapstructure:\"tag\"`\n\tChanges    []string `mapstructure:\"changes\"`\n\n\tctx interpolate.Context\n}\n\ntype PostProcessor struct {\n\tconfig Config\n}\n\nfunc (p *PostProcessor) ConfigSpec() hcldec.ObjectSpec { return p.config.FlatMapstructure().HCL2Spec() }\n\nfunc (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\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n\n}\n\nfunc (p *PostProcessor) PostProcess(ctx context.Context, ui packer.Ui, artifact packer.Artifact) (packer.Artifact, bool, bool, error) {\n\tswitch artifact.BuilderId() {\n\tcase docker.BuilderId, artifice.BuilderId:\n\t\tbreak\n\tdefault:\n\t\terr := fmt.Errorf(\n\t\t\t\"Unknown artifact type: %s\\nCan only import from Docker builder \"+\n\t\t\t\t\"and Artifice post-processor artifacts. If you are getting this \"+\n\t\t\t\t\"error after having run the docker builder, it may be because you \"+\n\t\t\t\t\"set commit: true in your Docker builder, so the image is \"+\n\t\t\t\t\"already imported. \",\n\t\t\tartifact.BuilderId())\n\t\treturn nil, false, false, err\n\t}\n\n\timportRepo := p.config.Repository\n\tif p.config.Tag != \"\" {\n\t\timportRepo += \":\" + p.config.Tag\n\t}\n\n\tdriver := &docker.DockerDriver{Ctx: &p.config.ctx, Ui: ui}\n\n\tui.Message(\"Importing image: \" + artifact.Id())\n\tui.Message(\"Repository: \" + importRepo)\n\tid, err := driver.Import(artifact.Files()[0], p.config.Changes, importRepo)\n\tif err != nil {\n\t\treturn nil, false, false, err\n\t}\n\n\tui.Message(\"Imported ID: \" + id)\n\n\t\/\/ Build the artifact\n\tartifact = &docker.ImportArtifact{\n\t\tBuilderIdValue: BuilderId,\n\t\tDriver:         driver,\n\t\tIdValue:        importRepo,\n\t}\n\n\treturn artifact, false, false, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package webfw_test\n\nimport (\n\t\"net\/http\"\n\n\t\"github.com\/urandom\/webfw\"\n\t\"github.com\/urandom\/webfw\/context\"\n\t\"github.com\/urandom\/webfw\/renderer\"\n)\n\ntype Hello struct {\n\twebfw.BaseController\n}\n\nfunc NewHello(pattern string) Hello {\n\treturn Hello{webfw.NewBaseController(pattern, MethodAll, \"\")}\n}\n\nfunc (con Hello) Handler(c *context.Context) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tparams := webfw.GetParams(c, r)\n\t\td := renderer.RenderData{\"name\": params[\"name\"]}\n\n\t\terr := webfw.GetRenderCtx(c, r)(w, d, \"hello.tmpl\")\n\t\tif err != nil {\n\t\t\twebfw.GetLogger(c, r).Print(err)\n\t\t}\n\t}\n}\n\nfunc Example() {\n\ts := webfw.NewServer()\n\n\tdispatcher := s.Dispatcher(\"\/\")\n\n\tdispatcher.Handle(NewHello(\"\/hello\/:name\"))\n\tif err := s.ListenAndServe(); err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc main() {\n\tExample()\n}\n<commit_msg>fix the example api usage<commit_after>package webfw_test\n\nimport (\n\t\"net\/http\"\n\n\t\"github.com\/urandom\/webfw\"\n\t\"github.com\/urandom\/webfw\/context\"\n\t\"github.com\/urandom\/webfw\/renderer\"\n)\n\ntype Hello struct {\n\twebfw.BaseController\n}\n\nfunc NewHello(pattern string) Hello {\n\treturn Hello{webfw.NewBaseController(pattern, webfw.MethodAll, \"\")}\n}\n\nfunc (con Hello) Handler(c context.Context) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tparams := webfw.GetParams(c, r)\n\t\td := renderer.RenderData{\"name\": params[\"name\"]}\n\n\t\terr := webfw.GetRenderCtx(c, r)(w, d, \"hello.tmpl\")\n\t\tif err != nil {\n\t\t\twebfw.GetLogger(c, r).Print(err)\n\t\t}\n\t}\n}\n\nfunc Example() {\n\ts := webfw.NewServer()\n\n\tdispatcher := s.Dispatcher(\"\/\")\n\n\tdispatcher.Handle(NewHello(\"\/hello\/:name\"))\n\tif err := s.ListenAndServe(); err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc main() {\n\tExample()\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2021 ETH Zurich\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage reservationstore\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n\n\tbase \"github.com\/scionproto\/scion\/go\/co\/reservation\"\n\t\"github.com\/scionproto\/scion\/go\/co\/reservation\/conf\"\n\t\"github.com\/scionproto\/scion\/go\/co\/reservation\/segment\"\n\t\"github.com\/scionproto\/scion\/go\/lib\/addr\"\n\t\"github.com\/scionproto\/scion\/go\/lib\/colibri\/reservation\"\n\t\"github.com\/scionproto\/scion\/go\/lib\/log\"\n\t\"github.com\/scionproto\/scion\/go\/lib\/pathpol\"\n\t\"github.com\/scionproto\/scion\/go\/lib\/serrors\"\n\tcolpath \"github.com\/scionproto\/scion\/go\/lib\/slayers\/path\/colibri\"\n\t\"github.com\/scionproto\/scion\/go\/lib\/snet\"\n)\n\n\/\/ sleepAtLeast is the time duration that the keeper will sleep at a minimum, even\n\/\/ if it's called very frequently.\nconst sleepAtLeast = 4 * time.Second\n\nconst sleepAtMost = 5 * time.Minute\n\n\/\/ min validity in the future for the reservations when checking their compliance,\n\/\/ the bigger the value, the more probable it is not to break continuity.\n\/\/ Typically this value would be twice the max. sleep period, to ensure no index would\n\/\/ expire while the keeper is sleeping.\nconst minDuration = 2 * sleepAtMost\n\n\/\/ min validity of new indices\/reservations. The bigger the value, the longer a single index\n\/\/ can be used. Too big a value could produce errors in the admission for some ASes.\n\/\/ This value would typically be equal to twice minDuration.\nconst newIndexMinDuration = 2 * minDuration\n\n\/\/ ServiceFacilitator defines a minimal interface that has to be implemented to be\n\/\/ usable by the keeper.\ntype ServiceFacilitator interface {\n\tPathsTo(ctx context.Context, dst addr.IA) ([]snet.Path, error)\n\tSetupRequest(ctx context.Context, req *segment.SetupReq) error\n\tActivateRequest(\n\t\tcontext.Context,\n\t\t*base.Request,\n\t\tbase.PathSteps,\n\t\t*colpath.ColibriPathMinimal,\n\t\tbool,\n\t) error\n\tGetReservationsAtSource(ctx context.Context) ([]*segment.Reservation, error)\n\tDeleteExpiredIndices(ctx context.Context) error\n}\n\n\/\/ keeper looks after the reservations configured in reservations.json\n\/\/ It starts by cleaning up those reservations that have expired.\n\/\/ The keeper tries to match existing reservations with configured entries.\n\/\/ If no match is found, a new reservation will be created.\ntype keeper struct {\n\tnow        func() time.Time\n\tlocalIA    addr.IA\n\tsleepUntil time.Time \/\/ nothing to do in the keeper until this time\n\tprovider   ServiceFacilitator\n\tentries    []*entry\n}\n\ntype entry struct {\n\tconf *configuration\n\trsv  *segment.Reservation\n}\n\n\/\/ PrepareSetupRequest creates a valid setup request with the steps always in the direction of\n\/\/ the traffic of the SegR, and the transport path always in the direction of the next\n\/\/ colibri service (thus for down-path SegRs the transport will be in the reverse wrt the steps).\nfunc (e *entry) PrepareSetupRequest(now, expTime time.Time, localAS addr.AS,\n\tp snet.Path) *segment.SetupReq {\n\n\tsteps, err := base.StepsFromSnet(p)\n\tif err != nil {\n\t\tlog.Info(\"error in SCION path, cannot convert to steps\", \"err\", err, \"path\", p)\n\t\tpanic(err)\n\t}\n\tcurrentStep := 0\n\n\t\/\/ if the SegR is of down-path type, reverse the steps\n\tif e.conf.pathType == reservation.DownPath {\n\t\tsteps = steps.Reverse()\n\t\tcurrentStep = len(steps) - 1\n\t}\n\n\tid, _ := reservation.NewID(localAS, make([]byte, reservation.IDSuffixSegLen))\n\treturn &segment.SetupReq{\n\t\tRequest:        *base.NewRequest(now, id, 0, len(steps)),\n\t\tExpirationTime: expTime,\n\t\tPathType:       e.conf.pathType,\n\t\tMinBW:          e.conf.minBW,\n\t\tMaxBW:          e.conf.maxBW,\n\t\tSplitCls:       e.conf.splitCls,\n\t\tPathProps:      e.conf.endProps,\n\t\tAllocTrail:     reservation.AllocationBeads{},\n\t\tSteps:          steps,\n\t\tCurrentStep:    currentStep,\n\t\tTransportPath:  nil, \/\/ new setups are not transported in colibri paths\n\t}\n}\n\nfunc (e *entry) PrepareRenewalRequest(now, expTime time.Time) *segment.SetupReq {\n\treturn &segment.SetupReq{\n\t\tRequest: *base.NewRequest(\n\t\t\tnow, &e.rsv.ID, e.rsv.NextIndexToRenew(), len(e.rsv.Steps)),\n\t\tExpirationTime: expTime,\n\t\tPathType:       e.conf.pathType,\n\t\tMinBW:          e.conf.minBW,\n\t\tMaxBW:          e.conf.maxBW,\n\t\tSplitCls:       e.rsv.TrafficSplit,\n\t\tPathProps:      e.rsv.PathEndProps,\n\t\tAllocTrail:     reservation.AllocationBeads{},\n\t\tSteps:          e.rsv.Steps.Copy(),\n\t\tCurrentStep:    0,\n\t\tTransportPath:  e.rsv.TransportPath,\n\t\tReservation:    e.rsv,\n\t}\n}\n\nfunc NewKeeper(\n\tctx context.Context,\n\tprovider ServiceFacilitator,\n\tconf *conf.Reservations,\n\tlocalIA addr.IA,\n) (*keeper, error) {\n\n\t\/\/ load configuration\n\treqs, err := parseInitial(conf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ cleanup expired indices before reading reservations\n\tif err := provider.DeleteExpiredIndices(ctx); err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ get existing reservations\n\trsvs, err := provider.GetReservationsAtSource(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tentries := matchRsvsWithConfiguration(rsvs, reqs)\n\n\tlog.Debug(\"colibri keeper\", \"reservations\", len(entries))\n\treturn &keeper{\n\t\tnow:        time.Now,\n\t\tlocalIA:    localIA,\n\t\tsleepUntil: time.Now().Add(-time.Nanosecond),\n\t\tprovider:   provider,\n\t\tentries:    entries,\n\t}, nil\n}\n\n\/\/ OneShot keeps all reservations healthy. Those that need renewal are renewed, those\n\/\/ that still have no reservation ID for its config will request a new one.\n\/\/ The function returns the time when it should be called next.\nfunc (k *keeper) OneShot(ctx context.Context) (time.Time, error) {\n\twg := sync.WaitGroup{}\n\ttimes := make([]time.Time, len(k.entries))\n\terrs := make(serrors.List, len(k.entries))\n\twg.Add(len(k.entries))\n\tfor i, e := range k.entries {\n\t\ti, e := i, e\n\t\tgo func() {\n\t\t\tdefer log.HandlePanic()\n\t\t\tdefer wg.Done()\n\t\t\ttimes[i], errs[i] = k.keepReservation(ctx, e)\n\t\t}()\n\t}\n\twg.Wait()\n\tif err := errs.Coalesce(); err != nil {\n\t\treturn k.now().Add(sleepAtLeast), err\n\t}\n\t\/\/ wakeupAtLatest is the maximum to wake up the keeper\n\twakeupAtLatest := k.now().Add(sleepAtMost)\n\tfor _, t := range times {\n\t\tif t.Before(wakeupAtLatest) {\n\t\t\twakeupAtLatest = t\n\t\t}\n\t}\n\t\/\/ but the keeper must sleep at least a minimum amount of time\n\tif wakeupAtLatest.Sub(k.now()) < sleepAtLeast {\n\t\twakeupAtLatest = k.now().Add(sleepAtLeast)\n\t}\n\treturn wakeupAtLatest, nil\n}\n\n\/\/ keepReservation will ensure that the reservation exists or a request is created.\nfunc (k *keeper) keepReservation(ctx context.Context, e *entry) (time.Time, error) {\n\tnow := k.now()\n\tvar err error\n\tif e.rsv == nil {\n\t\te.rsv, err = k.askNewReservation(ctx, e)\n\t\tif err != nil {\n\t\t\treturn time.Time{}, err\n\t\t}\n\t}\n\n\tswitch compliance(e, k.now().Add(minDuration)) {\n\tcase Compliant:\n\tcase NeedsIndices:\n\t\terr = k.askNewIndices(ctx, e)\n\tcase NeedsActivation:\n\t\terr = k.activateIndex(ctx, e)\n\t}\n\n\tif err != nil {\n\t\treturn time.Time{}, err\n\t}\n\treturn now.Add(newIndexMinDuration), nil\n}\n\n\/\/ matchRsvsWithConfiguration matches existing reservations with configuration.\n\/\/ It returns the appropriate entries to manage from the keeper.\n\/\/ Those entries without a reservation ID must obtain a new reservation;\n\/\/ those with a reservation ID will need index activation, etc.\nfunc matchRsvsWithConfiguration(rsvs []*segment.Reservation, conf []*configuration) []*entry {\n\tconf = append(conf[:0:0], conf...)\n\t\/\/ greedy strategy: for each reservation try to match it with the first compatible configuration\n\tentries := make([]*entry, 0)\n\tfor _, r := range rsvs {\n\t\ti := findCompatibleConfiguration(r, conf)\n\t\tif i < 0 {\n\t\t\tcontinue\n\t\t}\n\t\tentries = append(entries, &entry{\n\t\t\tconf: conf[i],\n\t\t\trsv:  r,\n\t\t})\n\t\t\/\/ one conf. is matched against this r; remove that entry from the pool\n\t\tconf = append(conf[:i], conf[i+1:]...)\n\t}\n\tfor _, c := range conf {\n\t\tentries = append(entries, &entry{\n\t\t\tconf: c,\n\t\t})\n\t}\n\treturn entries\n}\n\n\/\/ findCompatibleConfiguration finds the first compatible configuration with the reservation.\n\/\/ It returns the index of the configuration in the slice, or -1 if no valid one is found.\nfunc findCompatibleConfiguration(r *segment.Reservation, conf []*configuration) int {\n\tfor i, c := range conf {\n\t\tswitch {\n\t\tcase r.Steps.DstIA() != c.dst:\n\t\t\tcontinue\n\t\tcase r.PathType != c.pathType:\n\t\t\tcontinue\n\t\tcase r.TrafficSplit != c.splitCls:\n\t\t\tcontinue\n\t\tcase r.PathEndProps != c.endProps:\n\t\t\tcontinue\n\t\tcase !c.predicate.EvalInterfaces(r.Steps.Interfaces()):\n\t\t\tcontinue\n\t\t}\n\t\treturn i\n\t}\n\treturn -1\n}\n\nfunc (k *keeper) activateIndex(ctx context.Context, e *entry) error {\n\treq := base.NewRequest(k.now(), &e.rsv.ID, e.rsv.NextIndexToActivate().Idx,\n\t\tlen(e.rsv.Steps))\n\tinReverse := e.rsv.PathType == reservation.DownPath\n\terr := k.provider.ActivateRequest(ctx, req, e.rsv.Steps.Copy(), e.rsv.TransportPath, inReverse)\n\tif err == nil {\n\t\terr = e.rsv.SetIndexActive(req.Index)\n\t}\n\treturn err\n}\n\n\/\/ askNewIndices requests a renewal\nfunc (k *keeper) askNewIndices(ctx context.Context, e *entry) error {\n\tnow := k.now()\n\treq := e.PrepareRenewalRequest(now, now.Add(newIndexMinDuration))\n\treturn k.provider.SetupRequest(ctx, req)\n}\n\nfunc (k *keeper) askNewReservation(ctx context.Context, e *entry) (*segment.Reservation, error) {\n\tnow := k.now()\n\tpaths, err := k.provider.PathsTo(ctx, e.conf.dst)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ try with each possible path\n\tpaths = e.conf.predicate.Eval(paths)\n\tfor _, p := range paths {\n\t\treq := e.PrepareSetupRequest(now, now.Add(newIndexMinDuration), k.localIA.AS(), p)\n\t\terr := k.provider.SetupRequest(ctx, req)\n\t\tif err == nil {\n\t\t\tif req.Reservation == nil {\n\t\t\t\tpanic(\"logic error, reservation after new request is empty\")\n\t\t\t}\n\t\t}\n\t\tif req.Reservation != nil {\n\t\t\treturn req.Reservation, err\n\t\t}\n\t\tlog.Info(\"error creating new reservation from best effort path\", \"path\", p, \"err\", err)\n\t}\n\treturn nil, serrors.New(\"no more best effort paths to create reservation\", \"dst\", e.conf.dst)\n}\n\n\/\/ configuration is a 1 to 1 association to a conf.ReservationEntry\ntype configuration struct {\n\tdst       addr.IA\n\tpathType  reservation.PathType\n\tpredicate *pathpol.Sequence\n\tminBW     reservation.BWCls\n\tmaxBW     reservation.BWCls\n\tsplitCls  reservation.SplitCls\n\tendProps  reservation.PathEndProps\n}\n\ntype Compliance int\n\nconst (\n\tNeedsIndices    = Compliance(iota) \/\/ ask for a new index\n\tNeedsActivation                    \/\/ ask to activate index\n\tCompliant                          \/\/ already has an active compliant index\n)\n\nfunc (c Compliance) String() string {\n\tswitch c {\n\tcase NeedsIndices:\n\t\treturn \"NeedsIndices\"\n\tcase NeedsActivation:\n\t\treturn \"NeedsActivation\"\n\tcase Compliant:\n\t\treturn \"Compliant\"\n\tdefault:\n\t\tpanic(fmt.Errorf(\"unknown value for compliance %d\", c))\n\t}\n}\n\n\/\/ compliance finds the status of the reservation in regard with the configuration.\n\/\/ It returns Compliant if it contains active indices compatible with the configuration,\n\/\/ NeedsActivation if the compatible index(es) exist but need to be activated, or\n\/\/ NeedsIndices if no compatible index exists.\n\/\/ The function expects a non-nil reservation.\nfunc compliance(e *entry, until time.Time) Compliance {\n\tidxs := e.rsv.Indices.Filter(\n\t\tsegment.ByMinBW(e.conf.minBW),\n\t\tsegment.ByMaxBW(e.conf.maxBW),\n\t\tsegment.NotConfirmed(),\n\t\tsegment.ByExpiration(until),\n\t)\n\tswitch {\n\tcase len(idxs) == 0:\n\t\treturn NeedsIndices\n\tcase len(idxs.Filter(segment.NotSwitchableFrom(e.rsv.ActiveIndex()))) == 0:\n\t\treturn NeedsActivation\n\tdefault:\n\t\treturn Compliant\n\t}\n}\n\nfunc parseInitial(conf *conf.Reservations) ([]*configuration, error) {\n\tif conf == nil {\n\t\tlog.Info(\"COLIBRI not keeping any reservations\")\n\t\treturn nil, nil\n\t}\n\tlog.Info(\"COLIBRI will keep reservations\", \"count\", len(conf.Rsvs))\n\tinitial := make([]*configuration, len(conf.Rsvs))\n\tfor i, r := range conf.Rsvs {\n\t\tseq, err := pathpol.NewSequence(r.PathPredicate)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif r.MinSize > r.MaxSize {\n\t\t\treturn nil, serrors.New(\"min bw must be less or equal than max bw\",\n\t\t\t\t\"min_bw\", r.MinSize, \"max_bw\", r.MaxSize)\n\t\t}\n\n\t\tinitial[i] = &configuration{\n\t\t\tdst:       r.DstAS,\n\t\t\tpathType:  r.PathType,\n\t\t\tpredicate: seq,\n\t\t\tminBW:     r.MinSize,\n\t\t\tmaxBW:     r.MaxSize,\n\t\t\tsplitCls:  r.SplitCls,\n\t\t\tendProps:  reservation.PathEndProps(r.EndProps),\n\t\t}\n\t}\n\treturn initial, nil\n}\n<commit_msg>fix SetupReq.currentStep in renewal and indices after confirmation for keeper (#141)<commit_after>\/\/ Copyright 2021 ETH Zurich\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage reservationstore\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n\n\tbase \"github.com\/scionproto\/scion\/go\/co\/reservation\"\n\t\"github.com\/scionproto\/scion\/go\/co\/reservation\/conf\"\n\t\"github.com\/scionproto\/scion\/go\/co\/reservation\/segment\"\n\t\"github.com\/scionproto\/scion\/go\/lib\/addr\"\n\t\"github.com\/scionproto\/scion\/go\/lib\/colibri\/reservation\"\n\t\"github.com\/scionproto\/scion\/go\/lib\/log\"\n\t\"github.com\/scionproto\/scion\/go\/lib\/pathpol\"\n\t\"github.com\/scionproto\/scion\/go\/lib\/serrors\"\n\tcolpath \"github.com\/scionproto\/scion\/go\/lib\/slayers\/path\/colibri\"\n\t\"github.com\/scionproto\/scion\/go\/lib\/snet\"\n)\n\n\/\/ sleepAtLeast is the time duration that the keeper will sleep at a minimum, even\n\/\/ if it's called very frequently.\nconst sleepAtLeast = 4 * time.Second\n\nconst sleepAtMost = 5 * time.Minute\n\n\/\/ min validity in the future for the reservations when checking their compliance,\n\/\/ the bigger the value, the more probable it is not to break continuity.\n\/\/ Typically this value would be twice the max. sleep period, to ensure no index would\n\/\/ expire while the keeper is sleeping.\nconst minDuration = 2 * sleepAtMost\n\n\/\/ min validity of new indices\/reservations. The bigger the value, the longer a single index\n\/\/ can be used. Too big a value could produce errors in the admission for some ASes.\n\/\/ This value would typically be equal to twice minDuration.\nconst newIndexMinDuration = 2 * minDuration\n\n\/\/ ServiceFacilitator defines a minimal interface that has to be implemented to be\n\/\/ usable by the keeper.\ntype ServiceFacilitator interface {\n\tPathsTo(ctx context.Context, dst addr.IA) ([]snet.Path, error)\n\tSetupRequest(ctx context.Context, req *segment.SetupReq) error\n\tActivateRequest(\n\t\tcontext.Context,\n\t\t*base.Request,\n\t\tbase.PathSteps,\n\t\t*colpath.ColibriPathMinimal,\n\t\tbool,\n\t) error\n\tGetReservationsAtSource(ctx context.Context) ([]*segment.Reservation, error)\n\tDeleteExpiredIndices(ctx context.Context) error\n}\n\n\/\/ keeper looks after the reservations configured in reservations.json\n\/\/ It starts by cleaning up those reservations that have expired.\n\/\/ The keeper tries to match existing reservations with configured entries.\n\/\/ If no match is found, a new reservation will be created.\ntype keeper struct {\n\tnow        func() time.Time\n\tlocalIA    addr.IA\n\tsleepUntil time.Time \/\/ nothing to do in the keeper until this time\n\tprovider   ServiceFacilitator\n\tentries    []*entry\n}\n\ntype entry struct {\n\tconf *configuration\n\trsv  *segment.Reservation\n}\n\n\/\/ PrepareSetupRequest creates a valid setup request with the steps always in the direction of\n\/\/ the traffic of the SegR, and the transport path always in the direction of the next\n\/\/ colibri service (thus for down-path SegRs the transport will be in the reverse wrt the steps).\nfunc (e *entry) PrepareSetupRequest(now, expTime time.Time, localAS addr.AS,\n\tp snet.Path) *segment.SetupReq {\n\n\tsteps, err := base.StepsFromSnet(p)\n\tif err != nil {\n\t\tlog.Info(\"error in SCION path, cannot convert to steps\", \"err\", err, \"path\", p)\n\t\tpanic(err)\n\t}\n\tcurrentStep := 0\n\n\t\/\/ if the SegR is of down-path type, reverse the steps\n\tif e.conf.pathType == reservation.DownPath {\n\t\tsteps = steps.Reverse()\n\t\tcurrentStep = len(steps) - 1\n\t}\n\n\tid, _ := reservation.NewID(localAS, make([]byte, reservation.IDSuffixSegLen))\n\treturn &segment.SetupReq{\n\t\tRequest:        *base.NewRequest(now, id, 0, len(steps)),\n\t\tExpirationTime: expTime,\n\t\tPathType:       e.conf.pathType,\n\t\tMinBW:          e.conf.minBW,\n\t\tMaxBW:          e.conf.maxBW,\n\t\tSplitCls:       e.conf.splitCls,\n\t\tPathProps:      e.conf.endProps,\n\t\tAllocTrail:     reservation.AllocationBeads{},\n\t\tSteps:          steps,\n\t\tCurrentStep:    currentStep,\n\t\tTransportPath:  nil, \/\/ new setups are not transported in colibri paths\n\t}\n}\n\nfunc (e *entry) PrepareRenewalRequest(now, expTime time.Time) *segment.SetupReq {\n\treturn &segment.SetupReq{\n\t\tRequest: *base.NewRequest(\n\t\t\tnow, &e.rsv.ID, e.rsv.NextIndexToRenew(), len(e.rsv.Steps)),\n\t\tExpirationTime: expTime,\n\t\tPathType:       e.conf.pathType,\n\t\tMinBW:          e.conf.minBW,\n\t\tMaxBW:          e.conf.maxBW,\n\t\tSplitCls:       e.rsv.TrafficSplit,\n\t\tPathProps:      e.rsv.PathEndProps,\n\t\tAllocTrail:     reservation.AllocationBeads{},\n\t\tSteps:          e.rsv.Steps.Copy(),\n\t\tCurrentStep:    e.rsv.CurrentStep,\n\t\tTransportPath:  e.rsv.TransportPath,\n\t\tReservation:    e.rsv,\n\t}\n}\n\nfunc NewKeeper(\n\tctx context.Context,\n\tprovider ServiceFacilitator,\n\tconf *conf.Reservations,\n\tlocalIA addr.IA,\n) (*keeper, error) {\n\n\t\/\/ load configuration\n\treqs, err := parseInitial(conf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ cleanup expired indices before reading reservations\n\tif err := provider.DeleteExpiredIndices(ctx); err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ get existing reservations\n\trsvs, err := provider.GetReservationsAtSource(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tentries := matchRsvsWithConfiguration(rsvs, reqs)\n\n\tlog.Debug(\"colibri keeper\", \"reservations\", len(entries))\n\treturn &keeper{\n\t\tnow:        time.Now,\n\t\tlocalIA:    localIA,\n\t\tsleepUntil: time.Now().Add(-time.Nanosecond),\n\t\tprovider:   provider,\n\t\tentries:    entries,\n\t}, nil\n}\n\n\/\/ OneShot keeps all reservations healthy. Those that need renewal are renewed, those\n\/\/ that still have no reservation ID for its config will request a new one.\n\/\/ The function returns the time when it should be called next.\nfunc (k *keeper) OneShot(ctx context.Context) (time.Time, error) {\n\twg := sync.WaitGroup{}\n\ttimes := make([]time.Time, len(k.entries))\n\terrs := make(serrors.List, len(k.entries))\n\twg.Add(len(k.entries))\n\tfor i, e := range k.entries {\n\t\ti, e := i, e\n\t\tgo func() {\n\t\t\tdefer log.HandlePanic()\n\t\t\tdefer wg.Done()\n\t\t\ttimes[i], errs[i] = k.keepReservation(ctx, e)\n\t\t}()\n\t}\n\twg.Wait()\n\tif err := errs.Coalesce(); err != nil {\n\t\treturn k.now().Add(sleepAtLeast), err\n\t}\n\t\/\/ wakeupAtLatest is the maximum to wake up the keeper\n\twakeupAtLatest := k.now().Add(sleepAtMost)\n\tfor _, t := range times {\n\t\tif t.Before(wakeupAtLatest) {\n\t\t\twakeupAtLatest = t\n\t\t}\n\t}\n\t\/\/ but the keeper must sleep at least a minimum amount of time\n\tif wakeupAtLatest.Sub(k.now()) < sleepAtLeast {\n\t\twakeupAtLatest = k.now().Add(sleepAtLeast)\n\t}\n\treturn wakeupAtLatest, nil\n}\n\n\/\/ keepReservation will ensure that the reservation exists or a request is created.\nfunc (k *keeper) keepReservation(ctx context.Context, e *entry) (time.Time, error) {\n\tnow := k.now()\n\tvar err error\n\tif e.rsv == nil {\n\t\te.rsv, err = k.askNewReservation(ctx, e)\n\t\tif err != nil {\n\t\t\treturn time.Time{}, err\n\t\t}\n\t}\n\n\tswitch compliance(e, k.now().Add(minDuration)) {\n\tcase Compliant:\n\tcase NeedsIndices:\n\t\terr = k.askNewIndices(ctx, e)\n\tcase NeedsActivation:\n\t\terr = k.activateIndex(ctx, e)\n\t}\n\n\tif err != nil {\n\t\treturn time.Time{}, err\n\t}\n\treturn now.Add(newIndexMinDuration), nil\n}\n\n\/\/ matchRsvsWithConfiguration matches existing reservations with configuration.\n\/\/ It returns the appropriate entries to manage from the keeper.\n\/\/ Those entries without a reservation ID must obtain a new reservation;\n\/\/ those with a reservation ID will need index activation, etc.\nfunc matchRsvsWithConfiguration(rsvs []*segment.Reservation, conf []*configuration) []*entry {\n\tconf = append(conf[:0:0], conf...)\n\t\/\/ greedy strategy: for each reservation try to match it with the first compatible configuration\n\tentries := make([]*entry, 0)\n\tfor _, r := range rsvs {\n\t\ti := findCompatibleConfiguration(r, conf)\n\t\tif i < 0 {\n\t\t\tcontinue\n\t\t}\n\t\tentries = append(entries, &entry{\n\t\t\tconf: conf[i],\n\t\t\trsv:  r,\n\t\t})\n\t\t\/\/ one conf. is matched against this r; remove that entry from the pool\n\t\tconf = append(conf[:i], conf[i+1:]...)\n\t}\n\tfor _, c := range conf {\n\t\tentries = append(entries, &entry{\n\t\t\tconf: c,\n\t\t})\n\t}\n\treturn entries\n}\n\n\/\/ findCompatibleConfiguration finds the first compatible configuration with the reservation.\n\/\/ It returns the index of the configuration in the slice, or -1 if no valid one is found.\nfunc findCompatibleConfiguration(r *segment.Reservation, conf []*configuration) int {\n\tfor i, c := range conf {\n\t\tswitch {\n\t\tcase r.Steps.DstIA() != c.dst:\n\t\t\tcontinue\n\t\tcase r.PathType != c.pathType:\n\t\t\tcontinue\n\t\tcase r.TrafficSplit != c.splitCls:\n\t\t\tcontinue\n\t\tcase r.PathEndProps != c.endProps:\n\t\t\tcontinue\n\t\tcase !c.predicate.EvalInterfaces(r.Steps.Interfaces()):\n\t\t\tcontinue\n\t\t}\n\t\treturn i\n\t}\n\treturn -1\n}\n\nfunc (k *keeper) activateIndex(ctx context.Context, e *entry) error {\n\treq := base.NewRequest(k.now(), &e.rsv.ID, e.rsv.NextIndexToActivate().Idx,\n\t\tlen(e.rsv.Steps))\n\tinReverse := e.rsv.PathType == reservation.DownPath\n\terr := k.provider.ActivateRequest(ctx, req, e.rsv.Steps.Copy(), e.rsv.TransportPath, inReverse)\n\tif err == nil {\n\t\terr = e.rsv.SetIndexActive(req.Index)\n\t}\n\treturn err\n}\n\n\/\/ askNewIndices requests a renewal\nfunc (k *keeper) askNewIndices(ctx context.Context, e *entry) error {\n\tnow := k.now()\n\treq := e.PrepareRenewalRequest(now, now.Add(newIndexMinDuration))\n\terr := k.provider.SetupRequest(ctx, req)\n\tif err != nil {\n\t\treturn err\n\t}\n\t\/\/ otherwise the entry reservation is not updated with the new indices\n\t\/\/ TODO(JordiSubira): Check whether we are missing else from the updated reservation\n\t\/\/ after confirming indices.\n\te.rsv.Indices = req.Reservation.Indices\n\treturn nil\n}\n\nfunc (k *keeper) askNewReservation(ctx context.Context, e *entry) (*segment.Reservation, error) {\n\tnow := k.now()\n\tpaths, err := k.provider.PathsTo(ctx, e.conf.dst)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ try with each possible path\n\tpaths = e.conf.predicate.Eval(paths)\n\tfor _, p := range paths {\n\t\treq := e.PrepareSetupRequest(now, now.Add(newIndexMinDuration), k.localIA.AS(), p)\n\t\terr := k.provider.SetupRequest(ctx, req)\n\t\tif err == nil {\n\t\t\tif req.Reservation == nil {\n\t\t\t\tpanic(\"logic error, reservation after new request is empty\")\n\t\t\t}\n\t\t}\n\t\tif req.Reservation != nil {\n\t\t\treturn req.Reservation, err\n\t\t}\n\t\tlog.Info(\"error creating new reservation from best effort path\", \"path\", p, \"err\", err)\n\t}\n\treturn nil, serrors.New(\"no more best effort paths to create reservation\", \"dst\", e.conf.dst)\n}\n\n\/\/ configuration is a 1 to 1 association to a conf.ReservationEntry\ntype configuration struct {\n\tdst       addr.IA\n\tpathType  reservation.PathType\n\tpredicate *pathpol.Sequence\n\tminBW     reservation.BWCls\n\tmaxBW     reservation.BWCls\n\tsplitCls  reservation.SplitCls\n\tendProps  reservation.PathEndProps\n}\n\ntype Compliance int\n\nconst (\n\tNeedsIndices    = Compliance(iota) \/\/ ask for a new index\n\tNeedsActivation                    \/\/ ask to activate index\n\tCompliant                          \/\/ already has an active compliant index\n)\n\nfunc (c Compliance) String() string {\n\tswitch c {\n\tcase NeedsIndices:\n\t\treturn \"NeedsIndices\"\n\tcase NeedsActivation:\n\t\treturn \"NeedsActivation\"\n\tcase Compliant:\n\t\treturn \"Compliant\"\n\tdefault:\n\t\tpanic(fmt.Errorf(\"unknown value for compliance %d\", c))\n\t}\n}\n\n\/\/ compliance finds the status of the reservation in regard with the configuration.\n\/\/ It returns Compliant if it contains active indices compatible with the configuration,\n\/\/ NeedsActivation if the compatible index(es) exist but need to be activated, or\n\/\/ NeedsIndices if no compatible index exists.\n\/\/ The function expects a non-nil reservation.\nfunc compliance(e *entry, until time.Time) Compliance {\n\tidxs := e.rsv.Indices.Filter(\n\t\tsegment.ByMinBW(e.conf.minBW),\n\t\tsegment.ByMaxBW(e.conf.maxBW),\n\t\tsegment.NotConfirmed(),\n\t\tsegment.ByExpiration(until),\n\t)\n\tswitch {\n\tcase len(idxs) == 0:\n\t\treturn NeedsIndices\n\tcase len(idxs.Filter(segment.NotSwitchableFrom(e.rsv.ActiveIndex()))) == 0:\n\t\treturn NeedsActivation\n\tdefault:\n\t\treturn Compliant\n\t}\n}\n\nfunc parseInitial(conf *conf.Reservations) ([]*configuration, error) {\n\tif conf == nil {\n\t\tlog.Info(\"COLIBRI not keeping any reservations\")\n\t\treturn nil, nil\n\t}\n\tlog.Info(\"COLIBRI will keep reservations\", \"count\", len(conf.Rsvs))\n\tinitial := make([]*configuration, len(conf.Rsvs))\n\tfor i, r := range conf.Rsvs {\n\t\tseq, err := pathpol.NewSequence(r.PathPredicate)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif r.MinSize > r.MaxSize {\n\t\t\treturn nil, serrors.New(\"min bw must be less or equal than max bw\",\n\t\t\t\t\"min_bw\", r.MinSize, \"max_bw\", r.MaxSize)\n\t\t}\n\n\t\tinitial[i] = &configuration{\n\t\t\tdst:       r.DstAS,\n\t\t\tpathType:  r.PathType,\n\t\t\tpredicate: seq,\n\t\t\tminBW:     r.MinSize,\n\t\t\tmaxBW:     r.MaxSize,\n\t\t\tsplitCls:  r.SplitCls,\n\t\t\tendProps:  reservation.PathEndProps(r.EndProps),\n\t\t}\n\t}\n\treturn initial, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package secio\n\nimport (\n\t\"crypto\/cipher\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\n\t\"crypto\/hmac\"\n\n\tcontext \"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/code.google.com\/p\/go.net\/context\"\n\tproto \"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/code.google.com\/p\/goprotobuf\/proto\"\n\tmsgio \"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/github.com\/jbenet\/go-msgio\"\n\tmpool \"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/github.com\/jbenet\/go-msgio\/mpool\"\n)\n\n\/\/ ErrMACInvalid signals that a MAC verification failed\nvar ErrMACInvalid = errors.New(\"MAC verification failed\")\n\n\/\/ bufPool is a ByteSlicePool for messages. we need buffers because (sadly)\n\/\/ we cannot encrypt in place-- the user needs their buffer back.\nvar bufPool = mpool.ByteSlicePool\n\ntype etmWriter struct {\n\t\/\/ params\n\tpool mpool.Pool        \/\/ for the buffers with encrypted data\n\tmsg  msgio.WriteCloser \/\/ msgio for knowing where boundaries lie\n\tstr  cipher.Stream     \/\/ the stream cipher to encrypt with\n\tmac  HMAC              \/\/ the mac to authenticate data with\n}\n\n\/\/ NewETMWriter Encrypt-Then-MAC\nfunc NewETMWriter(w io.Writer, s cipher.Stream, mac HMAC) msgio.WriteCloser {\n\treturn &etmWriter{msg: msgio.NewWriter(w), str: s, mac: mac, pool: bufPool}\n}\n\n\/\/ Write writes passed in buffer as a single message.\nfunc (w *etmWriter) Write(b []byte) (int, error) {\n\tif err := w.WriteMsg(b); err != nil {\n\t\treturn 0, err\n\t}\n\treturn len(b), nil\n}\n\n\/\/ WriteMsg writes the msg in the passed in buffer.\nfunc (w *etmWriter) WriteMsg(b []byte) error {\n\n\t\/\/ encrypt.\n\tdata := w.pool.Get(uint32(len(b))).([]byte)\n\tdata = data[:len(b)] \/\/ the pool's buffer may be larger\n\tw.str.XORKeyStream(data, b)\n\n\t\/\/ log.Debugf(\"ENC plaintext (%d): %s %v\", len(b), b, b)\n\t\/\/ log.Debugf(\"ENC ciphertext (%d): %s %v\", len(data), data, data)\n\n\t\/\/ then, mac.\n\tif _, err := w.mac.Write(data); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Sum appends.\n\tdata = w.mac.Sum(data)\n\tw.mac.Reset()\n\t\/\/ it's sad to append here. our buffers are -- hopefully -- coming from\n\t\/\/ a shared buffer pool, so the append may not actually cause allocation\n\t\/\/ one can only hope. i guess we'll see.\n\n\treturn w.msg.WriteMsg(data)\n}\n\nfunc (w *etmWriter) Close() error {\n\treturn w.msg.Close()\n}\n\ntype etmReader struct {\n\tmsgio.Reader\n\tio.Closer\n\n\t\/\/ params\n\tmsg msgio.ReadCloser \/\/ msgio for knowing where boundaries lie\n\tstr cipher.Stream    \/\/ the stream cipher to encrypt with\n\tmac HMAC             \/\/ the mac to authenticate data with\n}\n\n\/\/ NewETMReader Encrypt-Then-MAC\nfunc NewETMReader(r io.Reader, s cipher.Stream, mac HMAC) msgio.ReadCloser {\n\treturn &etmReader{msg: msgio.NewReader(r), str: s, mac: mac}\n}\n\nfunc (r *etmReader) NextMsgLen() (int, error) {\n\treturn r.msg.NextMsgLen()\n}\n\nfunc (r *etmReader) Read(buf []byte) (int, error) {\n\t\/\/ first, check the buffer has enough space.\n\tfullLen, err := r.msg.NextMsgLen()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tdataLen := fullLen - r.mac.size\n\tif cap(buf) < dataLen {\n\t\treturn 0, io.ErrShortBuffer\n\t}\n\n\tbuf2 := buf\n\tchanged := false\n\tif cap(buf) < fullLen {\n\t\tbuf2 = make([]byte, fullLen)\n\t\tchanged = true\n\t}\n\tbuf2 = buf2[:fullLen]\n\n\tn, err := io.ReadFull(r.msg, buf2)\n\tif err != nil {\n\t\treturn n, err\n\t}\n\n\tm, err := r.macCheckThenDecrypt(buf2)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tbuf2 = buf2[:m]\n\tif changed {\n\t\treturn copy(buf, buf2), nil\n\t}\n\treturn m, nil\n}\n\nfunc (r *etmReader) ReadMsg() ([]byte, error) {\n\tmsg, err := r.msg.ReadMsg()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tn, err := r.macCheckThenDecrypt(msg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn msg[:n], nil\n}\n\nfunc (r *etmReader) macCheckThenDecrypt(m []byte) (int, error) {\n\tl := len(m)\n\tif l < r.mac.size {\n\t\treturn 0, fmt.Errorf(\"buffer (%d) shorter than MAC size (%d)\", l, r.mac.size)\n\t}\n\n\tmark := l - r.mac.size\n\tdata := m[:mark]\n\tmacd := m[mark:]\n\n\tr.mac.Write(data)\n\texpected := r.mac.Sum(nil)\n\tr.mac.Reset()\n\n\t\/\/ check mac. if failed, return error.\n\tif !hmac.Equal(macd, expected) {\n\t\tlog.Error(\"MAC Invalid:\", expected, \"!=\", macd)\n\t\treturn 0, ErrMACInvalid\n\t}\n\n\t\/\/ ok seems good. decrypt. (can decrypt in place, yay!)\n\t\/\/ log.Debugf(\"DEC ciphertext (%d): %s %v\", len(data), data, data)\n\tr.str.XORKeyStream(data, data)\n\t\/\/ log.Debugf(\"DEC plaintext (%d): %s %v\", len(data), data, data)\n\n\treturn mark, nil\n}\n\nfunc (w *etmReader) Close() error {\n\treturn w.msg.Close()\n}\n\n\/\/ ReleaseMsg signals a buffer can be reused.\nfunc (r *etmReader) ReleaseMsg(b []byte) {\n\tr.msg.ReleaseMsg(b)\n}\n\n\/\/ writeMsgCtx is used by the\nfunc writeMsgCtx(ctx context.Context, w msgio.Writer, msg proto.Message) ([]byte, error) {\n\tenc, err := proto.Marshal(msg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ write in a goroutine so we can exit when our context is cancelled.\n\tdone := make(chan error)\n\tgo func(m []byte) {\n\t\terr := w.WriteMsg(m)\n\t\tdone <- err\n\t}(enc)\n\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn nil, ctx.Err()\n\tcase e := <-done:\n\t\treturn enc, e\n\t}\n}\n\nfunc readMsgCtx(ctx context.Context, r msgio.Reader, p proto.Message) ([]byte, error) {\n\tvar msg []byte\n\n\t\/\/ read in a goroutine so we can exit when our context is cancelled.\n\tdone := make(chan error)\n\tgo func() {\n\t\tvar err error\n\t\tmsg, err = r.ReadMsg()\n\t\tdone <- err\n\t}()\n\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn nil, ctx.Err()\n\tcase e := <-done:\n\t\tif e != nil {\n\t\t\treturn nil, e\n\t\t}\n\t}\n\n\treturn msg, proto.Unmarshal(msg, p)\n}\n<commit_msg>secio: buffer remainders in calls to Read()<commit_after>package secio\n\nimport (\n\t\"crypto\/cipher\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\n\t\"crypto\/hmac\"\n\n\tcontext \"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/code.google.com\/p\/go.net\/context\"\n\tproto \"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/code.google.com\/p\/goprotobuf\/proto\"\n\tmsgio \"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/github.com\/jbenet\/go-msgio\"\n\tmpool \"github.com\/jbenet\/go-ipfs\/Godeps\/_workspace\/src\/github.com\/jbenet\/go-msgio\/mpool\"\n)\n\n\/\/ ErrMACInvalid signals that a MAC verification failed\nvar ErrMACInvalid = errors.New(\"MAC verification failed\")\n\n\/\/ bufPool is a ByteSlicePool for messages. we need buffers because (sadly)\n\/\/ we cannot encrypt in place-- the user needs their buffer back.\nvar bufPool = mpool.ByteSlicePool\n\ntype etmWriter struct {\n\t\/\/ params\n\tpool mpool.Pool        \/\/ for the buffers with encrypted data\n\tmsg  msgio.WriteCloser \/\/ msgio for knowing where boundaries lie\n\tstr  cipher.Stream     \/\/ the stream cipher to encrypt with\n\tmac  HMAC              \/\/ the mac to authenticate data with\n}\n\n\/\/ NewETMWriter Encrypt-Then-MAC\nfunc NewETMWriter(w io.Writer, s cipher.Stream, mac HMAC) msgio.WriteCloser {\n\treturn &etmWriter{msg: msgio.NewWriter(w), str: s, mac: mac, pool: bufPool}\n}\n\n\/\/ Write writes passed in buffer as a single message.\nfunc (w *etmWriter) Write(b []byte) (int, error) {\n\tif err := w.WriteMsg(b); err != nil {\n\t\treturn 0, err\n\t}\n\treturn len(b), nil\n}\n\n\/\/ WriteMsg writes the msg in the passed in buffer.\nfunc (w *etmWriter) WriteMsg(b []byte) error {\n\n\t\/\/ encrypt.\n\tdata := w.pool.Get(uint32(len(b))).([]byte)\n\tdata = data[:len(b)] \/\/ the pool's buffer may be larger\n\tw.str.XORKeyStream(data, b)\n\n\t\/\/ log.Debugf(\"ENC plaintext (%d): %s %v\", len(b), b, b)\n\t\/\/ log.Debugf(\"ENC ciphertext (%d): %s %v\", len(data), data, data)\n\n\t\/\/ then, mac.\n\tif _, err := w.mac.Write(data); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Sum appends.\n\tdata = w.mac.Sum(data)\n\tw.mac.Reset()\n\t\/\/ it's sad to append here. our buffers are -- hopefully -- coming from\n\t\/\/ a shared buffer pool, so the append may not actually cause allocation\n\t\/\/ one can only hope. i guess we'll see.\n\n\treturn w.msg.WriteMsg(data)\n}\n\nfunc (w *etmWriter) Close() error {\n\treturn w.msg.Close()\n}\n\ntype etmReader struct {\n\tmsgio.Reader\n\tio.Closer\n\n\t\/\/ buffer\n\tbuf []byte\n\n\t\/\/ params\n\tmsg msgio.ReadCloser \/\/ msgio for knowing where boundaries lie\n\tstr cipher.Stream    \/\/ the stream cipher to encrypt with\n\tmac HMAC             \/\/ the mac to authenticate data with\n}\n\n\/\/ NewETMReader Encrypt-Then-MAC\nfunc NewETMReader(r io.Reader, s cipher.Stream, mac HMAC) msgio.ReadCloser {\n\treturn &etmReader{msg: msgio.NewReader(r), str: s, mac: mac}\n}\n\nfunc (r *etmReader) NextMsgLen() (int, error) {\n\treturn r.msg.NextMsgLen()\n}\n\nfunc (r *etmReader) drainBuf(buf []byte) int {\n\tif r.buf == nil {\n\t\treturn 0\n\t}\n\n\tn := copy(buf, r.buf)\n\tr.buf = r.buf[n:]\n\treturn n\n}\n\nfunc (r *etmReader) Read(buf []byte) (int, error) {\n\t\/\/ first, check if we have anything in the buffer\n\tcopied := r.drainBuf(buf)\n\tbuf = buf[copied:]\n\tif copied > 0 {\n\t\treturn copied, nil\n\t\t\/\/ return here to avoid complicating the rest...\n\t\t\/\/ user can call io.ReadFull.\n\t}\n\n\t\/\/ check the buffer has enough space for the next msg\n\tfullLen, err := r.msg.NextMsgLen()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tbuf2 := buf\n\tchanged := false\n\t\/\/ if not enough space, allocate a new buffer.\n\tif cap(buf) < fullLen {\n\t\tbuf2 = make([]byte, fullLen)\n\t\tchanged = true\n\t}\n\tbuf2 = buf2[:fullLen]\n\n\tn, err := io.ReadFull(r.msg, buf2)\n\tif err != nil {\n\t\treturn n, err\n\t}\n\n\tm, err := r.macCheckThenDecrypt(buf2)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tbuf2 = buf2[:m]\n\tif !changed {\n\t\treturn m, nil\n\t}\n\n\tn = copy(buf, buf2)\n\tif len(buf2) > len(buf) {\n\t\tr.buf = buf2[len(buf):] \/\/ had some left over? save it.\n\t}\n\treturn n, nil\n}\n\nfunc (r *etmReader) ReadMsg() ([]byte, error) {\n\tmsg, err := r.msg.ReadMsg()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tn, err := r.macCheckThenDecrypt(msg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn msg[:n], nil\n}\n\nfunc (r *etmReader) macCheckThenDecrypt(m []byte) (int, error) {\n\tl := len(m)\n\tif l < r.mac.size {\n\t\treturn 0, fmt.Errorf(\"buffer (%d) shorter than MAC size (%d)\", l, r.mac.size)\n\t}\n\n\tmark := l - r.mac.size\n\tdata := m[:mark]\n\tmacd := m[mark:]\n\n\tr.mac.Write(data)\n\texpected := r.mac.Sum(nil)\n\tr.mac.Reset()\n\n\t\/\/ check mac. if failed, return error.\n\tif !hmac.Equal(macd, expected) {\n\t\tlog.Error(\"MAC Invalid:\", expected, \"!=\", macd)\n\t\treturn 0, ErrMACInvalid\n\t}\n\n\t\/\/ ok seems good. decrypt. (can decrypt in place, yay!)\n\t\/\/ log.Debugf(\"DEC ciphertext (%d): %s %v\", len(data), data, data)\n\tr.str.XORKeyStream(data, data)\n\t\/\/ log.Debugf(\"DEC plaintext (%d): %s %v\", len(data), data, data)\n\n\treturn mark, nil\n}\n\nfunc (w *etmReader) Close() error {\n\treturn w.msg.Close()\n}\n\n\/\/ ReleaseMsg signals a buffer can be reused.\nfunc (r *etmReader) ReleaseMsg(b []byte) {\n\tr.msg.ReleaseMsg(b)\n}\n\n\/\/ writeMsgCtx is used by the\nfunc writeMsgCtx(ctx context.Context, w msgio.Writer, msg proto.Message) ([]byte, error) {\n\tenc, err := proto.Marshal(msg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ write in a goroutine so we can exit when our context is cancelled.\n\tdone := make(chan error)\n\tgo func(m []byte) {\n\t\terr := w.WriteMsg(m)\n\t\tdone <- err\n\t}(enc)\n\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn nil, ctx.Err()\n\tcase e := <-done:\n\t\treturn enc, e\n\t}\n}\n\nfunc readMsgCtx(ctx context.Context, r msgio.Reader, p proto.Message) ([]byte, error) {\n\tvar msg []byte\n\n\t\/\/ read in a goroutine so we can exit when our context is cancelled.\n\tdone := make(chan error)\n\tgo func() {\n\t\tvar err error\n\t\tmsg, err = r.ReadMsg()\n\t\tdone <- err\n\t}()\n\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn nil, ctx.Err()\n\tcase e := <-done:\n\t\tif e != nil {\n\t\t\treturn nil, e\n\t\t}\n\t}\n\n\treturn msg, proto.Unmarshal(msg, p)\n}\n<|endoftext|>"}
{"text":"<commit_before>package susigo\n\nimport (\n\t\"crypto\/tls\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"log\"\n\t\"net\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"time\"\n)\n\ntype Callback func(*Event)\n\ntype Susi struct {\n\tcert             tls.Certificate\n\taddr             string\n\tconnected        bool\n\tconn             net.Conn\n\tencoder          *json.Encoder\n\tdecoder          *json.Decoder\n\tcallbacks        map[string]Callback\n\tconsumers        map[string]map[int64]Callback\n\tprocessors       map[string]map[int64]Callback\n\tpublishProcesses map[string][]Callback\n}\n\ntype Event struct {\n\tTopic     string              `json:\"topic\"`\n\tPayload   interface{}         `json:\"payload\"`\n\tHeaders   []map[string]string `json:\"headers\"`\n\tID        string              `json:\"id\"`\n\tSessionID string              `json:\"sessionid\"`\n}\n\ntype Message struct {\n\tType string `json:\"type\"`\n\tData *Event `json:\"data\"`\n}\n\nfunc NewSusi(addr, certFile, keyFile string) (*Susi, error) {\n\tsusi := new(Susi)\n\tcert, err := tls.LoadX509KeyPair(certFile, keyFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsusi.cert = cert\n\tsusi.callbacks = make(map[string]Callback)\n\tsusi.addr = addr\n\tsusi.consumers = make(map[string]map[int64]Callback)\n\tsusi.processors = make(map[string]map[int64]Callback)\n\tsusi.publishProcesses = make(map[string][]Callback)\n\tsusi.connected = false\n\tgo susi.backend()\n\treturn susi, nil\n}\n\nfunc (susi *Susi) Publish(event Event, callback Callback) error {\n\tif !susi.connected {\n\t\treturn errors.New(\"susi not connected\")\n\t}\n\tvar id = event.ID\n\tif event.ID == \"\" {\n\t\tid = strconv.FormatInt(time.Now().UnixNano(), 10)\n\t\tevent.ID = id\n\t}\n\tevent.ID = id\n\tpacket := map[string]interface{}{\n\t\t\"type\": \"publish\",\n\t\t\"data\": event,\n\t}\n\tsusi.callbacks[id] = callback\n\treturn susi.encoder.Encode(packet)\n}\n\nfunc (susi *Susi) RegisterConsumer(topic string, callback Callback) (int64, error) {\n\tif susi.consumers[topic] == nil {\n\t\tsusi.consumers[topic] = make(map[int64]Callback)\n\t}\n\tconsumers := susi.consumers[topic]\n\tid := time.Now().UnixNano()\n\tconsumers[id] = callback\n\tif len(consumers) == 1 {\n\t\tpacket := map[string]interface{}{\n\t\t\t\"type\": \"registerConsumer\",\n\t\t\t\"data\": map[string]interface{}{\n\t\t\t\t\"topic\": topic,\n\t\t\t},\n\t\t}\n\t\tif susi.connected {\n\t\t\treturn id, susi.encoder.Encode(packet)\n\t\t}\n\t\treturn id, nil\n\t}\n\treturn -1, nil\n}\n\nfunc (susi *Susi) RegisterProcessor(topic string, callback Callback) (int64, error) {\n\tif susi.processors[topic] == nil {\n\t\tsusi.processors[topic] = make(map[int64]Callback)\n\t}\n\tprocessors := susi.processors[topic]\n\tid := time.Now().UnixNano()\n\tprocessors[id] = callback\n\tif len(processors) == 1 {\n\t\tpacket := map[string]interface{}{\n\t\t\t\"type\": \"registerProcessor\",\n\t\t\t\"data\": map[string]interface{}{\n\t\t\t\t\"topic\": topic,\n\t\t\t},\n\t\t}\n\t\tif susi.connected {\n\t\t\treturn id, susi.encoder.Encode(packet)\n\t\t}\n\t\treturn id, nil\n\t}\n\treturn -1, nil\n}\n\nfunc (susi *Susi) UnregisterConsumer(id int64) error {\n\tfor _, consumers := range susi.consumers {\n\t\tif topic, ok := consumers[id]; ok {\n\t\t\tdelete(consumers, id)\n\t\t\tif len(consumers) == 0 {\n\t\t\t\tpacket := map[string]interface{}{\n\t\t\t\t\t\"type\": \"unregisterConsumer\",\n\t\t\t\t\t\"data\": map[string]interface{}{\n\t\t\t\t\t\t\"topic\": topic,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tif susi.connected {\n\t\t\t\t\treturn susi.encoder.Encode(packet)\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn errors.New(\"no such consumer\")\n}\n\nfunc (susi *Susi) UnregisterProcessor(id int64) error {\n\tfor _, processors := range susi.processors {\n\t\tif topic, ok := processors[id]; ok {\n\t\t\tdelete(processors, id)\n\t\t\tif len(processors) == 0 {\n\t\t\t\tpacket := map[string]interface{}{\n\t\t\t\t\t\"type\": \"unregisterProcessor\",\n\t\t\t\t\t\"data\": map[string]interface{}{\n\t\t\t\t\t\t\"topic\": topic,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tif susi.connected {\n\t\t\t\t\treturn susi.encoder.Encode(packet)\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn errors.New(\"no such processor\")\n}\n\nfunc (susi *Susi) connect() error {\n\tconn, err := tls.Dial(\"tcp\", susi.addr, &tls.Config{\n\t\tCertificates:       []tls.Certificate{susi.cert},\n\t\tInsecureSkipVerify: true,\n\t})\n\tif err != nil {\n\t\tlog.Printf(\"failed connecting susi-core (%v), retry...\", err)\n\t\treturn err\n\t}\n\tsusi.conn = conn\n\tsusi.connected = true\n\tsusi.encoder = json.NewEncoder(susi.conn)\n\tsusi.decoder = json.NewDecoder(susi.conn)\n\tfor consumerTopic := range susi.consumers {\n\t\tpacket := map[string]interface{}{\n\t\t\t\"type\": \"registerConsumer\",\n\t\t\t\"data\": map[string]interface{}{\n\t\t\t\t\"topic\": consumerTopic,\n\t\t\t},\n\t\t}\n\t\tsusi.encoder.Encode(packet)\n\t}\n\tfor processorTopic := range susi.processors {\n\t\tpacket := map[string]interface{}{\n\t\t\t\"type\": \"registerConsumer\",\n\t\t\t\"data\": map[string]interface{}{\n\t\t\t\t\"topic\": processorTopic,\n\t\t\t},\n\t\t}\n\t\tsusi.encoder.Encode(packet)\n\t}\n\treturn nil\n}\n\nfunc (susi *Susi) backend() {\n\tpacket := Message{}\n\tfor {\n\t\tif !susi.connected {\n\t\t\terr := susi.connect()\n\t\t\tif err != nil {\n\t\t\t\ttime.Sleep(1 * time.Second)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\terr := susi.decoder.Decode(&packet)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error reading from susi json decoder: \", err)\n\t\t\tsusi.connected = false\n\t\t\tcontinue\n\t\t}\n\t\tswitch packet.Type {\n\t\tcase \"ack\":\n\t\t\t{\n\t\t\t\tevent := packet.Data\n\t\t\t\tid := event.ID\n\t\t\t\tcallback := susi.callbacks[id]\n\t\t\t\tcallback(event)\n\t\t\t\tdelete(susi.callbacks, id)\n\t\t\t}\n\t\tcase \"consumerEvent\":\n\t\t\t{\n\t\t\t\tevent := packet.Data\n\t\t\t\ttopic := event.Topic\n\t\t\t\tvar matchingConsumers []Callback\n\t\t\t\tfor pattern, consumers := range susi.consumers {\n\t\t\t\t\tif matched, err := regexp.MatchString(pattern, topic); err == nil && matched {\n\t\t\t\t\t\tfor _, consumer := range consumers {\n\t\t\t\t\t\t\tmatchingConsumers = append(matchingConsumers, consumer)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor _, consumer := range matchingConsumers {\n\t\t\t\t\tconsumer(event)\n\t\t\t\t}\n\t\t\t}\n\t\tcase \"processorEvent\":\n\t\t\t{\n\t\t\t\tevent := packet.Data\n\t\t\t\ttopic := event.Topic\n\t\t\t\tvar matchingProcessors []Callback\n\t\t\t\tfor pattern, processors := range susi.processors {\n\t\t\t\t\tif matched, err := regexp.MatchString(pattern, topic); err == nil && matched {\n\t\t\t\t\t\tfor _, processor := range processors {\n\t\t\t\t\t\t\tmatchingProcessors = append(matchingProcessors, processor)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tsusi.publishProcesses[event.ID] = matchingProcessors\n\t\t\t\tsusi.Ack(event)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (susi *Susi) Ack(event *Event) error {\n\tif process, ok := susi.publishProcesses[event.ID]; ok {\n\t\tif len(process) == 0 {\n\t\t\tpacket := map[string]interface{}{\n\t\t\t\t\"type\": \"ack\",\n\t\t\t\t\"data\": event,\n\t\t\t}\n\t\t\tdelete(susi.publishProcesses, event.ID)\n\t\t\tif susi.connected {\n\t\t\t\treturn susi.encoder.Encode(packet)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t\tcb := process[0]\n\t\tprocess = process[1:]\n\t\tcb(event)\n\t\treturn nil\n\t}\n\treturn errors.New(\"no publish process found\")\n}\n\nfunc (susi *Susi) Dismiss(event *Event) error {\n\tif _, ok := susi.publishProcesses[event.ID]; ok {\n\t\tpacket := map[string]interface{}{\n\t\t\t\"type\": \"dismiss\",\n\t\t\t\"data\": event,\n\t\t}\n\t\tdelete(susi.publishProcesses, event.ID)\n\t\tif susi.connected {\n\t\t\treturn susi.encoder.Encode(packet)\n\t\t}\n\t\treturn nil\n\t}\n\treturn errors.New(\"no publish process found\")\n}\n<commit_msg>fixed wrong reregister message type;<commit_after>package susigo\n\nimport (\n\t\"crypto\/tls\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"log\"\n\t\"net\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"time\"\n)\n\ntype Callback func(*Event)\n\ntype Susi struct {\n\tcert             tls.Certificate\n\taddr             string\n\tconnected        bool\n\tconn             net.Conn\n\tencoder          *json.Encoder\n\tdecoder          *json.Decoder\n\tcallbacks        map[string]Callback\n\tconsumers        map[string]map[int64]Callback\n\tprocessors       map[string]map[int64]Callback\n\tpublishProcesses map[string][]Callback\n}\n\ntype Event struct {\n\tTopic     string              `json:\"topic\"`\n\tPayload   interface{}         `json:\"payload\"`\n\tHeaders   []map[string]string `json:\"headers\"`\n\tID        string              `json:\"id\"`\n\tSessionID string              `json:\"sessionid\"`\n}\n\ntype Message struct {\n\tType string `json:\"type\"`\n\tData *Event `json:\"data\"`\n}\n\nfunc NewSusi(addr, certFile, keyFile string) (*Susi, error) {\n\tsusi := new(Susi)\n\tcert, err := tls.LoadX509KeyPair(certFile, keyFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsusi.cert = cert\n\tsusi.callbacks = make(map[string]Callback)\n\tsusi.addr = addr\n\tsusi.consumers = make(map[string]map[int64]Callback)\n\tsusi.processors = make(map[string]map[int64]Callback)\n\tsusi.publishProcesses = make(map[string][]Callback)\n\tsusi.connected = false\n\tgo susi.backend()\n\treturn susi, nil\n}\n\nfunc (susi *Susi) Publish(event Event, callback Callback) error {\n\tif !susi.connected {\n\t\treturn errors.New(\"susi not connected\")\n\t}\n\tvar id = event.ID\n\tif event.ID == \"\" {\n\t\tid = strconv.FormatInt(time.Now().UnixNano(), 10)\n\t\tevent.ID = id\n\t}\n\tevent.ID = id\n\tpacket := map[string]interface{}{\n\t\t\"type\": \"publish\",\n\t\t\"data\": event,\n\t}\n\tsusi.callbacks[id] = callback\n\treturn susi.encoder.Encode(packet)\n}\n\nfunc (susi *Susi) RegisterConsumer(topic string, callback Callback) (int64, error) {\n\tif susi.consumers[topic] == nil {\n\t\tsusi.consumers[topic] = make(map[int64]Callback)\n\t}\n\tconsumers := susi.consumers[topic]\n\tid := time.Now().UnixNano()\n\tconsumers[id] = callback\n\tif len(consumers) == 1 {\n\t\tpacket := map[string]interface{}{\n\t\t\t\"type\": \"registerConsumer\",\n\t\t\t\"data\": map[string]interface{}{\n\t\t\t\t\"topic\": topic,\n\t\t\t},\n\t\t}\n\t\tif susi.connected {\n\t\t\treturn id, susi.encoder.Encode(packet)\n\t\t}\n\t\treturn id, nil\n\t}\n\treturn -1, nil\n}\n\nfunc (susi *Susi) RegisterProcessor(topic string, callback Callback) (int64, error) {\n\tif susi.processors[topic] == nil {\n\t\tsusi.processors[topic] = make(map[int64]Callback)\n\t}\n\tprocessors := susi.processors[topic]\n\tid := time.Now().UnixNano()\n\tprocessors[id] = callback\n\tif len(processors) == 1 {\n\t\tpacket := map[string]interface{}{\n\t\t\t\"type\": \"registerProcessor\",\n\t\t\t\"data\": map[string]interface{}{\n\t\t\t\t\"topic\": topic,\n\t\t\t},\n\t\t}\n\t\tif susi.connected {\n\t\t\treturn id, susi.encoder.Encode(packet)\n\t\t}\n\t\treturn id, nil\n\t}\n\treturn -1, nil\n}\n\nfunc (susi *Susi) UnregisterConsumer(id int64) error {\n\tfor _, consumers := range susi.consumers {\n\t\tif topic, ok := consumers[id]; ok {\n\t\t\tdelete(consumers, id)\n\t\t\tif len(consumers) == 0 {\n\t\t\t\tpacket := map[string]interface{}{\n\t\t\t\t\t\"type\": \"unregisterConsumer\",\n\t\t\t\t\t\"data\": map[string]interface{}{\n\t\t\t\t\t\t\"topic\": topic,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tif susi.connected {\n\t\t\t\t\treturn susi.encoder.Encode(packet)\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn errors.New(\"no such consumer\")\n}\n\nfunc (susi *Susi) UnregisterProcessor(id int64) error {\n\tfor _, processors := range susi.processors {\n\t\tif topic, ok := processors[id]; ok {\n\t\t\tdelete(processors, id)\n\t\t\tif len(processors) == 0 {\n\t\t\t\tpacket := map[string]interface{}{\n\t\t\t\t\t\"type\": \"unregisterProcessor\",\n\t\t\t\t\t\"data\": map[string]interface{}{\n\t\t\t\t\t\t\"topic\": topic,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tif susi.connected {\n\t\t\t\t\treturn susi.encoder.Encode(packet)\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn errors.New(\"no such processor\")\n}\n\nfunc (susi *Susi) connect() error {\n\tconn, err := tls.Dial(\"tcp\", susi.addr, &tls.Config{\n\t\tCertificates:       []tls.Certificate{susi.cert},\n\t\tInsecureSkipVerify: true,\n\t})\n\tif err != nil {\n\t\tlog.Printf(\"failed connecting susi-core (%v), retry...\", err)\n\t\treturn err\n\t}\n\tsusi.conn = conn\n\tsusi.connected = true\n\tsusi.encoder = json.NewEncoder(susi.conn)\n\tsusi.decoder = json.NewDecoder(susi.conn)\n\tfor consumerTopic := range susi.consumers {\n\t\tpacket := map[string]interface{}{\n\t\t\t\"type\": \"registerConsumer\",\n\t\t\t\"data\": map[string]interface{}{\n\t\t\t\t\"topic\": consumerTopic,\n\t\t\t},\n\t\t}\n\t\tsusi.encoder.Encode(packet)\n\t}\n\tfor processorTopic := range susi.processors {\n\t\tpacket := map[string]interface{}{\n\t\t\t\"type\": \"registerProcessor\",\n\t\t\t\"data\": map[string]interface{}{\n\t\t\t\t\"topic\": processorTopic,\n\t\t\t},\n\t\t}\n\t\tsusi.encoder.Encode(packet)\n\t}\n\treturn nil\n}\n\nfunc (susi *Susi) backend() {\n\tpacket := Message{}\n\tfor {\n\t\tif !susi.connected {\n\t\t\terr := susi.connect()\n\t\t\tif err != nil {\n\t\t\t\ttime.Sleep(1 * time.Second)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\terr := susi.decoder.Decode(&packet)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error reading from susi json decoder: \", err)\n\t\t\tsusi.connected = false\n\t\t\tcontinue\n\t\t}\n\t\tswitch packet.Type {\n\t\tcase \"ack\":\n\t\t\t{\n\t\t\t\tevent := packet.Data\n\t\t\t\tid := event.ID\n\t\t\t\tcallback := susi.callbacks[id]\n\t\t\t\tcallback(event)\n\t\t\t\tdelete(susi.callbacks, id)\n\t\t\t}\n\t\tcase \"consumerEvent\":\n\t\t\t{\n\t\t\t\tevent := packet.Data\n\t\t\t\ttopic := event.Topic\n\t\t\t\tvar matchingConsumers []Callback\n\t\t\t\tfor pattern, consumers := range susi.consumers {\n\t\t\t\t\tif matched, err := regexp.MatchString(pattern, topic); err == nil && matched {\n\t\t\t\t\t\tfor _, consumer := range consumers {\n\t\t\t\t\t\t\tmatchingConsumers = append(matchingConsumers, consumer)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor _, consumer := range matchingConsumers {\n\t\t\t\t\tconsumer(event)\n\t\t\t\t}\n\t\t\t}\n\t\tcase \"processorEvent\":\n\t\t\t{\n\t\t\t\tevent := packet.Data\n\t\t\t\ttopic := event.Topic\n\t\t\t\tvar matchingProcessors []Callback\n\t\t\t\tfor pattern, processors := range susi.processors {\n\t\t\t\t\tif matched, err := regexp.MatchString(pattern, topic); err == nil && matched {\n\t\t\t\t\t\tfor _, processor := range processors {\n\t\t\t\t\t\t\tmatchingProcessors = append(matchingProcessors, processor)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tsusi.publishProcesses[event.ID] = matchingProcessors\n\t\t\t\tsusi.Ack(event)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (susi *Susi) Ack(event *Event) error {\n\tif process, ok := susi.publishProcesses[event.ID]; ok {\n\t\tif len(process) == 0 {\n\t\t\tpacket := map[string]interface{}{\n\t\t\t\t\"type\": \"ack\",\n\t\t\t\t\"data\": event,\n\t\t\t}\n\t\t\tdelete(susi.publishProcesses, event.ID)\n\t\t\tif susi.connected {\n\t\t\t\treturn susi.encoder.Encode(packet)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t\tcb := process[0]\n\t\tprocess = process[1:]\n\t\tcb(event)\n\t\treturn nil\n\t}\n\treturn errors.New(\"no publish process found\")\n}\n\nfunc (susi *Susi) Dismiss(event *Event) error {\n\tif _, ok := susi.publishProcesses[event.ID]; ok {\n\t\tpacket := map[string]interface{}{\n\t\t\t\"type\": \"dismiss\",\n\t\t\t\"data\": event,\n\t\t}\n\t\tdelete(susi.publishProcesses, event.ID)\n\t\tif susi.connected {\n\t\t\treturn susi.encoder.Encode(packet)\n\t\t}\n\t\treturn nil\n\t}\n\treturn errors.New(\"no publish process found\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package server\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net\"\n\t\"strings\"\n\n\tcnitypes \"github.com\/containernetworking\/cni\/pkg\/types\"\n\tcnicurrent \"github.com\/containernetworking\/cni\/pkg\/types\/current\"\n\t\"github.com\/cri-o\/cri-o\/internal\/lib\/sandbox\"\n\t\"github.com\/cri-o\/cri-o\/internal\/pkg\/log\"\n\t\"k8s.io\/kubernetes\/pkg\/kubelet\/dockershim\/network\/hostport\"\n)\n\n\/\/ networkStart sets up the sandbox's network and returns the pod IP on success\n\/\/ or an error\nfunc (s *Server) networkStart(ctx context.Context, sb *sandbox.Sandbox) (podIPs []string, result cnitypes.Result, err error) {\n\tif sb.HostNetwork() {\n\t\treturn nil, nil, nil\n\t}\n\n\tpodNetwork, err := s.newPodNetwork(sb)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Ensure network resources are cleaned up if the plugin succeeded\n\t\/\/ but an error happened between plugin success and the end of networkStart()\n\tdefer func() {\n\t\tif err != nil {\n\t\t\ts.networkStop(ctx, sb)\n\t\t}\n\t}()\n\n\t_, err = s.netPlugin.SetUpPod(podNetwork)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"failed to create pod network sandbox %s(%s): %v\", sb.Name(), sb.ID(), err)\n\t\treturn\n\t}\n\n\ttmp, err := s.netPlugin.GetPodNetworkStatus(podNetwork)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"failed to get network status for pod sandbox %s(%s): %v\", sb.Name(), sb.ID(), err)\n\t\treturn\n\t}\n\n\t\/\/ only one cnitypes.Result is returned since newPodNetwork sets Networks list empty\n\tresult = tmp[0]\n\tlog.Debugf(ctx, \"CNI setup result: %v\", result)\n\n\tnetwork, err := cnicurrent.GetResult(result)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"failed to get network JSON for pod sandbox %s(%s): %v\", sb.Name(), sb.ID(), err)\n\t\treturn\n\t}\n\n\tfor idx, podIPConfig := range network.IPs {\n\t\tpodIP := strings.Split(podIPConfig.Address.String(), \"\/\")[0]\n\n\t\t\/\/ Apply the hostport mappings only for the first IP to avoid allocating\n\t\t\/\/ the same host port twice\n\t\tif idx == 0 && len(sb.PortMappings()) > 0 {\n\t\t\tip := net.ParseIP(podIP)\n\t\t\tif ip == nil {\n\t\t\t\terr = fmt.Errorf(\"failed to get valid ip address for sandbox %s(%s)\", sb.Name(), sb.ID())\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\terr = s.hostportManager.Add(sb.ID(), &hostport.PodPortMapping{\n\t\t\t\tName:         sb.Name(),\n\t\t\t\tPortMappings: sb.PortMappings(),\n\t\t\t\tIP:           ip,\n\t\t\t\tHostNetwork:  false,\n\t\t\t}, \"lo\")\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"failed to add hostport mapping for sandbox %s(%s): %v\", sb.Name(), sb.ID(), err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tpodIPs = append(podIPs, podIP)\n\t}\n\n\tlog.Debugf(ctx, \"found POD IPs: %v\", podIPs)\n\treturn podIPs, result, err\n}\n\n\/\/ getSandboxIP retrieves the IP address for the sandbox\nfunc (s *Server) getSandboxIPs(sb *sandbox.Sandbox) (podIPs []string, err error) {\n\tif sb.HostNetwork() {\n\t\treturn nil, nil\n\t}\n\n\tpodNetwork, err := s.newPodNetwork(sb)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult, err := s.netPlugin.GetPodNetworkStatus(podNetwork)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get network status for pod sandbox %s(%s): %v\", sb.Name(), sb.ID(), err)\n\t}\n\n\tres, err := cnicurrent.GetResult(result[0])\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get network JSON for pod sandbox %s(%s): %v\", sb.Name(), sb.ID(), err)\n\t}\n\n\tfor _, podIPConfig := range res.IPs {\n\t\tpodIPs = append(podIPs, strings.Split(podIPConfig.Address.String(), \"\/\")[0])\n\t}\n\n\treturn podIPs, nil\n}\n\n\/\/ networkStop cleans up and removes a pod's network.  It is best-effort and\n\/\/ must call the network plugin even if the network namespace is already gone\nfunc (s *Server) networkStop(ctx context.Context, sb *sandbox.Sandbox) {\n\tif sb.HostNetwork() {\n\t\treturn\n\t}\n\n\tif err := s.hostportManager.Remove(sb.ID(), &hostport.PodPortMapping{\n\t\tName:         sb.Name(),\n\t\tPortMappings: sb.PortMappings(),\n\t\tHostNetwork:  false,\n\t}); err != nil {\n\t\tlog.Warnf(ctx, \"failed to remove hostport for pod sandbox %s(%s): %v\",\n\t\t\tsb.Name(), sb.ID(), err)\n\t}\n\n\tpodNetwork, err := s.newPodNetwork(sb)\n\tif err != nil {\n\t\tlog.Warnf(ctx, err.Error())\n\t\treturn\n\t}\n\tif err := s.netPlugin.TearDownPod(podNetwork); err != nil {\n\t\tlog.Warnf(ctx, \"failed to destroy network for pod sandbox %s(%s): %v\",\n\t\t\tsb.Name(), sb.ID(), err)\n\t}\n}\n<commit_msg>Add network setup metrics<commit_after>package server\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net\"\n\t\"strings\"\n\t\"time\"\n\n\tcnitypes \"github.com\/containernetworking\/cni\/pkg\/types\"\n\tcnicurrent \"github.com\/containernetworking\/cni\/pkg\/types\/current\"\n\t\"github.com\/cri-o\/cri-o\/internal\/lib\/sandbox\"\n\t\"github.com\/cri-o\/cri-o\/internal\/pkg\/log\"\n\t\"github.com\/cri-o\/cri-o\/server\/metrics\"\n\t\"k8s.io\/kubernetes\/pkg\/kubelet\/dockershim\/network\/hostport\"\n)\n\n\/\/ networkStart sets up the sandbox's network and returns the pod IP on success\n\/\/ or an error\nfunc (s *Server) networkStart(ctx context.Context, sb *sandbox.Sandbox) (podIPs []string, result cnitypes.Result, err error) {\n\toverallStart := time.Now()\n\n\tif sb.HostNetwork() {\n\t\treturn nil, nil, nil\n\t}\n\n\tpodNetwork, err := s.newPodNetwork(sb)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Ensure network resources are cleaned up if the plugin succeeded\n\t\/\/ but an error happened between plugin success and the end of networkStart()\n\tdefer func() {\n\t\tif err != nil {\n\t\t\ts.networkStop(ctx, sb)\n\t\t}\n\t}()\n\n\tpodSetUpStart := time.Now()\n\t_, err = s.netPlugin.SetUpPod(podNetwork)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"failed to create pod network sandbox %s(%s): %v\", sb.Name(), sb.ID(), err)\n\t\treturn\n\t}\n\t\/\/ metric about the CNI network setup operation\n\tmetrics.CRIOOperationsLatency.WithLabelValues(\"network_setup_pod\").\n\t\tObserve(metrics.SinceInMicroseconds(podSetUpStart))\n\n\ttmp, err := s.netPlugin.GetPodNetworkStatus(podNetwork)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"failed to get network status for pod sandbox %s(%s): %v\", sb.Name(), sb.ID(), err)\n\t\treturn\n\t}\n\n\t\/\/ only one cnitypes.Result is returned since newPodNetwork sets Networks list empty\n\tresult = tmp[0]\n\tlog.Debugf(ctx, \"CNI setup result: %v\", result)\n\n\tnetwork, err := cnicurrent.GetResult(result)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"failed to get network JSON for pod sandbox %s(%s): %v\", sb.Name(), sb.ID(), err)\n\t\treturn\n\t}\n\n\tfor idx, podIPConfig := range network.IPs {\n\t\tpodIP := strings.Split(podIPConfig.Address.String(), \"\/\")[0]\n\n\t\t\/\/ Apply the hostport mappings only for the first IP to avoid allocating\n\t\t\/\/ the same host port twice\n\t\tif idx == 0 && len(sb.PortMappings()) > 0 {\n\t\t\tip := net.ParseIP(podIP)\n\t\t\tif ip == nil {\n\t\t\t\terr = fmt.Errorf(\"failed to get valid ip address for sandbox %s(%s)\", sb.Name(), sb.ID())\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\terr = s.hostportManager.Add(sb.ID(), &hostport.PodPortMapping{\n\t\t\t\tName:         sb.Name(),\n\t\t\t\tPortMappings: sb.PortMappings(),\n\t\t\t\tIP:           ip,\n\t\t\t\tHostNetwork:  false,\n\t\t\t}, \"lo\")\n\t\t\tif err != nil {\n\t\t\t\terr = fmt.Errorf(\"failed to add hostport mapping for sandbox %s(%s): %v\", sb.Name(), sb.ID(), err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tpodIPs = append(podIPs, podIP)\n\t}\n\n\tlog.Debugf(ctx, \"found POD IPs: %v\", podIPs)\n\n\t\/\/ metric about the whole network setup operation\n\tmetrics.CRIOOperationsLatency.WithLabelValues(\"network_setup_overall\").\n\t\tObserve(metrics.SinceInMicroseconds(overallStart))\n\treturn podIPs, result, err\n}\n\n\/\/ getSandboxIP retrieves the IP address for the sandbox\nfunc (s *Server) getSandboxIPs(sb *sandbox.Sandbox) (podIPs []string, err error) {\n\tif sb.HostNetwork() {\n\t\treturn nil, nil\n\t}\n\n\tpodNetwork, err := s.newPodNetwork(sb)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult, err := s.netPlugin.GetPodNetworkStatus(podNetwork)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get network status for pod sandbox %s(%s): %v\", sb.Name(), sb.ID(), err)\n\t}\n\n\tres, err := cnicurrent.GetResult(result[0])\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get network JSON for pod sandbox %s(%s): %v\", sb.Name(), sb.ID(), err)\n\t}\n\n\tfor _, podIPConfig := range res.IPs {\n\t\tpodIPs = append(podIPs, strings.Split(podIPConfig.Address.String(), \"\/\")[0])\n\t}\n\n\treturn podIPs, nil\n}\n\n\/\/ networkStop cleans up and removes a pod's network.  It is best-effort and\n\/\/ must call the network plugin even if the network namespace is already gone\nfunc (s *Server) networkStop(ctx context.Context, sb *sandbox.Sandbox) {\n\tif sb.HostNetwork() {\n\t\treturn\n\t}\n\n\tif err := s.hostportManager.Remove(sb.ID(), &hostport.PodPortMapping{\n\t\tName:         sb.Name(),\n\t\tPortMappings: sb.PortMappings(),\n\t\tHostNetwork:  false,\n\t}); err != nil {\n\t\tlog.Warnf(ctx, \"failed to remove hostport for pod sandbox %s(%s): %v\",\n\t\t\tsb.Name(), sb.ID(), err)\n\t}\n\n\tpodNetwork, err := s.newPodNetwork(sb)\n\tif err != nil {\n\t\tlog.Warnf(ctx, err.Error())\n\t\treturn\n\t}\n\tif err := s.netPlugin.TearDownPod(podNetwork); err != nil {\n\t\tlog.Warnf(ctx, \"failed to destroy network for pod sandbox %s(%s): %v\",\n\t\t\tsb.Name(), sb.ID(), err)\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package pongo2\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\ntype Expression struct {\n\texpr1    IEvaluator\n\texpr2    IEvaluator\n\top_token *Token\n}\n\ntype relationalExpression struct {\n\texpr1    IEvaluator\n\texpr2    IEvaluator\n\top_token *Token\n}\n\ntype simpleExpression struct {\n\tlocation_token *Token\n\tnegate         bool\n\tnegative_sign  bool\n\tterm1          IEvaluator\n\tterm2          IEvaluator\n\top_token       *Token\n}\n\ntype term struct {\n\tfactor1  IEvaluator\n\tfactor2  IEvaluator\n\top_token *Token\n}\n\ntype power struct {\n\tpower1 IEvaluator\n\tpower2 IEvaluator\n}\n\nfunc (expr *Expression) Execute(ctx *ExecutionContext) (string, error) {\n\tvalue, err := expr.Evaluate(ctx)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn value.String(), nil\n}\n\nfunc (expr *Expression) Evaluate(ctx *ExecutionContext) (*Value, error) {\n\tv1, err := expr.expr1.Evaluate(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif expr.expr2 != nil {\n\t\tv2, err := expr.expr2.Evaluate(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tswitch expr.op_token.Val {\n\t\tcase \"and\", \"&&\":\n\t\t\treturn AsValue(v1.IsTrue() && v2.IsTrue()), nil\n\t\tcase \"or\", \"||\":\n\t\t\treturn AsValue(v1.IsTrue() || v2.IsTrue()), nil\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"unimplemented: %s\", expr.op_token.Val))\n\t\t}\n\t} else {\n\t\treturn v1, nil\n\t}\n}\n\nfunc (expr *relationalExpression) Evaluate(ctx *ExecutionContext) (*Value, error) {\n\tv1, err := expr.expr1.Evaluate(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif expr.expr2 != nil {\n\t\tv2, err := expr.expr2.Evaluate(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tswitch expr.op_token.Val {\n\t\tcase \"<=\":\n\t\t\tif v1.IsFloat() || v2.IsFloat() {\n\t\t\t\t\/\/ Result will be a float\n\t\t\t\treturn AsValue(v1.Float() <= v2.Float()), nil\n\t\t\t} else {\n\t\t\t\t\/\/ Result will be an integer\n\t\t\t\treturn AsValue(v1.Integer() <= v2.Integer()), nil\n\t\t\t}\n\t\tcase \">=\":\n\t\t\tif v1.IsFloat() || v2.IsFloat() {\n\t\t\t\t\/\/ Result will be a float\n\t\t\t\treturn AsValue(v1.Float() >= v2.Float()), nil\n\t\t\t} else {\n\t\t\t\t\/\/ Result will be an integer\n\t\t\t\treturn AsValue(v1.Integer() >= v2.Integer()), nil\n\t\t\t}\n\t\tcase \"==\":\n\t\t\treturn AsValue(v1.EqualValueTo(v2)), nil\n\t\tcase \">\":\n\t\t\tif v1.IsFloat() || v2.IsFloat() {\n\t\t\t\t\/\/ Result will be a float\n\t\t\t\treturn AsValue(v1.Float() > v2.Float()), nil\n\t\t\t} else {\n\t\t\t\t\/\/ Result will be an integer\n\t\t\t\treturn AsValue(v1.Integer() > v2.Integer()), nil\n\t\t\t}\n\t\tcase \"<\":\n\t\t\tif v1.IsFloat() || v2.IsFloat() {\n\t\t\t\t\/\/ Result will be a float\n\t\t\t\treturn AsValue(v1.Float() < v2.Float()), nil\n\t\t\t} else {\n\t\t\t\t\/\/ Result will be an integer\n\t\t\t\treturn AsValue(v1.Integer() < v2.Integer()), nil\n\t\t\t}\n\t\tcase \"!=\", \"<>\":\n\t\t\treturn AsValue(!v1.EqualValueTo(v2)), nil\n\t\tcase \"in\":\n\t\t\treturn AsValue(v2.Contains(v1)), nil\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"unimplemented: %s\", expr.op_token.Val))\n\t\t}\n\t} else {\n\t\treturn v1, nil\n\t}\n}\n\nfunc (expr *simpleExpression) Evaluate(ctx *ExecutionContext) (*Value, error) {\n\tt1, err := expr.term1.Evaluate(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult := t1\n\n\tif expr.negate {\n\t\tresult = result.Negate()\n\t}\n\n\tif expr.negative_sign {\n\t\tif result.IsNumber() {\n\t\t\tswitch {\n\t\t\tcase result.IsFloat():\n\t\t\t\tresult = AsValue(-1 * result.Float())\n\t\t\tcase result.IsInteger():\n\t\t\t\tresult = AsValue(-1 * result.Integer())\n\t\t\tdefault:\n\t\t\t\tpanic(\"not possible\")\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil, ctx.Error(\"Negative sign on a non-number expression\", expr.location_token)\n\t\t}\n\t}\n\n\tif expr.term2 != nil {\n\t\tt2, err := expr.term2.Evaluate(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tswitch expr.op_token.Val {\n\t\tcase \"+\":\n\t\t\tif result.IsFloat() || t2.IsFloat() {\n\t\t\t\t\/\/ Result will be a float\n\t\t\t\treturn AsValue(result.Float() + t2.Float()), nil\n\t\t\t} else {\n\t\t\t\t\/\/ Result will be an integer\n\t\t\t\treturn AsValue(result.Integer() + t2.Integer()), nil\n\t\t\t}\n\t\tcase \"-\":\n\t\t\tif result.IsFloat() || t2.IsFloat() {\n\t\t\t\t\/\/ Result will be a float\n\t\t\t\treturn AsValue(result.Float() - t2.Float()), nil\n\t\t\t} else {\n\t\t\t\t\/\/ Result will be an integer\n\t\t\t\treturn AsValue(result.Integer() - t2.Integer()), nil\n\t\t\t}\n\t\tdefault:\n\t\t\tpanic(\"unimplemented\")\n\t\t}\n\t}\n\n\treturn result, nil\n}\n\nfunc (t *term) Evaluate(ctx *ExecutionContext) (*Value, error) {\n\tf1, err := t.factor1.Evaluate(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif t.factor2 != nil {\n\t\tf2, err := t.factor2.Evaluate(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tswitch t.op_token.Val {\n\t\tcase \"*\":\n\t\t\treturn AsValue(f1.Integer() * f2.Integer()), nil\n\t\tcase \"\/\":\n\t\t\tpanic(\"unimplemented\")\n\t\tdefault:\n\t\t\tpanic(\"unimplemented\")\n\t\t}\n\t} else {\n\t\treturn f1, nil\n\t}\n}\n\nfunc (pw *power) Evaluate(ctx *ExecutionContext) (*Value, error) {\n\tp1, err := pw.power1.Evaluate(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif pw.power2 != nil {\n\t\tp2, err := pw.power2.Evaluate(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn AsValue(math.Pow(p1.Float(), p2.Float())), nil\n\t} else {\n\t\treturn p1, nil\n\t}\n}\n\nfunc (p *Parser) parseFactor() (IEvaluator, error) {\n\tif p.Match(TokenSymbol, \"(\") != nil {\n\t\texpr, err := p.ParseExpression()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif p.Match(TokenSymbol, \")\") == nil {\n\t\t\treturn nil, p.Error(\"Closing bracket expected after expression\", nil)\n\t\t}\n\t\treturn expr, nil\n\t}\n\n\treturn p.parseVariableOrLiteralWithFilter()\n}\n\nfunc (p *Parser) parseTerm() (IEvaluator, error) {\n\tterm := new(term)\n\n\tfactor1, err := p.parsePower()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tterm.factor1 = factor1\n\n\tif p.PeekOne(TokenSymbol, \"*\", \"\/\") != nil {\n\t\top := p.Current()\n\t\tp.Consume()\n\t\tfactor2, err := p.parseTerm()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tterm.factor2 = factor2\n\t\tterm.op_token = op\n\t}\n\n\treturn term, nil\n}\n\nfunc (p *Parser) parsePower() (IEvaluator, error) {\n\tpw := new(power)\n\n\tpower1, err := p.parseFactor()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpw.power1 = power1\n\n\tif p.Match(TokenSymbol, \"^\") != nil {\n\t\tpower2, err := p.parsePower()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpw.power2 = power2\n\t}\n\n\treturn pw, nil\n}\n\nfunc (p *Parser) parseSimpleExpression() (IEvaluator, error) {\n\texpr := new(simpleExpression)\n\texpr.location_token = p.Current()\n\n\tif sign := p.MatchOne(TokenSymbol, \"+\", \"-\"); sign != nil {\n\t\tif sign.Val == \"-\" {\n\t\t\texpr.negative_sign = true\n\t\t}\n\t}\n\n\tif p.Match(TokenSymbol, \"!\") != nil || p.Match(TokenKeyword, \"not\") != nil {\n\t\texpr.negate = true\n\t}\n\n\tterm1, err := p.parseTerm()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\texpr.term1 = term1\n\n\tif p.PeekOne(TokenSymbol, \"+\", \"-\") != nil {\n\t\top := p.Current()\n\t\tp.Consume()\n\t\tterm2, err := p.parseSimpleExpression()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\texpr.term2 = term2\n\t\texpr.op_token = op\n\t}\n\n\treturn expr, nil\n}\n\nfunc (p *Parser) parseRelationalExpression() (IEvaluator, error) {\n\texpr1, err := p.parseSimpleExpression()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\texpr := &relationalExpression{\n\t\texpr1: expr1,\n\t}\n\n\tif t := p.MatchOne(TokenSymbol, \"==\", \"<=\", \">=\", \"!=\", \"<>\", \">\", \"<\"); t != nil {\n\t\texpr2, err := p.parseRelationalExpression()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\texpr.op_token = t\n\t\texpr.expr2 = expr2\n\t} else if t := p.MatchOne(TokenKeyword, \"in\"); t != nil {\n\t\texpr2, err := p.parseSimpleExpression()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\texpr.op_token = t\n\t\texpr.expr2 = expr2\n\t}\n\n\treturn expr, nil\n}\n\nfunc (p *Parser) ParseExpression() (INodeEvaluator, error) {\n\trexpr1, err := p.parseRelationalExpression()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\texp := &Expression{\n\t\texpr1: rexpr1,\n\t}\n\n\tif p.PeekOne(TokenSymbol, \"&&\", \"||\") != nil || p.PeekOne(TokenKeyword, \"and\", \"or\") != nil {\n\t\top := p.Current()\n\t\tp.Consume()\n\t\texpr2, err := p.ParseExpression()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\texp.expr2 = expr2\n\t\texp.op_token = op\n\t}\n\n\treturn exp, nil\n}\n<commit_msg>Removed wrong comments.<commit_after>package pongo2\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\ntype Expression struct {\n\texpr1    IEvaluator\n\texpr2    IEvaluator\n\top_token *Token\n}\n\ntype relationalExpression struct {\n\texpr1    IEvaluator\n\texpr2    IEvaluator\n\top_token *Token\n}\n\ntype simpleExpression struct {\n\tlocation_token *Token\n\tnegate         bool\n\tnegative_sign  bool\n\tterm1          IEvaluator\n\tterm2          IEvaluator\n\top_token       *Token\n}\n\ntype term struct {\n\tfactor1  IEvaluator\n\tfactor2  IEvaluator\n\top_token *Token\n}\n\ntype power struct {\n\tpower1 IEvaluator\n\tpower2 IEvaluator\n}\n\nfunc (expr *Expression) Execute(ctx *ExecutionContext) (string, error) {\n\tvalue, err := expr.Evaluate(ctx)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn value.String(), nil\n}\n\nfunc (expr *Expression) Evaluate(ctx *ExecutionContext) (*Value, error) {\n\tv1, err := expr.expr1.Evaluate(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif expr.expr2 != nil {\n\t\tv2, err := expr.expr2.Evaluate(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tswitch expr.op_token.Val {\n\t\tcase \"and\", \"&&\":\n\t\t\treturn AsValue(v1.IsTrue() && v2.IsTrue()), nil\n\t\tcase \"or\", \"||\":\n\t\t\treturn AsValue(v1.IsTrue() || v2.IsTrue()), nil\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"unimplemented: %s\", expr.op_token.Val))\n\t\t}\n\t} else {\n\t\treturn v1, nil\n\t}\n}\n\nfunc (expr *relationalExpression) Evaluate(ctx *ExecutionContext) (*Value, error) {\n\tv1, err := expr.expr1.Evaluate(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif expr.expr2 != nil {\n\t\tv2, err := expr.expr2.Evaluate(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tswitch expr.op_token.Val {\n\t\tcase \"<=\":\n\t\t\tif v1.IsFloat() || v2.IsFloat() {\n\t\t\t\treturn AsValue(v1.Float() <= v2.Float()), nil\n\t\t\t} else {\n\t\t\t\treturn AsValue(v1.Integer() <= v2.Integer()), nil\n\t\t\t}\n\t\tcase \">=\":\n\t\t\tif v1.IsFloat() || v2.IsFloat() {\n\t\t\t\treturn AsValue(v1.Float() >= v2.Float()), nil\n\t\t\t} else {\n\t\t\t\treturn AsValue(v1.Integer() >= v2.Integer()), nil\n\t\t\t}\n\t\tcase \"==\":\n\t\t\treturn AsValue(v1.EqualValueTo(v2)), nil\n\t\tcase \">\":\n\t\t\tif v1.IsFloat() || v2.IsFloat() {\n\t\t\t\treturn AsValue(v1.Float() > v2.Float()), nil\n\t\t\t} else {\n\t\t\t\treturn AsValue(v1.Integer() > v2.Integer()), nil\n\t\t\t}\n\t\tcase \"<\":\n\t\t\tif v1.IsFloat() || v2.IsFloat() {\n\t\t\t\treturn AsValue(v1.Float() < v2.Float()), nil\n\t\t\t} else {\n\t\t\t\treturn AsValue(v1.Integer() < v2.Integer()), nil\n\t\t\t}\n\t\tcase \"!=\", \"<>\":\n\t\t\treturn AsValue(!v1.EqualValueTo(v2)), nil\n\t\tcase \"in\":\n\t\t\treturn AsValue(v2.Contains(v1)), nil\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"unimplemented: %s\", expr.op_token.Val))\n\t\t}\n\t} else {\n\t\treturn v1, nil\n\t}\n}\n\nfunc (expr *simpleExpression) Evaluate(ctx *ExecutionContext) (*Value, error) {\n\tt1, err := expr.term1.Evaluate(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresult := t1\n\n\tif expr.negate {\n\t\tresult = result.Negate()\n\t}\n\n\tif expr.negative_sign {\n\t\tif result.IsNumber() {\n\t\t\tswitch {\n\t\t\tcase result.IsFloat():\n\t\t\t\tresult = AsValue(-1 * result.Float())\n\t\t\tcase result.IsInteger():\n\t\t\t\tresult = AsValue(-1 * result.Integer())\n\t\t\tdefault:\n\t\t\t\tpanic(\"not possible\")\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil, ctx.Error(\"Negative sign on a non-number expression\", expr.location_token)\n\t\t}\n\t}\n\n\tif expr.term2 != nil {\n\t\tt2, err := expr.term2.Evaluate(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tswitch expr.op_token.Val {\n\t\tcase \"+\":\n\t\t\tif result.IsFloat() || t2.IsFloat() {\n\t\t\t\t\/\/ Result will be a float\n\t\t\t\treturn AsValue(result.Float() + t2.Float()), nil\n\t\t\t} else {\n\t\t\t\t\/\/ Result will be an integer\n\t\t\t\treturn AsValue(result.Integer() + t2.Integer()), nil\n\t\t\t}\n\t\tcase \"-\":\n\t\t\tif result.IsFloat() || t2.IsFloat() {\n\t\t\t\t\/\/ Result will be a float\n\t\t\t\treturn AsValue(result.Float() - t2.Float()), nil\n\t\t\t} else {\n\t\t\t\t\/\/ Result will be an integer\n\t\t\t\treturn AsValue(result.Integer() - t2.Integer()), nil\n\t\t\t}\n\t\tdefault:\n\t\t\tpanic(\"unimplemented\")\n\t\t}\n\t}\n\n\treturn result, nil\n}\n\nfunc (t *term) Evaluate(ctx *ExecutionContext) (*Value, error) {\n\tf1, err := t.factor1.Evaluate(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif t.factor2 != nil {\n\t\tf2, err := t.factor2.Evaluate(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tswitch t.op_token.Val {\n\t\tcase \"*\":\n\t\t\treturn AsValue(f1.Integer() * f2.Integer()), nil\n\t\tcase \"\/\":\n\t\t\tpanic(\"unimplemented\")\n\t\tdefault:\n\t\t\tpanic(\"unimplemented\")\n\t\t}\n\t} else {\n\t\treturn f1, nil\n\t}\n}\n\nfunc (pw *power) Evaluate(ctx *ExecutionContext) (*Value, error) {\n\tp1, err := pw.power1.Evaluate(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif pw.power2 != nil {\n\t\tp2, err := pw.power2.Evaluate(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn AsValue(math.Pow(p1.Float(), p2.Float())), nil\n\t} else {\n\t\treturn p1, nil\n\t}\n}\n\nfunc (p *Parser) parseFactor() (IEvaluator, error) {\n\tif p.Match(TokenSymbol, \"(\") != nil {\n\t\texpr, err := p.ParseExpression()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif p.Match(TokenSymbol, \")\") == nil {\n\t\t\treturn nil, p.Error(\"Closing bracket expected after expression\", nil)\n\t\t}\n\t\treturn expr, nil\n\t}\n\n\treturn p.parseVariableOrLiteralWithFilter()\n}\n\nfunc (p *Parser) parseTerm() (IEvaluator, error) {\n\tterm := new(term)\n\n\tfactor1, err := p.parsePower()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tterm.factor1 = factor1\n\n\tif p.PeekOne(TokenSymbol, \"*\", \"\/\") != nil {\n\t\top := p.Current()\n\t\tp.Consume()\n\t\tfactor2, err := p.parseTerm()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tterm.factor2 = factor2\n\t\tterm.op_token = op\n\t}\n\n\treturn term, nil\n}\n\nfunc (p *Parser) parsePower() (IEvaluator, error) {\n\tpw := new(power)\n\n\tpower1, err := p.parseFactor()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpw.power1 = power1\n\n\tif p.Match(TokenSymbol, \"^\") != nil {\n\t\tpower2, err := p.parsePower()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tpw.power2 = power2\n\t}\n\n\treturn pw, nil\n}\n\nfunc (p *Parser) parseSimpleExpression() (IEvaluator, error) {\n\texpr := new(simpleExpression)\n\texpr.location_token = p.Current()\n\n\tif sign := p.MatchOne(TokenSymbol, \"+\", \"-\"); sign != nil {\n\t\tif sign.Val == \"-\" {\n\t\t\texpr.negative_sign = true\n\t\t}\n\t}\n\n\tif p.Match(TokenSymbol, \"!\") != nil || p.Match(TokenKeyword, \"not\") != nil {\n\t\texpr.negate = true\n\t}\n\n\tterm1, err := p.parseTerm()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\texpr.term1 = term1\n\n\tif p.PeekOne(TokenSymbol, \"+\", \"-\") != nil {\n\t\top := p.Current()\n\t\tp.Consume()\n\t\tterm2, err := p.parseSimpleExpression()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\texpr.term2 = term2\n\t\texpr.op_token = op\n\t}\n\n\treturn expr, nil\n}\n\nfunc (p *Parser) parseRelationalExpression() (IEvaluator, error) {\n\texpr1, err := p.parseSimpleExpression()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\texpr := &relationalExpression{\n\t\texpr1: expr1,\n\t}\n\n\tif t := p.MatchOne(TokenSymbol, \"==\", \"<=\", \">=\", \"!=\", \"<>\", \">\", \"<\"); t != nil {\n\t\texpr2, err := p.parseRelationalExpression()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\texpr.op_token = t\n\t\texpr.expr2 = expr2\n\t} else if t := p.MatchOne(TokenKeyword, \"in\"); t != nil {\n\t\texpr2, err := p.parseSimpleExpression()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\texpr.op_token = t\n\t\texpr.expr2 = expr2\n\t}\n\n\treturn expr, nil\n}\n\nfunc (p *Parser) ParseExpression() (INodeEvaluator, error) {\n\trexpr1, err := p.parseRelationalExpression()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\texp := &Expression{\n\t\texpr1: rexpr1,\n\t}\n\n\tif p.PeekOne(TokenSymbol, \"&&\", \"||\") != nil || p.PeekOne(TokenKeyword, \"and\", \"or\") != nil {\n\t\top := p.Current()\n\t\tp.Consume()\n\t\texpr2, err := p.ParseExpression()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\texp.expr2 = expr2\n\t\texp.op_token = op\n\t}\n\n\treturn exp, nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package gcs\n\nimport (\n\t\"fmt\"\n\t\"github.com\/astaxie\/beego\/config\"\n\t\"golang.org\/x\/oauth2\"\n\t\"golang.org\/x\/oauth2\/google\"\n\tstorage \"google.golang.org\/api\/storage\/v1\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n)\n\nvar (\n\tjsonKeyFile string\n\tbucketName  string\n\tprojectID   string\n\tdriverType  string\n)\n\n\/*\n\/\/Should Open this const config to replace below one when use testgcs.go\nconst (\n\tjsonfile   = \".\/gcs\/key.json\"\n\tbucketName = \"dockyad-example-bucket\"\n\tprojectID  = \"dockyad-test\"\n)\n*\/\nfunc init() {\n\n\t\/\/Reading config file named conf\/runtime.conf for backend\n\tconf, err := config.NewConfig(\"ini\", \".\/runtime.conf\")\n\tif err != nil {\n\t\tlog.Fatalf(\"GCS reading conf\/runtime.conf err %v\", err)\n\t}\n\n\tdriverType = conf.String(\"backenddriver\")\n\tif driverType == \"\" {\n\t\tlog.Fatalf(\"GCS reading conf\/runtime.conf, get driverType is nil\")\n\t}\n\t\/\/Get config var for jsonKeyFile, bucketName, projectID, which should be used later in oauth and get obj\n\tif jsonKeyFile = conf.String(driverType + \"::jsonkeyfile\"); jsonKeyFile == \"\" {\n\t\tlog.Fatalf(\"GCS reading conf\/runtime.conf, GCS get jsonKeyFile err, is nil\")\n\t}\n\n\tif bucketName = conf.String(driverType + \"::bucketname\"); bucketName == \"\" {\n\t\tlog.Fatalf(\"GCS reading conf\/runtime.conf, GCS get bucketName err, is nil\")\n\t}\n\n\tif projectID := conf.String(driverType + \"::projectid\"); projectID == \"\" {\n\t\tlog.Fatalf(\"GCS reading conf\/runtime.conf, GCS get projectID err, is nil\")\n\t}\n}\n\nfunc Gcssave(file string) (url string, err error) {\n\n\t\/\/read json key(key.json) to do oauth according JWT\n\tdata, err := ioutil.ReadFile(jsonKeyFile)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tconf, err := google.JWTConfigFromJSON(data, \"https:\/\/www.googleapis.com\/auth\/devstorage.full_control\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/new storage service and token, we dont need context here\n\tclient := conf.Client(oauth2.NoContext)\n\tgcsToken, err := conf.TokenSource(oauth2.NoContext).Token()\n\tservice, err := storage.New(client)\n\tif err != nil {\n\t\tlog.Fatalf(\"GCS unable to create storage service: %v\", err)\n\t}\n\n\t\/\/ If the bucket already exists and the user has access,  don't try to create it.\n\tif _, err := service.Buckets.Get(bucketName).Do(); err != nil {\n\t\t\/\/ If bucket is not exist, Create a bucket.\n\t\tif _, err := service.Buckets.Insert(projectID, &storage.Bucket{Name: bucketName}).Do(); err != nil {\n\t\t\tlog.Fatalf(\"GCS failed creating bucket %s: %v\", bucketName, err)\n\t\t}\n\t}\n\n\t\/\/Split filename as a objectName\n\tvar objectName string\n\tfor _, objectName = range strings.Split(file, \"\/\") {\n\t}\n\tobject := &storage.Object{Name: objectName}\n\n\t\/\/ Insert an object into a bucket.\n\tfileDes, err := os.Open(file)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error opening %q: %v\", file, err)\n\t}\n\tobjs, err := service.Objects.Insert(bucketName, object).Media(fileDes).Do()\n\tif err != nil {\n\t\tlog.Fatalf(\"GCS Objects.Insert failed: %v\", err)\n\t}\n\tretUrl := objs.MediaLink + \"&access_token=\" + gcsToken.AccessToken\n\tfmt.Println(fmt.Sprintf(\"GCS tmpUrl=%s\", retUrl))\n\n\tif err != nil {\n\t\treturn \"\", err\n\t} else {\n\t\treturn retUrl, nil\n\t}\n}\n<commit_msg>Modify gcs.go to delete the not neccessary output.<commit_after>package gcs\n\nimport (\n\t\"fmt\"\n\t\"github.com\/astaxie\/beego\/config\"\n\t\"golang.org\/x\/oauth2\"\n\t\"golang.org\/x\/oauth2\/google\"\n\tstorage \"google.golang.org\/api\/storage\/v1\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n)\n\nvar (\n\tjsonKeyFile string\n\tbucketName  string\n\tprojectID   string\n\tdriverType  string\n)\n\n\/*\n\/\/Should Open this const config to replace below one when use testgcs.go\nconst (\n\tjsonfile   = \".\/gcs\/key.json\"\n\tbucketName = \"dockyad-example-bucket\"\n\tprojectID  = \"dockyad-test\"\n)\n*\/\nfunc init() {\n\n\t\/\/Reading config file named conf\/runtime.conf for backend\n\tconf, err := config.NewConfig(\"ini\", \".\/runtime.conf\")\n\tif err != nil {\n\t\tlog.Fatalf(\"GCS reading conf\/runtime.conf err %v\", err)\n\t}\n\n\tdriverType = conf.String(\"backenddriver\")\n\tif driverType == \"\" {\n\t\tlog.Fatalf(\"GCS reading conf\/runtime.conf, get driverType is nil\")\n\t}\n\t\/\/Get config var for jsonKeyFile, bucketName, projectID, which should be used later in oauth and get obj\n\tif jsonKeyFile = conf.String(driverType + \"::jsonkeyfile\"); jsonKeyFile == \"\" {\n\t\tlog.Fatalf(\"GCS reading conf\/runtime.conf, GCS get jsonKeyFile err, is nil\")\n\t}\n\n\tif bucketName = conf.String(driverType + \"::bucketname\"); bucketName == \"\" {\n\t\tlog.Fatalf(\"GCS reading conf\/runtime.conf, GCS get bucketName err, is nil\")\n\t}\n\n\tif projectID := conf.String(driverType + \"::projectid\"); projectID == \"\" {\n\t\tlog.Fatalf(\"GCS reading conf\/runtime.conf, GCS get projectID err, is nil\")\n\t}\n}\n\nfunc Gcssave(file string) (url string, err error) {\n\n\t\/\/read json key(key.json) to do oauth according JWT\n\tdata, err := ioutil.ReadFile(jsonKeyFile)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tconf, err := google.JWTConfigFromJSON(data, \"https:\/\/www.googleapis.com\/auth\/devstorage.full_control\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/new storage service and token, we dont need context here\n\tclient := conf.Client(oauth2.NoContext)\n\tgcsToken, err := conf.TokenSource(oauth2.NoContext).Token()\n\tservice, err := storage.New(client)\n\tif err != nil {\n\t\tlog.Fatalf(\"GCS unable to create storage service: %v\", err)\n\t}\n\n\t\/\/ If the bucket already exists and the user has access,  don't try to create it.\n\tif _, err := service.Buckets.Get(bucketName).Do(); err != nil {\n\t\t\/\/ If bucket is not exist, Create a bucket.\n\t\tif _, err := service.Buckets.Insert(projectID, &storage.Bucket{Name: bucketName}).Do(); err != nil {\n\t\t\tlog.Fatalf(\"GCS failed creating bucket %s: %v\", bucketName, err)\n\t\t}\n\t}\n\n\t\/\/Split filename as a objectName\n\tvar objectName string\n\tfor _, objectName = range strings.Split(file, \"\/\") {\n\t}\n\tobject := &storage.Object{Name: objectName}\n\n\t\/\/ Insert an object into a bucket.\n\tfileDes, err := os.Open(file)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error opening %q: %v\", file, err)\n\t}\n\tobjs, err := service.Objects.Insert(bucketName, object).Media(fileDes).Do()\n\tif err != nil {\n\t\tlog.Fatalf(\"GCS Objects.Insert failed: %v\", err)\n\t}\n\tretUrl := objs.MediaLink + \"&access_token=\" + gcsToken.AccessToken\n\t\/\/fmt.Println(fmt.Sprintf(\"GCS tmpUrl=%s\", retUrl))\n\n\tif err != nil {\n\t\treturn \"\", err\n\t} else {\n\t\treturn retUrl, nil\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package encoder\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"io\"\n\t\"unicode\/utf8\"\n)\n\nvar hex = \"0123456789abcdef\"\n\n\/\/ WriteString writes a JSON string to the writer. JSON encoding used\n\/\/ from the encoding\/json package.\nfunc WriteString(w io.Writer, v string) error {\n\tvar buf bytes.Buffer\n\treturn WriteStringWithBuffer(w, v, &buf)\n}\n\n\/\/ WriteString writes a JSON string to the writer. JSON encoding used\n\/\/ from the encoding\/json package.\nfunc WriteStringWithBuffer(w io.Writer, v string, buf *bytes.Buffer) error {\n\tbuf.Reset()\n\tbuf.WriteByte('\"')\n\tprev := 0\n\tfor i := 0; i < len(v); {\n\t\tif b := v[i]; b < utf8.RuneSelf {\n\t\t\tif 0x20 <= b && b != '\\\\' && b != '\"' && b != '<' && b != '>' {\n\t\t\t\ti++\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif prev < i {\n\t\t\t\tbuf.WriteString(v[prev:i])\n\t\t\t}\n\t\t\tswitch b {\n\t\t\tcase '\\\\', '\"':\n\t\t\t\tbuf.WriteByte('\\\\')\n\t\t\t\tbuf.WriteByte(b)\n\t\t\tcase '\\n':\n\t\t\t\tbuf.WriteByte('\\\\')\n\t\t\t\tbuf.WriteByte('n')\n\t\t\tcase '\\r':\n\t\t\t\tbuf.WriteByte('\\\\')\n\t\t\t\tbuf.WriteByte('r')\n\t\t\tdefault:\n\t\t\t\t\/\/ This encodes bytes < 0x20 except for \\n and \\r,\n\t\t\t\t\/\/ as well as < and >. The latter are escaped because they\n\t\t\t\t\/\/ can lead to security holes when user-controlled strings\n\t\t\t\t\/\/ are rendered into JSON and served to some browsers.\n\t\t\t\tbuf.WriteString(`\\u00`)\n\t\t\t\tbuf.WriteByte(hex[b>>4])\n\t\t\t\tbuf.WriteByte(hex[b&0xF])\n\t\t\t}\n\t\t\ti++\n\t\t\tprev = i\n\t\t\tcontinue\n\t\t}\n\t\tc, size := utf8.DecodeRuneInString(v[i:])\n\t\tif c == utf8.RuneError && size == 1 {\n\t\t\treturn &json.InvalidUTF8Error{S: v}\n\t\t}\n\t\ti += size\n\t}\n\tif prev < len(v) {\n\t\tbuf.WriteString(v[prev:])\n\t}\n\tbuf.WriteByte('\"')\n\tw.Write(buf.Bytes())\n\treturn nil\n}\n<commit_msg>Remove old string writer.<commit_after><|endoftext|>"}
{"text":"<commit_before><commit_msg>Fix up delete function<commit_after><|endoftext|>"}
{"text":"<commit_before>package creds\n\nimport (\n\t\"sync\"\n\t\"time\"\n\n\t\"encoding\/json\"\n\n\t\"code.cloudfoundry.org\/clock\"\n\t\"code.cloudfoundry.org\/lager\"\n)\n\n\/\/go:generate counterfeiter . VarSourcePool\n\ntype VarSourcePool interface {\n\tFindOrCreate(lager.Logger, map[string]interface{}, ManagerFactory) (Secrets, error)\n\tSize() int\n\tClose()\n}\n\ntype inPoolManager struct {\n\tmanager        Manager\n\tsecretsFactory SecretsFactory\n\tlastUseTime    time.Time\n\tclock          clock.Clock\n}\n\nfunc (m *inPoolManager) Close(logger lager.Logger) {\n\tm.manager.Close(logger)\n}\n\nfunc (m *inPoolManager) NewSecrets() Secrets {\n\tm.lastUseTime = m.clock.Now()\n\treturn m.secretsFactory.NewSecrets()\n}\n\ntype varSourcePool struct {\n\tpool  map[string]*inPoolManager\n\tlock  sync.Mutex\n\tttl   time.Duration\n\tclock clock.Clock\n\n\tcloseOnce sync.Once\n\tclosed    chan struct{}\n}\n\nfunc NewVarSourcePool(\n\tlogger lager.Logger,\n\tttl time.Duration,\n\tcollectInterval time.Duration,\n\tclock clock.Clock,\n) VarSourcePool {\n\tpool := &varSourcePool{\n\t\tpool:  map[string]*inPoolManager{},\n\t\tlock:  sync.Mutex{},\n\t\tttl:   ttl,\n\t\tclock: clock,\n\n\t\tcloseOnce: sync.Once{},\n\t\tclosed:    make(chan struct{}),\n\t}\n\n\tgo pool.collectLoop(\n\t\tlogger.Session(\"collect\"),\n\t\tcollectInterval,\n\t)\n\n\treturn pool\n}\n\nfunc (pool *varSourcePool) Size() int {\n\treturn len(pool.pool)\n}\n\nfunc (pool *varSourcePool) FindOrCreate(logger lager.Logger, config map[string]interface{}, factory ManagerFactory) (Secrets, error) {\n\tb, err := json.Marshal(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkey := string(b)\n\n\tpool.lock.Lock()\n\tdefer pool.lock.Unlock()\n\n\tif _, ok := pool.pool[key]; !ok {\n\t\tmanager, err := factory.NewInstance(config)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = manager.Init(logger)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tsecretsFactory, err := manager.NewSecretsFactory(logger)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tpool.pool[key] = &inPoolManager{\n\t\t\tclock:          pool.clock,\n\t\t\tmanager:        manager,\n\t\t\tsecretsFactory: secretsFactory,\n\t\t}\n\t} else {\n\t\tlogger.Debug(\"found-existing-credential-manager\")\n\t}\n\n\treturn pool.pool[key].NewSecrets(), nil\n}\n\nfunc (pool *varSourcePool) Close() {\n\tpool.closeOnce.Do(func() {\n\t\tclose(pool.closed)\n\t})\n}\n\nfunc (pool *varSourcePool) collectLoop(logger lager.Logger, interval time.Duration) {\n\tticker := pool.clock.NewTicker(interval)\n\tdefer ticker.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-pool.closed:\n\t\t\tpool.collect(logger.Session(\"close\"), true)\n\t\t\treturn\n\t\tcase <-ticker.C():\n\t\t\tpool.collect(logger.Session(\"tick\"), false)\n\t\t}\n\t}\n}\n\nfunc (pool *varSourcePool) collect(logger lager.Logger, all bool) error {\n\tpool.lock.Lock()\n\tdefer pool.lock.Unlock()\n\n\tlogger.Debug(\"before\", lager.Data{\"size\": len(pool.pool)})\n\n\ttoDeleteKeys := []string{}\n\tfor key, manager := range pool.pool {\n\t\tif all || manager.lastUseTime.Add(pool.ttl).Before(pool.clock.Now()) {\n\t\t\ttoDeleteKeys = append(toDeleteKeys, key)\n\t\t\tmanager.Close(logger)\n\t\t}\n\t}\n\n\tfor _, key := range toDeleteKeys {\n\t\tdelete(pool.pool, key)\n\t}\n\n\tlogger.Debug(\"after\", lager.Data{\"size\": len(pool.pool)})\n\n\treturn nil\n}\n<commit_msg>atc: structure: fix data race in var source pool<commit_after>package creds\n\nimport (\n\t\"sync\"\n\t\"time\"\n\n\t\"encoding\/json\"\n\n\t\"code.cloudfoundry.org\/clock\"\n\t\"code.cloudfoundry.org\/lager\"\n)\n\n\/\/go:generate counterfeiter . VarSourcePool\n\ntype VarSourcePool interface {\n\tFindOrCreate(lager.Logger, map[string]interface{}, ManagerFactory) (Secrets, error)\n\tSize() int\n\tClose()\n}\n\ntype inPoolManager struct {\n\tmanager        Manager\n\tsecretsFactory SecretsFactory\n\tlastUseTime    time.Time\n\tclock          clock.Clock\n}\n\nfunc (m *inPoolManager) Close(logger lager.Logger) {\n\tm.manager.Close(logger)\n}\n\nfunc (m *inPoolManager) NewSecrets() Secrets {\n\tm.lastUseTime = m.clock.Now()\n\treturn m.secretsFactory.NewSecrets()\n}\n\ntype varSourcePool struct {\n\tpool  map[string]*inPoolManager\n\tlock  sync.Mutex\n\tttl   time.Duration\n\tclock clock.Clock\n\n\tcloseOnce sync.Once\n\tclosed    chan struct{}\n}\n\nfunc NewVarSourcePool(\n\tlogger lager.Logger,\n\tttl time.Duration,\n\tcollectInterval time.Duration,\n\tclock clock.Clock,\n) VarSourcePool {\n\tpool := &varSourcePool{\n\t\tpool:  map[string]*inPoolManager{},\n\t\tlock:  sync.Mutex{},\n\t\tttl:   ttl,\n\t\tclock: clock,\n\n\t\tcloseOnce: sync.Once{},\n\t\tclosed:    make(chan struct{}),\n\t}\n\n\tgo pool.collectLoop(\n\t\tlogger.Session(\"collect\"),\n\t\tcollectInterval,\n\t)\n\n\treturn pool\n}\n\nfunc (pool *varSourcePool) Size() int {\n\tpool.lock.Lock()\n\tdefer pool.lock.Unlock()\n\treturn len(pool.pool)\n}\n\nfunc (pool *varSourcePool) FindOrCreate(logger lager.Logger, config map[string]interface{}, factory ManagerFactory) (Secrets, error) {\n\tb, err := json.Marshal(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkey := string(b)\n\n\tpool.lock.Lock()\n\tdefer pool.lock.Unlock()\n\n\tif _, ok := pool.pool[key]; !ok {\n\t\tmanager, err := factory.NewInstance(config)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\terr = manager.Init(logger)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tsecretsFactory, err := manager.NewSecretsFactory(logger)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tpool.pool[key] = &inPoolManager{\n\t\t\tclock:          pool.clock,\n\t\t\tmanager:        manager,\n\t\t\tsecretsFactory: secretsFactory,\n\t\t}\n\t} else {\n\t\tlogger.Debug(\"found-existing-credential-manager\")\n\t}\n\n\treturn pool.pool[key].NewSecrets(), nil\n}\n\nfunc (pool *varSourcePool) Close() {\n\tpool.closeOnce.Do(func() {\n\t\tclose(pool.closed)\n\t})\n}\n\nfunc (pool *varSourcePool) collectLoop(logger lager.Logger, interval time.Duration) {\n\tticker := pool.clock.NewTicker(interval)\n\tdefer ticker.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-pool.closed:\n\t\t\tpool.collect(logger.Session(\"close\"), true)\n\t\t\treturn\n\t\tcase <-ticker.C():\n\t\t\tpool.collect(logger.Session(\"tick\"), false)\n\t\t}\n\t}\n}\n\nfunc (pool *varSourcePool) collect(logger lager.Logger, all bool) error {\n\tpool.lock.Lock()\n\tdefer pool.lock.Unlock()\n\n\tlogger.Debug(\"before\", lager.Data{\"size\": len(pool.pool)})\n\n\ttoDeleteKeys := []string{}\n\tfor key, manager := range pool.pool {\n\t\tif all || manager.lastUseTime.Add(pool.ttl).Before(pool.clock.Now()) {\n\t\t\ttoDeleteKeys = append(toDeleteKeys, key)\n\t\t\tmanager.Close(logger)\n\t\t}\n\t}\n\n\tfor _, key := range toDeleteKeys {\n\t\tdelete(pool.pool, key)\n\t}\n\n\tlogger.Debug(\"after\", lager.Data{\"size\": len(pool.pool)})\n\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/Copyright 2017 Huawei Technologies Co., Ltd\n\/\/\n\/\/Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/you may not use this file except in compliance with the License.\n\/\/You may obtain a copy of the License at\n\/\/\n\/\/   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/Unless required by applicable law or agreed to in writing, software\n\/\/distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/See the License for the specific language governing permissions and\n\/\/limitations under the License.\npackage notification\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\tapt \"github.com\/ServiceComb\/service-center\/server\/core\"\n\tpb \"github.com\/ServiceComb\/service-center\/server\/core\/proto\"\n\tms \"github.com\/ServiceComb\/service-center\/server\/service\/microservice\"\n\t\"github.com\/ServiceComb\/service-center\/util\"\n\t\"github.com\/gorilla\/websocket\"\n\t\"golang.org\/x\/net\/context\"\n\t\"time\"\n)\n\nfunc HandleWatchJob(watcher *ListWatcher, stream pb.ServiceInstanceCtrl_WatchServer, timeout time.Duration) (err error) {\n\tfor {\n\t\tselect {\n\t\tcase <-time.After(timeout):\n\t\t\/\/ TODO grpc 长连接心跳？\n\t\tcase job := <-watcher.Job:\n\t\t\tif job == nil {\n\t\t\t\terr = errors.New(\"channel is closed\")\n\t\t\t\tutil.LOGGER.Errorf(err, \"watcher %s %s caught an exception\",\n\t\t\t\t\twatcher.Subject(), watcher.Id())\n\t\t\t\treturn\n\t\t\t}\n\t\t\tresp := job.(*WatchJob).Response\n\t\t\tutil.LOGGER.Infof(\"event is coming in, watcher %s %s\",\n\t\t\t\twatcher.Subject(), watcher.Id())\n\n\t\t\terr = stream.Send(resp)\n\t\t\tif err != nil {\n\t\t\t\tutil.LOGGER.Errorf(err, \"send message error, watcher %s %s\",\n\t\t\t\t\twatcher.Subject(), watcher.Id())\n\t\t\t\twatcher.SetError(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\ntype WebSocketHandler struct {\n\tctx             context.Context\n\tconn            *websocket.Conn\n\twatcher         *ListWatcher\n\tneedPingWatcher bool\n}\n\nfunc (wh *WebSocketHandler) Init() error {\n\tremoteAddr := wh.conn.RemoteAddr().String()\n\tif err := GetNotifyService().AddSubscriber(wh.watcher); err != nil {\n\t\terr = fmt.Errorf(\"establish[%s] websocket watch failed: notify service error, %s.\",\n\t\t\tremoteAddr, err.Error())\n\t\tutil.LOGGER.Errorf(nil, err.Error())\n\n\t\terr = wh.conn.WriteMessage(websocket.TextMessage, util.StringToBytesWithNoCopy(err.Error()))\n\t\tif err != nil {\n\t\t\tutil.LOGGER.Errorf(err, \"establish[%s] websocket watch failed: write message failed.\", remoteAddr)\n\t\t}\n\t\treturn err\n\t}\n\tutil.LOGGER.Debugf(\"start watching instance status, watcher[%s] %s %s\",\n\t\tremoteAddr, wh.watcher.Subject(), wh.watcher.Id())\n\treturn nil\n}\n\nfunc (wh *WebSocketHandler) Timeout() time.Duration {\n\treturn GetNotifyService().Config.NotifyTimeout\n}\n\nfunc (wh *WebSocketHandler) websocketHeartbeat(messageType int) error {\n\terr := wh.conn.WriteControl(messageType, []byte{}, time.Now().Add(wh.Timeout()))\n\tif err != nil {\n\t\tmessageTypeName := \"Ping\"\n\t\tif messageType == websocket.PongMessage {\n\t\t\tmessageTypeName = \"Pong\"\n\t\t}\n\t\tutil.LOGGER.Errorf(err, \"fail to send '%s' to watcher[%s] %s %s\", messageTypeName,\n\t\t\twh.conn.RemoteAddr(), wh.watcher.Subject(), wh.watcher.Id())\n\t\t\/\/wh.watcher.SetError(err)\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (wh *WebSocketHandler) HandleWatchWebSocketControlMessage() {\n\tremoteAddr := wh.conn.RemoteAddr().String()\n\t\/\/ PING\n\twh.conn.SetPingHandler(func(message string) error {\n\t\tif wh.needPingWatcher {\n\t\t\tutil.LOGGER.Infof(\"received 'Ping' message '%s' from watcher[%s] %s %s, no longer send 'Ping' to it\",\n\t\t\t\tmessage, remoteAddr, wh.watcher.Subject(), wh.watcher.Id())\n\t\t}\n\t\twh.needPingWatcher = false\n\t\treturn wh.websocketHeartbeat(websocket.PongMessage)\n\t})\n\t\/\/ PONG\n\twh.conn.SetPongHandler(func(message string) error {\n\t\tutil.LOGGER.Debugf(\"received 'Pong' message %s from watcher[%s] %s %s\",\n\t\t\tmessage, remoteAddr, wh.watcher.Subject(), wh.watcher.Id())\n\t\treturn nil\n\t})\n\t\/\/ CLOSE\n\twh.conn.SetCloseHandler(func(code int, text string) error {\n\t\tutil.LOGGER.Warnf(nil, \"watcher[%s] %s %s active closed\", remoteAddr,\n\t\t\twh.watcher.Subject(), wh.watcher.Id())\n\t\treturn wh.Close(code, text)\n\t})\n\n\tfor {\n\t\t_, _, err := wh.conn.ReadMessage()\n\t\tif err != nil {\n\t\t\twh.watcher.SetError(err)\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (wh *WebSocketHandler) HandleWatchWebSocketJob() {\n\tremoteAddr := wh.conn.RemoteAddr().String()\n\n\tfor {\n\t\tselect {\n\t\tcase <-wh.ctx.Done():\n\t\t\tutil.LOGGER.Warnf(nil, \"handle timed out, watcher[%s] %s %s\", remoteAddr,\n\t\t\t\twh.watcher.Subject(), wh.watcher.Id())\n\t\t\treturn\n\t\tcase <-time.After(wh.Timeout()):\n\t\t\tif wh.watcher.Err() != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\ttenant := util.ParseTenantProject(wh.ctx)\n\t\t\tif !ms.ServiceExist(context.Background(), tenant, wh.watcher.Id()) {\n\t\t\t\terr := fmt.Errorf(\"Service does not exit.\")\n\t\t\t\tutil.LOGGER.Warnf(err, \"watcher[%s] %s %s exit\", remoteAddr, wh.watcher.Subject(), wh.watcher.Id())\n\t\t\t\terr = wh.conn.WriteMessage(websocket.TextMessage, util.StringToBytesWithNoCopy(err.Error()))\n\t\t\t\tif err != nil {\n\t\t\t\t\tutil.LOGGER.Errorf(err, \"watch catch a err: write message error, watcher[%s] %s %s\",\n\t\t\t\t\t\tremoteAddr, wh.watcher.Subject(), wh.watcher.Id())\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif !wh.needPingWatcher {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tutil.LOGGER.Debugf(\"send heartbeat to watcher[%s] %s %s\", remoteAddr, wh.watcher.Subject(), wh.watcher.Id())\n\t\t\terr := wh.websocketHeartbeat(websocket.PingMessage)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase job := <-wh.watcher.Job:\n\t\t\tif wh.watcher.Err() != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif job == nil {\n\t\t\t\terr := wh.conn.WriteMessage(websocket.TextMessage,\n\t\t\t\t\tutil.StringToBytesWithNoCopy(\"watch catch a err: watcher quit for server shutdown\"))\n\t\t\t\tif err != nil {\n\t\t\t\t\tutil.LOGGER.Errorf(err, \"watch catch a err: write message error, watcher[%s] %s %s\",\n\t\t\t\t\t\tremoteAddr, wh.watcher.Subject(), wh.watcher.Id())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tutil.LOGGER.Warnf(nil, \"watch catch a err: server shutdown, watcher[%s] %s %s\",\n\t\t\t\t\tremoteAddr, wh.watcher.Subject(), wh.watcher.Id())\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tresp := job.(*WatchJob).Response\n\n\t\t\tutil.LOGGER.Warnf(nil, \"event[%s] is coming in, watcher[%s] %s %s, providers' info %s %s\",\n\t\t\t\tresp.Action, remoteAddr, wh.watcher.Subject(), wh.watcher.Id(), resp.Instance.ServiceId, resp.Instance.InstanceId)\n\n\t\t\tresp.Response = nil\n\t\t\tdata, err := json.Marshal(resp)\n\t\t\tif err != nil {\n\t\t\t\tutil.LOGGER.Errorf(err, \"watch catch a err: marshal output file error, watcher[%s] %s %s\",\n\t\t\t\t\tremoteAddr, wh.watcher.Subject(), wh.watcher.Id())\n\t\t\t\tmessage := fmt.Sprintf(\"marshal output file error, %s\", err.Error())\n\t\t\t\terr = wh.conn.WriteMessage(websocket.TextMessage, util.StringToBytesWithNoCopy(message))\n\t\t\t\tif err != nil {\n\t\t\t\t\tutil.LOGGER.Errorf(err, \"watch catch a err: write message error, watcher[%s] %s %s\",\n\t\t\t\t\t\tremoteAddr, wh.watcher.Subject(), wh.watcher.Id())\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t\terr = wh.conn.WriteMessage(websocket.TextMessage, data)\n\t\t\tif err != nil {\n\t\t\t\tutil.LOGGER.Errorf(err, \"watch catch a err: write message error, watcher[%s] %s %s\",\n\t\t\t\t\tremoteAddr, wh.watcher.Subject(), wh.watcher.Id())\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (wh *WebSocketHandler) Close(code int, text string) error {\n\tremoteAddr := wh.conn.RemoteAddr().String()\n\tmessage := []byte{}\n\tif code != websocket.CloseNoStatusReceived {\n\t\tmessage = websocket.FormatCloseMessage(code, text)\n\t}\n\terr := wh.conn.WriteControl(websocket.CloseMessage, message, time.Now().Add(wh.Timeout()))\n\tif err != nil {\n\t\tutil.LOGGER.Errorf(err, \"watch catch a err: write 'Close' message error, watcher[%s] %s %s\",\n\t\t\tremoteAddr, wh.watcher.Subject(), wh.watcher.Id())\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc DoWebSocketWatch(ctx context.Context, serviceId string, conn *websocket.Conn) {\n\ttenant := util.ParseTenantProject(ctx)\n\thandler := &WebSocketHandler{\n\t\tctx:             ctx,\n\t\tconn:            conn,\n\t\twatcher:         NewInstanceWatcher(serviceId, apt.GetInstanceRootKey(tenant)+\"\/\"),\n\t\tneedPingWatcher: true,\n\t}\n\tprocessHandler(handler)\n}\n\nfunc DoWebSocketListAndWatch(ctx context.Context, serviceId string, f func() ([]*pb.WatchInstanceResponse, int64), conn *websocket.Conn) {\n\ttenant := util.ParseTenantProject(ctx)\n\thandler := &WebSocketHandler{\n\t\tctx:             ctx,\n\t\tconn:            conn,\n\t\twatcher:         NewInstanceListWatcher(serviceId, apt.GetInstanceRootKey(tenant)+\"\/\", f),\n\t\tneedPingWatcher: true,\n\t}\n\tprocessHandler(handler)\n}\n\nfunc processHandler(handler *WebSocketHandler) {\n\tif err := handler.Init(); err != nil {\n\t\treturn\n\t}\n\tgo handler.HandleWatchWebSocketControlMessage()\n\thandler.HandleWatchWebSocketJob()\n}\n\nfunc EstablishWebSocketError(conn *websocket.Conn, err error) {\n\tremoteAddr := conn.RemoteAddr().String()\n\tutil.LOGGER.Errorf(err, \"establish[%s] websocket watch failed.\", remoteAddr)\n\tif err := conn.WriteMessage(websocket.TextMessage, util.StringToBytesWithNoCopy(err.Error())); err != nil {\n\t\tutil.LOGGER.Errorf(err, \"establish[%s] websocket watch failed: write message failed.\", remoteAddr)\n\t}\n}\n\nfunc PublishInstanceEvent(tenant string, action pb.EventType, serviceKey *pb.MicroServiceKey, instance *pb.MicroServiceInstance, rev int64, subscribers []string) {\n\tresponse := &pb.WatchInstanceResponse{\n\t\tResponse: pb.CreateResponse(pb.Response_SUCCESS, \"Watch instance successfully.\"),\n\t\tAction:   string(action),\n\t\tKey:      serviceKey,\n\t\tInstance: instance,\n\t}\n\tfor _, consumerId := range subscribers {\n\t\tjob := NewWatchJob(INSTANCE, consumerId, apt.GetInstanceRootKey(tenant)+\"\/\", rev, response)\n\t\tutil.LOGGER.Debugf(\"publish event to notify service, %v\", job)\n\n\t\t\/\/ TODO add超时怎么处理？\n\t\tGetNotifyService().AddJob(job)\n\t}\n}\n\nfunc NewInstanceWatcher(selfServiceId, instanceRoot string) *ListWatcher {\n\treturn NewWatcher(INSTANCE, selfServiceId, instanceRoot)\n}\n\nfunc NewInstanceListWatcher(selfServiceId, instanceRoot string, listFunc func() (results []*pb.WatchInstanceResponse, rev int64)) *ListWatcher {\n\treturn NewListWatcher(INSTANCE, selfServiceId, instanceRoot, listFunc)\n}\n<commit_msg>Bug fixes: list & watch do not exit when connection was closed.<commit_after>\/\/Copyright 2017 Huawei Technologies Co., Ltd\n\/\/\n\/\/Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/you may not use this file except in compliance with the License.\n\/\/You may obtain a copy of the License at\n\/\/\n\/\/   http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/Unless required by applicable law or agreed to in writing, software\n\/\/distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/See the License for the specific language governing permissions and\n\/\/limitations under the License.\npackage notification\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\tapt \"github.com\/ServiceComb\/service-center\/server\/core\"\n\tpb \"github.com\/ServiceComb\/service-center\/server\/core\/proto\"\n\tms \"github.com\/ServiceComb\/service-center\/server\/service\/microservice\"\n\t\"github.com\/ServiceComb\/service-center\/util\"\n\t\"github.com\/gorilla\/websocket\"\n\t\"golang.org\/x\/net\/context\"\n\t\"time\"\n)\n\nfunc HandleWatchJob(watcher *ListWatcher, stream pb.ServiceInstanceCtrl_WatchServer, timeout time.Duration) (err error) {\n\tfor {\n\t\tselect {\n\t\tcase <-time.After(timeout):\n\t\t\/\/ TODO grpc 长连接心跳？\n\t\tcase job := <-watcher.Job:\n\t\t\tif job == nil {\n\t\t\t\terr = errors.New(\"channel is closed\")\n\t\t\t\tutil.LOGGER.Errorf(err, \"watcher %s %s caught an exception\",\n\t\t\t\t\twatcher.Subject(), watcher.Id())\n\t\t\t\treturn\n\t\t\t}\n\t\t\tresp := job.(*WatchJob).Response\n\t\t\tutil.LOGGER.Infof(\"event is coming in, watcher %s %s\",\n\t\t\t\twatcher.Subject(), watcher.Id())\n\n\t\t\terr = stream.Send(resp)\n\t\t\tif err != nil {\n\t\t\t\tutil.LOGGER.Errorf(err, \"send message error, watcher %s %s\",\n\t\t\t\t\twatcher.Subject(), watcher.Id())\n\t\t\t\twatcher.SetError(err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\ntype WebSocketHandler struct {\n\tctx             context.Context\n\tconn            *websocket.Conn\n\twatcher         *ListWatcher\n\tneedPingWatcher bool\n\tclosed          chan struct{}\n}\n\nfunc (wh *WebSocketHandler) Init() error {\n\tremoteAddr := wh.conn.RemoteAddr().String()\n\tif err := GetNotifyService().AddSubscriber(wh.watcher); err != nil {\n\t\terr = fmt.Errorf(\"establish[%s] websocket watch failed: notify service error, %s.\",\n\t\t\tremoteAddr, err.Error())\n\t\tutil.LOGGER.Errorf(nil, err.Error())\n\n\t\terr = wh.conn.WriteMessage(websocket.TextMessage, util.StringToBytesWithNoCopy(err.Error()))\n\t\tif err != nil {\n\t\t\tutil.LOGGER.Errorf(err, \"establish[%s] websocket watch failed: write message failed.\", remoteAddr)\n\t\t}\n\t\treturn err\n\t}\n\tutil.LOGGER.Debugf(\"start watching instance status, watcher[%s] %s %s\",\n\t\tremoteAddr, wh.watcher.Subject(), wh.watcher.Id())\n\treturn nil\n}\n\nfunc (wh *WebSocketHandler) Timeout() time.Duration {\n\treturn GetNotifyService().Config.NotifyTimeout\n}\n\nfunc (wh *WebSocketHandler) websocketHeartbeat(messageType int) error {\n\terr := wh.conn.WriteControl(messageType, []byte{}, time.Now().Add(wh.Timeout()))\n\tif err != nil {\n\t\tmessageTypeName := \"Ping\"\n\t\tif messageType == websocket.PongMessage {\n\t\t\tmessageTypeName = \"Pong\"\n\t\t}\n\t\tutil.LOGGER.Errorf(err, \"fail to send '%s' to watcher[%s] %s %s\", messageTypeName,\n\t\t\twh.conn.RemoteAddr(), wh.watcher.Subject(), wh.watcher.Id())\n\t\t\/\/wh.watcher.SetError(err)\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (wh *WebSocketHandler) HandleWatchWebSocketControlMessage() {\n\tdefer close(wh.closed)\n\n\tremoteAddr := wh.conn.RemoteAddr().String()\n\t\/\/ PING\n\twh.conn.SetPingHandler(func(message string) error {\n\t\tif wh.needPingWatcher {\n\t\t\tutil.LOGGER.Infof(\"received 'Ping' message '%s' from watcher[%s] %s %s, no longer send 'Ping' to it\",\n\t\t\t\tmessage, remoteAddr, wh.watcher.Subject(), wh.watcher.Id())\n\t\t}\n\t\twh.needPingWatcher = false\n\t\treturn wh.websocketHeartbeat(websocket.PongMessage)\n\t})\n\t\/\/ PONG\n\twh.conn.SetPongHandler(func(message string) error {\n\t\tutil.LOGGER.Debugf(\"received 'Pong' message %s from watcher[%s] %s %s\",\n\t\t\tmessage, remoteAddr, wh.watcher.Subject(), wh.watcher.Id())\n\t\treturn nil\n\t})\n\t\/\/ CLOSE\n\twh.conn.SetCloseHandler(func(code int, text string) error {\n\t\tutil.LOGGER.Warnf(nil, \"watcher[%s] %s %s active closed\", remoteAddr,\n\t\t\twh.watcher.Subject(), wh.watcher.Id())\n\t\treturn wh.Close(code, text)\n\t})\n\n\tfor {\n\t\t_, _, err := wh.conn.ReadMessage()\n\t\tif err != nil {\n\t\t\twh.watcher.SetError(err)\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (wh *WebSocketHandler) HandleWatchWebSocketJob() {\n\tremoteAddr := wh.conn.RemoteAddr().String()\n\n\tfor {\n\t\tselect {\n\t\tcase <-wh.closed:\n\t\t\treturn\n\t\tcase <-wh.ctx.Done():\n\t\t\tutil.LOGGER.Warnf(nil, \"handle timed out, watcher[%s] %s %s\", remoteAddr,\n\t\t\t\twh.watcher.Subject(), wh.watcher.Id())\n\t\t\treturn\n\t\tcase <-time.After(wh.Timeout()):\n\t\t\tif wh.watcher.Err() != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\ttenant := util.ParseTenantProject(wh.ctx)\n\t\t\tif !ms.ServiceExist(context.Background(), tenant, wh.watcher.Id()) {\n\t\t\t\terr := fmt.Errorf(\"Service does not exit.\")\n\t\t\t\tutil.LOGGER.Warnf(err, \"watcher[%s] %s %s exit\", remoteAddr, wh.watcher.Subject(), wh.watcher.Id())\n\t\t\t\terr = wh.conn.WriteMessage(websocket.TextMessage, util.StringToBytesWithNoCopy(err.Error()))\n\t\t\t\tif err != nil {\n\t\t\t\t\tutil.LOGGER.Errorf(err, \"watcher[%s] %s %s catch an err: write message error\",\n\t\t\t\t\t\tremoteAddr, wh.watcher.Subject(), wh.watcher.Id())\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif !wh.needPingWatcher {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tutil.LOGGER.Debugf(\"send 'Ping' message to watcher[%s] %s %s\", remoteAddr, wh.watcher.Subject(), wh.watcher.Id())\n\t\t\terr := wh.websocketHeartbeat(websocket.PingMessage)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\tcase job := <-wh.watcher.Job:\n\t\t\tif wh.watcher.Err() != nil {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif job == nil {\n\t\t\t\terr := wh.conn.WriteMessage(websocket.TextMessage,\n\t\t\t\t\tutil.StringToBytesWithNoCopy(\"watcher catch an err: server shutdown\"))\n\t\t\t\tif err != nil {\n\t\t\t\t\tutil.LOGGER.Errorf(err, \"watcher[%s] %s %s catch an err: write message error\",\n\t\t\t\t\t\tremoteAddr, wh.watcher.Subject(), wh.watcher.Id())\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tutil.LOGGER.Warnf(nil, \"watcher[%s] %s %s catch an err: server shutdown\",\n\t\t\t\t\tremoteAddr, wh.watcher.Subject(), wh.watcher.Id())\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tresp := job.(*WatchJob).Response\n\n\t\t\tutil.LOGGER.Warnf(nil, \"event[%s] is coming in, watcher[%s] %s %s, providers' info %s %s\",\n\t\t\t\tresp.Action, remoteAddr, wh.watcher.Subject(), wh.watcher.Id(), resp.Instance.ServiceId, resp.Instance.InstanceId)\n\n\t\t\tresp.Response = nil\n\t\t\tdata, err := json.Marshal(resp)\n\t\t\tif err != nil {\n\t\t\t\tutil.LOGGER.Errorf(err, \"watcher[%s] %s %s catch an err: marshal output file error\",\n\t\t\t\t\tremoteAddr, wh.watcher.Subject(), wh.watcher.Id())\n\t\t\t\tmessage := fmt.Sprintf(\"marshal output file error, %s\", err.Error())\n\t\t\t\terr = wh.conn.WriteMessage(websocket.TextMessage, util.StringToBytesWithNoCopy(message))\n\t\t\t\tif err != nil {\n\t\t\t\t\tutil.LOGGER.Errorf(err, \"watcher[%s] %s %s catch an err: write message error\",\n\t\t\t\t\t\tremoteAddr, wh.watcher.Subject(), wh.watcher.Id())\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t\terr = wh.conn.WriteMessage(websocket.TextMessage, data)\n\t\t\tif err != nil {\n\t\t\t\tutil.LOGGER.Errorf(err, \"watcher[%s] %s %s catch an err: write message error\",\n\t\t\t\t\tremoteAddr, wh.watcher.Subject(), wh.watcher.Id())\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (wh *WebSocketHandler) Close(code int, text string) error {\n\tremoteAddr := wh.conn.RemoteAddr().String()\n\tmessage := []byte{}\n\tif code != websocket.CloseNoStatusReceived {\n\t\tmessage = websocket.FormatCloseMessage(code, text)\n\t}\n\terr := wh.conn.WriteControl(websocket.CloseMessage, message, time.Now().Add(wh.Timeout()))\n\tif err != nil {\n\t\tutil.LOGGER.Errorf(err, \"watcher[%s] %s %s catch an err: write 'Close' message error\",\n\t\t\tremoteAddr, wh.watcher.Subject(), wh.watcher.Id())\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc DoWebSocketWatch(ctx context.Context, serviceId string, conn *websocket.Conn) {\n\ttenant := util.ParseTenantProject(ctx)\n\thandler := &WebSocketHandler{\n\t\tctx:             ctx,\n\t\tconn:            conn,\n\t\twatcher:         NewInstanceWatcher(serviceId, apt.GetInstanceRootKey(tenant)+\"\/\"),\n\t\tneedPingWatcher: true,\n\t\tclosed:          make(chan struct{}),\n\t}\n\tprocessHandler(handler)\n}\n\nfunc DoWebSocketListAndWatch(ctx context.Context, serviceId string, f func() ([]*pb.WatchInstanceResponse, int64), conn *websocket.Conn) {\n\ttenant := util.ParseTenantProject(ctx)\n\thandler := &WebSocketHandler{\n\t\tctx:             ctx,\n\t\tconn:            conn,\n\t\twatcher:         NewInstanceListWatcher(serviceId, apt.GetInstanceRootKey(tenant)+\"\/\", f),\n\t\tneedPingWatcher: true,\n\t\tclosed:          make(chan struct{}),\n\t}\n\tprocessHandler(handler)\n}\n\nfunc processHandler(handler *WebSocketHandler) {\n\tif err := handler.Init(); err != nil {\n\t\treturn\n\t}\n\tgo handler.HandleWatchWebSocketControlMessage()\n\thandler.HandleWatchWebSocketJob()\n}\n\nfunc EstablishWebSocketError(conn *websocket.Conn, err error) {\n\tremoteAddr := conn.RemoteAddr().String()\n\tutil.LOGGER.Errorf(err, \"establish[%s] websocket watch failed.\", remoteAddr)\n\tif err := conn.WriteMessage(websocket.TextMessage, util.StringToBytesWithNoCopy(err.Error())); err != nil {\n\t\tutil.LOGGER.Errorf(err, \"establish[%s] websocket watch failed: write message failed.\", remoteAddr)\n\t}\n}\n\nfunc PublishInstanceEvent(tenant string, action pb.EventType, serviceKey *pb.MicroServiceKey, instance *pb.MicroServiceInstance, rev int64, subscribers []string) {\n\tresponse := &pb.WatchInstanceResponse{\n\t\tResponse: pb.CreateResponse(pb.Response_SUCCESS, \"Watch instance successfully.\"),\n\t\tAction:   string(action),\n\t\tKey:      serviceKey,\n\t\tInstance: instance,\n\t}\n\tfor _, consumerId := range subscribers {\n\t\tjob := NewWatchJob(INSTANCE, consumerId, apt.GetInstanceRootKey(tenant)+\"\/\", rev, response)\n\t\tutil.LOGGER.Debugf(\"publish event to notify service, %v\", job)\n\n\t\t\/\/ TODO add超时怎么处理？\n\t\tGetNotifyService().AddJob(job)\n\t}\n}\n\nfunc NewInstanceWatcher(selfServiceId, instanceRoot string) *ListWatcher {\n\treturn NewWatcher(INSTANCE, selfServiceId, instanceRoot)\n}\n\nfunc NewInstanceListWatcher(selfServiceId, instanceRoot string, listFunc func() (results []*pb.WatchInstanceResponse, rev int64)) *ListWatcher {\n\treturn NewListWatcher(INSTANCE, selfServiceId, instanceRoot, listFunc)\n}\n<|endoftext|>"}
{"text":"<commit_before>package controlplane\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"k8s.io\/client-go\/rest\"\n\n\t\"k8s.io\/kubernetes\/test\/e2e\/framework\"\n\t\"k8s.io\/kubernetes\/test\/e2e\/upgrades\"\n\n\t\"github.com\/openshift\/origin\/pkg\/monitor\"\n\t\"github.com\/openshift\/origin\/test\/extended\/util\/disruption\"\n)\n\n\/\/ NewKubeAvailableWithNewConnectionsTest tests that the Kubernetes control plane remains available during and after a cluster upgrade.\nfunc NewKubeAvailableWithNewConnectionsTest() upgrades.Test {\n\treturn &availableTest{\n\t\ttestName:        \"[sig-api-machinery] Kubernetes APIs remain available for new connections\",\n\t\tname:            \"kubernetes-api-available-new-connections\",\n\t\tstartMonitoring: monitor.StartKubeAPIMonitoringWithNewConnections,\n\t}\n}\n\n\/\/ NewOpenShiftAvailableNewConnectionsTest tests that the OpenShift APIs remains available during and after a cluster upgrade.\nfunc NewOpenShiftAvailableNewConnectionsTest() upgrades.Test {\n\treturn &availableTest{\n\t\ttestName:        \"[sig-api-machinery] OpenShift APIs remain available for new connections\",\n\t\tname:            \"openshift-api-available-new-connections\",\n\t\tstartMonitoring: monitor.StartOpenShiftAPIMonitoringWithNewConnections,\n\t}\n}\n\n\/\/ NewOAuthAvailableNewConnectionsTest tests that the OAuth APIs remains available during and after a cluster upgrade.\nfunc NewOAuthAvailableNewConnectionsTest() upgrades.Test {\n\treturn &availableTest{\n\t\ttestName:        \"[sig-api-machinery] OAuth APIs remain available for new connections\",\n\t\tname:            \"oauth-api-available-new-connections\",\n\t\tstartMonitoring: monitor.StartOAuthAPIMonitoringWithNewConnections,\n\t}\n}\n\n\/\/ NewKubeAvailableWithConnectionReuseTest tests that the Kubernetes control plane remains available during and after a cluster upgrade.\nfunc NewKubeAvailableWithConnectionReuseTest() upgrades.Test {\n\treturn &availableTest{\n\t\ttestName:        \"[sig-api-machinery] Kubernetes APIs remain available with reused connections\",\n\t\tname:            \"kubernetes-api-available-reused-connections\",\n\t\tstartMonitoring: monitor.StartKubeAPIMonitoringWithConnectionReuse,\n\t}\n}\n\n\/\/ NewOpenShiftAvailableTest tests that the OpenShift APIs remains available during and after a cluster upgrade.\nfunc NewOpenShiftAvailableWithConnectionReuseTest() upgrades.Test {\n\treturn &availableTest{\n\t\ttestName:        \"[sig-api-machinery] OpenShift APIs remain available with reused connections\",\n\t\tname:            \"openshift-api-available-reused-connections\",\n\t\tstartMonitoring: monitor.StartOpenShiftAPIMonitoringWithConnectionReuse,\n\t}\n}\n\n\/\/ NewOauthAvailableTest tests that the OAuth APIs remains available during and after a cluster upgrade.\nfunc NewOAuthAvailableWithConnectionReuseTest() upgrades.Test {\n\treturn &availableTest{\n\t\ttestName:        \"[sig-api-machinery] OAuth APIs remain available with reused connections\",\n\t\tname:            \"oauth-api-available-reused-connections\",\n\t\tstartMonitoring: monitor.StartOAuthAPIMonitoringWithConnectionReuse,\n\t}\n}\n\ntype availableTest struct {\n\t\/\/ testName is the name to show in unit\n\ttestName string\n\t\/\/ name helps distinguish which API server in particular is unavailable.\n\tname            string\n\tstartMonitoring starter\n}\n\ntype starter func(ctx context.Context, m *monitor.Monitor, clusterConfig *rest.Config, timeout time.Duration) error\n\nfunc (t availableTest) Name() string { return t.name }\nfunc (t availableTest) DisplayName() string {\n\treturn t.testName\n}\n\n\/\/ Setup does nothing\nfunc (t *availableTest) Setup(f *framework.Framework) {\n}\n\n\/\/ Test runs a connectivity check to the core APIs.\nfunc (t *availableTest) Test(f *framework.Framework, done <-chan struct{}, upgrade upgrades.UpgradeType) {\n\tconfig, err := framework.LoadConfig()\n\tframework.ExpectNoError(err)\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tm := monitor.NewMonitorWithInterval(time.Second)\n\terr = t.startMonitoring(ctx, m, config, 15*time.Second)\n\tframework.ExpectNoError(err, \"unable to monitor API\")\n\n\tstart := time.Now()\n\tm.StartSampling(ctx)\n\n\t\/\/ wait to ensure API is still up after the test ends\n\t<-done\n\ttime.Sleep(15 * time.Second)\n\tcancel()\n\tend := time.Now()\n\n\t\/\/ AWS and Azure in 4.7 reached the point of having no disruption and thus\n\t\/\/ now lock in that requirement. GCP has a known issue with health checking\n\t\/\/ https:\/\/bugzilla.redhat.com\/show_bug.cgi?id=1925698 that when fixed will\n\t\/\/ relax. Having two providers lock in the requirement ensures we block\n\t\/\/ regression and ratchet\n\ttoleratedDisruption := 0.08\n\tif framework.ProviderIs(\"aws\", \"azure\") {\n\t\ttoleratedDisruption = 0\n\t}\n\tdisruption.ExpectNoDisruption(f, toleratedDisruption, end.Sub(start), m.EventIntervals(time.Time{}, time.Time{}), fmt.Sprintf(\"API %q was unreachable during disruption\", t.name))\n}\n\n\/\/ Teardown cleans up any remaining resources.\nfunc (t *availableTest) Teardown(f *framework.Framework) {\n}\n<commit_msg>test: Mark GCP as fixed and AWS as flaky in upgrade availability<commit_after>package controlplane\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"k8s.io\/client-go\/rest\"\n\n\t\"k8s.io\/kubernetes\/test\/e2e\/framework\"\n\t\"k8s.io\/kubernetes\/test\/e2e\/upgrades\"\n\n\t\"github.com\/openshift\/origin\/pkg\/monitor\"\n\t\"github.com\/openshift\/origin\/test\/extended\/util\/disruption\"\n)\n\n\/\/ NewKubeAvailableWithNewConnectionsTest tests that the Kubernetes control plane remains available during and after a cluster upgrade.\nfunc NewKubeAvailableWithNewConnectionsTest() upgrades.Test {\n\treturn &availableTest{\n\t\ttestName:        \"[sig-api-machinery] Kubernetes APIs remain available for new connections\",\n\t\tname:            \"kubernetes-api-available-new-connections\",\n\t\tstartMonitoring: monitor.StartKubeAPIMonitoringWithNewConnections,\n\t}\n}\n\n\/\/ NewOpenShiftAvailableNewConnectionsTest tests that the OpenShift APIs remains available during and after a cluster upgrade.\nfunc NewOpenShiftAvailableNewConnectionsTest() upgrades.Test {\n\treturn &availableTest{\n\t\ttestName:        \"[sig-api-machinery] OpenShift APIs remain available for new connections\",\n\t\tname:            \"openshift-api-available-new-connections\",\n\t\tstartMonitoring: monitor.StartOpenShiftAPIMonitoringWithNewConnections,\n\t}\n}\n\n\/\/ NewOAuthAvailableNewConnectionsTest tests that the OAuth APIs remains available during and after a cluster upgrade.\nfunc NewOAuthAvailableNewConnectionsTest() upgrades.Test {\n\treturn &availableTest{\n\t\ttestName:        \"[sig-api-machinery] OAuth APIs remain available for new connections\",\n\t\tname:            \"oauth-api-available-new-connections\",\n\t\tstartMonitoring: monitor.StartOAuthAPIMonitoringWithNewConnections,\n\t}\n}\n\n\/\/ NewKubeAvailableWithConnectionReuseTest tests that the Kubernetes control plane remains available during and after a cluster upgrade.\nfunc NewKubeAvailableWithConnectionReuseTest() upgrades.Test {\n\treturn &availableTest{\n\t\ttestName:        \"[sig-api-machinery] Kubernetes APIs remain available with reused connections\",\n\t\tname:            \"kubernetes-api-available-reused-connections\",\n\t\tstartMonitoring: monitor.StartKubeAPIMonitoringWithConnectionReuse,\n\t}\n}\n\n\/\/ NewOpenShiftAvailableTest tests that the OpenShift APIs remains available during and after a cluster upgrade.\nfunc NewOpenShiftAvailableWithConnectionReuseTest() upgrades.Test {\n\treturn &availableTest{\n\t\ttestName:        \"[sig-api-machinery] OpenShift APIs remain available with reused connections\",\n\t\tname:            \"openshift-api-available-reused-connections\",\n\t\tstartMonitoring: monitor.StartOpenShiftAPIMonitoringWithConnectionReuse,\n\t}\n}\n\n\/\/ NewOauthAvailableTest tests that the OAuth APIs remains available during and after a cluster upgrade.\nfunc NewOAuthAvailableWithConnectionReuseTest() upgrades.Test {\n\treturn &availableTest{\n\t\ttestName:        \"[sig-api-machinery] OAuth APIs remain available with reused connections\",\n\t\tname:            \"oauth-api-available-reused-connections\",\n\t\tstartMonitoring: monitor.StartOAuthAPIMonitoringWithConnectionReuse,\n\t}\n}\n\ntype availableTest struct {\n\t\/\/ testName is the name to show in unit\n\ttestName string\n\t\/\/ name helps distinguish which API server in particular is unavailable.\n\tname            string\n\tstartMonitoring starter\n}\n\ntype starter func(ctx context.Context, m *monitor.Monitor, clusterConfig *rest.Config, timeout time.Duration) error\n\nfunc (t availableTest) Name() string { return t.name }\nfunc (t availableTest) DisplayName() string {\n\treturn t.testName\n}\n\n\/\/ Setup does nothing\nfunc (t *availableTest) Setup(f *framework.Framework) {\n}\n\n\/\/ Test runs a connectivity check to the core APIs.\nfunc (t *availableTest) Test(f *framework.Framework, done <-chan struct{}, upgrade upgrades.UpgradeType) {\n\tconfig, err := framework.LoadConfig()\n\tframework.ExpectNoError(err)\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tm := monitor.NewMonitorWithInterval(time.Second)\n\terr = t.startMonitoring(ctx, m, config, 15*time.Second)\n\tframework.ExpectNoError(err, \"unable to monitor API\")\n\n\tstart := time.Now()\n\tm.StartSampling(ctx)\n\n\t\/\/ wait to ensure API is still up after the test ends\n\t<-done\n\ttime.Sleep(15 * time.Second)\n\tcancel()\n\tend := time.Now()\n\n\ttoleratedDisruption := 0.08\n\tif framework.ProviderIs(\"azure\", \"gcp\") {\n\t\ttoleratedDisruption = 0\n\t}\n\tdisruption.ExpectNoDisruption(f, toleratedDisruption, end.Sub(start), m.EventIntervals(time.Time{}, time.Time{}), fmt.Sprintf(\"API %q was unreachable during disruption (AWS has a known issue: https:\/\/bugzilla.redhat.com\/show_bug.cgi?id=1943804)\", t.name))\n}\n\n\/\/ Teardown cleans up any remaining resources.\nfunc (t *availableTest) Teardown(f *framework.Framework) {\n}\n<|endoftext|>"}
{"text":"<commit_before>package main\n\nimport \"fmt\"\n\nfunc setZeroes(matrix [][]int) {\n\tlengthM := len(matrix)\n\tcolLen := len(matrix[0])\n\n\tvar zeroRow = make([]int, colLen)\n\tvar colZeroIndex []int\n\n\tfor i := 0; i < lengthM; i++ {\n\t\ttestI := 0\n\t\tfor colIndex, ele := range matrix[i] {\n\t\t\tif ele == 0 {\n\t\t\t\tcolZeroIndex = append(colZeroIndex, colIndex)\n\t\t\t\ttestI += 1\n\t\t\t}\n\t\t}\n\t\tif testI != 0 {\n\t\t\tmatrix[i] = zeroRow\n\t\t} else {\n\t\t\tfor _, ii := range colZeroIndex {\n\t\t\t\tmatrix[i][ii] = 0\n\t\t\t}\n\t\t}\n\n\t}\n\tfmt.Print(matrix)\n}\n\nfunc main() {\n\tmatrix := [][]int{\n\t\t[]int{1, 2, 0, 3, 4, 5},\n\t\t[]int{0, 4, 5, 6, 7, 8},\n\t\t[]int{1, 2, 3, 4, 5, 6},\n\t}\n\tsetZeroes(matrix)\n}\n<commit_msg>finish bug<commit_after>package main\n\nimport \"fmt\"\n\nfunc setZeroes(matrix [][]int) {\n\tlengthM := len(matrix)\n\tcolLen := len(matrix[0])\n\n\tvar zeroRow = make([]int, colLen)\n\tvar colZeroIndex []int\n\n\tfor i := 0; i < lengthM; i++ {\n\t\ttestI := 0\n\t\tfor colIndex, ele := range matrix[i] {\n\t\t\tif ele == 0 {\n\t\t\t\tcolZeroIndex = append(colZeroIndex, colIndex)\n\t\t\t\ttestI += 1\n\t\t\t}\n\t\t}\n\t\tif testI != 0 {\n\t\t\tfor rei := 0; rei < i; rei++ {\n\t\t\t\tfor _, ii := range colZeroIndex {\n\t\t\t\t\tmatrix[rei][ii] = 0\n\t\t\t\t}\n\t\t\t}\n\t\t\tmatrix[i] = zeroRow\n\t\t} else {\n\t\t\tfor _, ii := range colZeroIndex {\n\t\t\t\tmatrix[i][ii] = 0\n\t\t\t}\n\t\t}\n\n\t}\n\tfmt.Print(matrix)\n}\n\nfunc main() {\n\tmatrix := [][]int{\n\t\t[]int{1, 2, 0, 3, 4, 5},\n\t\t[]int{0, 4, 5, 6, 7, 8},\n\t\t[]int{1, 2, 3, 4, 5, 6},\n\t}\n\tsetZeroes(matrix)\n\n\tmatrix2 := [][]int{\n\t\t[]int{1, 2, 3, 3, 4, 5},\n\t\t[]int{0, 4, 5, 6, 7, 8},\n\t\t[]int{1, 2, 3, 4, 5, 6},\n\t}\n\tsetZeroes(matrix2)\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ +build !linux,!darwin\n\npackage networkallocator\n\nfunc getInitializers() []initializer {\n\treturn nil\n}\n<commit_msg>Fixing build break for winodws<commit_after>\/\/ +build !linux,!darwin,!windows\n\npackage networkallocator\n\nfunc getInitializers() []initializer {\n\treturn nil\n}\n<|endoftext|>"}
{"text":"<commit_before>package bbhw\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strconv\"\n)\n\n\/\/ SysFS managed ADCs ------------------------------------\n\ntype SysfsADC struct {\n\tNumber uint\n\tfd     *os.File\n\terr    error\n}\n\nfunc LoadOverlayForSysfsADC() error {\n\terr := AddDeviceTreeOverlayIfNotAlreadyLoaded(\"BB-ADC\")\n\tif err == ERROR_DTO_ALREADY_LOADED {\n\t\treturn nil\n\t} else {\n\t\treturn err\n\t}\n}\n\n\/\/ Instantinate a new ADC to read through sysfs. Takes ADC AIN numer (same as in sysfs)\nfunc NewSysfsADC(number uint) (adc *SysfsADC, err error) {\n\tadc = new(SysfsADC)\n\tadc.Number = number\n\tain := fmt.Sprintf(\"in_voltage%d_raw\", number)\n\n\tvar adc_dir string\n\tadc_dir, err = findTSCADCDir()\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/check if file really exists and open\n\tadc.fd, err = os.OpenFile(filepath.Join(adc_dir, ain), os.O_RDONLY|os.O_SYNC, 0666)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn adc, nil\n}\n\n\/\/ Wrapper around NewSysfsGPIO. Does not return an error but panics instead. Useful to avoid multiple return values.\n\/\/ This is the function with the same signature as all the other New*GPIO*s\nfunc NewSysfsADCOrPanic(number uint) (adc *SysfsADC) {\n\tadc, err := NewSysfsADC(number)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn adc\n}\n\n\/\/returns raw SysFs Value.\n\/\/ In case of new kernel 4.4 that means raw value which we convert to actual mV\nfunc (adc *SysfsADC) ReadValue() (value uint16) {\n\tif adc == nil {\n\t\tpanic(\"adc == nil\")\n\t}\n\tif adc.fd == nil {\n\t\tpanic(\"adc.fd == nil\")\n\t}\n\t_, adc.err = adc.fd.Seek(0, 0)\n\tif adc.err != nil {\n\t\treturn\n\t}\n\n\tvar numread int\n\tbuf := make([]byte, 16, 16)\n\tnumread, adc.err = adc.fd.Read(buf)\n\tif adc.err != nil {\n\t\treturn\n\t}\n\tvar value64 uint64\n\tvalue64, adc.err = strconv.ParseUint(string(buf[0:numread-1]), 10, 16)\n\n\treturn uint16(value64 * 1800 \/ 4096) \/\/4096 means 1.8V means 1800mV\n}\n\nfunc (adc *SysfsADC) CheckErrorOccurred() error {\n\tif adc == nil {\n\t\tpanic(\"adc == nil\")\n\t}\n\treturn adc.err\n}\n\nfunc (adc *SysfsADC) ReadValueCheckError() (value uint16, err error) {\n\tvalue = adc.ReadValue()\n\terr = adc.CheckErrorOccurred()\n\treturn\n}\n\nfunc findTSCADCDir() (adcdir string, err error) {\n\tvar ocp_dir string\n\tif ocp_dir, err = findOCPDir(); err != nil {\n\t\treturn\n\t}\n\tadcdir = filepath.Join(ocp_dir, \"44e0d000.tscadc\/TI-am335x-adc\/iio:device0\/\")\n\treturn\n}\n\nfunc findPyADCDir(ain string) (tdir string, err error) {\n\tvar ocp_dir string\n\tif ocp_dir, err = findOCPDir(); err != nil {\n\t\treturn\n\t}\n\tre1 := regexp.MustCompile(filepath.Join(ocp_dir, `.*`+ain+`\\.\\d+`+\"$\"))\n\terr = filepath.Walk(ocp_dir, makeFindDirHelperFunc(&tdir, re1, 5))\n\tif err == foundit_error_ {\n\t\terr = nil\n\t} else if err == nil {\n\t\terr = fmt.Errorf(\"ADC Directory for %s Not Found\", ain)\n\t}\n\treturn\n}\n<commit_msg>function to wait until adc shows up in sysfs<commit_after>package bbhw\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"time\"\n)\n\n\/\/ SysFS managed ADCs ------------------------------------\n\ntype SysfsADC struct {\n\tNumber uint\n\tfd     *os.File\n\terr    error\n}\n\nfunc LoadOverlayForSysfsADC() error {\n\terr := AddDeviceTreeOverlayIfNotAlreadyLoaded(\"BB-ADC\")\n\tif err == ERROR_DTO_ALREADY_LOADED {\n\t\treturn nil\n\t} else {\n\t\treturn err\n\t}\n}\n\nfunc WaitUntilSysFSADCRunning() error {\n\tadc_dir, err := findTSCADCDir()\n\tif err != nil {\n\t\treturn err\n\t}\n\tadcpath := filepath.Join(adc_dir, \"in_voltage0_raw\")\n\tfor wait := 200; wait > 0; wait-- {\n\t\tif doesPathExist(adcpath) {\n\t\t\tbreak\n\t\t} else {\n\t\t\ttime.Sleep(50 * time.Millisecond)\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ Instantinate a new ADC to read through sysfs. Takes ADC AIN numer (same as in sysfs)\nfunc NewSysfsADC(number uint) (adc *SysfsADC, err error) {\n\tadc = new(SysfsADC)\n\tadc.Number = number\n\tain := fmt.Sprintf(\"in_voltage%d_raw\", number)\n\n\tvar adc_dir string\n\tadc_dir, err = findTSCADCDir()\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/check if file really exists and open\n\tadc.fd, err = os.OpenFile(filepath.Join(adc_dir, ain), os.O_RDONLY|os.O_SYNC, 0666)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn adc, nil\n}\n\n\/\/ Wrapper around NewSysfsGPIO. Does not return an error but panics instead. Useful to avoid multiple return values.\n\/\/ This is the function with the same signature as all the other New*GPIO*s\nfunc NewSysfsADCOrPanic(number uint) (adc *SysfsADC) {\n\tadc, err := NewSysfsADC(number)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn adc\n}\n\n\/\/returns raw SysFs Value.\n\/\/ In case of new kernel 4.4 that means raw value which we convert to actual mV\nfunc (adc *SysfsADC) ReadValue() (value uint16) {\n\tif adc == nil {\n\t\tpanic(\"adc == nil\")\n\t}\n\tif adc.fd == nil {\n\t\tpanic(\"adc.fd == nil\")\n\t}\n\t_, adc.err = adc.fd.Seek(0, 0)\n\tif adc.err != nil {\n\t\treturn\n\t}\n\n\tvar numread int\n\tbuf := make([]byte, 16, 16)\n\tnumread, adc.err = adc.fd.Read(buf)\n\tif adc.err != nil {\n\t\treturn\n\t}\n\tvar value64 uint64\n\tvalue64, adc.err = strconv.ParseUint(string(buf[0:numread-1]), 10, 16)\n\n\treturn uint16(value64 * 1800 \/ 4096) \/\/4096 means 1.8V means 1800mV\n}\n\nfunc (adc *SysfsADC) CheckErrorOccurred() error {\n\tif adc == nil {\n\t\tpanic(\"adc == nil\")\n\t}\n\treturn adc.err\n}\n\nfunc (adc *SysfsADC) ReadValueCheckError() (value uint16, err error) {\n\tvalue = adc.ReadValue()\n\terr = adc.CheckErrorOccurred()\n\treturn\n}\n\nfunc findTSCADCDir() (adcdir string, err error) {\n\tvar ocp_dir string\n\tif ocp_dir, err = findOCPDir(); err != nil {\n\t\treturn\n\t}\n\tadcdir = filepath.Join(ocp_dir, \"44e0d000.tscadc\/TI-am335x-adc\/iio:device0\/\")\n\treturn\n}\n\nfunc findPyADCDir(ain string) (tdir string, err error) {\n\tvar ocp_dir string\n\tif ocp_dir, err = findOCPDir(); err != nil {\n\t\treturn\n\t}\n\tre1 := regexp.MustCompile(filepath.Join(ocp_dir, `.*`+ain+`\\.\\d+`+\"$\"))\n\terr = filepath.Walk(ocp_dir, makeFindDirHelperFunc(&tdir, re1, 5))\n\tif err == foundit_error_ {\n\t\terr = nil\n\t} else if err == nil {\n\t\terr = fmt.Errorf(\"ADC Directory for %s Not Found\", ain)\n\t}\n\treturn\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2018 Istio Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this currentFile except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage graph\n\nimport (\n\t\"encoding\/json\"\n\t\"reflect\"\n\t\"testing\"\n\t\"time\"\n\n\t\"istio.io\/tools\/isotope\/convert\/pkg\/graph\/script\"\n\t\"istio.io\/tools\/isotope\/convert\/pkg\/graph\/svc\"\n\n\t\"istio.io\/tools\/isotope\/convert\/pkg\/graph\/svctype\"\n)\n\nfunc TestServiceGraph_UnmarshalJSON(t *testing.T) {\n\ttests := []struct {\n\t\tinput []byte\n\t\tgraph ServiceGraph\n\t\terr   error\n\t}{\n\t\t{jsonWithOneService, graphWithOneService, nil},\n\t\t{jsonWithDefaultsAndManyServices, graphWithDefaultsAndManyServices, nil},\n\t\t{\n\t\t\tjsonWithRequestToUndefinedService,\n\t\t\tServiceGraph{},\n\t\t\tErrRequestToUndefinedService{\"b\"},\n\t\t},\n\t\t{\n\t\t\tjsonWithNestedConcurrentCommand,\n\t\t\tServiceGraph{},\n\t\t\tErrNestedConcurrentCommand,\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\ttest := test\n\t\tt.Run(\"\", func(t *testing.T) {\n\t\t\tt.Parallel()\n\n\t\t\tvar graph ServiceGraph\n\t\t\terr := json.Unmarshal(test.input, &graph)\n\t\t\tif err == nil {\n\t\t\t\tif !reflect.DeepEqual(test.graph, graph) {\n\t\t\t\t\tt.Errorf(\"expected %v; actual %v\", test.graph, graph)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif test.err != err {\n\t\t\t\t\tt.Errorf(\"expected %v; actual %v\", test.err, err)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nvar (\n\tjsonWithOneService = []byte(`\n\t\t{\n\t\t\t\"services\": [{\"name\": \"a\"}]\n\t\t}\n\t`)\n\tgraphWithOneService = ServiceGraph{[]svc.Service{\n\t\t{\n\t\t\tName:        \"a\",\n\t\t\tType:        svctype.ServiceHTTP,\n\t\t\tNumReplicas: 1,\n\t\t},\n\t}}\n\tjsonWithDefaultsAndManyServices = []byte(`\n\t\t{\n\t\t\t\"defaults\": {\n\t\t\t\t\"errorRate\": 0.1,\n\t\t\t\t\"numReplicas\": 2,\n\t\t\t\t\"requestSize\": 516,\n\t\t\t\t\"responseSize\": 128,\n\t\t\t\t\"script\": [\n\t\t\t\t\t{ \"sleep\": \"100ms\" }\n\t\t\t\t]\n\t\t\t},\n\t\t\t\"services\": [\n\t\t\t\t{\n\t\t\t\t\t\"name\": \"a\",\n\t\t\t\t\t\"numReplicas\": 5\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t\"name\": \"b\",\n\t\t\t\t\t\"script\": [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\"call\": {\n\t\t\t\t\t\t\t\t\"service\": \"a\",\n\t\t\t\t\t\t\t\t\"size\": \"1KiB\"\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{ \"sleep\": \"10ms\" }\n\t\t\t\t\t]\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t\"name\": \"c\",\n\t\t\t\t\t\"type\": \"grpc\",\n\t\t\t\t\t\"numReplicas\": 1,\n\t\t\t\t\t\"errorRate\": \"20%\",\n\t\t\t\t\t\"responseSize\": \"1K\",\n\t\t\t\t\t\"script\": [\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t{ \"call\": \"a\" },\n\t\t\t\t\t\t\t{ \"call\": \"b\" }\n\t\t\t\t\t\t],\n\t\t\t\t\t\t{ \"sleep\": \"10ms\" }\n\t\t\t\t\t]\n\t\t\t\t}\n\t\t\t]\n\t\t}\n\t`)\n\tgraphWithDefaultsAndManyServices = ServiceGraph{[]svc.Service{\n\t\t{\n\t\t\tName:         \"a\",\n\t\t\tType:         svctype.ServiceHTTP,\n\t\t\tNumReplicas:  5,\n\t\t\tErrorRate:    0.1,\n\t\t\tResponseSize: 128,\n\t\t\tScript: script.Script([]script.Command{\n\t\t\t\tscript.SleepCommand(100 * time.Millisecond),\n\t\t\t}),\n\t\t},\n\t\t{\n\t\t\tName:         \"b\",\n\t\t\tType:         svctype.ServiceHTTP,\n\t\t\tNumReplicas:  2,\n\t\t\tErrorRate:    0.1,\n\t\t\tResponseSize: 128,\n\t\t\tScript: script.Script([]script.Command{\n\t\t\t\tscript.RequestCommand{ServiceName: \"a\", Size: 1024},\n\t\t\t\tscript.SleepCommand(10 * time.Millisecond),\n\t\t\t}),\n\t\t},\n\t\t{\n\t\t\tName:         \"c\",\n\t\t\tType:         svctype.ServiceGRPC,\n\t\t\tNumReplicas:  1,\n\t\t\tErrorRate:    0.2,\n\t\t\tResponseSize: 1024,\n\t\t\tScript: script.Script([]script.Command{\n\t\t\t\tscript.ConcurrentCommand{\n\t\t\t\t\tscript.RequestCommand{ServiceName: \"a\", Size: 516},\n\t\t\t\t\tscript.RequestCommand{ServiceName: \"b\", Size: 516},\n\t\t\t\t},\n\t\t\t\tscript.SleepCommand(10 * time.Millisecond),\n\t\t\t}),\n\t\t},\n\t}}\n\tjsonWithRequestToUndefinedService = []byte(`\n\t\t{\n\t\t\t\"services\": [\n\t\t\t\t{\n\t\t\t\t\t\"name\": \"a\",\n\t\t\t\t\t\"script\": [{ \"call\": \"b\"}]\n\t\t\t\t}\n\t\t\t]\n\t\t}\n\t`)\n\tjsonWithNestedConcurrentCommand = []byte(`\n\t\t{\n\t\t\t\"services\": [\n\t\t\t\t{\n\t\t\t\t\t\"name\": \"a\"\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t\"name\": \"b\",\n\t\t\t\t\t\"script\": [\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t[{ \"call\": \"a\" }, { \"call\": \"a\" }],\n\t\t\t\t\t\t\t{ \"sleep\": \"10ms\" }\n\t\t\t\t\t\t]\n\t\t\t\t\t]\n\t\t\t\t}\n\t\t\t]\n\t\t}\n\t`)\n)\n<commit_msg>remove reduntant type conversion (#1582)<commit_after>\/\/ Copyright 2018 Istio Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this currentFile except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage graph\n\nimport (\n\t\"encoding\/json\"\n\t\"reflect\"\n\t\"testing\"\n\t\"time\"\n\n\t\"istio.io\/tools\/isotope\/convert\/pkg\/graph\/script\"\n\t\"istio.io\/tools\/isotope\/convert\/pkg\/graph\/svc\"\n\n\t\"istio.io\/tools\/isotope\/convert\/pkg\/graph\/svctype\"\n)\n\nfunc TestServiceGraph_UnmarshalJSON(t *testing.T) {\n\ttests := []struct {\n\t\tinput []byte\n\t\tgraph ServiceGraph\n\t\terr   error\n\t}{\n\t\t{jsonWithOneService, graphWithOneService, nil},\n\t\t{jsonWithDefaultsAndManyServices, graphWithDefaultsAndManyServices, nil},\n\t\t{\n\t\t\tjsonWithRequestToUndefinedService,\n\t\t\tServiceGraph{},\n\t\t\tErrRequestToUndefinedService{\"b\"},\n\t\t},\n\t\t{\n\t\t\tjsonWithNestedConcurrentCommand,\n\t\t\tServiceGraph{},\n\t\t\tErrNestedConcurrentCommand,\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\ttest := test\n\t\tt.Run(\"\", func(t *testing.T) {\n\t\t\tt.Parallel()\n\n\t\t\tvar graph ServiceGraph\n\t\t\terr := json.Unmarshal(test.input, &graph)\n\t\t\tif err == nil {\n\t\t\t\tif !reflect.DeepEqual(test.graph, graph) {\n\t\t\t\t\tt.Errorf(\"expected %v; actual %v\", test.graph, graph)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif test.err != err {\n\t\t\t\t\tt.Errorf(\"expected %v; actual %v\", test.err, err)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nvar (\n\tjsonWithOneService = []byte(`\n\t\t{\n\t\t\t\"services\": [{\"name\": \"a\"}]\n\t\t}\n\t`)\n\tgraphWithOneService = ServiceGraph{[]svc.Service{\n\t\t{\n\t\t\tName:        \"a\",\n\t\t\tType:        svctype.ServiceHTTP,\n\t\t\tNumReplicas: 1,\n\t\t},\n\t}}\n\tjsonWithDefaultsAndManyServices = []byte(`\n\t\t{\n\t\t\t\"defaults\": {\n\t\t\t\t\"errorRate\": 0.1,\n\t\t\t\t\"numReplicas\": 2,\n\t\t\t\t\"requestSize\": 516,\n\t\t\t\t\"responseSize\": 128,\n\t\t\t\t\"script\": [\n\t\t\t\t\t{ \"sleep\": \"100ms\" }\n\t\t\t\t]\n\t\t\t},\n\t\t\t\"services\": [\n\t\t\t\t{\n\t\t\t\t\t\"name\": \"a\",\n\t\t\t\t\t\"numReplicas\": 5\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t\"name\": \"b\",\n\t\t\t\t\t\"script\": [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\"call\": {\n\t\t\t\t\t\t\t\t\"service\": \"a\",\n\t\t\t\t\t\t\t\t\"size\": \"1KiB\"\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{ \"sleep\": \"10ms\" }\n\t\t\t\t\t]\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t\"name\": \"c\",\n\t\t\t\t\t\"type\": \"grpc\",\n\t\t\t\t\t\"numReplicas\": 1,\n\t\t\t\t\t\"errorRate\": \"20%\",\n\t\t\t\t\t\"responseSize\": \"1K\",\n\t\t\t\t\t\"script\": [\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t{ \"call\": \"a\" },\n\t\t\t\t\t\t\t{ \"call\": \"b\" }\n\t\t\t\t\t\t],\n\t\t\t\t\t\t{ \"sleep\": \"10ms\" }\n\t\t\t\t\t]\n\t\t\t\t}\n\t\t\t]\n\t\t}\n\t`)\n\tgraphWithDefaultsAndManyServices = ServiceGraph{[]svc.Service{\n\t\t{\n\t\t\tName:         \"a\",\n\t\t\tType:         svctype.ServiceHTTP,\n\t\t\tNumReplicas:  5,\n\t\t\tErrorRate:    0.1,\n\t\t\tResponseSize: 128,\n\t\t\tScript: script.Script([]script.Command{\n\t\t\t\t100 * time.Millisecond,\n\t\t\t}),\n\t\t},\n\t\t{\n\t\t\tName:         \"b\",\n\t\t\tType:         svctype.ServiceHTTP,\n\t\t\tNumReplicas:  2,\n\t\t\tErrorRate:    0.1,\n\t\t\tResponseSize: 128,\n\t\t\tScript: script.Script([]script.Command{\n\t\t\t\tscript.RequestCommand{ServiceName: \"a\", Size: 1024},\n\t\t\t\t10 * time.Millisecond,\n\t\t\t}),\n\t\t},\n\t\t{\n\t\t\tName:         \"c\",\n\t\t\tType:         svctype.ServiceGRPC,\n\t\t\tNumReplicas:  1,\n\t\t\tErrorRate:    0.2,\n\t\t\tResponseSize: 1024,\n\t\t\tScript: script.Script([]script.Command{\n\t\t\t\tscript.ConcurrentCommand{\n\t\t\t\t\tscript.RequestCommand{ServiceName: \"a\", Size: 516},\n\t\t\t\t\tscript.RequestCommand{ServiceName: \"b\", Size: 516},\n\t\t\t\t},\n\t\t\t\t10 * time.Millisecond,\n\t\t\t}),\n\t\t},\n\t}}\n\tjsonWithRequestToUndefinedService = []byte(`\n\t\t{\n\t\t\t\"services\": [\n\t\t\t\t{\n\t\t\t\t\t\"name\": \"a\",\n\t\t\t\t\t\"script\": [{ \"call\": \"b\"}]\n\t\t\t\t}\n\t\t\t]\n\t\t}\n\t`)\n\tjsonWithNestedConcurrentCommand = []byte(`\n\t\t{\n\t\t\t\"services\": [\n\t\t\t\t{\n\t\t\t\t\t\"name\": \"a\"\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t\"name\": \"b\",\n\t\t\t\t\t\"script\": [\n\t\t\t\t\t\t[\n\t\t\t\t\t\t\t[{ \"call\": \"a\" }, { \"call\": \"a\" }],\n\t\t\t\t\t\t\t{ \"sleep\": \"10ms\" }\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<|endoftext|>"}
{"text":"<commit_before>\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage template\n\nimport (\n\t\"fmt\";\n\t\"io\";\n\t\"os\";\n\t\"reflect\";\n\t\"template\";\n\t\"testing\";\n)\n\ntype Test struct {\n\tin, out string\n}\n\ntype T struct {\n\titem string;\n\tvalue string;\n}\n\ntype S struct {\n\theader string;\n\tinteger int;\n\tdata []T;\n\tpdata []*T;\n\tempty []*T;\n\tnull []*T;\n}\n\nvar t1 = T{ \"ItemNumber1\", \"ValueNumber1\" }\nvar t2 = T{ \"ItemNumber2\", \"ValueNumber2\" }\n\nfunc uppercase(v reflect.Value) string {\n\ts := reflect.Indirect(v).(reflect.StringValue).Get();\n\tt := \"\";\n\tfor i := 0; i < len(s); i++ {\n\t\tc := s[i];\n\t\tif 'a' <= c && c <= 'z' {\n\t\t\tc = c + 'A' - 'a'\n\t\t}\n\t\tt += string(c);\n\t}\n\treturn t;\n}\n\nfunc plus1(v reflect.Value) string {\n\ti := reflect.Indirect(v).(reflect.IntValue).Get();\n\treturn fmt.Sprint(i + 1);\n}\n\nvar formatters = FormatterMap {\n\t\"uppercase\" : uppercase,\n\t\"+1\" : plus1,\n}\n\nvar tests = []*Test {\n\t\/\/ Simple\n\t&Test{ \"\", \"\" },\n\t&Test{ \"abc\\ndef\\n\", \"abc\\ndef\\n\" },\n\t&Test{ \" {.meta-left}   \\n\", \"{\" },\n\t&Test{ \" {.meta-right}   \\n\", \"}\" },\n\t&Test{ \" {.space}   \\n\", \" \" },\n\t&Test{ \"     {#comment}   \\n\", \"\" },\n\n\t\/\/ Section\n\t&Test{\n\t\t\"{.section data }\\n\"\n\t\t\"some text for the section\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"some text for the section\\n\"\n\t},\n\t&Test{\n\t\t\"{.section data }\\n\"\n\t\t\"{header}={integer}\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"Header=77\\n\"\n\t},\n\t&Test{\n\t\t\"{.section pdata }\\n\"\n\t\t\"{header}={integer}\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"Header=77\\n\"\n\t},\n\t&Test{\n\t\t\"{.section pdata }\\n\"\n\t\t\"data present\\n\"\n\t\t\"{.or}\\n\"\n\t\t\"data not present\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"data present\\n\"\n\t},\n\t&Test{\n\t\t\"{.section empty }\\n\"\n\t\t\"data present\\n\"\n\t\t\"{.or}\\n\"\n\t\t\"data not present\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"data not present\\n\"\n\t},\n\t&Test{\n\t\t\"{.section null }\\n\"\n\t\t\"data present\\n\"\n\t\t\"{.or}\\n\"\n\t\t\"data not present\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"data not present\\n\"\n\t},\n\t&Test{\n\t\t\"{.section pdata }\\n\"\n\t\t\"{header}={integer}\\n\"\n\t\t\"{.section @ }\\n\"\n\t\t\"{header}={integer}\\n\"\n\t\t\"{.end}\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"Header=77\\n\"\n\t\t\"Header=77\\n\"\n\t},\n\n\t\/\/ Repeated\n\t&Test{\n\t\t\"{.section pdata }\\n\"\n\t\t\"{.repeated section @ }\\n\"\n\t\t\"{item}={value}\\n\"\n\t\t\"{.end}\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"ItemNumber1=ValueNumber1\\n\"\n\t\t\"ItemNumber2=ValueNumber2\\n\"\n\t},\n\n\t\/\/ Formatters\n\t&Test{\n\t\t\"{.section pdata }\\n\"\n\t\t\"{header|uppercase}={integer|+1}\\n\"\n\t\t\"{header|html}={integer|str}\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"HEADER=78\\n\"\n\t\t\"Header=77\\n\"\n\t},\n}\n\nfunc TestAll(t *testing.T) {\n\ts := new(S);\n\t\/\/ initialized by hand for clarity.\n\ts.header = \"Header\";\n\ts.integer = 77;\n\ts.data = []T{ t1, t2 };\n\ts.pdata = []*T{ &t1, &t2 };\n\ts.empty = []*T{ };\n\ts.null = nil;\n\n\tvar buf io.ByteBuffer;\n\tfor i, test := range tests {\n\t\tbuf.Reset();\n\t\terr := Execute(test.in, s, formatters, &buf);\n\t\tif err != nil {\n\t\t\tt.Error(\"unexpected error:\", err)\n\t\t}\n\t\tif string(buf.Data()) != test.out {\n\t\t\tt.Errorf(\"for %q: expected %q got %q\", test.in, test.out, string(buf.Data()));\n\t\t}\n\t}\n}\n\nfunc TestBadDriverType(t *testing.T) {\n\terr := Execute(\"hi\", \"hello\", nil, os.Stdout);\n\tif err == nil {\n\t\tt.Error(\"failed to detect string as driver type\")\n\t}\n\tvar s S;\n}\n<commit_msg>template bug<commit_after>\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\npackage template\n\nimport (\n\t\"fmt\";\n\t\"io\";\n\t\"os\";\n\t\"reflect\";\n\t\"template\";\n\t\"testing\";\n)\n\ntype Test struct {\n\tin, out string\n}\n\ntype T struct {\n\titem string;\n\tvalue string;\n}\n\ntype S struct {\n\theader string;\n\tinteger int;\n\tdata []T;\n\tpdata []*T;\n\tempty []*T;\n\tnull []*T;\n}\n\nvar t1 = T{ \"ItemNumber1\", \"ValueNumber1\" }\nvar t2 = T{ \"ItemNumber2\", \"ValueNumber2\" }\n\nfunc uppercase(v interface{}) string {\n\ts := v.(string);\n\tt := \"\";\n\tfor i := 0; i < len(s); i++ {\n\t\tc := s[i];\n\t\tif 'a' <= c && c <= 'z' {\n\t\t\tc = c + 'A' - 'a'\n\t\t}\n\t\tt += string(c);\n\t}\n\treturn t;\n}\n\nfunc plus1(v interface{}) string {\n\ti := v.(int);\n\treturn fmt.Sprint(i + 1);\n}\n\nfunc writer(f func(interface{}) string) (func(io.Write, interface{}, string)) {\n\treturn func(w io.Write, v interface{}, format string) {\n\t\tio.WriteString(w, f(v));\n\t}\n}\n\n\nvar formatters = FormatterMap {\n\t\"uppercase\" : writer(uppercase),\n\t\"+1\" : writer(plus1),\n}\n\nvar tests = []*Test {\n\t\/\/ Simple\n\t&Test{ \"\", \"\" },\n\t&Test{ \"abc\\ndef\\n\", \"abc\\ndef\\n\" },\n\t&Test{ \" {.meta-left}   \\n\", \"{\" },\n\t&Test{ \" {.meta-right}   \\n\", \"}\" },\n\t&Test{ \" {.space}   \\n\", \" \" },\n\t&Test{ \"     {#comment}   \\n\", \"\" },\n\n\t\/\/ Section\n\t&Test{\n\t\t\"{.section data }\\n\"\n\t\t\"some text for the section\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"some text for the section\\n\"\n\t},\n\t&Test{\n\t\t\"{.section data }\\n\"\n\t\t\"{header}={integer}\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"Header=77\\n\"\n\t},\n\t&Test{\n\t\t\"{.section pdata }\\n\"\n\t\t\"{header}={integer}\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"Header=77\\n\"\n\t},\n\t&Test{\n\t\t\"{.section pdata }\\n\"\n\t\t\"data present\\n\"\n\t\t\"{.or}\\n\"\n\t\t\"data not present\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"data present\\n\"\n\t},\n\t&Test{\n\t\t\"{.section empty }\\n\"\n\t\t\"data present\\n\"\n\t\t\"{.or}\\n\"\n\t\t\"data not present\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"data not present\\n\"\n\t},\n\t&Test{\n\t\t\"{.section null }\\n\"\n\t\t\"data present\\n\"\n\t\t\"{.or}\\n\"\n\t\t\"data not present\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"data not present\\n\"\n\t},\n\t&Test{\n\t\t\"{.section pdata }\\n\"\n\t\t\"{header}={integer}\\n\"\n\t\t\"{.section @ }\\n\"\n\t\t\"{header}={integer}\\n\"\n\t\t\"{.end}\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"Header=77\\n\"\n\t\t\"Header=77\\n\"\n\t},\n\n\t\/\/ Repeated\n\t&Test{\n\t\t\"{.section pdata }\\n\"\n\t\t\"{.repeated section @ }\\n\"\n\t\t\"{item}={value}\\n\"\n\t\t\"{.end}\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"ItemNumber1=ValueNumber1\\n\"\n\t\t\"ItemNumber2=ValueNumber2\\n\"\n\t},\n\n\t\/\/ Formatters\n\t&Test{\n\t\t\"{.section pdata }\\n\"\n\t\t\"{header|uppercase}={integer|+1}\\n\"\n\t\t\"{header|html}={integer|str}\\n\"\n\t\t\"{.end}\\n\",\n\n\t\t\"HEADER=78\\n\"\n\t\t\"Header=77\\n\"\n\t},\n\t\n\t\/\/ Bugs\n\/\/\t&Test{\n\/\/\t\t\"{.section data}{.end} {header}\\n\",\n\/\/\t\t\n\/\/\t\t\" 77\\n\"\n\/\/\t},\n}\n\nfunc TestAll(t *testing.T) {\n\ts := new(S);\n\t\/\/ initialized by hand for clarity.\n\ts.header = \"Header\";\n\ts.integer = 77;\n\ts.data = []T{ t1, t2 };\n\ts.pdata = []*T{ &t1, &t2 };\n\ts.empty = []*T{ };\n\ts.null = nil;\n\n\tvar buf io.ByteBuffer;\n\tfor i, test := range tests {\n\t\tbuf.Reset();\n\t\terr := Execute(test.in, s, formatters, &buf);\n\t\tif err != nil {\n\t\t\tt.Error(\"unexpected error:\", err)\n\t\t}\n\t\tif string(buf.Data()) != test.out {\n\t\t\tt.Errorf(\"for %q: expected %q got %q\", test.in, test.out, string(buf.Data()));\n\t\t}\n\t}\n}\n\nfunc TestBadDriverType(t *testing.T) {\n\terr := Execute(\"hi\", \"hello\", nil, os.Stdout);\n\tif err == nil {\n\t\tt.Error(\"failed to detect string as driver type\")\n\t}\n\tvar s S;\n}\n<|endoftext|>"}
{"text":"<commit_before>\/\/Package aphcollection contains collection functions for string\n\/\/slices\npackage aphcollection\n\n\/\/ Index returns the index of the first instance of s in slice a, or -1 if s is\n\/\/ not present in a\nfunc Index(a []string, s string) int {\n\tfor i, v := range a {\n\t\tif v == s {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}\n\n\/\/ Contains reports whether s is present in slice a\nfunc Contains(a []string, s string) bool {\n\treturn Index(a, s) >= 0\n}\n\n\/\/ Map applies the given function to each element of a, returning slice of\n\/\/ results\nfunc Map(a []string, fn func(string) string) []string {\n\tsl := make([]string, len(a))\n\tfor i, v := range a {\n\t\tsl[i] = fn(v)\n\t}\n\treturn sl\n}\n<commit_msg>added check for empty slice<commit_after>\/\/Package aphcollection contains collection functions for string\n\/\/slices\npackage aphcollection\n\n\/\/ Index returns the index of the first instance of s in slice a, or -1 if s is\n\/\/ not present in a\nfunc Index(a []string, s string) int {\n\tif len(a) == 0 {\n\t\treturn -1\n\t}\n\tfor i, v := range a {\n\t\tif v == s {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}\n\n\/\/ Contains reports whether s is present in slice a\nfunc Contains(a []string, s string) bool {\n\tif len(a) == 0 {\n\t\treturn false\n\t}\n\treturn Index(a, s) >= 0\n}\n\n\/\/ Map applies the given function to each element of a, returning slice of\n\/\/ results\nfunc Map(a []string, fn func(string) string) []string {\n\tif len(a) == 0 {\n\t\treturn a\n\t}\n\tsl := make([]string, len(a))\n\tfor i, v := range a {\n\t\tsl[i] = fn(v)\n\t}\n\treturn sl\n}\n<|endoftext|>"}
{"text":"<commit_before>\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage simplepush\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"net\/url\"\n\t\"strings\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/mozilla-services\/pushgo\/client\"\n)\n\nfunc newTestHandler(t *testing.T) (*Handler, *Application) {\n\n\ttlogger, _ := NewLogger(&TestLogger{DEBUG, t})\n\n\tmx := &TestMetrics{}\n\tmx.Init(nil, nil)\n\tstore := &NoStore{logger: tlogger, maxChannels: 10}\n\tcount := int32(0)\n\tpping := &NoopPing{}\n\tapp := &Application{\n\t\thostname:           \"test\",\n\t\thost:               \"test\",\n\t\tclientMinPing:      10 * time.Second,\n\t\tclientHelloTimeout: 10 * time.Second,\n\t\tclientMux:          new(sync.RWMutex),\n\t\tpushLongPongs:      true,\n\t\ttokenKey:           []byte(\"\"),\n\t\tmetrics:            mx,\n\t\tclients:            make(map[string]*Client),\n\t\tclientCount:        &count,\n\t\tstore:              store,\n\t\tpropping:           pping,\n\t}\n\tapp.SetLogger(tlogger)\n\tserver := &Serv{}\n\tserver.Init(app, server.ConfigStruct())\n\tapp.SetServer(server)\n\tlocator := &NoLocator{logger: tlogger}\n\trouter := NewBroadcastRouter()\n\trouter.Init(app, router.ConfigStruct())\n\trouter.SetLocator(locator)\n\tapp.SetRouter(router)\n\n\thandler := &Handler{\n\t\tapp:        app,\n\t\tlogger:     tlogger,\n\t\tstore:      store,\n\t\trouter:     router,\n\t\tmetrics:    mx,\n\t\ttokenKey:   app.TokenKey(),\n\t\tmaxDataLen: 140,\n\t\tpropping:   pping,\n\t}\n\treturn handler, app\n}\n\nfunc Test_UpdateHandler(t *testing.T) {\n\tvar err error\n\tuaid := \"deadbeef000000000000000000000000\"\n\tchid := \"decafbad000000000000000000000000\"\n\tdata := \"This is a test of the emergency broadcasting system.\"\n\n\thandler, app := newTestHandler(t)\n\tnoPush := &PushWS{\n\t\tSocket: nil,\n\t\tBorn:   time.Now(),\n\t}\n\tnoPush.SetUAID(uaid)\n\n\tworker := &NoWorker{Socket: noPush,\n\t\tLogger: app.Logger(),\n\t}\n\n\tapp.AddClient(uaid, &Client{\n\t\tWorker(worker),\n\t\tnoPush,\n\t\tuaid})\n\tresp := httptest.NewRecorder()\n\t\/\/ don't bother with encryption right now.\n\tkey, _ := app.Store().IDsToKey(uaid, chid)\n\treq, err := http.NewRequest(\"PUT\",\n\t\tfmt.Sprintf(\"http:\/\/test\/update\/%s\", key),\n\t\tnil)\n\tif req == nil {\n\t\tt.Fatal(\"Update put returned nil\")\n\t}\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treq.Form = make(url.Values)\n\treq.Form.Add(\"version\", \"1\")\n\treq.Form.Add(\"data\", data)\n\ttmux := mux.NewRouter()\n\n\t\/\/ Yay! Actually try the test!\n\ttmux.HandleFunc(\"\/update\/{key}\", handler.UpdateHandler)\n\ttmux.ServeHTTP(resp, req)\n\tif resp.Body.String() != \"{}\" {\n\t\tt.Error(\"Unexpected response from server\")\n\t}\n\trep := FlushData{}\n\tif err = json.Unmarshal(worker.Outbuffer, &rep); err != nil {\n\t\tt.Errorf(\"Could not read output buffer %s\", err.Error())\n\t}\n\tif rep.Data != data {\n\t\tt.Error(\"Returned data does not match expected value\")\n\t}\n\tif rep.Version != 1 {\n\t\tt.Error(\"Returned version does not match expected value\")\n\t}\n}\n\nfunc endpointIds(uri *url.URL) (deviceId, channelId string, ok bool) {\n\tif !uri.IsAbs() {\n\t\tok = false\n\t\treturn\n\t}\n\tpathPrefix := \"\/update\/\"\n\ti := strings.Index(uri.Path, pathPrefix)\n\tif i < 0 {\n\t\tok = false\n\t\treturn\n\t}\n\tkey := strings.SplitN(uri.Path[i+len(pathPrefix):], \".\", 2)\n\tif len(key) < 2 {\n\t\tok = false\n\t\treturn\n\t}\n\treturn key[0], key[1], true\n}\n\nfunc TestBadKey(t *testing.T) {\n\torigin, err := Server.Origin()\n\tif err != nil {\n\t\tt.Fatalf(\"Error initializing test server: %#v\", err)\n\t}\n\tconn, deviceId, err := client.Dial(origin)\n\tif err != nil {\n\t\tt.Fatalf(\"Error dialing origin: %#v\", err)\n\t}\n\tdefer conn.Close()\n\tchannelId, endpoint, err := conn.Subscribe()\n\tif err != nil {\n\t\tt.Fatalf(\"Error subscribing to channel: %#v\", err)\n\t}\n\turi, err := url.ParseRequestURI(endpoint)\n\tif err != nil {\n\t\tt.Fatalf(\"Error parsing push endpoint %#v: %#v\", endpoint, err)\n\t}\n\tkeyDevice, keyChannel, ok := endpointIds(uri)\n\tif !ok {\n\t\tt.Errorf(\"Incomplete push endpoint: %#v\", endpoint)\n\t}\n\tif keyDevice != deviceId {\n\t\tt.Errorf(\"Mismatched device IDs: got %#v; want %#v\", keyDevice, deviceId)\n\t}\n\tif keyChannel != channelId {\n\t\tt.Errorf(\"Mismatched channel IDs: got %#v; want %#v\", keyChannel, channelId)\n\t}\n\tnewURI, _ := uri.Parse(fmt.Sprintf(\"\/update\/%s\", keyDevice))\n\terr = client.Notify(newURI.String(), 1)\n\tclientErr, ok := err.(client.Error)\n\tif !ok {\n\t\tt.Errorf(\"Type assertion failed for endpoint error: %#v\", err)\n\t} else if clientErr.Status() != 404 {\n\t\tt.Errorf(\"Unexpected endpoint status: got %#v; want 404\", clientErr.Status())\n\t}\n}\n\nfunc TestMissingKey(t *testing.T) {\n\torigin, err := Server.Origin()\n\tif err != nil {\n\t\tt.Fatalf(\"Error initializing test server: %#v\", err)\n\t}\n\tconn, deviceId, err := client.Dial(origin)\n\tif err != nil {\n\t\tt.Fatalf(\"Error dialing origin: %#v\", err)\n\t}\n\tdefer conn.Close()\n\tchannelId, endpoint, err := conn.Subscribe()\n\tif err != nil {\n\t\tt.Fatalf(\"Error subscribing to channel: %#v\", err)\n\t}\n\turi, err := url.ParseRequestURI(endpoint)\n\tif err != nil {\n\t\tt.Fatalf(\"Error parsing push endpoint %#v: %#v\", endpoint, err)\n\t}\n\tkeyDevice, keyChannel, ok := endpointIds(uri)\n\tif !ok {\n\t\tt.Errorf(\"Incomplete push endpoint: %#v\", endpoint)\n\t}\n\tif keyDevice != deviceId {\n\t\tt.Errorf(\"Mismatched device IDs: got %#v; want %#v\", keyDevice, deviceId)\n\t}\n\tif keyChannel != channelId {\n\t\tt.Errorf(\"Mismatched channel IDs: got %#v; want %#v\", keyChannel, channelId)\n\t}\n\tnewURI, _ := uri.Parse(fmt.Sprintf(\"\/update\/%s.\", keyDevice))\n\terr = client.Notify(newURI.String(), 1)\n\tclientErr, ok := err.(client.Error)\n\tif !ok {\n\t\tt.Errorf(\"Type assertion failed for endpoint error: %#v\", err)\n\t} else if clientErr.Status() != 404 {\n\t\tt.Errorf(\"Unexpected endpoint status: got %#v; want 404\", clientErr.Status())\n\t}\n}\n<commit_msg>Add test for empty Content-Type header<commit_after>\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\npackage simplepush\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"net\/url\"\n\t\"strings\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/mozilla-services\/pushgo\/client\"\n)\n\nfunc newTestHandler(t *testing.T) (*Handler, *Application) {\n\n\ttlogger, _ := NewLogger(&TestLogger{DEBUG, t})\n\n\tmx := &TestMetrics{}\n\tmx.Init(nil, nil)\n\tstore := &NoStore{logger: tlogger, maxChannels: 10}\n\tcount := int32(0)\n\tpping := &NoopPing{}\n\tapp := &Application{\n\t\thostname:           \"test\",\n\t\thost:               \"test\",\n\t\tclientMinPing:      10 * time.Second,\n\t\tclientHelloTimeout: 10 * time.Second,\n\t\tclientMux:          new(sync.RWMutex),\n\t\tpushLongPongs:      true,\n\t\ttokenKey:           []byte(\"\"),\n\t\tmetrics:            mx,\n\t\tclients:            make(map[string]*Client),\n\t\tclientCount:        &count,\n\t\tstore:              store,\n\t\tpropping:           pping,\n\t}\n\tapp.SetLogger(tlogger)\n\tserver := &Serv{}\n\tserver.Init(app, server.ConfigStruct())\n\tapp.SetServer(server)\n\tlocator := &NoLocator{logger: tlogger}\n\trouter := NewBroadcastRouter()\n\trouter.Init(app, router.ConfigStruct())\n\trouter.SetLocator(locator)\n\tapp.SetRouter(router)\n\n\thandler := &Handler{\n\t\tapp:        app,\n\t\tlogger:     tlogger,\n\t\tstore:      store,\n\t\trouter:     router,\n\t\tmetrics:    mx,\n\t\ttokenKey:   app.TokenKey(),\n\t\tmaxDataLen: 140,\n\t\tpropping:   pping,\n\t}\n\treturn handler, app\n}\n\nfunc Test_UpdateHandler(t *testing.T) {\n\tvar err error\n\tuaid := \"deadbeef000000000000000000000000\"\n\tchid := \"decafbad000000000000000000000000\"\n\tdata := \"This is a test of the emergency broadcasting system.\"\n\n\thandler, app := newTestHandler(t)\n\tnoPush := &PushWS{\n\t\tSocket: nil,\n\t\tBorn:   time.Now(),\n\t}\n\tnoPush.SetUAID(uaid)\n\n\tworker := &NoWorker{Socket: noPush,\n\t\tLogger: app.Logger(),\n\t}\n\n\tapp.AddClient(uaid, &Client{\n\t\tWorker(worker),\n\t\tnoPush,\n\t\tuaid})\n\tresp := httptest.NewRecorder()\n\t\/\/ don't bother with encryption right now.\n\tkey, _ := app.Store().IDsToKey(uaid, chid)\n\treq, err := http.NewRequest(\"PUT\",\n\t\tfmt.Sprintf(\"http:\/\/test\/update\/%s\", key),\n\t\tnil)\n\tif req == nil {\n\t\tt.Fatal(\"Update put returned nil\")\n\t}\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treq.Form = make(url.Values)\n\treq.Form.Add(\"version\", \"1\")\n\treq.Form.Add(\"data\", data)\n\ttmux := mux.NewRouter()\n\n\t\/\/ Yay! Actually try the test!\n\ttmux.HandleFunc(\"\/update\/{key}\", handler.UpdateHandler)\n\ttmux.ServeHTTP(resp, req)\n\tif resp.Body.String() != \"{}\" {\n\t\tt.Error(\"Unexpected response from server\")\n\t}\n\trep := FlushData{}\n\tif err = json.Unmarshal(worker.Outbuffer, &rep); err != nil {\n\t\tt.Errorf(\"Could not read output buffer %s\", err.Error())\n\t}\n\tif rep.Data != data {\n\t\tt.Error(\"Returned data does not match expected value\")\n\t}\n\tif rep.Version != 1 {\n\t\tt.Error(\"Returned version does not match expected value\")\n\t}\n\n\t\/\/retry without a Content-Type header\n\tresp = httptest.NewRecorder()\n\treq.Header.Set(\"Content-Type\", \"\")\n\ttmux.ServeHTTP(resp, req)\n\tif resp.Body.String() != \"{}\" {\n\t\tt.Error(\"Unexpected response from server\")\n\t}\n\trep = FlushData{}\n\tif err = json.Unmarshal(worker.Outbuffer, &rep); err != nil {\n\t\tt.Errorf(\"Could not read output buffer %s\", err.Error())\n\t}\n\tif rep.Data != data {\n\t\tt.Error(\"Returned data does not match expected value\")\n\t}\n\tif rep.Version != 1 {\n\t\tt.Error(\"Returned version does not match expected value\")\n\t}\n\n}\n\nfunc endpointIds(uri *url.URL) (deviceId, channelId string, ok bool) {\n\tif !uri.IsAbs() {\n\t\tok = false\n\t\treturn\n\t}\n\tpathPrefix := \"\/update\/\"\n\ti := strings.Index(uri.Path, pathPrefix)\n\tif i < 0 {\n\t\tok = false\n\t\treturn\n\t}\n\tkey := strings.SplitN(uri.Path[i+len(pathPrefix):], \".\", 2)\n\tif len(key) < 2 {\n\t\tok = false\n\t\treturn\n\t}\n\treturn key[0], key[1], true\n}\n\nfunc TestBadKey(t *testing.T) {\n\torigin, err := Server.Origin()\n\tif err != nil {\n\t\tt.Fatalf(\"Error initializing test server: %#v\", err)\n\t}\n\tconn, deviceId, err := client.Dial(origin)\n\tif err != nil {\n\t\tt.Fatalf(\"Error dialing origin: %#v\", err)\n\t}\n\tdefer conn.Close()\n\tchannelId, endpoint, err := conn.Subscribe()\n\tif err != nil {\n\t\tt.Fatalf(\"Error subscribing to channel: %#v\", err)\n\t}\n\turi, err := url.ParseRequestURI(endpoint)\n\tif err != nil {\n\t\tt.Fatalf(\"Error parsing push endpoint %#v: %#v\", endpoint, err)\n\t}\n\tkeyDevice, keyChannel, ok := endpointIds(uri)\n\tif !ok {\n\t\tt.Errorf(\"Incomplete push endpoint: %#v\", endpoint)\n\t}\n\tif keyDevice != deviceId {\n\t\tt.Errorf(\"Mismatched device IDs: got %#v; want %#v\", keyDevice, deviceId)\n\t}\n\tif keyChannel != channelId {\n\t\tt.Errorf(\"Mismatched channel IDs: got %#v; want %#v\", keyChannel, channelId)\n\t}\n\tnewURI, _ := uri.Parse(fmt.Sprintf(\"\/update\/%s\", keyDevice))\n\terr = client.Notify(newURI.String(), 1)\n\tclientErr, ok := err.(client.Error)\n\tif !ok {\n\t\tt.Errorf(\"Type assertion failed for endpoint error: %#v\", err)\n\t} else if clientErr.Status() != 404 {\n\t\tt.Errorf(\"Unexpected endpoint status: got %#v; want 404\", clientErr.Status())\n\t}\n}\n\nfunc TestMissingKey(t *testing.T) {\n\torigin, err := Server.Origin()\n\tif err != nil {\n\t\tt.Fatalf(\"Error initializing test server: %#v\", err)\n\t}\n\tconn, deviceId, err := client.Dial(origin)\n\tif err != nil {\n\t\tt.Fatalf(\"Error dialing origin: %#v\", err)\n\t}\n\tdefer conn.Close()\n\tchannelId, endpoint, err := conn.Subscribe()\n\tif err != nil {\n\t\tt.Fatalf(\"Error subscribing to channel: %#v\", err)\n\t}\n\turi, err := url.ParseRequestURI(endpoint)\n\tif err != nil {\n\t\tt.Fatalf(\"Error parsing push endpoint %#v: %#v\", endpoint, err)\n\t}\n\tkeyDevice, keyChannel, ok := endpointIds(uri)\n\tif !ok {\n\t\tt.Errorf(\"Incomplete push endpoint: %#v\", endpoint)\n\t}\n\tif keyDevice != deviceId {\n\t\tt.Errorf(\"Mismatched device IDs: got %#v; want %#v\", keyDevice, deviceId)\n\t}\n\tif keyChannel != channelId {\n\t\tt.Errorf(\"Mismatched channel IDs: got %#v; want %#v\", keyChannel, channelId)\n\t}\n\tnewURI, _ := uri.Parse(fmt.Sprintf(\"\/update\/%s.\", keyDevice))\n\terr = client.Notify(newURI.String(), 1)\n\tclientErr, ok := err.(client.Error)\n\tif !ok {\n\t\tt.Errorf(\"Type assertion failed for endpoint error: %#v\", err)\n\t} else if clientErr.Status() != 404 {\n\t\tt.Errorf(\"Unexpected endpoint status: got %#v; want 404\", clientErr.Status())\n\t}\n}\n<|endoftext|>"}
{"text":"<commit_before>package aws\n\nimport (\n\t\"fmt\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/s3\"\n\t\"github.com\/qiniu\/qshell\/v2\/iqshell\"\n\t\"github.com\/qiniu\/qshell\/v2\/iqshell\/common\/alert\"\n\t\"github.com\/qiniu\/qshell\/v2\/iqshell\/common\/data\"\n\t\"github.com\/qiniu\/qshell\/v2\/iqshell\/common\/export\"\n\t\"github.com\/qiniu\/qshell\/v2\/iqshell\/common\/flow\"\n\t\"github.com\/qiniu\/qshell\/v2\/iqshell\/common\/log\"\n\t\"github.com\/qiniu\/qshell\/v2\/iqshell\/common\/utils\"\n\t\"github.com\/qiniu\/qshell\/v2\/iqshell\/common\/workspace\"\n\t\"github.com\/qiniu\/qshell\/v2\/iqshell\/storage\/object\"\n\t\"github.com\/qiniu\/qshell\/v2\/iqshell\/storage\/object\/batch\"\n\t\"path\/filepath\"\n\t\"time\"\n)\n\ntype FetchInfo struct {\n\tQiniuBucket   string\n\tHost          string\n\tBatchInfo     batch.Info\n\tAwsBucketInfo ListBucketInfo\n}\n\nfunc (info *FetchInfo) Check() *data.CodeError {\n\t\/\/ check AWS bucket\n\tif info.AwsBucketInfo.Bucket == \"\" {\n\t\treturn alert.CannotEmptyError(\"AWS bucket\", \"\")\n\t}\n\n\t\/\/ check AWS region\n\tif info.AwsBucketInfo.Region == \"\" {\n\t\treturn alert.CannotEmptyError(\"AWS region\", \"\")\n\t}\n\n\t\/\/ check AWS region\n\tif info.QiniuBucket == \"\" {\n\t\treturn alert.CannotEmptyError(\"Qiniu bucket\", \"\")\n\t}\n\n\tif info.AwsBucketInfo.Id == \"\" || info.AwsBucketInfo.SecretKey == \"\" {\n\t\treturn alert.CannotEmptyError(\"AWS ID and SecretKey\", \"\")\n\t}\n\n\tif info.BatchInfo.WorkerCount <= 0 || info.BatchInfo.WorkerCount >= 1000 {\n\t\tinfo.BatchInfo.WorkerCount = 20\n\t}\n\n\treturn nil\n}\n\nfunc Fetch(cfg *iqshell.Config, info FetchInfo) {\n\tcfg.JobPathBuilder = func(cmdPath string) string {\n\t\tjobId := utils.Md5Hex(fmt.Sprintf(\"%s:%s:%s:%s\", cfg.CmdCfg.CmdId, info.AwsBucketInfo.Region, info.AwsBucketInfo.Bucket, info.QiniuBucket))\n\t\treturn filepath.Join(cmdPath, jobId)\n\t}\n\tif shouldContinue := iqshell.CheckAndLoad(cfg, iqshell.CheckAndLoadInfo{\n\t\tChecker: &info,\n\t}); !shouldContinue {\n\t\treturn\n\t}\n\n\texporter, err := export.NewFileExport(export.FileExporterConfig{\n\t\tSuccessExportFilePath:   info.BatchInfo.SuccessExportFilePath,\n\t\tFailExportFilePath:      info.BatchInfo.FailExportFilePath,\n\t\tOverwriteExportFilePath: info.BatchInfo.OverwriteExportFilePath,\n\t})\n\n\tif err != nil {\n\t\tlog.ErrorF(\"get export error:%v\", err)\n\t\treturn\n\t}\n\n\tfetchInfoChan := make(chan flow.Work, info.BatchInfo.WorkerCount)\n\t\/\/ 生产者\n\tgo func() {\n\t\tif e := listBucket(info.AwsBucketInfo, func(svc *s3.S3, obj *s3.Object) {\n\t\t\treq, _ := svc.GetObjectRequest(&s3.GetObjectInput{\n\t\t\t\tBucket: aws.String(info.AwsBucketInfo.Bucket),\n\t\t\t\tKey:    obj.Key,\n\t\t\t})\n\t\t\tif downloadUrl, e := req.Presign(5 * 3600 * time.Second); e == nil {\n\t\t\t\tfetchInfoChan <- &object.FetchApiInfo{\n\t\t\t\t\tBucket:  info.QiniuBucket,\n\t\t\t\t\tKey:     *obj.Key,\n\t\t\t\t\tFromUrl: downloadUrl,\n\t\t\t\t}\n\t\t\t\tlog.DebugF(\"get object:%s\\t%d\\t%s\\t%s\\n%s\", *obj.Key, *obj.Size, *obj.ETag, *obj.LastModified, downloadUrl)\n\t\t\t} else {\n\t\t\t\tlog.ErrorF(\"fetch([%s:%s]) create download url error: %v\", info.AwsBucketInfo.Bucket, *obj.Key, e)\n\t\t\t}\n\t\t}); e != nil {\n\t\t\tlog.Error(e)\n\t\t}\n\t\tclose(fetchInfoChan)\n\t}()\n\t\n\tvar overseer flow.Overseer\n\tif info.BatchInfo.EnableRecord {\n\t\tdbPath := filepath.Join(workspace.GetJobDir(), \".recorder\")\n\t\tlog.DebugF(\"aws batch fetch recorder:%s\", dbPath)\n\t\tif overseer, err = flow.NewDBRecordOverseer(dbPath, func() *flow.WorkRecord {\n\t\t\treturn &flow.WorkRecord{\n\t\t\t\tWorkInfo: &flow.WorkInfo{\n\t\t\t\t\tData: \"\",\n\t\t\t\t\tWork: nil,\n\t\t\t\t},\n\t\t\t\tResult: &object.FetchResult{},\n\t\t\t\tErr:    nil,\n\t\t\t}\n\t\t}); err != nil {\n\t\t\tlog.ErrorF(\"aws batch fetch create overseer error:%v\", err)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tlog.Debug(\"aws batch fetch recorder:Not Enable\")\n\t}\n\n\tmetric := &batch.Metric{}\n\tmetric.Start()\n\tflow.New(info.BatchInfo.Info).\n\t\tWorkProviderWithChan(fetchInfoChan).\n\t\tWorkerProvider(flow.NewWorkerProvider(func() (flow.Worker, *data.CodeError) {\n\t\t\treturn flow.NewSimpleWorker(func(workInfo *flow.WorkInfo) (flow.Result, *data.CodeError) {\n\t\t\t\tin := workInfo.Work.(*object.FetchApiInfo)\n\t\t\t\treturn object.Fetch(*in)\n\t\t\t}), nil\n\t\t})).\n\t\tFlowWillStartFunc(func(flow *flow.Flow) (err *data.CodeError) {\n\t\t\tmetric.AddTotalCount(flow.WorkProvider.WorkTotalCount())\n\t\t\treturn nil\n\t\t}).\n\t\tSetOverseer(overseer).\n\t\tShouldRedo(func(workInfo *flow.WorkInfo, workRecord *flow.WorkRecord) (shouldRedo bool, cause *data.CodeError) {\n\t\t\tif workRecord.Err == nil {\n\t\t\t\treturn false, nil\n\t\t\t}\n\n\t\t\tif !info.BatchInfo.RecordRedoWhileError {\n\t\t\t\treturn false, workRecord.Err\n\t\t\t}\n\n\t\t\tresult, _ := workRecord.Result.(*object.FetchResult)\n\t\t\tif result == nil {\n\t\t\t\treturn true, data.NewEmptyError().AppendDesc(\"no result found\")\n\t\t\t}\n\t\t\tif !result.IsValid() {\n\t\t\t\treturn true, data.NewEmptyError().AppendDesc(\"result is invalid\")\n\t\t\t}\n\t\t\treturn false, nil\n\t\t}).\n\t\tOnWorkSkip(func(work *flow.WorkInfo, result flow.Result, err *data.CodeError) {\n\t\t\tmetric.AddCurrentCount(1)\n\t\t\tmetric.PrintProgress(\"Batching:\" + work.Data)\n\n\t\t\toperationResult, _ := result.(*object.FetchResult)\n\t\t\tif err != nil && err.Code == data.ErrorCodeAlreadyDone {\n\t\t\t\tif operationResult != nil && operationResult.IsValid() {\n\t\t\t\t\tmetric.AddSuccessCount(1)\n\t\t\t\t\tlog.DebugF(\"Skip line:%s because have done and success\", work.Data)\n\t\t\t\t} else {\n\t\t\t\t\tmetric.AddFailureCount(1)\n\t\t\t\t\tlog.DebugF(\"Skip line:%s because have done and failure, %v\", work.Data, err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tmetric.AddSkippedCount(1)\n\t\t\t\texporter.Fail().ExportF(\"%s%s%v\", work.Data, flow.ErrorSeparate, err)\n\t\t\t\tlog.DebugF(\"Skip line:%s because:%v\", work.Data, err)\n\t\t\t}\n\n\t\t}).\n\t\tOnWorkSuccess(func(workInfo *flow.WorkInfo, result flow.Result) {\n\t\t\tmetric.AddCurrentCount(1)\n\t\t\tmetric.AddSuccessCount(1)\n\t\t\tmetric.PrintProgress(\"Batching:\" + workInfo.Data)\n\n\t\t\tin, _ := workInfo.Work.(*object.FetchApiInfo)\n\t\t\texporter.Success().ExportF(\"%s\\t%s\", in.FromUrl, in.Bucket)\n\t\t\tlog.InfoF(\"AWS Fetch Success, '%s' => [%s:%s]\", in.FromUrl, in.Bucket, in.Key)\n\t\t}).\n\t\tOnWorkFail(func(workInfo *flow.WorkInfo, err *data.CodeError) {\n\t\t\tmetric.AddCurrentCount(1)\n\t\t\tmetric.AddFailureCount(1)\n\t\t\tmetric.PrintProgress(\"AWS Batching:\" + workInfo.Data)\n\n\t\t\texporter.Fail().ExportF(\"%s%s%v\", workInfo.Data, flow.ErrorSeparate, err)\n\t\t\tif in, ok := workInfo.Work.(*object.FetchApiInfo); ok {\n\t\t\t\tlog.ErrorF(\"AWS Fetch Failed, '%s' => [%s:%s], Error: %v\", in.FromUrl, in.Bucket, in.Key, err)\n\t\t\t} else {\n\t\t\t\tlog.ErrorF(\"AWS Fetch Failed, %s, Error: %s\", workInfo.Data, err)\n\t\t\t}\n\t\t}).Build().Start()\n\n\tmetric.End()\n\tif metric.TotalCount <= 0 {\n\t\tmetric.TotalCount = metric.SuccessCount + metric.FailureCount + metric.SkippedCount\n\t}\n\n\t\/\/ 输出结果\n\tresultPath := filepath.Join(workspace.GetJobDir(), \".result\")\n\tif e := utils.MarshalToFile(resultPath, metric); e != nil {\n\t\tlog.ErrorF(\"save aws batch fetch result to path:%s error:%v\", resultPath, e)\n\t} else {\n\t\tlog.DebugF(\"save aws batch fetch result to path:%s\", resultPath)\n\t}\n\n\tlog.Info(\"------------- AWS Batch Result --------------\")\n\tlog.InfoF(\"%20s%10d\", \"Total:\", metric.TotalCount)\n\tlog.InfoF(\"%20s%10d\", \"Success:\", metric.SuccessCount)\n\tlog.InfoF(\"%20s%10d\", \"Failure:\", metric.FailureCount)\n\tlog.InfoF(\"%20s%10d\", \"Skipped:\", metric.SkippedCount)\n\tlog.InfoF(\"%20s%10ds\", \"Duration:\", metric.Duration)\n\tlog.InfoF(\"--------------------------------------------\")\n}\n<commit_msg>gofmt<commit_after>package aws\n\nimport (\n\t\"fmt\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/s3\"\n\t\"github.com\/qiniu\/qshell\/v2\/iqshell\"\n\t\"github.com\/qiniu\/qshell\/v2\/iqshell\/common\/alert\"\n\t\"github.com\/qiniu\/qshell\/v2\/iqshell\/common\/data\"\n\t\"github.com\/qiniu\/qshell\/v2\/iqshell\/common\/export\"\n\t\"github.com\/qiniu\/qshell\/v2\/iqshell\/common\/flow\"\n\t\"github.com\/qiniu\/qshell\/v2\/iqshell\/common\/log\"\n\t\"github.com\/qiniu\/qshell\/v2\/iqshell\/common\/utils\"\n\t\"github.com\/qiniu\/qshell\/v2\/iqshell\/common\/workspace\"\n\t\"github.com\/qiniu\/qshell\/v2\/iqshell\/storage\/object\"\n\t\"github.com\/qiniu\/qshell\/v2\/iqshell\/storage\/object\/batch\"\n\t\"path\/filepath\"\n\t\"time\"\n)\n\ntype FetchInfo struct {\n\tQiniuBucket   string\n\tHost          string\n\tBatchInfo     batch.Info\n\tAwsBucketInfo ListBucketInfo\n}\n\nfunc (info *FetchInfo) Check() *data.CodeError {\n\t\/\/ check AWS bucket\n\tif info.AwsBucketInfo.Bucket == \"\" {\n\t\treturn alert.CannotEmptyError(\"AWS bucket\", \"\")\n\t}\n\n\t\/\/ check AWS region\n\tif info.AwsBucketInfo.Region == \"\" {\n\t\treturn alert.CannotEmptyError(\"AWS region\", \"\")\n\t}\n\n\t\/\/ check AWS region\n\tif info.QiniuBucket == \"\" {\n\t\treturn alert.CannotEmptyError(\"Qiniu bucket\", \"\")\n\t}\n\n\tif info.AwsBucketInfo.Id == \"\" || info.AwsBucketInfo.SecretKey == \"\" {\n\t\treturn alert.CannotEmptyError(\"AWS ID and SecretKey\", \"\")\n\t}\n\n\tif info.BatchInfo.WorkerCount <= 0 || info.BatchInfo.WorkerCount >= 1000 {\n\t\tinfo.BatchInfo.WorkerCount = 20\n\t}\n\n\treturn nil\n}\n\nfunc Fetch(cfg *iqshell.Config, info FetchInfo) {\n\tcfg.JobPathBuilder = func(cmdPath string) string {\n\t\tjobId := utils.Md5Hex(fmt.Sprintf(\"%s:%s:%s:%s\", cfg.CmdCfg.CmdId, info.AwsBucketInfo.Region, info.AwsBucketInfo.Bucket, info.QiniuBucket))\n\t\treturn filepath.Join(cmdPath, jobId)\n\t}\n\tif shouldContinue := iqshell.CheckAndLoad(cfg, iqshell.CheckAndLoadInfo{\n\t\tChecker: &info,\n\t}); !shouldContinue {\n\t\treturn\n\t}\n\n\texporter, err := export.NewFileExport(export.FileExporterConfig{\n\t\tSuccessExportFilePath:   info.BatchInfo.SuccessExportFilePath,\n\t\tFailExportFilePath:      info.BatchInfo.FailExportFilePath,\n\t\tOverwriteExportFilePath: info.BatchInfo.OverwriteExportFilePath,\n\t})\n\n\tif err != nil {\n\t\tlog.ErrorF(\"get export error:%v\", err)\n\t\treturn\n\t}\n\n\tfetchInfoChan := make(chan flow.Work, info.BatchInfo.WorkerCount)\n\t\/\/ 生产者\n\tgo func() {\n\t\tif e := listBucket(info.AwsBucketInfo, func(svc *s3.S3, obj *s3.Object) {\n\t\t\treq, _ := svc.GetObjectRequest(&s3.GetObjectInput{\n\t\t\t\tBucket: aws.String(info.AwsBucketInfo.Bucket),\n\t\t\t\tKey:    obj.Key,\n\t\t\t})\n\t\t\tif downloadUrl, e := req.Presign(5 * 3600 * time.Second); e == nil {\n\t\t\t\tfetchInfoChan <- &object.FetchApiInfo{\n\t\t\t\t\tBucket:  info.QiniuBucket,\n\t\t\t\t\tKey:     *obj.Key,\n\t\t\t\t\tFromUrl: downloadUrl,\n\t\t\t\t}\n\t\t\t\tlog.DebugF(\"get object:%s\\t%d\\t%s\\t%s\\n%s\", *obj.Key, *obj.Size, *obj.ETag, *obj.LastModified, downloadUrl)\n\t\t\t} else {\n\t\t\t\tlog.ErrorF(\"fetch([%s:%s]) create download url error: %v\", info.AwsBucketInfo.Bucket, *obj.Key, e)\n\t\t\t}\n\t\t}); e != nil {\n\t\t\tlog.Error(e)\n\t\t}\n\t\tclose(fetchInfoChan)\n\t}()\n\n\tvar overseer flow.Overseer\n\tif info.BatchInfo.EnableRecord {\n\t\tdbPath := filepath.Join(workspace.GetJobDir(), \".recorder\")\n\t\tlog.DebugF(\"aws batch fetch recorder:%s\", dbPath)\n\t\tif overseer, err = flow.NewDBRecordOverseer(dbPath, func() *flow.WorkRecord {\n\t\t\treturn &flow.WorkRecord{\n\t\t\t\tWorkInfo: &flow.WorkInfo{\n\t\t\t\t\tData: \"\",\n\t\t\t\t\tWork: nil,\n\t\t\t\t},\n\t\t\t\tResult: &object.FetchResult{},\n\t\t\t\tErr:    nil,\n\t\t\t}\n\t\t}); err != nil {\n\t\t\tlog.ErrorF(\"aws batch fetch create overseer error:%v\", err)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tlog.Debug(\"aws batch fetch recorder:Not Enable\")\n\t}\n\n\tmetric := &batch.Metric{}\n\tmetric.Start()\n\tflow.New(info.BatchInfo.Info).\n\t\tWorkProviderWithChan(fetchInfoChan).\n\t\tWorkerProvider(flow.NewWorkerProvider(func() (flow.Worker, *data.CodeError) {\n\t\t\treturn flow.NewSimpleWorker(func(workInfo *flow.WorkInfo) (flow.Result, *data.CodeError) {\n\t\t\t\tin := workInfo.Work.(*object.FetchApiInfo)\n\t\t\t\treturn object.Fetch(*in)\n\t\t\t}), nil\n\t\t})).\n\t\tFlowWillStartFunc(func(flow *flow.Flow) (err *data.CodeError) {\n\t\t\tmetric.AddTotalCount(flow.WorkProvider.WorkTotalCount())\n\t\t\treturn nil\n\t\t}).\n\t\tSetOverseer(overseer).\n\t\tShouldRedo(func(workInfo *flow.WorkInfo, workRecord *flow.WorkRecord) (shouldRedo bool, cause *data.CodeError) {\n\t\t\tif workRecord.Err == nil {\n\t\t\t\treturn false, nil\n\t\t\t}\n\n\t\t\tif !info.BatchInfo.RecordRedoWhileError {\n\t\t\t\treturn false, workRecord.Err\n\t\t\t}\n\n\t\t\tresult, _ := workRecord.Result.(*object.FetchResult)\n\t\t\tif result == nil {\n\t\t\t\treturn true, data.NewEmptyError().AppendDesc(\"no result found\")\n\t\t\t}\n\t\t\tif !result.IsValid() {\n\t\t\t\treturn true, data.NewEmptyError().AppendDesc(\"result is invalid\")\n\t\t\t}\n\t\t\treturn false, nil\n\t\t}).\n\t\tOnWorkSkip(func(work *flow.WorkInfo, result flow.Result, err *data.CodeError) {\n\t\t\tmetric.AddCurrentCount(1)\n\t\t\tmetric.PrintProgress(\"Batching:\" + work.Data)\n\n\t\t\toperationResult, _ := result.(*object.FetchResult)\n\t\t\tif err != nil && err.Code == data.ErrorCodeAlreadyDone {\n\t\t\t\tif operationResult != nil && operationResult.IsValid() {\n\t\t\t\t\tmetric.AddSuccessCount(1)\n\t\t\t\t\tlog.DebugF(\"Skip line:%s because have done and success\", work.Data)\n\t\t\t\t} else {\n\t\t\t\t\tmetric.AddFailureCount(1)\n\t\t\t\t\tlog.DebugF(\"Skip line:%s because have done and failure, %v\", work.Data, err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tmetric.AddSkippedCount(1)\n\t\t\t\texporter.Fail().ExportF(\"%s%s%v\", work.Data, flow.ErrorSeparate, err)\n\t\t\t\tlog.DebugF(\"Skip line:%s because:%v\", work.Data, err)\n\t\t\t}\n\n\t\t}).\n\t\tOnWorkSuccess(func(workInfo *flow.WorkInfo, result flow.Result) {\n\t\t\tmetric.AddCurrentCount(1)\n\t\t\tmetric.AddSuccessCount(1)\n\t\t\tmetric.PrintProgress(\"Batching:\" + workInfo.Data)\n\n\t\t\tin, _ := workInfo.Work.(*object.FetchApiInfo)\n\t\t\texporter.Success().ExportF(\"%s\\t%s\", in.FromUrl, in.Bucket)\n\t\t\tlog.InfoF(\"AWS Fetch Success, '%s' => [%s:%s]\", in.FromUrl, in.Bucket, in.Key)\n\t\t}).\n\t\tOnWorkFail(func(workInfo *flow.WorkInfo, err *data.CodeError) {\n\t\t\tmetric.AddCurrentCount(1)\n\t\t\tmetric.AddFailureCount(1)\n\t\t\tmetric.PrintProgress(\"AWS Batching:\" + workInfo.Data)\n\n\t\t\texporter.Fail().ExportF(\"%s%s%v\", workInfo.Data, flow.ErrorSeparate, err)\n\t\t\tif in, ok := workInfo.Work.(*object.FetchApiInfo); ok {\n\t\t\t\tlog.ErrorF(\"AWS Fetch Failed, '%s' => [%s:%s], Error: %v\", in.FromUrl, in.Bucket, in.Key, err)\n\t\t\t} else {\n\t\t\t\tlog.ErrorF(\"AWS Fetch Failed, %s, Error: %s\", workInfo.Data, err)\n\t\t\t}\n\t\t}).Build().Start()\n\n\tmetric.End()\n\tif metric.TotalCount <= 0 {\n\t\tmetric.TotalCount = metric.SuccessCount + metric.FailureCount + metric.SkippedCount\n\t}\n\n\t\/\/ 输出结果\n\tresultPath := filepath.Join(workspace.GetJobDir(), \".result\")\n\tif e := utils.MarshalToFile(resultPath, metric); e != nil {\n\t\tlog.ErrorF(\"save aws batch fetch result to path:%s error:%v\", resultPath, e)\n\t} else {\n\t\tlog.DebugF(\"save aws batch fetch result to path:%s\", resultPath)\n\t}\n\n\tlog.Info(\"------------- AWS Batch Result --------------\")\n\tlog.InfoF(\"%20s%10d\", \"Total:\", metric.TotalCount)\n\tlog.InfoF(\"%20s%10d\", \"Success:\", metric.SuccessCount)\n\tlog.InfoF(\"%20s%10d\", \"Failure:\", metric.FailureCount)\n\tlog.InfoF(\"%20s%10d\", \"Skipped:\", metric.SkippedCount)\n\tlog.InfoF(\"%20s%10ds\", \"Duration:\", metric.Duration)\n\tlog.InfoF(\"--------------------------------------------\")\n}\n<|endoftext|>"}
{"text":"<commit_before>package s3\n\n\/\/ Tests for the PFS' S3 emulation API. Note that, in calls to\n\/\/ `tu.UniqueString`, all lowercase characters are used, unlike in other\n\/\/ tests. This is in order to generate repo names that are also valid bucket\n\/\/ names. Otherwise minio complains that the bucket name is not valid.\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"testing\"\n\n\tminio \"github.com\/minio\/minio-go\"\n\t\"github.com\/pachyderm\/pachyderm\/src\/client\"\n\t\"github.com\/pachyderm\/pachyderm\/src\/client\/pkg\/require\"\n\t\"github.com\/pachyderm\/pachyderm\/src\/server\/pfs\/server\"\n\t\"github.com\/pachyderm\/pachyderm\/src\/server\/pkg\/backoff\"\n\ttu \"github.com\/pachyderm\/pachyderm\/src\/server\/pkg\/testutil\"\n)\n\nfunc serve(t *testing.T, pc *client.APIClient) (*http.Server, uint16) {\n\tport := tu.UniquePort()\n\tsrv := Server(pc, port)\n\n\tgo func() {\n\t\tif err := srv.ListenAndServe(); err != http.ErrServerClosed {\n\t\t\tt.Fatalf(\"http server returned an error: %v\", err)\n\t\t}\n\t}()\n\n\t\/\/ Wait for the server to start\n\trequire.NoError(t, backoff.Retry(func() error {\n\t\tc := &http.Client{}\n\t\tres, err := c.Get(fmt.Sprintf(\"http:\/\/127.0.0.1:%d\/_ping\", port))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t} else if res.StatusCode != 200 {\n\t\t\treturn fmt.Errorf(\"Unexpected status code: %d\", res.StatusCode)\n\t\t}\n\t\treturn nil\n\t}, backoff.NewTestingBackOff()))\n\treturn srv, port\n}\n\nfunc getObject(c *minio.Client, repo, branch, file string) (string, error) {\n\tobj, err := c.GetObject(repo, fmt.Sprintf(\"%s\/%s\", branch, file))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tbytes, err := ioutil.ReadAll(obj)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif err = obj.Close(); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(bytes), nil\n}\n\n\nfunc TestGetFile(t *testing.T) {\n\trepo := tu.UniqueString(\"testgetfile\")\n\tpc := server.GetPachClient(t)\n\trequire.NoError(t, pc.CreateRepo(repo))\n\t_, err := pc.PutFile(repo, \"master\", \"file\", strings.NewReader(\"content\"))\n\trequire.NoError(t, err)\n\n\tsrv, port := serve(t, pc)\n\tc, err := minio.New(fmt.Sprintf(\"127.0.0.1:%d\", port), \"id\", \"secret\", false)\n\trequire.NoError(t, err)\n\n\tfetchedContent, err := getObject(c, repo, \"master\", \"file\")\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"content\", fetchedContent)\n\n\trequire.NoError(t, srv.Close())\n}\n\nfunc TestGetFileInBranch(t *testing.T) {\n\trepo := tu.UniqueString(\"testgetfileinbranch\")\n\tpc := server.GetPachClient(t)\n\trequire.NoError(t, pc.CreateRepo(repo))\n\trequire.NoError(t, pc.CreateBranch(repo, \"branch\", \"\", nil))\n\t_, err := pc.PutFile(repo, \"branch\", \"file\", strings.NewReader(\"content\"))\n\trequire.NoError(t, err)\n\n\tsrv, port := serve(t, pc)\n\tc, err := minio.New(fmt.Sprintf(\"127.0.0.1:%d\", port), \"id\", \"secret\", false)\n\trequire.NoError(t, err)\n\n\tfetchedContent, err := getObject(c, repo, \"branch\", \"file\")\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"content\", fetchedContent)\n\n\trequire.NoError(t, srv.Close())\n}\n\nfunc TestNonExistingBranch(t *testing.T) {\n\trepo := tu.UniqueString(\"testnonexistingbranch\")\n\tpc := server.GetPachClient(t)\n\trequire.NoError(t, pc.CreateRepo(repo))\n\n\tsrv, port := serve(t, pc)\n\tc, err := minio.New(fmt.Sprintf(\"127.0.0.1:%d\", port), \"id\", \"secret\", false)\n\trequire.NoError(t, err)\n\n\t_, err = getObject(c, repo, \"branch\", \"file\")\n\trequire.YesError(t, err)\n\trequire.Equal(t, err.Error(), \"The specified key does not exist.\")\n\trequire.NoError(t, srv.Close())\n}\n\nfunc TestNonExistingRepo(t *testing.T) {\n\trepo := tu.UniqueString(\"testnonexistingrepo\")\n\tpc := server.GetPachClient(t)\n\n\tsrv, port := serve(t, pc)\n\tc, err := minio.New(fmt.Sprintf(\"127.0.0.1:%d\", port), \"id\", \"secret\", false)\n\trequire.NoError(t, err)\n\n\t_, err = getObject(c, repo, \"master\", \"file\")\n\trequire.YesError(t, err)\n\trequire.Equal(t, err.Error(), \"The specified bucket does not exist.\")\n\trequire.NoError(t, srv.Close())\n}\n<commit_msg>Use defer to ensure the object is closed<commit_after>package s3\n\n\/\/ Tests for the PFS' S3 emulation API. Note that, in calls to\n\/\/ `tu.UniqueString`, all lowercase characters are used, unlike in other\n\/\/ tests. This is in order to generate repo names that are also valid bucket\n\/\/ names. Otherwise minio complains that the bucket name is not valid.\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"testing\"\n\n\tminio \"github.com\/minio\/minio-go\"\n\t\"github.com\/pachyderm\/pachyderm\/src\/client\"\n\t\"github.com\/pachyderm\/pachyderm\/src\/client\/pkg\/require\"\n\t\"github.com\/pachyderm\/pachyderm\/src\/server\/pfs\/server\"\n\t\"github.com\/pachyderm\/pachyderm\/src\/server\/pkg\/backoff\"\n\ttu \"github.com\/pachyderm\/pachyderm\/src\/server\/pkg\/testutil\"\n)\n\nfunc serve(t *testing.T, pc *client.APIClient) (*http.Server, uint16) {\n\tport := tu.UniquePort()\n\tsrv := Server(pc, port)\n\n\tgo func() {\n\t\tif err := srv.ListenAndServe(); err != http.ErrServerClosed {\n\t\t\tt.Fatalf(\"http server returned an error: %v\", err)\n\t\t}\n\t}()\n\n\t\/\/ Wait for the server to start\n\trequire.NoError(t, backoff.Retry(func() error {\n\t\tc := &http.Client{}\n\t\tres, err := c.Get(fmt.Sprintf(\"http:\/\/127.0.0.1:%d\/_ping\", port))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t} else if res.StatusCode != 200 {\n\t\t\treturn fmt.Errorf(\"Unexpected status code: %d\", res.StatusCode)\n\t\t}\n\t\treturn nil\n\t}, backoff.NewTestingBackOff()))\n\treturn srv, port\n}\n\nfunc getObject(c *minio.Client, repo, branch, file string) (string, error) {\n\tobj, err := c.GetObject(repo, fmt.Sprintf(\"%s\/%s\", branch, file))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer func() { err = obj.Close() }()\n\tbytes, err := ioutil.ReadAll(obj)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn string(bytes), err\n}\n\n\nfunc TestGetFile(t *testing.T) {\n\trepo := tu.UniqueString(\"testgetfile\")\n\tpc := server.GetPachClient(t)\n\trequire.NoError(t, pc.CreateRepo(repo))\n\t_, err := pc.PutFile(repo, \"master\", \"file\", strings.NewReader(\"content\"))\n\trequire.NoError(t, err)\n\n\tsrv, port := serve(t, pc)\n\tc, err := minio.New(fmt.Sprintf(\"127.0.0.1:%d\", port), \"id\", \"secret\", false)\n\trequire.NoError(t, err)\n\n\tfetchedContent, err := getObject(c, repo, \"master\", \"file\")\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"content\", fetchedContent)\n\n\trequire.NoError(t, srv.Close())\n}\n\nfunc TestGetFileInBranch(t *testing.T) {\n\trepo := tu.UniqueString(\"testgetfileinbranch\")\n\tpc := server.GetPachClient(t)\n\trequire.NoError(t, pc.CreateRepo(repo))\n\trequire.NoError(t, pc.CreateBranch(repo, \"branch\", \"\", nil))\n\t_, err := pc.PutFile(repo, \"branch\", \"file\", strings.NewReader(\"content\"))\n\trequire.NoError(t, err)\n\n\tsrv, port := serve(t, pc)\n\tc, err := minio.New(fmt.Sprintf(\"127.0.0.1:%d\", port), \"id\", \"secret\", false)\n\trequire.NoError(t, err)\n\n\tfetchedContent, err := getObject(c, repo, \"branch\", \"file\")\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"content\", fetchedContent)\n\n\trequire.NoError(t, srv.Close())\n}\n\nfunc TestNonExistingBranch(t *testing.T) {\n\trepo := tu.UniqueString(\"testnonexistingbranch\")\n\tpc := server.GetPachClient(t)\n\trequire.NoError(t, pc.CreateRepo(repo))\n\n\tsrv, port := serve(t, pc)\n\tc, err := minio.New(fmt.Sprintf(\"127.0.0.1:%d\", port), \"id\", \"secret\", false)\n\trequire.NoError(t, err)\n\n\t_, err = getObject(c, repo, \"branch\", \"file\")\n\trequire.YesError(t, err)\n\trequire.Equal(t, err.Error(), \"The specified key does not exist.\")\n\trequire.NoError(t, srv.Close())\n}\n\nfunc TestNonExistingRepo(t *testing.T) {\n\trepo := tu.UniqueString(\"testnonexistingrepo\")\n\tpc := server.GetPachClient(t)\n\n\tsrv, port := serve(t, pc)\n\tc, err := minio.New(fmt.Sprintf(\"127.0.0.1:%d\", port), \"id\", \"secret\", false)\n\trequire.NoError(t, err)\n\n\t_, err = getObject(c, repo, \"master\", \"file\")\n\trequire.YesError(t, err)\n\trequire.Equal(t, err.Error(), \"The specified bucket does not exist.\")\n\trequire.NoError(t, srv.Close())\n}\n<|endoftext|>"}
{"text":"<commit_before>package handlers\n\n\/\/go:generate make\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strconv\"\n\t\"strings\"\n)\n\ntype SecurityType int64\n\nconst (\n\tCurrency SecurityType = 1\n\tStock                 = 2\n)\n\nfunc GetSecurityType(typestring string) SecurityType {\n\tif strings.EqualFold(typestring, \"currency\") {\n\t\treturn Currency\n\t} else if strings.EqualFold(typestring, \"stock\") {\n\t\treturn Stock\n\t} else {\n\t\treturn 0\n\t}\n}\n\ntype Security struct {\n\tSecurityId  int64\n\tUserId      int64\n\tName        string\n\tDescription string\n\tSymbol      string\n\t\/\/ Number of decimal digits (to the right of the decimal point) this\n\t\/\/ security is precise to\n\tPrecision int\n\tType      SecurityType\n\t\/\/ AlternateId is CUSIP for Type=Stock, ISO4217 for Type=Currency\n\tAlternateId string\n}\n\ntype SecurityList struct {\n\tSecurities *[]*Security `json:\"securities\"`\n}\n\nfunc (s *Security) Read(json_str string) error {\n\tdec := json.NewDecoder(strings.NewReader(json_str))\n\treturn dec.Decode(s)\n}\n\nfunc (s *Security) Write(w http.ResponseWriter) error {\n\tenc := json.NewEncoder(w)\n\treturn enc.Encode(s)\n}\n\nfunc (sl *SecurityList) Read(json_str string) error {\n\tdec := json.NewDecoder(strings.NewReader(json_str))\n\treturn dec.Decode(sl)\n}\n\nfunc (sl *SecurityList) Write(w http.ResponseWriter) error {\n\tenc := json.NewEncoder(w)\n\treturn enc.Encode(sl)\n}\n\nfunc SearchSecurityTemplates(search string, _type SecurityType, limit int64) []*Security {\n\tupperSearch := strings.ToUpper(search)\n\tvar results []*Security\n\tfor i, security := range SecurityTemplates {\n\t\tif strings.Contains(strings.ToUpper(security.Name), upperSearch) ||\n\t\t\tstrings.Contains(strings.ToUpper(security.Description), upperSearch) ||\n\t\t\tstrings.Contains(strings.ToUpper(security.Symbol), upperSearch) {\n\t\t\tif _type == 0 || _type == security.Type {\n\t\t\t\tresults = append(results, &SecurityTemplates[i])\n\t\t\t\tif limit != -1 && int64(len(results)) >= limit {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn results\n}\n\nfunc FindSecurityTemplate(name string, _type SecurityType) *Security {\n\tfor _, security := range SecurityTemplates {\n\t\tif name == security.Name && _type == security.Type {\n\t\t\treturn &security\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc FindCurrencyTemplate(iso4217 int64) *Security {\n\tiso4217string := strconv.FormatInt(iso4217, 10)\n\tfor _, security := range SecurityTemplates {\n\t\tif security.Type == Currency && security.AlternateId == iso4217string {\n\t\t\treturn &security\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GetSecurity(tx *Tx, securityid int64, userid int64) (*Security, error) {\n\tvar s Security\n\n\terr := tx.SelectOne(&s, \"SELECT * from securities where UserId=? AND SecurityId=?\", userid, securityid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &s, nil\n}\n\nfunc GetSecurities(tx *Tx, userid int64) (*[]*Security, error) {\n\tvar securities []*Security\n\n\t_, err := tx.Select(&securities, \"SELECT * from securities where UserId=?\", userid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &securities, nil\n}\n\nfunc InsertSecurity(tx *Tx, s *Security) error {\n\terr := tx.Insert(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc UpdateSecurity(tx *Tx, s *Security) (err error) {\n\tuser, err := GetUser(tx, s.UserId)\n\tif err != nil {\n\t\treturn\n\t} else if user.DefaultCurrency == s.SecurityId && s.Type != Currency {\n\t\treturn errors.New(\"Cannot change security which is user's default currency to be non-currency\")\n\t}\n\n\tcount, err := tx.Update(s)\n\tif err != nil {\n\t\treturn\n\t}\n\tif count > 1 {\n\t\treturn fmt.Errorf(\"Updated %d securities (expected 1)\", count)\n\t}\n\n\treturn nil\n}\n\ntype SecurityInUseError struct {\n\tmessage string\n}\n\nfunc (e SecurityInUseError) Error() string {\n\treturn e.message\n}\n\nfunc DeleteSecurity(tx *Tx, s *Security) error {\n\t\/\/ First, ensure no accounts are using this security\n\taccounts, err := tx.SelectInt(\"SELECT count(*) from accounts where UserId=? and SecurityId=?\", s.UserId, s.SecurityId)\n\n\tif accounts != 0 {\n\t\treturn SecurityInUseError{\"One or more accounts still use this security\"}\n\t}\n\n\tuser, err := GetUser(tx, s.UserId)\n\tif err != nil {\n\t\treturn err\n\t} else if user.DefaultCurrency == s.SecurityId {\n\t\treturn SecurityInUseError{\"Cannot delete security which is user's default currency\"}\n\t}\n\n\t\/\/ Remove all prices involving this security (either of this security, or\n\t\/\/ using it as a currency)\n\t_, err = tx.Exec(\"DELETE FROM prices WHERE SecurityId=? OR CurrencyId=?\", s.SecurityId, s.SecurityId)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcount, err := tx.Delete(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif count != 1 {\n\t\treturn errors.New(\"Deleted more than one security\")\n\t}\n\n\treturn nil\n}\n\nfunc ImportGetCreateSecurity(tx *Tx, userid int64, security *Security) (*Security, error) {\n\tsecurity.UserId = userid\n\tif len(security.AlternateId) == 0 {\n\t\t\/\/ Always create a new local security if we can't match on the AlternateId\n\t\terr := InsertSecurity(tx, security)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn security, nil\n\t}\n\n\tvar securities []*Security\n\n\t_, err := tx.Select(&securities, \"SELECT * from securities where UserId=? AND Type=? AND AlternateId=? AND Precision=?\", userid, security.Type, security.AlternateId, security.Precision)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ First try to find a case insensitive match on the name or symbol\n\tupperName := strings.ToUpper(security.Name)\n\tupperSymbol := strings.ToUpper(security.Symbol)\n\tfor _, s := range securities {\n\t\tif (len(s.Name) > 0 && strings.ToUpper(s.Name) == upperName) ||\n\t\t\t(len(s.Symbol) > 0 && strings.ToUpper(s.Symbol) == upperSymbol) {\n\t\t\treturn s, nil\n\t\t}\n\t}\n\t\/\/\t\tif strings.Contains(strings.ToUpper(security.Name), upperSearch) ||\n\n\t\/\/ Try to find a partial string match on the name or symbol\n\tfor _, s := range securities {\n\t\tsUpperName := strings.ToUpper(s.Name)\n\t\tsUpperSymbol := strings.ToUpper(s.Symbol)\n\t\tif (len(upperName) > 0 && len(s.Name) > 0 && (strings.Contains(upperName, sUpperName) || strings.Contains(sUpperName, upperName))) ||\n\t\t\t(len(upperSymbol) > 0 && len(s.Symbol) > 0 && (strings.Contains(upperSymbol, sUpperSymbol) || strings.Contains(sUpperSymbol, upperSymbol))) {\n\t\t\treturn s, nil\n\t\t}\n\t}\n\n\t\/\/ Give up and return the first security in the list\n\tif len(securities) > 0 {\n\t\treturn securities[0], nil\n\t}\n\n\t\/\/ If there wasn't even one security in the list, make a new one\n\terr = InsertSecurity(tx, security)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn security, nil\n}\n\nfunc SecurityHandler(r *http.Request, context *Context) ResponseWriterWriter {\n\tuser, err := GetUserFromSession(context.Tx, r)\n\tif err != nil {\n\t\treturn NewError(1 \/*Not Signed In*\/)\n\t}\n\n\tif r.Method == \"POST\" {\n\t\tif !context.LastLevel() {\n\t\t\tsecurityid, err := context.NextID()\n\t\t\tif err != nil {\n\t\t\t\treturn NewError(3 \/*Invalid Request*\/)\n\t\t\t}\n\t\t\tif context.NextLevel() != \"prices\" {\n\t\t\t\treturn NewError(3 \/*Invalid Request*\/)\n\t\t\t}\n\t\t\treturn PriceHandler(r, context, user, securityid)\n\t\t}\n\n\t\tvar security Security\n\t\tif err := ReadJSON(r, &security); err != nil {\n\t\t\treturn NewError(3 \/*Invalid Request*\/)\n\t\t}\n\t\tsecurity.SecurityId = -1\n\t\tsecurity.UserId = user.UserId\n\n\t\terr = InsertSecurity(context.Tx, &security)\n\t\tif err != nil {\n\t\t\tlog.Print(err)\n\t\t\treturn NewError(999 \/*Internal Error*\/)\n\t\t}\n\n\t\treturn ResponseWrapper{201, &security}\n\t} else if r.Method == \"GET\" {\n\t\tif context.LastLevel() {\n\t\t\t\/\/Return all securities\n\t\t\tvar sl SecurityList\n\n\t\t\tsecurities, err := GetSecurities(context.Tx, user.UserId)\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t\treturn NewError(999 \/*Internal Error*\/)\n\t\t\t}\n\n\t\t\tsl.Securities = securities\n\t\t\treturn &sl\n\t\t} else {\n\t\t\tsecurityid, err := context.NextID()\n\t\t\tif err != nil {\n\t\t\t\treturn NewError(3 \/*Invalid Request*\/)\n\t\t\t}\n\n\t\t\tif !context.LastLevel() {\n\t\t\t\tif context.NextLevel() != \"prices\" {\n\t\t\t\t\treturn NewError(3 \/*Invalid Request*\/)\n\t\t\t\t}\n\t\t\t\treturn PriceHandler(r, context, user, securityid)\n\t\t\t}\n\n\t\t\tsecurity, err := GetSecurity(context.Tx, securityid, user.UserId)\n\t\t\tif err != nil {\n\t\t\t\treturn NewError(3 \/*Invalid Request*\/)\n\t\t\t}\n\n\t\t\treturn security\n\t\t}\n\t} else {\n\t\tsecurityid, err := context.NextID()\n\t\tif err != nil {\n\t\t\treturn NewError(3 \/*Invalid Request*\/)\n\t\t}\n\t\tif !context.LastLevel() {\n\t\t\tif context.NextLevel() != \"prices\" {\n\t\t\t\treturn NewError(3 \/*Invalid Request*\/)\n\t\t\t}\n\t\t\treturn PriceHandler(r, context, user, securityid)\n\t\t}\n\n\t\tif r.Method == \"PUT\" {\n\t\t\tvar security Security\n\t\t\tif err := ReadJSON(r, &security); err != nil || security.SecurityId != securityid {\n\t\t\t\treturn NewError(3 \/*Invalid Request*\/)\n\t\t\t}\n\t\t\tsecurity.UserId = user.UserId\n\n\t\t\terr = UpdateSecurity(context.Tx, &security)\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t\treturn NewError(999 \/*Internal Error*\/)\n\t\t\t}\n\n\t\t\treturn &security\n\t\t} else if r.Method == \"DELETE\" {\n\t\t\tsecurity, err := GetSecurity(context.Tx, securityid, user.UserId)\n\t\t\tif err != nil {\n\t\t\t\treturn NewError(3 \/*Invalid Request*\/)\n\t\t\t}\n\n\t\t\terr = DeleteSecurity(context.Tx, security)\n\t\t\tif _, ok := err.(SecurityInUseError); ok {\n\t\t\t\treturn NewError(7 \/*In Use Error*\/)\n\t\t\t} else if err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t\treturn NewError(999 \/*Internal Error*\/)\n\t\t\t}\n\n\t\t\treturn SuccessWriter{}\n\t\t}\n\t}\n\treturn NewError(3 \/*Invalid Request*\/)\n}\n\nfunc SecurityTemplateHandler(r *http.Request, context *Context) ResponseWriterWriter {\n\tif r.Method == \"GET\" {\n\t\tvar sl SecurityList\n\n\t\tquery, _ := url.ParseQuery(r.URL.RawQuery)\n\n\t\tvar limit int64 = -1\n\t\tsearch := query.Get(\"search\")\n\n\t\tvar _type SecurityType = 0\n\t\ttypestring := query.Get(\"type\")\n\t\tif len(typestring) > 0 {\n\t\t\t_type = GetSecurityType(typestring)\n\t\t\tif _type == 0 {\n\t\t\t\treturn NewError(3 \/*Invalid Request*\/)\n\t\t\t}\n\t\t}\n\n\t\tlimitstring := query.Get(\"limit\")\n\t\tif limitstring != \"\" {\n\t\t\tlimitint, err := strconv.ParseInt(limitstring, 10, 0)\n\t\t\tif err != nil {\n\t\t\t\treturn NewError(3 \/*Invalid Request*\/)\n\t\t\t}\n\t\t\tlimit = limitint\n\t\t}\n\n\t\tsecurities := SearchSecurityTemplates(search, _type, limit)\n\n\t\tsl.Securities = &securities\n\t\treturn &sl\n\t} else {\n\t\treturn NewError(3 \/*Invalid Request*\/)\n\t}\n}\n<commit_msg>securities: Don't use 'precision', a MySQL reserved word, in DB<commit_after>package handlers\n\n\/\/go:generate make\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strconv\"\n\t\"strings\"\n)\n\ntype SecurityType int64\n\nconst (\n\tCurrency SecurityType = 1\n\tStock                 = 2\n)\n\nfunc GetSecurityType(typestring string) SecurityType {\n\tif strings.EqualFold(typestring, \"currency\") {\n\t\treturn Currency\n\t} else if strings.EqualFold(typestring, \"stock\") {\n\t\treturn Stock\n\t} else {\n\t\treturn 0\n\t}\n}\n\ntype Security struct {\n\tSecurityId  int64\n\tUserId      int64\n\tName        string\n\tDescription string\n\tSymbol      string\n\t\/\/ Number of decimal digits (to the right of the decimal point) this\n\t\/\/ security is precise to\n\tPrecision int `db:\"Preciseness\"`\n\tType      SecurityType\n\t\/\/ AlternateId is CUSIP for Type=Stock, ISO4217 for Type=Currency\n\tAlternateId string\n}\n\ntype SecurityList struct {\n\tSecurities *[]*Security `json:\"securities\"`\n}\n\nfunc (s *Security) Read(json_str string) error {\n\tdec := json.NewDecoder(strings.NewReader(json_str))\n\treturn dec.Decode(s)\n}\n\nfunc (s *Security) Write(w http.ResponseWriter) error {\n\tenc := json.NewEncoder(w)\n\treturn enc.Encode(s)\n}\n\nfunc (sl *SecurityList) Read(json_str string) error {\n\tdec := json.NewDecoder(strings.NewReader(json_str))\n\treturn dec.Decode(sl)\n}\n\nfunc (sl *SecurityList) Write(w http.ResponseWriter) error {\n\tenc := json.NewEncoder(w)\n\treturn enc.Encode(sl)\n}\n\nfunc SearchSecurityTemplates(search string, _type SecurityType, limit int64) []*Security {\n\tupperSearch := strings.ToUpper(search)\n\tvar results []*Security\n\tfor i, security := range SecurityTemplates {\n\t\tif strings.Contains(strings.ToUpper(security.Name), upperSearch) ||\n\t\t\tstrings.Contains(strings.ToUpper(security.Description), upperSearch) ||\n\t\t\tstrings.Contains(strings.ToUpper(security.Symbol), upperSearch) {\n\t\t\tif _type == 0 || _type == security.Type {\n\t\t\t\tresults = append(results, &SecurityTemplates[i])\n\t\t\t\tif limit != -1 && int64(len(results)) >= limit {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn results\n}\n\nfunc FindSecurityTemplate(name string, _type SecurityType) *Security {\n\tfor _, security := range SecurityTemplates {\n\t\tif name == security.Name && _type == security.Type {\n\t\t\treturn &security\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc FindCurrencyTemplate(iso4217 int64) *Security {\n\tiso4217string := strconv.FormatInt(iso4217, 10)\n\tfor _, security := range SecurityTemplates {\n\t\tif security.Type == Currency && security.AlternateId == iso4217string {\n\t\t\treturn &security\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GetSecurity(tx *Tx, securityid int64, userid int64) (*Security, error) {\n\tvar s Security\n\n\terr := tx.SelectOne(&s, \"SELECT * from securities where UserId=? AND SecurityId=?\", userid, securityid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &s, nil\n}\n\nfunc GetSecurities(tx *Tx, userid int64) (*[]*Security, error) {\n\tvar securities []*Security\n\n\t_, err := tx.Select(&securities, \"SELECT * from securities where UserId=?\", userid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &securities, nil\n}\n\nfunc InsertSecurity(tx *Tx, s *Security) error {\n\terr := tx.Insert(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc UpdateSecurity(tx *Tx, s *Security) (err error) {\n\tuser, err := GetUser(tx, s.UserId)\n\tif err != nil {\n\t\treturn\n\t} else if user.DefaultCurrency == s.SecurityId && s.Type != Currency {\n\t\treturn errors.New(\"Cannot change security which is user's default currency to be non-currency\")\n\t}\n\n\tcount, err := tx.Update(s)\n\tif err != nil {\n\t\treturn\n\t}\n\tif count > 1 {\n\t\treturn fmt.Errorf(\"Updated %d securities (expected 1)\", count)\n\t}\n\n\treturn nil\n}\n\ntype SecurityInUseError struct {\n\tmessage string\n}\n\nfunc (e SecurityInUseError) Error() string {\n\treturn e.message\n}\n\nfunc DeleteSecurity(tx *Tx, s *Security) error {\n\t\/\/ First, ensure no accounts are using this security\n\taccounts, err := tx.SelectInt(\"SELECT count(*) from accounts where UserId=? and SecurityId=?\", s.UserId, s.SecurityId)\n\n\tif accounts != 0 {\n\t\treturn SecurityInUseError{\"One or more accounts still use this security\"}\n\t}\n\n\tuser, err := GetUser(tx, s.UserId)\n\tif err != nil {\n\t\treturn err\n\t} else if user.DefaultCurrency == s.SecurityId {\n\t\treturn SecurityInUseError{\"Cannot delete security which is user's default currency\"}\n\t}\n\n\t\/\/ Remove all prices involving this security (either of this security, or\n\t\/\/ using it as a currency)\n\t_, err = tx.Exec(\"DELETE FROM prices WHERE SecurityId=? OR CurrencyId=?\", s.SecurityId, s.SecurityId)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcount, err := tx.Delete(s)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif count != 1 {\n\t\treturn errors.New(\"Deleted more than one security\")\n\t}\n\n\treturn nil\n}\n\nfunc ImportGetCreateSecurity(tx *Tx, userid int64, security *Security) (*Security, error) {\n\tsecurity.UserId = userid\n\tif len(security.AlternateId) == 0 {\n\t\t\/\/ Always create a new local security if we can't match on the AlternateId\n\t\terr := InsertSecurity(tx, security)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn security, nil\n\t}\n\n\tvar securities []*Security\n\n\t_, err := tx.Select(&securities, \"SELECT * from securities where UserId=? AND Type=? AND AlternateId=? AND Preciseness=?\", userid, security.Type, security.AlternateId, security.Precision)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ First try to find a case insensitive match on the name or symbol\n\tupperName := strings.ToUpper(security.Name)\n\tupperSymbol := strings.ToUpper(security.Symbol)\n\tfor _, s := range securities {\n\t\tif (len(s.Name) > 0 && strings.ToUpper(s.Name) == upperName) ||\n\t\t\t(len(s.Symbol) > 0 && strings.ToUpper(s.Symbol) == upperSymbol) {\n\t\t\treturn s, nil\n\t\t}\n\t}\n\t\/\/\t\tif strings.Contains(strings.ToUpper(security.Name), upperSearch) ||\n\n\t\/\/ Try to find a partial string match on the name or symbol\n\tfor _, s := range securities {\n\t\tsUpperName := strings.ToUpper(s.Name)\n\t\tsUpperSymbol := strings.ToUpper(s.Symbol)\n\t\tif (len(upperName) > 0 && len(s.Name) > 0 && (strings.Contains(upperName, sUpperName) || strings.Contains(sUpperName, upperName))) ||\n\t\t\t(len(upperSymbol) > 0 && len(s.Symbol) > 0 && (strings.Contains(upperSymbol, sUpperSymbol) || strings.Contains(sUpperSymbol, upperSymbol))) {\n\t\t\treturn s, nil\n\t\t}\n\t}\n\n\t\/\/ Give up and return the first security in the list\n\tif len(securities) > 0 {\n\t\treturn securities[0], nil\n\t}\n\n\t\/\/ If there wasn't even one security in the list, make a new one\n\terr = InsertSecurity(tx, security)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn security, nil\n}\n\nfunc SecurityHandler(r *http.Request, context *Context) ResponseWriterWriter {\n\tuser, err := GetUserFromSession(context.Tx, r)\n\tif err != nil {\n\t\treturn NewError(1 \/*Not Signed In*\/)\n\t}\n\n\tif r.Method == \"POST\" {\n\t\tif !context.LastLevel() {\n\t\t\tsecurityid, err := context.NextID()\n\t\t\tif err != nil {\n\t\t\t\treturn NewError(3 \/*Invalid Request*\/)\n\t\t\t}\n\t\t\tif context.NextLevel() != \"prices\" {\n\t\t\t\treturn NewError(3 \/*Invalid Request*\/)\n\t\t\t}\n\t\t\treturn PriceHandler(r, context, user, securityid)\n\t\t}\n\n\t\tvar security Security\n\t\tif err := ReadJSON(r, &security); err != nil {\n\t\t\treturn NewError(3 \/*Invalid Request*\/)\n\t\t}\n\t\tsecurity.SecurityId = -1\n\t\tsecurity.UserId = user.UserId\n\n\t\terr = InsertSecurity(context.Tx, &security)\n\t\tif err != nil {\n\t\t\tlog.Print(err)\n\t\t\treturn NewError(999 \/*Internal Error*\/)\n\t\t}\n\n\t\treturn ResponseWrapper{201, &security}\n\t} else if r.Method == \"GET\" {\n\t\tif context.LastLevel() {\n\t\t\t\/\/Return all securities\n\t\t\tvar sl SecurityList\n\n\t\t\tsecurities, err := GetSecurities(context.Tx, user.UserId)\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t\treturn NewError(999 \/*Internal Error*\/)\n\t\t\t}\n\n\t\t\tsl.Securities = securities\n\t\t\treturn &sl\n\t\t} else {\n\t\t\tsecurityid, err := context.NextID()\n\t\t\tif err != nil {\n\t\t\t\treturn NewError(3 \/*Invalid Request*\/)\n\t\t\t}\n\n\t\t\tif !context.LastLevel() {\n\t\t\t\tif context.NextLevel() != \"prices\" {\n\t\t\t\t\treturn NewError(3 \/*Invalid Request*\/)\n\t\t\t\t}\n\t\t\t\treturn PriceHandler(r, context, user, securityid)\n\t\t\t}\n\n\t\t\tsecurity, err := GetSecurity(context.Tx, securityid, user.UserId)\n\t\t\tif err != nil {\n\t\t\t\treturn NewError(3 \/*Invalid Request*\/)\n\t\t\t}\n\n\t\t\treturn security\n\t\t}\n\t} else {\n\t\tsecurityid, err := context.NextID()\n\t\tif err != nil {\n\t\t\treturn NewError(3 \/*Invalid Request*\/)\n\t\t}\n\t\tif !context.LastLevel() {\n\t\t\tif context.NextLevel() != \"prices\" {\n\t\t\t\treturn NewError(3 \/*Invalid Request*\/)\n\t\t\t}\n\t\t\treturn PriceHandler(r, context, user, securityid)\n\t\t}\n\n\t\tif r.Method == \"PUT\" {\n\t\t\tvar security Security\n\t\t\tif err := ReadJSON(r, &security); err != nil || security.SecurityId != securityid {\n\t\t\t\treturn NewError(3 \/*Invalid Request*\/)\n\t\t\t}\n\t\t\tsecurity.UserId = user.UserId\n\n\t\t\terr = UpdateSecurity(context.Tx, &security)\n\t\t\tif err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t\treturn NewError(999 \/*Internal Error*\/)\n\t\t\t}\n\n\t\t\treturn &security\n\t\t} else if r.Method == \"DELETE\" {\n\t\t\tsecurity, err := GetSecurity(context.Tx, securityid, user.UserId)\n\t\t\tif err != nil {\n\t\t\t\treturn NewError(3 \/*Invalid Request*\/)\n\t\t\t}\n\n\t\t\terr = DeleteSecurity(context.Tx, security)\n\t\t\tif _, ok := err.(SecurityInUseError); ok {\n\t\t\t\treturn NewError(7 \/*In Use Error*\/)\n\t\t\t} else if err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t\treturn NewError(999 \/*Internal Error*\/)\n\t\t\t}\n\n\t\t\treturn SuccessWriter{}\n\t\t}\n\t}\n\treturn NewError(3 \/*Invalid Request*\/)\n}\n\nfunc SecurityTemplateHandler(r *http.Request, context *Context) ResponseWriterWriter {\n\tif r.Method == \"GET\" {\n\t\tvar sl SecurityList\n\n\t\tquery, _ := url.ParseQuery(r.URL.RawQuery)\n\n\t\tvar limit int64 = -1\n\t\tsearch := query.Get(\"search\")\n\n\t\tvar _type SecurityType = 0\n\t\ttypestring := query.Get(\"type\")\n\t\tif len(typestring) > 0 {\n\t\t\t_type = GetSecurityType(typestring)\n\t\t\tif _type == 0 {\n\t\t\t\treturn NewError(3 \/*Invalid Request*\/)\n\t\t\t}\n\t\t}\n\n\t\tlimitstring := query.Get(\"limit\")\n\t\tif limitstring != \"\" {\n\t\t\tlimitint, err := strconv.ParseInt(limitstring, 10, 0)\n\t\t\tif err != nil {\n\t\t\t\treturn NewError(3 \/*Invalid Request*\/)\n\t\t\t}\n\t\t\tlimit = limitint\n\t\t}\n\n\t\tsecurities := SearchSecurityTemplates(search, _type, limit)\n\n\t\tsl.Securities = &securities\n\t\treturn &sl\n\t} else {\n\t\treturn NewError(3 \/*Invalid Request*\/)\n\t}\n}\n<|endoftext|>"}
