{"text":"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}\nfix TestWALPeriodicSync (#3342)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":"\/\/ +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: \" ...\",\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}\nlncli\/autopilot: add -ignorelocal state flag to query\/\/ +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] ...\",\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":"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ンンー ンンンン ンーンン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":"\/\/ 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}\ntests: Remove comment.\/\/ 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":"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}\nRefactor get metaspackage 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":"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}\nGetBlockHashesFromHash(hash, max) gives back max hashes starting from PARENT of hashpackage 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":"\/\/ 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}\nMove initialization logic into NewBPFSniffer\/\/ 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":"\/\/ 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}\nAdd back tests (#4905)\/\/ 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":"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}\nAdd bot account to testingpackage 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":"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}\namend logpackage 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":"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}\nSkip network testspackage 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":"\/\/ +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}\nSwitch to new memory driver location\/\/ +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":"\/\/ 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}\nruntime: add Func method benchmarks\/\/ 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":"\/\/ 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 = `
{{printf \"%s\" . |html}}<\/pre>`\n\nvar frontPageText = `\n\n\n