{"text":"package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/jh-bate\/fantail-bot\/Godeps\/_workspace\/src\/github.com\/tucnak\/telebot\"\n)\n\nconst (\n\t\/\/commands\n\tyostart_command = \"\/start\"\n\tyobg_command = \"\/yobg\"\n\tyolow_command = \"\/yolow\"\n\tyomove_command = \"\/yomove\"\n\tyofood_command = \"\/yofood\"\n\n\ttyping_action = \"typing\"\n\n\tnote_json = `{\"type\":\"note\",\"user\":\"%s\",\"data\":{\"text\":\"%s\"},\"time\":\"%s\"}`\n)\n\n\/\/our bot\nvar fBot *fantailBot\n\ntype (\n\tlang struct {\n\t\tGreetings []string `json:\"greet\"`\n\t\tGoodbyes []string `json:\"goodbye\"`\n\t\tYes []string `json:\"yes\"`\n\t\tNo []string `json:\"no\"`\n\t\tBg struct {\n\t\t\tComment string `json:\"comment\"`\n\t\t\tQuestion string `json:\"question\"`\n\t\t\tAbove option `json:\"above\"`\n\t\t\tIn option `json:\"in\"`\n\t\t\tBelow option `json:\"below\"`\n\t\t\tThank string `json:\"thank\"`\n\t\t} `json:\"bg\"`\n\t\tMove struct {\n\t\t\tComment string `json:\"comment\"`\n\t\t\tQuestion string `json:\"question\"`\n\t\t\tEx1 string `json:\"typeOne\"`\n\t\t\tEx2 string `json:\"typeTwo\"`\n\t\t\tEx3 string `json:\"typeThree\"`\n\t\t\tEx4 string `json:\"typeFour\"`\n\t\t\tThank string `json:\"thank\"`\n\t\t} `json:\"move\"`\n\t\tFood struct {\n\t\t\tComment string `json:\"comment\"`\n\t\t\tQuestion string `json:\"question\"`\n\t\t\tSnack string `json:\"snack\"`\n\t\t\tMeal string `json:\"meal\"`\n\t\t\tOther string `json:\"other\"`\n\t\t\tThank string `json:\"thank\"`\n\t\t} `json:\"food\"`\n\t\tLow struct {\n\t\t\tComment string `json:\"comment\"`\n\t\t\tQuestion string `json:\"question\"`\n\t\t\tGood option `json:\"good\"`\n\t\t\tNotGood option `json:\"notGood\"`\n\t\t\tOther option `json:\"other\"`\n\t\t\tThank string `json:\"thank\"`\n\t\t} `json:\"low\"`\n\t}\n\n\toption struct {\n\t\tText string `json:\"text\"`\n\t\tFeedback []string `json:\"feedback\"`\n\t\tFollowUp []string `json:\"followUp\"`\n\t}\n\n\tfantailBot struct {\n\t\tprocess\n\t\tbot *telebot.Bot\n\t\t*lang\n\t}\n\tprocess interface {\n\t\tgetBot() *telebot.Bot\n\t\tgetLanguage() *lang\n\t\tisRunning(string) bool\n\t\trunningName() string\n\t\taddPart(*part)\n\t\trun(telebot.Message)\n\t}\n\tpart struct {\n\t\tfn func(msg telebot.Message)\n\t\ttoRun bool\n\t}\n)\n\nfunc loadLanguage() *lang {\n\n\tfile, _ := os.Open(\"languageConfig.json\")\n\tdecoder := json.NewDecoder(file)\n\tvar language lang\n\terr := decoder.Decode(&language)\n\tif err != nil {\n\t\tlog.Panic(\"could not load language \", err.Error())\n\t}\n\treturn &language\n}\n\nfunc getfBot() *fantailBot {\n\tbotToken := os.Getenv(\"BOT_TOKEN\")\n\n\tif botToken == \"\" {\n\t\tlog.Fatal(\"$BOT_TOKEN must be set\")\n\t}\n\n\tbot, err := telebot.NewBot(botToken)\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn &fantailBot{bot: bot, lang: loadLanguage()}\n}\n\nfunc (this *fantailBot) isCurrentlyRunning(processName string) bool {\n\tif this.process != nil && this.process.runningName() == processName {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc main() {\n\n\tfBot = getfBot()\n\n\tmessages := make(chan telebot.Message)\n\tfBot.bot.Listen(messages, 1*time.Second)\n\n\tfor msg := range messages {\n\n\t\tlog.Println(\"incomming msg\", msg.Text)\n\t\tif fBot.process != nil {\n\t\t\tlog.Println(\"running process \", fBot.process.runningName())\n\t\t}\n\t\tif strings.Contains(msg.Text, yostart_command) {\n\t\t\t\/\/show all options\n\t\t\tb := newBasics(fBot, yostart_command)\n\t\t\tb.options(msg)\n\t\t} else if strings.Contains(msg.Text, yobg_command) || fBot.isCurrentlyRunning(yobg_command) {\n\t\t\tif strings.Contains(msg.Text, yobg_command) {\n\t\t\t\tb := newBasics(fBot, yobg_command)\n\t\t\t\tb.addPart(&part{fn: b.bg, toRun: true})\n\t\t\t\tb.addPart(&part{fn: b.bgFeedback, toRun: true})\n\t\t\t\tb.addPart(&part{fn: b.seeYou, toRun: true})\n\t\t\t\tfBot.setProcess(b)\n\t\t\t}\n\n\t\t\tfBot.process.run(msg)\n\t\t} else if strings.Contains(msg.Text, yomove_command) || fBot.isCurrentlyRunning(yomove_command) {\n\t\t\tif strings.Contains(msg.Text, yomove_command) {\n\t\t\t\tb := newBasics(fBot, yomove_command)\n\t\t\t\tb.addPart(&part{fn: b.yoMove, toRun: true})\n\t\t\t\tb.addPart(&part{fn: b.seeYou, toRun: true})\n\t\t\t\tfBot.setProcess(b)\n\t\t\t}\n\n\t\t\tfBot.process.run(msg)\n\t\t} else if strings.Contains(msg.Text, yofood_command) || fBot.isCurrentlyRunning(yofood_command) {\n\t\t\tif strings.Contains(msg.Text, yofood_command) {\n\t\t\t\tb := newBasics(fBot, yofood_command)\n\t\t\t\tb.addPart(&part{fn: b.yoFood, toRun: true})\n\t\t\t\tb.addPart(&part{fn: b.seeYou, toRun: true})\n\t\t\t\tfBot.setProcess(b)\n\t\t\t}\n\n\t\t\tfBot.process.run(msg)\n\t\t} else if strings.Contains(msg.Text, yolow_command) || fBot.isCurrentlyRunning(yolow_command) {\n\t\t\tif strings.Contains(msg.Text, yolow_command) {\n\t\t\t\tb := newBasics(fBot, yolow_command)\n\t\t\t\tb.addPart(&part{fn: b.low, toRun: true})\n\t\t\t\tb.addPart(&part{fn: b.lowFeedBack, toRun: true})\n\t\t\t\tb.addPart(&part{fn: b.seeYou, toRun: true})\n\t\t\t\tfBot.setProcess(b)\n\t\t\t}\n\t\t\tfBot.process.run(msg)\n\t\t}\n\n\t}\n}\n\ntype basics struct {\n\tfBot *fantailBot\n\tparts []*part\n\tname string\n}\n\nfunc newBasics(fBot *fantailBot, name string) *basics {\n\treturn &basics{fBot: fBot, name: name}\n}\n\nfunc (this *fantailBot) setProcess(p *basics) {\n\tthis.process = nil\n\tthis.process = p\n\treturn\n}\n\nfunc (this *basics) seeYou(msg telebot.Message) {\n\tthis.getBot().SendMessage(\n\t\tmsg.Chat,\n\t\tthis.getLanguage().Goodbyes[rand.Intn(len(this.getLanguage().Goodbyes))],\n\t\t&telebot.SendOptions{\n\t\t\tReplyMarkup: telebot.ReplyMarkup{\n\t\t\t\tForceReply: true,\n\t\t\t\tCustomKeyboard: [][]string{\n\t\t\t\t\t[]string{this.getLanguage().Goodbyes[rand.Intn(len(this.getLanguage().Goodbyes))]},\n\t\t\t\t},\n\t\t\t\tResizeKeyboard: true,\n\t\t\t\tOneTimeKeyboard: true,\n\t\t\t},\n\t\t})\n\treturn\n}\n\nfunc (this *basics) pause(msg telebot.Message) {\n\tthis.getBot().SendChatAction(msg.Chat, typing_action)\n\ttime.Sleep(2 * time.Second)\n\treturn\n}\n\nfunc (this *basics) addPart(p *part) {\n\tthis.parts = append(this.parts, p)\n\treturn\n}\n\nfunc (this *basics) isRunning(name string) bool {\n\treturn this.name == name\n}\n\nfunc (this *basics) runningName() string {\n\treturn this.name\n}\n\nfunc (this *basics) run(m telebot.Message) {\n\tfor i := range this.parts {\n\t\tlog.Println(\"checking \", i, \"of\", len(this.parts), \"run?\", this.parts[i].toRun)\n\t\tif this.parts[i].toRun {\n\t\t\tlog.Println(\"running \", i)\n\t\t\tthis.parts[i].toRun = false\n\t\t\tthis.parts[i].fn(m)\n\t\t\tlog.Println(\"has run \", i)\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (this *basics) getBot() *telebot.Bot {\n\treturn this.fBot.bot\n}\n\nfunc (this *basics) getLanguage() *lang {\n\treturn this.fBot.lang\n}\n\nfunc (this *basics) options(msg telebot.Message) {\n\tthis.getBot().SendMessage(msg.Chat,\n\t\tfmt.Sprintf(\"%s %s! What can we do for you?\", this.getLanguage().Greetings[rand.Intn(len(this.getLanguage().Greetings))], msg.Chat.FirstName),\n\t\t&telebot.SendOptions{\n\t\t\tReplyMarkup: telebot.ReplyMarkup{\n\t\t\t\tForceReply: true,\n\t\t\t\tCustomKeyboard: [][]string{\n\t\t\t\t\t[]string{yobg_command},\n\t\t\t\t\t[]string{yofood_command},\n\t\t\t\t\t[]string{yomove_command},\n\t\t\t\t\t[]string{yolow_command},\n\t\t\t\t},\n\t\t\t\tResizeKeyboard: true,\n\t\t\t\tOneTimeKeyboard: false,\n\t\t\t},\n\t\t})\n\treturn\n}\n\nfunc (this *basics) yesNoOpts() *telebot.SendOptions {\n\treturn &telebot.SendOptions{\n\t\tReplyMarkup: telebot.ReplyMarkup{\n\t\t\tForceReply: true,\n\t\t\tCustomKeyboard: [][]string{\n\t\t\t\t[]string{this.getLanguage().Yes[rand.Intn(len(this.getLanguage().Yes))]},\n\t\t\t\t[]string{this.getLanguage().No[rand.Intn(len(this.getLanguage().No))]},\n\t\t\t},\n\t\t\tResizeKeyboard: true,\n\t\t\tOneTimeKeyboard: true,\n\t\t},\n\t}\n}\n\nfunc (this *basics) bg(msg telebot.Message) {\n\tthis.getBot().SendMessage(msg.Chat,\n\t\tthis.getLanguage().Bg.Question,\n\t\t&telebot.SendOptions{\n\t\t\tReplyMarkup: telebot.ReplyMarkup{\n\t\t\t\tForceReply: true,\n\t\t\t\tCustomKeyboard: [][]string{\n\t\t\t\t\t[]string{this.getLanguage().Bg.Above.Text},\n\t\t\t\t\t[]string{this.getLanguage().Bg.In.Text},\n\t\t\t\t\t[]string{this.getLanguage().Bg.Below.Text},\n\t\t\t\t},\n\t\t\t\tResizeKeyboard: true,\n\t\t\t\tOneTimeKeyboard: true,\n\t\t\t},\n\t\t})\n\treturn\n}\n\nfunc (this *basics) bgFeedback(msg telebot.Message) {\n\tswitch {\n\tcase msg.Text == this.getLanguage().Bg.Above.Text:\n\t\tthis.getBot().SendMessage(msg.Chat, this.getLanguage().Bg.Above.Feedback[rand.Intn(len(this.getLanguage().Bg.Above.Feedback))], nil)\n\t\tthis.pause(msg)\n\t\tthis.getBot().SendMessage(msg.Chat, this.getLanguage().Bg.Above.FollowUp[rand.Intn(len(this.getLanguage().Bg.Above.FollowUp))], this.yesNoOpts())\n\t\treturn\n\tcase msg.Text == this.getLanguage().Bg.In.Text:\n\t\tthis.getBot().SendMessage(msg.Chat, this.getLanguage().Bg.In.Feedback[rand.Intn(len(this.getLanguage().Bg.In.Feedback))], nil)\n\t\tthis.pause(msg)\n\t\tthis.getBot().SendMessage(msg.Chat, this.getLanguage().Bg.In.FollowUp[rand.Intn(len(this.getLanguage().Bg.In.FollowUp))], this.yesNoOpts())\n\t\treturn\n\tcase msg.Text == this.getLanguage().Bg.Below.Text:\n\t\tthis.getBot().SendMessage(msg.Chat, this.getLanguage().Bg.Below.Feedback[rand.Intn(len(this.getLanguage().Bg.Below.Feedback))], nil)\n\t\tthis.pause(msg)\n\t\tthis.getBot().SendMessage(msg.Chat, this.getLanguage().Bg.Below.FollowUp[rand.Intn(len(this.getLanguage().Bg.Below.FollowUp))], this.yesNoOpts())\n\t\treturn\n\t}\n\treturn\n}\n\nfunc (this *basics) low(msg telebot.Message) {\n\tthis.getBot().SendMessage(msg.Chat,\n\t\tthis.getLanguage().Low.Question,\n\t\t&telebot.SendOptions{\n\t\t\tReplyMarkup: telebot.ReplyMarkup{\n\t\t\t\tForceReply: true,\n\t\t\t\tCustomKeyboard: [][]string{\n\t\t\t\t\t[]string{this.getLanguage().Low.Good.Text},\n\t\t\t\t\t[]string{this.getLanguage().Low.NotGood.Text},\n\t\t\t\t\t[]string{this.getLanguage().Low.Other.Text},\n\t\t\t\t},\n\t\t\t\tResizeKeyboard: true,\n\t\t\t\tOneTimeKeyboard: true,\n\t\t\t},\n\t\t})\n\treturn\n}\n\nfunc (this *basics) lowFeedBack(msg telebot.Message) {\n\tswitch {\n\tcase msg.Text == this.getLanguage().Low.Good.Text:\n\t\tthis.getBot().SendMessage(\n\t\t\tmsg.Chat,\n\t\t\tthis.getLanguage().Low.Good.Feedback[rand.Intn(len(this.getLanguage().Low.Good.Feedback))],\n\t\t\tnil,\n\t\t)\n\t\tthis.pause(msg)\n\t\tthis.getBot().SendMessage(\n\t\t\tmsg.Chat,\n\t\t\tthis.getLanguage().Low.Good.Feedback[rand.Intn(len(this.getLanguage().Low.Good.Feedback))],\n\t\t\tthis.yesNoOpts(),\n\t\t)\n\t\treturn\n\tcase msg.Text == this.getLanguage().Low.NotGood.Text:\n\t\tthis.getBot().SendMessage(\n\t\t\tmsg.Chat,\n\t\t\tthis.getLanguage().Low.NotGood.Feedback[rand.Intn(len(this.getLanguage().Low.NotGood.Feedback))],\n\t\t\tnil,\n\t\t)\n\t\tthis.pause(msg)\n\t\tthis.getBot().SendMessage(\n\t\t\tmsg.Chat,\n\t\t\tthis.getLanguage().Low.NotGood.FollowUp[rand.Intn(len(this.getLanguage().Low.NotGood.FollowUp))],\n\t\t\tthis.yesNoOpts(),\n\t\t)\n\t\treturn\n\tcase msg.Text == this.getLanguage().Low.Other.Text:\n\t\tthis.getBot().SendMessage(\n\t\t\tmsg.Chat,\n\t\t\tthis.getLanguage().Low.Other.Feedback[rand.Intn(len(this.getLanguage().Low.Other.Feedback))],\n\t\t\tnil,\n\t\t)\n\t\tthis.pause(msg)\n\t\tthis.getBot().SendMessage(\n\t\t\tmsg.Chat,\n\t\t\tthis.getLanguage().Low.Other.FollowUp[rand.Intn(len(this.getLanguage().Low.Other.FollowUp))],\n\t\t\tthis.yesNoOpts(),\n\t\t)\n\t\treturn\n\t}\n\treturn\n}\n\nfunc (this *basics) yoFood(msg telebot.Message) {\n\tthis.getBot().SendMessage(msg.Chat,\n\t\tthis.getLanguage().Food.Question,\n\t\t&telebot.SendOptions{\n\t\t\tReplyMarkup: telebot.ReplyMarkup{\n\t\t\t\tForceReply: true,\n\t\t\t\tCustomKeyboard: [][]string{\n\t\t\t\t\t[]string{this.getLanguage().Food.Snack},\n\t\t\t\t\t[]string{this.getLanguage().Food.Meal},\n\t\t\t\t\t[]string{this.getLanguage().Food.Other},\n\t\t\t\t},\n\t\t\t\tResizeKeyboard: true,\n\t\t\t\tOneTimeKeyboard: true,\n\t\t\t},\n\t\t})\n\treturn\n}\n\nfunc (this *basics) yoMove(msg telebot.Message) {\n\tthis.getBot().SendMessage(msg.Chat,\n\t\tthis.getLanguage().Move.Question,\n\t\t&telebot.SendOptions{\n\t\t\tReplyMarkup: telebot.ReplyMarkup{\n\t\t\t\tForceReply: true,\n\t\t\t\tCustomKeyboard: [][]string{\n\t\t\t\t\t[]string{this.getLanguage().Move.Ex1},\n\t\t\t\t\t[]string{this.getLanguage().Move.Ex2},\n\t\t\t\t\t[]string{this.getLanguage().Move.Ex3},\n\t\t\t\t\t[]string{this.getLanguage().Move.Ex4},\n\t\t\t\t},\n\t\t\t\tResizeKeyboard: true,\n\t\t\t\tOneTimeKeyboard: true,\n\t\t\t},\n\t\t})\n\treturn\n}\nfix to load configpackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"log\"\n\t\"math\/rand\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/jh-bate\/fantail-bot\/Godeps\/_workspace\/src\/github.com\/tucnak\/telebot\"\n)\n\nconst (\n\t\/\/commands\n\tyostart_command = \"\/start\"\n\tyobg_command = \"\/yobg\"\n\tyolow_command = \"\/yolow\"\n\tyomove_command = \"\/yomove\"\n\tyofood_command = \"\/yofood\"\n\n\ttyping_action = \"typing\"\n\n\tnote_json = `{\"type\":\"note\",\"user\":\"%s\",\"data\":{\"text\":\"%s\"},\"time\":\"%s\"}`\n)\n\n\/\/our bot\nvar fBot *fantailBot\n\ntype (\n\tlang struct {\n\t\tGreetings []string `json:\"greet\"`\n\t\tGoodbyes []string `json:\"goodbye\"`\n\t\tYes []string `json:\"yes\"`\n\t\tNo []string `json:\"no\"`\n\t\tBg struct {\n\t\t\tComment string `json:\"comment\"`\n\t\t\tQuestion string `json:\"question\"`\n\t\t\tAbove option `json:\"above\"`\n\t\t\tIn option `json:\"in\"`\n\t\t\tBelow option `json:\"below\"`\n\t\t\tThank string `json:\"thank\"`\n\t\t} `json:\"bg\"`\n\t\tMove struct {\n\t\t\tComment string `json:\"comment\"`\n\t\t\tQuestion string `json:\"question\"`\n\t\t\tEx1 string `json:\"typeOne\"`\n\t\t\tEx2 string `json:\"typeTwo\"`\n\t\t\tEx3 string `json:\"typeThree\"`\n\t\t\tEx4 string `json:\"typeFour\"`\n\t\t\tThank string `json:\"thank\"`\n\t\t} `json:\"move\"`\n\t\tFood struct {\n\t\t\tComment string `json:\"comment\"`\n\t\t\tQuestion string `json:\"question\"`\n\t\t\tSnack string `json:\"snack\"`\n\t\t\tMeal string `json:\"meal\"`\n\t\t\tOther string `json:\"other\"`\n\t\t\tThank string `json:\"thank\"`\n\t\t} `json:\"food\"`\n\t\tLow struct {\n\t\t\tComment string `json:\"comment\"`\n\t\t\tQuestion string `json:\"question\"`\n\t\t\tGood option `json:\"good\"`\n\t\t\tNotGood option `json:\"notGood\"`\n\t\t\tOther option `json:\"other\"`\n\t\t\tThank string `json:\"thank\"`\n\t\t} `json:\"low\"`\n\t}\n\n\toption struct {\n\t\tText string `json:\"text\"`\n\t\tFeedback []string `json:\"feedback\"`\n\t\tFollowUp []string `json:\"followUp\"`\n\t}\n\n\tfantailBot struct {\n\t\tprocess\n\t\tbot *telebot.Bot\n\t\t*lang\n\t}\n\tprocess interface {\n\t\tgetBot() *telebot.Bot\n\t\tgetLanguage() *lang\n\t\tisRunning(string) bool\n\t\trunningName() string\n\t\taddPart(*part)\n\t\trun(telebot.Message)\n\t}\n\tpart struct {\n\t\tfn func(msg telebot.Message)\n\t\ttoRun bool\n\t}\n)\n\nfunc loadLanguage() *lang {\n\n\tfile, _ := os.Open(\".\/languageConfig.json\")\n\tdecoder := json.NewDecoder(file)\n\tvar language lang\n\terr := decoder.Decode(&language)\n\tif err != nil {\n\t\tlog.Panic(\"could not load language \", err.Error())\n\t}\n\treturn &language\n}\n\nfunc getfBot() *fantailBot {\n\tbotToken := os.Getenv(\"BOT_TOKEN\")\n\n\tif botToken == \"\" {\n\t\tlog.Fatal(\"$BOT_TOKEN must be set\")\n\t}\n\n\tbot, err := telebot.NewBot(botToken)\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn &fantailBot{bot: bot, lang: loadLanguage()}\n}\n\nfunc (this *fantailBot) isCurrentlyRunning(processName string) bool {\n\tif this.process != nil && this.process.runningName() == processName {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc main() {\n\n\tfBot = getfBot()\n\n\tmessages := make(chan telebot.Message)\n\tfBot.bot.Listen(messages, 1*time.Second)\n\n\tfor msg := range messages {\n\n\t\tlog.Println(\"incomming msg\", msg.Text)\n\t\tif fBot.process != nil {\n\t\t\tlog.Println(\"running process \", fBot.process.runningName())\n\t\t}\n\t\tif strings.Contains(msg.Text, yostart_command) {\n\t\t\t\/\/show all options\n\t\t\tb := newBasics(fBot, yostart_command)\n\t\t\tb.options(msg)\n\t\t} else if strings.Contains(msg.Text, yobg_command) || fBot.isCurrentlyRunning(yobg_command) {\n\t\t\tif strings.Contains(msg.Text, yobg_command) {\n\t\t\t\tb := newBasics(fBot, yobg_command)\n\t\t\t\tb.addPart(&part{fn: b.bg, toRun: true})\n\t\t\t\tb.addPart(&part{fn: b.bgFeedback, toRun: true})\n\t\t\t\tb.addPart(&part{fn: b.seeYou, toRun: true})\n\t\t\t\tfBot.setProcess(b)\n\t\t\t}\n\n\t\t\tfBot.process.run(msg)\n\t\t} else if strings.Contains(msg.Text, yomove_command) || fBot.isCurrentlyRunning(yomove_command) {\n\t\t\tif strings.Contains(msg.Text, yomove_command) {\n\t\t\t\tb := newBasics(fBot, yomove_command)\n\t\t\t\tb.addPart(&part{fn: b.yoMove, toRun: true})\n\t\t\t\tb.addPart(&part{fn: b.seeYou, toRun: true})\n\t\t\t\tfBot.setProcess(b)\n\t\t\t}\n\n\t\t\tfBot.process.run(msg)\n\t\t} else if strings.Contains(msg.Text, yofood_command) || fBot.isCurrentlyRunning(yofood_command) {\n\t\t\tif strings.Contains(msg.Text, yofood_command) {\n\t\t\t\tb := newBasics(fBot, yofood_command)\n\t\t\t\tb.addPart(&part{fn: b.yoFood, toRun: true})\n\t\t\t\tb.addPart(&part{fn: b.seeYou, toRun: true})\n\t\t\t\tfBot.setProcess(b)\n\t\t\t}\n\n\t\t\tfBot.process.run(msg)\n\t\t} else if strings.Contains(msg.Text, yolow_command) || fBot.isCurrentlyRunning(yolow_command) {\n\t\t\tif strings.Contains(msg.Text, yolow_command) {\n\t\t\t\tb := newBasics(fBot, yolow_command)\n\t\t\t\tb.addPart(&part{fn: b.low, toRun: true})\n\t\t\t\tb.addPart(&part{fn: b.lowFeedBack, toRun: true})\n\t\t\t\tb.addPart(&part{fn: b.seeYou, toRun: true})\n\t\t\t\tfBot.setProcess(b)\n\t\t\t}\n\t\t\tfBot.process.run(msg)\n\t\t}\n\n\t}\n}\n\ntype basics struct {\n\tfBot *fantailBot\n\tparts []*part\n\tname string\n}\n\nfunc newBasics(fBot *fantailBot, name string) *basics {\n\treturn &basics{fBot: fBot, name: name}\n}\n\nfunc (this *fantailBot) setProcess(p *basics) {\n\tthis.process = nil\n\tthis.process = p\n\treturn\n}\n\nfunc (this *basics) seeYou(msg telebot.Message) {\n\tthis.getBot().SendMessage(\n\t\tmsg.Chat,\n\t\tthis.getLanguage().Goodbyes[rand.Intn(len(this.getLanguage().Goodbyes))],\n\t\t&telebot.SendOptions{\n\t\t\tReplyMarkup: telebot.ReplyMarkup{\n\t\t\t\tForceReply: true,\n\t\t\t\tCustomKeyboard: [][]string{\n\t\t\t\t\t[]string{this.getLanguage().Goodbyes[rand.Intn(len(this.getLanguage().Goodbyes))]},\n\t\t\t\t},\n\t\t\t\tResizeKeyboard: true,\n\t\t\t\tOneTimeKeyboard: true,\n\t\t\t},\n\t\t})\n\treturn\n}\n\nfunc (this *basics) pause(msg telebot.Message) {\n\tthis.getBot().SendChatAction(msg.Chat, typing_action)\n\ttime.Sleep(2 * time.Second)\n\treturn\n}\n\nfunc (this *basics) addPart(p *part) {\n\tthis.parts = append(this.parts, p)\n\treturn\n}\n\nfunc (this *basics) isRunning(name string) bool {\n\treturn this.name == name\n}\n\nfunc (this *basics) runningName() string {\n\treturn this.name\n}\n\nfunc (this *basics) run(m telebot.Message) {\n\tfor i := range this.parts {\n\t\tlog.Println(\"checking \", i, \"of\", len(this.parts), \"run?\", this.parts[i].toRun)\n\t\tif this.parts[i].toRun {\n\t\t\tlog.Println(\"running \", i)\n\t\t\tthis.parts[i].toRun = false\n\t\t\tthis.parts[i].fn(m)\n\t\t\tlog.Println(\"has run \", i)\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (this *basics) getBot() *telebot.Bot {\n\treturn this.fBot.bot\n}\n\nfunc (this *basics) getLanguage() *lang {\n\treturn this.fBot.lang\n}\n\nfunc (this *basics) options(msg telebot.Message) {\n\tthis.getBot().SendMessage(msg.Chat,\n\t\tfmt.Sprintf(\"%s %s! What can we do for you?\", this.getLanguage().Greetings[rand.Intn(len(this.getLanguage().Greetings))], msg.Chat.FirstName),\n\t\t&telebot.SendOptions{\n\t\t\tReplyMarkup: telebot.ReplyMarkup{\n\t\t\t\tForceReply: true,\n\t\t\t\tCustomKeyboard: [][]string{\n\t\t\t\t\t[]string{yobg_command},\n\t\t\t\t\t[]string{yofood_command},\n\t\t\t\t\t[]string{yomove_command},\n\t\t\t\t\t[]string{yolow_command},\n\t\t\t\t},\n\t\t\t\tResizeKeyboard: true,\n\t\t\t\tOneTimeKeyboard: false,\n\t\t\t},\n\t\t})\n\treturn\n}\n\nfunc (this *basics) yesNoOpts() *telebot.SendOptions {\n\treturn &telebot.SendOptions{\n\t\tReplyMarkup: telebot.ReplyMarkup{\n\t\t\tForceReply: true,\n\t\t\tCustomKeyboard: [][]string{\n\t\t\t\t[]string{this.getLanguage().Yes[rand.Intn(len(this.getLanguage().Yes))]},\n\t\t\t\t[]string{this.getLanguage().No[rand.Intn(len(this.getLanguage().No))]},\n\t\t\t},\n\t\t\tResizeKeyboard: true,\n\t\t\tOneTimeKeyboard: true,\n\t\t},\n\t}\n}\n\nfunc (this *basics) bg(msg telebot.Message) {\n\tthis.getBot().SendMessage(msg.Chat,\n\t\tthis.getLanguage().Bg.Question,\n\t\t&telebot.SendOptions{\n\t\t\tReplyMarkup: telebot.ReplyMarkup{\n\t\t\t\tForceReply: true,\n\t\t\t\tCustomKeyboard: [][]string{\n\t\t\t\t\t[]string{this.getLanguage().Bg.Above.Text},\n\t\t\t\t\t[]string{this.getLanguage().Bg.In.Text},\n\t\t\t\t\t[]string{this.getLanguage().Bg.Below.Text},\n\t\t\t\t},\n\t\t\t\tResizeKeyboard: true,\n\t\t\t\tOneTimeKeyboard: true,\n\t\t\t},\n\t\t})\n\treturn\n}\n\nfunc (this *basics) bgFeedback(msg telebot.Message) {\n\tswitch {\n\tcase msg.Text == this.getLanguage().Bg.Above.Text:\n\t\tthis.getBot().SendMessage(msg.Chat, this.getLanguage().Bg.Above.Feedback[rand.Intn(len(this.getLanguage().Bg.Above.Feedback))], nil)\n\t\tthis.pause(msg)\n\t\tthis.getBot().SendMessage(msg.Chat, this.getLanguage().Bg.Above.FollowUp[rand.Intn(len(this.getLanguage().Bg.Above.FollowUp))], this.yesNoOpts())\n\t\treturn\n\tcase msg.Text == this.getLanguage().Bg.In.Text:\n\t\tthis.getBot().SendMessage(msg.Chat, this.getLanguage().Bg.In.Feedback[rand.Intn(len(this.getLanguage().Bg.In.Feedback))], nil)\n\t\tthis.pause(msg)\n\t\tthis.getBot().SendMessage(msg.Chat, this.getLanguage().Bg.In.FollowUp[rand.Intn(len(this.getLanguage().Bg.In.FollowUp))], this.yesNoOpts())\n\t\treturn\n\tcase msg.Text == this.getLanguage().Bg.Below.Text:\n\t\tthis.getBot().SendMessage(msg.Chat, this.getLanguage().Bg.Below.Feedback[rand.Intn(len(this.getLanguage().Bg.Below.Feedback))], nil)\n\t\tthis.pause(msg)\n\t\tthis.getBot().SendMessage(msg.Chat, this.getLanguage().Bg.Below.FollowUp[rand.Intn(len(this.getLanguage().Bg.Below.FollowUp))], this.yesNoOpts())\n\t\treturn\n\t}\n\treturn\n}\n\nfunc (this *basics) low(msg telebot.Message) {\n\tthis.getBot().SendMessage(msg.Chat,\n\t\tthis.getLanguage().Low.Question,\n\t\t&telebot.SendOptions{\n\t\t\tReplyMarkup: telebot.ReplyMarkup{\n\t\t\t\tForceReply: true,\n\t\t\t\tCustomKeyboard: [][]string{\n\t\t\t\t\t[]string{this.getLanguage().Low.Good.Text},\n\t\t\t\t\t[]string{this.getLanguage().Low.NotGood.Text},\n\t\t\t\t\t[]string{this.getLanguage().Low.Other.Text},\n\t\t\t\t},\n\t\t\t\tResizeKeyboard: true,\n\t\t\t\tOneTimeKeyboard: true,\n\t\t\t},\n\t\t})\n\treturn\n}\n\nfunc (this *basics) lowFeedBack(msg telebot.Message) {\n\tswitch {\n\tcase msg.Text == this.getLanguage().Low.Good.Text:\n\t\tthis.getBot().SendMessage(\n\t\t\tmsg.Chat,\n\t\t\tthis.getLanguage().Low.Good.Feedback[rand.Intn(len(this.getLanguage().Low.Good.Feedback))],\n\t\t\tnil,\n\t\t)\n\t\tthis.pause(msg)\n\t\tthis.getBot().SendMessage(\n\t\t\tmsg.Chat,\n\t\t\tthis.getLanguage().Low.Good.Feedback[rand.Intn(len(this.getLanguage().Low.Good.Feedback))],\n\t\t\tthis.yesNoOpts(),\n\t\t)\n\t\treturn\n\tcase msg.Text == this.getLanguage().Low.NotGood.Text:\n\t\tthis.getBot().SendMessage(\n\t\t\tmsg.Chat,\n\t\t\tthis.getLanguage().Low.NotGood.Feedback[rand.Intn(len(this.getLanguage().Low.NotGood.Feedback))],\n\t\t\tnil,\n\t\t)\n\t\tthis.pause(msg)\n\t\tthis.getBot().SendMessage(\n\t\t\tmsg.Chat,\n\t\t\tthis.getLanguage().Low.NotGood.FollowUp[rand.Intn(len(this.getLanguage().Low.NotGood.FollowUp))],\n\t\t\tthis.yesNoOpts(),\n\t\t)\n\t\treturn\n\tcase msg.Text == this.getLanguage().Low.Other.Text:\n\t\tthis.getBot().SendMessage(\n\t\t\tmsg.Chat,\n\t\t\tthis.getLanguage().Low.Other.Feedback[rand.Intn(len(this.getLanguage().Low.Other.Feedback))],\n\t\t\tnil,\n\t\t)\n\t\tthis.pause(msg)\n\t\tthis.getBot().SendMessage(\n\t\t\tmsg.Chat,\n\t\t\tthis.getLanguage().Low.Other.FollowUp[rand.Intn(len(this.getLanguage().Low.Other.FollowUp))],\n\t\t\tthis.yesNoOpts(),\n\t\t)\n\t\treturn\n\t}\n\treturn\n}\n\nfunc (this *basics) yoFood(msg telebot.Message) {\n\tthis.getBot().SendMessage(msg.Chat,\n\t\tthis.getLanguage().Food.Question,\n\t\t&telebot.SendOptions{\n\t\t\tReplyMarkup: telebot.ReplyMarkup{\n\t\t\t\tForceReply: true,\n\t\t\t\tCustomKeyboard: [][]string{\n\t\t\t\t\t[]string{this.getLanguage().Food.Snack},\n\t\t\t\t\t[]string{this.getLanguage().Food.Meal},\n\t\t\t\t\t[]string{this.getLanguage().Food.Other},\n\t\t\t\t},\n\t\t\t\tResizeKeyboard: true,\n\t\t\t\tOneTimeKeyboard: true,\n\t\t\t},\n\t\t})\n\treturn\n}\n\nfunc (this *basics) yoMove(msg telebot.Message) {\n\tthis.getBot().SendMessage(msg.Chat,\n\t\tthis.getLanguage().Move.Question,\n\t\t&telebot.SendOptions{\n\t\t\tReplyMarkup: telebot.ReplyMarkup{\n\t\t\t\tForceReply: true,\n\t\t\t\tCustomKeyboard: [][]string{\n\t\t\t\t\t[]string{this.getLanguage().Move.Ex1},\n\t\t\t\t\t[]string{this.getLanguage().Move.Ex2},\n\t\t\t\t\t[]string{this.getLanguage().Move.Ex3},\n\t\t\t\t\t[]string{this.getLanguage().Move.Ex4},\n\t\t\t\t},\n\t\t\t\tResizeKeyboard: true,\n\t\t\t\tOneTimeKeyboard: true,\n\t\t\t},\n\t\t})\n\treturn\n}\n<|endoftext|>"} {"text":"package raft\n\nimport (\n\t\"encoding\/json\"\n\tgolog \"log\"\n)\n\ntype Interface interface {\n\tStep(m Message)\n\tMsgs() []Message\n}\n\ntype tick int\n\ntype config struct {\n\tNodeId int\n\tAddress string\n}\n\ntype Node struct {\n\t\/\/ election timeout and heartbeat timeout in tick\n\telection tick\n\theartbeat tick\n\n\t\/\/ elapsed ticks after the last reset\n\telapsed tick\n\tsm *stateMachine\n}\n\nfunc New(id int, heartbeat, election tick) *Node {\n\tif election < heartbeat*3 {\n\t\tpanic(\"election is least three times as heartbeat [election: %d, heartbeat: %d]\")\n\t}\n\n\tn := &Node{\n\t\theartbeat: heartbeat,\n\t\telection: election,\n\t\tsm: newStateMachine(id, []int{id}),\n\t}\n\n\treturn n\n}\n\nfunc Dictate(n *Node) *Node {\n\tn.Step(Message{Type: msgHup})\n\tn.Add(n.Id())\n\treturn n\n}\n\nfunc (n *Node) Id() int { return n.sm.id }\n\n\/\/ Propose asynchronously proposes data be applied to the underlying state machine.\nfunc (n *Node) Propose(data []byte) { n.propose(normal, data) }\n\nfunc (n *Node) propose(t int, data []byte) {\n\tn.Step(Message{Type: msgProp, Entries: []Entry{{Type: t, Data: data}}})\n}\n\nfunc (n *Node) Add(id int) { n.updateConf(configAdd, &config{NodeId: id}) }\n\nfunc (n *Node) Remove(id int) { n.updateConf(configRemove, &config{NodeId: id}) }\n\nfunc (n *Node) Msgs() []Message {\n\treturn n.sm.Msgs()\n}\n\nfunc (n *Node) Step(m Message) {\n\tl := len(n.sm.msgs)\n\tn.sm.Step(m)\n\tfor _, m := range n.sm.msgs[l:] {\n\t\t\/\/ reset elapsed in two cases:\n\t\t\/\/ msgAppResp -> heard from the leader of the same term\n\t\t\/\/ msgVoteResp with grant -> heard from the candidate the node voted for\n\t\tswitch m.Type {\n\t\tcase msgAppResp:\n\t\t\tn.elapsed = 0\n\t\tcase msgVoteResp:\n\t\t\tif m.Index >= 0 {\n\t\t\t\tn.elapsed = 0\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ Next applies all available committed commands.\nfunc (n *Node) Next() []Entry {\n\tents := n.sm.nextEnts()\n\tnents := make([]Entry, 0)\n\tfor i := range ents {\n\t\tswitch ents[i].Type {\n\t\tcase normal:\n\t\t\t\/\/ dispatch to the application state machine\n\t\t\tnents = append(nents, ents[i])\n\t\tcase configAdd:\n\t\t\tc := new(config)\n\t\t\tif err := json.Unmarshal(ents[i].Data, c); err != nil {\n\t\t\t\tgolog.Println(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tn.sm.Add(c.NodeId)\n\t\tcase configRemove:\n\t\t\tc := new(config)\n\t\t\tif err := json.Unmarshal(ents[i].Data, c); err != nil {\n\t\t\t\tgolog.Println(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tn.sm.Remove(c.NodeId)\n\t\tdefault:\n\t\t\tpanic(\"unexpected entry type\")\n\t\t}\n\t}\n\treturn nents\n}\n\n\/\/ Tick triggers the node to do a tick.\n\/\/ If the current elapsed is greater or equal than the timeout,\n\/\/ node will send corresponding message to the statemachine.\nfunc (n *Node) Tick() {\n\ttimeout, msgType := n.election, msgHup\n\tif n.sm.state == stateLeader {\n\t\ttimeout, msgType = n.heartbeat, msgBeat\n\t}\n\tif n.elapsed >= timeout {\n\t\tn.Step(Message{Type: msgType})\n\t\tn.elapsed = 0\n\t} else {\n\t\tn.elapsed++\n\t}\n}\n\nfunc (n *Node) updateConf(t int, c *config) {\n\tdata, err := json.Marshal(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tn.propose(t, data)\n}\nraft: make Msgs one linepackage raft\n\nimport (\n\t\"encoding\/json\"\n\tgolog \"log\"\n)\n\ntype Interface interface {\n\tStep(m Message)\n\tMsgs() []Message\n}\n\ntype tick int\n\ntype config struct {\n\tNodeId int\n\tAddress string\n}\n\ntype Node struct {\n\t\/\/ election timeout and heartbeat timeout in tick\n\telection tick\n\theartbeat tick\n\n\t\/\/ elapsed ticks after the last reset\n\telapsed tick\n\tsm *stateMachine\n}\n\nfunc New(id int, heartbeat, election tick) *Node {\n\tif election < heartbeat*3 {\n\t\tpanic(\"election is least three times as heartbeat [election: %d, heartbeat: %d]\")\n\t}\n\n\tn := &Node{\n\t\theartbeat: heartbeat,\n\t\telection: election,\n\t\tsm: newStateMachine(id, []int{id}),\n\t}\n\n\treturn n\n}\n\nfunc Dictate(n *Node) *Node {\n\tn.Step(Message{Type: msgHup})\n\tn.Add(n.Id())\n\treturn n\n}\n\nfunc (n *Node) Id() int { return n.sm.id }\n\n\/\/ Propose asynchronously proposes data be applied to the underlying state machine.\nfunc (n *Node) Propose(data []byte) { n.propose(normal, data) }\n\nfunc (n *Node) propose(t int, data []byte) {\n\tn.Step(Message{Type: msgProp, Entries: []Entry{{Type: t, Data: data}}})\n}\n\nfunc (n *Node) Add(id int) { n.updateConf(configAdd, &config{NodeId: id}) }\n\nfunc (n *Node) Remove(id int) { n.updateConf(configRemove, &config{NodeId: id}) }\n\nfunc (n *Node) Msgs() []Message { return n.sm.Msgs() }\n\nfunc (n *Node) Step(m Message) {\n\tl := len(n.sm.msgs)\n\tn.sm.Step(m)\n\tfor _, m := range n.sm.msgs[l:] {\n\t\t\/\/ reset elapsed in two cases:\n\t\t\/\/ msgAppResp -> heard from the leader of the same term\n\t\t\/\/ msgVoteResp with grant -> heard from the candidate the node voted for\n\t\tswitch m.Type {\n\t\tcase msgAppResp:\n\t\t\tn.elapsed = 0\n\t\tcase msgVoteResp:\n\t\t\tif m.Index >= 0 {\n\t\t\t\tn.elapsed = 0\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ Next applies all available committed commands.\nfunc (n *Node) Next() []Entry {\n\tents := n.sm.nextEnts()\n\tnents := make([]Entry, 0)\n\tfor i := range ents {\n\t\tswitch ents[i].Type {\n\t\tcase normal:\n\t\t\t\/\/ dispatch to the application state machine\n\t\t\tnents = append(nents, ents[i])\n\t\tcase configAdd:\n\t\t\tc := new(config)\n\t\t\tif err := json.Unmarshal(ents[i].Data, c); err != nil {\n\t\t\t\tgolog.Println(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tn.sm.Add(c.NodeId)\n\t\tcase configRemove:\n\t\t\tc := new(config)\n\t\t\tif err := json.Unmarshal(ents[i].Data, c); err != nil {\n\t\t\t\tgolog.Println(err)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tn.sm.Remove(c.NodeId)\n\t\tdefault:\n\t\t\tpanic(\"unexpected entry type\")\n\t\t}\n\t}\n\treturn nents\n}\n\n\/\/ Tick triggers the node to do a tick.\n\/\/ If the current elapsed is greater or equal than the timeout,\n\/\/ node will send corresponding message to the statemachine.\nfunc (n *Node) Tick() {\n\ttimeout, msgType := n.election, msgHup\n\tif n.sm.state == stateLeader {\n\t\ttimeout, msgType = n.heartbeat, msgBeat\n\t}\n\tif n.elapsed >= timeout {\n\t\tn.Step(Message{Type: msgType})\n\t\tn.elapsed = 0\n\t} else {\n\t\tn.elapsed++\n\t}\n}\n\nfunc (n *Node) updateConf(t int, c *config) {\n\tdata, err := json.Marshal(c)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tn.propose(t, data)\n}\n<|endoftext|>"} {"text":"package rain\n\nimport (\n\t\"encoding\/xml\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"time\"\n)\n\n\/\/ Location0 struct\ntype Location0 struct {\n\tLat float32 `xml:\"lat\"`\n\tLng float32 `xml:\"lng\"`\n\tName string `xml:\"locationName\"`\n\tStationID string `xml:\"stationId\"`\n\tTime time.Time `xml:\"time>obsTime\"`\n\tWeatherElement []WeatherElement `xml:\"weatherElement\"`\n\tParameter []Parameter `xml:\"parameter\"`\n}\n\n\/\/ Location1 struct\ntype Location1 struct {\n\tGeocode int `xml:\"geocode\"`\n\tName string `xml:\"locationName\"`\n\tHazards Hazards `xml:\"hazardConditions>hazards\"`\n}\n\n\/\/ WeatherElement struct\ntype WeatherElement struct {\n\tName string `xml:\"elementName\"`\n\tValue float32 `xml:\"elementValue>value\"`\n}\n\n\/\/ Parameter struct\ntype Parameter struct {\n\tName string `xml:\"parameterName\"`\n\tValue string `xml:\"parameterValue\"`\n}\n\n\/\/ ValidTime struct\ntype ValidTime struct {\n\tStartTime time.Time `xml:\"startTime\"`\n\tEndTime time.Time `xml:\"endTime\"`\n}\n\n\/\/ AffectedAreas struct\ntype AffectedAreas struct {\n\tName string `xml:\"locationName\"`\n}\n\n\/\/ HazardInfo0 struct\ntype HazardInfo0 struct {\n\tLanguage string `xml:\"language\"`\n\tPhenomena string `xml:\"phenomena\"`\n\tSignificance string `xml:\"significance\"`\n}\n\n\/\/ HazardInfo1 struct\ntype HazardInfo1 struct {\n\tLanguage string `xml:\"language\"`\n\tPhenomena string `xml:\"phenomena\"`\n\tAffectedAreas []AffectedAreas `xml:\"affectedAreas>location\"`\n}\n\n\/\/ Hazards struct\ntype Hazards struct {\n\tInfo HazardInfo0 `xml:\"info\"`\n\tValidTime ValidTime `xml:\"validTime\"`\n\tHazardInfo HazardInfo1 `xml:\"hazard>info\"`\n}\n\n\/\/ ResultRaining struct\ntype ResultRaining struct {\n\tLocation []Location0 `xml:\"location\"`\n}\n\n\/\/ ResultWarning struct\ntype ResultWarning struct {\n\tLocation []Location1 `xml:\"dataset>location\"`\n}\n\nconst baseURL = \"http:\/\/opendata.cwb.gov.tw\/opendataapi?dataid=\"\nconst authKey = \"CWB-FB35C2AC-9286-4B7E-AD11-6BBB7F2855F7\"\nconst timeZone = \"Asia\/Taipei\"\n\nfunc fetchXML(url string) []byte {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\tfmt.Printf(\"error: %v\", err)\n\t\tos.Exit(1)\n\t}\n\n\txmldata, err := ioutil.ReadAll(resp.Body)\n\tresp.Body.Close()\n\tif err != nil {\n\t\tfmt.Printf(\"error: %v\", err)\n\t\tos.Exit(1)\n\t}\n\n\treturn xmldata\n}\n\n\/\/ GetRainingInfo \"雨量警示\"\nfunc GetRainingInfo(targets []string, noLevel bool) ([]string, string) {\n\tvar token = \"\"\n\tvar msgs = []string{}\n\n\trainLevel := map[string]float32{\n\t\t\"10minutes\": 5, \/\/ 5\n\t\t\"1hour\": 20, \/\/ 20\n\t}\n\n\turl := baseURL + \"O-A0002-001\" + \"&authorizationkey=\" + authKey\n\txmldata := fetchXML(url)\n\n\tv := ResultRaining{}\n\terr := xml.Unmarshal([]byte(xmldata), &v)\n\tif err != nil {\n\t\tlog.Printf(\"error: %v\", err)\n\t\treturn []string{}, \"\"\n\t}\n\n\tlog.Printf(\"### 雨量資訊正常連線,已取得 %d 筆地區資料 ###\\n\", len(v.Location))\n\n\tfor _, location := range v.Location {\n\t\tvar msg string\n\t\tfor _, parameter := range location.Parameter {\n\t\t\tif parameter.Name == \"CITY\" {\n\t\t\t\tfor _, target := range targets {\n\t\t\t\t\tif parameter.Value == target {\n\t\t\t\t\t\tfor _, element := range location.WeatherElement {\n\t\t\t\t\t\t\ttoken = location.Time.Format(\"20060102150405\")\n\n\t\t\t\t\t\t\tswitch element.Name {\n\t\t\t\t\t\t\tcase \"MIN_10\":\n\t\t\t\t\t\t\t\tif noLevel {\n\t\t\t\t\t\t\t\t\tif element.Value <= 0 {\n\t\t\t\t\t\t\t\t\t\tmsg = msg + fmt.Sprintf(\"%s:%s\", \"*10分鐘雨量*\", \"-\")\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tmsg = msg + fmt.Sprintf(\"%s:%.1f\", \"*10分鐘雨量*\", element.Value)\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tif element.Value <= 0 {\n\t\t\t\t\t\t\t\t\t\tlog.Printf(\"%s:%s\", \"*10分鐘雨量*\", \"-\")\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tlog.Printf(\"%s:%.1f\", \"*10分鐘雨量*\", element.Value)\n\t\t\t\t\t\t\t\t\t\tif element.Value >= rainLevel[\"10minutes\"] {\n\t\t\t\t\t\t\t\t\t\t\tmsg = msg + fmt.Sprintf(\"【%s】*豪大雨警報*\\n%s:%.1f \\n\", location.Name, \"10分鐘雨量\", element.Value)\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tcase \"RAIN\":\n\t\t\t\t\t\t\t\tif noLevel {\n\t\t\t\t\t\t\t\t\tif element.Value <= 0 {\n\t\t\t\t\t\t\t\t\t\tmsg = msg + fmt.Sprintf(\"【%s】\\n%s:%s\\n\", location.Name, \"時雨量\", \"-\")\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tmsg = msg + fmt.Sprintf(\"【%s】\\n%s:%.1f\\n\", location.Name, \"時雨量\", element.Value)\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tif element.Value <= 0 {\n\t\t\t\t\t\t\t\t\t\tlog.Printf(\"[%s]\", location.Name)\n\t\t\t\t\t\t\t\t\t\tlog.Printf(\"%s:%s\", \"時雨量\", \"-\")\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tlog.Printf(\"[%s]\", location.Name)\n\t\t\t\t\t\t\t\t\t\tlog.Printf(\"%s:%.1f\", \"時雨量\", element.Value)\n\t\t\t\t\t\t\t\t\t\tif element.Value >= rainLevel[\"1hour\"] {\n\t\t\t\t\t\t\t\t\t\t\tmsg = msg + fmt.Sprintf(\"【%s】*豪大雨警報*\\n%s:%.1f \\n\", location.Name, \"時雨量\", element.Value)\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif msg != \"\" {\n\t\t\tmsgs = append(msgs, msg)\n\t\t}\n\t}\n\n\treturn msgs, token\n}\n\n\/\/ GetWarningInfo \"豪大雨特報\"\nfunc GetWarningInfo(targets []string) ([]string, string) {\n\tvar token = \"\"\n\tvar msgs = []string{}\n\n\turl := baseURL + \"W-C0033-001\" + \"&authorizationkey=\" + authKey\n\txmldata := fetchXML(url)\n\n\tv := ResultWarning{}\n\terr := xml.Unmarshal([]byte(xmldata), &v)\n\tif err != nil {\n\t\tlog.Printf(\"error: %v\", err)\n\t\treturn []string{}, \"\"\n\t}\n\n\tlog.Printf(\"### 天氣警報資訊正常連線,已取得 %d 筆地區資料 ###\\n\", len(v.Location))\n\n\tlocal := time.Now()\n\tlocation, err := time.LoadLocation(timeZone)\n\tif err == nil {\n\t\tlocal = local.In(location)\n\t}\n\n\tvar hazardmsgs = \"\"\n\n\tfor i, location := range v.Location {\n\t\tif i == 0 {\n\t\t\ttoken = location.Hazards.ValidTime.StartTime.Format(\"20060102150405\") + \" \" + location.Hazards.ValidTime.EndTime.Format(\"20060102150405\")\n\t\t}\n\t\tif location.Hazards.Info.Phenomena != \"\" && location.Hazards.ValidTime.EndTime.After(local) {\n\t\t\tif targets != nil {\n\t\t\t\tfor _, name := range targets {\n\t\t\t\t\tif name == location.Name {\n\t\t\t\t\t\thazardmsgs = hazardmsgs + saveHazards(location) + \"\\n\\n\"\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\thazardmsgs = hazardmsgs + saveHazards(location) + \"\\n\\n\"\n\t\t\t}\n\t\t}\n\t}\n\n\tif hazardmsgs != \"\" {\n\t\tmsgs = append(msgs, hazardmsgs)\n\t}\n\n\treturn msgs, token\n}\n\nfunc saveHazards(location Location1) string {\n\tvar m string\n\n\tlog.Printf(\"【%s】%s%s\\n %s ~\\n %s\\n\", location.Name, location.Hazards.Info.Phenomena, location.Hazards.Info.Significance, location.Hazards.ValidTime.StartTime.Format(\"01\/02 15:04\"), location.Hazards.ValidTime.EndTime.Format(\"01\/02 15:04\"))\n\tm = fmt.Sprintf(\"【%s】%s%s\\n %s ~\\n %s\\n\", location.Name, location.Hazards.Info.Phenomena, location.Hazards.Info.Significance, location.Hazards.ValidTime.StartTime.Format(\"01\/02 15:04\"), location.Hazards.ValidTime.EndTime.Format(\"01\/02 15:04\"))\n\tif len(location.Hazards.HazardInfo.AffectedAreas) > 0 {\n\t\tlog.Printf(\"影響地區:\")\n\t\tm = m + \"影響地區:\"\n\t\tfor _, str := range location.Hazards.HazardInfo.AffectedAreas {\n\t\t\tlog.Printf(\"%s \", str.Name)\n\t\t\tm = m + fmt.Sprintf(\"%s \", str.Name)\n\t\t}\n\t}\n\n\treturn m\n}\nUpdate rain.gopackage rain\n\nimport (\n\t\"encoding\/xml\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"time\"\n)\n\n\/\/ Location0 struct\ntype Location0 struct {\n\tLat float32 `xml:\"lat\"`\n\tLng float32 `xml:\"lng\"`\n\tName string `xml:\"locationName\"`\n\tStationID string `xml:\"stationId\"`\n\tTime time.Time `xml:\"time>obsTime\"`\n\tWeatherElement []WeatherElement `xml:\"weatherElement\"`\n\tParameter []Parameter `xml:\"parameter\"`\n}\n\n\/\/ Location1 struct\ntype Location1 struct {\n\tGeocode int `xml:\"geocode\"`\n\tName string `xml:\"locationName\"`\n\tHazards Hazards `xml:\"hazardConditions>hazards\"`\n}\n\n\/\/ WeatherElement struct\ntype WeatherElement struct {\n\tName string `xml:\"elementName\"`\n\tValue float32 `xml:\"elementValue>value\"`\n}\n\n\/\/ Parameter struct\ntype Parameter struct {\n\tName string `xml:\"parameterName\"`\n\tValue string `xml:\"parameterValue\"`\n}\n\n\/\/ ValidTime struct\ntype ValidTime struct {\n\tStartTime time.Time `xml:\"startTime\"`\n\tEndTime time.Time `xml:\"endTime\"`\n}\n\n\/\/ AffectedAreas struct\ntype AffectedAreas struct {\n\tName string `xml:\"locationName\"`\n}\n\n\/\/ HazardInfo0 struct\ntype HazardInfo0 struct {\n\tLanguage string `xml:\"language\"`\n\tPhenomena string `xml:\"phenomena\"`\n\tSignificance string `xml:\"significance\"`\n}\n\n\/\/ HazardInfo1 struct\ntype HazardInfo1 struct {\n\tLanguage string `xml:\"language\"`\n\tPhenomena string `xml:\"phenomena\"`\n\tAffectedAreas []AffectedAreas `xml:\"affectedAreas>location\"`\n}\n\n\/\/ Hazards struct\ntype Hazards struct {\n\tInfo HazardInfo0 `xml:\"info\"`\n\tValidTime ValidTime `xml:\"validTime\"`\n\tHazardInfo HazardInfo1 `xml:\"hazard>info\"`\n}\n\n\/\/ ResultRaining struct\ntype ResultRaining struct {\n\tLocation []Location0 `xml:\"location\"`\n}\n\n\/\/ ResultWarning struct\ntype ResultWarning struct {\n\tLocation []Location1 `xml:\"dataset>location\"`\n}\n\nconst baseURL = \"http:\/\/opendata.cwb.gov.tw\/opendataapi?dataid=\"\nconst authKey = \"CWB-FB35C2AC-9286-4B7E-AD11-6BBB7F2855F7\"\nconst timeZone = \"Asia\/Taipei\"\n\nfunc fetchXML(url string) []byte {\n\tresp, err := http.Get(url)\n\tif err != nil {\n\t\tfmt.Printf(\"fetchXML http.Get error: %v\", err)\n\t\tos.Exit(1)\n\t}\n\n\txmldata, err := ioutil.ReadAll(resp.Body)\n\tresp.Body.Close()\n\tif err != nil {\n\t\tfmt.Printf(\"fetchXML ioutil.ReadAll error: %v\", err)\n\t\tos.Exit(1)\n\t}\n\n\treturn xmldata\n}\n\n\/\/ GetRainingInfo \"雨量警示\"\nfunc GetRainingInfo(targets []string, noLevel bool) ([]string, string) {\n\tvar token = \"\"\n\tvar msgs = []string{}\n\n\trainLevel := map[string]float32{\n\t\t\"10minutes\": 5, \/\/ 5\n\t\t\"1hour\": 20, \/\/ 20\n\t}\n\n\turl := baseURL + \"O-A0002-001\" + \"&authorizationkey=\" + authKey\n\txmldata := fetchXML(url)\n\n\tv := ResultRaining{}\n\terr := xml.Unmarshal([]byte(xmldata), &v)\n\tif err != nil {\n\t\tlog.Printf(\"GetRainingInfo fetchXML error: %v\", err)\n\t\treturn []string{}, \"\"\n\t}\n\n\tlog.Printf(\"### 雨量資訊正常連線,已取得 %d 筆地區資料 ###\\n\", len(v.Location))\n\n\tfor _, location := range v.Location {\n\t\tvar msg string\n\t\tfor _, parameter := range location.Parameter {\n\t\t\tif parameter.Name == \"CITY\" {\n\t\t\t\tfor _, target := range targets {\n\t\t\t\t\tif parameter.Value == target {\n\t\t\t\t\t\tfor _, element := range location.WeatherElement {\n\t\t\t\t\t\t\ttoken = location.Time.Format(\"20060102150405\")\n\n\t\t\t\t\t\t\tswitch element.Name {\n\t\t\t\t\t\t\tcase \"MIN_10\":\n\t\t\t\t\t\t\t\tif noLevel {\n\t\t\t\t\t\t\t\t\tif element.Value <= 0 {\n\t\t\t\t\t\t\t\t\t\tmsg = msg + fmt.Sprintf(\"%s:%s\", \"*10分鐘雨量*\", \"-\")\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tmsg = msg + fmt.Sprintf(\"%s:%.1f\", \"*10分鐘雨量*\", element.Value)\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tif element.Value <= 0 {\n\t\t\t\t\t\t\t\t\t\tlog.Printf(\"%s:%s\", \"*10分鐘雨量*\", \"-\")\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tlog.Printf(\"%s:%.1f\", \"*10分鐘雨量*\", element.Value)\n\t\t\t\t\t\t\t\t\t\tif element.Value >= rainLevel[\"10minutes\"] {\n\t\t\t\t\t\t\t\t\t\t\tmsg = msg + fmt.Sprintf(\"【%s】*豪大雨警報*\\n%s:%.1f \\n\", location.Name, \"10分鐘雨量\", element.Value)\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tcase \"RAIN\":\n\t\t\t\t\t\t\t\tif noLevel {\n\t\t\t\t\t\t\t\t\tif element.Value <= 0 {\n\t\t\t\t\t\t\t\t\t\tmsg = msg + fmt.Sprintf(\"【%s】\\n%s:%s\\n\", location.Name, \"時雨量\", \"-\")\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tmsg = msg + fmt.Sprintf(\"【%s】\\n%s:%.1f\\n\", location.Name, \"時雨量\", element.Value)\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tif element.Value <= 0 {\n\t\t\t\t\t\t\t\t\t\tlog.Printf(\"[%s]\", location.Name)\n\t\t\t\t\t\t\t\t\t\tlog.Printf(\"%s:%s\", \"時雨量\", \"-\")\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tlog.Printf(\"[%s]\", location.Name)\n\t\t\t\t\t\t\t\t\t\tlog.Printf(\"%s:%.1f\", \"時雨量\", element.Value)\n\t\t\t\t\t\t\t\t\t\tif element.Value >= rainLevel[\"1hour\"] {\n\t\t\t\t\t\t\t\t\t\t\tmsg = msg + fmt.Sprintf(\"【%s】*豪大雨警報*\\n%s:%.1f \\n\", location.Name, \"時雨量\", element.Value)\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif msg != \"\" {\n\t\t\tmsgs = append(msgs, msg)\n\t\t}\n\t}\n\n\treturn msgs, token\n}\n\n\/\/ GetWarningInfo \"豪大雨特報\"\nfunc GetWarningInfo(targets []string) ([]string, string) {\n\tvar token = \"\"\n\tvar msgs = []string{}\n\n\turl := baseURL + \"W-C0033-001\" + \"&authorizationkey=\" + authKey\n\txmldata := fetchXML(url)\n\n\tv := ResultWarning{}\n\terr := xml.Unmarshal([]byte(xmldata), &v)\n\tif err != nil {\n\t\tlog.Printf(\"GetWarningInfo fetchXML error: %v\", err)\n\t\treturn []string{}, \"\"\n\t}\n\n\tlog.Printf(\"### 天氣警報資訊正常連線,已取得 %d 筆地區資料 ###\\n\", len(v.Location))\n\n\tlocal := time.Now()\n\tlocation, err := time.LoadLocation(timeZone)\n\tif err == nil {\n\t\tlocal = local.In(location)\n\t}\n\n\tvar hazardmsgs = \"\"\n\n\tfor i, location := range v.Location {\n\t\tif i == 0 {\n\t\t\ttoken = location.Hazards.ValidTime.StartTime.Format(\"20060102150405\") + \" \" + location.Hazards.ValidTime.EndTime.Format(\"20060102150405\")\n\t\t}\n\t\tif location.Hazards.Info.Phenomena != \"\" && location.Hazards.ValidTime.EndTime.After(local) {\n\t\t\tif targets != nil {\n\t\t\t\tfor _, name := range targets {\n\t\t\t\t\tif name == location.Name {\n\t\t\t\t\t\thazardmsgs = hazardmsgs + saveHazards(location) + \"\\n\\n\"\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\thazardmsgs = hazardmsgs + saveHazards(location) + \"\\n\\n\"\n\t\t\t}\n\t\t}\n\t}\n\n\tif hazardmsgs != \"\" {\n\t\tmsgs = append(msgs, hazardmsgs)\n\t}\n\n\treturn msgs, token\n}\n\nfunc saveHazards(location Location1) string {\n\tvar m string\n\n\tlog.Printf(\"【%s】%s%s\\n %s ~\\n %s\\n\", location.Name, location.Hazards.Info.Phenomena, location.Hazards.Info.Significance, location.Hazards.ValidTime.StartTime.Format(\"01\/02 15:04\"), location.Hazards.ValidTime.EndTime.Format(\"01\/02 15:04\"))\n\tm = fmt.Sprintf(\"【%s】%s%s\\n %s ~\\n %s\\n\", location.Name, location.Hazards.Info.Phenomena, location.Hazards.Info.Significance, location.Hazards.ValidTime.StartTime.Format(\"01\/02 15:04\"), location.Hazards.ValidTime.EndTime.Format(\"01\/02 15:04\"))\n\tif len(location.Hazards.HazardInfo.AffectedAreas) > 0 {\n\t\tlog.Printf(\"影響地區:\")\n\t\tm = m + \"影響地區:\"\n\t\tfor _, str := range location.Hazards.HazardInfo.AffectedAreas {\n\t\t\tlog.Printf(\"%s \", str.Name)\n\t\t\tm = m + fmt.Sprintf(\"%s \", str.Name)\n\t\t}\n\t}\n\n\treturn m\n}\n<|endoftext|>"} {"text":"package gitbackend\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"github.com\/libgit2\/git2go\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"strings\"\n)\n\ntype FileStore struct {\n\trepo *git.Repository\n}\n\nfunc NewFileStore(path string, isBare bool) (fileStore FileStore, err error) {\n\trepo, err := git.InitRepository(path, isBare)\n\tif err != nil {\n\t\treturn\n\t}\n\tfileStore.repo = repo\n\treturn\n}\n\nfunc (this *FileStore) ReadDir(path string) (list []FileInfo, err error) {\n\tif strings.Trim(path, \"\/ \") == \"\" {\n\t\treturn this.readRootDir()\n\t} else {\n\t\treturn this.readSubDir(path)\n\t}\n}\n\nfunc (this *FileStore) readRootDir() (list []FileInfo, err error) {\n\theadCommitTree, err, noHead := this.headCommitTree()\n\tif err != nil {\n\t\t\/\/ return empty list for newly initialized repository without proper HEAD\n\t\t\/\/ usually the first commit sets a proper HEAD\n\t\t\/\/ this is only necessary for the root directory since there are no files after init\n\t\tif noHead {\n\t\t\terr = nil\n\t\t}\n\t\treturn\n\t}\n\tlist = this.listTree(headCommitTree)\n\treturn\n}\n\nfunc (this *FileStore) readSubDir(path string) (list []FileInfo, err error) {\n\theadCommitTree, err, _ := this.headCommitTree()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tentry, err := headCommitTree.EntryByPath(path)\n\tif err != nil {\n\t\treturn\n\t}\n\ttree, err := this.repo.LookupTree(entry.Id)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tlist = this.listTree(tree)\n\treturn\n}\n\nfunc (this *FileStore) listTree(tree *git.Tree) (list []FileInfo) {\n\tvar i uint64\n\tfor i = 0; i < tree.EntryCount(); i++ {\n\t\tentry := tree.EntryByIndex(i)\n\t\tisDir := entry.Type == git.ObjectTree\n\t\tlist = append(list, FileInfo{entry.Name, isDir})\n\t}\n\treturn\n}\n\nfunc (this *FileStore) Checksum(path string) (hexdigest string, err error) {\n\theadCommitTree, err, _ := this.headCommitTree()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tentry, err := headCommitTree.EntryByPath(path)\n\tif err != nil {\n\t\treturn\n\t}\n\thexdigest = entry.Id.String()\n\treturn\n}\n\nfunc (this *FileStore) ReadFile(path string) (reader io.Reader, err error) {\n\theadCommitTree, err, _ := this.headCommitTree()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tentry, err := headCommitTree.EntryByPath(path)\n\tif err != nil {\n\t\treturn\n\t}\n\tblob, err := this.repo.LookupBlob(entry.Id)\n\tif err != nil {\n\t\treturn\n\t}\n\treader = bytes.NewBuffer(blob.Contents())\n\treturn\n}\n\nfunc (this *FileStore) CreateDir(path string, commitInfo *CommitInfo) (err error) {\n\treader := strings.NewReader(\"\")\n\terr = this.WriteFile(fmt.Sprintf(\"%s\/.gitkeep\", path), reader, commitInfo)\n\treturn\n}\n\nfunc (this *FileStore) WriteFile(path string, reader io.Reader, commitInfo *CommitInfo) (err error) {\n\tblobOid, err := this.writeData(reader)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\toldTree, _, _ := this.headCommitTree()\n\tnewTreeId, err := this.updateTree(oldTree, path, blobOid)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\ttree, err := this.repo.LookupTree(newTreeId)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tsig := &git.Signature{\n\t\tName: commitInfo.AuthorName(),\n\t\tEmail: commitInfo.AuthorEmail(),\n\t\tWhen: commitInfo.Time(),\n\t}\n\n\tcommit, _, _ := this.headCommit()\n\tif commit == nil {\n\t\t_, err = this.repo.CreateCommit(\"HEAD\", sig, sig, commitInfo.Message(), tree)\n\n\t} else {\n\t\t_, err = this.repo.CreateCommit(\"HEAD\", sig, sig, commitInfo.Message(), tree, commit)\n\n\t}\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\treturn\n}\n\nfunc (this *FileStore) writeData(reader io.Reader) (blobOid *git.Oid, err error) {\n\todb, err := this.repo.Odb()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tdata, err := ioutil.ReadAll(reader)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tblobOid, err = odb.Write(data, git.ObjectBlob)\n\treturn\n}\n\nfunc (this *FileStore) updateTreeBlob(treebuilder *git.TreeBuilder, basename string, blobOid *git.Oid) (oid *git.Oid, err error) {\n\terr = treebuilder.Insert(basename, blobOid, int(git.FilemodeBlob))\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\treturn treebuilder.Write()\n}\n\nfunc (this *FileStore) updateTreeTree(treebuilder *git.TreeBuilder, basename string, childsPath string, blobOid *git.Oid) (oid *git.Oid, err error) {\n\tnewTreeOid, err := treebuilder.Write()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tnewTree, err := this.repo.LookupTree(newTreeOid)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tvar childTree *git.Tree\n\n\toldChildTreeTreeEntry := newTree.EntryByName(basename)\n\tif oldChildTreeTreeEntry == nil {\n\t\t\/\/ no child tree entry found -> auto-create new sub tree\n\t} else {\n\t\tchildTree, err = this.repo.LookupTree(oldChildTreeTreeEntry.Id)\n\t}\n\n\tchildTreeOid, err2 := this.updateTree(childTree, childsPath, blobOid)\n\tif err2 != nil {\n\t\tfmt.Println(err2)\n\t\terr = err2\n\t\treturn\n\t}\n\n\terr = treebuilder.Insert(basename, childTreeOid, int(git.FilemodeTree))\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\toid, err = treebuilder.Write()\n\treturn\n}\n\nfunc (this *FileStore) updateTree(oldParentTree *git.Tree, path string, blobOid *git.Oid) (oid *git.Oid, err error) {\n\tvar treebuilder *git.TreeBuilder\n\tif oldParentTree == nil {\n\t\ttreebuilder, err = this.repo.TreeBuilder()\n\t} else {\n\t\ttreebuilder, err = this.repo.TreeBuilderFromTree(oldParentTree)\n\t}\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tparts := strings.SplitN(path, \"\/\", 2)\n\tif len(parts) == 1 {\n\t\treturn this.updateTreeBlob(treebuilder, parts[0], blobOid)\n\t} else {\n\t\treturn this.updateTreeTree(treebuilder, parts[0], parts[1], blobOid)\n\t}\n}\n\nfunc (this *FileStore) headCommitTree() (tree *git.Tree, err error, noHead bool) {\n\tcommit, err, noHead := this.headCommit()\n\tif err != nil {\n\t\treturn\n\t}\n\ttree, err = commit.Tree()\n\treturn\n}\n\nfunc (this *FileStore) headCommit() (commit *git.Commit, err error, noHead bool) {\n\toid, err, noHead := this.headCommitId()\n\tif err != nil {\n\t\treturn\n\t}\n\tcommit, err = this.repo.LookupCommit(oid)\n\treturn\n}\n\nfunc (this *FileStore) headCommitId() (oid *git.Oid, err error, noHead bool) {\n\theadRef, err := this.repo.LookupReference(\"HEAD\")\n\tif err != nil {\n\t\treturn\n\t}\n\tref, err := headRef.Resolve()\n\tif err != nil {\n\t\tnoHead = true\n\t\treturn\n\t}\n\toid = ref.Target()\n\tif oid == nil {\n\t\terr = fmt.Errorf(\"Could not get Target for HEAD(%s)\\n\", oid.String())\n\t}\n\treturn\n}\nCleanup file store.package gitbackend\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"github.com\/libgit2\/git2go\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"strings\"\n)\n\ntype FileStore struct {\n\trepo *git.Repository\n}\n\nfunc NewFileStore(path string, isBare bool) (fileStore FileStore, err error) {\n\trepo, err := git.InitRepository(path, isBare)\n\tif err != nil {\n\t\treturn\n\t}\n\tfileStore.repo = repo\n\treturn\n}\n\nfunc (this *FileStore) ReadDir(path string) (list []FileInfo, err error) {\n\tif strings.Trim(path, \"\/ \") == \"\" {\n\t\treturn this.readRootDir()\n\t} else {\n\t\treturn this.readSubDir(path)\n\t}\n}\n\nfunc (this *FileStore) readRootDir() (list []FileInfo, err error) {\n\theadCommitTree, err, noHead := this.headCommitTree()\n\tif err != nil {\n\t\t\/\/ return empty list for newly initialized repository without proper HEAD\n\t\t\/\/ usually the first commit sets a proper HEAD\n\t\t\/\/ this is only necessary for the root directory since there are no files after init\n\t\tif noHead {\n\t\t\terr = nil\n\t\t}\n\t\treturn\n\t}\n\tlist = this.listTree(headCommitTree)\n\treturn\n}\n\nfunc (this *FileStore) readSubDir(path string) (list []FileInfo, err error) {\n\theadCommitTree, err, _ := this.headCommitTree()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tentry, err := headCommitTree.EntryByPath(path)\n\tif err != nil {\n\t\treturn\n\t}\n\ttree, err := this.repo.LookupTree(entry.Id)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tlist = this.listTree(tree)\n\treturn\n}\n\nfunc (this *FileStore) listTree(tree *git.Tree) (list []FileInfo) {\n\tvar i uint64\n\tfor i = 0; i < tree.EntryCount(); i++ {\n\t\tentry := tree.EntryByIndex(i)\n\t\tisDir := entry.Type == git.ObjectTree\n\t\tlist = append(list, FileInfo{entry.Name, isDir})\n\t}\n\treturn\n}\n\nfunc (this *FileStore) Checksum(path string) (hexdigest string, err error) {\n\theadCommitTree, err, _ := this.headCommitTree()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tentry, err := headCommitTree.EntryByPath(path)\n\tif err != nil {\n\t\treturn\n\t}\n\thexdigest = entry.Id.String()\n\treturn\n}\n\nfunc (this *FileStore) ReadFile(path string) (reader io.Reader, err error) {\n\theadCommitTree, err, _ := this.headCommitTree()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tentry, err := headCommitTree.EntryByPath(path)\n\tif err != nil {\n\t\treturn\n\t}\n\tblob, err := this.repo.LookupBlob(entry.Id)\n\tif err != nil {\n\t\treturn\n\t}\n\treader = bytes.NewBuffer(blob.Contents())\n\treturn\n}\n\nfunc (this *FileStore) CreateDir(path string, commitInfo *CommitInfo) (err error) {\n\treader := strings.NewReader(\"\")\n\terr = this.WriteFile(fmt.Sprintf(\"%s\/.gitkeep\", path), reader, commitInfo)\n\treturn\n}\n\nfunc (this *FileStore) WriteFile(path string, reader io.Reader, commitInfo *CommitInfo) (err error) {\n\tblobOid, err := this.writeData(reader)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\toldTree, _, _ := this.headCommitTree()\n\tnewTreeId, err := this.updateTree(oldTree, path, blobOid)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\ttree, err := this.repo.LookupTree(newTreeId)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tsig := &git.Signature{\n\t\tName: commitInfo.AuthorName(),\n\t\tEmail: commitInfo.AuthorEmail(),\n\t\tWhen: commitInfo.Time(),\n\t}\n\n\tcommit, _, _ := this.headCommit()\n\tif commit == nil {\n\t\t_, err = this.repo.CreateCommit(\"HEAD\", sig, sig, commitInfo.Message(), tree)\n\n\t} else {\n\t\t_, err = this.repo.CreateCommit(\"HEAD\", sig, sig, commitInfo.Message(), tree, commit)\n\n\t}\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\treturn\n}\n\nfunc (this *FileStore) writeData(reader io.Reader) (blobOid *git.Oid, err error) {\n\todb, err := this.repo.Odb()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tdata, err := ioutil.ReadAll(reader)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tblobOid, err = odb.Write(data, git.ObjectBlob)\n\treturn\n}\n\nfunc (this *FileStore) updateTreeBlob(treebuilder *git.TreeBuilder, basename string, blobOid *git.Oid) (oid *git.Oid, err error) {\n\terr = treebuilder.Insert(basename, blobOid, int(git.FilemodeBlob))\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\treturn treebuilder.Write()\n}\n\nfunc (this *FileStore) updateTreeTree(treebuilder *git.TreeBuilder, basename string, childsPath string, blobOid *git.Oid) (oid *git.Oid, err error) {\n\tnewTreeOid, err := treebuilder.Write()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tnewTree, err := this.repo.LookupTree(newTreeOid)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\tvar oldChildTree *git.Tree\n\n\t\/\/ try to fetch an existing tree entry\n\t\/\/ if no tree entry is found, a new one will automatically created later\n\toldChildTreeTreeEntry := newTree.EntryByName(basename)\n\tif oldChildTreeTreeEntry != nil {\n\t\toldChildTree, err = this.repo.LookupTree(oldChildTreeTreeEntry.Id)\n\t}\n\n\tchildTreeOid, err2 := this.updateTree(oldChildTree, childsPath, blobOid)\n\tif err2 != nil {\n\t\tfmt.Println(err2)\n\t\terr = err2\n\t\treturn\n\t}\n\n\terr = treebuilder.Insert(basename, childTreeOid, int(git.FilemodeTree))\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\toid, err = treebuilder.Write()\n\treturn\n}\n\nfunc (this *FileStore) updateTree(oldParentTree *git.Tree, path string, blobOid *git.Oid) (oid *git.Oid, err error) {\n\tvar treebuilder *git.TreeBuilder\n\tif oldParentTree == nil {\n\t\ttreebuilder, err = this.repo.TreeBuilder()\n\t} else {\n\t\ttreebuilder, err = this.repo.TreeBuilderFromTree(oldParentTree)\n\t}\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tparts := strings.SplitN(path, \"\/\", 2)\n\tif len(parts) == 1 {\n\t\treturn this.updateTreeBlob(treebuilder, parts[0], blobOid)\n\t} else {\n\t\treturn this.updateTreeTree(treebuilder, parts[0], parts[1], blobOid)\n\t}\n}\n\nfunc (this *FileStore) headCommitTree() (tree *git.Tree, err error, noHead bool) {\n\tcommit, err, noHead := this.headCommit()\n\tif err != nil {\n\t\treturn\n\t}\n\ttree, err = commit.Tree()\n\treturn\n}\n\nfunc (this *FileStore) headCommit() (commit *git.Commit, err error, noHead bool) {\n\toid, err, noHead := this.headCommitId()\n\tif err != nil {\n\t\treturn\n\t}\n\tcommit, err = this.repo.LookupCommit(oid)\n\treturn\n}\n\nfunc (this *FileStore) headCommitId() (oid *git.Oid, err error, noHead bool) {\n\theadRef, err := this.repo.LookupReference(\"HEAD\")\n\tif err != nil {\n\t\treturn\n\t}\n\tref, err := headRef.Resolve()\n\tif err != nil {\n\t\tnoHead = true\n\t\treturn\n\t}\n\toid = ref.Target()\n\tif oid == nil {\n\t\terr = fmt.Errorf(\"Could not get Target for HEAD(%s)\\n\", oid.String())\n\t}\n\treturn\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"os\"\n\t\"os\/user\"\n\t\"path\/filepath\"\n\t\"runtime\"\n)\n\n\/\/ The user's home directory\nvar HomeDir = homeDir()\n\n\/\/ AppDir is the .heroku path\nfunc AppDir() string {\n\tif runtime.GOOS == \"windows\" {\n\t\tdir := os.Getenv(\"LOCALAPPDIR\")\n\t\tif dir != \"\" {\n\t\t\treturn filepath.Join(dir, \"heroku\")\n\t\t}\n\t}\n\treturn filepath.Join(HomeDir, \".heroku\")\n}\n\nfunc homeDir() string {\n\thome := os.Getenv(\"HOME\")\n\tif home != \"\" {\n\t\treturn home\n\t}\n\tuser, err := user.Current()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn user.HomeDir\n}\ncorrected windows env varpackage main\n\nimport (\n\t\"os\"\n\t\"os\/user\"\n\t\"path\/filepath\"\n\t\"runtime\"\n)\n\n\/\/ The user's home directory\nvar HomeDir = homeDir()\n\n\/\/ AppDir is the .heroku path\nfunc AppDir() string {\n\tif runtime.GOOS == \"windows\" {\n\t\tdir := os.Getenv(\"LOCALAPPDATA\")\n\t\tif dir != \"\" {\n\t\t\treturn filepath.Join(dir, \"heroku\")\n\t\t}\n\t}\n\treturn filepath.Join(HomeDir, \".heroku\")\n}\n\nfunc homeDir() string {\n\thome := os.Getenv(\"HOME\")\n\tif home != \"\" {\n\t\treturn home\n\t}\n\tuser, err := user.Current()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn user.HomeDir\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"time\"\n\n\t\"github.com\/getsentry\/sentry-go\"\n\tsentryecho \"github.com\/getsentry\/sentry-go\/echo\"\n\t\"github.com\/labstack\/echo\/v4\"\n\t\"github.com\/labstack\/echo\/v4\/middleware\"\n\t\"github.com\/labstack\/gommon\/log\"\n\t\"github.com\/pkg\/errors\"\n\n\tstrava \"github.com\/PtrTeixeira\/cookbook\/strava\/client\"\n)\n\ntype handler struct {\n\tcfg *Config\n\tclient *strava.Client\n\tlog echo.Logger\n}\n\n\/\/ RedirectParams are the parameters from the Strava oauth redirect\ntype RedirectParams struct {\n\tErr string `form:\"error\" query:\"error\"`\n\tCode string `form:\"code\" query:\"code\"`\n\tState string `form:\"email\" query:\"state\"`\n}\n\nfunc main() {\n\tconfig, err := InitConfig()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\te := echo.New()\n\te.HideBanner = true\n\te.Logger.SetLevel(log.INFO)\n\th := handler{\n\t\tcfg: config,\n\t\tclient: strava.NewClient(),\n\t\tlog: e.Logger,\n\t}\n\n\tinitializeSentry(e.Logger, config)\n\n\t\/\/ Middleware\n\te.Use(middleware.Logger())\n\te.Use(middleware.Recover())\n\te.Use(sentryecho.New(sentryecho.Options{\n\t\tRepanic: true,\n\t\tTimeout: time.Second * 3,\n\t}))\n\n\t\/\/ Routes\n\te.GET(\"\/health\", h.healthCheck)\n\te.GET(\"\/punchcard\", h.getPunchcard)\n\te.GET(\"\/strava\/login\", h.redirectToStrava)\n\te.GET(\"\/strava\/callback\", h.stravaOauthCallback)\n\n\t\/\/ Start server\n\te.Logger.Fatal(e.Start(\":8080\"))\n}\n\nfunc initializeSentry(log echo.Logger, config *Config) {\n\tsentryDsn := config.SentryDsn\n\tif sentryDsn == \"\" {\n\t\tlog.Info(\"Sentry DSN was unset, will not report to Sentry\")\n\t\treturn\n\t}\n\n\tif config.Environment == \"local\" {\n\t\tlog.Info(\"Environment is \\\"local\\\", won't report to Sentry\")\n\t\treturn\n\t}\n\n\terr := sentry.Init(sentry.ClientOptions{\n\t\tDsn: sentryDsn,\n\t})\n\n\tif err != nil {\n\t\tlog.Warnf(\"Sentry initialization failed: %v\\n\", err)\n\t}\n}\n\n\/\/ Handler\nfunc (h handler) redirectToStrava(c echo.Context) error {\n\tdest, err := url.Parse(\"https:\/\/www.strava.com\/oauth\/authorize\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tredirectURL := fmt.Sprintf(\"%s\/strava\/callback\", h.cfg.BaseURL)\n\tqueryParams := dest.Query()\n\tqueryParams.Set(\"client_id\", h.cfg.StravaClientID)\n\tqueryParams.Set(\"redirect_uri\", redirectURL)\n\tqueryParams.Set(\"response_type\", \"code\")\n\tqueryParams.Set(\"scope\", \"read,activity:read\")\n\n\tdest.RawQuery = queryParams.Encode()\n\n\treturn c.Redirect(http.StatusSeeOther, dest.String())\n}\n\nfunc (h handler) healthCheck(c echo.Context) error {\n\tif h.cfg.StravaClientID == \"\" || h.cfg.StravaClientSecret == \"\" {\n\t\treturn errors.New(\"Strava client ID or secret was blank!\")\n\t}\n\n\treturn c.NoContent(http.StatusOK)\n}\n\nfunc (h handler) getPunchcard(c echo.Context) error {\n\tauthCookie, err := c.Cookie(\"StravaAuthToken\")\n\tif err != nil {\n\t\th.log.Warn(\"Could not read access token from cookie\", err)\n\t\treturn c.NoContent(http.StatusForbidden)\n\t}\n\n\tresponse, err := h.client.GetAthleteActivities(authCookie.Value, 1, 50)\n\tif err != nil {\n\t\th.log.Error(\"Could not read data athlete data from Strava\", err)\n\t}\n\tpunchcard := GetPunchcard(response)\n\n\treturn c.JSON(http.StatusOK, punchcard)\n}\n\nfunc (h handler) stravaOauthCallback(c echo.Context) error {\n\tparams := new(RedirectParams)\n\tif err := c.Bind(params); err != nil {\n\t\th.log.Warn(\"Could not get redirect params\", err)\n\t\treturn c.NoContent(http.StatusBadRequest)\n\t}\n\n\tif params.Err == \"access_denied\" {\n\t\th.log.Warn(\"Access was denied for user, cannot proceed\")\n\t\treturn c.Redirect(http.StatusSeeOther, \"http:\/\/strava.com\")\n\t}\n\n\tclient := h.client\n\tresponse, err := client.GetToken(\"x\"+h.cfg.StravaClientID, h.cfg.StravaClientSecret, params.Code)\n\tif err != nil {\n\t\te := errors.Wrap(err, \"Could not get auth token from Strava\")\n\t\tif hub := sentryecho.GetHubFromContext(c); hub != nil {\n\t\t\th.log.Info(\"Got Hub from context; sending to sentry\")\n\t\t\thub.CaptureException(e)\n\t\t\treturn e\n\t\t}\n\t\treturn err\n\t}\n\n\tcookie := new(http.Cookie)\n\tcookie.Name = \"StravaAuthToken\"\n\tcookie.Value = response.AccessToken\n\tcookie.Expires = time.Now().Add(24 * time.Hour)\n\tcookie.Path = \"\/\"\n\tcookie.HttpOnly = true\n\tcookie.SameSite = http.SameSiteStrictMode\n\tc.SetCookie(cookie)\n\treturn c.Redirect(http.StatusSeeOther, h.cfg.DashboardURL)\n}\nRemove change for testingpackage main\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"time\"\n\n\t\"github.com\/getsentry\/sentry-go\"\n\tsentryecho \"github.com\/getsentry\/sentry-go\/echo\"\n\t\"github.com\/labstack\/echo\/v4\"\n\t\"github.com\/labstack\/echo\/v4\/middleware\"\n\t\"github.com\/labstack\/gommon\/log\"\n\t\"github.com\/pkg\/errors\"\n\n\tstrava \"github.com\/PtrTeixeira\/cookbook\/strava\/client\"\n)\n\ntype handler struct {\n\tcfg *Config\n\tclient *strava.Client\n\tlog echo.Logger\n}\n\n\/\/ RedirectParams are the parameters from the Strava oauth redirect\ntype RedirectParams struct {\n\tErr string `form:\"error\" query:\"error\"`\n\tCode string `form:\"code\" query:\"code\"`\n\tState string `form:\"email\" query:\"state\"`\n}\n\nfunc main() {\n\tconfig, err := InitConfig()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\te := echo.New()\n\te.HideBanner = true\n\te.Logger.SetLevel(log.INFO)\n\th := handler{\n\t\tcfg: config,\n\t\tclient: strava.NewClient(),\n\t\tlog: e.Logger,\n\t}\n\n\tinitializeSentry(e.Logger, config)\n\n\t\/\/ Middleware\n\te.Use(middleware.Logger())\n\te.Use(middleware.Recover())\n\te.Use(sentryecho.New(sentryecho.Options{\n\t\tRepanic: true,\n\t\tTimeout: time.Second * 3,\n\t}))\n\n\t\/\/ Routes\n\te.GET(\"\/health\", h.healthCheck)\n\te.GET(\"\/punchcard\", h.getPunchcard)\n\te.GET(\"\/strava\/login\", h.redirectToStrava)\n\te.GET(\"\/strava\/callback\", h.stravaOauthCallback)\n\n\t\/\/ Start server\n\te.Logger.Fatal(e.Start(\":8080\"))\n}\n\nfunc initializeSentry(log echo.Logger, config *Config) {\n\tsentryDsn := config.SentryDsn\n\tif sentryDsn == \"\" {\n\t\tlog.Info(\"Sentry DSN was unset, will not report to Sentry\")\n\t\treturn\n\t}\n\n\tif config.Environment == \"local\" {\n\t\tlog.Info(\"Environment is \\\"local\\\", won't report to Sentry\")\n\t\treturn\n\t}\n\n\terr := sentry.Init(sentry.ClientOptions{\n\t\tDsn: sentryDsn,\n\t})\n\n\tif err != nil {\n\t\tlog.Warnf(\"Sentry initialization failed: %v\\n\", err)\n\t}\n}\n\n\/\/ Handler\nfunc (h handler) redirectToStrava(c echo.Context) error {\n\tdest, err := url.Parse(\"https:\/\/www.strava.com\/oauth\/authorize\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tredirectURL := fmt.Sprintf(\"%s\/strava\/callback\", h.cfg.BaseURL)\n\tqueryParams := dest.Query()\n\tqueryParams.Set(\"client_id\", h.cfg.StravaClientID)\n\tqueryParams.Set(\"redirect_uri\", redirectURL)\n\tqueryParams.Set(\"response_type\", \"code\")\n\tqueryParams.Set(\"scope\", \"read,activity:read\")\n\n\tdest.RawQuery = queryParams.Encode()\n\n\treturn c.Redirect(http.StatusSeeOther, dest.String())\n}\n\nfunc (h handler) healthCheck(c echo.Context) error {\n\tif h.cfg.StravaClientID == \"\" || h.cfg.StravaClientSecret == \"\" {\n\t\treturn errors.New(\"Strava client ID or secret was blank!\")\n\t}\n\n\treturn c.NoContent(http.StatusOK)\n}\n\nfunc (h handler) getPunchcard(c echo.Context) error {\n\tauthCookie, err := c.Cookie(\"StravaAuthToken\")\n\tif err != nil {\n\t\th.log.Warn(\"Could not read access token from cookie\", err)\n\t\treturn c.NoContent(http.StatusForbidden)\n\t}\n\n\tresponse, err := h.client.GetAthleteActivities(authCookie.Value, 1, 50)\n\tif err != nil {\n\t\th.log.Error(\"Could not read data athlete data from Strava\", err)\n\t}\n\tpunchcard := GetPunchcard(response)\n\n\treturn c.JSON(http.StatusOK, punchcard)\n}\n\nfunc (h handler) stravaOauthCallback(c echo.Context) error {\n\tparams := new(RedirectParams)\n\tif err := c.Bind(params); err != nil {\n\t\th.log.Warn(\"Could not get redirect params\", err)\n\t\treturn c.NoContent(http.StatusBadRequest)\n\t}\n\n\tif params.Err == \"access_denied\" {\n\t\th.log.Warn(\"Access was denied for user, cannot proceed\")\n\t\treturn c.Redirect(http.StatusSeeOther, \"http:\/\/strava.com\")\n\t}\n\n\tclient := h.client\n\tresponse, err := client.GetToken(h.cfg.StravaClientID, h.cfg.StravaClientSecret, params.Code)\n\tif err != nil {\n\t\te := errors.Wrap(err, \"Could not get auth token from Strava\")\n\t\tif hub := sentryecho.GetHubFromContext(c); hub != nil {\n\t\t\th.log.Info(\"Got Hub from context; sending to sentry\")\n\t\t\thub.CaptureException(e)\n\t\t\treturn e\n\t\t}\n\t\treturn err\n\t}\n\n\tcookie := new(http.Cookie)\n\tcookie.Name = \"StravaAuthToken\"\n\tcookie.Value = response.AccessToken\n\tcookie.Expires = time.Now().Add(24 * time.Hour)\n\tcookie.Path = \"\/\"\n\tcookie.HttpOnly = true\n\tcookie.SameSite = http.SameSiteStrictMode\n\tc.SetCookie(cookie)\n\treturn c.Redirect(http.StatusSeeOther, h.cfg.DashboardURL)\n}\n<|endoftext|>"} {"text":"\/*\n\targs is a package used to keep all command line parsing out util so our\n\tcode can be reused\n*\/\npackage args\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n)\n\nvar (\n\t\/\/ Flag variables\n\tSearchFlag *string \/\/ SearchFlag is used to provide a string to search for types\n\tInfoFlag *string \/\/ InfoFlag is used to provide an int to display info about a type\n\tDamage *string \/\/ Damage is used to provide a TypeID to calculate damage of a weapon\n\tSDEVersion *string \/\/ Version of the SDE to force\n\tApplyModule *string\n\tVerboseInfo *bool \/\/ If our info should print as much data about a type that we can\n\tLicenseFlag *bool \/\/ Print Licensing information\n\tVersionFlag *bool \/\/ Print current version\n\tSlowFlag *bool \/\/ Don't use optimizations\n\tTimeExecution *bool \/\/ Should we time our functions?\n\tClean *bool \/\/ Cleans cache and database files\n\tDumpTypes *bool \/\/ Dumps all types to a file for use with category.go\n\tGetMarketData *bool \/\/ Flag used if getting market data with -i\n\tRunServer *bool \/\/ Runs a server for hosting the web version of SDETool\n\tDebug *bool\n\tForcePanic *bool\n\tQuiet *bool\n\tUninstall *bool\n\tNoColor *bool\n\tNoSkills *bool \/\/ Calculate stats without skill bonuses\n\tComplexModCount *int \/\/ ComplexModCount is used to calculate how many Complex mods to use\n\tEnhancedModCount *int \/\/ EnhancedModCount is used to calculate how many Enhanced mods to use\n\tBasicModCount *int \/\/ BasicModCount is used to calculate how many Basic mods to use\n\tProf *int \/\/ Prof is how many levels of proficiency used when calculating damage\n\tPort *int \/\/ What port to listen on?\n)\n\n\/\/ Init handles parsing command line flags\nfunc Init() {\n\t\/\/ Flags\n\tSearchFlag = flag.String(\"s\", \"\", \"Search for TypeIDs\")\n\tInfoFlag = flag.String(\"i\", \"\", \"Get info with a TypeID, typeName or mDisplayName\")\n\tVerboseInfo = flag.Bool(\"vi\", false, \"Prints all attributes when used with -i\")\n\tLicenseFlag = flag.Bool(\"l\", false, \"Prints license information.\")\n\tVersionFlag = flag.Bool(\"version\", false, \"Prints the SDETool version\")\n\tSlowFlag = flag.Bool(\"slow\", false, \"Forces the use of unoptimized functions\")\n\tTimeExecution = flag.Bool(\"time\", false, \"Times the execution of functions that may take a decent amount of time\")\n\tClean = flag.Bool(\"clean\", false, \"Cleans all database and cache files\")\n\tDumpTypes = flag.Bool(\"dump\", false, \"Dumps all types to a file for use with the category package\")\n\tApplyModule = flag.String(\"m\", \"\", \"Used with -i to apply a module to a dropsuit\")\n\n\tGetMarketData = flag.Bool(\"market\", false, \"Gets market data on item, used with -i. Sorry CCP if I'm pounding your APIs ;P\")\n\tDebug = flag.Bool(\"debug\", false, \"Debug? Debug!\")\n\tForcePanic = flag.Bool(\"fp\", false, \"Forces a panic, debug uses\")\n\tQuiet = flag.Bool(\"quiet\", false, \"Used with flags like uninstall where you want it to produce no output, ask for input or block in any sort of way\")\n\tUninstall = flag.Bool(\"uninstall\", false, \"Uninstalls SDETool if install via makefile or manually in your PATH variable\")\n\tNoColor = flag.Bool(\"nocolor\", false, \"Used to disable color. Usefull for >'ing and |'ing\")\n\tNoSkills = flag.Bool(\"ns\", false, \"Used to prevent SDETool from applying skill bonuses\")\n\t\/\/ Damage and mod counts\n\tDamage = flag.String(\"d\", \"\", \"Get damage calculations, takes a TypeID\")\n\tSDEVersion = flag.String(\"sv\", \"1.8\", \"Version of the SDE to use, in the form of '1.7' or '1.8'\")\n\tComplexModCount = flag.Int(\"c\", 0, \"Amount of complex damage mods, used with -d\")\n\tEnhancedModCount = flag.Int(\"e\", 0, \"Amount of enhanced damage mods, used with -d\")\n\tBasicModCount = flag.Int(\"b\", 0, \"Amount of enhanced damage mods, used with -d\")\n\tProf = flag.Int(\"p\", 0, \"Prof level, used with -d\")\n\n\t\/\/ Server related\n\tRunServer = flag.Bool(\"server\", false, \"Runs a server for hosting the web version of SDETool\")\n\tPort = flag.Int(\"port\", 80, \"Port used for -server\")\n\tflag.Parse()\n}\n\n\/\/ I don't quite like how flag.PrintDefaults() prints out the flags so I\n\/\/ decided to make this\nfunc PrintHelp() {\n\thelp := `\n\tSearch: -s\n\t Supply with the name of the item to search for. Returns the typeID and\n\t full name of each\n\tInfo: -i\n\t Supply with either a typeID, typeName or displayName of the type you want\n\t to print info for.\n\t Sub Flags:\n\t Market: -m\n\t Prints basic market data for the type you're searching (Currently \n\t broken)\n\t Damage: -d\n\t By itself it will print a damage chart, you can supply the\n\t (-c)omplex, (-e)nhanced, (-b)asic damage mod count and the\n\t (-p)roficiency level.\n\tDebug: -d\n\t Prints debug information, very helpful for bug reporting\n\tTime execution: -time\n\t Prints execution time of critical functions, helpful for optimizing\n\tVersion: -v\n\t`\n\tfmt.Println(help)\n}\nFix help\/*\n\targs is a package used to keep all command line parsing out util so our\n\tcode can be reused\n*\/\npackage args\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n)\n\nvar (\n\t\/\/ Flag variables\n\tSearchFlag *string \/\/ SearchFlag is used to provide a string to search for types\n\tInfoFlag *string \/\/ InfoFlag is used to provide an int to display info about a type\n\tDamage *string \/\/ Damage is used to provide a TypeID to calculate damage of a weapon\n\tSDEVersion *string \/\/ Version of the SDE to force\n\tApplyModule *string\n\tVerboseInfo *bool \/\/ If our info should print as much data about a type that we can\n\tLicenseFlag *bool \/\/ Print Licensing information\n\tVersionFlag *bool \/\/ Print current version\n\tSlowFlag *bool \/\/ Don't use optimizations\n\tTimeExecution *bool \/\/ Should we time our functions?\n\tClean *bool \/\/ Cleans cache and database files\n\tDumpTypes *bool \/\/ Dumps all types to a file for use with category.go\n\tGetMarketData *bool \/\/ Flag used if getting market data with -i\n\tRunServer *bool \/\/ Runs a server for hosting the web version of SDETool\n\tDebug *bool\n\tForcePanic *bool\n\tQuiet *bool\n\tUninstall *bool\n\tNoColor *bool\n\tNoSkills *bool \/\/ Calculate stats without skill bonuses\n\tComplexModCount *int \/\/ ComplexModCount is used to calculate how many Complex mods to use\n\tEnhancedModCount *int \/\/ EnhancedModCount is used to calculate how many Enhanced mods to use\n\tBasicModCount *int \/\/ BasicModCount is used to calculate how many Basic mods to use\n\tProf *int \/\/ Prof is how many levels of proficiency used when calculating damage\n\tPort *int \/\/ What port to listen on?\n)\n\n\/\/ Init handles parsing command line flags\nfunc Init() {\n\t\/\/ Flags\n\tSearchFlag = flag.String(\"s\", \"\", \"Search for TypeIDs\")\n\tInfoFlag = flag.String(\"i\", \"\", \"Get info with a TypeID, typeName or mDisplayName\")\n\tVerboseInfo = flag.Bool(\"vi\", false, \"Prints all attributes when used with -i\")\n\tLicenseFlag = flag.Bool(\"l\", false, \"Prints license information.\")\n\tVersionFlag = flag.Bool(\"version\", false, \"Prints the SDETool version\")\n\tSlowFlag = flag.Bool(\"slow\", false, \"Forces the use of unoptimized functions\")\n\tTimeExecution = flag.Bool(\"time\", false, \"Times the execution of functions that may take a decent amount of time\")\n\tClean = flag.Bool(\"clean\", false, \"Cleans all database and cache files\")\n\tDumpTypes = flag.Bool(\"dump\", false, \"Dumps all types to a file for use with the category package\")\n\tApplyModule = flag.String(\"m\", \"\", \"Used with -i to apply a module to a dropsuit\")\n\n\tGetMarketData = flag.Bool(\"market\", false, \"Gets market data on item, used with -i. Sorry CCP if I'm pounding your APIs ;P\")\n\tDebug = flag.Bool(\"debug\", false, \"Debug? Debug!\")\n\tForcePanic = flag.Bool(\"fp\", false, \"Forces a panic, debug uses\")\n\tQuiet = flag.Bool(\"quiet\", false, \"Used with flags like uninstall where you want it to produce no output, ask for input or block in any sort of way\")\n\tUninstall = flag.Bool(\"uninstall\", false, \"Uninstalls SDETool if install via makefile or manually in your PATH variable\")\n\tNoColor = flag.Bool(\"nocolor\", false, \"Used to disable color. Usefull for >'ing and |'ing\")\n\tNoSkills = flag.Bool(\"ns\", false, \"Used to prevent SDETool from applying skill bonuses\")\n\t\/\/ Damage and mod counts\n\tDamage = flag.String(\"d\", \"\", \"Get damage calculations, takes a TypeID\")\n\tSDEVersion = flag.String(\"sv\", \"1.8\", \"Version of the SDE to use, in the form of '1.7' or '1.8'\")\n\tComplexModCount = flag.Int(\"c\", 0, \"Amount of complex damage mods, used with -d\")\n\tEnhancedModCount = flag.Int(\"e\", 0, \"Amount of enhanced damage mods, used with -d\")\n\tBasicModCount = flag.Int(\"b\", 0, \"Amount of enhanced damage mods, used with -d\")\n\tProf = flag.Int(\"p\", 0, \"Prof level, used with -d\")\n\n\t\/\/ Server related\n\tRunServer = flag.Bool(\"server\", false, \"Runs a server for hosting the web version of SDETool\")\n\tPort = flag.Int(\"port\", 80, \"Port used for -server\")\n\tflag.Parse()\n}\n\n\/\/ I don't quite like how flag.PrintDefaults() prints out the flags so I\n\/\/ decided to make this\nfunc PrintHelp() {\n\thelp := `\nSearch: -s\n Supply with the name of the item to search for. Returns the typeID and\n full name of each\nInfo: -i\n Supply with either a typeID, typeName or displayName of the type you want\n to print info for.\n Sub Flags:\n Market: -m\n Prints basic market data for the type you're searching (Currently \n broken)\n Damage: -d\n By itself it will print a damage chart, you can supply the\n (-c)omplex, (-e)nhanced, (-b)asic damage mod count and the\n (-p)roficiency level.\nDebug: -d\n Prints debug information, very helpful for bug reporting\nTime execution: -time\n Prints execution time of critical functions, helpful for optimizing\nVersion: -v\n\t`\n\tfmt.Println(help)\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\n\t\"code.google.com\/p\/gopacket\"\n\t\"code.google.com\/p\/gopacket\/layers\"\n\t\"code.google.com\/p\/gopacket\/pcap\"\n\t\"github.com\/Sirupsen\/logrus\"\n)\n\nvar (\n\trequestARPStore *ARPStore = NewARPStore()\n\treplyARPStore *ARPStore = NewARPStore()\n)\n\nfunc watch(iface *net.Interface) error {\n\taddr, err := getInterfaceIPAddress(iface)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif addr.IP.String() == \"127.0.0.1\" {\n\t\treturn fmt.Errorf(\"Skipping %s (%s).\", addr.String(), addr.IP)\n\t}\n\n\tLog.WithFields(logrus.Fields{\n\t\t\"interface\": iface.Name,\n\t\t\"address\": addr.String(),\n\t}).Infof(\"Watching interface.\")\n\n\thandle, err := pcap.OpenLive(iface.Name, 65536, true, pcap.BlockForever)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ This is a blocking call.\n\tprocess(handle, iface)\n\n\tLog.WithFields(logrus.Fields{\n\t\t\"interface\": iface.Name,\n\t\t\"address\": addr.String(),\n\t}).Infof(\"Stopped watching interface.\")\n\n\treturn nil\n}\n\nfunc process(handle *pcap.Handle, iface *net.Interface) {\n\tsrc := gopacket.NewPacketSource(handle, layers.LayerTypeEthernet)\n\tfor {\n\t\tvar packet gopacket.Packet\n\t\tselect {\n\t\tcase <-stop:\n\t\t\treturn\n\t\tcase packet = <-src.Packets():\n\t\t\tarpLayer := packet.Layer(layers.LayerTypeARP)\n\t\t\tif arpLayer == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\thandleARP(arpLayer.(*layers.ARP))\n\n\t\t}\n\t}\n}\n\nfunc handleARP(arp *layers.ARP) {\n\tarpData := &ARPData{\n\t\tOperation: arp.Operation,\n\t\tSenderMACAddress: net.HardwareAddr(arp.SourceHwAddress).String(),\n\t\tSenderIPAddress: net.IP(arp.SourceProtAddress).String(),\n\t\tTargetMACAddress: net.HardwareAddr(arp.DstHwAddress).String(),\n\t\tTargetIPAddress: net.IP(arp.DstProtAddress).String(),\n\t}\n\n\tswitch arpData.Operation {\n\tcase 1: \/\/ This operation value defines an arp request.\n\t\t\/\/ For a standard ARP request:\n\t\t\/\/ - SourceHwAddress: This is the MAC address of the requestor.\n\t\t\/\/ - SourceProtAddress: This is the IP address of the requestor.\n\t\t\/\/ - DstHwAddress: This field is ignored. Basically, this is what an ARP request is actually requesting.\n\t\t\/\/ - DstProtAddress: This is the IP address for which the requestor would like the MAC address for (i.e. a reply).\n\t\tLog.WithFields(logrus.Fields{\n\t\t\t\"Requestor MAC Address\": arpData.SenderMACAddress,\n\t\t\t\"Requestor IP Address\": arpData.SenderIPAddress,\n\t\t\t\"Ignored MAC Address\": arpData.TargetMACAddress,\n\t\t\t\"Destination IP Address\": arpData.TargetIPAddress,\n\t\t}).Infof(\"Recieved ARP request.\")\n\n\t\tif existingData, existed := requestARPStore.PutARPData(arpData); existed {\n\t\t\tLog.Infof(\"Replacing existing request: %#v\", *existingData)\n\t\t}\n\tcase 2: \/\/ This operation value defines an arp reply.\n\t\t\/\/ For an ARP reply:\n\t\t\/\/ - SourceHwAddress: This is the MAC address of the replier.\n\t\t\/\/ - SourceProtAddress: This is the IP address of the replier.\n\t\t\/\/ - DstHwAddress: This field indicates the address of the requesting host.\n\t\t\/\/ - DstProtAddress: This is the IP address of the requesting host.\n\t\tLog.WithFields(logrus.Fields{\n\t\t\t\"Replier MAC Address\": arpData.SenderMACAddress,\n\t\t\t\"Replier IP Address\": arpData.SenderIPAddress,\n\t\t\t\"Requestor MAC Address\": arpData.TargetMACAddress,\n\t\t\t\"Requestor IP Address\": arpData.TargetIPAddress,\n\t\t}).Infof(\"Recieved ARP reply.\")\n\n\t\tif existingData, existed := replyARPStore.PutARPData(arpData); existed {\n\t\t\tLog.Infof(\"Replacing existing reply: %#v\", *existingData)\n\t\t}\n\tdefault:\n\t\tLog.Warnf(\"Unknown sender operation for ARP packet: %#v\", *arp)\n\t}\n}\nAdded detection and a store for gratuitous ARP requests.package main\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\n\t\"code.google.com\/p\/gopacket\"\n\t\"code.google.com\/p\/gopacket\/layers\"\n\t\"code.google.com\/p\/gopacket\/pcap\"\n\t\"github.com\/Sirupsen\/logrus\"\n)\n\nvar (\n\trequestARPStore *ARPStore = NewARPStore()\n\treplyARPStore *ARPStore = NewARPStore()\n\tgratuitousARPStore *ARPStore = NewARPStore()\n)\n\nconst (\n\tGratuitousTargetMAC = \"ff:ff:ff:ff:ff:ff\"\n)\n\nfunc watch(iface *net.Interface) error {\n\taddr, err := getInterfaceIPAddress(iface)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif addr.IP.String() == \"127.0.0.1\" {\n\t\treturn fmt.Errorf(\"Skipping %s (%s).\", addr.String(), addr.IP)\n\t}\n\n\tLog.WithFields(logrus.Fields{\n\t\t\"interface\": iface.Name,\n\t\t\"address\": addr.String(),\n\t}).Infof(\"Watching interface.\")\n\n\thandle, err := pcap.OpenLive(iface.Name, 65536, true, pcap.BlockForever)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ This is a blocking call.\n\tprocess(handle, iface)\n\n\tLog.WithFields(logrus.Fields{\n\t\t\"interface\": iface.Name,\n\t\t\"address\": addr.String(),\n\t}).Infof(\"Stopped watching interface.\")\n\n\treturn nil\n}\n\nfunc process(handle *pcap.Handle, iface *net.Interface) {\n\tsrc := gopacket.NewPacketSource(handle, layers.LayerTypeEthernet)\n\tfor {\n\t\tvar packet gopacket.Packet\n\t\tselect {\n\t\tcase <-stop:\n\t\t\treturn\n\t\tcase packet = <-src.Packets():\n\t\t\tarpLayer := packet.Layer(layers.LayerTypeARP)\n\t\t\tif arpLayer == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\thandleARP(arpLayer.(*layers.ARP))\n\n\t\t}\n\t}\n}\n\nfunc handleARP(arp *layers.ARP) {\n\tarpData := &ARPData{\n\t\tOperation: arp.Operation,\n\t\tSenderMACAddress: net.HardwareAddr(arp.SourceHwAddress).String(),\n\t\tSenderIPAddress: net.IP(arp.SourceProtAddress).String(),\n\t\tTargetMACAddress: net.HardwareAddr(arp.DstHwAddress).String(),\n\t\tTargetIPAddress: net.IP(arp.DstProtAddress).String(),\n\t}\n\n\tswitch arpData.Operation {\n\tcase 1: \/\/ This operation value defines an arp request.\n\t\t\/\/ For a standard ARP request:\n\t\t\/\/ - SourceHwAddress: This is the MAC address of the requestor.\n\t\t\/\/ - SourceProtAddress: This is the IP address of the requestor.\n\t\t\/\/ - DstHwAddress: This field is ignored. Basically, this is what an ARP request is actually requesting.\n\t\t\/\/ - DstProtAddress: This is the IP address for which the requestor would like the MAC address for (i.e. a reply).\n\n\t\tif arpData.TargetMACAddress == GratuitousTargetMAC {\n\t\t\tLog.WithFields(logrus.Fields{\n\t\t\t\t\"Requestor MAC Address\": arpData.SenderMACAddress,\n\t\t\t\t\"Requestor IP Address\": arpData.SenderIPAddress,\n\t\t\t\t\"Broadcast MAC Address\": arpData.TargetMACAddress,\n\t\t\t\t\"Destination IP Address\": arpData.TargetIPAddress,\n\t\t\t}).Infof(\"Recieved gratuitous ARP request.\")\n\n\t\t\tif existingData, existed := gratuitousARPStore.PutARPData(arpData); existed {\n\t\t\t\tLog.Infof(\"Replacing existing gratuitous request: %#v\", *existingData)\n\t\t\t}\n\n\t\t\treturn\n\t\t}\n\n\t\tLog.WithFields(logrus.Fields{\n\t\t\t\"Requestor MAC Address\": arpData.SenderMACAddress,\n\t\t\t\"Requestor IP Address\": arpData.SenderIPAddress,\n\t\t\t\"Ignored MAC Address\": arpData.TargetMACAddress,\n\t\t\t\"Destination IP Address\": arpData.TargetIPAddress,\n\t\t}).Infof(\"Recieved ARP request.\")\n\n\t\tif existingData, existed := requestARPStore.PutARPData(arpData); existed {\n\t\t\tLog.Infof(\"Replacing existing request: %#v\", *existingData)\n\t\t}\n\tcase 2: \/\/ This operation value defines an arp reply.\n\t\t\/\/ For an ARP reply:\n\t\t\/\/ - SourceHwAddress: This is the MAC address of the replier.\n\t\t\/\/ - SourceProtAddress: This is the IP address of the replier.\n\t\t\/\/ - DstHwAddress: This field indicates the address of the requesting host.\n\t\t\/\/ - DstProtAddress: This is the IP address of the requesting host.\n\t\tLog.WithFields(logrus.Fields{\n\t\t\t\"Replier MAC Address\": arpData.SenderMACAddress,\n\t\t\t\"Replier IP Address\": arpData.SenderIPAddress,\n\t\t\t\"Requestor MAC Address\": arpData.TargetMACAddress,\n\t\t\t\"Requestor IP Address\": arpData.TargetIPAddress,\n\t\t}).Infof(\"Recieved ARP reply.\")\n\n\t\tif existingData, existed := replyARPStore.PutARPData(arpData); existed {\n\t\t\tLog.Infof(\"Replacing existing reply: %#v\", *existingData)\n\t\t}\n\tdefault:\n\t\tLog.Warnf(\"Unknown sender operation for ARP packet: %#v\", *arp)\n\t}\n}\n<|endoftext|>"} {"text":"package frequency\n\nimport (\n\t\"encoding\/gob\"\n\t\"math\"\n\t\"os\"\n\t\"sync\"\n)\n\nvar EnglishAnalyzer = Analyzer{\n\t\/\/ Generated from the combined texts of Moby Dick, Jane Eare, and other Project Gutenberg titles\n\tfrequency: [256]int64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 132230, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1118323, 4805, 16267, 10, 17, 11, 30, 13831, 1299, 1299, 352, 0, 97346, 24497, 47923, 198, 1133, 1409, 659, 517, 471, 490, 349, 350, 504, 301, 6172, 16468, 3, 2, 3, 4411, 20, 12139, 5370, 5999, 3507, 5993, 4066, 3747, 7966, 26560, 1878, 695, 3840, 6518, 4805, 5236, 4835, 460, 3992, 8246, 16050, 1289, 960, 6071, 298, 2106, 221, 407, 0, 407, 0, 963, 0, 425022, 80895, 140227, 226517, 688599, 127083, 105382, 321942, 349210, 4730, 35065, 221740, 128556, 373375, 395487, 90412, 5787, 325314, 341986, 476299, 150327, 53345, 109065, 8599, 95926, 4605, 14, 0, 14, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},\n\tsize: 6921848,\n}\n\ntype Analyzer struct {\n\tmu sync.RWMutex\n\tfrequency [256]int64\n\tsize int64\n}\n\nfunc NewAnalyzer() *Analyzer {\n\treturn &Analyzer{}\n}\n\n\/\/ Feed - Feed an analyzer with contents, updating the frequency table.\n\/\/ The analyzer state is updated - not replaced, so multiple Feed calls are OK.\nfunc (a *Analyzer) Feed(contents []byte) {\n\ta.mu.Lock()\n\tdefer a.mu.Unlock()\n\n\t\/\/ Update the character count in analyzer\n\tfor _, character := range contents {\n\t\ta.frequency[character] += 1\n\t\ta.size += 1\n\t}\n\n\treturn\n}\n\n\/\/ Score - Score contents according to the analyzer frequency tables. Return a value in the range of 0 - 1.\nfunc (a *Analyzer) Score(contents []byte) float64 {\n\tother := NewAnalyzer()\n\tother.Feed(contents)\n\n\ta.mu.RLock()\n\tdefer a.mu.RUnlock()\n\n\treturn scoreFrequencies(a, other)\n}\n\n\/\/ ScoreString - Score string. Return a value in the range 0 - 1.\nfunc (a *Analyzer) ScoreString(text string) float64 {\n\treturn a.Score([]byte(text))\n}\n\n\/\/ Save - save the analyzer state to a file at path.\nfunc (a *Analyzer) Save(path string) error {\n\tfile, err := os.Create(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\ta.mu.RLock()\n\tdefer a.mu.RUnlock()\n\tencoder := gob.NewEncoder(file)\n\tif err := encoder.Encode(a.frequency); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ Restore - restore the state previously saved at path, overwriting current analyzer state\nfunc (a *Analyzer) Restore(path string) error {\n\tfile, err := os.Open(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\ta.mu.Lock()\n\tdefer a.mu.Unlock()\n\n\tdecoder := gob.NewDecoder(file)\n\tif err := decoder.Decode(&a.frequency); err != nil {\n\t\treturn err\n\t}\n\n\tfor _, v := range a.frequency {\n\t\ta.size += v\n\t}\n\n\treturn nil\n}\n\n\/\/ relativeDifference - the relative difference between two numbers, a and b, as a value in the range 0 -1.\nfunc relativeDifference(a, b float64) float64 {\n\tif a == 0 && b == 0 {\n\t\treturn 0\n\t}\n\treturn math.Abs(a-b) \/ max(a, b)\n}\n\nfunc scoreFrequencies(ref, target *Analyzer) (score float64) {\n\tvar r float64 = 0\n\tvar t float64 = 0\n\n\tfor i := 0; i < 256; i++ {\n\t\tr = float64(ref.frequency[i]) \/ float64(ref.size)\n\t\tt = float64(target.frequency[i]) \/ float64(target.size)\n\t\tscore += (r * (1 - relativeDifference(r, t)))\n\t}\n\n\treturn score\n}\n\nfunc max(a, b float64) float64 {\n\tif a > b {\n\t\treturn a\n\t} else {\n\t\treturn b\n\t}\n}\nFix incorrect type of EnglishAnalyzerpackage frequency\n\nimport (\n\t\"encoding\/gob\"\n\t\"math\"\n\t\"os\"\n\t\"sync\"\n)\n\nvar EnglishAnalyzer = &Analyzer{\n\t\/\/ Generated from the combined texts of Moby Dick, Jane Eare, and other Project Gutenberg titles\n\tfrequency: [256]int64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 132230, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1118323, 4805, 16267, 10, 17, 11, 30, 13831, 1299, 1299, 352, 0, 97346, 24497, 47923, 198, 1133, 1409, 659, 517, 471, 490, 349, 350, 504, 301, 6172, 16468, 3, 2, 3, 4411, 20, 12139, 5370, 5999, 3507, 5993, 4066, 3747, 7966, 26560, 1878, 695, 3840, 6518, 4805, 5236, 4835, 460, 3992, 8246, 16050, 1289, 960, 6071, 298, 2106, 221, 407, 0, 407, 0, 963, 0, 425022, 80895, 140227, 226517, 688599, 127083, 105382, 321942, 349210, 4730, 35065, 221740, 128556, 373375, 395487, 90412, 5787, 325314, 341986, 476299, 150327, 53345, 109065, 8599, 95926, 4605, 14, 0, 14, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},\n\tsize: 6921848,\n}\n\ntype Analyzer struct {\n\tmu sync.RWMutex\n\tfrequency [256]int64\n\tsize int64\n}\n\nfunc NewAnalyzer() *Analyzer {\n\treturn &Analyzer{}\n}\n\n\/\/ Feed - Feed an analyzer with contents, updating the frequency table.\n\/\/ The analyzer state is updated - not replaced, so multiple Feed calls are OK.\nfunc (a *Analyzer) Feed(contents []byte) {\n\ta.mu.Lock()\n\tdefer a.mu.Unlock()\n\n\t\/\/ Update the character count in analyzer\n\tfor _, character := range contents {\n\t\ta.frequency[character] += 1\n\t\ta.size += 1\n\t}\n\n\treturn\n}\n\n\/\/ Score - Score contents according to the analyzer frequency tables. Return a value in the range of 0 - 1.\nfunc (a *Analyzer) Score(contents []byte) float64 {\n\tother := NewAnalyzer()\n\tother.Feed(contents)\n\n\ta.mu.RLock()\n\tdefer a.mu.RUnlock()\n\n\treturn scoreFrequencies(a, other)\n}\n\n\/\/ ScoreString - Score string. Return a value in the range 0 - 1.\nfunc (a *Analyzer) ScoreString(text string) float64 {\n\treturn a.Score([]byte(text))\n}\n\n\/\/ Save - save the analyzer state to a file at path.\nfunc (a *Analyzer) Save(path string) error {\n\tfile, err := os.Create(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\ta.mu.RLock()\n\tdefer a.mu.RUnlock()\n\tencoder := gob.NewEncoder(file)\n\tif err := encoder.Encode(a.frequency); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ Restore - restore the state previously saved at path, overwriting current analyzer state\nfunc (a *Analyzer) Restore(path string) error {\n\tfile, err := os.Open(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\ta.mu.Lock()\n\tdefer a.mu.Unlock()\n\n\tdecoder := gob.NewDecoder(file)\n\tif err := decoder.Decode(&a.frequency); err != nil {\n\t\treturn err\n\t}\n\n\tfor _, v := range a.frequency {\n\t\ta.size += v\n\t}\n\n\treturn nil\n}\n\n\/\/ relativeDifference - the relative difference between two numbers, a and b, as a value in the range 0 -1.\nfunc relativeDifference(a, b float64) float64 {\n\tif a == 0 && b == 0 {\n\t\treturn 0\n\t}\n\treturn math.Abs(a-b) \/ max(a, b)\n}\n\nfunc scoreFrequencies(ref, target *Analyzer) (score float64) {\n\tvar r float64 = 0\n\tvar t float64 = 0\n\n\tfor i := 0; i < 256; i++ {\n\t\tr = float64(ref.frequency[i]) \/ float64(ref.size)\n\t\tt = float64(target.frequency[i]) \/ float64(target.size)\n\t\tscore += (r * (1 - relativeDifference(r, t)))\n\t}\n\n\treturn score\n}\n\nfunc max(a, b float64) float64 {\n\tif a > b {\n\t\treturn a\n\t} else {\n\t\treturn b\n\t}\n}\n<|endoftext|>"} {"text":"package asmd\n\nimport (\n\t\"errors\"\n\t\"os\"\n\t\"strconv\"\n\t\"time\"\n)\n\nfunc (v Variable) ToStdLogic(name string) string {\n\tstr := name + \" : std_logic\"\n\n\tif v.BitWidth > 1 {\n\t\tstr += \"_vector (\" + strconv.FormatUint(v.BitWidth-1, 10) + \" downto 0)\"\n\t}\n\n\treturn str\n}\n\nfunc (v Variable) ToStdLogicSignal(name string) string {\n\tstr := \"signal \" + v.ToStdLogic(name)\n\tif v.DefaultValue != \"\" {\n\t\tstr += \" := \" + v.DefaultValue\n\t}\n\tstr += \";\"\n\treturn str\n}\n\n\/\/func (v Variable) ToGeneric(name string) string {}\n\nfunc (m *StateMachine) VHDL(filename string) (err error) {\n\tfile, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\t\/\/ Comments\n\twrite(file, \"\\n\")\n\twrite(file, \"--------------------------------------------------------------------------------\\n\")\n\twrite(file, \"-- Module Name: \", m.Options.ModuleName, \"\\n\")\n\twrite(file, \"-- Author: \", m.Options.Author, \"\\n\")\n\twrite(file, \"-- Date: \", time.Now().Format(\"2 Jan 2006\"), \"\\n\")\n\twrite(file, \"--\\n\")\n\twrite(file, \"--------------------------------------------------------------------------------\\n\")\n\twrite(file, \"\\n\")\n\twrite(file, \"\\n\")\n\n\t\/\/ library and use statements\n\t\/\/ TODO infer the minimal set using given types\n\twrite(file, \"library IEEE;\\n\")\n\twrite(file, \"use IEEE.STD_LOGIC_1164.ALL;\\n\")\n\twrite(file, \"use IEEE.NUMERIC_STD.ALL;\\n\")\n\twrite(file, \"\\n\")\n\n\t\/\/ entity start\n\twrite(file, \"entity \", m.Options.trimmedModuleName, \" is\\n\")\n\n\t\/\/ Entity - Generics\n\tif len(m.Parameters) > 0 {\n\t\twrite(file, m.indent(1), \"generic (\\n\")\n\t\tisFirst := true\n\t\tfor name, properties := range m.Parameters {\n\t\t\twrite(file, m.indent(2))\n\t\t\tif isFirst {\n\t\t\t\twrite(file, \" \")\n\t\t\t\tisFirst = false\n\t\t\t} else {\n\t\t\t\twrite(file, \"; \")\n\t\t\t}\n\t\t\twrite(file, name, \": \", properties.Type, \" := \", properties.DefaultValue)\n\t\t\twrite(file, \"\\n\")\n\t\t}\n\t\twrite(file, m.indent(1), \");\\n\")\n\t}\n\n\tif len(m.Inputs) > 0 || len(m.Outputs) > 0 {\n\t\twrite(file, m.indent(1), \"port (\\n\")\n\t\tvar isFirst bool\n\n\t\t\/\/ Entity - Inputs\n\t\tisFirst = true\n\t\tfor name, properties := range m.Inputs {\n\t\t\twrite(file, m.indent(2))\n\t\t\tif isFirst {\n\t\t\t\twrite(file, \" \")\n\t\t\t\tisFirst = false\n\t\t\t} else {\n\t\t\t\twrite(file, \"; \")\n\t\t\t}\n\t\t\twrite(file, properties.ToStdLogic(name))\n\t\t\twrite(file, \"\\n\")\n\t\t}\n\n\t\t\/\/ Entity - Outputs\n\t\t\/\/ We're merely continuing the same list so don't reset isFirst.\n\t\t\/\/ TODO make this DRY with Inputs section\n\t\tfor name, properties := range m.Outputs {\n\t\t\twrite(file, m.indent(2))\n\t\t\tif isFirst {\n\t\t\t\twrite(file, \" \")\n\t\t\t\tisFirst = false\n\t\t\t} else {\n\t\t\t\twrite(file, \"; \")\n\t\t\t}\n\t\t\twrite(file, properties.ToStdLogic(name))\n\t\t\twrite(file, \"\\n\")\n\t\t}\n\n\t\twrite(file, m.indent(1), \");\\n\")\n\t}\n\n\t\/\/ Entity end\n\twrite(file, \"end \", m.Options.trimmedModuleName, \";\\n\")\n\twrite(file, \"\\n\")\n\n\t\/\/ architecture start\n\twrite(file, \"architecture Behavioral of \", m.Options.trimmedModuleName, \" is\\n\")\n\n\t\/\/ Constants (?)\n\t\/\/ Internal Signals\n\twrite(file, m.indent(1), \"-- Register signals\\n\")\n\tfor sigName, signal := range m.Registers {\n\t\twrite(file, m.indent(1), signal.ToStdLogicSignal(sigName+\"_reg, \"+sigName+\"_next\"), \"\\n\")\n\t}\n\twrite(file, \"\\n\")\n\n\t\/\/ Internal signals for functional units\n\tfor unitName, unit := range m.FunctionalUnits {\n\t\twrite(file, m.indent(1), \"-- \", unitName, \" connections\\n\")\n\t\tfor sigName, signal := range unit.Inputs {\n\t\t\twrite(file, m.indent(1), signal.ToStdLogicSignal(sigName), \"\\n\")\n\t\t}\n\t\tfor sigName, signal := range unit.Outputs {\n\t\t\twrite(file, m.indent(1), signal.ToStdLogicSignal(sigName), \"\\n\")\n\t\t}\n\t\tfor sigName, signal := range unit.Registers {\n\t\t\twrite(file, m.indent(1), signal.ToStdLogicSignal(sigName+\"_reg\"), \"\\n\")\n\t\t\twrite(file, m.indent(1), signal.ToStdLogicSignal(sigName+\"_reg, \"+sigName+\"_next\"), \"\\n\")\n\t\t}\n\t}\n\tif len(m.FunctionalUnits) > 0 {\n\t\twrite(file, \"\\n\")\n\t}\n\n\twrite(file, m.indent(1), \"-- FSM declarations\\n\")\n\t\/\/ State machine states\n\twrite(file, m.indent(1), \"type state is (\")\n\tisFirst := true\n\tfor stateName, _ := range m.States {\n\t\tif isFirst {\n\t\t\tisFirst = false\n\t\t} else {\n\t\t\twrite(file, \", \")\n\t\t}\n\t\twrite(file, stateName+\"_s\")\n\t}\n\twrite(file, \"\\n\")\n\t\/\/ State machine signals\n\twrite(file, m.indent(1), \"signal state_reg, state_next : state := \", m.Options.FirstState, \";\\n\")\n\n\t\/\/ architecture \"begin\"\n\twrite(file, \"begin\\n\")\n\n\t\/\/ Register process\n\twrite(file, m.indent(1), \"-- FSM state register\\n\")\n\twrite(file, m.indent(1), \"process(clk, rst)\\n\")\n\twrite(file, m.indent(1), \"begin\\n\")\n\twrite(file, m.indent(2), \"if (rst='1') then\\n\")\n\twrite(file, m.indent(3), \"state_reg <= \", m.Options.FirstState, \";\\n\")\n\tif m.Options.ClockType == \"posedge\" {\n\t\twrite(file, m.indent(2), \"elsif (clk'event and clk='1') then\\n\")\n\t} else if m.Options.ClockType == \"negedge\" {\n\t\twrite(file, m.indent(2), \"elsif (clk'event and clk='0') then\\n\")\n\t} else {\n\t\treturn errors.New(\"Unrecognized clock type: \" + m.Options.ClockType)\n\t}\n\twrite(file, m.indent(3), \"state_reg <= state_next;\\n\")\n\twrite(file, m.indent(2), \"end if;\\n\")\n\twrite(file, m.indent(1), \"end process;\\n\")\n\t\/\/ Next State process\n\t\/\/ Mealy(?) Output process\n\t\/\/ architecture end\n\twrite(file, \"end Behavioral;\\n\")\n\twrite(file, \"\\n\")\n\n\treturn nil\n}\nState traversal and write-out is done. Still need VHDL value literals, transition subnet cycle detection, and corrected state_reg printouts (sensitivity list, port).package asmd\n\nimport (\n\t\"errors\"\n\t\"os\"\n\t\"strconv\"\n\t\"time\"\n)\n\nfunc (v Variable) ToStdLogic(name string) string {\n\tstr := name + \" : std_logic\"\n\n\tif v.BitWidth > 1 {\n\t\tstr += \"_vector (\" + strconv.FormatUint(v.BitWidth-1, 10) + \" downto 0)\"\n\t}\n\n\treturn str\n}\n\nfunc (v Variable) ToStdLogicSignal(name string) string {\n\tstr := \"signal \" + v.ToStdLogic(name)\n\tif v.DefaultValue != \"\" {\n\t\tstr += \" := \" + v.DefaultValue\n\t}\n\tstr += \";\"\n\treturn str\n}\n\n\/\/func (v Variable) ToGeneric(name string) string {}\n\nfunc (m *StateMachine) VHDL(filename string) (err error) {\n\tfile, err := os.Create(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\t\/\/ Comments\n\twrite(file, \"\\n\")\n\twrite(file, \"--------------------------------------------------------------------------------\\n\")\n\twrite(file, \"-- Module Name: \", m.Options.ModuleName, \"\\n\")\n\twrite(file, \"-- Author: \", m.Options.Author, \"\\n\")\n\twrite(file, \"-- Date: \", time.Now().Format(\"2 Jan 2006\"), \"\\n\")\n\twrite(file, \"--\\n\")\n\twrite(file, \"--------------------------------------------------------------------------------\\n\")\n\twrite(file, \"\\n\")\n\twrite(file, \"\\n\")\n\n\t\/\/ library and use statements\n\t\/\/ TODO infer the minimal set using given types\n\twrite(file, \"library IEEE;\\n\")\n\twrite(file, \"use IEEE.STD_LOGIC_1164.ALL;\\n\")\n\twrite(file, \"use IEEE.NUMERIC_STD.ALL;\\n\")\n\twrite(file, \"\\n\")\n\n\t\/\/ entity start\n\twrite(file, \"entity \", m.Options.trimmedModuleName, \" is\\n\")\n\n\t\/\/ Entity - Generics\n\tif len(m.Parameters) > 0 {\n\t\twrite(file, m.indent(1), \"generic (\\n\")\n\t\tisFirst := true\n\t\tfor name, properties := range m.Parameters {\n\t\t\twrite(file, m.indent(2))\n\t\t\tif isFirst {\n\t\t\t\twrite(file, \" \")\n\t\t\t\tisFirst = false\n\t\t\t} else {\n\t\t\t\twrite(file, \"; \")\n\t\t\t}\n\t\t\twrite(file, name, \": \", properties.Type, \" := \", properties.DefaultValue)\n\t\t\twrite(file, \"\\n\")\n\t\t}\n\t\twrite(file, m.indent(1), \");\\n\")\n\t}\n\n\tif len(m.Inputs) > 0 || len(m.Outputs) > 0 {\n\t\twrite(file, m.indent(1), \"port (\\n\")\n\t\tvar isFirst bool\n\n\t\t\/\/ Entity - Inputs\n\t\tisFirst = true\n\t\tfor name, properties := range m.Inputs {\n\t\t\twrite(file, m.indent(2))\n\t\t\tif isFirst {\n\t\t\t\twrite(file, \" \")\n\t\t\t\tisFirst = false\n\t\t\t} else {\n\t\t\t\twrite(file, \"; \")\n\t\t\t}\n\t\t\twrite(file, properties.ToStdLogic(name))\n\t\t\twrite(file, \"\\n\")\n\t\t}\n\n\t\t\/\/ Entity - Outputs\n\t\t\/\/ We're merely continuing the same list so don't reset isFirst.\n\t\t\/\/ TODO make this DRY with Inputs section\n\t\tfor name, properties := range m.Outputs {\n\t\t\twrite(file, m.indent(2))\n\t\t\tif isFirst {\n\t\t\t\twrite(file, \" \")\n\t\t\t\tisFirst = false\n\t\t\t} else {\n\t\t\t\twrite(file, \"; \")\n\t\t\t}\n\t\t\twrite(file, properties.ToStdLogic(name))\n\t\t\twrite(file, \"\\n\")\n\t\t}\n\n\t\twrite(file, m.indent(1), \");\\n\")\n\t}\n\n\t\/\/ Entity end\n\twrite(file, \"end \", m.Options.trimmedModuleName, \";\\n\")\n\twrite(file, \"\\n\")\n\n\t\/\/ architecture start\n\twrite(file, \"architecture Behavioral of \", m.Options.trimmedModuleName, \" is\\n\")\n\n\t\/\/ Constants (?)\n\t\/\/ Internal Signals\n\twrite(file, m.indent(1), \"-- Register signals\\n\")\n\tfor sigName, signal := range m.Registers {\n\t\twrite(file, m.indent(1), signal.ToStdLogicSignal(sigName+\"_reg, \"+sigName+\"_next\"), \"\\n\")\n\t}\n\twrite(file, \"\\n\")\n\n\t\/\/ Internal signals for functional units\n\tfor unitName, unit := range m.FunctionalUnits {\n\t\twrite(file, m.indent(1), \"-- \", unitName, \" connections\\n\")\n\t\tfor sigName, signal := range unit.Inputs {\n\t\t\twrite(file, m.indent(1), signal.ToStdLogicSignal(sigName), \"\\n\")\n\t\t}\n\t\tfor sigName, signal := range unit.Outputs {\n\t\t\twrite(file, m.indent(1), signal.ToStdLogicSignal(sigName), \"\\n\")\n\t\t}\n\t\tfor sigName, signal := range unit.Registers {\n\t\t\twrite(file, m.indent(1), signal.ToStdLogicSignal(sigName+\"_reg\"), \"\\n\")\n\t\t\twrite(file, m.indent(1), signal.ToStdLogicSignal(sigName+\"_reg, \"+sigName+\"_next\"), \"\\n\")\n\t\t}\n\t}\n\tif len(m.FunctionalUnits) > 0 {\n\t\twrite(file, \"\\n\")\n\t}\n\n\twrite(file, m.indent(1), \"-- FSM declarations\\n\")\n\t\/\/ State machine states\n\twrite(file, m.indent(1), \"type state is (\")\n\tisFirst := true\n\tfor stateName, _ := range m.States {\n\t\tif isFirst {\n\t\t\tisFirst = false\n\t\t} else {\n\t\t\twrite(file, \", \")\n\t\t}\n\t\twrite(file, stateName)\n\t}\n\twrite(file, \"\\n\")\n\t\/\/ State machine signals\n\twrite(file, m.indent(1), \"signal state_reg, state_next : state := \", m.Options.FirstState, \";\\n\")\n\n\t\/\/ architecture \"begin\"\n\twrite(file, \"begin\\n\")\n\n\t\/\/ Register process\n\twrite(file, m.indent(1), \"-- Register Process\\n\")\n\twrite(file, m.indent(1), \"process(clk\")\n\tif *m.Options.AddAsyncReset {\n\t\twrite(file, \", rst\")\n\t}\n\twrite(file, \")\\n\")\n\twrite(file, m.indent(1), \"begin\\n\")\n\tif *m.Options.AddAsyncReset {\n\t\twrite(file, m.indent(2), \"if (rst='1') then\\n\")\n\t\twrite(file, m.indent(3), \"-- async reset of registers\\n\")\n\t\twrite(file, m.indent(3), \"state_reg <= \", m.Options.FirstState, \";\\n\")\n\t\tfor name, reg := range m.Registers {\n\t\t\tdefVal := reg.DefaultValue\n\t\t\tif defVal == \"0\" {\n\t\t\t\tdefVal = \"(others => '0')\"\n\t\t\t}\n\t\t\twrite(file, m.indent(3), name+\"_reg\", \" <= \", defVal, \";\\n\")\n\t\t}\n\t}\n\twrite(file, m.indent(2))\n\tif *m.Options.AddAsyncReset {\n\t\twrite(file, \"els\")\n\t}\n\tif m.Options.ClockType == \"posedge\" {\n\t\twrite(file, \"if (clk'event and clk='1') then\\n\")\n\t} else if m.Options.ClockType == \"negedge\" {\n\t\twrite(file, \"if (clk'event and clk='0') then\\n\")\n\t} else {\n\t\treturn errors.New(\"Unrecognized clock type: \" + m.Options.ClockType)\n\t}\n\twrite(file, m.indent(3), \"-- FSM state register\\n\")\n\twrite(file, m.indent(3), \"state_reg <= state_next;\\n\")\n\twrite(file, m.indent(3), \"-- algorithm registers\\n\")\n\tfor name, _ := range m.Registers {\n\t\twrite(file, m.indent(3), name+\"_reg\", \" <= \", name+\"_next\", \";\\n\")\n\t}\n\twrite(file, m.indent(2), \"end if;\\n\")\n\twrite(file, m.indent(1), \"end process;\\n\")\n\twrite(file, \"\\n\")\n\n\t\/\/ Next State + Output + RTL Operation process\n\twrite(file, m.indent(1), \"-- Next State + Output + RTL Operation process\\n\")\n\twrite(file, m.indent(1), \"process(\")\n\t\/\/ TODO add in proper sensitivity list inference instead of this \"benign sledgehammer\" approach\n\tisFirst = true\n\tfor name, _ := range m.Inputs {\n\t\tif name == \"clk\" || name == \"rst\" {\n\t\t\tcontinue\n\t\t}\n\t\tif !isFirst {\n\t\t\twrite(file, \", \")\n\t\t} else {\n\t\t\tisFirst = false\n\t\t}\n\t\twrite(file, name)\n\t}\n\tfor name, _ := range m.Registers {\n\t\tif !isFirst {\n\t\t\twrite(file, \", \")\n\t\t} else {\n\t\t\tisFirst = false\n\t\t}\n\t\twrite(file, name+\"_reg\", \", \", name+\"_next\")\n\t}\n\twrite(file, \")\\n\")\n\twrite(file, m.indent(1), \"begin\\n\")\n\t\/\/ default register 'next's to previous value\n\twrite(file, m.indent(2), \"state_next <= state_reg;\\n\")\n\tfor regName, _ := range m.Registers {\n\t\twrite(file, m.indent(2), regName+\"_next\", \" <= \", regName+\"_reg\", \";\\n\")\n\t}\n\tfor outName, out := range m.Outputs {\n\t\twrite(file, m.indent(2), outName, \" <= \", out.DefaultValue, \";\\n\")\n\t}\n\t\/\/ state switch statement\n\twrite(file, m.indent(2), \"case state_reg is\\n\")\n\tfor stateName, state := range m.States {\n\t\tif state.IsMealy {\n\t\t\tcontinue\n\t\t}\n\t\twrite(file, m.indent(3), \"case \", stateName, \" =>\\n\")\n\t\twriteVhdlNextNetwork(file, 4, m, state.Next)\n\t\tfor regName, operation := range state.Operations {\n\t\t\twrite(file, m.indent(4), regName+\"_next\", \" <= \", operation, \";\\n\")\n\t\t}\n\t}\n\twrite(file, m.indent(2), \"end case;\\n\")\n\twrite(file, m.indent(1), \"end process;\\n\")\n\n\t\/\/ Functional units\n\tfor unitName, unit := range m.FunctionalUnits {\n\t\twrite(file, \"\\n\")\n\t\twrite(file, m.indent(1), \"-- FunctionalUnit \", unitName, \" with \", strconv.Itoa(len(unit.Registers)), \" registers\\n\")\n\t}\n\n\t\/\/ architecture end\n\twrite(file, \"end Behavioral;\\n\")\n\twrite(file, \"\\n\")\n\n\treturn nil\n}\n\nfunc writeVhdlNextNetwork(file *os.File, indentLevel uint, m *StateMachine, nextThingName string) {\n\tif nextState, ok := m.States[nextThingName]; ok && !nextState.IsMealy {\n\t\t\/\/ base case\n\t\t\/\/ TODO validate this is valid during Parse\n\t\twrite(file, m.indent(indentLevel), \"state_reg <= \", nextThingName, \";\\n\")\n\t} else if nextState, ok := m.States[nextThingName]; ok && nextState.IsMealy {\n\t\tfor out, action := range nextState.Operations {\n\t\t\tvarName := out\n\t\t\tif _, ok := m.Registers[out]; ok {\n\t\t\t\tvarName = out + \"_next\"\n\t\t\t}\n\t\t\twrite(file, m.indent(indentLevel), varName, \" <= \", action, \";\\n\")\n\t\t}\n\t\twriteVhdlNextNetwork(file, indentLevel, m, nextState.Next)\n\t} else if cond, ok := m.Conditions[nextThingName]; ok {\n\t\t\/\/ TODO support elsif\n\t\twrite(file, m.indent(indentLevel), \"if \", cond.Expression, \" then\\n\")\n\t\twriteVhdlNextNetwork(file, indentLevel+1, m, cond.TrueTarget)\n\t\twrite(file, m.indent(indentLevel), \"else\\n\")\n\t\twriteVhdlNextNetwork(file, indentLevel+1, m, cond.FalseTarget)\n\t\twrite(file, m.indent(indentLevel), \"end if;\\n\")\n\t}\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"errors\"\n\t\"github.com\/cyfdecyf\/shadowsocks-go\/src\/shadowsocks\"\n)\n\nfunc initShadowSocks() {\n\tif config.shadowPasswd != \"\" {\n\t\tif config.shadowSocks == \"\" {\n\t\t\tgoto confnotcomplete\n\t\t}\n\t\tshadowsocks.InitTable(config.shadowPasswd)\n\t} else if config.shadowSocks != \"\" {\n\t\tgoto confnotcomplete\n\t}\nconfnotcomplete:\n\terrl.Println(\"Missing option, shadowSocks and shadowPasswd should be both given\")\n}\n\nvar noShadowSocksErr = errors.New(\"No shadowsocks configuration\")\n\nfunc createShadowSocksConnection(hostFull string) (cn conn, err error) {\n\tif config.shadowSocks == \"\" {\n\t\treturn zeroConn, noShadowSocksErr\n\t}\n\tc, err := shadowsocks.Dial(hostFull, config.shadowSocks)\n\tif err != nil {\n\t\tdebug.Printf(\"Creating shadowsocks connection: %s %v\\n\", hostFull, err)\n\t\treturn zeroConn, err\n\t}\n\tdebug.Println(\"shadowsocks connection created to:\", hostFull)\n\treturn conn{c, shadowSocksConn}, nil\n}\nRefactor shadowsocks initialization.package main\n\nimport (\n\t\"errors\"\n\t\"github.com\/cyfdecyf\/shadowsocks-go\/src\/shadowsocks\"\n)\n\nvar hasShadowSocksServer = false\n\nfunc initShadowSocks() {\n\tif config.shadowSocks != \"\" && config.shadowPasswd != \"\" {\n\t\tshadowsocks.InitTable(config.shadowPasswd)\n\t\thasShadowSocksServer = true\n\t\treturn\n\t}\n\tif (config.shadowSocks != \"\" && config.shadowPasswd == \"\") ||\n\t\t(config.shadowSocks == \"\" && config.shadowPasswd != \"\") {\n\t\terrl.Println(\"Missing option, shadowSocks and shadowPasswd should be both given\")\n\t}\n}\n\nvar noShadowSocksErr = errors.New(\"No shadowsocks configuration\")\n\nfunc createShadowSocksConnection(hostFull string) (cn conn, err error) {\n\tif config.shadowSocks == \"\" {\n\t\treturn zeroConn, noShadowSocksErr\n\t}\n\tc, err := shadowsocks.Dial(hostFull, config.shadowSocks)\n\tif err != nil {\n\t\tdebug.Printf(\"Creating shadowsocks connection: %s %v\\n\", hostFull, err)\n\t\treturn zeroConn, err\n\t}\n\tdebug.Println(\"shadowsocks connection created to:\", hostFull)\n\treturn conn{c, shadowSocksConn}, nil\n}\n<|endoftext|>"} {"text":"package builder\n\n\/\/ nginx\nconst (\n\tNginxVersion = \"1.22.0\"\n\tNginxDownloadURLPrefix = \"https:\/\/nginx.org\/download\"\n)\n\n\/\/ pcre\nconst (\n\tPcreVersion = \"10.40\"\n\tPcreDownloadURLPrefix = \"https:\/\/github.com\/PhilipHazel\/pcre2\/releases\/download\"\n)\n\n\/\/ openssl\nconst (\n\tOpenSSLVersion = \"1.1.1p\"\n\tOpenSSLDownloadURLPrefix = \"https:\/\/www.openssl.org\/source\"\n)\n\n\/\/ libressl\nconst (\n\tLibreSSLVersion = \"3.5.3\"\n\tLibreSSLDownloadURLPrefix = \"https:\/\/ftp.openbsd.org\/pub\/OpenBSD\/LibreSSL\"\n)\n\n\/\/ zlib\nconst (\n\tZlibVersion = \"1.2.12\"\n\tZlibDownloadURLPrefix = \"https:\/\/zlib.net\"\n)\n\n\/\/ openResty\nconst (\n\tOpenRestyVersion = \"1.21.4.1\"\n\tOpenRestyDownloadURLPrefix = \"https:\/\/openresty.org\/download\"\n)\n\n\/\/ tengine\nconst (\n\tTengineVersion = \"2.3.3\"\n\tTengineDownloadURLPrefix = \"https:\/\/tengine.taobao.org\/download\"\n)\n\n\/\/ component enumerations\nconst (\n\tComponentNginx = iota\n\tComponentOpenResty\n\tComponentTengine\n\tComponentPcre\n\tComponentOpenSSL\n\tComponentLibreSSL\n\tComponentZlib\n\tComponentMax\n)\nbumped default openssl version to 1.1.1q.package builder\n\n\/\/ nginx\nconst (\n\tNginxVersion = \"1.22.0\"\n\tNginxDownloadURLPrefix = \"https:\/\/nginx.org\/download\"\n)\n\n\/\/ pcre\nconst (\n\tPcreVersion = \"10.40\"\n\tPcreDownloadURLPrefix = \"https:\/\/github.com\/PhilipHazel\/pcre2\/releases\/download\"\n)\n\n\/\/ openssl\nconst (\n\tOpenSSLVersion = \"1.1.1q\"\n\tOpenSSLDownloadURLPrefix = \"https:\/\/www.openssl.org\/source\"\n)\n\n\/\/ libressl\nconst (\n\tLibreSSLVersion = \"3.5.3\"\n\tLibreSSLDownloadURLPrefix = \"https:\/\/ftp.openbsd.org\/pub\/OpenBSD\/LibreSSL\"\n)\n\n\/\/ zlib\nconst (\n\tZlibVersion = \"1.2.12\"\n\tZlibDownloadURLPrefix = \"https:\/\/zlib.net\"\n)\n\n\/\/ openResty\nconst (\n\tOpenRestyVersion = \"1.21.4.1\"\n\tOpenRestyDownloadURLPrefix = \"https:\/\/openresty.org\/download\"\n)\n\n\/\/ tengine\nconst (\n\tTengineVersion = \"2.3.3\"\n\tTengineDownloadURLPrefix = \"https:\/\/tengine.taobao.org\/download\"\n)\n\n\/\/ component enumerations\nconst (\n\tComponentNginx = iota\n\tComponentOpenResty\n\tComponentTengine\n\tComponentPcre\n\tComponentOpenSSL\n\tComponentLibreSSL\n\tComponentZlib\n\tComponentMax\n)\n<|endoftext|>"} {"text":"\/\/ Copyright © 2017 The Kubicorn 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 resources\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"strconv\"\n\n\t\"github.com\/digitalocean\/godo\"\n\t\"github.com\/kris-nova\/kubicorn\/apis\/cluster\"\n\t\"github.com\/kris-nova\/kubicorn\/cloud\"\n\t\"github.com\/kris-nova\/kubicorn\/cutil\/compare\"\n\t\"github.com\/kris-nova\/kubicorn\/cutil\/defaults\"\n\t\"github.com\/kris-nova\/kubicorn\/cutil\/logger\"\n)\n\nvar _ cloud.Resource = &SSH{}\n\ntype SSH struct {\n\tShared\n\tUser string\n\tPublicKeyFingerprint string\n\tPublicKeyData string\n\tPublicKeyPath string\n}\n\nfunc (r *SSH) Actual(immutable *cluster.Cluster) (*cluster.Cluster, cloud.Resource, error) {\n\tlogger.Debug(\"ssh.Actual\")\n\tnewResource := &SSH{\n\t\tShared: Shared{\n\t\t\tName: r.Name,\n\t\t\tCloudID: immutable.SSH.Identifier,\n\t\t},\n\t\tUser: immutable.SSH.User,\n\t}\n\n\tif r.CloudID != \"\" {\n\n\t\tid, err := strconv.Atoi(r.CloudID)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tssh, _, err := Sdk.Client.Keys.GetByID(context.TODO(), id)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tstrid := strconv.Itoa(ssh.ID)\n\t\tnewResource.Name = ssh.Name\n\t\tnewResource.CloudID = strid\n\t\tnewResource.PublicKeyData = ssh.PublicKey\n\t\tnewResource.PublicKeyFingerprint = ssh.Fingerprint\n\t} else {\n\t\tfound := false\n\t\tkeys, _, err := Sdk.Client.Keys.List(context.TODO(), &godo.ListOptions{})\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tfor _, key := range keys {\n\t\t\tif key.Fingerprint == immutable.SSH.PublicKeyFingerprint {\n\t\t\t\tfound = true\n\t\t\t\tnewResource.Name = key.Name\n\t\t\t\tnewResource.CloudID = strconv.Itoa(key.ID)\n\t\t\t\tnewResource.PublicKeyData = key.PublicKey\n\t\t\t\tnewResource.PublicKeyFingerprint = key.Fingerprint\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\tnewResource.PublicKeyPath = immutable.SSH.PublicKeyPath\n\t\t\tnewResource.PublicKeyFingerprint = immutable.SSH.PublicKeyFingerprint\n\t\t\tnewResource.PublicKeyData = string(immutable.SSH.PublicKeyData)\n\t\t\tnewResource.User = immutable.SSH.User\n\t\t\tnewResource.CloudID = immutable.SSH.Identifier\n\t\t}\n\t}\n\n\tnewCluster := r.immutableRender(newResource, immutable)\n\treturn newCluster, newResource, nil\n}\n\nfunc (r *SSH) Expected(immutable *cluster.Cluster) (*cluster.Cluster, cloud.Resource, error) {\n\tlogger.Debug(\"ssh.Expected\")\n\tnewResource := &SSH{\n\t\tShared: Shared{\n\t\t\tName: r.Name,\n\t\t\tCloudID: immutable.SSH.Identifier,\n\t\t},\n\t\tPublicKeyFingerprint: immutable.SSH.PublicKeyFingerprint,\n\t\tPublicKeyData: string(immutable.SSH.PublicKeyData),\n\t\tPublicKeyPath: immutable.SSH.PublicKeyPath,\n\t\tUser: immutable.SSH.User,\n\t}\n\tnewCluster := r.immutableRender(newResource, immutable)\n\treturn newCluster, newResource, nil\n}\n\nfunc (r *SSH) Apply(actual, expected cloud.Resource, immutable *cluster.Cluster) (*cluster.Cluster, cloud.Resource, error) {\n\tlogger.Debug(\"droplet.Apply\")\n\tapplyResource := expected.(*SSH)\n\tisEqual, err := compare.IsEqual(actual.(*SSH), expected.(*SSH))\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif isEqual && actual.(*SSH).Shared.CloudID != \"\" {\n\t\treturn immutable, applyResource, nil\n\t}\n\trequest := &godo.KeyCreateRequest{\n\t\tName: expected.(*SSH).Name,\n\t\tPublicKey: expected.(*SSH).PublicKeyData,\n\t}\n\tkey, _, err := Sdk.Client.Keys.Create(context.TODO(), request)\n\tif err != nil {\n\t\tgodoErr := err.(*godo.ErrorResponse)\n\t\tif godoErr.Message != \"SSH Key is already in use on your account\" {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tkey, _, err = Sdk.Client.Keys.GetByFingerprint(context.TODO(), expected.(*SSH).PublicKeyFingerprint)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tlogger.Info(\"Using existing SSH Key [%s]\", actual.(*SSH).Name)\n\t} else {\n\t\tlogger.Info(\"Created SSH Key [%d]\", key.ID)\n\t}\n\n\tid := strconv.Itoa(key.ID)\n\tnewResource := &SSH{\n\t\tShared: Shared{\n\t\t\tName: key.Name,\n\t\t\tCloudID: id,\n\t\t},\n\t\tPublicKeyFingerprint: key.Fingerprint,\n\t\tPublicKeyData: key.PublicKey,\n\t\tPublicKeyPath: expected.(*SSH).PublicKeyPath,\n\t\tUser: expected.(*SSH).User,\n\t}\n\tnewCluster := r.immutableRender(newResource, immutable)\n\treturn newCluster, newResource, nil\n}\nfunc (r *SSH) Delete(actual cloud.Resource, immutable *cluster.Cluster) (*cluster.Cluster, cloud.Resource, error) {\n\tlogger.Debug(\"ssh.Delete\")\n\tforce := false\n\tif force {\n\t\tdeleteResource := actual.(*SSH)\n\t\tif deleteResource.CloudID == \"\" {\n\t\t\treturn nil, nil, fmt.Errorf(\"Unable to delete ssh resource without Id [%s]\", deleteResource.Name)\n\t\t}\n\t\tid, err := strconv.Atoi(immutable.SSH.Identifier)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\n\t\t_, err = Sdk.Client.Keys.DeleteByID(context.TODO(), id)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\n\t\tlogger.Info(\"Deleted SSH Key [%d]\", id)\n\t}\n\tnewResource := &SSH{}\n\tnewResource.Name = actual.(*SSH).Name\n\tnewResource.Tags = actual.(*SSH).Tags\n\tnewResource.User = actual.(*SSH).User\n\tnewResource.PublicKeyPath = actual.(*SSH).PublicKeyPath\n\n\tnewCluster := r.immutableRender(newResource, immutable)\n\treturn newCluster, newResource, nil\n}\n\nfunc (r *SSH) immutableRender(newResource cloud.Resource, inaccurateCluster *cluster.Cluster) *cluster.Cluster {\n\tlogger.Debug(\"ssh.Render\")\n\tnewCluster := defaults.NewClusterDefaults(inaccurateCluster)\n\tnewCluster.SSH.PublicKeyData = []byte(newResource.(*SSH).PublicKeyData)\n\tnewCluster.SSH.PublicKeyFingerprint = newResource.(*SSH).PublicKeyFingerprint\n\tnewCluster.SSH.PublicKeyPath = newResource.(*SSH).PublicKeyPath\n\tnewCluster.SSH.Identifier = newResource.(*SSH).CloudID\n\tnewCluster.SSH.User = newResource.(*SSH).User\n\treturn newCluster\n}\nFixed a issue where the public key path was missing.\/\/ Copyright © 2017 The Kubicorn 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 resources\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"strconv\"\n\n\t\"github.com\/digitalocean\/godo\"\n\t\"github.com\/kris-nova\/kubicorn\/apis\/cluster\"\n\t\"github.com\/kris-nova\/kubicorn\/cloud\"\n\t\"github.com\/kris-nova\/kubicorn\/cutil\/compare\"\n\t\"github.com\/kris-nova\/kubicorn\/cutil\/defaults\"\n\t\"github.com\/kris-nova\/kubicorn\/cutil\/logger\"\n)\n\nvar _ cloud.Resource = &SSH{}\n\ntype SSH struct {\n\tShared\n\tUser string\n\tPublicKeyFingerprint string\n\tPublicKeyData string\n\tPublicKeyPath string\n}\n\nfunc (r *SSH) Actual(immutable *cluster.Cluster) (*cluster.Cluster, cloud.Resource, error) {\n\tlogger.Debug(\"ssh.Actual\")\n\tnewResource := &SSH{\n\t\tShared: Shared{\n\t\t\tName: r.Name,\n\t\t\tCloudID: immutable.SSH.Identifier,\n\t\t},\n\t\tUser: immutable.SSH.User,\n\t}\n\n\tif r.CloudID != \"\" {\n\n\t\tid, err := strconv.Atoi(r.CloudID)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tssh, _, err := Sdk.Client.Keys.GetByID(context.TODO(), id)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tstrid := strconv.Itoa(ssh.ID)\n\t\tnewResource.Name = ssh.Name\n\t\tnewResource.CloudID = strid\n\t\tnewResource.PublicKeyData = ssh.PublicKey\n\t\tnewResource.PublicKeyFingerprint = ssh.Fingerprint\n\t} else {\n\t\tfound := false\n\t\tkeys, _, err := Sdk.Client.Keys.List(context.TODO(), &godo.ListOptions{})\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tfor _, key := range keys {\n\t\t\tif key.Fingerprint == immutable.SSH.PublicKeyFingerprint {\n\t\t\t\tfound = true\n\t\t\t\tnewResource.Name = key.Name\n\t\t\t\tnewResource.CloudID = strconv.Itoa(key.ID)\n\t\t\t\tnewResource.PublicKeyData = key.PublicKey\n\t\t\t\tnewResource.PublicKeyFingerprint = key.Fingerprint\n\t\t\t\tnewResource.PublicKeyPath = immutable.SSH.PublicKeyPath\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\tnewResource.PublicKeyPath = immutable.SSH.PublicKeyPath\n\t\t\tnewResource.PublicKeyFingerprint = immutable.SSH.PublicKeyFingerprint\n\t\t\tnewResource.PublicKeyData = string(immutable.SSH.PublicKeyData)\n\t\t\tnewResource.User = immutable.SSH.User\n\t\t\tnewResource.CloudID = immutable.SSH.Identifier\n\t\t}\n\t}\n\n\tnewCluster := r.immutableRender(newResource, immutable)\n\treturn newCluster, newResource, nil\n}\n\nfunc (r *SSH) Expected(immutable *cluster.Cluster) (*cluster.Cluster, cloud.Resource, error) {\n\tlogger.Debug(\"ssh.Expected\")\n\tnewResource := &SSH{\n\t\tShared: Shared{\n\t\t\tName: r.Name,\n\t\t\tCloudID: immutable.SSH.Identifier,\n\t\t},\n\t\tPublicKeyFingerprint: immutable.SSH.PublicKeyFingerprint,\n\t\tPublicKeyData: string(immutable.SSH.PublicKeyData),\n\t\tPublicKeyPath: immutable.SSH.PublicKeyPath,\n\t\tUser: immutable.SSH.User,\n\t}\n\tnewCluster := r.immutableRender(newResource, immutable)\n\treturn newCluster, newResource, nil\n}\n\nfunc (r *SSH) Apply(actual, expected cloud.Resource, immutable *cluster.Cluster) (*cluster.Cluster, cloud.Resource, error) {\n\tlogger.Debug(\"droplet.Apply\")\n\tapplyResource := expected.(*SSH)\n\tisEqual, err := compare.IsEqual(actual.(*SSH), expected.(*SSH))\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tif isEqual && actual.(*SSH).Shared.CloudID != \"\" {\n\t\treturn immutable, applyResource, nil\n\t}\n\trequest := &godo.KeyCreateRequest{\n\t\tName: expected.(*SSH).Name,\n\t\tPublicKey: expected.(*SSH).PublicKeyData,\n\t}\n\tkey, _, err := Sdk.Client.Keys.Create(context.TODO(), request)\n\tif err != nil {\n\t\tgodoErr := err.(*godo.ErrorResponse)\n\t\tif godoErr.Message != \"SSH Key is already in use on your account\" {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tkey, _, err = Sdk.Client.Keys.GetByFingerprint(context.TODO(), expected.(*SSH).PublicKeyFingerprint)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tlogger.Info(\"Using existing SSH Key [%s]\", actual.(*SSH).Name)\n\t} else {\n\t\tlogger.Info(\"Created SSH Key [%d]\", key.ID)\n\t}\n\n\tid := strconv.Itoa(key.ID)\n\tnewResource := &SSH{\n\t\tShared: Shared{\n\t\t\tName: key.Name,\n\t\t\tCloudID: id,\n\t\t},\n\t\tPublicKeyFingerprint: key.Fingerprint,\n\t\tPublicKeyData: key.PublicKey,\n\t\tPublicKeyPath: expected.(*SSH).PublicKeyPath,\n\t\tUser: expected.(*SSH).User,\n\t}\n\tnewCluster := r.immutableRender(newResource, immutable)\n\treturn newCluster, newResource, nil\n}\nfunc (r *SSH) Delete(actual cloud.Resource, immutable *cluster.Cluster) (*cluster.Cluster, cloud.Resource, error) {\n\tlogger.Debug(\"ssh.Delete\")\n\tforce := false\n\tif force {\n\t\tdeleteResource := actual.(*SSH)\n\t\tif deleteResource.CloudID == \"\" {\n\t\t\treturn nil, nil, fmt.Errorf(\"Unable to delete ssh resource without Id [%s]\", deleteResource.Name)\n\t\t}\n\t\tid, err := strconv.Atoi(immutable.SSH.Identifier)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\n\t\t_, err = Sdk.Client.Keys.DeleteByID(context.TODO(), id)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\n\t\tlogger.Info(\"Deleted SSH Key [%d]\", id)\n\t}\n\tnewResource := &SSH{}\n\tnewResource.Name = actual.(*SSH).Name\n\tnewResource.Tags = actual.(*SSH).Tags\n\tnewResource.User = actual.(*SSH).User\n\tnewResource.PublicKeyPath = actual.(*SSH).PublicKeyPath\n\n\tnewCluster := r.immutableRender(newResource, immutable)\n\treturn newCluster, newResource, nil\n}\n\nfunc (r *SSH) immutableRender(newResource cloud.Resource, inaccurateCluster *cluster.Cluster) *cluster.Cluster {\n\tlogger.Debug(\"ssh.Render\")\n\tnewCluster := defaults.NewClusterDefaults(inaccurateCluster)\n\tnewCluster.SSH.PublicKeyData = []byte(newResource.(*SSH).PublicKeyData)\n\tnewCluster.SSH.PublicKeyFingerprint = newResource.(*SSH).PublicKeyFingerprint\n\tnewCluster.SSH.PublicKeyPath = newResource.(*SSH).PublicKeyPath\n\tnewCluster.SSH.Identifier = newResource.(*SSH).CloudID\n\tnewCluster.SSH.User = newResource.(*SSH).User\n\treturn newCluster\n}\n<|endoftext|>"} {"text":"package gate\n\nimport (\n\t\"github.com\/golang\/protobuf\/proto\"\n\t\"github.com\/name5566\/leaf\/chanrpc\"\n\t\"github.com\/name5566\/leaf\/log\"\n\t\"github.com\/name5566\/leaf\/network\"\n\t\"github.com\/name5566\/leaf\/network\/json\"\n\t\"github.com\/name5566\/leaf\/network\/protobuf\"\n\t\"reflect\"\n)\n\ntype TCPGate struct {\n\tAddr string\n\tMaxConnNum int\n\tPendingWriteNum int\n\tLenMsgLen int\n\tMinMsgLen uint32\n\tMaxMsgLen uint32\n\tLittleEndian bool\n\tJSONProcessor *json.Processor\n\tProtobufProcessor *protobuf.Processor\n\tAgentChanRPC *chanrpc.Server\n}\n\nfunc (gate *TCPGate) Run(closeSig chan bool) {\n\tserver := new(network.TCPServer)\n\tserver.Addr = gate.Addr\n\tserver.MaxConnNum = gate.MaxConnNum\n\tserver.PendingWriteNum = gate.PendingWriteNum\n\tserver.LenMsgLen = gate.LenMsgLen\n\tserver.MinMsgLen = gate.MinMsgLen\n\tserver.MaxMsgLen = gate.MaxMsgLen\n\tserver.LittleEndian = gate.LittleEndian\n\tserver.NewAgent = func(conn *network.TCPConn) network.Agent {\n\t\ta := new(TCPAgent)\n\t\ta.conn = conn\n\t\ta.gate = gate\n\n\t\tif gate.AgentChanRPC != nil {\n\t\t\tgate.AgentChanRPC.Go(\"NewAgent\", a)\n\t\t}\n\n\t\treturn a\n\t}\n\n\tserver.Start()\n\t<-closeSig\n\tserver.Close()\n}\n\nfunc (gate *TCPGate) OnDestroy() {}\n\ntype TCPAgent struct {\n\tconn *network.TCPConn\n\tgate *TCPGate\n\tuserData interface{}\n}\n\nfunc (a *TCPAgent) Run() {\n\tfor {\n\t\tdata, err := a.conn.ReadMsg()\n\t\tif err != nil {\n\t\t\tlog.Debug(\"read message: %v\", err)\n\t\t\tbreak\n\t\t}\n\n\t\tif a.gate.JSONProcessor != nil {\n\t\t\t\/\/ json\n\t\t\tmsg, err := a.gate.JSONProcessor.Unmarshal(data)\n\t\t\tif err != nil {\n\t\t\t\tlog.Debug(\"unmarshal json error: %v\", err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\terr = a.gate.JSONProcessor.Route(msg, Agent(a))\n\t\t\tif err != nil {\n\t\t\t\tlog.Debug(\"route message error: %v\", err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t} else if a.gate.ProtobufProcessor != nil {\n\t\t\t\/\/ protobuf\n\t\t\tmsg, err := a.gate.ProtobufProcessor.Unmarshal(data)\n\t\t\tif err != nil {\n\t\t\t\tlog.Debug(\"unmarshal protobuf error: %v\", err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\terr = a.gate.ProtobufProcessor.Route(msg, Agent(a))\n\t\t\tif err != nil {\n\t\t\t\tlog.Debug(\"route message error: %v\", err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (a *TCPAgent) OnClose() {\n\tif a.gate.AgentChanRPC != nil {\n\t\terr := a.gate.AgentChanRPC.Open(0).Call0(\"CloseAgent\", a)\n\t\tif err != nil {\n\t\t\tlog.Error(\"chanrpc error: %v\", err)\n\t\t}\n\t}\n}\n\nfunc (a *TCPAgent) WriteMsg(msg interface{}) {\n\tif a.gate.JSONProcessor != nil {\n\t\t\/\/ json\n\t\tdata, err := a.gate.JSONProcessor.Marshal(msg)\n\t\tif err != nil {\n\t\t\tlog.Error(\"marshal json %v error: %v\", reflect.TypeOf(msg), err)\n\t\t\treturn\n\t\t}\n\t\ta.conn.WriteMsg(data)\n\t} else if a.gate.ProtobufProcessor != nil {\n\t\t\/\/ protobuf\n\t\tid, data, err := a.gate.ProtobufProcessor.Marshal(msg.(proto.Message))\n\t\tif err != nil {\n\t\t\tlog.Error(\"marshal protobuf %v error: %v\", reflect.TypeOf(msg), err)\n\t\t\treturn\n\t\t}\n\t\ta.conn.WriteMsg(id, data)\n\t}\n}\n\nfunc (a *TCPAgent) Close() {\n\ta.conn.Close()\n}\n\nfunc (a *TCPAgent) UserData() interface{} {\n\treturn a.userData\n}\n\nfunc (a *TCPAgent) SetUserData(data interface{}) {\n\ta.userData = data\n}\nGate support Websocketpackage gate\n\nimport (\n\t\"github.com\/golang\/protobuf\/proto\"\n\t\"github.com\/name5566\/leaf\/chanrpc\"\n\t\"github.com\/name5566\/leaf\/log\"\n\t\"github.com\/name5566\/leaf\/network\"\n\t\"github.com\/name5566\/leaf\/network\/json\"\n\t\"github.com\/name5566\/leaf\/network\/protobuf\"\n\t\"reflect\"\n\t\"time\"\n)\n\ntype Gate struct {\n\tMaxConnNum int\n\tPendingWriteNum int\n\tMaxMsgLen uint32\n\tJSONProcessor *json.Processor\n\tProtobufProcessor *protobuf.Processor\n\tAgentChanRPC *chanrpc.Server\n\n\t\/\/ websocket\n\tWSAddr string\n\tHTTPTimeout time.Duration\n\n\t\/\/ tcp\n\tTCPAddr string\n\tLenMsgLen int\n\tLittleEndian bool\n}\n\nfunc (gate *Gate) Run(closeSig chan bool) {\n\tvar wsServer *network.WSServer\n\tif gate.WSAddr != \"\" {\n\t\twsServer = new(network.WSServer)\n\t\twsServer.Addr = gate.WSAddr\n\t\twsServer.MaxConnNum = gate.MaxConnNum\n\t\twsServer.PendingWriteNum = gate.PendingWriteNum\n\t\twsServer.MaxMsgLen = gate.MaxMsgLen\n\t\twsServer.HTTPTimeout = gate.HTTPTimeout\n\t\twsServer.NewAgent = func(conn *network.WSConn) network.Agent {\n\t\t\ta := &agent{wsConn: conn, gate: gate}\n\t\t\tif gate.AgentChanRPC != nil {\n\t\t\t\tgate.AgentChanRPC.Go(\"NewAgent\", a)\n\t\t\t}\n\t\t\treturn a\n\t\t}\n\t}\n\n\tvar tcpServer *network.TCPServer\n\tif gate.TCPAddr != \"\" {\n\t\ttcpServer = new(network.TCPServer)\n\t\ttcpServer.Addr = gate.TCPAddr\n\t\ttcpServer.MaxConnNum = gate.MaxConnNum\n\t\ttcpServer.PendingWriteNum = gate.PendingWriteNum\n\t\ttcpServer.LenMsgLen = gate.LenMsgLen\n\t\ttcpServer.MaxMsgLen = gate.MaxMsgLen\n\t\ttcpServer.LittleEndian = gate.LittleEndian\n\t\ttcpServer.NewAgent = func(conn *network.TCPConn) network.Agent {\n\t\t\ta := &agent{tcpConn: conn, gate: gate}\n\t\t\tif gate.AgentChanRPC != nil {\n\t\t\t\tgate.AgentChanRPC.Go(\"NewAgent\", a)\n\t\t\t}\n\t\t\treturn a\n\t\t}\n\t}\n\n\tif wsServer != nil {\n\t\twsServer.Start()\n\t}\n\tif tcpServer != nil {\n\t\ttcpServer.Start()\n\t}\n\t<-closeSig\n\tif wsServer != nil {\n\t\twsServer.Close()\n\t}\n\tif tcpServer != nil {\n\t\ttcpServer.Close()\n\t}\n}\n\nfunc (gate *Gate) OnDestroy() {}\n\ntype agent struct {\n\twsConn *network.WSConn\n\ttcpConn *network.TCPConn\n\tgate *Gate\n\tuserData interface{}\n}\n\nfunc (a *agent) Run() {\n\tfor {\n\t\tvar (\n\t\t\tdata []byte\n\t\t\terr error\n\t\t)\n\t\tif a.wsConn != nil {\n\t\t\tdata, err = a.wsConn.ReadMsg()\n\t\t} else if a.tcpConn != nil {\n\t\t\tdata, err = a.tcpConn.ReadMsg()\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Debug(\"read message: %v\", err)\n\t\t\tbreak\n\t\t}\n\n\t\tif a.gate.JSONProcessor != nil {\n\t\t\t\/\/ json\n\t\t\tmsg, err := a.gate.JSONProcessor.Unmarshal(data)\n\t\t\tif err != nil {\n\t\t\t\tlog.Debug(\"unmarshal json error: %v\", err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\terr = a.gate.JSONProcessor.Route(msg, a)\n\t\t\tif err != nil {\n\t\t\t\tlog.Debug(\"route message error: %v\", err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t} else if a.gate.ProtobufProcessor != nil {\n\t\t\t\/\/ protobuf\n\t\t\tmsg, err := a.gate.ProtobufProcessor.Unmarshal(data)\n\t\t\tif err != nil {\n\t\t\t\tlog.Debug(\"unmarshal protobuf error: %v\", err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\terr = a.gate.ProtobufProcessor.Route(msg, a)\n\t\t\tif err != nil {\n\t\t\t\tlog.Debug(\"route message error: %v\", err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (a *agent) OnClose() {\n\tif a.gate.AgentChanRPC != nil {\n\t\terr := a.gate.AgentChanRPC.Open(0).Call0(\"CloseAgent\", a)\n\t\tif err != nil {\n\t\t\tlog.Error(\"chanrpc error: %v\", err)\n\t\t}\n\t}\n}\n\nfunc (a *agent) WriteMsg(msg interface{}) {\n\tif a.gate.JSONProcessor != nil {\n\t\t\/\/ json\n\t\tdata, err := a.gate.JSONProcessor.Marshal(msg)\n\t\tif err != nil {\n\t\t\tlog.Error(\"marshal json %v error: %v\", reflect.TypeOf(msg), err)\n\t\t\treturn\n\t\t}\n\t\tif a.wsConn != nil {\n\t\t\ta.wsConn.WriteMsg(data)\n\t\t} else if a.tcpConn != nil {\n\t\t\ta.tcpConn.WriteMsg(data)\n\t\t}\n\t} else if a.gate.ProtobufProcessor != nil {\n\t\t\/\/ protobuf\n\t\tid, data, err := a.gate.ProtobufProcessor.Marshal(msg.(proto.Message))\n\t\tif err != nil {\n\t\t\tlog.Error(\"marshal protobuf %v error: %v\", reflect.TypeOf(msg), err)\n\t\t\treturn\n\t\t}\n\t\tif a.wsConn != nil {\n\t\t\tb := make([]byte, len(id)+len(data))\n\t\t\tcopy(b, id)\n\t\t\tcopy(b[len(id):], data)\n\t\t\ta.wsConn.WriteMsg(b)\n\t\t} else if a.tcpConn != nil {\n\t\t\ta.tcpConn.WriteMsg(id, data)\n\t\t}\n\t}\n}\n\nfunc (a *agent) Close() {\n\tif a.wsConn != nil {\n\t\ta.wsConn.Close()\n\t} else if a.tcpConn != nil {\n\t\ta.tcpConn.Close()\n\t}\n}\n\nfunc (a *agent) UserData() interface{} {\n\treturn a.userData\n}\n\nfunc (a *agent) SetUserData(data interface{}) {\n\ta.userData = data\n}\n<|endoftext|>"} {"text":"package aws\n\nimport (\n\t\"fmt\"\n\n\t\"encoding\/json\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/batch\"\n\t\"github.com\/hashicorp\/terraform\/helper\/schema\"\n\t\"github.com\/hashicorp\/terraform\/helper\/structure\"\n\t\"github.com\/hashicorp\/terraform\/helper\/validation\"\n)\n\nfunc resourceAwsBatchJobDefinition() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceAwsBatchJobDefinitionCreate,\n\t\tRead: resourceAwsBatchJobDefinitionRead,\n\t\tDelete: resourceAwsBatchJobDefinitionDelete,\n\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"name\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t\tValidateFunc: validateBatchName,\n\t\t\t},\n\t\t\t\"container_properties\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t\tStateFunc: func(v interface{}) string {\n\t\t\t\t\tjson, _ := structure.NormalizeJsonString(v)\n\t\t\t\t\treturn json\n\t\t\t\t},\n\t\t\t\tDiffSuppressFunc: suppressEquivalentJsonDiffs,\n\t\t\t\tValidateFunc: validateAwsBatchJobContainerProperties,\n\t\t\t},\n\t\t\t\"parameters\": {\n\t\t\t\tType: schema.TypeMap,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t\tElem: schema.TypeString,\n\t\t\t},\n\t\t\t\"retry_strategy\": {\n\t\t\t\tType: schema.TypeList,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t\tMaxItems: 1,\n\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\tSchema: map[string]*schema.Schema{\n\t\t\t\t\t\t\"attempts\": {\n\t\t\t\t\t\t\tType: schema.TypeInt,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tValidateFunc: validation.IntBetween(1, 10),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"timeout\": {\n\t\t\t\tType: schema.TypeList,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t\tMaxItems: 1,\n\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\tSchema: map[string]*schema.Schema{\n\t\t\t\t\t\t\"attempt_duration_seconds\": {\n\t\t\t\t\t\t\tType: schema.TypeInt,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tValidateFunc: validation.IntAtLeast(60),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"type\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t\tValidateFunc: validation.StringInSlice([]string{batch.JobDefinitionTypeContainer}, true),\n\t\t\t},\n\t\t\t\"revision\": {\n\t\t\t\tType: schema.TypeInt,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t\t\"arn\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc resourceAwsBatchJobDefinitionCreate(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).batchconn\n\tname := d.Get(\"name\").(string)\n\n\tinput := &batch.RegisterJobDefinitionInput{\n\t\tJobDefinitionName: aws.String(name),\n\t\tType: aws.String(d.Get(\"type\").(string)),\n\t}\n\n\tif v, ok := d.GetOk(\"container_properties\"); ok {\n\t\tprops, err := expandBatchJobContainerProperties(v.(string))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"%s %q\", err, name)\n\t\t}\n\t\tinput.ContainerProperties = props\n\t}\n\n\tif v, ok := d.GetOk(\"parameters\"); ok {\n\t\tinput.Parameters = expandJobDefinitionParameters(v.(map[string]interface{}))\n\t}\n\n\tif v, ok := d.GetOk(\"retry_strategy\"); ok {\n\t\tinput.RetryStrategy = expandJobDefinitionRetryStrategy(v.([]interface{}))\n\t}\n\n\tif v, ok := d.GetOk(\"timeout\"); ok {\n\t\tinput.Timeout = expandJobDefinitionTimeout(v.([]interface{}))\n\t}\n\n\tout, err := conn.RegisterJobDefinition(input)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%s %q\", err, name)\n\t}\n\td.SetId(*out.JobDefinitionArn)\n\td.Set(\"arn\", out.JobDefinitionArn)\n\treturn resourceAwsBatchJobDefinitionRead(d, meta)\n}\n\nfunc resourceAwsBatchJobDefinitionRead(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).batchconn\n\tarn := d.Get(\"arn\").(string)\n\tjob, err := getJobDefinition(conn, arn)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%s %q\", err, arn)\n\t}\n\tif job == nil {\n\t\td.SetId(\"\")\n\t\treturn nil\n\t}\n\td.Set(\"arn\", job.JobDefinitionArn)\n\td.Set(\"container_properties\", job.ContainerProperties)\n\td.Set(\"parameters\", aws.StringValueMap(job.Parameters))\n\n\tif err := d.Set(\"retry_strategy\", flattenBatchRetryStrategy(job.RetryStrategy)); err != nil {\n\t\treturn fmt.Errorf(\"error setting retry_strategy: %s\", err)\n\t}\n\n\tif err := d.Set(\"timeout\", flattenBatchJobTimeout(job.Timeout)); err != nil {\n\t\treturn fmt.Errorf(\"error setting timeout: %s\", err)\n\t}\n\n\td.Set(\"revision\", job.Revision)\n\td.Set(\"type\", job.Type)\n\treturn nil\n}\n\nfunc resourceAwsBatchJobDefinitionDelete(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).batchconn\n\tarn := d.Get(\"arn\").(string)\n\t_, err := conn.DeregisterJobDefinition(&batch.DeregisterJobDefinitionInput{\n\t\tJobDefinition: aws.String(arn),\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%s %q\", err, arn)\n\t}\n\td.SetId(\"\")\n\treturn nil\n}\n\nfunc getJobDefinition(conn *batch.Batch, arn string) (*batch.JobDefinition, error) {\n\tdescribeOpts := &batch.DescribeJobDefinitionsInput{\n\t\tJobDefinitions: []*string{aws.String(arn)},\n\t}\n\tresp, err := conn.DescribeJobDefinitions(describeOpts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnumJobDefinitions := len(resp.JobDefinitions)\n\tswitch {\n\tcase numJobDefinitions == 0:\n\t\treturn nil, nil\n\tcase numJobDefinitions == 1:\n\t\tif *resp.JobDefinitions[0].Status == \"ACTIVE\" {\n\t\t\treturn resp.JobDefinitions[0], nil\n\t\t}\n\t\treturn nil, nil\n\tcase numJobDefinitions > 1:\n\t\treturn nil, fmt.Errorf(\"Multiple Job Definitions with name %s\", arn)\n\t}\n\treturn nil, nil\n}\n\nfunc validateAwsBatchJobContainerProperties(v interface{}, k string) (ws []string, errors []error) {\n\tvalue := v.(string)\n\t_, err := expandBatchJobContainerProperties(value)\n\tif err != nil {\n\t\terrors = append(errors, fmt.Errorf(\"AWS Batch Job container_properties is invalid: %s\", err))\n\t}\n\treturn\n}\n\nfunc expandBatchJobContainerProperties(rawProps string) (*batch.ContainerProperties, error) {\n\tvar props *batch.ContainerProperties\n\n\terr := json.Unmarshal([]byte(rawProps), &props)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error decoding JSON: %s\", err)\n\t}\n\n\treturn props, nil\n}\n\nfunc expandJobDefinitionParameters(params map[string]interface{}) map[string]*string {\n\tvar jobParams = make(map[string]*string)\n\tfor k, v := range params {\n\t\tjobParams[k] = aws.String(v.(string))\n\t}\n\n\treturn jobParams\n}\n\nfunc expandJobDefinitionRetryStrategy(item []interface{}) *batch.RetryStrategy {\n\tdata := item[0].(map[string]interface{})\n\treturn &batch.RetryStrategy{\n\t\tAttempts: aws.Int64(int64(data[\"attempts\"].(int))),\n\t}\n}\n\nfunc flattenBatchRetryStrategy(item *batch.RetryStrategy) []map[string]interface{} {\n\tdata := []map[string]interface{}{}\n\tif item != nil {\n\t\tdata = append(data, map[string]interface{}{\n\t\t\t\"attempts\": int(aws.Int64Value(item.Attempts)),\n\t\t})\n\t}\n\treturn data\n}\n\nfunc expandJobDefinitionTimeout(item []interface{}) *batch.JobTimeout {\n\tdata := item[0].(map[string]interface{})\n\treturn &batch.JobTimeout{\n\t\tAttemptDurationSeconds: aws.Int64(int64(data[\"attempt_duration_seconds\"].(int))),\n\t}\n}\n\nfunc flattenBatchJobTimeout(item *batch.JobTimeout) []map[string]interface{} {\n\tdata := []map[string]interface{}{}\n\tif item != nil {\n\t\tdata = append(data, map[string]interface{}{\n\t\t\t\"attempt_duration_seconds\": int(aws.Int64Value(item.AttemptDurationSeconds)),\n\t\t})\n\t}\n\treturn data\n}\nAdd additional error checking to flatten and expandpackage aws\n\nimport (\n\t\"fmt\"\n\n\t\"encoding\/json\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/batch\"\n\t\"github.com\/hashicorp\/terraform\/helper\/schema\"\n\t\"github.com\/hashicorp\/terraform\/helper\/structure\"\n\t\"github.com\/hashicorp\/terraform\/helper\/validation\"\n)\n\nfunc resourceAwsBatchJobDefinition() *schema.Resource {\n\treturn &schema.Resource{\n\t\tCreate: resourceAwsBatchJobDefinitionCreate,\n\t\tRead: resourceAwsBatchJobDefinitionRead,\n\t\tDelete: resourceAwsBatchJobDefinitionDelete,\n\n\t\tSchema: map[string]*schema.Schema{\n\t\t\t\"name\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t\tValidateFunc: validateBatchName,\n\t\t\t},\n\t\t\t\"container_properties\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t\tStateFunc: func(v interface{}) string {\n\t\t\t\t\tjson, _ := structure.NormalizeJsonString(v)\n\t\t\t\t\treturn json\n\t\t\t\t},\n\t\t\t\tDiffSuppressFunc: suppressEquivalentJsonDiffs,\n\t\t\t\tValidateFunc: validateAwsBatchJobContainerProperties,\n\t\t\t},\n\t\t\t\"parameters\": {\n\t\t\t\tType: schema.TypeMap,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t\tElem: schema.TypeString,\n\t\t\t},\n\t\t\t\"retry_strategy\": {\n\t\t\t\tType: schema.TypeList,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t\tMaxItems: 1,\n\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\tSchema: map[string]*schema.Schema{\n\t\t\t\t\t\t\"attempts\": {\n\t\t\t\t\t\t\tType: schema.TypeInt,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tValidateFunc: validation.IntBetween(1, 10),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"timeout\": {\n\t\t\t\tType: schema.TypeList,\n\t\t\t\tOptional: true,\n\t\t\t\tForceNew: true,\n\t\t\t\tMaxItems: 1,\n\t\t\t\tElem: &schema.Resource{\n\t\t\t\t\tSchema: map[string]*schema.Schema{\n\t\t\t\t\t\t\"attempt_duration_seconds\": {\n\t\t\t\t\t\t\tType: schema.TypeInt,\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tValidateFunc: validation.IntAtLeast(60),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"type\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tRequired: true,\n\t\t\t\tForceNew: true,\n\t\t\t\tValidateFunc: validation.StringInSlice([]string{batch.JobDefinitionTypeContainer}, true),\n\t\t\t},\n\t\t\t\"revision\": {\n\t\t\t\tType: schema.TypeInt,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t\t\"arn\": {\n\t\t\t\tType: schema.TypeString,\n\t\t\t\tComputed: true,\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc resourceAwsBatchJobDefinitionCreate(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).batchconn\n\tname := d.Get(\"name\").(string)\n\n\tinput := &batch.RegisterJobDefinitionInput{\n\t\tJobDefinitionName: aws.String(name),\n\t\tType: aws.String(d.Get(\"type\").(string)),\n\t}\n\n\tif v, ok := d.GetOk(\"container_properties\"); ok {\n\t\tprops, err := expandBatchJobContainerProperties(v.(string))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"%s %q\", err, name)\n\t\t}\n\t\tinput.ContainerProperties = props\n\t}\n\n\tif v, ok := d.GetOk(\"parameters\"); ok {\n\t\tinput.Parameters = expandJobDefinitionParameters(v.(map[string]interface{}))\n\t}\n\n\tif v, ok := d.GetOk(\"retry_strategy\"); ok {\n\t\tinput.RetryStrategy = expandJobDefinitionRetryStrategy(v.([]interface{}))\n\t}\n\n\tif v, ok := d.GetOk(\"timeout\"); ok {\n\t\tinput.Timeout = expandJobDefinitionTimeout(v.([]interface{}))\n\t}\n\n\tout, err := conn.RegisterJobDefinition(input)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%s %q\", err, name)\n\t}\n\td.SetId(*out.JobDefinitionArn)\n\td.Set(\"arn\", out.JobDefinitionArn)\n\treturn resourceAwsBatchJobDefinitionRead(d, meta)\n}\n\nfunc resourceAwsBatchJobDefinitionRead(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).batchconn\n\tarn := d.Get(\"arn\").(string)\n\tjob, err := getJobDefinition(conn, arn)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%s %q\", err, arn)\n\t}\n\tif job == nil {\n\t\td.SetId(\"\")\n\t\treturn nil\n\t}\n\td.Set(\"arn\", job.JobDefinitionArn)\n\td.Set(\"container_properties\", job.ContainerProperties)\n\td.Set(\"parameters\", aws.StringValueMap(job.Parameters))\n\n\tif err := d.Set(\"retry_strategy\", flattenBatchRetryStrategy(job.RetryStrategy)); err != nil {\n\t\treturn fmt.Errorf(\"error setting retry_strategy: %s\", err)\n\t}\n\n\tif err := d.Set(\"timeout\", flattenBatchJobTimeout(job.Timeout)); err != nil {\n\t\treturn fmt.Errorf(\"error setting timeout: %s\", err)\n\t}\n\n\td.Set(\"revision\", job.Revision)\n\td.Set(\"type\", job.Type)\n\treturn nil\n}\n\nfunc resourceAwsBatchJobDefinitionDelete(d *schema.ResourceData, meta interface{}) error {\n\tconn := meta.(*AWSClient).batchconn\n\tarn := d.Get(\"arn\").(string)\n\t_, err := conn.DeregisterJobDefinition(&batch.DeregisterJobDefinitionInput{\n\t\tJobDefinition: aws.String(arn),\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%s %q\", err, arn)\n\t}\n\td.SetId(\"\")\n\treturn nil\n}\n\nfunc getJobDefinition(conn *batch.Batch, arn string) (*batch.JobDefinition, error) {\n\tdescribeOpts := &batch.DescribeJobDefinitionsInput{\n\t\tJobDefinitions: []*string{aws.String(arn)},\n\t}\n\tresp, err := conn.DescribeJobDefinitions(describeOpts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnumJobDefinitions := len(resp.JobDefinitions)\n\tswitch {\n\tcase numJobDefinitions == 0:\n\t\treturn nil, nil\n\tcase numJobDefinitions == 1:\n\t\tif *resp.JobDefinitions[0].Status == \"ACTIVE\" {\n\t\t\treturn resp.JobDefinitions[0], nil\n\t\t}\n\t\treturn nil, nil\n\tcase numJobDefinitions > 1:\n\t\treturn nil, fmt.Errorf(\"Multiple Job Definitions with name %s\", arn)\n\t}\n\treturn nil, nil\n}\n\nfunc validateAwsBatchJobContainerProperties(v interface{}, k string) (ws []string, errors []error) {\n\tvalue := v.(string)\n\t_, err := expandBatchJobContainerProperties(value)\n\tif err != nil {\n\t\terrors = append(errors, fmt.Errorf(\"AWS Batch Job container_properties is invalid: %s\", err))\n\t}\n\treturn\n}\n\nfunc expandBatchJobContainerProperties(rawProps string) (*batch.ContainerProperties, error) {\n\tvar props *batch.ContainerProperties\n\n\terr := json.Unmarshal([]byte(rawProps), &props)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error decoding JSON: %s\", err)\n\t}\n\n\treturn props, nil\n}\n\nfunc expandJobDefinitionParameters(params map[string]interface{}) map[string]*string {\n\tvar jobParams = make(map[string]*string)\n\tfor k, v := range params {\n\t\tjobParams[k] = aws.String(v.(string))\n\t}\n\n\treturn jobParams\n}\n\nfunc expandJobDefinitionRetryStrategy(item []interface{}) *batch.RetryStrategy {\n\tretryStrategy := &batch.RetryStrategy{}\n\tdata := item[0].(map[string]interface{})\n\n\tif v, ok := data[\"attempts\"].(int); ok && v > 0 && v <= 10 {\n\t\tretryStrategy.Attempts = aws.Int64(int64(v))\n\t}\n\n\treturn retryStrategy\n}\n\nfunc flattenBatchRetryStrategy(item *batch.RetryStrategy) []map[string]interface{} {\n\tdata := []map[string]interface{}{}\n\tif item != nil && item.Attempts != nil {\n\t\tdata = append(data, map[string]interface{}{\n\t\t\t\"attempts\": int(aws.Int64Value(item.Attempts)),\n\t\t})\n\t}\n\treturn data\n}\n\nfunc expandJobDefinitionTimeout(item []interface{}) *batch.JobTimeout {\n\ttimeout := &batch.JobTimeout{}\n\tdata := item[0].(map[string]interface{})\n\n\tif v, ok := data[\"attempt_duration_seconds\"].(int); ok && v >= 60 {\n\t\ttimeout.AttemptDurationSeconds = aws.Int64(int64(v))\n\t}\n\n\treturn timeout\n}\n\nfunc flattenBatchJobTimeout(item *batch.JobTimeout) []map[string]interface{} {\n\tdata := []map[string]interface{}{}\n\tif item != nil && item.AttemptDurationSeconds != nil {\n\t\tdata = append(data, map[string]interface{}{\n\t\t\t\"attempt_duration_seconds\": int(aws.Int64Value(item.AttemptDurationSeconds)),\n\t\t})\n\t}\n\treturn data\n}\n<|endoftext|>"} {"text":"package carTime\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/bullettrain-sh\/bullettrain-go-core\/ansi\"\n)\n\nconst (\n\tcarPaint = \"black:white\"\n\tsymbolIcon = \"\"\n\tsymbolPaint = \"black:white\"\n)\n\n\/\/ Time Car\ntype Car struct {\n\tpaint string\n}\n\n\/\/ GetPaint returns the calculated end paint string for the car.\nfunc (c *Car) GetPaint() string {\n\tif c.paint = os.Getenv(\"BULLETTRAIN_CAR_TIME_PAINT\"); c.paint == \"\" {\n\t\tc.paint = carPaint\n\t}\n\n\treturn c.paint\n}\n\nfunc paintedSymbol() string {\n\tvar timeSymbol string\n\tif timeSymbol = os.Getenv(\"BULLETTRAIN_CAR_TIME_SYMBOL_ICON\"); timeSymbol == \"\" {\n\t\ttimeSymbol = symbolIcon\n\t}\n\n\tvar timeSymbolPaint string\n\tif timeSymbolPaint = os.Getenv(\"BULLETTRAIN_CAR_TIME_SYMBOL_PAINT\"); timeSymbolPaint == \"\" {\n\t\ttimeSymbolPaint = symbolPaint\n\t}\n\n\treturn ansi.Color(timeSymbol, timeSymbolPaint)\n}\n\n\/\/ CanShow decides if this car needs to be displayed.\nfunc (c *Car) CanShow() bool {\n\ts := false\n\tif e := os.Getenv(\"BULLETTRAIN_CAR_TIME_SHOW\"); e == \"true\" {\n\t\ts = true\n\t}\n\n\treturn s\n}\n\n\/\/ Render builds and passes the end product of a completely composed car onto\n\/\/ the channel.\nfunc (c *Car) Render(out chan<- string) {\n\tdefer close(out)\n\tcarPaint := ansi.ColorFunc(c.GetPaint())\n\tn := time.Now()\n\n\tt := n.Format(\"15:04:05\")\n\tif h := os.Getenv(\"BULLETTRAIN_CAR_TIME_12HR\"); h == \"true\" {\n\t\tt = n.Format(\"3:04:05\")\n\t}\n\n\tout <- fmt.Sprintf(\"%s%s\",\n\t\tpaintedSymbol(),\n\t\tcarPaint(fmt.Sprintf(\"%s\", t)))\n}\n\n\/\/ GetSeparatorPaint overrides the Fg\/Bg colours of the right hand side\n\/\/ separator through ENV variables.\nfunc (c *Car) GetSeparatorPaint() string {\n\treturn os.Getenv(\"BULLETTRAIN_CAR_TIME_SEPARATOR_PAINT\")\n}\n\n\/\/ GetSeparatorSymbol overrides the symbol of the right hand side\n\/\/ separator through ENV variables.\nfunc (c *Car) GetSeparatorSymbol() string {\n\treturn os.Getenv(\"BULLETTRAIN_CAR_TIME_SEPARATOR_SYMBOL\")\n}\nFix up time code from code reviewpackage carTime\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com\/bullettrain-sh\/bullettrain-go-core\/ansi\"\n)\n\nconst (\n\tcarPaint = \"black:white\"\n\tsymbolIcon = \"\"\n\tsymbolPaint = \"black:white\"\n)\n\n\/\/ Time Car\ntype Car struct {\n\tpaint string\n}\n\n\/\/ GetPaint returns the calculated end paint string for the car.\nfunc (c *Car) GetPaint() string {\n\tif c.paint = os.Getenv(\"BULLETTRAIN_CAR_TIME_PAINT\"); c.paint == \"\" {\n\t\tc.paint = carPaint\n\t}\n\n\treturn c.paint\n}\n\nfunc paintedSymbol() string {\n\tvar timeSymbol string\n\tif timeSymbol = os.Getenv(\"BULLETTRAIN_CAR_TIME_SYMBOL_ICON\"); timeSymbol == \"\" {\n\t\ttimeSymbol = symbolIcon\n\t}\n\n\tvar timeSymbolPaint string\n\tif timeSymbolPaint = os.Getenv(\"BULLETTRAIN_CAR_TIME_SYMBOL_PAINT\"); timeSymbolPaint == \"\" {\n\t\ttimeSymbolPaint = symbolPaint\n\t}\n\n\treturn ansi.Color(timeSymbol, timeSymbolPaint)\n}\n\n\/\/ CanShow decides if this car needs to be displayed.\nfunc (c *Car) CanShow() bool {\n\ts := false\n\tif e := os.Getenv(\"BULLETTRAIN_CAR_TIME_SHOW\"); e == \"true\" {\n\t\ts = true\n\t}\n\n\treturn s\n}\n\n\/\/ Render builds and passes the end product of a completely composed car onto\n\/\/ the channel.\nfunc (c *Car) Render(out chan<- string) {\n\tdefer close(out)\n\tcarPaint := ansi.ColorFunc(c.GetPaint())\n\tn := time.Now()\n\n\tt := n.Format(\"15:04:05\")\n\tif h := os.Getenv(\"BULLETTRAIN_CAR_TIME_12HR\"); h == \"true\" {\n\t\tt = n.Format(\"3:04:05\")\n\t}\n\n\tout <- fmt.Sprintf(\"%s%s\", paintedSymbol(), carPaint(t))\n}\n\n\/\/ GetSeparatorPaint overrides the Fg\/Bg colours of the right hand side\n\/\/ separator through ENV variables.\nfunc (c *Car) GetSeparatorPaint() string {\n\treturn os.Getenv(\"BULLETTRAIN_CAR_TIME_SEPARATOR_PAINT\")\n}\n\n\/\/ GetSeparatorSymbol overrides the symbol of the right hand side\n\/\/ separator through ENV variables.\nfunc (c *Car) GetSeparatorSymbol() string {\n\treturn os.Getenv(\"BULLETTRAIN_CAR_TIME_SEPARATOR_SYMBOL\")\n}\n<|endoftext|>"} {"text":"\/*\nRESTful API for the car share system\n*\/\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/http\"\n\n\t\"github.com\/LewisWatson\/carshare-back\/model\"\n\t\"github.com\/LewisWatson\/carshare-back\/resource\"\n\t\"github.com\/LewisWatson\/carshare-back\/storage\/mongodb\"\n\t\"github.com\/benbjohnson\/clock\"\n\t\"github.com\/manyminds\/api2go\"\n\t\"github.com\/manyminds\/api2go-adapter\/gingonic\"\n\n\t\"gopkg.in\/LewisWatson\/firebase-jwt-auth.v1\"\n\t\"gopkg.in\/alecthomas\/kingpin.v2\"\n\t\"gopkg.in\/gin-gonic\/gin.v1\"\n\t\"gopkg.in\/mgo.v2\"\n)\n\nvar (\n\tport = kingpin.Flag(\"port\", \"Set port to bind to\").Default(\"31415\").Envar(\"CARSHARE_PORT\").Int()\n\tmgoURL = kingpin.Flag(\"mgoURL\", \"URL to MongoDB server or seed server(s) for clusters\").Default(\"localhost\").Envar(\"CARSHARE_MGO_URL\").URL()\n\tfirebaseProjectID = kingpin.Flag(\"firebase\", \"Firebase project to use for authentication\").Default(\"ridesharelogger\").Envar(\"CARSHARE_FIREBASE_PROJECT\").String()\n\tacao = kingpin.Flag(\"cors\", \"Enable HTTP Access Control (CORS) for the specified URI\").PlaceHolder(\"URI\").Envar(\"CARSHARE_CORS_URI\").String()\n)\n\nfunc main() {\n\n\tkingpin.UsageTemplate(kingpin.CompactUsageTemplate).Version(\"0.3.3\").Author(\"Lewis Watson\")\n\tkingpin.CommandLine.Help = \"API for tracking car shares\"\n\tkingpin.Parse()\n\n\tlog.Printf(\"connecting to mongodb server %s%s\", (*mgoURL).Host, (*mgoURL).Path)\n\tdb, err := mgo.Dial((*mgoURL).String())\n\tif err != nil {\n\t\tlog.Fatalf(\"error connecting to mongodb server: %s\", err)\n\t}\n\n\tuserStorage := &mongodb.UserStorage{}\n\tcarShareStorage := &mongodb.CarShareStorage{}\n\ttripStorage := &mongodb.TripStorage{}\n\n\tlog.Printf(\"using firebase project \\\"%s\\\" for authentication\", *firebaseProjectID)\n\ttokenVerifier, err := fireauth.New(*firebaseProjectID)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tr := gin.Default()\n\tapi := api2go.NewAPIWithRouting(\n\t\t\"v0\",\n\t\tapi2go.NewStaticResolver(\"\/\"),\n\t\tgingonic.New(r),\n\t)\n\n\tif *acao != \"\" {\n\t\tlog.Printf(\"enabling CORS access for %s\", *acao)\n\t\tapi.UseMiddleware(\n\t\t\tfunc(c api2go.APIContexter, w http.ResponseWriter, r *http.Request) {\n\t\t\t\tc.Set(\"db\", db)\n\t\t\t\tw.Header().Set(\"Access-Control-Allow-Origin\", *acao)\n\t\t\t\tw.Header().Set(\"Access-Control-Allow-Headers\", \"Authorization,content-type\")\n\t\t\t\tw.Header().Set(\"Access-Control-Allow-Methods\", \"GET,PATCH,DELETE,OPTIONS\")\n\t\t\t},\n\t\t)\n\t}\n\n\tapi.AddResource(\n\t\tmodel.User{},\n\t\tresource.UserResource{\n\t\t\tUserStorage: userStorage,\n\t\t},\n\t)\n\tapi.AddResource(\n\t\tmodel.Trip{},\n\t\tresource.TripResource{\n\t\t\tTripStorage: tripStorage,\n\t\t\tUserStorage: userStorage,\n\t\t\tCarShareStorage: carShareStorage,\n\t\t\tClock: clock.New(),\n\t\t},\n\t)\n\tapi.AddResource(\n\t\tmodel.CarShare{},\n\t\tresource.CarShareResource{\n\t\t\tCarShareStorage: carShareStorage,\n\t\t\tTripStorage: tripStorage,\n\t\t\tUserStorage: userStorage,\n\t\t\tTokenVerifier: tokenVerifier,\n\t\t},\n\t)\n\n\tr.GET(\"\/ping\", func(c *gin.Context) {\n\t\tc.String(200, \"pong\")\n\t})\n\n\tlog.Printf(\"listening on :%d\", *port)\n\tlog.Fatal(r.Run(fmt.Sprintf(\":%d\", *port)))\n}\nTweak logging\/*\nRESTful API for the car share system\n*\/\npackage main\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"os\"\n\n\t\"github.com\/LewisWatson\/carshare-back\/model\"\n\t\"github.com\/LewisWatson\/carshare-back\/resource\"\n\t\"github.com\/LewisWatson\/carshare-back\/storage\/mongodb\"\n\t\"github.com\/benbjohnson\/clock\"\n\t\"github.com\/manyminds\/api2go\"\n\t\"github.com\/manyminds\/api2go-adapter\/gingonic\"\n\t\"github.com\/op\/go-logging\"\n\n\t\"gopkg.in\/LewisWatson\/firebase-jwt-auth.v1\"\n\t\"gopkg.in\/alecthomas\/kingpin.v2\"\n\t\"gopkg.in\/gin-gonic\/gin.v1\"\n\t\"gopkg.in\/mgo.v2\"\n)\n\nvar (\n\tport = kingpin.Flag(\"port\", \"Set port to bind to\").Default(\"31415\").Envar(\"CARSHARE_PORT\").Int()\n\tmgoURL = kingpin.Flag(\"mgoURL\", \"URL to MongoDB server or seed server(s) for clusters\").Default(\"localhost\").Envar(\"CARSHARE_MGO_URL\").URL()\n\tfirebaseProjectID = kingpin.Flag(\"firebase\", \"Firebase project to use for authentication\").Default(\"ridesharelogger\").Envar(\"CARSHARE_FIREBASE_PROJECT\").String()\n\tacao = kingpin.Flag(\"cors\", \"Enable HTTP Access Control (CORS) for the specified URI\").PlaceHolder(\"URI\").Envar(\"CARSHARE_CORS_URI\").String()\n\n\tlog = logging.MustGetLogger(\"example\")\n\tformat = logging.MustStringFormatter(\n\t\t`%{color}%{time:2006-01-02T15:04:05.999} %{shortfunc} %{level:.4s} %{id:03x}%{color:reset} %{message}`,\n\t)\n)\n\nfunc main() {\n\n\tlogging.SetBackend(logging.NewBackendFormatter(logging.NewLogBackend(os.Stderr, \"\", 0), format))\n\n\tkingpin.UsageTemplate(kingpin.CompactUsageTemplate).Version(\"0.3.3\").Author(\"Lewis Watson\")\n\tkingpin.CommandLine.Help = \"API for tracking car shares\"\n\tkingpin.Parse()\n\n\tlog.Infof(\"connecting to mongodb server %s%s\", (*mgoURL).Host, (*mgoURL).Path)\n\tdb, err := mgo.Dial((*mgoURL).String())\n\tif err != nil {\n\t\tlog.Fatalf(\"error connecting to mongodb server: %s\", err)\n\t}\n\n\tuserStorage := &mongodb.UserStorage{}\n\tcarShareStorage := &mongodb.CarShareStorage{}\n\ttripStorage := &mongodb.TripStorage{}\n\n\tlog.Infof(\"using firebase project \\\"%s\\\" for authentication\", *firebaseProjectID)\n\ttokenVerifier, err := fireauth.New(*firebaseProjectID)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tr := gin.Default()\n\tapi := api2go.NewAPIWithRouting(\n\t\t\"v0\",\n\t\tapi2go.NewStaticResolver(\"\/\"),\n\t\tgingonic.New(r),\n\t)\n\n\tif *acao != \"\" {\n\t\tlog.Infof(\"enabling CORS access for %s\", *acao)\n\t\tapi.UseMiddleware(\n\t\t\tfunc(c api2go.APIContexter, w http.ResponseWriter, r *http.Request) {\n\t\t\t\tc.Set(\"db\", db)\n\t\t\t\tw.Header().Set(\"Access-Control-Allow-Origin\", *acao)\n\t\t\t\tw.Header().Set(\"Access-Control-Allow-Headers\", \"Authorization,content-type\")\n\t\t\t\tw.Header().Set(\"Access-Control-Allow-Methods\", \"GET,PATCH,DELETE,OPTIONS\")\n\t\t\t},\n\t\t)\n\t}\n\n\tapi.AddResource(\n\t\tmodel.User{},\n\t\tresource.UserResource{\n\t\t\tUserStorage: userStorage,\n\t\t},\n\t)\n\tapi.AddResource(\n\t\tmodel.Trip{},\n\t\tresource.TripResource{\n\t\t\tTripStorage: tripStorage,\n\t\t\tUserStorage: userStorage,\n\t\t\tCarShareStorage: carShareStorage,\n\t\t\tClock: clock.New(),\n\t\t},\n\t)\n\tapi.AddResource(\n\t\tmodel.CarShare{},\n\t\tresource.CarShareResource{\n\t\t\tCarShareStorage: carShareStorage,\n\t\t\tTripStorage: tripStorage,\n\t\t\tUserStorage: userStorage,\n\t\t\tTokenVerifier: tokenVerifier,\n\t\t},\n\t)\n\n\tr.GET(\"\/ping\", func(c *gin.Context) {\n\t\tc.String(200, \"pong\")\n\t})\n\n\tlog.Infof(\"Listening and serving HTTP on :%d\", *port)\n\tlog.Fatal(r.Run(fmt.Sprintf(\":%d\", *port)))\n}\n<|endoftext|>"} {"text":"\/*\nRESTful API for the car share system\n*\/\npackage main\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"os\"\n\n\t\"github.com\/LewisWatson\/carshare-back\/model\"\n\t\"github.com\/LewisWatson\/carshare-back\/resource\"\n\t\"github.com\/LewisWatson\/carshare-back\/storage\/mongodb\"\n\t\"github.com\/benbjohnson\/clock\"\n\t\"github.com\/manyminds\/api2go\"\n\t\"github.com\/manyminds\/api2go-adapter\/gingonic\"\n\t\"github.com\/op\/go-logging\"\n\t\"github.com\/prometheus\/client_golang\/prometheus\/promhttp\"\n\n\t\"gopkg.in\/LewisWatson\/firebase-jwt-auth.v1\"\n\t\"gopkg.in\/alecthomas\/kingpin.v2\"\n\t\"gopkg.in\/gin-gonic\/gin.v1\"\n\t\"gopkg.in\/mgo.v2\"\n)\n\nvar (\n\tport = kingpin.Flag(\"port\", \"Set port to bind to\").Default(\"31415\").Envar(\"CARSHARE_PORT\").Int()\n\tmgoURL = kingpin.Flag(\"mgoURL\", \"URL to MongoDB server or seed server(s) for clusters\").Default(\"localhost\").Envar(\"CARSHARE_MGO_URL\").URL()\n\tfirebaseProjectID = kingpin.Flag(\"firebase\", \"Firebase project to use for authentication\").Default(\"ridesharelogger\").Envar(\"CARSHARE_FIREBASE_PROJECT\").String()\n\tacao = kingpin.Flag(\"cors\", \"Enable HTTP Access Control (CORS) for the specified URI\").PlaceHolder(\"URI\").Envar(\"CARSHARE_CORS_URI\").String()\n\n\tlog = logging.MustGetLogger(\"main\")\n\tformat = logging.MustStringFormatter(\n\t\t`%{color}%{time:2006-01-02T15:04:05.999} %{shortpkg} %{longfunc} %{level:.4s} %{id:03x}%{color:reset} %{message}`,\n\t)\n\n\tuserStorage = &mongodb.UserStorage{}\n\tcarShareStorage = &mongodb.CarShareStorage{}\n\ttripStorage = &mongodb.TripStorage{}\n)\n\nfunc init() {\n\n\tlogging.SetBackend(logging.NewBackendFormatter(logging.NewLogBackend(os.Stderr, \"\", 0), format))\n\n\tkingpin.UsageTemplate(kingpin.CompactUsageTemplate).Version(\"0.4.0\").Author(\"Lewis Watson\")\n\tkingpin.CommandLine.Help = \"API for tracking car shares\"\n\tkingpin.Parse()\n}\n\nfunc main() {\n\n\tlog.Infof(\"connecting to mongodb server %s%s\", (*mgoURL).Host, (*mgoURL).Path)\n\tdb, err := mgo.Dial((*mgoURL).String())\n\tif err != nil {\n\t\tlog.Fatalf(\"error connecting to mongodb server: %s\", err)\n\t}\n\n\tlog.Infof(\"using firebase project \\\"%s\\\" for authentication\", *firebaseProjectID)\n\ttokenVerifier, err := fireauth.New(*firebaseProjectID)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tr := gin.Default()\n\tapi := api2go.NewAPIWithRouting(\n\t\t\"v0\",\n\t\tapi2go.NewStaticResolver(\"\/\"),\n\t\tgingonic.New(r),\n\t)\n\n\tif *acao != \"\" {\n\t\tlog.Infof(\"enabling CORS access for %s\", *acao)\n\t\tapi.UseMiddleware(\n\t\t\tfunc(c api2go.APIContexter, w http.ResponseWriter, r *http.Request) {\n\t\t\t\tc.Set(\"db\", db)\n\t\t\t\tw.Header().Set(\"Access-Control-Allow-Origin\", *acao)\n\t\t\t\tw.Header().Set(\"Access-Control-Allow-Headers\", \"Authorization,content-type\")\n\t\t\t\tw.Header().Set(\"Access-Control-Allow-Methods\", \"GET,PATCH,DELETE,OPTIONS\")\n\t\t\t},\n\t\t)\n\t}\n\n\tapi.AddResource(\n\t\tmodel.User{},\n\t\tresource.UserResource{\n\t\t\tUserStorage: userStorage,\n\t\t},\n\t)\n\tapi.AddResource(\n\t\tmodel.Trip{},\n\t\tresource.TripResource{\n\t\t\tTripStorage: tripStorage,\n\t\t\tUserStorage: userStorage,\n\t\t\tCarShareStorage: carShareStorage,\n\t\t\tClock: clock.New(),\n\t\t},\n\t)\n\tapi.AddResource(\n\t\tmodel.CarShare{},\n\t\tresource.CarShareResource{\n\t\t\tCarShareStorage: carShareStorage,\n\t\t\tTripStorage: tripStorage,\n\t\t\tUserStorage: userStorage,\n\t\t\tTokenVerifier: tokenVerifier,\n\t\t},\n\t)\n\n\t\/\/ handler for metrics\n\tr.GET(\"\/metrics\", gin.WrapH(promhttp.Handler()))\n\n\tlog.Infof(\"Listening and serving HTTP on :%d\", *port)\n\tlog.Fatal(r.Run(fmt.Sprintf(\":%d\", *port)))\n}\nTweak logging\/*\nRESTful API for the car share system\n*\/\npackage main\n\nimport (\n\t\"fmt\"\n\t\"net\/http\"\n\t\"os\"\n\n\t\"github.com\/LewisWatson\/carshare-back\/model\"\n\t\"github.com\/LewisWatson\/carshare-back\/resource\"\n\t\"github.com\/LewisWatson\/carshare-back\/storage\/mongodb\"\n\t\"github.com\/benbjohnson\/clock\"\n\t\"github.com\/manyminds\/api2go\"\n\t\"github.com\/manyminds\/api2go-adapter\/gingonic\"\n\t\"github.com\/op\/go-logging\"\n\t\"github.com\/prometheus\/client_golang\/prometheus\/promhttp\"\n\n\t\"gopkg.in\/LewisWatson\/firebase-jwt-auth.v1\"\n\t\"gopkg.in\/alecthomas\/kingpin.v2\"\n\t\"gopkg.in\/gin-gonic\/gin.v1\"\n\t\"gopkg.in\/mgo.v2\"\n)\n\nvar (\n\tport = kingpin.Flag(\"port\", \"Set port to bind to\").Default(\"31415\").Envar(\"CARSHARE_PORT\").Int()\n\tmgoURL = kingpin.Flag(\"mgoURL\", \"URL to MongoDB server or seed server(s) for clusters\").Default(\"localhost\").Envar(\"CARSHARE_MGO_URL\").URL()\n\tfirebaseProjectID = kingpin.Flag(\"firebase\", \"Firebase project to use for authentication\").Default(\"ridesharelogger\").Envar(\"CARSHARE_FIREBASE_PROJECT\").String()\n\tacao = kingpin.Flag(\"cors\", \"Enable HTTP Access Control (CORS) for the specified URI\").PlaceHolder(\"URI\").Envar(\"CARSHARE_CORS_URI\").String()\n\n\tlog = logging.MustGetLogger(\"main\")\n\tformat = logging.MustStringFormatter(\n\t\t`%{color}%{time:2006-01-02T15:04:05.999} %{level:.4s} %{id:03x}%{color:reset} %{message}`,\n\t)\n\n\tuserStorage = &mongodb.UserStorage{}\n\tcarShareStorage = &mongodb.CarShareStorage{}\n\ttripStorage = &mongodb.TripStorage{}\n)\n\nfunc init() {\n\n\tlogging.SetBackend(logging.NewBackendFormatter(logging.NewLogBackend(os.Stderr, \"\", 0), format))\n\n\tkingpin.UsageTemplate(kingpin.CompactUsageTemplate).Version(\"0.4.0\").Author(\"Lewis Watson\")\n\tkingpin.CommandLine.Help = \"API for tracking car shares\"\n\tkingpin.Parse()\n}\n\nfunc main() {\n\n\tlog.Infof(\"connecting to mongodb server %s%s\", (*mgoURL).Host, (*mgoURL).Path)\n\tdb, err := mgo.Dial((*mgoURL).String())\n\tif err != nil {\n\t\tlog.Fatalf(\"error connecting to mongodb server: %s\", err)\n\t}\n\n\tlog.Infof(\"using firebase project \\\"%s\\\" for authentication\", *firebaseProjectID)\n\ttokenVerifier, err := fireauth.New(*firebaseProjectID)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tr := gin.Default()\n\tapi := api2go.NewAPIWithRouting(\n\t\t\"v0\",\n\t\tapi2go.NewStaticResolver(\"\/\"),\n\t\tgingonic.New(r),\n\t)\n\n\tif *acao != \"\" {\n\t\tlog.Infof(\"enabling CORS access for %s\", *acao)\n\t\tapi.UseMiddleware(\n\t\t\tfunc(c api2go.APIContexter, w http.ResponseWriter, r *http.Request) {\n\t\t\t\tc.Set(\"db\", db)\n\t\t\t\tw.Header().Set(\"Access-Control-Allow-Origin\", *acao)\n\t\t\t\tw.Header().Set(\"Access-Control-Allow-Headers\", \"Authorization,content-type\")\n\t\t\t\tw.Header().Set(\"Access-Control-Allow-Methods\", \"GET,PATCH,DELETE,OPTIONS\")\n\t\t\t},\n\t\t)\n\t}\n\n\tapi.AddResource(\n\t\tmodel.User{},\n\t\tresource.UserResource{\n\t\t\tUserStorage: userStorage,\n\t\t},\n\t)\n\tapi.AddResource(\n\t\tmodel.Trip{},\n\t\tresource.TripResource{\n\t\t\tTripStorage: tripStorage,\n\t\t\tUserStorage: userStorage,\n\t\t\tCarShareStorage: carShareStorage,\n\t\t\tClock: clock.New(),\n\t\t},\n\t)\n\tapi.AddResource(\n\t\tmodel.CarShare{},\n\t\tresource.CarShareResource{\n\t\t\tCarShareStorage: carShareStorage,\n\t\t\tTripStorage: tripStorage,\n\t\t\tUserStorage: userStorage,\n\t\t\tTokenVerifier: tokenVerifier,\n\t\t},\n\t)\n\n\t\/\/ handler for metrics\n\tr.GET(\"\/metrics\", gin.WrapH(promhttp.Handler()))\n\n\tlog.Infof(\"Listening and serving HTTP on :%d\", *port)\n\tlog.Fatal(r.Run(fmt.Sprintf(\":%d\", *port)))\n}\n<|endoftext|>"} {"text":"package certs\n\nimport (\n\t\"bytes\"\n\t\"crypto\"\n\t\"crypto\/ecdsa\"\n\t\"crypto\/rand\"\n\t\"crypto\/rsa\"\n\t\"crypto\/sha256\"\n\t\"crypto\/tls\"\n\t\"crypto\/x509\"\n\t\"crypto\/x509\/pkix\"\n\t\"encoding\/hex\"\n\t\"encoding\/pem\"\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\tcache \"github.com\/pmylund\/go-cache\"\n)\n\n\/\/ StorageHandler is a standard interface to a storage backend,\n\/\/ used by AuthorisationManager to read and write key values to the backend\ntype StorageHandler interface {\n\tGetKey(string) (string, error)\n\tSetKey(string, string, int64) error\n\tGetKeys(string) []string\n\tDeleteKey(string) bool\n\tDeleteScanMatch(string) bool\n}\n\ntype CertificateManager struct {\n\tstorage StorageHandler\n\tlogger *logrus.Entry\n\tcache *cache.Cache\n\tsecret string\n}\n\nfunc NewCertificateManager(storage StorageHandler, secret string, logger *logrus.Logger) *CertificateManager {\n\tif logger == nil {\n\t\tlogger = logrus.New()\n\t}\n\n\treturn &CertificateManager{\n\t\tstorage: storage,\n\t\tlogger: logger.WithFields(logrus.Fields{\"prefix\": \"cert_storage\"}),\n\t\tcache: cache.New(5*time.Minute, 10*time.Minute),\n\t\tsecret: secret,\n\t}\n}\n\n\/\/ Extracted from: https:\/\/golang.org\/src\/crypto\/tls\/tls.go\n\/\/\n\/\/ Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates\n\/\/ PKCS#1 private keys by default, while OpenSSL 1.0.0 generates PKCS#8 keys.\n\/\/ OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three.\nfunc parsePrivateKey(der []byte) (crypto.PrivateKey, error) {\n\tif key, err := x509.ParsePKCS1PrivateKey(der); err == nil {\n\t\treturn key, nil\n\t}\n\tif key, err := x509.ParsePKCS8PrivateKey(der); err == nil {\n\t\tswitch key := key.(type) {\n\t\tcase *rsa.PrivateKey, *ecdsa.PrivateKey:\n\t\t\treturn key, nil\n\t\tdefault:\n\t\t\treturn nil, errors.New(\"tls: found unknown private key type in PKCS#8 wrapping\")\n\t\t}\n\t}\n\n\tif key, err := x509.ParseECPrivateKey(der); err == nil {\n\t\treturn key, nil\n\t}\n\n\treturn nil, errors.New(\"tls: failed to parse private key\")\n}\n\nfunc isSHA256(value string) bool {\n\t\/\/ check if hex encoded\n\tif _, err := hex.DecodeString(value); err != nil {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\nfunc HexSHA256(cert []byte) string {\n\tcertSHA := sha256.Sum256(cert)\n\treturn hex.EncodeToString(certSHA[:])\n}\n\nfunc ParsePEM(data []byte, secret string) ([]*pem.Block, error) {\n\tvar pemBlocks []*pem.Block\n\n\tfor {\n\t\tvar block *pem.Block\n\t\tblock, data = pem.Decode(data)\n\n\t\tif block == nil {\n\t\t\tbreak\n\t\t}\n\n\t\tif x509.IsEncryptedPEMBlock(block) {\n\t\t\tvar err error\n\t\t\tblock.Bytes, err = x509.DecryptPEMBlock(block, []byte(secret))\n\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\tpemBlocks = append(pemBlocks, block)\n\t}\n\n\treturn pemBlocks, nil\n}\n\nfunc publicKey(priv interface{}) interface{} {\n\tswitch k := priv.(type) {\n\tcase *rsa.PrivateKey:\n\t\treturn &k.PublicKey\n\tcase *ecdsa.PrivateKey:\n\t\treturn &k.PublicKey\n\tdefault:\n\t\treturn nil\n\t}\n}\n\nfunc ParsePEMCertificate(data []byte, secret string) (*tls.Certificate, error) {\n\tvar cert tls.Certificate\n\n\tblocks, err := ParsePEM(data, secret)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar certID string\n\n\tfor _, block := range blocks {\n\t\tif block.Type == \"CERTIFICATE\" {\n\t\t\tcertID = HexSHA256(block.Bytes)\n\t\t\tcert.Certificate = append(cert.Certificate, block.Bytes)\n\t\t\tcontinue\n\t\t}\n\n\t\tif strings.HasSuffix(block.Type, \"PRIVATE KEY\") {\n\t\t\tcert.PrivateKey, err = parsePrivateKey(block.Bytes)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif block.Type == \"PUBLIC KEY\" {\n\t\t\t\/\/ Create a dummny cert just for listing purpose\n\t\t\tcert.Certificate = append(cert.Certificate, block.Bytes)\n\t\t\tcert.Leaf = &x509.Certificate{Subject: pkix.Name{CommonName: \"Public Key: \" + HexSHA256(block.Bytes)}}\n\t\t}\n\t}\n\n\tif len(cert.Certificate) == 0 {\n\t\treturn nil, errors.New(\"Can't find CERTIFICATE block\")\n\t}\n\n\tif cert.Leaf == nil {\n\t\tcert.Leaf, err = x509.ParseCertificate(cert.Certificate[0])\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t\/\/ Cache certificate fingerprint\n\tcert.Leaf.Extensions = append([]pkix.Extension{{\n\t\tValue: []byte(certID),\n\t}}, cert.Leaf.Extensions...)\n\n\treturn &cert, nil\n}\n\ntype CertificateType int\n\nconst (\n\tCertificatePrivate CertificateType = iota\n\tCertificatePublic\n\tCertificateAny\n)\n\nfunc isPrivateKeyEmpty(cert *tls.Certificate) bool {\n\tswitch priv := cert.PrivateKey.(type) {\n\tdefault:\n\t\tif priv == nil {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc isCertCanBeListed(cert *tls.Certificate, mode CertificateType) bool {\n\tswitch mode {\n\tcase CertificatePrivate:\n\t\treturn !isPrivateKeyEmpty(cert)\n\tcase CertificatePublic:\n\t\treturn isPrivateKeyEmpty(cert)\n\tcase CertificateAny:\n\t\treturn true\n\t}\n\n\treturn true\n}\n\ntype CertificateMeta struct {\n\tID string `json:\"id\"`\n\tFingerprint string `json:\"fingerprint\"`\n\tHasPrivateKey bool `json:\"has_private\"`\n\tIssuer pkix.Name `json:\"issuer,omitempty\"`\n\tSubject pkix.Name `json:\"subject,omitempty\"`\n\tNotBefore time.Time `json:\"not_before,omitempty\"`\n\tNotAfter time.Time `json:\"not_after,omitempty\"`\n\tDNSNames []string `json:\"dns_names,omitempty\"`\n}\n\nfunc ExtractCertificateMeta(cert *tls.Certificate, certID string) *CertificateMeta {\n\treturn &CertificateMeta{\n\t\tID: certID,\n\t\tFingerprint: string(cert.Leaf.Extensions[0].Value),\n\t\tHasPrivateKey: !isPrivateKeyEmpty(cert),\n\t\tIssuer: cert.Leaf.Issuer,\n\t\tSubject: cert.Leaf.Subject,\n\t\tNotBefore: cert.Leaf.NotBefore,\n\t\tNotAfter: cert.Leaf.NotAfter,\n\t\tDNSNames: cert.Leaf.DNSNames,\n\t}\n}\n\nfunc (c *CertificateManager) List(certIDs []string, mode CertificateType) (out []*tls.Certificate) {\n\tvar cert *tls.Certificate\n\tvar rawCert []byte\n\tvar err error\n\n\tfor _, id := range certIDs {\n\t\tif cert, found := c.cache.Get(id); found {\n\t\t\tif isCertCanBeListed(cert.(*tls.Certificate), mode) {\n\t\t\t\tout = append(out, cert.(*tls.Certificate))\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif isSHA256(id) {\n\t\t\tvar val string\n\t\t\tval, err = c.storage.GetKey(\"raw-\" + id)\n\t\t\tif err != nil {\n\t\t\t\tc.logger.Warn(\"Can't retrieve certificate from Redis:\", id, err)\n\t\t\t\tout = append(out, nil)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\trawCert = []byte(val)\n\t\t} else {\n\t\t\trawCert, err = ioutil.ReadFile(id)\n\t\t\tif err != nil {\n\t\t\t\tc.logger.Error(\"Error while reading certificate from file:\", id, err)\n\t\t\t\tout = append(out, nil)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tcert, err = ParsePEMCertificate(rawCert, c.secret)\n\t\tif err != nil {\n\t\t\tc.logger.Error(\"Error while parsing certificate: \", id, \" \", err)\n\t\t\tout = append(out, nil)\n\t\t\tcontinue\n\t\t}\n\n\t\tc.cache.Set(id, cert, cache.DefaultExpiration)\n\n\t\tif isCertCanBeListed(cert, mode) {\n\t\t\tout = append(out, cert)\n\t\t}\n\t}\n\n\treturn out\n}\n\n\/\/ Returns list of fingerprints\nfunc (c *CertificateManager) ListPublicKeys(keyIDs []string) (out []string) {\n\tvar rawKey []byte\n\tvar err error\n\n\tfor _, id := range keyIDs {\n\t\tif fingerprint, found := c.cache.Get(\"pub-\" + id); found {\n\t\t\tout = append(out, fingerprint.(string))\n\t\t\tcontinue\n\t\t}\n\n\t\tif isSHA256(id) {\n\t\t\tvar val string\n\t\t\tval, err = c.storage.GetKey(\"raw-\" + id)\n\t\t\tif err != nil {\n\t\t\t\tc.logger.Warn(\"Can't retrieve public key from Redis:\", id, err)\n\t\t\t\tout = append(out, \"\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\trawKey = []byte(val)\n\t\t} else {\n\t\t\trawKey, err = ioutil.ReadFile(id)\n\t\t\tif err != nil {\n\t\t\t\tc.logger.Error(\"Error while reading public key from file:\", id, err)\n\t\t\t\tout = append(out, \"\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tblock, _ := pem.Decode(rawKey)\n\t\tif block == nil {\n\t\t\tc.logger.Error(\"Can't parse public key:\", id)\n\t\t\tout = append(out, \"\")\n\t\t\tcontinue\n\t\t}\n\n\t\tfingerprint := HexSHA256(block.Bytes)\n\t\tc.cache.Set(\"pub-\"+id, fingerprint, cache.DefaultExpiration)\n\t\tout = append(out, fingerprint)\n\t}\n\n\treturn out\n}\n\nfunc (c *CertificateManager) ListAllIds(prefix string) (out []string) {\n\tkeys := c.storage.GetKeys(\"raw-\" + prefix + \"*\")\n\n\tfor _, key := range keys {\n\t\tout = append(out, strings.TrimPrefix(key, \"raw-\"))\n\t}\n\n\treturn out\n}\n\nfunc (c *CertificateManager) GetRaw(certID string) (string, error) {\n\treturn c.storage.GetKey(\"raw-\" + certID)\n}\n\nfunc (c *CertificateManager) Add(certData []byte, orgID string) (string, error) {\n\tvar certBlocks [][]byte\n\tvar keyPEM, keyRaw []byte\n\tvar publicKeyPem []byte\n\n\trest := certData\n\n\tfor {\n\t\tvar block *pem.Block\n\n\t\tblock, rest = pem.Decode(rest)\n\t\tif block == nil {\n\t\t\tbreak\n\t\t}\n\n\t\tif strings.HasSuffix(block.Type, \"PRIVATE KEY\") {\n\t\t\tif len(keyRaw) > 0 {\n\t\t\t\terr := errors.New(\"Found multiple private keys\")\n\t\t\t\tc.logger.Error(err)\n\t\t\t\treturn \"\", err\n\t\t\t}\n\n\t\t\tkeyRaw = block.Bytes\n\t\t\tkeyPEM = pem.EncodeToMemory(block)\n\t\t} else if block.Type == \"CERTIFICATE\" {\n\t\t\tcertBlocks = append(certBlocks, pem.EncodeToMemory(block))\n\t\t} else if block.Type == \"PUBLIC KEY\" {\n\t\t\tpublicKeyPem = pem.EncodeToMemory(block)\n\t\t} else {\n\t\t\tc.logger.Info(\"Ingnoring PEM block with type:\", block.Type)\n\t\t}\n\t}\n\n\tcertChainPEM := bytes.Join(certBlocks, []byte(\"\\n\"))\n\n\tif len(certChainPEM) == 0 {\n\t\tif len(publicKeyPem) == 0 {\n\t\t\terr := errors.New(\"Failed to decode certificate. It should be PEM encoded.\")\n\t\t\tc.logger.Error(err)\n\t\t\treturn \"\", err\n\t\t} else {\n\t\t\tcertChainPEM = publicKeyPem\n\t\t}\n\t} else if len(publicKeyPem) > 0 {\n\t\terr := errors.New(\"Public keys can't be combined with certificates\")\n\t\tc.logger.Error(err)\n\t\treturn \"\", err\n\t}\n\n\tvar certID string\n\n\t\/\/ Found private key, check if it match the certificate\n\tif len(keyPEM) > 0 {\n\t\tcert, err := tls.X509KeyPair(certChainPEM, keyPEM)\n\t\tif err != nil {\n\t\t\tc.logger.Error(err)\n\t\t\treturn \"\", err\n\t\t}\n\n\t\t\/\/ Encrypt private key and append it to the chain\n\t\tencryptedKeyPEMBlock, err := x509.EncryptPEMBlock(rand.Reader, \"ENCRYPTED PRIVATE KEY\", keyRaw, []byte(c.secret), x509.PEMCipherAES256)\n\t\tif err != nil {\n\t\t\tc.logger.Error(\"Failed to encode private key\", err)\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tcertChainPEM = append(certChainPEM, []byte(\"\\n\")...)\n\t\tcertChainPEM = append(certChainPEM, pem.EncodeToMemory(encryptedKeyPEMBlock)...)\n\n\t\tcertID = orgID + HexSHA256(cert.Certificate[0])\n\t} else if len(publicKeyPem) > 0 {\n\t\tpublicKey, _ := pem.Decode(publicKeyPem)\n\t\tcertID = orgID + HexSHA256(publicKey.Bytes)\n\t} else {\n\t\t\/\/ Get first cert\n\t\tcertRaw, _ := pem.Decode(certChainPEM)\n\t\tcert, err := x509.ParseCertificate(certRaw.Bytes)\n\t\tif err != nil {\n\t\t\terr := errors.New(\"Error while parsing certificate: \" + err.Error())\n\t\t\tc.logger.Error(err)\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tcertID = orgID + HexSHA256(cert.Raw)\n\t}\n\n\tif cert, err := c.storage.GetKey(\"raw-\" + certID); err == nil && cert != \"\" {\n\t\treturn \"\", errors.New(\"Certificate with \" + certID + \" id already exists\")\n\t}\n\n\tif err := c.storage.SetKey(\"raw-\"+certID, string(certChainPEM), 0); err != nil {\n\t\tc.logger.Error(err)\n\t\treturn \"\", err\n\t}\n\n\treturn certID, nil\n}\n\nfunc (c *CertificateManager) Delete(certID string) {\n\tc.storage.DeleteKey(\"raw-\" + certID)\n\tc.cache.Delete(certID)\n}\n\nfunc (c *CertificateManager) CertPool(certIDs []string) *x509.CertPool {\n\tpool := x509.NewCertPool()\n\n\tfor _, cert := range c.List(certIDs, CertificatePublic) {\n\t\tif cert != nil {\n\t\t\tpool.AddCert(cert.Leaf)\n\t\t}\n\t}\n\n\treturn pool\n}\n\nfunc (c *CertificateManager) ValidateRequestCertificate(certIDs []string, r *http.Request) error {\n\tif r.TLS == nil {\n\t\treturn errors.New(\"TLS not enabled\")\n\t}\n\n\tif len(r.TLS.PeerCertificates) == 0 {\n\t\treturn errors.New(\"Client TLS certificate is required\")\n\t}\n\n\tleaf := r.TLS.PeerCertificates[0]\n\n\tcertID := HexSHA256(leaf.Raw)\n\tfor _, cert := range c.List(certIDs, CertificatePublic) {\n\t\t\/\/ Extensions[0] contains cache of certificate SHA256\n\t\tif cert == nil || string(cert.Leaf.Extensions[0].Value) == certID {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn errors.New(\"Certificate with SHA256 \" + certID + \" not allowed\")\n}\n\nfunc (c *CertificateManager) FlushCache() {\n\tc.cache.Flush()\n}\n\nfunc (c *CertificateManager) flushStorage() {\n\tc.storage.DeleteScanMatch(\"*\")\n}\nFix retrieval of private certificates from Hybrid env (#2391)package certs\n\nimport (\n\t\"bytes\"\n\t\"crypto\"\n\t\"crypto\/ecdsa\"\n\t\"crypto\/rand\"\n\t\"crypto\/rsa\"\n\t\"crypto\/sha256\"\n\t\"crypto\/tls\"\n\t\"crypto\/x509\"\n\t\"crypto\/x509\/pkix\"\n\t\"encoding\/hex\"\n\t\"encoding\/pem\"\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/Sirupsen\/logrus\"\n\tcache \"github.com\/pmylund\/go-cache\"\n)\n\n\/\/ StorageHandler is a standard interface to a storage backend,\n\/\/ used by AuthorisationManager to read and write key values to the backend\ntype StorageHandler interface {\n\tGetKey(string) (string, error)\n\tSetKey(string, string, int64) error\n\tGetKeys(string) []string\n\tDeleteKey(string) bool\n\tDeleteScanMatch(string) bool\n}\n\ntype CertificateManager struct {\n\tstorage StorageHandler\n\tlogger *logrus.Entry\n\tcache *cache.Cache\n\tsecret string\n}\n\nfunc NewCertificateManager(storage StorageHandler, secret string, logger *logrus.Logger) *CertificateManager {\n\tif logger == nil {\n\t\tlogger = logrus.New()\n\t}\n\n\treturn &CertificateManager{\n\t\tstorage: storage,\n\t\tlogger: logger.WithFields(logrus.Fields{\"prefix\": \"cert_storage\"}),\n\t\tcache: cache.New(5*time.Minute, 10*time.Minute),\n\t\tsecret: secret,\n\t}\n}\n\n\/\/ Extracted from: https:\/\/golang.org\/src\/crypto\/tls\/tls.go\n\/\/\n\/\/ Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates\n\/\/ PKCS#1 private keys by default, while OpenSSL 1.0.0 generates PKCS#8 keys.\n\/\/ OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three.\nfunc parsePrivateKey(der []byte) (crypto.PrivateKey, error) {\n\tif key, err := x509.ParsePKCS1PrivateKey(der); err == nil {\n\t\treturn key, nil\n\t}\n\tif key, err := x509.ParsePKCS8PrivateKey(der); err == nil {\n\t\tswitch key := key.(type) {\n\t\tcase *rsa.PrivateKey, *ecdsa.PrivateKey:\n\t\t\treturn key, nil\n\t\tdefault:\n\t\t\treturn nil, errors.New(\"tls: found unknown private key type in PKCS#8 wrapping\")\n\t\t}\n\t}\n\n\tif key, err := x509.ParseECPrivateKey(der); err == nil {\n\t\treturn key, nil\n\t}\n\n\treturn nil, errors.New(\"tls: failed to parse private key\")\n}\n\nfunc isSHA256(value string) bool {\n\t\/\/ check if hex encoded\n\tif _, err := hex.DecodeString(value); err != nil {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\nfunc HexSHA256(cert []byte) string {\n\tcertSHA := sha256.Sum256(cert)\n\treturn hex.EncodeToString(certSHA[:])\n}\n\nfunc ParsePEM(data []byte, secret string) ([]*pem.Block, error) {\n\tvar pemBlocks []*pem.Block\n\n\tfor {\n\t\tvar block *pem.Block\n\t\tblock, data = pem.Decode(data)\n\n\t\tif block == nil {\n\t\t\tbreak\n\t\t}\n\n\t\tif x509.IsEncryptedPEMBlock(block) {\n\t\t\tvar err error\n\t\t\tblock.Bytes, err = x509.DecryptPEMBlock(block, []byte(secret))\n\t\t\tblock.Headers = nil\n\t\t\tblock.Type = strings.Replace(block.Type, \"ENCRYPTED \", \"\", 1)\n\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\tpemBlocks = append(pemBlocks, block)\n\t}\n\n\treturn pemBlocks, nil\n}\n\nfunc publicKey(priv interface{}) interface{} {\n\tswitch k := priv.(type) {\n\tcase *rsa.PrivateKey:\n\t\treturn &k.PublicKey\n\tcase *ecdsa.PrivateKey:\n\t\treturn &k.PublicKey\n\tdefault:\n\t\treturn nil\n\t}\n}\n\nfunc ParsePEMCertificate(data []byte, secret string) (*tls.Certificate, error) {\n\tvar cert tls.Certificate\n\n\tblocks, err := ParsePEM(data, secret)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar certID string\n\n\tfor _, block := range blocks {\n\t\tif block.Type == \"CERTIFICATE\" {\n\t\t\tcertID = HexSHA256(block.Bytes)\n\t\t\tcert.Certificate = append(cert.Certificate, block.Bytes)\n\t\t\tcontinue\n\t\t}\n\n\t\tif strings.HasSuffix(block.Type, \"PRIVATE KEY\") {\n\t\t\tcert.PrivateKey, err = parsePrivateKey(block.Bytes)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif block.Type == \"PUBLIC KEY\" {\n\t\t\t\/\/ Create a dummny cert just for listing purpose\n\t\t\tcert.Certificate = append(cert.Certificate, block.Bytes)\n\t\t\tcert.Leaf = &x509.Certificate{Subject: pkix.Name{CommonName: \"Public Key: \" + HexSHA256(block.Bytes)}}\n\t\t}\n\t}\n\n\tif len(cert.Certificate) == 0 {\n\t\treturn nil, errors.New(\"Can't find CERTIFICATE block\")\n\t}\n\n\tif cert.Leaf == nil {\n\t\tcert.Leaf, err = x509.ParseCertificate(cert.Certificate[0])\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t\/\/ Cache certificate fingerprint\n\tcert.Leaf.Extensions = append([]pkix.Extension{{\n\t\tValue: []byte(certID),\n\t}}, cert.Leaf.Extensions...)\n\n\treturn &cert, nil\n}\n\ntype CertificateType int\n\nconst (\n\tCertificatePrivate CertificateType = iota\n\tCertificatePublic\n\tCertificateAny\n)\n\nfunc isPrivateKeyEmpty(cert *tls.Certificate) bool {\n\tswitch priv := cert.PrivateKey.(type) {\n\tdefault:\n\t\tif priv == nil {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc isCertCanBeListed(cert *tls.Certificate, mode CertificateType) bool {\n\tswitch mode {\n\tcase CertificatePrivate:\n\t\treturn !isPrivateKeyEmpty(cert)\n\tcase CertificatePublic:\n\t\treturn isPrivateKeyEmpty(cert)\n\tcase CertificateAny:\n\t\treturn true\n\t}\n\n\treturn true\n}\n\ntype CertificateMeta struct {\n\tID string `json:\"id\"`\n\tFingerprint string `json:\"fingerprint\"`\n\tHasPrivateKey bool `json:\"has_private\"`\n\tIssuer pkix.Name `json:\"issuer,omitempty\"`\n\tSubject pkix.Name `json:\"subject,omitempty\"`\n\tNotBefore time.Time `json:\"not_before,omitempty\"`\n\tNotAfter time.Time `json:\"not_after,omitempty\"`\n\tDNSNames []string `json:\"dns_names,omitempty\"`\n}\n\nfunc ExtractCertificateMeta(cert *tls.Certificate, certID string) *CertificateMeta {\n\treturn &CertificateMeta{\n\t\tID: certID,\n\t\tFingerprint: string(cert.Leaf.Extensions[0].Value),\n\t\tHasPrivateKey: !isPrivateKeyEmpty(cert),\n\t\tIssuer: cert.Leaf.Issuer,\n\t\tSubject: cert.Leaf.Subject,\n\t\tNotBefore: cert.Leaf.NotBefore,\n\t\tNotAfter: cert.Leaf.NotAfter,\n\t\tDNSNames: cert.Leaf.DNSNames,\n\t}\n}\n\nfunc (c *CertificateManager) List(certIDs []string, mode CertificateType) (out []*tls.Certificate) {\n\tvar cert *tls.Certificate\n\tvar rawCert []byte\n\tvar err error\n\n\tfor _, id := range certIDs {\n\t\tif cert, found := c.cache.Get(id); found {\n\t\t\tif isCertCanBeListed(cert.(*tls.Certificate), mode) {\n\t\t\t\tout = append(out, cert.(*tls.Certificate))\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tif isSHA256(id) {\n\t\t\tvar val string\n\t\t\tval, err = c.storage.GetKey(\"raw-\" + id)\n\t\t\tif err != nil {\n\t\t\t\tc.logger.Warn(\"Can't retrieve certificate from Redis:\", id, err)\n\t\t\t\tout = append(out, nil)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\trawCert = []byte(val)\n\t\t} else {\n\t\t\trawCert, err = ioutil.ReadFile(id)\n\t\t\tif err != nil {\n\t\t\t\tc.logger.Error(\"Error while reading certificate from file:\", id, err)\n\t\t\t\tout = append(out, nil)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tcert, err = ParsePEMCertificate(rawCert, c.secret)\n\t\tif err != nil {\n\t\t\tc.logger.Error(\"Error while parsing certificate: \", id, \" \", err)\n\t\t\tc.logger.Debug(\"Failed certificate: \", string(rawCert))\n\t\t\tout = append(out, nil)\n\t\t\tcontinue\n\t\t}\n\n\t\tc.cache.Set(id, cert, cache.DefaultExpiration)\n\n\t\tif isCertCanBeListed(cert, mode) {\n\t\t\tout = append(out, cert)\n\t\t}\n\t}\n\n\treturn out\n}\n\n\/\/ Returns list of fingerprints\nfunc (c *CertificateManager) ListPublicKeys(keyIDs []string) (out []string) {\n\tvar rawKey []byte\n\tvar err error\n\n\tfor _, id := range keyIDs {\n\t\tif fingerprint, found := c.cache.Get(\"pub-\" + id); found {\n\t\t\tout = append(out, fingerprint.(string))\n\t\t\tcontinue\n\t\t}\n\n\t\tif isSHA256(id) {\n\t\t\tvar val string\n\t\t\tval, err = c.storage.GetKey(\"raw-\" + id)\n\t\t\tif err != nil {\n\t\t\t\tc.logger.Warn(\"Can't retrieve public key from Redis:\", id, err)\n\t\t\t\tout = append(out, \"\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\trawKey = []byte(val)\n\t\t} else {\n\t\t\trawKey, err = ioutil.ReadFile(id)\n\t\t\tif err != nil {\n\t\t\t\tc.logger.Error(\"Error while reading public key from file:\", id, err)\n\t\t\t\tout = append(out, \"\")\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tblock, _ := pem.Decode(rawKey)\n\t\tif block == nil {\n\t\t\tc.logger.Error(\"Can't parse public key:\", id)\n\t\t\tout = append(out, \"\")\n\t\t\tcontinue\n\t\t}\n\n\t\tfingerprint := HexSHA256(block.Bytes)\n\t\tc.cache.Set(\"pub-\"+id, fingerprint, cache.DefaultExpiration)\n\t\tout = append(out, fingerprint)\n\t}\n\n\treturn out\n}\n\nfunc (c *CertificateManager) ListAllIds(prefix string) (out []string) {\n\tkeys := c.storage.GetKeys(\"raw-\" + prefix + \"*\")\n\n\tfor _, key := range keys {\n\t\tout = append(out, strings.TrimPrefix(key, \"raw-\"))\n\t}\n\n\treturn out\n}\n\nfunc (c *CertificateManager) GetRaw(certID string) (string, error) {\n\treturn c.storage.GetKey(\"raw-\" + certID)\n}\n\nfunc (c *CertificateManager) Add(certData []byte, orgID string) (string, error) {\n\tvar certBlocks [][]byte\n\tvar keyPEM, keyRaw []byte\n\tvar publicKeyPem []byte\n\n\trest := certData\n\n\tfor {\n\t\tvar block *pem.Block\n\n\t\tblock, rest = pem.Decode(rest)\n\t\tif block == nil {\n\t\t\tbreak\n\t\t}\n\n\t\tif strings.HasSuffix(block.Type, \"PRIVATE KEY\") {\n\t\t\tif len(keyRaw) > 0 {\n\t\t\t\terr := errors.New(\"Found multiple private keys\")\n\t\t\t\tc.logger.Error(err)\n\t\t\t\treturn \"\", err\n\t\t\t}\n\n\t\t\tkeyRaw = block.Bytes\n\t\t\tkeyPEM = pem.EncodeToMemory(block)\n\t\t} else if block.Type == \"CERTIFICATE\" {\n\t\t\tcertBlocks = append(certBlocks, pem.EncodeToMemory(block))\n\t\t} else if block.Type == \"PUBLIC KEY\" {\n\t\t\tpublicKeyPem = pem.EncodeToMemory(block)\n\t\t} else {\n\t\t\tc.logger.Info(\"Ingnoring PEM block with type:\", block.Type)\n\t\t}\n\t}\n\n\tcertChainPEM := bytes.Join(certBlocks, []byte(\"\\n\"))\n\n\tif len(certChainPEM) == 0 {\n\t\tif len(publicKeyPem) == 0 {\n\t\t\terr := errors.New(\"Failed to decode certificate. It should be PEM encoded.\")\n\t\t\tc.logger.Error(err)\n\t\t\treturn \"\", err\n\t\t} else {\n\t\t\tcertChainPEM = publicKeyPem\n\t\t}\n\t} else if len(publicKeyPem) > 0 {\n\t\terr := errors.New(\"Public keys can't be combined with certificates\")\n\t\tc.logger.Error(err)\n\t\treturn \"\", err\n\t}\n\n\tvar certID string\n\n\t\/\/ Found private key, check if it match the certificate\n\tif len(keyPEM) > 0 {\n\t\tcert, err := tls.X509KeyPair(certChainPEM, keyPEM)\n\t\tif err != nil {\n\t\t\tc.logger.Error(err)\n\t\t\treturn \"\", err\n\t\t}\n\n\t\t\/\/ Encrypt private key and append it to the chain\n\t\tencryptedKeyPEMBlock, err := x509.EncryptPEMBlock(rand.Reader, \"ENCRYPTED PRIVATE KEY\", keyRaw, []byte(c.secret), x509.PEMCipherAES256)\n\t\tif err != nil {\n\t\t\tc.logger.Error(\"Failed to encode private key\", err)\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tcertChainPEM = append(certChainPEM, []byte(\"\\n\")...)\n\t\tcertChainPEM = append(certChainPEM, pem.EncodeToMemory(encryptedKeyPEMBlock)...)\n\n\t\tcertID = orgID + HexSHA256(cert.Certificate[0])\n\t} else if len(publicKeyPem) > 0 {\n\t\tpublicKey, _ := pem.Decode(publicKeyPem)\n\t\tcertID = orgID + HexSHA256(publicKey.Bytes)\n\t} else {\n\t\t\/\/ Get first cert\n\t\tcertRaw, _ := pem.Decode(certChainPEM)\n\t\tcert, err := x509.ParseCertificate(certRaw.Bytes)\n\t\tif err != nil {\n\t\t\terr := errors.New(\"Error while parsing certificate: \" + err.Error())\n\t\t\tc.logger.Error(err)\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tcertID = orgID + HexSHA256(cert.Raw)\n\t}\n\n\tif cert, err := c.storage.GetKey(\"raw-\" + certID); err == nil && cert != \"\" {\n\t\treturn \"\", errors.New(\"Certificate with \" + certID + \" id already exists\")\n\t}\n\n\tif err := c.storage.SetKey(\"raw-\"+certID, string(certChainPEM), 0); err != nil {\n\t\tc.logger.Error(err)\n\t\treturn \"\", err\n\t}\n\n\treturn certID, nil\n}\n\nfunc (c *CertificateManager) Delete(certID string) {\n\tc.storage.DeleteKey(\"raw-\" + certID)\n\tc.cache.Delete(certID)\n}\n\nfunc (c *CertificateManager) CertPool(certIDs []string) *x509.CertPool {\n\tpool := x509.NewCertPool()\n\n\tfor _, cert := range c.List(certIDs, CertificatePublic) {\n\t\tif cert != nil {\n\t\t\tpool.AddCert(cert.Leaf)\n\t\t}\n\t}\n\n\treturn pool\n}\n\nfunc (c *CertificateManager) ValidateRequestCertificate(certIDs []string, r *http.Request) error {\n\tif r.TLS == nil {\n\t\treturn errors.New(\"TLS not enabled\")\n\t}\n\n\tif len(r.TLS.PeerCertificates) == 0 {\n\t\treturn errors.New(\"Client TLS certificate is required\")\n\t}\n\n\tleaf := r.TLS.PeerCertificates[0]\n\n\tcertID := HexSHA256(leaf.Raw)\n\tfor _, cert := range c.List(certIDs, CertificatePublic) {\n\t\t\/\/ Extensions[0] contains cache of certificate SHA256\n\t\tif cert == nil || string(cert.Leaf.Extensions[0].Value) == certID {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn errors.New(\"Certificate with SHA256 \" + certID + \" not allowed\")\n}\n\nfunc (c *CertificateManager) FlushCache() {\n\tc.cache.Flush()\n}\n\nfunc (c *CertificateManager) flushStorage() {\n\tc.storage.DeleteScanMatch(\"*\")\n}\n<|endoftext|>"} {"text":"package chunk\n\nimport (\n\t\"errors\"\n\t\"sync\"\n\n\t. \"github.com\/claudetech\/loggo\/default\"\n)\n\n\/\/ ErrTimeout is a timeout error\nvar ErrTimeout = errors.New(\"timeout\")\n\n\/\/ Storage is a chunk storage\ntype Storage struct {\n\tChunkSize int64\n\tMaxChunks int\n\tchunks map[string][]byte\n\tstack *Stack\n\tlock sync.Mutex\n}\n\n\/\/ Item represents a chunk in RAM\ntype Item struct {\n\tid string\n\tbytes []byte\n}\n\n\/\/ NewStorage creates a new storage\nfunc NewStorage(chunkSize int64, maxChunks int) *Storage {\n\tstorage := Storage{\n\t\tChunkSize: chunkSize,\n\t\tMaxChunks: maxChunks,\n\t\tchunks: make(map[string][]byte),\n\t\tstack: NewStack(maxChunks),\n\t}\n\n\treturn &storage\n}\n\n\/\/ Clear removes all old chunks on disk (will be called on each program start)\nfunc (s *Storage) Clear() error {\n\treturn nil\n}\n\n\/\/ Load a chunk from ram or creates it\nfunc (s *Storage) Load(id string) []byte {\n\ts.lock.Lock()\n\tif chunk, exists := s.chunks[id]; exists {\n\t\ts.stack.Touch(id)\n\t\ts.lock.Unlock()\n\t\treturn chunk\n\t}\n\ts.lock.Unlock()\n\treturn nil\n}\n\n\/\/ Store stores a chunk in the RAM and adds it to the disk storage queue\nfunc (s *Storage) Store(id string, bytes []byte) error {\n\ts.lock.Lock()\n\n\tif _, exists := s.chunks[id]; exists {\n\t\ts.stack.Touch(id)\n\t\ts.lock.Unlock()\n\t\treturn nil\n\t}\n\n\tdeleteID := s.stack.Pop()\n\tif \"\" != deleteID {\n\t\tdelete(s.chunks, deleteID)\n\n\t\tLog.Debugf(\"Deleted chunk %v\", deleteID)\n\t}\n\n\ts.chunks[id] = bytes\n\ts.stack.Push(id)\n\ts.lock.Unlock()\n\n\treturn nil\n}\nAllow parrallel reads from storage using rw lockpackage chunk\n\nimport (\n\t\"errors\"\n\t\"sync\"\n\n\t. \"github.com\/claudetech\/loggo\/default\"\n)\n\n\/\/ ErrTimeout is a timeout error\nvar ErrTimeout = errors.New(\"timeout\")\n\n\/\/ Storage is a chunk storage\ntype Storage struct {\n\tChunkSize int64\n\tMaxChunks int\n\tchunks map[string][]byte\n\tstack *Stack\n\tlock sync.RWMutex\n}\n\n\/\/ Item represents a chunk in RAM\ntype Item struct {\n\tid string\n\tbytes []byte\n}\n\n\/\/ NewStorage creates a new storage\nfunc NewStorage(chunkSize int64, maxChunks int) *Storage {\n\tstorage := Storage{\n\t\tChunkSize: chunkSize,\n\t\tMaxChunks: maxChunks,\n\t\tchunks: make(map[string][]byte),\n\t\tstack: NewStack(maxChunks),\n\t}\n\n\treturn &storage\n}\n\n\/\/ Clear removes all old chunks on disk (will be called on each program start)\nfunc (s *Storage) Clear() error {\n\treturn nil\n}\n\n\/\/ Load a chunk from ram or creates it\nfunc (s *Storage) Load(id string) []byte {\n\ts.lock.RLock()\n\tif chunk, exists := s.chunks[id]; exists {\n\t\ts.stack.Touch(id)\n\t\ts.lock.RUnlock()\n\t\treturn chunk\n\t}\n\ts.lock.RUnlock()\n\treturn nil\n}\n\n\/\/ Store stores a chunk in the RAM and adds it to the disk storage queue\nfunc (s *Storage) Store(id string, bytes []byte) error {\n\ts.lock.RLock()\n\n\tif _, exists := s.chunks[id]; exists {\n\t\ts.stack.Touch(id)\n\t\ts.lock.RUnlock()\n\t\treturn nil\n\t}\n\n\ts.lock.RUnlock()\n\ts.lock.Lock()\n\n\tdeleteID := s.stack.Pop()\n\tif \"\" != deleteID {\n\t\tdelete(s.chunks, deleteID)\n\n\t\tLog.Debugf(\"Deleted chunk %v\", deleteID)\n\t}\n\n\ts.chunks[id] = bytes\n\ts.stack.Push(id)\n\ts.lock.Unlock()\n\n\treturn nil\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\tkingpin \"gopkg.in\/alecthomas\/kingpin.v2\"\n\n\t\"github.com\/ShowMax\/go-fqdn\"\n\t\"github.com\/go-kit\/kit\/log\"\n\t\"github.com\/go-kit\/kit\/log\/level\"\n\t\"github.com\/prometheus\/common\/promlog\"\n\t\"github.com\/prometheus\/common\/promlog\/flag\"\n\t\"github.com\/robustperception\/pushprox\/util\"\n)\n\nvar (\n\tmyFqdn = kingpin.Flag(\"fqdn\", \"FQDN to register with\").Default(fqdn.Get()).String()\n\tproxyURL = kingpin.Flag(\"proxy-url\", \"Push proxy to talk to.\").Required().String()\n)\n\ntype Coordinator struct {\n\tlogger log.Logger\n}\n\nfunc (c *Coordinator) doScrape(request *http.Request, client *http.Client) {\n\tlogger := log.With(c.logger, \"scrape_id\", request.Header.Get(\"id\"))\n\tctx, _ := context.WithTimeout(request.Context(), util.GetScrapeTimeout(request.Header))\n\trequest = request.WithContext(ctx)\n\t\/\/ We cannot handle https requests at the proxy, as we would only\n\t\/\/ see a CONNECT, so use a URL parameter to trigger it.\n\tparams := request.URL.Query()\n\tif params.Get(\"_scheme\") == \"https\" {\n\t\trequest.URL.Scheme = \"https\"\n\t\tparams.Del(\"_scheme\")\n\t\trequest.URL.RawQuery = params.Encode()\n\t}\n\n\tscrapeResp, err := client.Do(request)\n\tif err != nil {\n\t\tmsg := fmt.Sprintf(\"Failed to scrape %s: %s\", request.URL.String(), err)\n\t\tlevel.Warn(logger).Log(\"msg\", \"Failed to scrape\", \"Request URL\", request.URL.String(), \"err\", err)\n\t\tresp := &http.Response{\n\t\t\tStatusCode: 500,\n\t\t\tHeader: http.Header{},\n\t\t\tBody: ioutil.NopCloser(strings.NewReader(msg)),\n\t\t}\n\t\terr = c.doPush(resp, request, client)\n\t\tif err != nil {\n\t\t\tlevel.Warn(logger).Log(\"msg\", \"Failed to push failed scrape response:\", \"err\", err)\n\t\t\treturn\n\t\t}\n\t\tlevel.Info(logger).Log(\"msg\", \"Pushed failed scrape response\")\n\t\treturn\n\t}\n\tlevel.Info(logger).Log(\"msg\", \"Retrieved scrape response\")\n\terr = c.doPush(scrapeResp, request, client)\n\tif err != nil {\n\t\tlevel.Warn(logger).Log(\"msg\", \"Failed to push scrape response:\", \"err\", err)\n\t\treturn\n\t}\n\tlevel.Info(logger).Log(\"msg\", \"Pushed scrape result\")\n}\n\n\/\/ Report the result of the scrape back up to the proxy.\nfunc (c *Coordinator) doPush(resp *http.Response, origRequest *http.Request, client *http.Client) error {\n\tresp.Header.Set(\"id\", origRequest.Header.Get(\"id\")) \/\/ Link the request and response\n\t\/\/ Remaining scrape deadline.\n\tdeadline, _ := origRequest.Context().Deadline()\n\tresp.Header.Set(\"X-Prometheus-Scrape-Timeout\", fmt.Sprintf(\"%f\", float64(time.Until(deadline))\/1e9))\n\n\tbase, err := url.Parse(*proxyURL)\n\tif err != nil {\n\t\treturn err\n\t}\n\tu, err := url.Parse(\"\/push\")\n\tif err != nil {\n\t\treturn err\n\t}\n\turl := base.ResolveReference(u)\n\n\tbuf := &bytes.Buffer{}\n\tresp.Write(buf)\n\trequest := &http.Request{\n\t\tMethod: \"POST\",\n\t\tURL: url,\n\t\tBody: ioutil.NopCloser(buf),\n\t\tContentLength: int64(buf.Len()),\n\t}\n\trequest = request.WithContext(origRequest.Context())\n\t_, err = client.Do(request)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc loop(c Coordinator) {\n\tclient := &http.Client{}\n\tbase, err := url.Parse(*proxyURL)\n\tif err != nil {\n\t\tlevel.Error(c.logger).Log(\"msg\", \"Error parsing url:\", \"err\", err)\n\t\treturn\n\t}\n\tu, err := url.Parse(\"\/poll\")\n\tif err != nil {\n\t\tlevel.Error(c.logger).Log(\"msg\", \"Error parsing url:\", \"err\", err)\n\t\treturn\n\t}\n\turl := base.ResolveReference(u)\n\tresp, err := client.Post(url.String(), \"\", strings.NewReader(*myFqdn))\n\tif err != nil {\n\t\tlevel.Error(c.logger).Log(\"msg\", \"Error polling:\", \"err\", err)\n\t\ttime.Sleep(time.Second) \/\/ Don't pound the server. TODO: Randomised exponential backoff.\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\trequest, err := http.ReadRequest(bufio.NewReader(resp.Body))\n\tif err != nil {\n\t\tlevel.Error(c.logger).Log(\"msg\", \"Error reading request:\", \"err\", err)\n\t\treturn\n\t}\n\tlevel.Info(c.logger).Log(\"msg\", \"Got scrape request\", \"scrape_id\", request.Header.Get(\"id\"), \"url\", request.URL)\n\n\trequest.RequestURI = \"\"\n\n\tgo c.doScrape(request, client)\n}\n\nfunc main() {\n\tallowedLevel := promlog.AllowedLevel{}\n\tflag.AddFlags(kingpin.CommandLine, &allowedLevel)\n\tkingpin.HelpFlag.Short('h')\n\tkingpin.Parse()\n\tlogger := promlog.New(allowedLevel)\n\tcoordinator := Coordinator{logger: logger}\n\tif *proxyURL == \"\" {\n\t\tlevel.Error(coordinator.logger).Log(\"msg\", \"-proxy-url flag must be specified.\")\n\t\tos.Exit(1)\n\t}\n\tlevel.Info(coordinator.logger).Log(\"msg\", \"URL and FQDN info\", \"proxy_url\", *proxyURL, \"Using FQDN of\", *myFqdn)\n\tfor {\n\t\tloop(coordinator)\n\t}\n}\nsleep when error occuredpackage main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\tkingpin \"gopkg.in\/alecthomas\/kingpin.v2\"\n\n\t\"github.com\/ShowMax\/go-fqdn\"\n\t\"github.com\/go-kit\/kit\/log\"\n\t\"github.com\/go-kit\/kit\/log\/level\"\n\t\"github.com\/prometheus\/common\/promlog\"\n\t\"github.com\/prometheus\/common\/promlog\/flag\"\n\t\"github.com\/robustperception\/pushprox\/util\"\n)\n\nvar (\n\tmyFqdn = kingpin.Flag(\"fqdn\", \"FQDN to register with\").Default(fqdn.Get()).String()\n\tproxyURL = kingpin.Flag(\"proxy-url\", \"Push proxy to talk to.\").Required().String()\n)\n\ntype Coordinator struct {\n\tlogger log.Logger\n}\n\nfunc (c *Coordinator) doScrape(request *http.Request, client *http.Client) {\n\tlogger := log.With(c.logger, \"scrape_id\", request.Header.Get(\"id\"))\n\tctx, _ := context.WithTimeout(request.Context(), util.GetScrapeTimeout(request.Header))\n\trequest = request.WithContext(ctx)\n\t\/\/ We cannot handle https requests at the proxy, as we would only\n\t\/\/ see a CONNECT, so use a URL parameter to trigger it.\n\tparams := request.URL.Query()\n\tif params.Get(\"_scheme\") == \"https\" {\n\t\trequest.URL.Scheme = \"https\"\n\t\tparams.Del(\"_scheme\")\n\t\trequest.URL.RawQuery = params.Encode()\n\t}\n\n\tscrapeResp, err := client.Do(request)\n\tif err != nil {\n\t\tmsg := fmt.Sprintf(\"Failed to scrape %s: %s\", request.URL.String(), err)\n\t\tlevel.Warn(logger).Log(\"msg\", \"Failed to scrape\", \"Request URL\", request.URL.String(), \"err\", err)\n\t\tresp := &http.Response{\n\t\t\tStatusCode: 500,\n\t\t\tHeader: http.Header{},\n\t\t\tBody: ioutil.NopCloser(strings.NewReader(msg)),\n\t\t}\n\t\terr = c.doPush(resp, request, client)\n\t\tif err != nil {\n\t\t\tlevel.Warn(logger).Log(\"msg\", \"Failed to push failed scrape response:\", \"err\", err)\n\t\t\treturn\n\t\t}\n\t\tlevel.Info(logger).Log(\"msg\", \"Pushed failed scrape response\")\n\t\treturn\n\t}\n\tlevel.Info(logger).Log(\"msg\", \"Retrieved scrape response\")\n\terr = c.doPush(scrapeResp, request, client)\n\tif err != nil {\n\t\tlevel.Warn(logger).Log(\"msg\", \"Failed to push scrape response:\", \"err\", err)\n\t\treturn\n\t}\n\tlevel.Info(logger).Log(\"msg\", \"Pushed scrape result\")\n}\n\n\/\/ Report the result of the scrape back up to the proxy.\nfunc (c *Coordinator) doPush(resp *http.Response, origRequest *http.Request, client *http.Client) error {\n\tresp.Header.Set(\"id\", origRequest.Header.Get(\"id\")) \/\/ Link the request and response\n\t\/\/ Remaining scrape deadline.\n\tdeadline, _ := origRequest.Context().Deadline()\n\tresp.Header.Set(\"X-Prometheus-Scrape-Timeout\", fmt.Sprintf(\"%f\", float64(time.Until(deadline))\/1e9))\n\n\tbase, err := url.Parse(*proxyURL)\n\tif err != nil {\n\t\treturn err\n\t}\n\tu, err := url.Parse(\"\/push\")\n\tif err != nil {\n\t\treturn err\n\t}\n\turl := base.ResolveReference(u)\n\n\tbuf := &bytes.Buffer{}\n\tresp.Write(buf)\n\trequest := &http.Request{\n\t\tMethod: \"POST\",\n\t\tURL: url,\n\t\tBody: ioutil.NopCloser(buf),\n\t\tContentLength: int64(buf.Len()),\n\t}\n\trequest = request.WithContext(origRequest.Context())\n\t_, err = client.Do(request)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc loop(c Coordinator) error {\n\tclient := &http.Client{}\n\tbase, err := url.Parse(*proxyURL)\n\tif err != nil {\n\t\tlevel.Error(c.logger).Log(\"msg\", \"Error parsing url:\", \"err\", err)\n\t\treturn errors.New(\"error parsing url\")\n\t}\n\tu, err := url.Parse(\"\/poll\")\n\tif err != nil {\n\t\tlevel.Error(c.logger).Log(\"msg\", \"Error parsing url:\", \"err\", err)\n\t\treturn errors.New(\"error parsing url poll\")\n\t}\n\turl := base.ResolveReference(u)\n\tresp, err := client.Post(url.String(), \"\", strings.NewReader(*myFqdn))\n\tif err != nil {\n\t\tlevel.Error(c.logger).Log(\"msg\", \"Error polling:\", \"err\", err)\n\t\treturn errors.New(\"error polling\")\n\t}\n\tdefer resp.Body.Close()\n\trequest, err := http.ReadRequest(bufio.NewReader(resp.Body))\n\tif err != nil {\n\t\tlevel.Error(c.logger).Log(\"msg\", \"Error reading request:\", \"err\", err)\n\t\treturn errors.New(\"error reading request\")\n\t}\n\tlevel.Info(c.logger).Log(\"msg\", \"Got scrape request\", \"scrape_id\", request.Header.Get(\"id\"), \"url\", request.URL)\n\n\trequest.RequestURI = \"\"\n\n\tgo c.doScrape(request, client)\n\n\treturn nil\n}\n\nfunc main() {\n\tallowedLevel := promlog.AllowedLevel{}\n\tflag.AddFlags(kingpin.CommandLine, &allowedLevel)\n\tkingpin.HelpFlag.Short('h')\n\tkingpin.Parse()\n\tlogger := promlog.New(allowedLevel)\n\tcoordinator := Coordinator{logger: logger}\n\tif *proxyURL == \"\" {\n\t\tlevel.Error(coordinator.logger).Log(\"msg\", \"-proxy-url flag must be specified.\")\n\t\tos.Exit(1)\n\t}\n\tlevel.Info(coordinator.logger).Log(\"msg\", \"URL and FQDN info\", \"proxy_url\", *proxyURL, \"Using FQDN of\", *myFqdn)\n\tfor {\n\t\terr := loop(coordinator)\n\t\tif err != nil {\n\t\t\ttime.Sleep(time.Second) \/\/ Don't pound the server. TODO: Randomised exponential backoff.\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"package controller\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"time\"\n\n\tct \"github.com\/flynn\/flynn-controller\/types\"\n\t\"github.com\/flynn\/rpcplus\"\n)\n\nfunc New(uri string) (*Client, error) {\n\tu, err := url.Parse(uri)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Client{url: uri, addr: u.Host}, nil\n}\n\ntype Client struct {\n\turl string\n\taddr string\n}\n\nvar ErrNotFound = errors.New(\"controller: not found\")\n\nfunc (c *Client) send(method, path string, in, out interface{}) error {\n\tdata, err := json.Marshal(in)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq, err := http.NewRequest(method, c.url+path, bytes.NewBuffer(data))\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer res.Body.Close()\n\tif res.StatusCode != 200 {\n\t\treturn fmt.Errorf(\"controller: unexpected status %d\", res.StatusCode)\n\t}\n\tif out != nil {\n\t\treturn json.NewDecoder(res.Body).Decode(out)\n\t}\n\treturn nil\n}\n\nfunc (c *Client) put(path string, in, out interface{}) error {\n\treturn c.send(\"PUT\", path, in, out)\n}\n\nfunc (c *Client) post(path string, in, out interface{}) error {\n\treturn c.send(\"POST\", path, in, out)\n}\n\nfunc (c *Client) get(path string, out interface{}) error {\n\tres, err := http.Get(c.url + path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer res.Body.Close()\n\tif res.StatusCode != 200 {\n\t\tif res.StatusCode == 404 {\n\t\t\treturn ErrNotFound\n\t\t}\n\t\treturn fmt.Errorf(\"controller: unexpected status %d\", res.StatusCode)\n\t}\n\treturn json.NewDecoder(res.Body).Decode(out)\n}\n\nfunc (c *Client) StreamFormations(since *time.Time) (<-chan *ct.ExpandedFormation, *error) {\n\tif since == nil {\n\t\t*since = time.Unix(0, 0)\n\t}\n\t\/\/ TODO: handle TLS\n\tclient, err := rpcplus.DialHTTP(\"tcp\", c.addr)\n\tif err != nil {\n\t\treturn nil, &err\n\t}\n\tch := make(chan *ct.ExpandedFormation)\n\treturn ch, &client.StreamGo(\"Controller.StreamFormations\", since, ch).Error\n}\n\nfunc (c *Client) CreateArtifact(artifact *ct.Artifact) error {\n\treturn c.post(\"\/artifacts\", artifact, artifact)\n}\n\nfunc (c *Client) CreateRelease(release *ct.Release) error {\n\treturn c.post(\"\/releases\", release, release)\n}\n\nfunc (c *Client) SetAppRelease(appID, releaseID string) error {\n\treturn c.put(\"\/apps\/\"+appID+\"\/release\", &ct.Release{ID: releaseID}, nil)\n}\n\nfunc (c *Client) GetAppRelease(appID string) (*ct.Release, error) {\n\trelease := &ct.Release{}\n\treturn release, c.get(\"\/apps\/\"+appID+\"\/release\", release)\n}\ncontroller: Add more methods to clientpackage controller\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"time\"\n\n\tct \"github.com\/flynn\/flynn-controller\/types\"\n\t\"github.com\/flynn\/rpcplus\"\n)\n\nfunc New(uri string) (*Client, error) {\n\tu, err := url.Parse(uri)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Client{url: uri, addr: u.Host}, nil\n}\n\ntype Client struct {\n\turl string\n\taddr string\n}\n\nvar ErrNotFound = errors.New(\"controller: not found\")\n\nfunc (c *Client) send(method, path string, in, out interface{}) error {\n\tdata, err := json.Marshal(in)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq, err := http.NewRequest(method, c.url+path, bytes.NewBuffer(data))\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Set(\"Content-Type\", \"application\/json\")\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer res.Body.Close()\n\tif res.StatusCode != 200 {\n\t\treturn fmt.Errorf(\"controller: unexpected status %d\", res.StatusCode)\n\t}\n\tif out != nil {\n\t\treturn json.NewDecoder(res.Body).Decode(out)\n\t}\n\treturn nil\n}\n\nfunc (c *Client) put(path string, in, out interface{}) error {\n\treturn c.send(\"PUT\", path, in, out)\n}\n\nfunc (c *Client) post(path string, in, out interface{}) error {\n\treturn c.send(\"POST\", path, in, out)\n}\n\nfunc (c *Client) get(path string, out interface{}) error {\n\tres, err := http.Get(c.url + path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer res.Body.Close()\n\tif res.StatusCode != 200 {\n\t\tif res.StatusCode == 404 {\n\t\t\treturn ErrNotFound\n\t\t}\n\t\treturn fmt.Errorf(\"controller: unexpected status %d\", res.StatusCode)\n\t}\n\treturn json.NewDecoder(res.Body).Decode(out)\n}\n\nfunc (c *Client) StreamFormations(since *time.Time) (<-chan *ct.ExpandedFormation, *error) {\n\tif since == nil {\n\t\t*since = time.Unix(0, 0)\n\t}\n\t\/\/ TODO: handle TLS\n\tclient, err := rpcplus.DialHTTP(\"tcp\", c.addr)\n\tif err != nil {\n\t\treturn nil, &err\n\t}\n\tch := make(chan *ct.ExpandedFormation)\n\treturn ch, &client.StreamGo(\"Controller.StreamFormations\", since, ch).Error\n}\n\nfunc (c *Client) CreateArtifact(artifact *ct.Artifact) error {\n\treturn c.post(\"\/artifacts\", artifact, artifact)\n}\n\nfunc (c *Client) CreateRelease(release *ct.Release) error {\n\treturn c.post(\"\/releases\", release, release)\n}\n\nfunc (c *Client) CreateApp(app *ct.App) error {\n\treturn c.post(\"\/apps\", app, app)\n}\n\nfunc (c *Client) CreateProvider(provider *ct.App) error {\n\treturn c.post(\"\/providers\", provider, provider)\n}\n\nfunc (c *Client) PutResource(resource *ct.Resource) error {\n\tif resource.ID == \"\" || resource.ProviderID == \"\" {\n\t\treturn errors.New(\"controller: missing id and\/or provider id\")\n\t}\n\treturn c.put(fmt.Sprintf(\"\/providers\/%s\/resources\/%s\", resource.ProviderID, resource.ID), resource, resource)\n}\n\nfunc (c *Client) PutFormation(formation *ct.Formation) error {\n\tif formation.AppID == \"\" || formation.ReleaseID == \"\" {\n\t\treturn errors.New(\"controller missing app id and\/or release id\")\n\t}\n\treturn c.put(fmt.Sprintf(\"\/apps\/%s\/formations\/%s\", formation.AppID, formation.ReleaseID), formation, formation)\n}\n\nfunc (c *Client) SetAppRelease(appID, releaseID string) error {\n\treturn c.put(\"\/apps\/\"+appID+\"\/release\", &ct.Release{ID: releaseID}, nil)\n}\n\nfunc (c *Client) GetAppRelease(appID string) (*ct.Release, error) {\n\trelease := &ct.Release{}\n\treturn release, c.get(\"\/apps\/\"+appID+\"\/release\", release)\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/golang\/glog\"\n\t\"github.com\/heidi-ann\/hydra\/config\"\n\t\"github.com\/heidi-ann\/hydra\/store\"\n\t\"io\"\n\t\"net\"\n\t\"os\"\n\t\"time\"\n)\n\nvar config_file = flag.String(\"config\", \"exampleconfig\", \"Client configuration file\")\nvar auto = flag.Int(\"auto\", -1, \"If workload is automatically generated, percentage of reads\")\n\nfunc connect(addrs []string, tries int) (net.Conn, error) {\n\tvar conn net.Conn\n\tvar err error\n\n\tfor i := range addrs {\n\t\tfor t := tries; t > 0; t-- {\n\t\t\tconn, err = net.Dial(\"tcp\", addrs[i])\n\n\t\t\t\/\/ if successful\n\t\t\tif err == nil {\n\t\t\t\tglog.Infof(\"Connected to %s\", addrs[i])\n\t\t\t\treturn conn, err\n\t\t\t}\n\n\t\t\t\/\/if unsuccessful\n\t\t\tglog.Warning(err)\n\t\t\ttime.Sleep(2 * time.Second)\n\t\t}\n\t}\n\n\treturn conn, err\n}\n\nfunc main() {\n\t\/\/ set up logging\n\tflag.Parse()\n\tdefer glog.Flush()\n\n\t\/\/ parse config file\n\tconf := config.Parse(*config_file)\n\n\t\/\/ connecting to server\n\tconn, err := connect(conf.Addresses.Address, 3)\n\tif err != nil {\n\t\tglog.Fatal(err)\n\t}\n\n\t\/\/ mian mian\n\tterm_reader := bufio.NewReader(os.Stdin)\n\tnet_reader := bufio.NewReader(conn)\n\tgen := store.Generate(*auto, 50)\n\n\tfor {\n\t\ttext := \"\"\n\n\t\tif *auto == -1 {\n\t\t\t\/\/ reading from terminal\n\t\t\tfmt.Print(\"Enter command: \")\n\t\t\ttext, err = term_reader.ReadString('\\n')\n\t\t\tif err != nil {\n\t\t\t\tglog.Fatal(err)\n\t\t\t}\n\t\t\tglog.Info(\"User entered\", text)\n\t\t} else {\n\t\t\t\/\/ use generator\n\t\t\ttext = gen.Next()\n\t\t\tglog.Info(\"Generator produced \", text)\n\t\t}\n\n\t\t\/\/ send to server\n\t\t_, err = conn.Write([]byte(text))\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tglog.Warning(err)\n\t\t\t\/\/ reconnecting to server\n\t\t\tconn, err = connect(conf.Addresses.Address, 3)\n\t\t\tif err != nil {\n\t\t\t\tglog.Fatal(err)\n\t\t\t}\n\t\t}\n\n\t\tglog.Info(\"Sent \", text)\n\n\t\t\/\/ read response\n\t\treply, err := net_reader.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tglog.Warning(err)\n\t\t\t\/\/ reconnecting to server\n\t\t\tconn, err = connect(conf.Addresses.Address, 3)\n\t\t\tif err != nil {\n\t\t\t\tglog.Fatal(err)\n\t\t\t}\n\t\t}\n\n\t\t\/\/ write to user\n\t\tfmt.Print(reply)\n\n\t}\n\n}\nadding persistent storepackage main\n\nimport (\n\t\"bufio\"\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/golang\/glog\"\n\t\"github.com\/heidi-ann\/hydra\/config\"\n\t\"github.com\/heidi-ann\/hydra\/store\"\n\t\"io\"\n\t\"net\"\n\t\"os\"\n\t\"time\"\n)\n\nvar config_file = flag.String(\"config\", \"exampleconfig\", \"Client configuration file\")\nvar auto = flag.Int(\"auto\", -1, \"If workload is automatically generated, percentage of reads\")\n\nfunc connect(addrs []string, tries int) (net.Conn, error) {\n\tvar conn net.Conn\n\tvar err error\n\n\tfor i := range addrs {\n\t\tfor t := tries; t > 0; t-- {\n\t\t\tconn, err = net.Dial(\"tcp\", addrs[i])\n\n\t\t\t\/\/ if successful\n\t\t\tif err == nil {\n\t\t\t\tglog.Infof(\"Connected to %s\", addrs[i])\n\t\t\t\treturn conn, err\n\t\t\t}\n\n\t\t\t\/\/if unsuccessful\n\t\t\tglog.Warning(err)\n\t\t\ttime.Sleep(2 * time.Second)\n\t\t}\n\t}\n\n\treturn conn, err\n}\n\nfunc main() {\n\t\/\/ set up logging\n\tflag.Parse()\n\tdefer glog.Flush()\n\n\t\/\/ parse config file\n\tconf := config.Parse(*config_file)\n\n\t\/\/ connecting to server\n\tconn, err := connect(conf.Addresses.Address, 3)\n\tif err != nil {\n\t\tglog.Fatal(err)\n\t}\n\n\t\/\/ mian mian\n\tterm_reader := bufio.NewReader(os.Stdin)\n\tnet_reader := bufio.NewReader(conn)\n\tgen := store.Generate(*auto, 50)\n\n\tfor {\n\t\ttext := \"\"\n\n\t\tif *auto == -1 {\n\t\t\t\/\/ reading from terminal\n\t\t\tfmt.Print(\"Enter command: \")\n\t\t\ttext, err = term_reader.ReadString('\\n')\n\t\t\tif err != nil {\n\t\t\t\tglog.Fatal(err)\n\t\t\t}\n\t\t\tglog.Info(\"User entered\", text)\n\t\t} else {\n\t\t\t\/\/ use generator\n\t\t\ttext = gen.Next()\n\t\t\tglog.Info(\"Generator produced \", text)\n\t\t}\n\n\t\t\/\/ send to server\n\t\tstartTime := time.Now()\n\t\t_, err = conn.Write([]byte(text))\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tglog.Warning(err)\n\t\t\t\/\/ reconnecting to server\n\t\t\tconn, err = connect(conf.Addresses.Address, 3)\n\t\t\tif err != nil {\n\t\t\t\tglog.Fatal(err)\n\t\t\t}\n\t\t}\n\n\t\tglog.Info(\"Sent \", text)\n\n\t\t\/\/ read response\n\t\treply, err := net_reader.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tglog.Warning(err)\n\t\t\t\/\/ reconnecting to server\n\t\t\tconn, err = connect(conf.Addresses.Address, 3)\n\t\t\tif err != nil {\n\t\t\t\tglog.Fatal(err)\n\t\t\t}\n\t\t}\n\n\t\t\/\/ write to user\n\t\tfmt.Print(reply, \"request took\", time.Since(startTime))\n\n\t}\n\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/koding\/kite\"\n\t\"os\"\n)\n\nfunc main() {\n\tk := kite.New(\"client\", \"1.0.0\")\n k.Config.DisableAuthentication = true\n\n\tfmt.Println(k.Config)\n\n\tclient := k.NewClient(\"http:\/\/\" + or.Getenv(\"SQUARE_SERVICE_HOST\") + \":\" + or.Getenv(\"SQUARE_SERVICE_PORT\") + \"\/kite\")\n\tconnected, err := client.Dial()\n\tif err != nil {\n\t\tk.Log.Fatal(err.Error())\n\t}\n\n\t\/\/ Wait until connected\n\t<-connected\n\t\n\tresponse, err := client.Tell(\"square\", 4)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(response.MustFloat64())\n}\nadded env variables to find square servicepackage main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/koding\/kite\"\n\t\"os\"\n)\n\nfunc main() {\n\tk := kite.New(\"client\", \"1.0.0\")\n k.Config.DisableAuthentication = true\n\n\tfmt.Println(k.Config)\n\n\tclient := k.NewClient(\"http:\/\/\" + os.Getenv(\"SQUARE_SERVICE_HOST\") + \":\" + os.Getenv(\"SQUARE_SERVICE_PORT\") + \"\/kite\")\n\tconnected, err := client.Dial()\n\tif err != nil {\n\t\tk.Log.Fatal(err.Error())\n\t}\n\n\t\/\/ Wait until connected\n\t<-connected\n\t\n\tresponse, err := client.Tell(\"square\", 4)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(response.MustFloat64())\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/emsihyo\/go.im\/comps\/se\"\n\t\"github.com\/sirupsen\/logrus\"\n\n\tuuid \"github.com\/satori\/go.uuid\"\n\n\t\"github.com\/emsihyo\/go.im\/comps\/bi\"\n\t\"github.com\/emsihyo\/go.im\/comps\/pr\"\n)\n\n\/\/Client Client\ntype Client struct {\n\tb *bi.BI\n\tsess bi.Session\n\taddr string\n\tid string\n\tplatform string\n\tpassword string\n\tisConnected bool\n\tisLogged bool\n\ttopics map[string]string\n\tsids map[string]int64\n\tmut sync.RWMutex\n}\n\n\/\/NewClient NewClient\nfunc NewClient(addr string, id string, platform string) *Client {\n\tb := bi.NewBI()\n\tcli := Client{b: b, addr: addr, id: id, platform: platform, topics: map[string]string{}, sids: map[string]int64{}}\n\tcli.b.On(pr.Type_Send.String(), func(sess bi.Session, req *pr.EmitSend) {\n\t\t\/\/ cli.mut.Lock()\n\t\t\/\/ defer cli.mut.Unlock()\n\t\t\/\/ sid := req.GetMessage().GetSID()\n\t\t\/\/ id := req.GetMessage().GetTo().GetID()\n\t\t\/\/ if sid > cli.sids[id] {\n\t\t\/\/ \tcli.sids[id] = sid\n\t\tlogrus.Debug(\"[REV]\", req.GetMessage().GetTo().GetID(), req.GetMessage().GetFrom().GetID(), req.GetMessage().GetBody())\n\t\t\/\/ }\n\t})\n\treturn &cli\n}\n\nfunc (cli *Client) preproccess() {\n\tfor {\n\t\tif false == cli.isConnected {\n\t\t\tif err := cli.connect(); nil != err {\n\t\t\t\t<-time.After(time.Second * 3)\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\tcli.isConnected = true\n\t\t\t}\n\t\t}\n\t\tif false == cli.isLogged {\n\t\t\tif err := cli.login(); nil != err {\n\t\t\t\t<-time.After(time.Second * 3)\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\tcli.isLogged = true\n\t\t\t\tfor _, topicID := range cli.topics {\n\t\t\t\t\tif _, err := cli.subscribe(topicID); nil != err {\n\t\t\t\t\t\tcli.reset()\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (cli *Client) connect() error {\n\ta, err := net.ResolveTCPAddr(\"tcp\", cli.addr)\n\tif nil != err {\n\t\tlogrus.Debug(\"[CONNECT]\", cli.id, err)\n\t\treturn err\n\t}\n\tc, err := net.DialTCP(\"tcp\", nil, a)\n\tif nil != err {\n\t\tlogrus.Debug(\"[CONNECT]\", cli.id, err)\n\t\treturn err\n\t}\n\tconn := bi.NewTCPConn(c)\n\tsess := se.NewSession(conn, &bi.ProtobufProtocol{}, time.Hour)\n\tcli.sess = sess\n\tgo cli.b.Handle(sess)\n\treturn nil\n}\n\nfunc (cli *Client) login() error {\n\tresp := pr.RespLogin{}\n\terr := cli.sess.GetSessionImpl().Request(pr.Type_Login.String(), &pr.ReqLogin{UserID: cli.id, Password: cli.password, Platform: cli.platform}, &resp, time.Hour)\n\tif nil != err {\n\t\tlogrus.Debug(\"[LOGIN]\", cli.id, err)\n\t\treturn err\n\t}\n\tif 0 != resp.Code {\n\t\terr = fmt.Errorf(\"code:%d, desc:%s\", resp.Code, resp.Desc)\n\t\tlogrus.Debug(\"[LOGIN]\", cli.id, err)\n\t\treturn err\n\t}\n\tlogrus.Debug(\"[LOGIN]\", cli.id)\n\treturn nil\n}\n\n\/\/Subscribe Subscribe\nfunc (cli *Client) Subscribe(topicID string) {\n\tcli.mut.Lock()\n\tdefer cli.mut.Unlock()\n\tfor {\n\t\tcli.preproccess()\n\t\t_, err := cli.subscribe(topicID)\n\t\tif nil != err {\n\t\t\tcli.reset()\n\t\t} else {\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/Unsubscribe Unsubscribe\n\/\/ func (cli *Client) Unsubscribe(topicID string) {\n\/\/ \tcli.mut.Lock()\n\/\/ \tdefer cli.mut.Unlock()\n\/\/ \tfor {\n\/\/ \t\tcli.preproccess()\n\/\/ \t\terr := cli.unsubscribe(topicID)\n\/\/ \t\tif nil != err {\n\/\/ \t\t\tlogrus.Debug(\"[UNSUBSCRIBE]\", err)\n\/\/ \t\t\tcli.reset()\n\/\/ \t\t} else {\n\/\/ \t\t\treturn\n\/\/ \t\t}\n\/\/ \t}\n\/\/ }\n\n\/\/Publish Publish\nfunc (cli *Client) Publish(topicID string, body string) {\n\tcli.mut.Lock()\n\tdefer cli.mut.Unlock()\n\tfor {\n\t\tcli.preproccess()\n\t\terr := cli.publish(topicID, body)\n\t\tif nil != err {\n\t\t\tcli.reset()\n\t\t} else {\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/Ping Ping\nfunc (cli *Client) Ping() int64 {\n\tcli.mut.Lock()\n\tdefer cli.mut.Unlock()\n\tfor {\n\t\tcli.preproccess()\n\t\tdelay, err := cli.ping()\n\t\tif nil != err {\n\t\t\tcli.reset()\n\t\t} else {\n\t\t\treturn delay\n\t\t}\n\t}\n}\n\nfunc (cli *Client) subscribe(topicID string) ([]*pr.Message, error) {\n\tif _, ok := cli.topics[topicID]; ok {\n\t\treturn nil, nil\n\t}\n\tsid := cli.sids[topicID]\n\tresp := pr.RespSubscribe{}\n\terr := cli.sess.GetSessionImpl().Request(pr.Type_Subscribe.String(), &pr.ReqSubscribe{TopicID: topicID, MinSID: sid, MaxCount: 20}, &resp, time.Hour)\n\tif nil != err {\n\t\tlogrus.Debug(\"[SUBSCRIBE]\", cli.id, topicID, err)\n\t\treturn nil, err\n\t}\n\tif 0 != resp.Code {\n\t\terr = fmt.Errorf(\"code:%d, desc:%s\", resp.Code, resp.Desc)\n\t\tlogrus.Debug(\"[SUBSCRIBE]\", cli.id, topicID, err)\n\t\treturn nil, err\n\t}\n\tcli.topics[topicID] = topicID\n\tif 0 != len(resp.Histories) {\n\t\tcli.sids[topicID] = resp.Histories[len(resp.Histories)-1].GetSID()\n\t}\n\tlogrus.Debug(\"[SUBSCRIBE]\", cli.id, topicID)\n\treturn resp.Histories, nil\n}\n\n\/\/ func (cli *Client) unsubscribe(topicID string) error {\n\/\/ \tif _, ok := cli.topics[topicID]; !ok {\n\/\/ \t\treturn nil\n\/\/ \t}\n\/\/ \tresp := pr.RespUnsubscribe{}\n\/\/ \terr := cli.sess.Request(int32(pr.Type_Unsubscribe), &pr.ReqUnsubscribe{TopicID: topicID}, &resp, time.Hour)\n\/\/ \tif nil != err {\n\/\/ \t\treturn err\n\/\/ \t}\n\/\/ \tif 0 != resp.Code {\n\/\/ \t\treturn fmt.Errorf(\"code:%d, desc:%s\", resp.Code, resp.Desc)\n\/\/ \t}\n\/\/ \tdelete(cli.topics, topicID)\n\/\/ \treturn nil\n\/\/ }\n\nfunc (cli *Client) publish(topicID string, body string) error {\n\tmessage := pr.Message{CID: uuid.NewV3(uuid.NewV4(), topicID+\"|\"+cli.id).String(), To: &pr.Topic{ID: topicID}, Body: body, From: &pr.Consumer{ID: cli.id}}\n\tresp := pr.RespDeliver{}\n\terr := cli.sess.GetSessionImpl().Request(pr.Type_Deliver.String(), &pr.ReqDeliver{Message: &message}, &resp, time.Hour)\n\tif nil != err {\n\t\tlogrus.Debug(\"[PUBLISH]\", cli.id, topicID, body, err)\n\t\treturn err\n\t}\n\tif 0 != resp.Code {\n\t\terr = fmt.Errorf(\"code:%d, desc:%s\", resp.Code, resp.Desc)\n\t\tlogrus.Debug(\"[PUBLISH]\", cli.id, topicID, body, err)\n\t\treturn err\n\t}\n\tlogrus.Debug(\"[PUBLISH]\", cli.id, topicID, body)\n\treturn nil\n}\n\nfunc (cli *Client) ping() (int64, error) {\n\tresp := pr.RespPing{}\n\tnow := time.Now().UnixNano()\n\terr := cli.sess.GetSessionImpl().Request(pr.Type_Ping.String(), &pr.ReqPing{}, &resp, time.Hour)\n\tif nil != err {\n\t\tlogrus.Debug(\"[PING]\", cli.id, err)\n\t\treturn 0, err\n\t}\n\t\/\/ delay := (time.Now().UnixNano() - now) \/ time.Millisecond.Nanoseconds()\n\tdelay := (time.Now().UnixNano() - now)\n\tlogrus.Debug(\"[PING]\", cli.id, delay)\n\treturn delay, nil\n}\n\n\/\/RandomTopic RandomTopic\nfunc (cli *Client) RandomTopic() string {\n\tcli.mut.Lock()\n\tdefer cli.mut.Unlock()\n\tvar topic string\n\tfor _, r := range cli.topics {\n\t\tif strings.EqualFold(r, cli.id) {\n\t\t\tcontinue\n\t\t}\n\t\ttopic = r\n\t\tbreak\n\t}\n\treturn topic\n}\n\n\/\/TopicCount TopicCount\nfunc (cli *Client) TopicCount() int {\n\tcli.mut.Lock()\n\tdefer cli.mut.Unlock()\n\treturn len(cli.topics)\n}\n\nfunc (cli *Client) reset() {\n\tcli.isConnected = false\n\tcli.isLogged = false\n\tcli.sess = nil\n}\nno messagepackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/emsihyo\/go.im\/comps\/se\"\n\t\"github.com\/sirupsen\/logrus\"\n\n\tuuid \"github.com\/satori\/go.uuid\"\n\n\t\"github.com\/emsihyo\/go.im\/comps\/bi\"\n\t\"github.com\/emsihyo\/go.im\/comps\/pr\"\n)\n\n\/\/Client Client\ntype Client struct {\n\tb *bi.BI\n\tsess bi.Session\n\taddr string\n\tid string\n\tplatform string\n\tpassword string\n\tisConnected bool\n\tisLogged bool\n\ttopics map[string]string\n\tsids map[string]int64\n\tmut sync.RWMutex\n}\n\n\/\/NewClient NewClient\nfunc NewClient(addr string, id string, platform string) *Client {\n\tb := bi.NewBI()\n\tcli := Client{b: b, addr: addr, id: id, platform: platform, topics: map[string]string{}, sids: map[string]int64{}}\n\tcli.b.On(pr.Type_Send.String(), func(sess bi.Session, req *pr.EmitSend) {\n\t\t\/\/ cli.mut.Lock()\n\t\t\/\/ defer cli.mut.Unlock()\n\t\t\/\/ sid := req.GetMessage().GetSID()\n\t\t\/\/ id := req.GetMessage().GetTo().GetID()\n\t\t\/\/ if sid > cli.sids[id] {\n\t\t\/\/ \tcli.sids[id] = sid\n\t\t\/\/ logrus.Debug(\"[REV]\", req.GetMessage().GetTo().GetID(), req.GetMessage().GetFrom().GetID(), req.GetMessage().GetBody())\n\t\t\/\/ }\n\t})\n\treturn &cli\n}\n\nfunc (cli *Client) preproccess() {\n\tfor {\n\t\tif false == cli.isConnected {\n\t\t\tif err := cli.connect(); nil != err {\n\t\t\t\tlog.Print(err)\n\t\t\t\t<-time.After(time.Second * 3)\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\tcli.isConnected = true\n\t\t\t}\n\t\t}\n\t\tif false == cli.isLogged {\n\t\t\tif err := cli.login(); nil != err {\n\t\t\t\tlog.Print(err)\n\t\t\t\t<-time.After(time.Second * 3)\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\tcli.isLogged = true\n\t\t\t\tfor _, topicID := range cli.topics {\n\t\t\t\t\tif _, err := cli.subscribe(topicID); nil != err {\n\t\t\t\t\t\tlog.Print(err)\n\t\t\t\t\t\tcli.reset()\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\t<-time.After(time.Millisecond * 10)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t} else {\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (cli *Client) connect() error {\n\ta, err := net.ResolveTCPAddr(\"tcp\", cli.addr)\n\tif nil != err {\n\t\tlog.Print(err)\n\t\treturn err\n\t}\n\tc, err := net.DialTCP(\"tcp\", nil, a)\n\tif nil != err {\n\t\tlog.Print(err)\n\t\treturn err\n\t}\n\tconn := bi.NewTCPConn(c)\n\tsess := se.NewSession(conn, &bi.ProtobufProtocol{}, time.Hour)\n\tcli.sess = sess\n\tgo cli.b.Handle(sess)\n\treturn nil\n}\n\nfunc (cli *Client) login() error {\n\tresp := pr.RespLogin{}\n\terr := cli.sess.GetSessionImpl().Request(pr.Type_Login.String(), &pr.ReqLogin{UserID: cli.id, Password: cli.password, Platform: cli.platform}, &resp, time.Hour)\n\tif nil != err {\n\t\tlog.Print(err)\n\t\treturn err\n\t}\n\tif 0 != resp.Code {\n\t\terr = fmt.Errorf(\"code:%d, desc:%s\", resp.Code, resp.Desc)\n\t\tlog.Print(err)\n\t\treturn err\n\t}\n\treturn nil\n}\n\n\/\/Subscribe Subscribe\nfunc (cli *Client) Subscribe(topicID string) {\n\tcli.mut.Lock()\n\tdefer cli.mut.Unlock()\n\tfor {\n\t\tcli.preproccess()\n\t\t_, err := cli.subscribe(topicID)\n\t\tif nil != err {\n\t\t\tcli.reset()\n\t\t} else {\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/Unsubscribe Unsubscribe\nfunc (cli *Client) Unsubscribe(topicID string) {\n\tcli.mut.Lock()\n\tdefer cli.mut.Unlock()\n\tfor {\n\t\tcli.preproccess()\n\t\terr := cli.unsubscribe(topicID)\n\t\tif nil != err {\n\t\t\tlogrus.Debug(\"[UNSUBSCRIBE]\", err)\n\t\t\tcli.reset()\n\t\t} else {\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/Publish Publish\nfunc (cli *Client) Publish(topicID string, body string) {\n\tcli.mut.Lock()\n\tdefer cli.mut.Unlock()\n\tfor {\n\t\tcli.preproccess()\n\t\terr := cli.publish(topicID, body)\n\t\tif nil != err {\n\t\t\tcli.reset()\n\t\t} else {\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\/\/Ping Ping\nfunc (cli *Client) Ping() int64 {\n\tcli.mut.Lock()\n\tdefer cli.mut.Unlock()\n\tfor {\n\t\tcli.preproccess()\n\t\tdelay, err := cli.ping()\n\t\tif nil != err {\n\t\t\tcli.reset()\n\t\t} else {\n\t\t\treturn delay\n\t\t}\n\t}\n}\n\nfunc (cli *Client) subscribe(topicID string) ([]*pr.Message, error) {\n\tif _, ok := cli.topics[topicID]; ok {\n\t\treturn nil, nil\n\t}\n\tsid := cli.sids[topicID]\n\tresp := pr.RespSubscribe{}\n\terr := cli.sess.GetSessionImpl().Request(pr.Type_Subscribe.String(), &pr.ReqSubscribe{TopicID: topicID, MinSID: sid, MaxCount: 20}, &resp, time.Hour)\n\tif nil != err {\n\t\tlog.Print(err)\n\t\treturn nil, err\n\t}\n\tif 0 != resp.Code {\n\t\terr = fmt.Errorf(\"code:%d, desc:%s\", resp.Code, resp.Desc)\n\t\tlog.Print(err)\n\t\treturn nil, err\n\t}\n\tcli.topics[topicID] = topicID\n\tif 0 != len(resp.Histories) {\n\t\tcli.sids[topicID] = resp.Histories[len(resp.Histories)-1].GetSID()\n\t}\n\treturn resp.Histories, nil\n}\n\nfunc (cli *Client) unsubscribe(topicID string) error {\n\tif _, ok := cli.topics[topicID]; !ok {\n\t\treturn nil\n\t}\n\tresp := pr.RespUnsubscribe{}\n\terr := cli.sess.GetSessionImpl().Request(pr.Type_Unsubscribe.String(), &pr.ReqUnsubscribe{TopicID: topicID}, &resp, time.Hour)\n\tif nil != err {\n\t\tlog.Print(err)\n\t\treturn err\n\t}\n\tif 0 != resp.Code {\n\t\terr := fmt.Errorf(\"code:%d, desc:%s\", resp.Code, resp.Desc)\n\t\tlog.Print(err)\n\t\treturn err\n\t}\n\tdelete(cli.topics, topicID)\n\treturn nil\n}\n\nfunc (cli *Client) publish(topicID string, body string) error {\n\tmessage := pr.Message{CID: uuid.NewV3(uuid.NewV4(), topicID+\"|\"+cli.id).String(), To: &pr.Topic{ID: topicID}, Body: body, From: &pr.Consumer{ID: cli.id}}\n\tresp := pr.RespDeliver{}\n\terr := cli.sess.GetSessionImpl().Request(pr.Type_Deliver.String(), &pr.ReqDeliver{Message: &message}, &resp, time.Hour)\n\tif nil != err {\n\t\tlog.Print(err)\n\t\treturn err\n\t}\n\tif 0 != resp.Code {\n\t\terr = fmt.Errorf(\"code:%d, desc:%s\", resp.Code, resp.Desc)\n\t\tlog.Print(err)\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (cli *Client) ping() (int64, error) {\n\tresp := pr.RespPing{}\n\tnow := time.Now().UnixNano()\n\terr := cli.sess.GetSessionImpl().Request(pr.Type_Ping.String(), &pr.ReqPing{}, &resp, time.Hour)\n\tif nil != err {\n\t\tlog.Print(err)\n\t\treturn 0, err\n\t}\n\tdelay := (time.Now().UnixNano() - now) \/ int64(time.Millisecond)\n\treturn delay, nil\n}\n\n\/\/RandomTopic RandomTopic\nfunc (cli *Client) RandomTopic() string {\n\tcli.mut.Lock()\n\tdefer cli.mut.Unlock()\n\tvar topic string\n\tfor _, r := range cli.topics {\n\t\tif strings.EqualFold(r, cli.id) {\n\t\t\tcontinue\n\t\t}\n\t\ttopic = r\n\t\tbreak\n\t}\n\treturn topic\n}\n\n\/\/TopicCount TopicCount\nfunc (cli *Client) TopicCount() int {\n\tcli.mut.Lock()\n\tdefer cli.mut.Unlock()\n\treturn len(cli.topics)\n}\n\nfunc (cli *Client) reset() {\n\tcli.isConnected = false\n\tcli.isLogged = false\n\tcli.sess = nil\n}\n<|endoftext|>"} {"text":"package main\n\nimport \"github.com\/guregu\/bbs\"\nimport \"net\/http\"\nimport \"encoding\/json\"\nimport \"fmt\"\nimport \"io\/ioutil\"\nimport \"bytes\"\nimport \"strings\"\nimport \"bufio\"\nimport \"os\"\nimport \"strconv\"\n\nvar bbsServer = \"http:\/\/localhost:8080\/bbs\"\nvar session = \"\"\nvar lastLine = \"\"\nvar verbose = true\nvar nextNext *next\n\nconst client_version string = \"test-client 0.1\" \/\/TODO: use this in User-Agent\n\ntype next struct {\n\tid string\n\ttoken string\n}\n\nfunc main() {\n\ttestClient()\n}\n\nfunc testClient() {\n\tif len(os.Args) > 1 {\n\t\tbbsServer = os.Args[1]\n\t}\n\n\tfmt.Println(\"Running test client: \" + client_version)\n\tfmt.Printf(\"Connecting to %s...\\n\", bbsServer)\n\thello, _ := json.Marshal(&bbs.BBSCommand{\"hello\"})\n\tsend(hello)\n\n\tr := bufio.NewReader(os.Stdin)\n\tfmt.Println(\"Type help for a list of commands or quit to exit.\")\n\tfmt.Print(\"> \")\n\tfor {\n\t\tline, err := r.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tinput(line)\n\t\tfmt.Print(\"> \")\n\t}\n}\n\nfunc input(line string) {\n\tfields := strings.Fields(line)\n\tif len(fields) == 0 {\n\t\treturn\n\t}\n\n\tswitch fields[0] {\n\tcase \".\":\n\t\tinput(lastLine)\n\tcase \"help\":\n\t\tfmt.Println(\"COMMANDS\\n\\tlogin username password\\n\\tnigol password username\\n\\tget topicID [filterID]\\n\\tboards\\n\\tlist [expression]\\n\\treply [topicID] [text]\\n\\tquit\\n\\thelp\\n\\t. (repeat last command)\")\n\tcase \"quit\":\n\t\tos.Exit(0)\n\tcase \"exit\":\n\t\tos.Exit(0)\n\tcase \"register\":\n\t\tif len(fields) == 3 {\n\t\t\tdoRegister(fields[1], fields[2])\n\t\t} else {\n\t\t\tfmt.Println(\"Input error.\")\n\t\t\tfmt.Println(\"usage: register username password\")\n\t\t}\n\tcase \"login\":\n\t\targs := strings.SplitN(line, \" \", 3)\n\t\tif strings.Contains(args[2], \" \") {\n\t\t\tfmt.Println(\"WARNING: If you have spaces in your username, you should use 'nigol' instead.\")\n\t\t}\n\t\tif len(fields) != 3 {\n\t\t\tfmt.Println(\"Input error.\")\n\t\t\tfmt.Println(\"usage: login username password\")\n\t\t}\n\t\tdoLogin(fields[1], fields[2])\n\t\tlastLine = line\n\tcase \"nigol\":\n\t\targs := strings.SplitN(line, \" \", 3)\n\t\tif strings.Contains(args[2], \" \") {\n\t\t\tfmt.Println(\"WARNING: If you have spaces in your password, you should use 'login' instead. If you have spaces in both, you're SOL.\")\n\t\t}\n\t\tif len(fields) != 3 {\n\t\t\tfmt.Println(\"Input error.\")\n\t\t\tfmt.Println(\"usage: nigol password username\")\n\t\t}\n\t\tdoLogin(fields[2], fields[1])\n\t\tlastLine = line\n\tcase \"get\":\n\t\tif len(fields) == 2 {\n\t\t\tdoGet(fields[1], &bbs.Range{1, 50}, \"\")\n\t\t} else if len(fields) == 4 {\n\t\t\tlwr, _ := strconv.Atoi(fields[2])\n\t\t\thrr, _ := strconv.Atoi(fields[3])\n\t\t\tdoGet(fields[1], &bbs.Range{lwr, hrr}, \"\")\n\t\t} else {\n\t\t\tfmt.Println(\"Input error.\")\n\t\t\tfmt.Println(\"usage: get topicID [lower upper filter]\")\n\t\t\tfmt.Println(\"usage: get board topicID\")\n\t\t}\n\t\tlastLine = line\n\tcase \"list\":\n\t\tif len(fields) == 1 {\n\t\t\tdoList(\"\")\n\t\t} else if len(fields) == 2 {\n\t\t\tdoList(fields[1])\n\t\t} else {\n\t\t\tfmt.Println(\"Input error.\")\n\t\t\tfmt.Println(\"usage: list [expression]\")\n\t\t}\n\t\tlastLine = line\n\tcase \"boards\":\n\t\tdoListBoards()\n\t\tlastLine = line\n\tcase \"reply\":\n\t\targs := strings.SplitN(line, \" \", 3)\n\t\tif len(args) < 3 {\n\t\t\tfmt.Println(\"Input error.\")\n\t\t\tfmt.Println(\"usage: reply topicID text...\")\n\t\t} else {\n\t\t\tdoReply(args[1], strings.Trim(args[2], \" \\n\"))\n\t\t}\n\t\tlastLine = line\n\tcase \"post\":\n\t\targs := strings.SplitN(line, \" \", 3)\n\t\tif len(args) < 3 {\n\t\t\tfmt.Println(\"Input error.\")\n\t\t\tfmt.Println(\"usage: reply title text...\")\n\t\t} else {\n\t\t\tdoPost(args[1], strings.Trim(args[2], \" \\n\"))\n\t\t}\n\t\tlastLine = line\n\tcase \"next\":\n\t\tif nextNext != nil {\n\t\t\tdoGetNext(nextNext.id, nextNext.token)\n\t\t}\n\tdefault:\n\t\tfmt.Println(\"What?\")\n\t}\n}\n\nfunc doRegister(u, pw string) {\n\treg, _ := json.Marshal(&bbs.RegisterCommand{\n\t\tCommand: \"register\",\n\t\tUsername: u,\n\t\tPassword: pw,\n\t})\n\tsend(reg)\n}\n\nfunc doLogin(u, pw string) {\n\tlogin, _ := json.Marshal(&bbs.LoginCommand{\"login\", u, pw, 0})\n\tsend(login)\n}\n\nfunc doList(exp string) {\n\tlist, _ := json.Marshal(&bbs.ListCommand{\"list\", session, \"thread\", exp, \"\"})\n\tsend(list)\n}\n\nfunc doListBoards() {\n\tlist, _ := json.Marshal(&bbs.ListCommand{\"list\", session, \"board\", \"\", \"\"})\n\tsend(list)\n}\n\nfunc doGet(t string, r *bbs.Range, filter string) {\n\tget, _ := json.Marshal(&bbs.GetCommand{\"get\", session, t, r, filter, \"text\", \"\"})\n\tsend(get)\n}\n\nfunc doGetNext(t string, n string) {\n\tnxt, _ := json.Marshal(&bbs.GetCommand{\n\t\tCommand: \"get\",\n\t\tSession: session,\n\t\tThreadID: t,\n\t\tNextToken: n,\n\t})\n}\n\nfunc doReply(id, text string) {\n\treply, _ := json.Marshal(&bbs.ReplyCommand{\"reply\", session, id, text, \"text\"})\n\tsend(reply)\n}\n\nfunc doPost(title, text string) {\n\tpost, _ := json.Marshal(&bbs.PostCommand{\n\t\tCommand: \"post\",\n\t\tSession: session,\n\t\tTitle: title,\n\t\tText: text,\n\t\tFormat: \"text\"})\n\tsend(post)\n}\n\nfunc getURL(url string) string {\n\tresp, _ := http.Get(url)\n\tdefer resp.Body.Close()\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\treturn string(body)\n}\n\nfunc parse(js []byte) {\n\tif verbose {\n\t\tfmt.Println(\"server -> client\")\n\t\tfmt.Println(string(js))\n\t}\n\n\tbbscmd := new(bbs.BBSCommand)\n\terr := json.Unmarshal(js, bbscmd)\n\tif err != nil {\n\t\tfmt.Println(\"JSON Parsing Error!! \" + string(js))\n\t\treturn\n\t}\n\n\tswitch bbscmd.Command {\n\tcase \"error\":\n\t\tm := bbs.ErrorMessage{}\n\t\tjson.Unmarshal(js, &m)\n\t\tonError(&m)\n\tcase \"hello\":\n\t\tm := bbs.HelloMessage{}\n\t\tjson.Unmarshal(js, &m)\n\t\tonHello(&m)\n\tcase \"welcome\":\n\t\tm := bbs.WelcomeMessage{}\n\t\tjson.Unmarshal(js, &m)\n\t\tonWelcome(&m)\n\tcase \"msg\":\n\t\tm := bbs.ThreadMessage{}\n\t\tjson.Unmarshal(js, &m)\n\t\tonMsg(&m)\n\tcase \"ok\":\n\t\tm := bbs.OKMessage{}\n\t\tjson.Unmarshal(js, &m)\n\t\tfmt.Println(\"(OK: \" + m.ReplyTo + \") \" + m.Result)\n\tcase \"list\":\n\t\tt := bbs.TypedMessage{}\n\t\tjson.Unmarshal(js, &t)\n\t\tif t.Type == \"thread\" {\n\t\t\tm := bbs.ListMessage{}\n\t\t\tjson.Unmarshal(js, &m)\n\t\t\tonList(&m)\n\t\t} else if t.Type == \"board\" {\n\t\t\tm := bbs.BoardListMessage{}\n\t\t\tjson.Unmarshal(js, &m)\n\t\t\tonBoardList(&m)\n\t\t}\n\t}\n}\n\nfunc onError(msg *bbs.ErrorMessage) {\n\tprettyPrint(\"Error on: \"+msg.ReplyTo, msg.Error)\n}\n\nfunc onHello(msg *bbs.HelloMessage) {\n\tprettyPrint(\"Connected\", fmt.Sprintf(\"Name: %s\\nDesc: %s\\nOptions: %v\\nVersion: %d\\nServer: %s\\n\", msg.Name, msg.Description, msg.Options, msg.ProtocolVersion, msg.ServerVersion))\n}\n\nfunc onWelcome(msg *bbs.WelcomeMessage) {\n\tprettyPrint(\"Welcome \"+msg.Username, \"Session: \"+msg.Session)\n\tsession = msg.Session\n}\n\nfunc onMsg(msg *bbs.ThreadMessage) {\n\tfmt.Printf(\"Thread: %s [%d] \\n Tags: %s \\n\", msg.Title, len(msg.Messages), strings.Join(msg.Tags, \", \"))\n\tif msg.Closed {\n\t\tfmt.Println(\"(Closed)\")\n\t}\n\tfor _, m := range msg.Messages {\n\t\tfmt.Printf(\"#%s User: %s | Date: %s | UserID: %s \\n\", m.ID, m.Author, m.Date, m.AuthorID)\n\t\tfmt.Println(m.Text + \"\\n\")\n\t}\n\tif msg.More {\n\t\tnextNext = &next{msg.ID, msg.NextToken}\n\t}\n}\n\nfunc onList(msg *bbs.ListMessage) {\n\tprettyPrint(\"Threads\", msg.Query)\n\tfor _, t := range msg.Threads {\n\t\tinfo := \"\"\n\t\tif t.Closed && t.Sticky {\n\t\t\tinfo = \"(Sticky, Closed)\"\n\t\t} else if t.Closed {\n\t\t\tinfo = \"(Closed)\"\n\t\t} else if t.Sticky {\n\t\t\tinfo = \"(Sticky)\"\n\t\t}\n\t\tnewposts := \" \"\n\t\tif t.UnreadPosts > 0 {\n\t\t\tnewposts = fmt.Sprintf(\" (unread: %d) \", t.UnreadPosts)\n\t\t}\n\t\tfmt.Printf(\"#%s [%s] %s %s | %d posts%s| %s | %s\\n\", t.ID, t.Author, info, t.Title, t.PostCount, newposts, t.Date, strings.Join(t.Tags, \", \"))\n\t}\n}\n\nfunc onBoardList(msg *bbs.BoardListMessage) {\n\tprettyPrint(\"Boards\", msg.Query)\n\tfor i, b := range msg.Boards {\n\t\tfmt.Printf(\"#%d (%s) %s\\n\", i, b.ID, b.Name)\n\t\tif b.Description != \"\" {\n\t\t\tfmt.Println(b.Description)\n\t\t}\n\t}\n}\n\nfunc send(js []byte) {\n\tif verbose {\n\t\tfmt.Println(\"client -> server\")\n\t\tfmt.Println(string(js))\n\t}\n\tresp, err := http.Post(bbsServer, \"application\/json\", bytes.NewReader(js))\n\tif err != nil {\n\t\tfmt.Printf(\"Could not send data. %v\\n\", err)\n\t\treturn\n\t}\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\tresp.Body.Close()\n\tparse(body)\n}\n\nfunc prettyPrint(s1, s2 string) {\n\tfmt.Printf(\"### %s\\n%s\\n\", s1, s2)\n}\nnext commandpackage main\n\nimport \"github.com\/guregu\/bbs\"\nimport \"net\/http\"\nimport \"encoding\/json\"\nimport \"fmt\"\nimport \"io\/ioutil\"\nimport \"bytes\"\nimport \"strings\"\nimport \"bufio\"\nimport \"os\"\nimport \"strconv\"\n\nvar bbsServer = \"http:\/\/localhost:8080\/bbs\"\nvar session = \"\"\nvar lastLine = \"\"\nvar verbose = true\nvar nextNext *next\n\nconst client_version string = \"test-client 0.1\" \/\/TODO: use this in User-Agent\n\ntype next struct {\n\tid string\n\ttoken string\n}\n\nfunc main() {\n\ttestClient()\n}\n\nfunc testClient() {\n\tif len(os.Args) > 1 {\n\t\tbbsServer = os.Args[1]\n\t}\n\n\tfmt.Println(\"Running test client: \" + client_version)\n\tfmt.Printf(\"Connecting to %s...\\n\", bbsServer)\n\thello, _ := json.Marshal(&bbs.BBSCommand{\"hello\"})\n\tsend(hello)\n\n\tr := bufio.NewReader(os.Stdin)\n\tfmt.Println(\"Type help for a list of commands or quit to exit.\")\n\tfmt.Print(\"> \")\n\tfor {\n\t\tline, err := r.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tinput(line)\n\t\tfmt.Print(\"> \")\n\t}\n}\n\nfunc input(line string) {\n\tfields := strings.Fields(line)\n\tif len(fields) == 0 {\n\t\treturn\n\t}\n\n\tswitch fields[0] {\n\tcase \".\":\n\t\tinput(lastLine)\n\tcase \"help\":\n\t\tfmt.Println(\"COMMANDS\\n\\tlogin username password\\n\\tnigol password username\\n\\tget topicID [filterID]\\n\\tboards\\n\\tlist [expression]\\n\\treply [topicID] [text]\\n\\tquit\\n\\thelp\\n\\t. (repeat last command)\")\n\tcase \"quit\":\n\t\tos.Exit(0)\n\tcase \"exit\":\n\t\tos.Exit(0)\n\tcase \"register\":\n\t\tif len(fields) == 3 {\n\t\t\tdoRegister(fields[1], fields[2])\n\t\t} else {\n\t\t\tfmt.Println(\"Input error.\")\n\t\t\tfmt.Println(\"usage: register username password\")\n\t\t}\n\tcase \"login\":\n\t\targs := strings.SplitN(line, \" \", 3)\n\t\tif strings.Contains(args[2], \" \") {\n\t\t\tfmt.Println(\"WARNING: If you have spaces in your username, you should use 'nigol' instead.\")\n\t\t}\n\t\tif len(fields) != 3 {\n\t\t\tfmt.Println(\"Input error.\")\n\t\t\tfmt.Println(\"usage: login username password\")\n\t\t}\n\t\tdoLogin(fields[1], fields[2])\n\t\tlastLine = line\n\tcase \"nigol\":\n\t\targs := strings.SplitN(line, \" \", 3)\n\t\tif strings.Contains(args[2], \" \") {\n\t\t\tfmt.Println(\"WARNING: If you have spaces in your password, you should use 'login' instead. If you have spaces in both, you're SOL.\")\n\t\t}\n\t\tif len(fields) != 3 {\n\t\t\tfmt.Println(\"Input error.\")\n\t\t\tfmt.Println(\"usage: nigol password username\")\n\t\t}\n\t\tdoLogin(fields[2], fields[1])\n\t\tlastLine = line\n\tcase \"get\":\n\t\tif len(fields) == 2 {\n\t\t\tdoGet(fields[1], &bbs.Range{1, 50}, \"\")\n\t\t} else if len(fields) == 4 {\n\t\t\tlwr, _ := strconv.Atoi(fields[2])\n\t\t\thrr, _ := strconv.Atoi(fields[3])\n\t\t\tdoGet(fields[1], &bbs.Range{lwr, hrr}, \"\")\n\t\t} else {\n\t\t\tfmt.Println(\"Input error.\")\n\t\t\tfmt.Println(\"usage: get topicID [lower upper filter]\")\n\t\t\tfmt.Println(\"usage: get board topicID\")\n\t\t}\n\t\tlastLine = line\n\tcase \"list\":\n\t\tif len(fields) == 1 {\n\t\t\tdoList(\"\")\n\t\t} else if len(fields) == 2 {\n\t\t\tdoList(fields[1])\n\t\t} else {\n\t\t\tfmt.Println(\"Input error.\")\n\t\t\tfmt.Println(\"usage: list [expression]\")\n\t\t}\n\t\tlastLine = line\n\tcase \"boards\":\n\t\tdoListBoards()\n\t\tlastLine = line\n\tcase \"reply\":\n\t\targs := strings.SplitN(line, \" \", 3)\n\t\tif len(args) < 3 {\n\t\t\tfmt.Println(\"Input error.\")\n\t\t\tfmt.Println(\"usage: reply topicID text...\")\n\t\t} else {\n\t\t\tdoReply(args[1], strings.Trim(args[2], \" \\n\"))\n\t\t}\n\t\tlastLine = line\n\tcase \"post\":\n\t\targs := strings.SplitN(line, \" \", 3)\n\t\tif len(args) < 3 {\n\t\t\tfmt.Println(\"Input error.\")\n\t\t\tfmt.Println(\"usage: reply title text...\")\n\t\t} else {\n\t\t\tdoPost(args[1], strings.Trim(args[2], \" \\n\"))\n\t\t}\n\t\tlastLine = line\n\tcase \"next\":\n\t\tif nextNext != nil {\n\t\t\tdoGetNext(nextNext.id, nextNext.token)\n\t\t}\n\tdefault:\n\t\tfmt.Println(\"What?\")\n\t}\n}\n\nfunc doRegister(u, pw string) {\n\treg, _ := json.Marshal(&bbs.RegisterCommand{\n\t\tCommand: \"register\",\n\t\tUsername: u,\n\t\tPassword: pw,\n\t})\n\tsend(reg)\n}\n\nfunc doLogin(u, pw string) {\n\tlogin, _ := json.Marshal(&bbs.LoginCommand{\"login\", u, pw, 0})\n\tsend(login)\n}\n\nfunc doList(exp string) {\n\tlist, _ := json.Marshal(&bbs.ListCommand{\"list\", session, \"thread\", exp, \"\"})\n\tsend(list)\n}\n\nfunc doListBoards() {\n\tlist, _ := json.Marshal(&bbs.ListCommand{\"list\", session, \"board\", \"\", \"\"})\n\tsend(list)\n}\n\nfunc doGet(t string, r *bbs.Range, filter string) {\n\tget, _ := json.Marshal(&bbs.GetCommand{\"get\", session, t, r, filter, \"text\", \"\"})\n\tsend(get)\n}\n\nfunc doGetNext(t string, n string) {\n\tnxt, _ := json.Marshal(&bbs.GetCommand{\n\t\tCommand: \"get\",\n\t\tSession: session,\n\t\tThreadID: t,\n\t\tNextToken: n,\n\t})\n\tsend(nxt)\n}\n\nfunc doReply(id, text string) {\n\treply, _ := json.Marshal(&bbs.ReplyCommand{\"reply\", session, id, text, \"text\"})\n\tsend(reply)\n}\n\nfunc doPost(title, text string) {\n\tpost, _ := json.Marshal(&bbs.PostCommand{\n\t\tCommand: \"post\",\n\t\tSession: session,\n\t\tTitle: title,\n\t\tText: text,\n\t\tFormat: \"text\"})\n\tsend(post)\n}\n\nfunc getURL(url string) string {\n\tresp, _ := http.Get(url)\n\tdefer resp.Body.Close()\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\treturn string(body)\n}\n\nfunc parse(js []byte) {\n\tif verbose {\n\t\tfmt.Println(\"server -> client\")\n\t\tfmt.Println(string(js))\n\t}\n\n\tbbscmd := new(bbs.BBSCommand)\n\terr := json.Unmarshal(js, bbscmd)\n\tif err != nil {\n\t\tfmt.Println(\"JSON Parsing Error!! \" + string(js))\n\t\treturn\n\t}\n\n\tswitch bbscmd.Command {\n\tcase \"error\":\n\t\tm := bbs.ErrorMessage{}\n\t\tjson.Unmarshal(js, &m)\n\t\tonError(&m)\n\tcase \"hello\":\n\t\tm := bbs.HelloMessage{}\n\t\tjson.Unmarshal(js, &m)\n\t\tonHello(&m)\n\tcase \"welcome\":\n\t\tm := bbs.WelcomeMessage{}\n\t\tjson.Unmarshal(js, &m)\n\t\tonWelcome(&m)\n\tcase \"msg\":\n\t\tm := bbs.ThreadMessage{}\n\t\tjson.Unmarshal(js, &m)\n\t\tonMsg(&m)\n\tcase \"ok\":\n\t\tm := bbs.OKMessage{}\n\t\tjson.Unmarshal(js, &m)\n\t\tfmt.Println(\"(OK: \" + m.ReplyTo + \") \" + m.Result)\n\tcase \"list\":\n\t\tt := bbs.TypedMessage{}\n\t\tjson.Unmarshal(js, &t)\n\t\tif t.Type == \"thread\" {\n\t\t\tm := bbs.ListMessage{}\n\t\t\tjson.Unmarshal(js, &m)\n\t\t\tonList(&m)\n\t\t} else if t.Type == \"board\" {\n\t\t\tm := bbs.BoardListMessage{}\n\t\t\tjson.Unmarshal(js, &m)\n\t\t\tonBoardList(&m)\n\t\t}\n\t}\n}\n\nfunc onError(msg *bbs.ErrorMessage) {\n\tprettyPrint(\"Error on: \"+msg.ReplyTo, msg.Error)\n}\n\nfunc onHello(msg *bbs.HelloMessage) {\n\tprettyPrint(\"Connected\", fmt.Sprintf(\"Name: %s\\nDesc: %s\\nOptions: %v\\nVersion: %d\\nServer: %s\\n\", msg.Name, msg.Description, msg.Options, msg.ProtocolVersion, msg.ServerVersion))\n}\n\nfunc onWelcome(msg *bbs.WelcomeMessage) {\n\tprettyPrint(\"Welcome \"+msg.Username, \"Session: \"+msg.Session)\n\tsession = msg.Session\n}\n\nfunc onMsg(msg *bbs.ThreadMessage) {\n\tfmt.Printf(\"Thread: %s [%d] \\n Tags: %s \\n\", msg.Title, len(msg.Messages), strings.Join(msg.Tags, \", \"))\n\tif msg.Closed {\n\t\tfmt.Println(\"(Closed)\")\n\t}\n\tfor _, m := range msg.Messages {\n\t\tfmt.Printf(\"#%s User: %s | Date: %s | UserID: %s \\n\", m.ID, m.Author, m.Date, m.AuthorID)\n\t\tfmt.Println(m.Text + \"\\n\")\n\t}\n\tif msg.More {\n\t\tnextNext = &next{msg.ID, msg.NextToken}\n\t}\n}\n\nfunc onList(msg *bbs.ListMessage) {\n\tprettyPrint(\"Threads\", msg.Query)\n\tfor _, t := range msg.Threads {\n\t\tinfo := \"\"\n\t\tif t.Closed && t.Sticky {\n\t\t\tinfo = \"(Sticky, Closed)\"\n\t\t} else if t.Closed {\n\t\t\tinfo = \"(Closed)\"\n\t\t} else if t.Sticky {\n\t\t\tinfo = \"(Sticky)\"\n\t\t}\n\t\tnewposts := \" \"\n\t\tif t.UnreadPosts > 0 {\n\t\t\tnewposts = fmt.Sprintf(\" (unread: %d) \", t.UnreadPosts)\n\t\t}\n\t\tfmt.Printf(\"#%s [%s] %s %s | %d posts%s| %s | %s\\n\", t.ID, t.Author, info, t.Title, t.PostCount, newposts, t.Date, strings.Join(t.Tags, \", \"))\n\t}\n}\n\nfunc onBoardList(msg *bbs.BoardListMessage) {\n\tprettyPrint(\"Boards\", msg.Query)\n\tfor i, b := range msg.Boards {\n\t\tfmt.Printf(\"#%d (%s) %s\\n\", i, b.ID, b.Name)\n\t\tif b.Description != \"\" {\n\t\t\tfmt.Println(b.Description)\n\t\t}\n\t}\n}\n\nfunc send(js []byte) {\n\tif verbose {\n\t\tfmt.Println(\"client -> server\")\n\t\tfmt.Println(string(js))\n\t}\n\tresp, err := http.Post(bbsServer, \"application\/json\", bytes.NewReader(js))\n\tif err != nil {\n\t\tfmt.Printf(\"Could not send data. %v\\n\", err)\n\t\treturn\n\t}\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\tresp.Body.Close()\n\tparse(body)\n}\n\nfunc prettyPrint(s1, s2 string) {\n\tfmt.Printf(\"### %s\\n%s\\n\", s1, s2)\n}\n<|endoftext|>"} {"text":"\/\/ An IMAP client.\npackage client\n\nimport (\n\t\"crypto\/tls\"\n\t\"io\"\n\t\"log\"\n\t\"net\"\n\t\"sync\"\n\n\timap \"github.com\/emersion\/go-imap\/common\"\n)\n\n\/\/ An IMAP client.\ntype Client struct {\n\tconn *imap.Conn\n\tisTLS bool\n\n\thandlers []imap.RespHandler\n\thandlersLocker sync.Locker\n\n\t\/\/ The server capabilities.\n\tCaps map[string]bool\n\t\/\/ The current connection state.\n\tState imap.ConnState\n\t\/\/ The selected mailbox, if there is one.\n\tMailbox *imap.MailboxStatus\n\n\t\/\/ A channel where info messages from the server will be sent.\n\tInfos chan *imap.StatusResp\n\t\/\/ A channel where warning messages from the server will be sent.\n\tWarnings chan *imap.StatusResp\n\t\/\/ A channel where error messages from the server will be sent.\n\tErrors chan *imap.StatusResp\n\t\/\/ A channel where bye messages from the server will be sent.\n\tByes chan *imap.StatusResp\n\t\/\/ A channel where mailbox updates from the server will be sent.\n\tMailboxUpdates chan *imap.MailboxStatus\n\t\/\/ A channel where deleted message IDs will be sent.\n\tExpunges chan uint32\n\n\t\/\/ TODO: support unilateral message updates\n\t\/\/ A channel where messages updates from the server will be sent.\n\t\/\/MessageUpdates chan *imap.Message\n}\n\nfunc (c *Client) read() error {\n\tr := c.conn.Reader\n\n\tdefer (func () {\n\t\tc.handlersLocker.Lock()\n\t\tdefer c.handlersLocker.Unlock()\n\n\t\tfor _, hdlr := range c.handlers {\n\t\t\tclose(hdlr)\n\t\t}\n\t\tc.handlers = nil\n\t})()\n\n\tfor {\n\t\tif c.State == imap.LogoutState {\n\t\t\treturn nil\n\t\t}\n\n\t\tc.conn.Wait()\n\n\t\tres, err := imap.ReadResp(r)\n\t\tif err == io.EOF {\n\t\t\treturn nil\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error reading response:\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tc.handlersLocker.Lock()\n\n\t\tvar accepted bool\n\t\tfor _, hdlr := range c.handlers {\n\t\t\tif hdlr == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\th := &imap.RespHandling{\n\t\t\t\tResp: res,\n\t\t\t\tAccepts: make(chan bool),\n\t\t\t}\n\n\t\t\thdlr <- h\n\n\t\t\taccepted = <-h.Accepts\n\t\t\tif accepted {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tc.handlersLocker.Unlock()\n\n\t\tif !accepted {\n\t\t\tlog.Println(\"Response has not been handled\", res)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (c *Client) addHandler(hdlr imap.RespHandler) {\n\tc.handlersLocker.Lock()\n\tdefer c.handlersLocker.Unlock()\n\n\tc.handlers = append(c.handlers, hdlr)\n}\n\nfunc (c *Client) removeHandler(hdlr imap.RespHandler) {\n\tc.handlersLocker.Lock()\n\tdefer c.handlersLocker.Unlock()\n\n\tfor i, h := range c.handlers {\n\t\tif h == hdlr {\n\t\t\tclose(hdlr)\n\t\t\tc.handlers = append(c.handlers[:i], c.handlers[i+1:]...)\n\t\t}\n\t}\n}\n\nfunc (c *Client) execute(cmdr imap.Commander, res imap.RespHandlerFrom) (status *imap.StatusResp, err error) {\n\tcmd := cmdr.Command()\n\tcmd.Tag = generateTag()\n\n\t\/\/ Add handler before sending command, to be sure to get the response in time\n\t\/\/ (in tests, the response is sent right after our command is received, so\n\t\/\/ sometimes the response was received before the setup of this handler)\n\tstatusHdlr := make(imap.RespHandler)\n\tc.addHandler(statusHdlr)\n\tdefer c.removeHandler(statusHdlr)\n\n\t_, err = cmd.WriteTo(c.conn.Writer)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif err = c.conn.Flush(); err != nil {\n\t\treturn\n\t}\n\n\tvar hdlr imap.RespHandler\n\tvar done chan error\n\tdefer (func () {\n\t\tif hdlr != nil { close(hdlr) }\n\t\tif done != nil { close(done) }\n\t})()\n\n\tif res != nil {\n\t\thdlr = make(imap.RespHandler)\n\t\tdone = make(chan error)\n\n\t\tgo (func() {\n\t\t\terr := res.HandleFrom(hdlr)\n\t\t\tdone <- err\n\t\t})()\n\t}\n\n\tfor h := range statusHdlr {\n\t\tif s, ok := h.Resp.(*imap.StatusResp); ok && s.Tag == cmd.Tag {\n\t\t\th.Accept()\n\t\t\tstatus = s\n\n\t\t\tif hdlr != nil {\n\t\t\t\tclose(hdlr)\n\t\t\t\thdlr = nil\n\t\t\t}\n\t\t\tbreak\n\t\t} else if hdlr != nil {\n\t\t\thdlr <- h\n\t\t} else {\n\t\t\th.Reject()\n\t\t}\n\t}\n\n\tif done != nil {\n\t\terr = <-done\n\t}\n\treturn\n}\n\n\/\/ Execute a generic command. cmdr is a value that can be converted to a raw\n\/\/ command and res is a value that can handle responses. The function returns\n\/\/ when the command has completed or failed, in this case err is nil. A non-nil\n\/\/ err value indicates a network error.\n\/\/\n\/\/ This function should not be called directly, it must only be used by\n\/\/ libraries implementing extensions of the IMAP protocol.\nfunc (c *Client) Execute(cmdr imap.Commander, res imap.RespHandlerFrom) (status *imap.StatusResp, err error) {\n\treturn c.execute(cmdr, res)\n}\n\nfunc (c *Client) handleContinuationReqs(continues chan bool) {\n\thdlr := make(imap.RespHandler)\n\tc.addHandler(hdlr)\n\tdefer c.removeHandler(hdlr)\n\n\tdefer close(continues)\n\n\tfor h := range hdlr {\n\t\tif _, ok := h.Resp.(*imap.ContinuationResp); ok {\n\t\t\t\/\/ Only accept if waiting for a continuation request\n\t\t\tselect {\n\t\t\tcase continues <- true:\n\t\t\t\th.Accept()\n\t\t\tdefault:\n\t\t\t\th.Reject()\n\t\t\t}\n\t\t} else {\n\t\t\th.Reject()\n\t\t}\n\t}\n}\n\nfunc (c *Client) gotStatusCaps(args []interface{}) {\n\tc.Caps = map[string]bool{}\n\tfor _, cap := range args {\n\t\tc.Caps[cap.(string)] = true\n\t}\n}\n\nfunc (c *Client) handleGreeting() *imap.StatusResp {\n\thdlr := make(imap.RespHandler)\n\tc.addHandler(hdlr)\n\tdefer c.removeHandler(hdlr)\n\n\t\/\/ Make sure to start reading after we have set up the base handlers,\n\t\/\/ otherwise some messages will be lost.\n\tgo c.read()\n\n\tfor h := range hdlr {\n\t\tstatus, ok := h.Resp.(*imap.StatusResp)\n\t\tif !ok || status.Tag != \"*\" || (status.Type != imap.OK && status.Type != imap.PREAUTH && status.Type != imap.BYE) {\n\t\t\th.Reject()\n\t\t\tcontinue\n\t\t}\n\n\t\th.Accept()\n\n\t\tif status.Code == \"CAPABILITY\" {\n\t\t\tc.gotStatusCaps(status.Arguments)\n\t\t}\n\n\t\tif status.Type == imap.PREAUTH {\n\t\t\tc.State = imap.AuthenticatedState\n\t\t}\n\t\tif status.Type == imap.BYE {\n\t\t\tc.State = imap.LogoutState\n\t\t}\n\n\t\tgo c.handleUnilateral()\n\n\t\treturn status\n\t}\n\n\treturn nil\n}\n\n\/\/ The server can send unilateral data. This function handles it.\nfunc (c *Client) handleUnilateral() {\n\thdlr := make(imap.RespHandler)\n\tc.addHandler(hdlr)\n\tdefer c.removeHandler(hdlr)\n\n\tfor h := range hdlr {\n\t\tswitch res := h.Resp.(type) {\n\t\tcase *imap.StatusResp:\n\t\t\tif res.Tag != \"*\" ||\n\t\t\t\t(res.Type != imap.OK && res.Type != imap.NO && res.Type != imap.BAD && res.Type != imap.BYE) ||\n\t\t\t\t(res.Code != \"\" && res.Code != \"ALERT\") {\n\t\t\t\th.Reject()\n\t\t\t\tbreak\n\t\t\t}\n\t\t\th.Accept()\n\n\t\t\tswitch res.Type {\n\t\t\tcase imap.OK:\n\t\t\t\tselect {\n\t\t\t\tcase c.Infos <- res:\n\t\t\t\tdefault:\n\t\t\t\t}\n\t\t\tcase imap.NO:\n\t\t\t\tselect {\n\t\t\t\tcase c.Warnings <- res:\n\t\t\t\tdefault:\n\t\t\t\t}\n\t\t\tcase imap.BAD:\n\t\t\t\tselect {\n\t\t\t\tcase c.Errors <- res:\n\t\t\t\tdefault:\n\t\t\t\t}\n\t\t\tcase imap.BYE:\n\t\t\t\tc.State = imap.LogoutState\n\t\t\t\tc.Mailbox = nil\n\t\t\t\tc.conn.Close()\n\n\t\t\t\tselect {\n\t\t\t\tcase c.Byes <- res:\n\t\t\t\tdefault:\n\t\t\t\t}\n\t\t\t}\n\t\tcase *imap.Resp:\n\t\t\tif len(res.Fields) < 2 {\n\t\t\t\th.Reject()\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tname, ok := res.Fields[1].(string)\n\t\t\tif !ok || (name != \"EXISTS\" && name != \"RECENT\" && name != \"EXPUNGE\") {\n\t\t\t\th.Reject()\n\t\t\t\tbreak\n\t\t\t}\n\t\t\th.Accept()\n\n\t\t\tswitch name {\n\t\t\tcase \"EXISTS\":\n\t\t\t\tif c.Mailbox == nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tc.Mailbox.Messages, _ = imap.ParseNumber(res.Fields[0])\n\n\t\t\t\tselect {\n\t\t\t\tcase c.MailboxUpdates <- c.Mailbox:\n\t\t\t\tdefault:\n\t\t\t\t}\n\t\t\tcase \"RECENT\":\n\t\t\t\tif c.Mailbox == nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tc.Mailbox.Recent, _ = imap.ParseNumber(res.Fields[0])\n\n\t\t\t\tselect {\n\t\t\t\tcase c.MailboxUpdates <- c.Mailbox:\n\t\t\t\tdefault:\n\t\t\t\t}\n\t\t\tcase \"EXPUNGE\":\n\t\t\t\tseqNum, _ := imap.ParseNumber(res.Fields[0])\n\n\t\t\t\tselect {\n\t\t\t\tcase c.Expunges <- seqNum:\n\t\t\t\tdefault:\n\t\t\t\t}\n\t\t\t}\n\t\tdefault:\n\t\t\th.Reject()\n\t\t}\n\t}\n}\n\n\/\/ Upgrade a connection, e.g. wrap an unencrypted connection with an encrypted\n\/\/ tunnel.\n\/\/\n\/\/ This function should not be called directly, it must only be used by\n\/\/ libraries implementing extensions of the IMAP protocol.\nfunc (c *Client) Upgrade(upgrader imap.ConnUpgrader) error {\n\treturn c.conn.Upgrade(upgrader)\n}\n\n\/\/ Check if this client's connection has TLS enabled.\nfunc (c *Client) IsTLS() bool {\n\treturn c.isTLS\n}\n\n\/\/ Create a new client from an existing connection.\nfunc NewClient(conn net.Conn) (c *Client, err error) {\n\tcontinues := make(chan bool)\n\tw := imap.NewClientWriter(nil, continues)\n\tr := imap.NewReader(nil)\n\n\tc = &Client{\n\t\tconn: imap.NewConn(conn, r, w),\n\t\thandlersLocker: &sync.Mutex{},\n\t\tState: imap.NotAuthenticatedState,\n\t}\n\n\tgo c.handleContinuationReqs(continues)\n\n\tgreeting := c.handleGreeting()\n\tgreeting.Err()\n\treturn\n}\n\n\/\/ Connect to an IMAP server using an unencrypted connection.\nfunc Dial(addr string) (c *Client, err error) {\n\tconn, err := net.Dial(\"tcp\", addr)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tc, err = NewClient(conn)\n\treturn\n}\n\n\/\/ Connect to an IMAP server using an encrypted connection.\nfunc DialTLS(addr string, tlsConfig *tls.Config) (c *Client, err error) {\n\tconn, err := tls.Dial(\"tcp\", addr, tlsConfig)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tc, err = NewClient(conn)\n\tc.isTLS = true\n\treturn\n}\nclient: fixes closed conn warnings\/\/ An IMAP client.\npackage client\n\nimport (\n\t\"crypto\/tls\"\n\t\"io\"\n\t\"log\"\n\t\"net\"\n\t\"sync\"\n\n\timap \"github.com\/emersion\/go-imap\/common\"\n)\n\n\/\/ An IMAP client.\ntype Client struct {\n\tconn *imap.Conn\n\tisTLS bool\n\n\thandlers []imap.RespHandler\n\thandlersLocker sync.Locker\n\n\t\/\/ The server capabilities.\n\tCaps map[string]bool\n\t\/\/ The current connection state.\n\tState imap.ConnState\n\t\/\/ The selected mailbox, if there is one.\n\tMailbox *imap.MailboxStatus\n\n\t\/\/ A channel where info messages from the server will be sent.\n\tInfos chan *imap.StatusResp\n\t\/\/ A channel where warning messages from the server will be sent.\n\tWarnings chan *imap.StatusResp\n\t\/\/ A channel where error messages from the server will be sent.\n\tErrors chan *imap.StatusResp\n\t\/\/ A channel where bye messages from the server will be sent.\n\tByes chan *imap.StatusResp\n\t\/\/ A channel where mailbox updates from the server will be sent.\n\tMailboxUpdates chan *imap.MailboxStatus\n\t\/\/ A channel where deleted message IDs will be sent.\n\tExpunges chan uint32\n\n\t\/\/ TODO: support unilateral message updates\n\t\/\/ A channel where messages updates from the server will be sent.\n\t\/\/MessageUpdates chan *imap.Message\n}\n\nfunc (c *Client) read() error {\n\tr := c.conn.Reader\n\n\tdefer (func () {\n\t\tc.handlersLocker.Lock()\n\t\tdefer c.handlersLocker.Unlock()\n\n\t\tfor _, hdlr := range c.handlers {\n\t\t\tclose(hdlr)\n\t\t}\n\t\tc.handlers = nil\n\t})()\n\n\tfor {\n\t\tif c.State == imap.LogoutState {\n\t\t\treturn nil\n\t\t}\n\n\t\tc.conn.Wait()\n\n\t\tres, err := imap.ReadResp(r)\n\t\tif err == io.EOF || c.State == imap.LogoutState {\n\t\t\treturn nil\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error reading response:\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\tc.handlersLocker.Lock()\n\n\t\tvar accepted bool\n\t\tfor _, hdlr := range c.handlers {\n\t\t\tif hdlr == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\th := &imap.RespHandling{\n\t\t\t\tResp: res,\n\t\t\t\tAccepts: make(chan bool),\n\t\t\t}\n\n\t\t\thdlr <- h\n\n\t\t\taccepted = <-h.Accepts\n\t\t\tif accepted {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tc.handlersLocker.Unlock()\n\n\t\tif !accepted {\n\t\t\tlog.Println(\"Response has not been handled\", res)\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (c *Client) addHandler(hdlr imap.RespHandler) {\n\tc.handlersLocker.Lock()\n\tdefer c.handlersLocker.Unlock()\n\n\tc.handlers = append(c.handlers, hdlr)\n}\n\nfunc (c *Client) removeHandler(hdlr imap.RespHandler) {\n\tc.handlersLocker.Lock()\n\tdefer c.handlersLocker.Unlock()\n\n\tfor i, h := range c.handlers {\n\t\tif h == hdlr {\n\t\t\tclose(hdlr)\n\t\t\tc.handlers = append(c.handlers[:i], c.handlers[i+1:]...)\n\t\t}\n\t}\n}\n\nfunc (c *Client) execute(cmdr imap.Commander, res imap.RespHandlerFrom) (status *imap.StatusResp, err error) {\n\tcmd := cmdr.Command()\n\tcmd.Tag = generateTag()\n\n\t\/\/ Add handler before sending command, to be sure to get the response in time\n\t\/\/ (in tests, the response is sent right after our command is received, so\n\t\/\/ sometimes the response was received before the setup of this handler)\n\tstatusHdlr := make(imap.RespHandler)\n\tc.addHandler(statusHdlr)\n\tdefer c.removeHandler(statusHdlr)\n\n\t_, err = cmd.WriteTo(c.conn.Writer)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif err = c.conn.Flush(); err != nil {\n\t\treturn\n\t}\n\n\tvar hdlr imap.RespHandler\n\tvar done chan error\n\tdefer (func () {\n\t\tif hdlr != nil { close(hdlr) }\n\t\tif done != nil { close(done) }\n\t})()\n\n\tif res != nil {\n\t\thdlr = make(imap.RespHandler)\n\t\tdone = make(chan error)\n\n\t\tgo (func() {\n\t\t\terr := res.HandleFrom(hdlr)\n\t\t\tdone <- err\n\t\t})()\n\t}\n\n\tfor h := range statusHdlr {\n\t\tif s, ok := h.Resp.(*imap.StatusResp); ok && s.Tag == cmd.Tag {\n\t\t\th.Accept()\n\t\t\tstatus = s\n\n\t\t\tif hdlr != nil {\n\t\t\t\tclose(hdlr)\n\t\t\t\thdlr = nil\n\t\t\t}\n\t\t\tbreak\n\t\t} else if hdlr != nil {\n\t\t\thdlr <- h\n\t\t} else {\n\t\t\th.Reject()\n\t\t}\n\t}\n\n\tif done != nil {\n\t\terr = <-done\n\t}\n\treturn\n}\n\n\/\/ Execute a generic command. cmdr is a value that can be converted to a raw\n\/\/ command and res is a value that can handle responses. The function returns\n\/\/ when the command has completed or failed, in this case err is nil. A non-nil\n\/\/ err value indicates a network error.\n\/\/\n\/\/ This function should not be called directly, it must only be used by\n\/\/ libraries implementing extensions of the IMAP protocol.\nfunc (c *Client) Execute(cmdr imap.Commander, res imap.RespHandlerFrom) (status *imap.StatusResp, err error) {\n\treturn c.execute(cmdr, res)\n}\n\nfunc (c *Client) handleContinuationReqs(continues chan bool) {\n\thdlr := make(imap.RespHandler)\n\tc.addHandler(hdlr)\n\tdefer c.removeHandler(hdlr)\n\n\tdefer close(continues)\n\n\tfor h := range hdlr {\n\t\tif _, ok := h.Resp.(*imap.ContinuationResp); ok {\n\t\t\t\/\/ Only accept if waiting for a continuation request\n\t\t\tselect {\n\t\t\tcase continues <- true:\n\t\t\t\th.Accept()\n\t\t\tdefault:\n\t\t\t\th.Reject()\n\t\t\t}\n\t\t} else {\n\t\t\th.Reject()\n\t\t}\n\t}\n}\n\nfunc (c *Client) gotStatusCaps(args []interface{}) {\n\tc.Caps = map[string]bool{}\n\tfor _, cap := range args {\n\t\tc.Caps[cap.(string)] = true\n\t}\n}\n\nfunc (c *Client) handleGreeting() *imap.StatusResp {\n\thdlr := make(imap.RespHandler)\n\tc.addHandler(hdlr)\n\tdefer c.removeHandler(hdlr)\n\n\t\/\/ Make sure to start reading after we have set up the base handlers,\n\t\/\/ otherwise some messages will be lost.\n\tgo c.read()\n\n\tfor h := range hdlr {\n\t\tstatus, ok := h.Resp.(*imap.StatusResp)\n\t\tif !ok || status.Tag != \"*\" || (status.Type != imap.OK && status.Type != imap.PREAUTH && status.Type != imap.BYE) {\n\t\t\th.Reject()\n\t\t\tcontinue\n\t\t}\n\n\t\th.Accept()\n\n\t\tif status.Code == \"CAPABILITY\" {\n\t\t\tc.gotStatusCaps(status.Arguments)\n\t\t}\n\n\t\tif status.Type == imap.PREAUTH {\n\t\t\tc.State = imap.AuthenticatedState\n\t\t}\n\t\tif status.Type == imap.BYE {\n\t\t\tc.State = imap.LogoutState\n\t\t}\n\n\t\tgo c.handleUnilateral()\n\n\t\treturn status\n\t}\n\n\treturn nil\n}\n\n\/\/ The server can send unilateral data. This function handles it.\nfunc (c *Client) handleUnilateral() {\n\thdlr := make(imap.RespHandler)\n\tc.addHandler(hdlr)\n\tdefer c.removeHandler(hdlr)\n\n\tfor h := range hdlr {\n\t\tswitch res := h.Resp.(type) {\n\t\tcase *imap.StatusResp:\n\t\t\tif res.Tag != \"*\" ||\n\t\t\t\t(res.Type != imap.OK && res.Type != imap.NO && res.Type != imap.BAD && res.Type != imap.BYE) ||\n\t\t\t\t(res.Code != \"\" && res.Code != \"ALERT\") {\n\t\t\t\th.Reject()\n\t\t\t\tbreak\n\t\t\t}\n\t\t\th.Accept()\n\n\t\t\tswitch res.Type {\n\t\t\tcase imap.OK:\n\t\t\t\tselect {\n\t\t\t\tcase c.Infos <- res:\n\t\t\t\tdefault:\n\t\t\t\t}\n\t\t\tcase imap.NO:\n\t\t\t\tselect {\n\t\t\t\tcase c.Warnings <- res:\n\t\t\t\tdefault:\n\t\t\t\t}\n\t\t\tcase imap.BAD:\n\t\t\t\tselect {\n\t\t\t\tcase c.Errors <- res:\n\t\t\t\tdefault:\n\t\t\t\t}\n\t\t\tcase imap.BYE:\n\t\t\t\tc.State = imap.LogoutState\n\t\t\t\tc.Mailbox = nil\n\t\t\t\tc.conn.Close()\n\n\t\t\t\tselect {\n\t\t\t\tcase c.Byes <- res:\n\t\t\t\tdefault:\n\t\t\t\t}\n\t\t\t}\n\t\tcase *imap.Resp:\n\t\t\tif len(res.Fields) < 2 {\n\t\t\t\th.Reject()\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tname, ok := res.Fields[1].(string)\n\t\t\tif !ok || (name != \"EXISTS\" && name != \"RECENT\" && name != \"EXPUNGE\") {\n\t\t\t\th.Reject()\n\t\t\t\tbreak\n\t\t\t}\n\t\t\th.Accept()\n\n\t\t\tswitch name {\n\t\t\tcase \"EXISTS\":\n\t\t\t\tif c.Mailbox == nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tc.Mailbox.Messages, _ = imap.ParseNumber(res.Fields[0])\n\n\t\t\t\tselect {\n\t\t\t\tcase c.MailboxUpdates <- c.Mailbox:\n\t\t\t\tdefault:\n\t\t\t\t}\n\t\t\tcase \"RECENT\":\n\t\t\t\tif c.Mailbox == nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tc.Mailbox.Recent, _ = imap.ParseNumber(res.Fields[0])\n\n\t\t\t\tselect {\n\t\t\t\tcase c.MailboxUpdates <- c.Mailbox:\n\t\t\t\tdefault:\n\t\t\t\t}\n\t\t\tcase \"EXPUNGE\":\n\t\t\t\tseqNum, _ := imap.ParseNumber(res.Fields[0])\n\n\t\t\t\tselect {\n\t\t\t\tcase c.Expunges <- seqNum:\n\t\t\t\tdefault:\n\t\t\t\t}\n\t\t\t}\n\t\tdefault:\n\t\t\th.Reject()\n\t\t}\n\t}\n}\n\n\/\/ Upgrade a connection, e.g. wrap an unencrypted connection with an encrypted\n\/\/ tunnel.\n\/\/\n\/\/ This function should not be called directly, it must only be used by\n\/\/ libraries implementing extensions of the IMAP protocol.\nfunc (c *Client) Upgrade(upgrader imap.ConnUpgrader) error {\n\treturn c.conn.Upgrade(upgrader)\n}\n\n\/\/ Check if this client's connection has TLS enabled.\nfunc (c *Client) IsTLS() bool {\n\treturn c.isTLS\n}\n\n\/\/ Create a new client from an existing connection.\nfunc NewClient(conn net.Conn) (c *Client, err error) {\n\tcontinues := make(chan bool)\n\tw := imap.NewClientWriter(nil, continues)\n\tr := imap.NewReader(nil)\n\n\tc = &Client{\n\t\tconn: imap.NewConn(conn, r, w),\n\t\thandlersLocker: &sync.Mutex{},\n\t\tState: imap.NotAuthenticatedState,\n\t}\n\n\tgo c.handleContinuationReqs(continues)\n\n\tgreeting := c.handleGreeting()\n\tgreeting.Err()\n\treturn\n}\n\n\/\/ Connect to an IMAP server using an unencrypted connection.\nfunc Dial(addr string) (c *Client, err error) {\n\tconn, err := net.Dial(\"tcp\", addr)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tc, err = NewClient(conn)\n\treturn\n}\n\n\/\/ Connect to an IMAP server using an encrypted connection.\nfunc DialTLS(addr string, tlsConfig *tls.Config) (c *Client, err error) {\n\tconn, err := tls.Dial(\"tcp\", addr, tlsConfig)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tc, err = NewClient(conn)\n\tc.isTLS = true\n\treturn\n}\n<|endoftext|>"} {"text":"package GoMM\r\n\r\nimport (\r\n\t\"github.com\/hashicorp\/memberlist\"\r\n\t\"log\"\r\n\t\"net\"\r\n\t\"strconv\"\r\n)\r\n\r\nconst (\r\n\tmemberlist_starting_port int = 7946\r\n\ttcp_offset int = 100\r\n)\r\n\r\ntype ClientFactory struct {\r\n\tnum_created int\r\n}\r\n\r\nfunc (f *ClientFactory) NewClient() (c Client) {\r\n\tc = Client{}\r\n\tf.initializeData(&c)\r\n\r\n\tf.num_created += 1\r\n\r\n\treturn\r\n}\r\n\r\nfunc (f *ClientFactory) initializeData(c *Client) error {\r\n\t\/\/ Initialize variables\r\n\tc.ActiveMembers = make(map[string]Node)\r\n\tc.pendingMembers = make(map[string]Node)\r\n\tc.barrierChannel = make(chan string)\r\n\tc.BroadcastChannel = make(chan Message, 10)\r\n\r\n\tvar config *memberlist.Config = memberlist.DefaultLocalConfig()\r\n\tc.Name = config.Name + \":\" + strconv.Itoa(memberlist_starting_port) + \"-\" + strconv.Itoa(f.num_created)\r\n\r\n\t\/\/ Configure the local Node data\r\n\taddress, err := f.getNonLoopBackAddress()\r\n\r\n\tc.node = Node{\r\n\t\tName: c.Name,\r\n\t\tAddr: address,\r\n\t\tPort: config.BindPort + tcp_offset + f.num_created,\r\n\t\tMemberlistPort: config.BindPort + f.num_created,\r\n\t}\r\n\r\n\treturn err\r\n}\r\n\r\nfunc (f *ClientFactory) getNonLoopBackAddress() (net.IP, error) {\r\n\t\/\/ https:\/\/www.socketloop.com\/tutorials\/golang-how-do-I-get-the-local-ip-non-loopback-address\r\n\r\n\taddrs, err := net.InterfaceAddrs()\r\n\tif err != nil {\r\n\t\treturn net.IP{}, err\r\n\t}\r\n\r\n\tfor _, address := range addrs {\r\n\r\n\t\t\/\/ check the address type and if it is not a loopback the display it\r\n\t\tif ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {\r\n\t\t\tif ipnet.IP.To4() != nil {\r\n\t\t\t\treturn ipnet.IP, err\r\n\t\t\t}\r\n\r\n\t\t}\r\n\t}\r\n\r\n\treturn net.IP{}, err\r\n}\r\n\r\n\/\/ Get Clients for the test\r\nfunc GetLocalClients(num int) []Client {\r\n\tfactory := ClientFactory{}\r\n\r\n\t\/\/ Create clients\r\n\tclients := make([]Client, num)\r\n\tClientNames := make([]string, num)\r\n\tfor i := 0; i < num; i++ {\r\n\t\tclients[i] = factory.NewClient()\r\n\r\n\t\ttcpAddr := clients[i].node.GetTCPAddr()\r\n\t\tClientNames[i] = tcpAddr.String()\r\n\t\tlog.Println(\"[DEBUG] Created Client\", tcpAddr.String())\r\n\t}\r\n\r\n\t\/\/ Create channel messengers\r\n\tresolverMap := make(map[string]chan Message)\r\n\tmessengers := GetChannelMessengers(ClientNames, resolverMap)\r\n\r\n\t\/\/ Attach chennel messengers to clients\r\n\tfor i := 0; i < num; i++ {\r\n\t\tclients[i].messenger = messengers[i]\r\n\t}\r\n\r\n\treturn clients\r\n}\r\n\r\n\/\/ func GetTCPClient() ([]Client, error) {\r\n\/\/ \treturn nil,\r\n\/\/ }\r\n\r\n\/\/ Get TCP clients\r\nfunc GetTCPClients(num int) ([]Client, error) {\r\n\tfactory := ClientFactory{}\r\n\r\n\tclients := make([]Client, num)\r\n\tfor i := 0; i < num; i++ {\r\n\t\tclients[i] = factory.NewClient()\r\n\t\ttcpAddr := clients[i].node.GetTCPAddr()\r\n\t\tmessenger, err := GetTCPMessenger(tcpAddr.String(), tcpAddr.String())\r\n\t\tfor err != nil {\r\n\t\t\t\/\/ If already in use, try a different port\r\n\t\t\tlog.Printf(\"[ERROR] Failed to create client: %s. Incrementing port and trying again\", tcpAddr.String())\r\n\t\t\tclients[i].node.Port += 1\r\n\t\t\tclients[i].node.MemberlistPort += 1\r\n\t\t\ttcpAddr = clients[i].node.GetTCPAddr()\r\n\t\t\tmessenger, err = GetTCPMessenger(tcpAddr.String(), tcpAddr.String())\r\n\t\t}\r\n\t\t\/\/ if err != nil {\r\n\t\t\/\/ \tlog.Println(\"[ERROR] Failed to create client\", tcpAddr.String())\r\n\t\t\/\/ \treturn clients, err\r\n\t\t\/\/ }\r\n\t\t\/\/ log.Println(\"[DEBUG] Created Client\", tcpAddr.String())\r\n\t\tclients[i].messenger = messenger\r\n\t}\r\n\r\n\treturn clients, nil\r\n}\r\nRemoved unneeded comments.package GoMM\r\n\r\nimport (\r\n\t\"github.com\/hashicorp\/memberlist\"\r\n\t\"log\"\r\n\t\"net\"\r\n\t\"strconv\"\r\n)\r\n\r\nconst (\r\n\tmemberlist_starting_port int = 7946\r\n\ttcp_offset int = 100\r\n)\r\n\r\ntype ClientFactory struct {\r\n\tnum_created int\r\n}\r\n\r\nfunc (f *ClientFactory) NewClient() (c Client) {\r\n\tc = Client{}\r\n\tf.initializeData(&c)\r\n\r\n\tf.num_created += 1\r\n\r\n\treturn\r\n}\r\n\r\nfunc (f *ClientFactory) initializeData(c *Client) error {\r\n\t\/\/ Initialize variables\r\n\tc.ActiveMembers = make(map[string]Node)\r\n\tc.pendingMembers = make(map[string]Node)\r\n\tc.barrierChannel = make(chan string)\r\n\tc.BroadcastChannel = make(chan Message, 10)\r\n\r\n\tvar config *memberlist.Config = memberlist.DefaultLocalConfig()\r\n\tc.Name = config.Name + \":\" + strconv.Itoa(memberlist_starting_port) + \"-\" + strconv.Itoa(f.num_created)\r\n\r\n\t\/\/ Configure the local Node data\r\n\taddress, err := f.getNonLoopBackAddress()\r\n\r\n\tc.node = Node{\r\n\t\tName: c.Name,\r\n\t\tAddr: address,\r\n\t\tPort: config.BindPort + tcp_offset + f.num_created,\r\n\t\tMemberlistPort: config.BindPort + f.num_created,\r\n\t}\r\n\r\n\treturn err\r\n}\r\n\r\nfunc (f *ClientFactory) getNonLoopBackAddress() (net.IP, error) {\r\n\t\/\/ https:\/\/www.socketloop.com\/tutorials\/golang-how-do-I-get-the-local-ip-non-loopback-address\r\n\r\n\taddrs, err := net.InterfaceAddrs()\r\n\tif err != nil {\r\n\t\treturn net.IP{}, err\r\n\t}\r\n\r\n\tfor _, address := range addrs {\r\n\r\n\t\t\/\/ check the address type and if it is not a loopback the display it\r\n\t\tif ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {\r\n\t\t\tif ipnet.IP.To4() != nil {\r\n\t\t\t\treturn ipnet.IP, err\r\n\t\t\t}\r\n\r\n\t\t}\r\n\t}\r\n\r\n\treturn net.IP{}, err\r\n}\r\n\r\n\/\/ Get Clients for the test\r\nfunc GetLocalClients(num int) []Client {\r\n\tfactory := ClientFactory{}\r\n\r\n\t\/\/ Create clients\r\n\tclients := make([]Client, num)\r\n\tClientNames := make([]string, num)\r\n\tfor i := 0; i < num; i++ {\r\n\t\tclients[i] = factory.NewClient()\r\n\r\n\t\ttcpAddr := clients[i].node.GetTCPAddr()\r\n\t\tClientNames[i] = tcpAddr.String()\r\n\t\tlog.Println(\"[DEBUG] Created Client\", tcpAddr.String())\r\n\t}\r\n\r\n\t\/\/ Create channel messengers\r\n\tresolverMap := make(map[string]chan Message)\r\n\tmessengers := GetChannelMessengers(ClientNames, resolverMap)\r\n\r\n\t\/\/ Attach chennel messengers to clients\r\n\tfor i := 0; i < num; i++ {\r\n\t\tclients[i].messenger = messengers[i]\r\n\t}\r\n\r\n\treturn clients\r\n}\r\n\r\n\/\/ Get TCP clients\r\nfunc GetTCPClients(num int) ([]Client, error) {\r\n\tfactory := ClientFactory{}\r\n\r\n\tclients := make([]Client, num)\r\n\tfor i := 0; i < num; i++ {\r\n\t\tclients[i] = factory.NewClient()\r\n\t\ttcpAddr := clients[i].node.GetTCPAddr()\r\n\t\tmessenger, err := GetTCPMessenger(tcpAddr.String(), tcpAddr.String())\r\n\t\tfor err != nil {\r\n\t\t\t\/\/ If already in use, try a different port\r\n\t\t\tlog.Printf(\"[ERROR] Failed to create client: %s. Incrementing port and trying again\", tcpAddr.String())\r\n\t\t\tclients[i].node.Port += 1\r\n\t\t\tclients[i].node.MemberlistPort += 1\r\n\t\t\ttcpAddr = clients[i].node.GetTCPAddr()\r\n\t\t\tmessenger, err = GetTCPMessenger(tcpAddr.String(), tcpAddr.String())\r\n\t\t}\r\n\t\tclients[i].messenger = messenger\r\n\t}\r\n\r\n\treturn clients, nil\r\n}\r\n<|endoftext|>"} {"text":"package rtmp\n\nimport (\n\t\"bytes\"\n\t\"code.google.com\/p\/go-uuid\/uuid\"\n\t\"github.com\/elobuff\/goamf\"\n)\n\nfunc (c *Client) EncodeInvoke(destination string, operation string, vals ...interface{}) (msg *Message, err error) {\n\ttid := c.NextTransactionId()\n\n\trmh := make(amf.Object)\n\trmh[\"DSRequestTimeout\"] = 60\n\trmh[\"DSId\"] = c.connectionId\n\trmh[\"DSEndpoint\"] = \"my-rtmps\"\n\n\tvar body []interface{}\n\tfor _, val := range vals {\n\t\tbody = append(body, val)\n\t}\n\n\trm := *amf.NewTypedObject()\n\trm.Type = \"flex.messaging.messages.RemotingMessage\"\n\trm.Object[\"destination\"] = destination\n\trm.Object[\"operation\"] = operation\n\trm.Object[\"messageId\"] = uuid.New()\n\trm.Object[\"source\"] = nil\n\trm.Object[\"timestamp\"] = 0\n\trm.Object[\"timeToLive\"] = 0\n\trm.Object[\"headers\"] = rmh\n\trm.Object[\"body\"] = body\n\n\tbuf := new(bytes.Buffer)\n\n\t\/\/ amf3 empty byte\n\tif err = amf.WriteMarker(buf, 0x00); err != nil {\n\t\treturn msg, Error(\"client invoke: could not encode amf3 0x00 byte: %s\", err)\n\t}\n\n\t\/\/ amf0 command\n\tif _, err = c.enc.EncodeAmf0Null(buf, true); err != nil {\n\t\treturn msg, Error(\"client invoke: could not encode amf0 command: %s\", err)\n\t}\n\n\t\/\/ amf0 tid\n\tif _, err = c.enc.EncodeAmf0Number(buf, float64(tid), true); err != nil {\n\t\treturn msg, Error(\"client invoke: could not encode amf0 tid: %s\", err)\n\t}\n\n\t\/\/ amf0 nil?\n\tif err = amf.WriteMarker(buf, 0x05); err != nil {\n\t\treturn msg, Error(\"client invoke: could not encode amf3 0x05 byte: %s\", err)\n\t}\n\n\t\/\/ amf0 amf3\n\tif err = c.enc.EncodeAmf0Amf3Marker(buf); err != nil {\n\t\treturn msg, Error(\"client invoke: could not encode amf3 0x11 byte: %s\", err)\n\t}\n\n\t\/\/ amf3 object\n\tif _, err = c.enc.EncodeAmf3(buf, rm); err != nil {\n\t\treturn msg, Error(\"client invoke: could not encode amf3 object: %s\", err)\n\t}\n\n\treturn &Message{\n\t\tType: MESSAGE_TYPE_AMF3,\n\t\tChunkStreamId: CHUNK_STREAM_ID_COMMAND,\n\t\tTransactionId: tid,\n\t\tLength: uint32(buf.Len()),\n\t\tBuffer: buf,\n\t}, nil\n}\nAllow invoking of command messages, don't use variadic input on encode invoke methods.package rtmp\n\nimport (\n\t\"bytes\"\n\t\"code.google.com\/p\/go-uuid\/uuid\"\n\t\"github.com\/elobuff\/goamf\"\n)\n\nfunc (c *Client) EncodeInvokeCommand(destination interface{}, operation interface{}, body interface{}) (msg *Message, err error) {\n\treturn c.EncodeInvoke(\"flex.messaging.messages.CommandMessage\", destination, operation, body)\n}\n\nfunc (c *Client) EncodeInvokeRemote(destination interface{}, operation interface{}, body interface{}) (msg *Message, err error) {\n\treturn c.EncodeInvoke(\"flex.messaging.messages.RemotingMessage\", destination, operation, body)\n}\n\nfunc (c *Client) EncodeInvoke(className string, destination interface{}, operation interface{}, body interface{}) (msg *Message, err error) {\n\ttid := c.NextTransactionId()\n\n\trmh := make(amf.Object)\n\trmh[\"DSRequestTimeout\"] = 60\n\trmh[\"DSId\"] = c.connectionId\n\trmh[\"DSEndpoint\"] = \"my-rtmps\"\n\n\trm := *amf.NewTypedObject()\n\trm.Type = className\n\trm.Object[\"destination\"] = destination\n\trm.Object[\"operation\"] = operation\n\trm.Object[\"messageId\"] = uuid.New()\n\trm.Object[\"source\"] = nil\n\trm.Object[\"timestamp\"] = 0\n\trm.Object[\"timeToLive\"] = 0\n\trm.Object[\"headers\"] = rmh\n\trm.Object[\"body\"] = body\n\n\tbuf := new(bytes.Buffer)\n\n\t\/\/ amf3 empty byte\n\tif err = amf.WriteMarker(buf, 0x00); err != nil {\n\t\treturn msg, Error(\"client invoke: could not encode amf3 0x00 byte: %s\", err)\n\t}\n\n\t\/\/ amf0 command\n\tif _, err = c.enc.EncodeAmf0Null(buf, true); err != nil {\n\t\treturn msg, Error(\"client invoke: could not encode amf0 command: %s\", err)\n\t}\n\n\t\/\/ amf0 tid\n\tif _, err = c.enc.EncodeAmf0Number(buf, float64(tid), true); err != nil {\n\t\treturn msg, Error(\"client invoke: could not encode amf0 tid: %s\", err)\n\t}\n\n\t\/\/ amf0 nil?\n\tif err = amf.WriteMarker(buf, 0x05); err != nil {\n\t\treturn msg, Error(\"client invoke: could not encode amf3 0x05 byte: %s\", err)\n\t}\n\n\t\/\/ amf0 amf3\n\tif err = c.enc.EncodeAmf0Amf3Marker(buf); err != nil {\n\t\treturn msg, Error(\"client invoke: could not encode amf3 0x11 byte: %s\", err)\n\t}\n\n\t\/\/ amf3 object\n\tif _, err = c.enc.EncodeAmf3(buf, rm); err != nil {\n\t\treturn msg, Error(\"client invoke: could not encode amf3 object: %s\", err)\n\t}\n\n\treturn &Message{\n\t\tType: MESSAGE_TYPE_AMF3,\n\t\tChunkStreamId: CHUNK_STREAM_ID_COMMAND,\n\t\tTransactionId: tid,\n\t\tLength: uint32(buf.Len()),\n\t\tBuffer: buf,\n\t}, nil\n}\n<|endoftext|>"} {"text":"package kamino\n\nimport (\n\t\"fmt\"\n\t\"net\/url\"\n\t\"os\/exec\"\n\n\t\"github.com\/modcloth\/go-fileutils\"\n)\n\ntype clone struct {\n\t*Genome\n\tworkdir string\n}\n\nfunc (creator *clone) cachePath() string {\n\treturn fmt.Sprintf(\"%s\/%s\/%s\", creator.workdir, creator.Account, creator.Repo)\n}\n\nfunc (creator *clone) cloneCacheIfAvailable() (string, error) {\n\tif err := creator.updateToRef(creator.cachePath()); err != nil {\n\t\treturn creator.cloneNoCache()\n\t}\n\n\treturn creator.cachePath(), nil\n}\n\nfunc (creator *clone) cloneForceCache() (string, error) {\n\tif err := creator.updateToRef(creator.cachePath()); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn creator.cachePath(), nil\n}\n\nfunc (creator *clone) cloneCreateCache() (string, error) {\n\tif err := creator.cloneRepo(creator.cachePath()); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn creator.cachePath(), nil\n}\n\nfunc (creator *clone) cloneNoCache() (string, error) {\n\tuuid, err := nextUUID()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tclonePath := fmt.Sprintf(\"%s\/%s\/%s\", creator.workdir, creator.Account, uuid)\n\n\tif err = creator.cloneRepo(clonePath); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn clonePath, nil\n}\n\nfunc (creator *clone) cloneRepo(dest string) error {\n\trepoURL := &url.URL{\n\t\tScheme: \"https\",\n\t\tHost: \"github.com\",\n\t\tPath: fmt.Sprintf(\"%s\/%s\", creator.Account, creator.Repo),\n\t}\n\n\tif creator.APIToken != \"\" {\n\t\trepoURL.User = url.User(creator.APIToken)\n\t}\n\n\tvar cloneCmd *exec.Cmd\n\n\tif creator.Depth == \"\" {\n\t\tcloneCmd = exec.Command(\n\t\t\t\"git\", \"clone\",\n\t\t\t\"--quiet\",\n\t\t\trepoURL.String(),\n\t\t\tdest,\n\t\t)\n\t} else {\n\t\tcloneCmd = exec.Command(\n\t\t\t\"git\", \"clone\",\n\t\t\t\"--quiet\",\n\t\t\t\"--depth\", creator.Depth,\n\t\t\trepoURL.String(),\n\t\t\tdest,\n\t\t)\n\t}\n\n\tif err := cloneCmd.Run(); err != nil {\n\t\treturn err\n\t}\n\n\tgit, err := fileutils.Which(\"git\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcheckoutCmd := &exec.Cmd{\n\t\tPath: git,\n\t\tDir: dest,\n\t\tArgs: []string{\"git\", \"checkout\", \"-qf\", creator.Ref},\n\t}\n\n\tif err := checkoutCmd.Run(); err != nil {\n\t\tfmt.Printf(\"GOT HERE, err = %q, dest = %q\\n\", err, dest)\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (creator *clone) updateToRef(dest string) error {\n\t\/*\n\t\tworkflow as follows:\n\t\t\tgit reset --hard\n\t\t\tgit clean -df\n\t\t\tgit fetch\n\t\t\tgit checkout -f \n\t\t\tgit symbolic-ref HEAD || git pull --rebase\n\t*\/\n\tgit, err := fileutils.Which(\"git\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmds := []*exec.Cmd{\n\t\t&exec.Cmd{\n\t\t\tPath: git,\n\t\t\tDir: dest,\n\t\t\tArgs: []string{\"git\", \"reset\", \"--hard\"},\n\t\t},\n\t\t&exec.Cmd{\n\t\t\tPath: git,\n\t\t\tDir: dest,\n\t\t\tArgs: []string{\"git\", \"clean\", \"-df\"},\n\t\t},\n\t\t&exec.Cmd{\n\t\t\tPath: git,\n\t\t\tDir: dest,\n\t\t\tArgs: []string{\"git\", \"fetch\"},\n\t\t},\n\t\t&exec.Cmd{\n\t\t\tPath: git,\n\t\t\tDir: dest,\n\t\t\tArgs: []string{\"git\", \"checkout\", \"-f\", creator.Ref},\n\t\t},\n\t}\n\n\tfor _, cmd := range cmds {\n\t\tif err := cmd.Run(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tdetectBranch := &exec.Cmd{\n\t\tPath: git,\n\t\tDir: dest,\n\t\tArgs: []string{\"git\", \"symbolic-ref\", \"HEAD\"},\n\t}\n\n\t\/\/ no error => we are on a proper branch (as opposed to a detached HEAD)\n\tif err := detectBranch.Run(); err == nil {\n\t\tpullRebase := &exec.Cmd{\n\t\t\tPath: git,\n\t\t\tDir: dest,\n\t\t\tArgs: []string{\"git\", \"pull\", \"--rebase\"},\n\t\t}\n\n\t\tif err = pullRebase.Run(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\nMaking our git operations more `--quiet`package kamino\n\nimport (\n\t\"fmt\"\n\t\"net\/url\"\n\t\"os\/exec\"\n\n\t\"github.com\/modcloth\/go-fileutils\"\n)\n\ntype clone struct {\n\t*Genome\n\tworkdir string\n}\n\nfunc (creator *clone) cachePath() string {\n\treturn fmt.Sprintf(\"%s\/%s\/%s\", creator.workdir, creator.Account, creator.Repo)\n}\n\nfunc (creator *clone) cloneCacheIfAvailable() (string, error) {\n\tif err := creator.updateToRef(creator.cachePath()); err != nil {\n\t\treturn creator.cloneNoCache()\n\t}\n\n\treturn creator.cachePath(), nil\n}\n\nfunc (creator *clone) cloneForceCache() (string, error) {\n\tif err := creator.updateToRef(creator.cachePath()); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn creator.cachePath(), nil\n}\n\nfunc (creator *clone) cloneCreateCache() (string, error) {\n\tif err := creator.cloneRepo(creator.cachePath()); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn creator.cachePath(), nil\n}\n\nfunc (creator *clone) cloneNoCache() (string, error) {\n\tuuid, err := nextUUID()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tclonePath := fmt.Sprintf(\"%s\/%s\/%s\", creator.workdir, creator.Account, uuid)\n\n\tif err = creator.cloneRepo(clonePath); err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn clonePath, nil\n}\n\nfunc (creator *clone) cloneRepo(dest string) error {\n\trepoURL := &url.URL{\n\t\tScheme: \"https\",\n\t\tHost: \"github.com\",\n\t\tPath: fmt.Sprintf(\"%s\/%s\", creator.Account, creator.Repo),\n\t}\n\n\tif creator.APIToken != \"\" {\n\t\trepoURL.User = url.User(creator.APIToken)\n\t}\n\n\tvar cloneCmd *exec.Cmd\n\n\tif creator.Depth == \"\" {\n\t\tcloneCmd = exec.Command(\n\t\t\t\"git\", \"clone\",\n\t\t\t\"--quiet\",\n\t\t\trepoURL.String(),\n\t\t\tdest,\n\t\t)\n\t} else {\n\t\tcloneCmd = exec.Command(\n\t\t\t\"git\", \"clone\",\n\t\t\t\"--quiet\",\n\t\t\t\"--depth\", creator.Depth,\n\t\t\trepoURL.String(),\n\t\t\tdest,\n\t\t)\n\t}\n\n\tif err := cloneCmd.Run(); err != nil {\n\t\treturn err\n\t}\n\n\tgit, err := fileutils.Which(\"git\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcheckoutCmd := &exec.Cmd{\n\t\tPath: git,\n\t\tDir: dest,\n\t\tArgs: []string{\"git\", \"checkout\", \"--force\", \"--quiet\", creator.Ref},\n\t}\n\n\tif err := checkoutCmd.Run(); err != nil {\n\t\tfmt.Printf(\"GOT HERE, err = %q, dest = %q\\n\", err, dest)\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (creator *clone) updateToRef(dest string) error {\n\t\/*\n\t\tworkflow as follows:\n\t\t\tgit reset --hard\n\t\t\tgit clean -df\n\t\t\tgit fetch\n\t\t\tgit checkout -f \n\t\t\tgit symbolic-ref HEAD || git pull --rebase\n\t*\/\n\tgit, err := fileutils.Which(\"git\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmds := []*exec.Cmd{\n\t\t&exec.Cmd{\n\t\t\tPath: git,\n\t\t\tDir: dest,\n\t\t\tArgs: []string{\"git\", \"reset\", \"--hard\", \"--quiet\"},\n\t\t},\n\t\t&exec.Cmd{\n\t\t\tPath: git,\n\t\t\tDir: dest,\n\t\t\tArgs: []string{\"git\", \"clean\", \"-d\", \"--force\", \"--quiet\"},\n\t\t},\n\t\t&exec.Cmd{\n\t\t\tPath: git,\n\t\t\tDir: dest,\n\t\t\tArgs: []string{\"git\", \"fetch\", \"--prune\", \"--quiet\"},\n\t\t},\n\t\t&exec.Cmd{\n\t\t\tPath: git,\n\t\t\tDir: dest,\n\t\t\tArgs: []string{\"git\", \"checkout\", \"--force\", \"--quiet\", creator.Ref},\n\t\t},\n\t}\n\n\tfor _, cmd := range cmds {\n\t\tif err := cmd.Run(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tdetectBranch := &exec.Cmd{\n\t\tPath: git,\n\t\tDir: dest,\n\t\tArgs: []string{\"git\", \"symbolic-ref\", \"--quiet\", \"HEAD\"},\n\t}\n\n\t\/\/ no error => we are on a proper branch (as opposed to a detached HEAD)\n\tif err := detectBranch.Run(); err == nil {\n\t\tpullRebase := &exec.Cmd{\n\t\t\tPath: git,\n\t\t\tDir: dest,\n\t\t\tArgs: []string{\"git\", \"pull\", \"--rebase\", \"--quiet\"},\n\t\t}\n\n\t\tif err = pullRebase.Run(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n<|endoftext|>"} {"text":"package zenodb\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"math\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"sync\/atomic\"\n\t\"time\"\n\n\t\"github.com\/getlantern\/bytemap\"\n\t\"github.com\/getlantern\/mtime\"\n\t\"github.com\/getlantern\/zenodb\/common\"\n\t\"github.com\/getlantern\/zenodb\/core\"\n\t\"github.com\/getlantern\/zenodb\/planner\"\n)\n\nvar (\n\tErrMissingQueryHandler = errors.New(\"Missing query handler for partition\")\n)\n\nfunc (db *DB) RegisterQueryHandler(partition int, query planner.QueryClusterFN) {\n\tdb.tablesMutex.Lock()\n\thandlersCh := db.remoteQueryHandlers[partition]\n\tif handlersCh == nil {\n\t\thandlersCh = make(chan planner.QueryClusterFN, db.opts.ClusterQueryConcurrency)\n\t}\n\tdb.remoteQueryHandlers[partition] = handlersCh\n\tdb.tablesMutex.Unlock()\n\thandlersCh <- query\n}\n\nfunc (db *DB) remoteQueryHandlerForPartition(partition int) planner.QueryClusterFN {\n\tdb.tablesMutex.RLock()\n\tdefer db.tablesMutex.RUnlock()\n\tselect {\n\tcase handler := <-db.remoteQueryHandlers[partition]:\n\t\treturn handler\n\tdefault:\n\t\treturn nil\n\t}\n}\n\nfunc (db *DB) queryForRemote(ctx context.Context, sqlString string, isSubQuery bool, subQueryResults [][]interface{}, unflat bool, onFields core.OnFields, onRow core.OnRow, onFlatRow core.OnFlatRow) (result interface{}, err error) {\n\tsource, prepareErr := db.Query(sqlString, isSubQuery, subQueryResults, common.ShouldIncludeMemStore(ctx))\n\tif prepareErr != nil {\n\t\tlog.Errorf(\"Error on preparing query for remote: %v\", prepareErr)\n\t\treturn nil, prepareErr\n\t}\n\telapsed := mtime.Stopwatch()\n\tdefer func() {\n\t\tlog.Debugf(\"Processed query in %v, error?: %v : %v\", elapsed(), err, sqlString)\n\t}()\n\tif unflat {\n\t\tresult, err = core.UnflattenOptimized(source).Iterate(ctx, onFields, onRow)\n\t} else {\n\t\tresult, err = source.Iterate(ctx, onFields, onFlatRow)\n\t}\n\treturn\n}\n\ntype remoteResult struct {\n\tpartition int\n\tfields core.Fields\n\tkey bytemap.ByteMap\n\tvals core.Vals\n\tflatRow *core.FlatRow\n\ttotalRows int\n\telapsed time.Duration\n\thighWaterMark int64\n\terr error\n}\n\nfunc (db *DB) queryCluster(ctx context.Context, sqlString string, isSubQuery bool, subQueryResults [][]interface{}, includeMemStore bool, unflat bool, onFields core.OnFields, onRow core.OnRow, onFlatRow core.OnFlatRow) (interface{}, error) {\n\tctx = common.WithIncludeMemStore(ctx, includeMemStore)\n\tnumPartitions := db.opts.NumPartitions\n\tresults := make(chan *remoteResult, numPartitions*100000) \/\/ TODO: make this tunable\n\tresultsByPartition := make(map[int]*int64)\n\n\tstats := &common.QueryStats{NumPartitions: numPartitions}\n\tmissingPartitions := make(map[int]bool, numPartitions)\n\tvar _finalErr error\n\tvar finalMx sync.RWMutex\n\n\tfinalStats := func() *common.QueryStats {\n\t\tfinalMx.RLock()\n\t\tdefer finalMx.RUnlock()\n\t\tmps := make([]string, 0, len(missingPartitions))\n\t\tfor partition := range missingPartitions {\n\t\t\tmps = append(mps, strconv.Itoa(partition))\n\t\t}\n\t\tstats.MissingPartitions = strings.Join(mps, \",\")\n\t\treturn stats\n\t}\n\n\tfinalErr := func() error {\n\t\tfinalMx.RLock()\n\t\tdefer finalMx.RUnlock()\n\t\tresult := _finalErr\n\t\treturn result\n\t}\n\n\tfail := func(partition int, err error) {\n\t\tfinalMx.Lock()\n\t\tdefer finalMx.Unlock()\n\t\tif _finalErr != nil {\n\t\t\t_finalErr = err\n\t\t}\n\t\tmissingPartitions[partition] = true\n\t}\n\n\tfinish := func(result *remoteResult) {\n\t\tfinalMx.Lock()\n\t\tdefer finalMx.Unlock()\n\t\tif result.err == nil {\n\t\t\tstats.NumSuccessfulPartitions++\n\t\t\tif stats.LowestHighWaterMark == 0 || stats.LowestHighWaterMark > result.highWaterMark {\n\t\t\t\tstats.LowestHighWaterMark = result.highWaterMark\n\t\t\t}\n\t\t\tif stats.HighestHighWaterMark < result.highWaterMark {\n\t\t\t\tstats.HighestHighWaterMark = result.highWaterMark\n\t\t\t}\n\t\t}\n\t}\n\n\t_stopped := int64(0)\n\tstopped := func() bool {\n\t\treturn atomic.LoadInt64(&_stopped) == 1\n\t}\n\tstop := func() {\n\t\tatomic.StoreInt64(&_stopped, 1)\n\t}\n\n\tsubCtx := ctx\n\tctxDeadline, ctxHasDeadline := subCtx.Deadline()\n\tif ctxHasDeadline {\n\t\t\/\/ Halve timeout for sub-contexts\n\t\tnow := time.Now()\n\t\ttimeout := ctxDeadline.Sub(now)\n\t\tvar cancel context.CancelFunc\n\t\tctxDeadline = now.Add(timeout \/ 2)\n\t\tsubCtx, cancel = context.WithDeadline(subCtx, ctxDeadline)\n\t\tdefer cancel()\n\t}\n\n\tfor i := 0; i < numPartitions; i++ {\n\t\tpartition := i\n\t\t_resultsForPartition := int64(0)\n\t\tresultsForPartition := &_resultsForPartition\n\t\tresultsByPartition[partition] = resultsForPartition\n\t\tgo func() {\n\t\t\tfor attempt := 0; attempt < 10; attempt++ {\n\t\t\t\telapsed := mtime.Stopwatch()\n\t\t\t\tquery := db.remoteQueryHandlerForPartition(partition)\n\t\t\t\tif query == nil {\n\t\t\t\t\tlog.Errorf(\"No query handler for partition %d, ignoring\", partition)\n\t\t\t\t\tresults <- &remoteResult{\n\t\t\t\t\t\tpartition: partition,\n\t\t\t\t\t\ttotalRows: 0,\n\t\t\t\t\t\telapsed: elapsed(),\n\t\t\t\t\t\terr: ErrMissingQueryHandler,\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tvar partOnRow func(key bytemap.ByteMap, vals core.Vals) (bool, error)\n\t\t\t\tvar partOnFlatRow func(row *core.FlatRow) (bool, error)\n\t\t\t\tif unflat {\n\t\t\t\t\tpartOnRow = func(key bytemap.ByteMap, vals core.Vals) (bool, error) {\n\t\t\t\t\t\terr := finalErr()\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn false, err\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif stopped() {\n\t\t\t\t\t\t\treturn false, nil\n\t\t\t\t\t\t}\n\t\t\t\t\t\tresults <- &remoteResult{\n\t\t\t\t\t\t\tpartition: partition,\n\t\t\t\t\t\t\tkey: key,\n\t\t\t\t\t\t\tvals: vals,\n\t\t\t\t\t\t}\n\t\t\t\t\t\tatomic.AddInt64(resultsForPartition, 1)\n\t\t\t\t\t\treturn true, nil\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tpartOnFlatRow = func(row *core.FlatRow) (bool, error) {\n\t\t\t\t\t\terr := finalErr()\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn false, err\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif stopped() {\n\t\t\t\t\t\t\treturn false, nil\n\t\t\t\t\t\t}\n\t\t\t\t\t\tresults <- &remoteResult{\n\t\t\t\t\t\t\tpartition: partition,\n\t\t\t\t\t\t\tflatRow: row,\n\t\t\t\t\t\t}\n\t\t\t\t\t\tatomic.AddInt64(resultsForPartition, 1)\n\t\t\t\t\t\treturn true, nil\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tqstats, err := query(subCtx, sqlString, isSubQuery, subQueryResults, unflat, func(fields core.Fields) error {\n\t\t\t\t\tresults <- &remoteResult{\n\t\t\t\t\t\tpartition: partition,\n\t\t\t\t\t\tfields: fields,\n\t\t\t\t\t}\n\t\t\t\t\treturn nil\n\t\t\t\t}, partOnRow, partOnFlatRow)\n\t\t\t\tif err != nil {\n\t\t\t\t\tswitch err.(type) {\n\t\t\t\t\tcase common.Retriable:\n\t\t\t\t\t\twait := time.Duration(math.Pow(1.5, float64(attempt))) * time.Second\n\t\t\t\t\t\tlog.Debugf(\"Failed on partition %d but error is retriable, continuing after %v: %v\", partition, wait, err)\n\t\t\t\t\t\ttime.Sleep(wait)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tlog.Debugf(\"Failed on partition %d and error is not retriable, will abort: %v\", partition, err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tvar highWaterMark int64\n\t\t\t\tqs, ok := qstats.(*common.QueryStats)\n\t\t\t\tif ok && qs != nil {\n\t\t\t\t\thighWaterMark = qs.HighestHighWaterMark\n\t\t\t\t}\n\t\t\t\tresults <- &remoteResult{\n\t\t\t\t\tpartition: partition,\n\t\t\t\t\ttotalRows: int(atomic.LoadInt64(resultsForPartition)),\n\t\t\t\t\telapsed: elapsed(),\n\t\t\t\t\thighWaterMark: highWaterMark,\n\t\t\t\t\terr: err,\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}()\n\t}\n\n\tstart := time.Now()\n\tdeadline := start.Add(db.opts.ClusterQueryTimeout)\n\tif ctxHasDeadline {\n\t\tdeadline = ctxDeadline\n\t}\n\tlog.Debugf(\"Deadline for results from partitions: %v (T - %v)\", deadline, deadline.Sub(time.Now()))\n\n\ttimeout := time.NewTimer(deadline.Sub(time.Now()))\n\tvar canonicalFields core.Fields\n\tfieldsByPartition := make([]core.Fields, db.opts.NumPartitions)\n\tpartitionRowMappers := make([]func(core.Vals) core.Vals, db.opts.NumPartitions)\n\tresultCount := 0\n\tfor pendingPartitions := numPartitions; pendingPartitions > 0; {\n\t\tselect {\n\t\tcase result := <-results:\n\t\t\t\/\/ first handle fields\n\t\t\tpartitionFields := result.fields\n\t\t\tif partitionFields != nil {\n\t\t\t\tif canonicalFields == nil {\n\t\t\t\t\tlog.Debugf(\"fields: %v\", partitionFields)\n\t\t\t\t\terr := onFields(partitionFields)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tfail(result.partition, err)\n\t\t\t\t\t}\n\t\t\t\t\tcanonicalFields = partitionFields\n\t\t\t\t}\n\n\t\t\t\t\/\/ Each partition can theoretically have different field definitions.\n\t\t\t\t\/\/ To accomodate this, we track the fields separate for each partition\n\t\t\t\t\/\/ and convert into the canonical form before sending onward.\n\t\t\t\tfieldsByPartition[result.partition] = partitionFields\n\t\t\t\tpartitionRowMappers[result.partition] = partitionRowMapper(canonicalFields, partitionFields)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ handle unflat rows\n\t\t\tif result.key != nil {\n\t\t\t\tif stopped() || finalErr() != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tmore, err := onRow(result.key, partitionRowMappers[result.partition](result.vals))\n\t\t\t\tif err == nil && !more {\n\t\t\t\t\tfail(result.partition, err)\n\t\t\t\t\tstop()\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ handle flat rows\n\t\t\tflatRow := result.flatRow\n\t\t\tif flatRow != nil {\n\t\t\t\tif stopped() || finalErr() != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tflatRow.SetFields(fieldsByPartition[result.partition])\n\t\t\t\tmore, err := onFlatRow(flatRow)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfail(result.partition, err)\n\t\t\t\t\treturn finalStats(), err\n\t\t\t\t} else if !more {\n\t\t\t\t\tstop()\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ final results for partition\n\t\t\tresultCount++\n\t\t\tpendingPartitions--\n\t\t\tif result.err != nil {\n\t\t\t\tlog.Errorf(\"Error from partition %d: %v\", result.partition, result.err)\n\t\t\t\tfail(result.partition, result.err)\n\t\t\t}\n\t\t\tfinish(result)\n\t\t\tlog.Debugf(\"%d\/%d got %d results from partition %d in %v\", resultCount, db.opts.NumPartitions, result.totalRows, result.partition, result.elapsed)\n\t\t\tdelete(resultsByPartition, result.partition)\n\t\tcase <-timeout.C:\n\t\t\tlog.Errorf(\"Failed to get results by deadline, %d of %d partitions reporting\", resultCount, numPartitions)\n\t\t\tmsg := bytes.NewBuffer([]byte(\"Missing partitions: \"))\n\t\t\tfirst := true\n\t\t\tfor partition, results := range resultsByPartition {\n\t\t\t\tif !first {\n\t\t\t\t\tmsg.WriteString(\" | \")\n\t\t\t\t}\n\t\t\t\tfirst = false\n\t\t\t\tmsg.WriteString(fmt.Sprintf(\"%d (%d)\", partition, results))\n\t\t\t\tfail(partition, core.ErrDeadlineExceeded)\n\t\t\t}\n\t\t\tlog.Debug(msg.String())\n\t\t\treturn finalStats(), finalErr()\n\t\t}\n\t}\n\n\treturn finalStats(), finalErr()\n}\n\nfunc partitionRowMapper(canonicalFields core.Fields, partitionFields core.Fields) func(core.Vals) core.Vals {\n\tif canonicalFields.Equals(partitionFields) {\n\t\treturn func(vals core.Vals) core.Vals { return vals }\n\t}\n\n\tscratch := make(core.Vals, len(canonicalFields))\n\tidxs := make([]int, 0, len(canonicalFields))\n\tfor _, canonicalField := range canonicalFields {\n\t\ti := -1\n\t\tfor _i, partitionField := range partitionFields {\n\t\t\tif canonicalField.Equals(partitionField) {\n\t\t\t\ti = _i\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tidxs = append(idxs, i)\n\t}\n\n\treturn func(vals core.Vals) core.Vals {\n\t\tfor o, i := range idxs {\n\t\t\tif i < 0 || i >= len(vals) {\n\t\t\t\tscratch[o] = nil\n\t\t\t} else {\n\t\t\t\tscratch[o] = vals[i]\n\t\t\t}\n\t\t}\n\n\t\tfor i := range vals {\n\t\t\tvals[i] = scratch[i]\n\t\t}\n\n\t\treturn vals\n\t}\n}\nTook out exponential backoff on retries in querying clusterpackage zenodb\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"sync\/atomic\"\n\t\"time\"\n\n\t\"github.com\/getlantern\/bytemap\"\n\t\"github.com\/getlantern\/mtime\"\n\t\"github.com\/getlantern\/zenodb\/common\"\n\t\"github.com\/getlantern\/zenodb\/core\"\n\t\"github.com\/getlantern\/zenodb\/planner\"\n)\n\nvar (\n\tErrMissingQueryHandler = errors.New(\"Missing query handler for partition\")\n)\n\nfunc (db *DB) RegisterQueryHandler(partition int, query planner.QueryClusterFN) {\n\tdb.tablesMutex.Lock()\n\thandlersCh := db.remoteQueryHandlers[partition]\n\tif handlersCh == nil {\n\t\thandlersCh = make(chan planner.QueryClusterFN, db.opts.ClusterQueryConcurrency)\n\t}\n\tdb.remoteQueryHandlers[partition] = handlersCh\n\tdb.tablesMutex.Unlock()\n\thandlersCh <- query\n}\n\nfunc (db *DB) remoteQueryHandlerForPartition(partition int) planner.QueryClusterFN {\n\tdb.tablesMutex.RLock()\n\tdefer db.tablesMutex.RUnlock()\n\tselect {\n\tcase handler := <-db.remoteQueryHandlers[partition]:\n\t\treturn handler\n\tdefault:\n\t\treturn nil\n\t}\n}\n\nfunc (db *DB) queryForRemote(ctx context.Context, sqlString string, isSubQuery bool, subQueryResults [][]interface{}, unflat bool, onFields core.OnFields, onRow core.OnRow, onFlatRow core.OnFlatRow) (result interface{}, err error) {\n\tsource, prepareErr := db.Query(sqlString, isSubQuery, subQueryResults, common.ShouldIncludeMemStore(ctx))\n\tif prepareErr != nil {\n\t\tlog.Errorf(\"Error on preparing query for remote: %v\", prepareErr)\n\t\treturn nil, prepareErr\n\t}\n\telapsed := mtime.Stopwatch()\n\tdefer func() {\n\t\tlog.Debugf(\"Processed query in %v, error?: %v : %v\", elapsed(), err, sqlString)\n\t}()\n\tif unflat {\n\t\tresult, err = core.UnflattenOptimized(source).Iterate(ctx, onFields, onRow)\n\t} else {\n\t\tresult, err = source.Iterate(ctx, onFields, onFlatRow)\n\t}\n\treturn\n}\n\ntype remoteResult struct {\n\tpartition int\n\tfields core.Fields\n\tkey bytemap.ByteMap\n\tvals core.Vals\n\tflatRow *core.FlatRow\n\ttotalRows int\n\telapsed time.Duration\n\thighWaterMark int64\n\terr error\n}\n\nfunc (db *DB) queryCluster(ctx context.Context, sqlString string, isSubQuery bool, subQueryResults [][]interface{}, includeMemStore bool, unflat bool, onFields core.OnFields, onRow core.OnRow, onFlatRow core.OnFlatRow) (interface{}, error) {\n\tctx = common.WithIncludeMemStore(ctx, includeMemStore)\n\tnumPartitions := db.opts.NumPartitions\n\tresults := make(chan *remoteResult, numPartitions*100000) \/\/ TODO: make this tunable\n\tresultsByPartition := make(map[int]*int64)\n\n\tstats := &common.QueryStats{NumPartitions: numPartitions}\n\tmissingPartitions := make(map[int]bool, numPartitions)\n\tvar _finalErr error\n\tvar finalMx sync.RWMutex\n\n\tfinalStats := func() *common.QueryStats {\n\t\tfinalMx.RLock()\n\t\tdefer finalMx.RUnlock()\n\t\tmps := make([]string, 0, len(missingPartitions))\n\t\tfor partition := range missingPartitions {\n\t\t\tmps = append(mps, strconv.Itoa(partition))\n\t\t}\n\t\tstats.MissingPartitions = strings.Join(mps, \",\")\n\t\treturn stats\n\t}\n\n\tfinalErr := func() error {\n\t\tfinalMx.RLock()\n\t\tdefer finalMx.RUnlock()\n\t\tresult := _finalErr\n\t\treturn result\n\t}\n\n\tfail := func(partition int, err error) {\n\t\tfinalMx.Lock()\n\t\tdefer finalMx.Unlock()\n\t\tif _finalErr != nil {\n\t\t\t_finalErr = err\n\t\t}\n\t\tmissingPartitions[partition] = true\n\t}\n\n\tfinish := func(result *remoteResult) {\n\t\tfinalMx.Lock()\n\t\tdefer finalMx.Unlock()\n\t\tif result.err == nil {\n\t\t\tstats.NumSuccessfulPartitions++\n\t\t\tif stats.LowestHighWaterMark == 0 || stats.LowestHighWaterMark > result.highWaterMark {\n\t\t\t\tstats.LowestHighWaterMark = result.highWaterMark\n\t\t\t}\n\t\t\tif stats.HighestHighWaterMark < result.highWaterMark {\n\t\t\t\tstats.HighestHighWaterMark = result.highWaterMark\n\t\t\t}\n\t\t}\n\t}\n\n\t_stopped := int64(0)\n\tstopped := func() bool {\n\t\treturn atomic.LoadInt64(&_stopped) == 1\n\t}\n\tstop := func() {\n\t\tatomic.StoreInt64(&_stopped, 1)\n\t}\n\n\tsubCtx := ctx\n\tctxDeadline, ctxHasDeadline := subCtx.Deadline()\n\tif ctxHasDeadline {\n\t\t\/\/ Halve timeout for sub-contexts\n\t\tnow := time.Now()\n\t\ttimeout := ctxDeadline.Sub(now)\n\t\tvar cancel context.CancelFunc\n\t\tctxDeadline = now.Add(timeout \/ 2)\n\t\tsubCtx, cancel = context.WithDeadline(subCtx, ctxDeadline)\n\t\tdefer cancel()\n\t}\n\n\tfor i := 0; i < numPartitions; i++ {\n\t\tpartition := i\n\t\t_resultsForPartition := int64(0)\n\t\tresultsForPartition := &_resultsForPartition\n\t\tresultsByPartition[partition] = resultsForPartition\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\telapsed := mtime.Stopwatch()\n\t\t\t\tquery := db.remoteQueryHandlerForPartition(partition)\n\t\t\t\tif query == nil {\n\t\t\t\t\tlog.Errorf(\"No query handler for partition %d, ignoring\", partition)\n\t\t\t\t\tresults <- &remoteResult{\n\t\t\t\t\t\tpartition: partition,\n\t\t\t\t\t\ttotalRows: 0,\n\t\t\t\t\t\telapsed: elapsed(),\n\t\t\t\t\t\terr: ErrMissingQueryHandler,\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tvar partOnRow func(key bytemap.ByteMap, vals core.Vals) (bool, error)\n\t\t\t\tvar partOnFlatRow func(row *core.FlatRow) (bool, error)\n\t\t\t\tif unflat {\n\t\t\t\t\tpartOnRow = func(key bytemap.ByteMap, vals core.Vals) (bool, error) {\n\t\t\t\t\t\terr := finalErr()\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn false, err\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif stopped() {\n\t\t\t\t\t\t\treturn false, nil\n\t\t\t\t\t\t}\n\t\t\t\t\t\tresults <- &remoteResult{\n\t\t\t\t\t\t\tpartition: partition,\n\t\t\t\t\t\t\tkey: key,\n\t\t\t\t\t\t\tvals: vals,\n\t\t\t\t\t\t}\n\t\t\t\t\t\tatomic.AddInt64(resultsForPartition, 1)\n\t\t\t\t\t\treturn true, nil\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tpartOnFlatRow = func(row *core.FlatRow) (bool, error) {\n\t\t\t\t\t\terr := finalErr()\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn false, err\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif stopped() {\n\t\t\t\t\t\t\treturn false, nil\n\t\t\t\t\t\t}\n\t\t\t\t\t\tresults <- &remoteResult{\n\t\t\t\t\t\t\tpartition: partition,\n\t\t\t\t\t\t\tflatRow: row,\n\t\t\t\t\t\t}\n\t\t\t\t\t\tatomic.AddInt64(resultsForPartition, 1)\n\t\t\t\t\t\treturn true, nil\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tqstats, err := query(subCtx, sqlString, isSubQuery, subQueryResults, unflat, func(fields core.Fields) error {\n\t\t\t\t\tresults <- &remoteResult{\n\t\t\t\t\t\tpartition: partition,\n\t\t\t\t\t\tfields: fields,\n\t\t\t\t\t}\n\t\t\t\t\treturn nil\n\t\t\t\t}, partOnRow, partOnFlatRow)\n\t\t\t\tif err != nil {\n\t\t\t\t\tswitch err.(type) {\n\t\t\t\t\tcase common.Retriable:\n\t\t\t\t\t\tlog.Debugf(\"Failed on partition %d but error is retriable, continuing: %v\", partition, err)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tlog.Debugf(\"Failed on partition %d and error is not retriable, will abort: %v\", partition, err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tvar highWaterMark int64\n\t\t\t\tqs, ok := qstats.(*common.QueryStats)\n\t\t\t\tif ok && qs != nil {\n\t\t\t\t\thighWaterMark = qs.HighestHighWaterMark\n\t\t\t\t}\n\t\t\t\tresults <- &remoteResult{\n\t\t\t\t\tpartition: partition,\n\t\t\t\t\ttotalRows: int(atomic.LoadInt64(resultsForPartition)),\n\t\t\t\t\telapsed: elapsed(),\n\t\t\t\t\thighWaterMark: highWaterMark,\n\t\t\t\t\terr: err,\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}()\n\t}\n\n\tstart := time.Now()\n\tdeadline := start.Add(db.opts.ClusterQueryTimeout)\n\tif ctxHasDeadline {\n\t\tdeadline = ctxDeadline\n\t}\n\tlog.Debugf(\"Deadline for results from partitions: %v (T - %v)\", deadline, deadline.Sub(time.Now()))\n\n\ttimeout := time.NewTimer(deadline.Sub(time.Now()))\n\tvar canonicalFields core.Fields\n\tfieldsByPartition := make([]core.Fields, db.opts.NumPartitions)\n\tpartitionRowMappers := make([]func(core.Vals) core.Vals, db.opts.NumPartitions)\n\tresultCount := 0\n\tfor pendingPartitions := numPartitions; pendingPartitions > 0; {\n\t\tselect {\n\t\tcase result := <-results:\n\t\t\t\/\/ first handle fields\n\t\t\tpartitionFields := result.fields\n\t\t\tif partitionFields != nil {\n\t\t\t\tif canonicalFields == nil {\n\t\t\t\t\tlog.Debugf(\"fields: %v\", partitionFields)\n\t\t\t\t\terr := onFields(partitionFields)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tfail(result.partition, err)\n\t\t\t\t\t}\n\t\t\t\t\tcanonicalFields = partitionFields\n\t\t\t\t}\n\n\t\t\t\t\/\/ Each partition can theoretically have different field definitions.\n\t\t\t\t\/\/ To accomodate this, we track the fields separate for each partition\n\t\t\t\t\/\/ and convert into the canonical form before sending onward.\n\t\t\t\tfieldsByPartition[result.partition] = partitionFields\n\t\t\t\tpartitionRowMappers[result.partition] = partitionRowMapper(canonicalFields, partitionFields)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ handle unflat rows\n\t\t\tif result.key != nil {\n\t\t\t\tif stopped() || finalErr() != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tmore, err := onRow(result.key, partitionRowMappers[result.partition](result.vals))\n\t\t\t\tif err == nil && !more {\n\t\t\t\t\tfail(result.partition, err)\n\t\t\t\t\tstop()\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ handle flat rows\n\t\t\tflatRow := result.flatRow\n\t\t\tif flatRow != nil {\n\t\t\t\tif stopped() || finalErr() != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tflatRow.SetFields(fieldsByPartition[result.partition])\n\t\t\t\tmore, err := onFlatRow(flatRow)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfail(result.partition, err)\n\t\t\t\t\treturn finalStats(), err\n\t\t\t\t} else if !more {\n\t\t\t\t\tstop()\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ final results for partition\n\t\t\tresultCount++\n\t\t\tpendingPartitions--\n\t\t\tif result.err != nil {\n\t\t\t\tlog.Errorf(\"Error from partition %d: %v\", result.partition, result.err)\n\t\t\t\tfail(result.partition, result.err)\n\t\t\t}\n\t\t\tfinish(result)\n\t\t\tlog.Debugf(\"%d\/%d got %d results from partition %d in %v\", resultCount, db.opts.NumPartitions, result.totalRows, result.partition, result.elapsed)\n\t\t\tdelete(resultsByPartition, result.partition)\n\t\tcase <-timeout.C:\n\t\t\tlog.Errorf(\"Failed to get results by deadline, %d of %d partitions reporting\", resultCount, numPartitions)\n\t\t\tmsg := bytes.NewBuffer([]byte(\"Missing partitions: \"))\n\t\t\tfirst := true\n\t\t\tfor partition, results := range resultsByPartition {\n\t\t\t\tif !first {\n\t\t\t\t\tmsg.WriteString(\" | \")\n\t\t\t\t}\n\t\t\t\tfirst = false\n\t\t\t\tmsg.WriteString(fmt.Sprintf(\"%d (%d)\", partition, results))\n\t\t\t\tfail(partition, core.ErrDeadlineExceeded)\n\t\t\t}\n\t\t\tlog.Debug(msg.String())\n\t\t\treturn finalStats(), finalErr()\n\t\t}\n\t}\n\n\treturn finalStats(), finalErr()\n}\n\nfunc partitionRowMapper(canonicalFields core.Fields, partitionFields core.Fields) func(core.Vals) core.Vals {\n\tif canonicalFields.Equals(partitionFields) {\n\t\treturn func(vals core.Vals) core.Vals { return vals }\n\t}\n\n\tscratch := make(core.Vals, len(canonicalFields))\n\tidxs := make([]int, 0, len(canonicalFields))\n\tfor _, canonicalField := range canonicalFields {\n\t\ti := -1\n\t\tfor _i, partitionField := range partitionFields {\n\t\t\tif canonicalField.Equals(partitionField) {\n\t\t\t\ti = _i\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tidxs = append(idxs, i)\n\t}\n\n\treturn func(vals core.Vals) core.Vals {\n\t\tfor o, i := range idxs {\n\t\t\tif i < 0 || i >= len(vals) {\n\t\t\t\tscratch[o] = nil\n\t\t\t} else {\n\t\t\t\tscratch[o] = vals[i]\n\t\t\t}\n\t\t}\n\n\t\tfor i := range vals {\n\t\t\tvals[i] = scratch[i]\n\t\t}\n\n\t\treturn vals\n\t}\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"path\"\n\t\"time\"\n\n\t\"github.com\/PonyvilleFM\/aura\/bot\"\n\t\"github.com\/PonyvilleFM\/aura\/recording\"\n\t\"github.com\/bwmarrin\/discordgo\"\n\t_ \"github.com\/joho\/godotenv\/autoload\"\n)\n\ntype aura struct {\n\tcs *bot.CommandSet\n\ts *discordgo.Session\n\n\tguildRecordings map[string]*recording.Recording\n\tstate *state\n}\n\ntype state struct {\n\tDownloadURLs map[string]string \/\/ Guild ID -> URL\n\tPermRoles map[string]string \/\/ Guild ID -> needed role ID\n}\n\nfunc (s *state) Save() error {\n\tfout, err := os.Create(path.Join(dataPrefix, \"state.json\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fout.Close()\n\n\treturn json.NewEncoder(fout).Encode(s)\n}\n\nfunc (s *state) Load() error {\n\tfin, err := os.Open(path.Join(dataPrefix, \"state.json\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fin.Close()\n\n\treturn json.NewDecoder(fin).Decode(s)\n}\n\nconst (\n\tdjonHelp = ``\n\tdjoffHelp = ``\n\tsetupHelp = ``\n)\n\nfunc (a *aura) Permissons(s *discordgo.Session, m *discordgo.Message, parv []string) error {\n\tch, err := s.Channel(m.ChannelID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgid := ch.GuildID\n\trole := a.state.PermRoles[gid]\n\n\tgu, err := s.GuildMember(gid, m.Author.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfound := false\n\tfor _, r := range gu.Roles {\n\t\tif r == role {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !found {\n\t\treturn errors.New(\"aura: no permissions\")\n\t}\n\n\treturn nil\n}\n\nfunc (a *aura) roles(s *discordgo.Session, m *discordgo.Message, parv []string) error {\n\tlog.Println(\"got here\")\n\tch, err := s.Channel(m.ChannelID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgid := ch.GuildID\n\n\tresult := \"Roles in this group:\\n\"\n\n\troles, err := s.GuildRoles(gid)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, r := range roles {\n\t\tresult += fmt.Sprintf(\"- %s: %s\\n\", r.ID, r.Name)\n\t}\n\n\ts.ChannelMessageSend(m.ChannelID, result)\n\treturn nil\n}\n\nfunc (a *aura) setup(s *discordgo.Session, m *discordgo.Message, parv []string) error {\n\tif len(parv) != 3 {\n\t\treturn errors.New(\"aura: wrong number of params for setup\")\n\t}\n\n\trole := parv[1]\n\turl := parv[2]\n\n\tch, err := s.Channel(m.ChannelID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgid := ch.GuildID\n\n\troles, err := s.GuildRoles(gid)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfound := false\n\tfor _, r := range roles {\n\t\tif r.ID == role {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !found {\n\t\treturn errors.New(\"aura: Role not found\")\n\t}\n\n\ta.state.PermRoles[gid] = role\n\ta.state.DownloadURLs[gid] = url\n\n\ts.ChannelMessageSend(m.ChannelID, fmt.Sprintf(\"Guild %s set up for recording url %s controlled by role %s\", gid, url, role))\n\n\ta.state.Save()\n\treturn nil\n}\n\nfunc (a *aura) djon(s *discordgo.Session, m *discordgo.Message, parv []string) error {\n\tfname := fmt.Sprintf(\"%s - %s.mp3\", m.Author.Username, time.Now().Format(time.ANSIC))\n\n\tch, err := s.Channel(m.ChannelID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgid := ch.GuildID\n\n\t_, ok := a.guildRecordings[gid]\n\tif ok {\n\t\treturn errors.New(\"aura: another recording is already in progress\")\n\t}\n\n\tr, err := recording.New(a.state.DownloadURLs[gid], path.Join(dataPrefix, fname))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ta.guildRecordings[gid] = r\n\tgo r.Start()\n\n\ts.ChannelMessageSend(m.ChannelID, fmt.Sprintf(\"Now recording: %s\", fname))\n\n\treturn nil\n}\n\nfunc (a *aura) djoff(s *discordgo.Session, m *discordgo.Message, parv []string) error {\n\tch, err := s.Channel(m.ChannelID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgid := ch.GuildID\n\n\tr, ok := a.guildRecordings[gid]\n\tif !ok {\n\t\treturn errors.New(\"aura: no recording is currently in progress\")\n\t}\n\n\tr.Cancel()\n\t<-r.Done()\n\n\ts.ChannelMessageSend(m.ChannelID, fmt.Sprintf(\"Recording complete: %s\", r.OutputFilename()))\n\n\treturn nil\n}\n\nfunc (a *aura) Handle(s *discordgo.Session, m *discordgo.MessageCreate) {\n\terr := a.cs.Run(s, m.Message)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n}\n\nvar (\n\ttoken = os.Getenv(\"TOKEN\")\n\tdataPrefix = os.Getenv(\"DATA_PREFIX\")\n)\n\nfunc main() {\n\tdg, err := discordgo.New(\"Bot \" + token)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\ta := &aura{\n\t\tcs: bot.NewCommandSet(),\n\t\ts: dg,\n\t\tguildRecordings: map[string]*recording.Recording{},\n\n\t\tstate: &state{\n\t\t\tDownloadURLs: map[string]string{},\n\t\t\tPermRoles: map[string]string{},\n\t\t},\n\t}\n\n\terr = a.state.Load()\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\ta.cs.Add(bot.NewBasicCommand(\"roles\", \"\", bot.NoPermissions, a.roles))\n\ta.cs.Add(bot.NewBasicCommand(\"setup\", setupHelp, bot.NoPermissions, a.setup))\n\ta.cs.Add(bot.NewBasicCommand(\"djon\", djonHelp, a.Permissons, a.djon))\n\ta.cs.Add(bot.NewBasicCommand(\"djoff\", djoffHelp, a.Permissons, a.djoff))\n\n\tdg.AddHandler(a.Handle)\n\tdg.AddHandler(messageCreate)\n\n\terr = dg.Open()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tlog.Println(\"ready\")\n\t<-make(chan struct{})\n}\n\n\/\/ This function will be called (due to AddHandler above) every time a new\n\/\/ message is created on any channel that the autenticated bot has access to.\nfunc messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {\n\t\/\/ Print message to stdout.\n\tfmt.Printf(\"%20s %20s %20s > %s\\n\", m.ChannelID, time.Now().Format(time.Stamp), m.Author.Username, m.Content)\n}\ncmd\/aura: url-escape the filename for download announcementspackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"net\/url\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/PonyvilleFM\/aura\/bot\"\n\t\"github.com\/PonyvilleFM\/aura\/recording\"\n\t\"github.com\/bwmarrin\/discordgo\"\n\t_ \"github.com\/joho\/godotenv\/autoload\"\n)\n\ntype aura struct {\n\tcs *bot.CommandSet\n\ts *discordgo.Session\n\n\tguildRecordings map[string]*recording.Recording\n\tstate *state\n}\n\ntype state struct {\n\tDownloadURLs map[string]string \/\/ Guild ID -> URL\n\tPermRoles map[string]string \/\/ Guild ID -> needed role ID\n}\n\nfunc (s *state) Save() error {\n\tfout, err := os.Create(path.Join(dataPrefix, \"state.json\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fout.Close()\n\n\treturn json.NewEncoder(fout).Encode(s)\n}\n\nfunc (s *state) Load() error {\n\tfin, err := os.Open(path.Join(dataPrefix, \"state.json\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer fin.Close()\n\n\treturn json.NewDecoder(fin).Decode(s)\n}\n\nconst (\n\tdjonHelp = ``\n\tdjoffHelp = ``\n\tsetupHelp = ``\n)\n\nfunc (a *aura) Permissons(s *discordgo.Session, m *discordgo.Message, parv []string) error {\n\tch, err := s.Channel(m.ChannelID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgid := ch.GuildID\n\trole := a.state.PermRoles[gid]\n\n\tgu, err := s.GuildMember(gid, m.Author.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfound := false\n\tfor _, r := range gu.Roles {\n\t\tif r == role {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !found {\n\t\treturn errors.New(\"aura: no permissions\")\n\t}\n\n\treturn nil\n}\n\nfunc (a *aura) roles(s *discordgo.Session, m *discordgo.Message, parv []string) error {\n\tlog.Println(\"got here\")\n\tch, err := s.Channel(m.ChannelID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgid := ch.GuildID\n\n\tresult := \"Roles in this group:\\n\"\n\n\troles, err := s.GuildRoles(gid)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, r := range roles {\n\t\tresult += fmt.Sprintf(\"- %s: %s\\n\", r.ID, r.Name)\n\t}\n\n\ts.ChannelMessageSend(m.ChannelID, result)\n\treturn nil\n}\n\nfunc (a *aura) setup(s *discordgo.Session, m *discordgo.Message, parv []string) error {\n\tif len(parv) != 3 {\n\t\treturn errors.New(\"aura: wrong number of params for setup\")\n\t}\n\n\trole := parv[1]\n\turl := parv[2]\n\n\tch, err := s.Channel(m.ChannelID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgid := ch.GuildID\n\n\troles, err := s.GuildRoles(gid)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfound := false\n\tfor _, r := range roles {\n\t\tif r.ID == role {\n\t\t\tfound = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif !found {\n\t\treturn errors.New(\"aura: Role not found\")\n\t}\n\n\ta.state.PermRoles[gid] = role\n\ta.state.DownloadURLs[gid] = url\n\n\ts.ChannelMessageSend(m.ChannelID, fmt.Sprintf(\"Guild %s set up for recording url %s controlled by role %s\", gid, url, role))\n\n\ta.state.Save()\n\treturn nil\n}\n\nfunc (a *aura) djon(s *discordgo.Session, m *discordgo.Message, parv []string) error {\n\tfname := fmt.Sprintf(\"%s - %s.mp3\", m.Author.Username, time.Now().Format(time.ANSIC))\n\n\tch, err := s.Channel(m.ChannelID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgid := ch.GuildID\n\n\t_, ok := a.guildRecordings[gid]\n\tif ok {\n\t\treturn errors.New(\"aura: another recording is already in progress\")\n\t}\n\n\tos.Mkdir(path.Join(dataPrefix, gid), 0775)\n\n\tr, err := recording.New(a.state.DownloadURLs[gid], path.Join(dataPrefix, gid, fname))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ta.guildRecordings[gid] = r\n\tgo r.Start()\n\n\ts.ChannelMessageSend(m.ChannelID, fmt.Sprintf(\"Now recording: %s\", fname))\n\n\treturn nil\n}\n\nfunc (a *aura) djoff(s *discordgo.Session, m *discordgo.Message, parv []string) error {\n\tch, err := s.Channel(m.ChannelID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tgid := ch.GuildID\n\n\tr, ok := a.guildRecordings[gid]\n\tif !ok {\n\t\treturn errors.New(\"aura: no recording is currently in progress\")\n\t}\n\n\tr.Cancel()\n\t<-r.Done()\n\n\tfname := r.OutputFilename()\n\tparts := strings.Split(fname, \"\/\")\n\n\ts.ChannelMessageSend(m.ChannelID, fmt.Sprintf(\"Recording complete: https:\/\/pvfmrecordings.greedo.xeserv.us\/var\/%s\/%s\", parts[1], url.QueryEscape(parts[2])))\n\n\treturn nil\n}\n\nfunc (a *aura) Handle(s *discordgo.Session, m *discordgo.MessageCreate) {\n\terr := a.cs.Run(s, m.Message)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n}\n\nvar (\n\ttoken = os.Getenv(\"TOKEN\")\n\tdataPrefix = os.Getenv(\"DATA_PREFIX\")\n)\n\nfunc main() {\n\tdg, err := discordgo.New(\"Bot \" + token)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\ta := &aura{\n\t\tcs: bot.NewCommandSet(),\n\t\ts: dg,\n\t\tguildRecordings: map[string]*recording.Recording{},\n\n\t\tstate: &state{\n\t\t\tDownloadURLs: map[string]string{},\n\t\t\tPermRoles: map[string]string{},\n\t\t},\n\t}\n\n\terr = a.state.Load()\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\ta.cs.Add(bot.NewBasicCommand(\"roles\", \"\", bot.NoPermissions, a.roles))\n\ta.cs.Add(bot.NewBasicCommand(\"setup\", setupHelp, bot.NoPermissions, a.setup))\n\ta.cs.Add(bot.NewBasicCommand(\"djon\", djonHelp, a.Permissons, a.djon))\n\ta.cs.Add(bot.NewBasicCommand(\"djoff\", djoffHelp, a.Permissons, a.djoff))\n\n\tdg.AddHandler(a.Handle)\n\tdg.AddHandler(messageCreate)\n\n\terr = dg.Open()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tlog.Println(\"ready\")\n\t<-make(chan struct{})\n}\n\n\/\/ This function will be called (due to AddHandler above) every time a new\n\/\/ message is created on any channel that the autenticated bot has access to.\nfunc messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {\n\t\/\/ Print message to stdout.\n\tfmt.Printf(\"%20s %20s %20s > %s\\n\", m.ChannelID, time.Now().Format(time.Stamp), m.Author.Username, m.Content)\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2013 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ This is a blog server for articles written in present format.\n\/\/ It powers blog.golang.org.\npackage main\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"encoding\/xml\"\n\t\"fmt\"\n\t\"html\/template\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"sort\"\n\t\"time\"\n\n\t\"code.google.com\/p\/go.blog\/pkg\/atom\"\n\t_ \"code.google.com\/p\/go.talks\/pkg\/playground\"\n\t\"code.google.com\/p\/go.talks\/pkg\/present\"\n)\n\nconst (\n\thostname = \"blog.golang.org\"\n\tbaseURL = \"http:\/\/\" + hostname\n\thomeArticles = 5 \/\/ articles to display on the home page\n\tfeedArticles = 10 \/\/ articles to include in Atom and JSON feeds\n)\n\nvar validJSONPFunc = regexp.MustCompile(`(?i)^[a-z_][a-z0-9_.]*$`)\n\n\/\/ Doc represents an article, adorned with presentation data:\n\/\/ its absolute path and related articles.\ntype Doc struct {\n\t*present.Doc\n\tPermalink string\n\tPath string\n\tRelated []*Doc\n\tNewer, Older *Doc\n\tHTML template.HTML \/\/ rendered article\n}\n\n\/\/ Server implements an http.Handler that serves blog articles.\ntype Server struct {\n\tdocs []*Doc\n\ttags []string\n\tdocPaths map[string]*Doc\n\tdocTags map[string][]*Doc\n\ttemplate struct {\n\t\thome, index, article, doc *template.Template\n\t}\n\tatomFeed []byte \/\/ pre-rendered Atom feed\n\tjsonFeed []byte \/\/ pre-rendered JSON feed\n\tcontent http.Handler\n}\n\n\/\/ NewServer constructs a new Server, serving articles from the specified\n\/\/ contentPath generated from templates from templatePath.\nfunc NewServer(contentPath, templatePath string) (*Server, error) {\n\tpresent.PlayEnabled = true\n\n\troot := filepath.Join(templatePath, \"root.tmpl\")\n\tparse := func(name string) (*template.Template, error) {\n\t\tt := template.New(\"\").Funcs(funcMap)\n\t\treturn t.ParseFiles(root, filepath.Join(templatePath, name))\n\t}\n\n\ts := &Server{}\n\n\t\/\/ Parse templates.\n\tvar err error\n\ts.template.home, err = parse(\"home.tmpl\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts.template.index, err = parse(\"index.tmpl\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts.template.article, err = parse(\"article.tmpl\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tp := present.Template().Funcs(funcMap)\n\ts.template.doc, err = p.ParseFiles(filepath.Join(templatePath, \"doc.tmpl\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Load content.\n\terr = s.loadDocs(filepath.Clean(contentPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = s.renderAtomFeed()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = s.renderJSONFeed()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Set up content file server.\n\ts.content = http.FileServer(http.Dir(contentPath))\n\n\treturn s, nil\n}\n\nvar funcMap = template.FuncMap{\n\t\"sectioned\": sectioned,\n\t\"authors\": authors,\n}\n\n\/\/ sectioned returns true if the provided Doc contains more than one section.\n\/\/ This is used to control whether to display the table of contents and headings.\nfunc sectioned(d *present.Doc) bool {\n\treturn len(d.Sections) > 1\n}\n\n\/\/ authors returns a comma-separated list of author names.\nfunc authors(authors []present.Author) string {\n\tvar b bytes.Buffer\n\tlast := len(authors) - 1\n\tfor i, a := range authors {\n\t\tif i > 0 {\n\t\t\tif i == last {\n\t\t\t\tb.WriteString(\" and \")\n\t\t\t} else {\n\t\t\t\tb.WriteString(\", \")\n\t\t\t}\n\t\t}\n\t\tb.WriteString(authorName(a))\n\t}\n\treturn b.String()\n}\n\n\/\/ authorName returns the first line of the Author text: the author's name.\nfunc authorName(a present.Author) string {\n\tel := a.TextElem()\n\tif len(el) == 0 {\n\t\treturn \"\"\n\t}\n\ttext, ok := el[0].(present.Text)\n\tif !ok || len(text.Lines) == 0 {\n\t\treturn \"\"\n\t}\n\treturn text.Lines[0]\n}\n\n\/\/ loadDocs reads all content from the provided file system root, renders all\n\/\/ the articles it finds, adds them to the Server's docs field, computes the\n\/\/ denormalized docPaths, docTags, and tags fields, and populates the various\n\/\/ helper fields (Next, Previous, Related) for each Doc.\nfunc (s *Server) loadDocs(root string) error {\n\t\/\/ Read content into docs field.\n\tconst ext = \".article\"\n\tfn := func(p string, info os.FileInfo, err error) error {\n\t\tif filepath.Ext(p) != ext {\n\t\t\treturn nil\n\t\t}\n\t\tf, err := os.Open(p)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer f.Close()\n\t\td, err := present.Parse(f, p, 0)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\thtml := new(bytes.Buffer)\n\t\terr = d.Render(html, s.template.doc)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tp = p[len(root) : len(p)-len(ext)] \/\/ trim root and extension\n\t\ts.docs = append(s.docs, &Doc{\n\t\t\tDoc: d,\n\t\t\tPath: p,\n\t\t\tPermalink: baseURL + p,\n\t\t\tHTML: template.HTML(html.String()),\n\t\t})\n\t\treturn nil\n\t}\n\terr := filepath.Walk(root, fn)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsort.Sort(docsByTime(s.docs))\n\n\t\/\/ Pull out doc paths and tags and put in reverse-associating maps.\n\ts.docPaths = make(map[string]*Doc)\n\ts.docTags = make(map[string][]*Doc)\n\tfor _, d := range s.docs {\n\t\ts.docPaths[d.Path] = d\n\t\tfor _, t := range d.Tags {\n\t\t\ts.docTags[t] = append(s.docTags[t], d)\n\t\t}\n\t}\n\n\t\/\/ Pull out unique sorted list of tags.\n\tfor t := range s.docTags {\n\t\ts.tags = append(s.tags, t)\n\t}\n\tsort.Strings(s.tags)\n\n\t\/\/ Set up presentation-related fields, Newer, Older, and Related.\n\tfor _, doc := range s.docs {\n\t\t\/\/ Newer, Older: docs adjacent to doc\n\t\tfor i := range s.docs {\n\t\t\tif s.docs[i] != doc {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif i > 0 {\n\t\t\t\tdoc.Newer = s.docs[i-1]\n\t\t\t}\n\t\t\tif i+1 < len(s.docs) {\n\t\t\t\tdoc.Older = s.docs[i+1]\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\t\/\/ Related: all docs that share tags with doc.\n\t\trelated := make(map[*Doc]bool)\n\t\tfor _, t := range doc.Tags {\n\t\t\tfor _, d := range s.docTags[t] {\n\t\t\t\tif d != doc {\n\t\t\t\t\trelated[d] = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor d := range related {\n\t\t\tdoc.Related = append(doc.Related, d)\n\t\t}\n\t\tsort.Sort(docsByTime(doc.Related))\n\t}\n\n\treturn nil\n}\n\n\/\/ renderAtomFeed generates an XML Atom feed and stores it in the Server's\n\/\/ atomFeed field.\nfunc (s *Server) renderAtomFeed() error {\n\tvar updated time.Time\n\tif len(s.docs) > 1 {\n\t\tupdated = s.docs[0].Time\n\t}\n\tfeed := atom.Feed{\n\t\tTitle: \"The Go Programming Language Blog\",\n\t\tID: \"tag:\" + hostname + \",2013:\" + hostname,\n\t\tUpdated: atom.Time(updated),\n\t\tLink: []atom.Link{{\n\t\t\tRel: \"self\",\n\t\t\tHref: baseURL + \"\/feed.atom\",\n\t\t}},\n\t}\n\tfor i, doc := range s.docs {\n\t\tif i >= feedArticles {\n\t\t\tbreak\n\t\t}\n\t\te := &atom.Entry{\n\t\t\tTitle: doc.Title,\n\t\t\tID: feed.ID + doc.Path,\n\t\t\tLink: []atom.Link{{\n\t\t\t\tRel: \"alternate\",\n\t\t\t\tHref: baseURL + doc.Path,\n\t\t\t}},\n\t\t\tPublished: atom.Time(doc.Time),\n\t\t\tUpdated: atom.Time(doc.Time),\n\t\t\tSummary: &atom.Text{\n\t\t\t\tType: \"html\",\n\t\t\t\tBody: summary(doc),\n\t\t\t},\n\t\t\tContent: &atom.Text{\n\t\t\t\tType: \"html\",\n\t\t\t\tBody: string(doc.HTML),\n\t\t\t},\n\t\t\tAuthor: &atom.Person{\n\t\t\t\tName: authors(doc.Authors),\n\t\t\t},\n\t\t}\n\t\tfeed.Entry = append(feed.Entry, e)\n\t}\n\tdata, err := xml.Marshal(&feed)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.atomFeed = data\n\treturn nil\n}\n\ntype jsonItem struct {\n\tTitle string\n\tLink string\n\tTime time.Time\n\tSummary string\n\tContent string\n\tAuthor string\n}\n\n\/\/ renderJSONFeed generates a JSON feed and stores it in the Server's jsonFeed\n\/\/ field.\nfunc (s *Server) renderJSONFeed() error {\n\tvar feed []jsonItem\n\tfor i, doc := range s.docs {\n\t\tif i >= feedArticles {\n\t\t\tbreak\n\t\t}\n\t\titem := jsonItem{\n\t\t\tTitle: doc.Title,\n\t\t\tLink: baseURL + doc.Path,\n\t\t\tTime: doc.Time,\n\t\t\tSummary: summary(doc),\n\t\t\tContent: string(doc.HTML),\n\t\t\tAuthor: authors(doc.Authors),\n\t\t}\n\t\tfeed = append(feed, item)\n\t}\n\tdata, err := json.Marshal(feed)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.jsonFeed = data\n\treturn nil\n}\n\n\/\/ summary returns the first paragraph of text from the provided Doc.\nfunc summary(d *Doc) string {\n\tif len(d.Sections) == 0 {\n\t\treturn \"\"\n\t}\n\tfor _, elem := range d.Sections[0].Elem {\n\t\ttext, ok := elem.(present.Text)\n\t\tif !ok || text.Pre {\n\t\t\t\/\/ skip everything but non-text elements\n\t\t\tcontinue\n\t\t}\n\t\tvar buf bytes.Buffer\n\t\tfor _, s := range text.Lines {\n\t\t\tbuf.WriteString(string(present.Style(s)))\n\t\t\tbuf.WriteByte('\\n')\n\t\t}\n\t\treturn buf.String()\n\t}\n\treturn \"\"\n}\n\n\/\/ rootData encapsulates data destined for the root template.\ntype rootData struct {\n\tDoc *Doc\n\tData interface{}\n}\n\n\/\/ ServeHTTP servers either an article list or a single article.\nfunc (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tvar (\n\t\td rootData\n\t\tt *template.Template\n\t)\n\tswitch p := r.URL.Path; p {\n\tcase \"\/\":\n\t\td.Data = s.docs\n\t\tif len(s.docs) > homeArticles {\n\t\t\td.Data = s.docs[:homeArticles]\n\t\t}\n\t\tt = s.template.home\n\tcase \"\/index\":\n\t\td.Data = s.docs\n\t\tt = s.template.index\n\tcase \"\/feed.atom\", \"\/feeds\/posts\/default\":\n\t\tw.Header().Set(\"Content-type\", \"application\/atom+xml; charset=utf-8\")\n\t\tw.Write(s.atomFeed)\n\t\treturn\n\tcase \"\/.json\":\n\t\tif p := r.FormValue(\"jsonp\"); validJSONPFunc.MatchString(p) {\n\t\t\tw.Header().Set(\"Content-type\", \"application\/javascript; charset=utf-8\")\n\t\t\tfmt.Fprintf(w, \"%v(%s)\", p, s.jsonFeed)\n\t\t\treturn\n\t\t}\n\t\tw.Header().Set(\"Content-type\", \"application\/json\")\n\t\tw.Write(s.jsonFeed)\n\t\treturn\n\tdefault:\n\t\tdoc, ok := s.docPaths[p]\n\t\tif !ok {\n\t\t\t\/\/ Not a doc; try to just serve static content.\n\t\t\ts.content.ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\t\td.Doc = doc\n\t\tt = s.template.article\n\t}\n\terr := t.ExecuteTemplate(w, \"root\", d)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n}\n\n\/\/ docsByTime implements sort.Interface, sorting Docs by their Time field.\ntype docsByTime []*Doc\n\nfunc (s docsByTime) Len() int { return len(s) }\nfunc (s docsByTime) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\nfunc (s docsByTime) Less(i, j int) bool { return s[i].Time.After(s[j].Time) }\ngo.blog\/cmd\/blog: fix JSON content-type\/\/ Copyright 2013 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ This is a blog server for articles written in present format.\n\/\/ It powers blog.golang.org.\npackage main\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"encoding\/xml\"\n\t\"fmt\"\n\t\"html\/template\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"sort\"\n\t\"time\"\n\n\t\"code.google.com\/p\/go.blog\/pkg\/atom\"\n\t_ \"code.google.com\/p\/go.talks\/pkg\/playground\"\n\t\"code.google.com\/p\/go.talks\/pkg\/present\"\n)\n\nconst (\n\thostname = \"blog.golang.org\"\n\tbaseURL = \"http:\/\/\" + hostname\n\thomeArticles = 5 \/\/ articles to display on the home page\n\tfeedArticles = 10 \/\/ articles to include in Atom and JSON feeds\n)\n\nvar validJSONPFunc = regexp.MustCompile(`(?i)^[a-z_][a-z0-9_.]*$`)\n\n\/\/ Doc represents an article, adorned with presentation data:\n\/\/ its absolute path and related articles.\ntype Doc struct {\n\t*present.Doc\n\tPermalink string\n\tPath string\n\tRelated []*Doc\n\tNewer, Older *Doc\n\tHTML template.HTML \/\/ rendered article\n}\n\n\/\/ Server implements an http.Handler that serves blog articles.\ntype Server struct {\n\tdocs []*Doc\n\ttags []string\n\tdocPaths map[string]*Doc\n\tdocTags map[string][]*Doc\n\ttemplate struct {\n\t\thome, index, article, doc *template.Template\n\t}\n\tatomFeed []byte \/\/ pre-rendered Atom feed\n\tjsonFeed []byte \/\/ pre-rendered JSON feed\n\tcontent http.Handler\n}\n\n\/\/ NewServer constructs a new Server, serving articles from the specified\n\/\/ contentPath generated from templates from templatePath.\nfunc NewServer(contentPath, templatePath string) (*Server, error) {\n\tpresent.PlayEnabled = true\n\n\troot := filepath.Join(templatePath, \"root.tmpl\")\n\tparse := func(name string) (*template.Template, error) {\n\t\tt := template.New(\"\").Funcs(funcMap)\n\t\treturn t.ParseFiles(root, filepath.Join(templatePath, name))\n\t}\n\n\ts := &Server{}\n\n\t\/\/ Parse templates.\n\tvar err error\n\ts.template.home, err = parse(\"home.tmpl\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts.template.index, err = parse(\"index.tmpl\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts.template.article, err = parse(\"article.tmpl\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tp := present.Template().Funcs(funcMap)\n\ts.template.doc, err = p.ParseFiles(filepath.Join(templatePath, \"doc.tmpl\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Load content.\n\terr = s.loadDocs(filepath.Clean(contentPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = s.renderAtomFeed()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = s.renderJSONFeed()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Set up content file server.\n\ts.content = http.FileServer(http.Dir(contentPath))\n\n\treturn s, nil\n}\n\nvar funcMap = template.FuncMap{\n\t\"sectioned\": sectioned,\n\t\"authors\": authors,\n}\n\n\/\/ sectioned returns true if the provided Doc contains more than one section.\n\/\/ This is used to control whether to display the table of contents and headings.\nfunc sectioned(d *present.Doc) bool {\n\treturn len(d.Sections) > 1\n}\n\n\/\/ authors returns a comma-separated list of author names.\nfunc authors(authors []present.Author) string {\n\tvar b bytes.Buffer\n\tlast := len(authors) - 1\n\tfor i, a := range authors {\n\t\tif i > 0 {\n\t\t\tif i == last {\n\t\t\t\tb.WriteString(\" and \")\n\t\t\t} else {\n\t\t\t\tb.WriteString(\", \")\n\t\t\t}\n\t\t}\n\t\tb.WriteString(authorName(a))\n\t}\n\treturn b.String()\n}\n\n\/\/ authorName returns the first line of the Author text: the author's name.\nfunc authorName(a present.Author) string {\n\tel := a.TextElem()\n\tif len(el) == 0 {\n\t\treturn \"\"\n\t}\n\ttext, ok := el[0].(present.Text)\n\tif !ok || len(text.Lines) == 0 {\n\t\treturn \"\"\n\t}\n\treturn text.Lines[0]\n}\n\n\/\/ loadDocs reads all content from the provided file system root, renders all\n\/\/ the articles it finds, adds them to the Server's docs field, computes the\n\/\/ denormalized docPaths, docTags, and tags fields, and populates the various\n\/\/ helper fields (Next, Previous, Related) for each Doc.\nfunc (s *Server) loadDocs(root string) error {\n\t\/\/ Read content into docs field.\n\tconst ext = \".article\"\n\tfn := func(p string, info os.FileInfo, err error) error {\n\t\tif filepath.Ext(p) != ext {\n\t\t\treturn nil\n\t\t}\n\t\tf, err := os.Open(p)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer f.Close()\n\t\td, err := present.Parse(f, p, 0)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\thtml := new(bytes.Buffer)\n\t\terr = d.Render(html, s.template.doc)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tp = p[len(root) : len(p)-len(ext)] \/\/ trim root and extension\n\t\ts.docs = append(s.docs, &Doc{\n\t\t\tDoc: d,\n\t\t\tPath: p,\n\t\t\tPermalink: baseURL + p,\n\t\t\tHTML: template.HTML(html.String()),\n\t\t})\n\t\treturn nil\n\t}\n\terr := filepath.Walk(root, fn)\n\tif err != nil {\n\t\treturn err\n\t}\n\tsort.Sort(docsByTime(s.docs))\n\n\t\/\/ Pull out doc paths and tags and put in reverse-associating maps.\n\ts.docPaths = make(map[string]*Doc)\n\ts.docTags = make(map[string][]*Doc)\n\tfor _, d := range s.docs {\n\t\ts.docPaths[d.Path] = d\n\t\tfor _, t := range d.Tags {\n\t\t\ts.docTags[t] = append(s.docTags[t], d)\n\t\t}\n\t}\n\n\t\/\/ Pull out unique sorted list of tags.\n\tfor t := range s.docTags {\n\t\ts.tags = append(s.tags, t)\n\t}\n\tsort.Strings(s.tags)\n\n\t\/\/ Set up presentation-related fields, Newer, Older, and Related.\n\tfor _, doc := range s.docs {\n\t\t\/\/ Newer, Older: docs adjacent to doc\n\t\tfor i := range s.docs {\n\t\t\tif s.docs[i] != doc {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif i > 0 {\n\t\t\t\tdoc.Newer = s.docs[i-1]\n\t\t\t}\n\t\t\tif i+1 < len(s.docs) {\n\t\t\t\tdoc.Older = s.docs[i+1]\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\t\/\/ Related: all docs that share tags with doc.\n\t\trelated := make(map[*Doc]bool)\n\t\tfor _, t := range doc.Tags {\n\t\t\tfor _, d := range s.docTags[t] {\n\t\t\t\tif d != doc {\n\t\t\t\t\trelated[d] = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor d := range related {\n\t\t\tdoc.Related = append(doc.Related, d)\n\t\t}\n\t\tsort.Sort(docsByTime(doc.Related))\n\t}\n\n\treturn nil\n}\n\n\/\/ renderAtomFeed generates an XML Atom feed and stores it in the Server's\n\/\/ atomFeed field.\nfunc (s *Server) renderAtomFeed() error {\n\tvar updated time.Time\n\tif len(s.docs) > 1 {\n\t\tupdated = s.docs[0].Time\n\t}\n\tfeed := atom.Feed{\n\t\tTitle: \"The Go Programming Language Blog\",\n\t\tID: \"tag:\" + hostname + \",2013:\" + hostname,\n\t\tUpdated: atom.Time(updated),\n\t\tLink: []atom.Link{{\n\t\t\tRel: \"self\",\n\t\t\tHref: baseURL + \"\/feed.atom\",\n\t\t}},\n\t}\n\tfor i, doc := range s.docs {\n\t\tif i >= feedArticles {\n\t\t\tbreak\n\t\t}\n\t\te := &atom.Entry{\n\t\t\tTitle: doc.Title,\n\t\t\tID: feed.ID + doc.Path,\n\t\t\tLink: []atom.Link{{\n\t\t\t\tRel: \"alternate\",\n\t\t\t\tHref: baseURL + doc.Path,\n\t\t\t}},\n\t\t\tPublished: atom.Time(doc.Time),\n\t\t\tUpdated: atom.Time(doc.Time),\n\t\t\tSummary: &atom.Text{\n\t\t\t\tType: \"html\",\n\t\t\t\tBody: summary(doc),\n\t\t\t},\n\t\t\tContent: &atom.Text{\n\t\t\t\tType: \"html\",\n\t\t\t\tBody: string(doc.HTML),\n\t\t\t},\n\t\t\tAuthor: &atom.Person{\n\t\t\t\tName: authors(doc.Authors),\n\t\t\t},\n\t\t}\n\t\tfeed.Entry = append(feed.Entry, e)\n\t}\n\tdata, err := xml.Marshal(&feed)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.atomFeed = data\n\treturn nil\n}\n\ntype jsonItem struct {\n\tTitle string\n\tLink string\n\tTime time.Time\n\tSummary string\n\tContent string\n\tAuthor string\n}\n\n\/\/ renderJSONFeed generates a JSON feed and stores it in the Server's jsonFeed\n\/\/ field.\nfunc (s *Server) renderJSONFeed() error {\n\tvar feed []jsonItem\n\tfor i, doc := range s.docs {\n\t\tif i >= feedArticles {\n\t\t\tbreak\n\t\t}\n\t\titem := jsonItem{\n\t\t\tTitle: doc.Title,\n\t\t\tLink: baseURL + doc.Path,\n\t\t\tTime: doc.Time,\n\t\t\tSummary: summary(doc),\n\t\t\tContent: string(doc.HTML),\n\t\t\tAuthor: authors(doc.Authors),\n\t\t}\n\t\tfeed = append(feed, item)\n\t}\n\tdata, err := json.Marshal(feed)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.jsonFeed = data\n\treturn nil\n}\n\n\/\/ summary returns the first paragraph of text from the provided Doc.\nfunc summary(d *Doc) string {\n\tif len(d.Sections) == 0 {\n\t\treturn \"\"\n\t}\n\tfor _, elem := range d.Sections[0].Elem {\n\t\ttext, ok := elem.(present.Text)\n\t\tif !ok || text.Pre {\n\t\t\t\/\/ skip everything but non-text elements\n\t\t\tcontinue\n\t\t}\n\t\tvar buf bytes.Buffer\n\t\tfor _, s := range text.Lines {\n\t\t\tbuf.WriteString(string(present.Style(s)))\n\t\t\tbuf.WriteByte('\\n')\n\t\t}\n\t\treturn buf.String()\n\t}\n\treturn \"\"\n}\n\n\/\/ rootData encapsulates data destined for the root template.\ntype rootData struct {\n\tDoc *Doc\n\tData interface{}\n}\n\n\/\/ ServeHTTP servers either an article list or a single article.\nfunc (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tvar (\n\t\td rootData\n\t\tt *template.Template\n\t)\n\tswitch p := r.URL.Path; p {\n\tcase \"\/\":\n\t\td.Data = s.docs\n\t\tif len(s.docs) > homeArticles {\n\t\t\td.Data = s.docs[:homeArticles]\n\t\t}\n\t\tt = s.template.home\n\tcase \"\/index\":\n\t\td.Data = s.docs\n\t\tt = s.template.index\n\tcase \"\/feed.atom\", \"\/feeds\/posts\/default\":\n\t\tw.Header().Set(\"Content-type\", \"application\/atom+xml; charset=utf-8\")\n\t\tw.Write(s.atomFeed)\n\t\treturn\n\tcase \"\/.json\":\n\t\tif p := r.FormValue(\"jsonp\"); validJSONPFunc.MatchString(p) {\n\t\t\tw.Header().Set(\"Content-type\", \"application\/javascript; charset=utf-8\")\n\t\t\tfmt.Fprintf(w, \"%v(%s)\", p, s.jsonFeed)\n\t\t\treturn\n\t\t}\n\t\tw.Header().Set(\"Content-type\", \"application\/json; charset=utf-8\")\n\t\tw.Write(s.jsonFeed)\n\t\treturn\n\tdefault:\n\t\tdoc, ok := s.docPaths[p]\n\t\tif !ok {\n\t\t\t\/\/ Not a doc; try to just serve static content.\n\t\t\ts.content.ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\t\td.Doc = doc\n\t\tt = s.template.article\n\t}\n\terr := t.ExecuteTemplate(w, \"root\", d)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n}\n\n\/\/ docsByTime implements sort.Interface, sorting Docs by their Time field.\ntype docsByTime []*Doc\n\nfunc (s docsByTime) Len() int { return len(s) }\nfunc (s docsByTime) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\nfunc (s docsByTime) Less(i, j int) bool { return s[i].Time.After(s[j].Time) }\n<|endoftext|>"} {"text":"\/\/ Copyright 2017 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\"os\"\n\t\"path\/filepath\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com\/golang\/dep\"\n\t\"github.com\/golang\/dep\/gps\"\n\t\"github.com\/golang\/dep\/gps\/pkgtree\"\n\t\"github.com\/golang\/dep\/internal\/fs\"\n\t\"github.com\/pkg\/errors\"\n)\n\nconst pruneShortHelp = `Pruning is now performed automatically by dep ensure.`\nconst pruneLongHelp = `\nPrune was merged into the ensure command.\nSet prune options in the manifest and it will be applied after every ensure.\ndep prune will be removed in a future version of dep, causing this command to exit non-0.\n`\n\ntype pruneCommand struct {\n}\n\nfunc (cmd *pruneCommand) Name() string { return \"prune\" }\nfunc (cmd *pruneCommand) Args() string { return \"\" }\nfunc (cmd *pruneCommand) ShortHelp() string { return pruneShortHelp }\nfunc (cmd *pruneCommand) LongHelp() string { return pruneLongHelp }\nfunc (cmd *pruneCommand) Hidden() bool { return false }\n\nfunc (cmd *pruneCommand) Register(fs *flag.FlagSet) {\n}\n\nfunc (cmd *pruneCommand) Run(ctx *dep.Ctx, args []string) error {\n\tctx.Out.Printf(\"Pruning is now performed automatically by dep ensure.\\n\")\n\tctx.Out.Printf(\"Set prune settings in %s and it it will be applied when running ensure.\\n\", dep.ManifestName)\n\tctx.Out.Printf(\"\\ndep prune will be removed in a future version, and this command will exit non-0.\\nPlease update your scripts.\\n\")\n\n\tp, err := ctx.LoadProject()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsm, err := ctx.SourceManager()\n\tif err != nil {\n\t\treturn err\n\t}\n\tsm.UseDefaultSignalHandling()\n\tdefer sm.Release()\n\n\t\/\/ While the network churns on ListVersions() requests, statically analyze\n\t\/\/ code from the current project.\n\tptree, err := pkgtree.ListPackages(p.ResolvedAbsRoot, string(p.ImportRoot))\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"analysis of local packages failed: %v\")\n\t}\n\n\t\/\/ Set up a solver in order to check the InputHash.\n\tparams := p.MakeParams()\n\tparams.RootPackageTree = ptree\n\n\tif ctx.Verbose {\n\t\tparams.TraceLogger = ctx.Err\n\t}\n\n\ts, err := gps.Prepare(params, sm)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"could not set up solver for input hashing\")\n\t}\n\n\tif p.Lock == nil {\n\t\treturn errors.Errorf(\"Gopkg.lock must exist for prune to know what files are safe to remove.\")\n\t}\n\n\tif !bytes.Equal(s.HashInputs(), p.Lock.SolveMeta.InputsDigest) {\n\t\treturn errors.Errorf(\"Gopkg.lock is out of sync; run dep ensure before pruning.\")\n\t}\n\n\tpruneLogger := ctx.Err\n\tif !ctx.Verbose {\n\t\tpruneLogger = log.New(ioutil.Discard, \"\", 0)\n\t}\n\treturn pruneProject(p, sm, pruneLogger)\n}\n\n\/\/ pruneProject removes unused packages from a project.\nfunc pruneProject(p *dep.Project, sm gps.SourceManager, logger *log.Logger) error {\n\ttd, err := ioutil.TempDir(os.TempDir(), \"dep\")\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"error while creating temp dir for writing manifest\/lock\/vendor\")\n\t}\n\tdefer os.RemoveAll(td)\n\n\tif err := gps.WriteDepTree(td, p.Lock, sm, gps.CascadingPruneOptions{DefaultOptions: gps.PruneNestedVendorDirs}, logger); err != nil {\n\t\treturn err\n\t}\n\n\tvar toKeep []string\n\tfor _, project := range p.Lock.Projects() {\n\t\tprojectRoot := string(project.Ident().ProjectRoot)\n\t\tfor _, pkg := range project.Packages() {\n\t\t\ttoKeep = append(toKeep, filepath.Join(projectRoot, pkg))\n\t\t}\n\t}\n\n\ttoDelete, err := calculatePrune(td, toKeep, logger)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(toDelete) > 0 {\n\t\tlogger.Println(\"Calculated the following directories to prune:\")\n\t\tfor _, d := range toDelete {\n\t\t\tlogger.Printf(\" %s\\n\", d)\n\t\t}\n\t} else {\n\t\tlogger.Println(\"No directories found to prune\")\n\t}\n\n\tif err := deleteDirs(toDelete); err != nil {\n\t\treturn err\n\t}\n\n\tvpath := filepath.Join(p.AbsRoot, \"vendor\")\n\tvendorbak := vpath + \".orig\"\n\tvar failerr error\n\tif _, err := os.Stat(vpath); err == nil {\n\t\t\/\/ Move out the old vendor dir. just do it into an adjacent dir, to\n\t\t\/\/ try to mitigate the possibility of a pointless cross-filesystem\n\t\t\/\/ move with a temp directory.\n\t\tif _, err := os.Stat(vendorbak); err == nil {\n\t\t\t\/\/ If the adjacent dir already exists, bite the bullet and move\n\t\t\t\/\/ to a proper tempdir.\n\t\t\tvendorbak = filepath.Join(td, \"vendor.orig\")\n\t\t}\n\t\tfailerr = fs.RenameWithFallback(vpath, vendorbak)\n\t\tif failerr != nil {\n\t\t\tgoto fail\n\t\t}\n\t}\n\n\t\/\/ Move in the new one.\n\tfailerr = fs.RenameWithFallback(td, vpath)\n\tif failerr != nil {\n\t\tgoto fail\n\t}\n\n\tos.RemoveAll(vendorbak)\n\n\treturn nil\n\nfail:\n\tfs.RenameWithFallback(vendorbak, vpath)\n\treturn failerr\n}\n\nfunc calculatePrune(vendorDir string, keep []string, logger *log.Logger) ([]string, error) {\n\tlogger.Println(\"Calculating prune. Checking the following packages:\")\n\tsort.Strings(keep)\n\ttoDelete := []string{}\n\terr := filepath.Walk(vendorDir, func(path string, info os.FileInfo, err error) error {\n\t\tif _, err := os.Lstat(path); err != nil {\n\t\t\treturn nil\n\t\t}\n\t\tif !info.IsDir() {\n\t\t\treturn nil\n\t\t}\n\t\tif path == vendorDir {\n\t\t\treturn nil\n\t\t}\n\n\t\tname := strings.TrimPrefix(path, vendorDir+string(filepath.Separator))\n\t\tlogger.Printf(\" %s\", name)\n\t\ti := sort.Search(len(keep), func(i int) bool {\n\t\t\treturn name <= keep[i]\n\t\t})\n\t\tif i >= len(keep) || !strings.HasPrefix(keep[i], name) {\n\t\t\ttoDelete = append(toDelete, path)\n\t\t}\n\t\treturn nil\n\t})\n\treturn toDelete, err\n}\n\nfunc deleteDirs(toDelete []string) error {\n\t\/\/ sort by length so we delete sub dirs first\n\tsort.Sort(byLen(toDelete))\n\tfor _, path := range toDelete {\n\t\tif err := os.RemoveAll(path); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\ntype byLen []string\n\nfunc (a byLen) Len() int { return len(a) }\nfunc (a byLen) Swap(i, j int) { a[i], a[j] = a[j], a[i] }\nfunc (a byLen) Less(i, j int) bool { return len(a[i]) > len(a[j]) }\ndep: Sharpen `dep prune` warning message\/\/ Copyright 2017 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\"os\"\n\t\"path\/filepath\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com\/golang\/dep\"\n\t\"github.com\/golang\/dep\/gps\"\n\t\"github.com\/golang\/dep\/gps\/pkgtree\"\n\t\"github.com\/golang\/dep\/internal\/fs\"\n\t\"github.com\/pkg\/errors\"\n)\n\nconst pruneShortHelp = `Pruning is now performed automatically by dep ensure.`\nconst pruneLongHelp = `\nPrune was merged into the ensure command.\nSet prune options in the manifest and it will be applied after every ensure.\ndep prune will be removed in a future version of dep, causing this command to exit non-0.\n`\n\ntype pruneCommand struct {\n}\n\nfunc (cmd *pruneCommand) Name() string { return \"prune\" }\nfunc (cmd *pruneCommand) Args() string { return \"\" }\nfunc (cmd *pruneCommand) ShortHelp() string { return pruneShortHelp }\nfunc (cmd *pruneCommand) LongHelp() string { return pruneLongHelp }\nfunc (cmd *pruneCommand) Hidden() bool { return false }\n\nfunc (cmd *pruneCommand) Register(fs *flag.FlagSet) {\n}\n\nfunc (cmd *pruneCommand) Run(ctx *dep.Ctx, args []string) error {\n\tctx.Err.Printf(\"Pruning is now performed automatically by dep ensure.\\n\")\n\tctx.Err.Printf(\"Set prune settings in %s and it it will be applied when running ensure.\\n\", dep.ManifestName)\n\tctx.Err.Printf(\"\\nThis command currently still prunes as it always has, to ease the transition.\\n\")\n\tctx.Err.Printf(\"However, it will be removed in a future version of dep.\\n\")\n\tctx.Err.Printf(\"\\nNow is the time to update your Gopkg.toml and remove `dep prune` from any scripts.\\n\")\n\n\tp, err := ctx.LoadProject()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsm, err := ctx.SourceManager()\n\tif err != nil {\n\t\treturn err\n\t}\n\tsm.UseDefaultSignalHandling()\n\tdefer sm.Release()\n\n\t\/\/ While the network churns on ListVersions() requests, statically analyze\n\t\/\/ code from the current project.\n\tptree, err := pkgtree.ListPackages(p.ResolvedAbsRoot, string(p.ImportRoot))\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"analysis of local packages failed: %v\")\n\t}\n\n\t\/\/ Set up a solver in order to check the InputHash.\n\tparams := p.MakeParams()\n\tparams.RootPackageTree = ptree\n\n\tif ctx.Verbose {\n\t\tparams.TraceLogger = ctx.Err\n\t}\n\n\ts, err := gps.Prepare(params, sm)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"could not set up solver for input hashing\")\n\t}\n\n\tif p.Lock == nil {\n\t\treturn errors.Errorf(\"Gopkg.lock must exist for prune to know what files are safe to remove.\")\n\t}\n\n\tif !bytes.Equal(s.HashInputs(), p.Lock.SolveMeta.InputsDigest) {\n\t\treturn errors.Errorf(\"Gopkg.lock is out of sync; run dep ensure before pruning.\")\n\t}\n\n\tpruneLogger := ctx.Err\n\tif !ctx.Verbose {\n\t\tpruneLogger = log.New(ioutil.Discard, \"\", 0)\n\t}\n\treturn pruneProject(p, sm, pruneLogger)\n}\n\n\/\/ pruneProject removes unused packages from a project.\nfunc pruneProject(p *dep.Project, sm gps.SourceManager, logger *log.Logger) error {\n\ttd, err := ioutil.TempDir(os.TempDir(), \"dep\")\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"error while creating temp dir for writing manifest\/lock\/vendor\")\n\t}\n\tdefer os.RemoveAll(td)\n\n\tif err := gps.WriteDepTree(td, p.Lock, sm, gps.CascadingPruneOptions{DefaultOptions: gps.PruneNestedVendorDirs}, logger); err != nil {\n\t\treturn err\n\t}\n\n\tvar toKeep []string\n\tfor _, project := range p.Lock.Projects() {\n\t\tprojectRoot := string(project.Ident().ProjectRoot)\n\t\tfor _, pkg := range project.Packages() {\n\t\t\ttoKeep = append(toKeep, filepath.Join(projectRoot, pkg))\n\t\t}\n\t}\n\n\ttoDelete, err := calculatePrune(td, toKeep, logger)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(toDelete) > 0 {\n\t\tlogger.Println(\"Calculated the following directories to prune:\")\n\t\tfor _, d := range toDelete {\n\t\t\tlogger.Printf(\" %s\\n\", d)\n\t\t}\n\t} else {\n\t\tlogger.Println(\"No directories found to prune\")\n\t}\n\n\tif err := deleteDirs(toDelete); err != nil {\n\t\treturn err\n\t}\n\n\tvpath := filepath.Join(p.AbsRoot, \"vendor\")\n\tvendorbak := vpath + \".orig\"\n\tvar failerr error\n\tif _, err := os.Stat(vpath); err == nil {\n\t\t\/\/ Move out the old vendor dir. just do it into an adjacent dir, to\n\t\t\/\/ try to mitigate the possibility of a pointless cross-filesystem\n\t\t\/\/ move with a temp directory.\n\t\tif _, err := os.Stat(vendorbak); err == nil {\n\t\t\t\/\/ If the adjacent dir already exists, bite the bullet and move\n\t\t\t\/\/ to a proper tempdir.\n\t\t\tvendorbak = filepath.Join(td, \"vendor.orig\")\n\t\t}\n\t\tfailerr = fs.RenameWithFallback(vpath, vendorbak)\n\t\tif failerr != nil {\n\t\t\tgoto fail\n\t\t}\n\t}\n\n\t\/\/ Move in the new one.\n\tfailerr = fs.RenameWithFallback(td, vpath)\n\tif failerr != nil {\n\t\tgoto fail\n\t}\n\n\tos.RemoveAll(vendorbak)\n\n\treturn nil\n\nfail:\n\tfs.RenameWithFallback(vendorbak, vpath)\n\treturn failerr\n}\n\nfunc calculatePrune(vendorDir string, keep []string, logger *log.Logger) ([]string, error) {\n\tlogger.Println(\"Calculating prune. Checking the following packages:\")\n\tsort.Strings(keep)\n\ttoDelete := []string{}\n\terr := filepath.Walk(vendorDir, func(path string, info os.FileInfo, err error) error {\n\t\tif _, err := os.Lstat(path); err != nil {\n\t\t\treturn nil\n\t\t}\n\t\tif !info.IsDir() {\n\t\t\treturn nil\n\t\t}\n\t\tif path == vendorDir {\n\t\t\treturn nil\n\t\t}\n\n\t\tname := strings.TrimPrefix(path, vendorDir+string(filepath.Separator))\n\t\tlogger.Printf(\" %s\", name)\n\t\ti := sort.Search(len(keep), func(i int) bool {\n\t\t\treturn name <= keep[i]\n\t\t})\n\t\tif i >= len(keep) || !strings.HasPrefix(keep[i], name) {\n\t\t\ttoDelete = append(toDelete, path)\n\t\t}\n\t\treturn nil\n\t})\n\treturn toDelete, err\n}\n\nfunc deleteDirs(toDelete []string) error {\n\t\/\/ sort by length so we delete sub dirs first\n\tsort.Sort(byLen(toDelete))\n\tfor _, path := range toDelete {\n\t\tif err := os.RemoveAll(path); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\ntype byLen []string\n\nfunc (a byLen) Len() int { return len(a) }\nfunc (a byLen) Swap(i, j int) { a[i], a[j] = a[j], a[i] }\nfunc (a byLen) Less(i, j int) bool { return len(a[i]) > len(a[j]) }\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"flag\"\n\t\"os\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/domainr\/dnsr\"\n\t\"github.com\/miekg\/dns\"\n\t\"github.com\/wsxiaoys\/terminal\/color\"\n\t\"golang.org\/x\/net\/idna\"\n)\n\nconst (\n\ttimeout = 2000 * time.Millisecond\n)\n\nvar (\n\tverbose bool\n\tresolver = dnsr.New(10000)\n)\n\nfunc init() {\n\tflag.BoolVar(\n\t\t&verbose,\n\t\t\"v\",\n\t\tfalse,\n\t\t\"print verbose info to the console\",\n\t)\n}\n\nfunc logV(fmt string, args ...interface{}) {\n\tif !verbose {\n\t\treturn\n\t}\n\tcolor.Printf(fmt, args...)\n}\n\nfunc main() {\n\tflag.Usage = func() {\n\t\tcolor.Fprintf(os.Stderr, \"Usage: %s [arguments] [type]\\n\\nAvailable arguments:\\n\", os.Args[0])\n\t\tflag.PrintDefaults()\n\t\tos.Exit(1)\n\t}\n\tflag.Parse()\n\tqtype := \"\"\n\targs := flag.Args()\n\tif len(args) == 0 {\n\t\tflag.Usage()\n\t} else if _, isType := dns.StringToType[args[len(args)-1]]; len(args) > 1 && isType {\n\t\tqtype, args = args[len(args)-1], args[:len(args)-1]\n\t}\n\tif verbose {\n\t\tdnsr.DebugLogger = os.Stderr\n\t}\n\tvar wg sync.WaitGroup\n\tstart := time.Now()\n\tfor _, name := range args {\n\t\twg.Add(1)\n\t\tgo func(name string, qtype string) {\n\t\t\tquery(name, qtype)\n\t\t\twg.Done()\n\t\t}(name, qtype)\n\t}\n\twg.Wait()\n\tlogV(\"\\n@{w};; Total elapsed: %s\\n\", time.Since(start).String())\n}\n\nfunc query(name, qtype string) {\n\tstart := time.Now()\n\tqname, err := idna.ToASCII(name)\n\tif err != nil {\n\t\tcolor.Fprintf(os.Stderr, \"Invalid IDN domain name: %s\\n\", name)\n\t\tos.Exit(1)\n\t}\n\n\trrs := resolver.Resolve(qname, qtype)\n\n\tcolor.Printf(\"\\n\")\n\tif len(rrs) > 0 {\n\t\tcolor.Printf(\"@{g};; RESULTS:\\n\")\n\t}\n\tfor _, rr := range rrs {\n\t\tcolor.Printf(\"@{g}%s\\n\", rr.String())\n\t}\n\n\tif rrs == nil {\n\t\tcolor.Printf(\"@{y};; NIL\\t%s\\t%s\\n\", name, qtype)\n\t} else if len(rrs) > 0 {\n\t\tcolor.Printf(\"@{g};; TRUE\\t%s\\t%s\\n\", name, qtype)\n\t} else {\n\t\tcolor.Printf(\"@{r};; FALSE\\t%s\\t%s\\n\", name, qtype)\n\t}\n\n\tcolor.Printf(\"@{.w};; Elapsed: %s\\n\", time.Since(start).String())\n}\ncmd\/dnsr: Use ResolveErr and log total time elapsed.package main\n\nimport (\n\t\"flag\"\n\t\"os\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/domainr\/dnsr\"\n\t\"github.com\/miekg\/dns\"\n\t\"github.com\/wsxiaoys\/terminal\/color\"\n\t\"golang.org\/x\/net\/idna\"\n)\n\nvar (\n\tverbose bool\n\tresolver = dnsr.New(10000)\n)\n\nfunc init() {\n\tflag.BoolVar(\n\t\t&verbose,\n\t\t\"v\",\n\t\tfalse,\n\t\t\"print verbose info to the console\",\n\t)\n}\n\nfunc logV(fmt string, args ...interface{}) {\n\tif !verbose {\n\t\treturn\n\t}\n\tcolor.Printf(fmt, args...)\n}\n\nfunc main() {\n\tflag.Usage = func() {\n\t\tcolor.Fprintf(os.Stderr, \"Usage: %s [arguments] [type]\\n\\nAvailable arguments:\\n\", os.Args[0])\n\t\tflag.PrintDefaults()\n\t\tos.Exit(1)\n\t}\n\tflag.Parse()\n\tqtype := \"\"\n\targs := flag.Args()\n\tif len(args) == 0 {\n\t\tflag.Usage()\n\t} else if _, isType := dns.StringToType[args[len(args)-1]]; len(args) > 1 && isType {\n\t\tqtype, args = args[len(args)-1], args[:len(args)-1]\n\t}\n\tif verbose {\n\t\tdnsr.DebugLogger = os.Stderr\n\t}\n\tvar wg sync.WaitGroup\n\tstart := time.Now()\n\tfor _, name := range args {\n\t\twg.Add(1)\n\t\tgo func(name string, qtype string) {\n\t\t\tquery(name, qtype)\n\t\t\twg.Done()\n\t\t}(name, qtype)\n\t}\n\twg.Wait()\n\tif len(args) > 1 {\n\t\tcolor.Printf(\"\\n@{.w};; Total elapsed: %s\\n\", time.Since(start).String())\n\t}\n}\n\nfunc query(name, qtype string) {\n\tstart := time.Now()\n\tqname, err := idna.ToASCII(name)\n\tif err != nil {\n\t\tcolor.Fprintf(os.Stderr, \"Invalid IDN domain name: %s\\n\", name)\n\t\tos.Exit(1)\n\t}\n\n\trrs, err := resolver.ResolveErr(qname, qtype)\n\n\tcolor.Printf(\"\\n\")\n\tif len(rrs) > 0 {\n\t\tcolor.Printf(\"@{g};; RESULTS:\\n\")\n\t}\n\tfor _, rr := range rrs {\n\t\tcolor.Printf(\"@{g}%s\\n\", rr.String())\n\t}\n\n\tif err != nil {\n\t\tcolor.Printf(\"@{r};; %s\\t%s\\t%s\\n\", err, name, qtype)\n\t} else if rrs == nil {\n\t\tcolor.Printf(\"@{y};; NIL\\t%s\\t%s\\n\", name, qtype)\n\t} else if len(rrs) > 0 {\n\t\tcolor.Printf(\"@{g};; TRUE\\t%s\\t%s\\n\", name, qtype)\n\t} else {\n\t\tcolor.Printf(\"@{r};; FALSE\\t%s\\t%s\\n\", name, qtype)\n\t}\n\n\tcolor.Printf(\"@{.w};; Elapsed: %s\\n\", time.Since(start).String())\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\n\t\"bitbucket.org\/cihangirsavas\/gene\/generators\/modules\"\n)\n\nvar (\n\tflagSchemaFile = flag.String(\"schema\", \"\", \"schema content file\")\n\tflagFolder = flag.String(\"target\", \".\/\", \"target directory name\")\n)\n\nfunc main() {\n\tflag.Parse()\n\n\tm, err := modules.NewFromFile(*flagSchemaFile)\n\tif err != nil {\n\t\tlog.Fatalf(err.Error())\n\t\treturn\n\t}\n\n\tm.TargetFolderName = *flagFolder\n\tfmt.Println(\"m-->\", m.Create())\n}\nGene added: created module with success logpackage main\n\nimport (\n\t\"flag\"\n\t\"log\"\n\n\t\"bitbucket.org\/cihangirsavas\/gene\/generators\/modules\"\n)\n\nvar (\n\tflagSchemaFile = flag.String(\"schema\", \"\", \"schema content file\")\n\tflagFolder = flag.String(\"target\", \".\/\", \"target directory name\")\n)\n\nfunc main() {\n\tflag.Parse()\n\n\tm, err := modules.NewFromFile(*flagSchemaFile)\n\tif err != nil {\n\t\tlog.Fatalf(err.Error())\n\t\treturn\n\t}\n\n\tm.TargetFolderName = *flagFolder\n\tif err := m.Create(); err != nil {\n\t\tlog.Fatalf(err.Error())\n\t\treturn\n\t}\n\n\tlog.Println(\"module created with success\")\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"os\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/howeyc\/ledger\"\n\n\t\"github.com\/BurntSushi\/toml\"\n\t\"github.com\/go-martini\/martini\"\n\t\"github.com\/martini-contrib\/gzip\"\n\t\"github.com\/martini-contrib\/staticbin\"\n)\n\nvar ledgerFileName string\nvar reportConfigFileName string\nvar stockConfigFileName string\nvar ledgerLock sync.Mutex\n\nfunc getTransactions() ([]*ledger.Transaction, error) {\n\tledgerLock.Lock()\n\tdefer ledgerLock.Unlock()\n\n\tledgerFileReader, err := os.Open(ledgerFileName)\n\tif err != nil {\n\t\treturn nil, err\n\n\t}\n\n\ttrans, terr := ledger.ParseLedger(ledgerFileReader)\n\tif terr != nil {\n\t\treturn nil, fmt.Errorf(\"%s:%s\", ledgerFileName, terr.Error())\n\t}\n\tledgerFileReader.Close()\n\n\treturn trans, nil\n}\n\ntype accountOp struct {\n\tName string `toml:\"name\"`\n\tOperation string `toml:\"operation\"` \/\/ +, -\n}\n\ntype calculatedAccount struct {\n\tName string `toml:\"name\"`\n\tAccountOperations []accountOp `toml:\"account_operation\"`\n}\n\ntype reportConfig struct {\n\tName string\n\tChart string\n\tDateRange string `toml:\"date_range\"`\n\tDateFreq string `toml:\"date_freq\"`\n\tAccounts []string\n\tExcludeAccountTrans []string `toml:\"exclude_account_trans\"`\n\tExcludeAccountsSummary []string `toml:\"exclude_account_summary\"`\n\tCalculatedAccounts []calculatedAccount `toml:\"calculated_account\"`\n}\n\ntype reportConfigStruct struct {\n\tReports []reportConfig `toml:\"report\"`\n}\n\nvar reportConfigData reportConfigStruct\n\ntype stockConfig struct {\n\tName string\n\tSection string\n\tTicker string\n\tAccount string\n\tShares float64\n}\n\ntype stockInfo struct {\n\tName string\n\tSection string\n\tType string\n\tTicker string\n\tAccount string\n\tShares float64\n\tPrice float64\n\tPriceChangeDay float64\n\tPriceChangePctDay float64\n\tPriceChangeOverall float64\n\tPriceChangePctOverall float64\n\tCost float64\n\tMarketValue float64\n\tGainLossDay float64\n\tGainLossOverall float64\n}\n\ntype stockConfigStruct struct {\n\tStocks []stockConfig `toml:\"stock\"`\n}\n\nvar stockConfigData stockConfigStruct\n\ntype pageData struct {\n\tReports []reportConfig\n\tTransactions []*ledger.Transaction\n\tAccounts []*ledger.Account\n\tStocks []stockInfo\n}\n\nfunc main() {\n\tvar serverPort int\n\tvar localhost bool\n\n\tflag.StringVar(&ledgerFileName, \"f\", \"\", \"Ledger file name (*Required).\")\n\tflag.StringVar(&reportConfigFileName, \"r\", \"\", \"Report config file name (*Required).\")\n\tflag.StringVar(&stockConfigFileName, \"s\", \"\", \"Stock config file name (*Optional).\")\n\tflag.IntVar(&serverPort, \"port\", 8056, \"Port to listen on.\")\n\tflag.BoolVar(&localhost, \"localhost\", false, \"Listen on localhost only.\")\n\n\tflag.Parse()\n\n\tif len(ledgerFileName) == 0 || len(reportConfigFileName) == 0 {\n\t\tflag.Usage()\n\t\treturn\n\t}\n\n\tgo func() {\n\t\tfor {\n\t\t\tvar rLoadData reportConfigStruct\n\t\t\ttoml.DecodeFile(reportConfigFileName, &rLoadData)\n\t\t\treportConfigData = rLoadData\n\t\t\ttime.Sleep(time.Minute * 5)\n\t\t}\n\t}()\n\n\tif len(stockConfigFileName) > 0 {\n\t\tvar sLoadData stockConfigStruct\n\t\ttoml.DecodeFile(stockConfigFileName, &sLoadData)\n\t\tstockConfigData = sLoadData\n\t}\n\n\tm := martini.Classic()\n\tm.Use(gzip.All())\n\tm.Use(staticbin.Static(\"public\", Asset))\n\n\tm.Get(\"\/ledger\", ledgerHandler)\n\tm.Get(\"\/accounts\", accountsHandler)\n\tm.Get(\"\/portfolio\", portfolioHandler)\n\tm.Get(\"\/account\/:accountName\", accountHandler)\n\tm.Get(\"\/report\/:reportName\", reportHandler)\n\tm.Get(\"\/\", func(w http.ResponseWriter, r *http.Request) {\n\t\thttp.Redirect(w, r, \"\/accounts\", http.StatusFound)\n\t})\n\n\tfmt.Println(\"Listening on port\", serverPort)\n\tlistenAddress := \"\"\n\tif localhost {\n\t\tlistenAddress = fmt.Sprintf(\"127.0.0.1:%d\", serverPort)\n\t} else {\n\t\tlistenAddress = fmt.Sprintf(\":%d\", serverPort)\n\t}\n\thttp.ListenAndServe(listenAddress, m)\n}\ncache transactions in web processpackage main\n\nimport (\n\t\"bytes\"\n\t\"crypto\/sha256\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\/http\"\n\t\"os\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/howeyc\/ledger\"\n\n\t\"github.com\/BurntSushi\/toml\"\n\t\"github.com\/go-martini\/martini\"\n\t\"github.com\/martini-contrib\/gzip\"\n\t\"github.com\/martini-contrib\/staticbin\"\n)\n\nvar ledgerFileName string\nvar reportConfigFileName string\nvar stockConfigFileName string\nvar ledgerLock sync.Mutex\nvar currentSum []byte\nvar currentTrans []*ledger.Transaction\n\nfunc getTransactions() ([]*ledger.Transaction, error) {\n\tledgerLock.Lock()\n\tdefer ledgerLock.Unlock()\n\n\tvar buf bytes.Buffer\n\th := sha256.New()\n\n\tledgerFileReader, err := os.Open(ledgerFileName)\n\tif err != nil {\n\t\treturn nil, err\n\n\t}\n\ttr := io.TeeReader(ledgerFileReader, h)\n\tio.Copy(&buf, tr)\n\tledgerFileReader.Close()\n\n\tsum := h.Sum(nil)\n\tif bytes.Compare(currentSum, sum) == 0 {\n\t\treturn currentTrans, nil\n\t}\n\n\ttrans, terr := ledger.ParseLedger(&buf)\n\tif terr != nil {\n\t\treturn nil, fmt.Errorf(\"%s:%s\", ledgerFileName, terr.Error())\n\t}\n\tcurrentSum = sum\n\tcurrentTrans = trans\n\n\treturn trans, nil\n}\n\ntype accountOp struct {\n\tName string `toml:\"name\"`\n\tOperation string `toml:\"operation\"` \/\/ +, -\n}\n\ntype calculatedAccount struct {\n\tName string `toml:\"name\"`\n\tAccountOperations []accountOp `toml:\"account_operation\"`\n}\n\ntype reportConfig struct {\n\tName string\n\tChart string\n\tDateRange string `toml:\"date_range\"`\n\tDateFreq string `toml:\"date_freq\"`\n\tAccounts []string\n\tExcludeAccountTrans []string `toml:\"exclude_account_trans\"`\n\tExcludeAccountsSummary []string `toml:\"exclude_account_summary\"`\n\tCalculatedAccounts []calculatedAccount `toml:\"calculated_account\"`\n}\n\ntype reportConfigStruct struct {\n\tReports []reportConfig `toml:\"report\"`\n}\n\nvar reportConfigData reportConfigStruct\n\ntype stockConfig struct {\n\tName string\n\tSection string\n\tTicker string\n\tAccount string\n\tShares float64\n}\n\ntype stockInfo struct {\n\tName string\n\tSection string\n\tType string\n\tTicker string\n\tAccount string\n\tShares float64\n\tPrice float64\n\tPriceChangeDay float64\n\tPriceChangePctDay float64\n\tPriceChangeOverall float64\n\tPriceChangePctOverall float64\n\tCost float64\n\tMarketValue float64\n\tGainLossDay float64\n\tGainLossOverall float64\n}\n\ntype stockConfigStruct struct {\n\tStocks []stockConfig `toml:\"stock\"`\n}\n\nvar stockConfigData stockConfigStruct\n\ntype pageData struct {\n\tReports []reportConfig\n\tTransactions []*ledger.Transaction\n\tAccounts []*ledger.Account\n\tStocks []stockInfo\n}\n\nfunc main() {\n\tvar serverPort int\n\tvar localhost bool\n\n\tflag.StringVar(&ledgerFileName, \"f\", \"\", \"Ledger file name (*Required).\")\n\tflag.StringVar(&reportConfigFileName, \"r\", \"\", \"Report config file name (*Required).\")\n\tflag.StringVar(&stockConfigFileName, \"s\", \"\", \"Stock config file name (*Optional).\")\n\tflag.IntVar(&serverPort, \"port\", 8056, \"Port to listen on.\")\n\tflag.BoolVar(&localhost, \"localhost\", false, \"Listen on localhost only.\")\n\n\tflag.Parse()\n\n\tif len(ledgerFileName) == 0 || len(reportConfigFileName) == 0 {\n\t\tflag.Usage()\n\t\treturn\n\t}\n\n\tgo func() {\n\t\tfor {\n\t\t\tvar rLoadData reportConfigStruct\n\t\t\ttoml.DecodeFile(reportConfigFileName, &rLoadData)\n\t\t\treportConfigData = rLoadData\n\t\t\ttime.Sleep(time.Minute * 5)\n\t\t}\n\t}()\n\n\tif len(stockConfigFileName) > 0 {\n\t\tvar sLoadData stockConfigStruct\n\t\ttoml.DecodeFile(stockConfigFileName, &sLoadData)\n\t\tstockConfigData = sLoadData\n\t}\n\n\t\/\/ initialize cache\n\tgetTransactions()\n\n\tm := martini.Classic()\n\tm.Use(gzip.All())\n\tm.Use(staticbin.Static(\"public\", Asset))\n\n\tm.Get(\"\/ledger\", ledgerHandler)\n\tm.Get(\"\/accounts\", accountsHandler)\n\tm.Get(\"\/portfolio\", portfolioHandler)\n\tm.Get(\"\/account\/:accountName\", accountHandler)\n\tm.Get(\"\/report\/:reportName\", reportHandler)\n\tm.Get(\"\/\", func(w http.ResponseWriter, r *http.Request) {\n\t\thttp.Redirect(w, r, \"\/accounts\", http.StatusFound)\n\t})\n\n\tfmt.Println(\"Listening on port\", serverPort)\n\tlistenAddress := \"\"\n\tif localhost {\n\t\tlistenAddress = fmt.Sprintf(\"127.0.0.1:%d\", serverPort)\n\t} else {\n\t\tlistenAddress = fmt.Sprintf(\":%d\", serverPort)\n\t}\n\thttp.ListenAndServe(listenAddress, m)\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"time\"\n\n\t\"github.com\/cortesi\/modd\"\n\t\"github.com\/cortesi\/termlog\"\n\t\"gopkg.in\/alecthomas\/kingpin.v2\"\n)\n\nconst batchTime = time.Millisecond * 200\n\nfunc main() {\n\tpaths := kingpin.Arg(\n\t\t\"path\",\n\t\t\"Paths to monitor for changes.\",\n\t).Required().Strings()\n\n\texcludes := kingpin.Flag(\"exclude\", \"Glob pattern for files to exclude from livereload\").\n\t\tPlaceHolder(\"PATTERN\").\n\t\tShort('x').\n\t\tStrings()\n\n\tdebug := kingpin.Flag(\"debug\", \"Debugging for devd development\").\n\t\tDefault(\"false\").\n\t\tBool()\n\n\tkingpin.Version(modd.Version)\n\tkingpin.Parse()\n\tlog := termlog.NewLog()\n\n\tif *debug {\n\t\tlog.Enable(\"debug\")\n\t\tmodd.Logger = log\n\t}\n\n\tmodchan := make(chan modd.Mod)\n\terr := modd.Watch(*paths, *excludes, batchTime, modchan)\n\tif err != nil {\n\t\tkingpin.Fatalf(\"Fatal error: %s\", err)\n\t}\n\tfor mod := range modchan {\n\t\tif len(mod.Added) > 0 {\n\t\t\tlog.Say(\"Added: %v\\n\", mod.Added)\n\t\t}\n\t\tif len(mod.Changed) > 0 {\n\t\t\tlog.Say(\"Changed: %v\\n\", mod.Changed)\n\t\t}\n\t\tif len(mod.Deleted) > 0 {\n\t\t\tlog.Say(\"Deleted: %v\\n\", mod.Deleted)\n\t\t}\n\t}\n}\nPrint a little something to show that modd is runningpackage main\n\nimport (\n\t\"time\"\n\n\t\"github.com\/cortesi\/modd\"\n\t\"github.com\/cortesi\/termlog\"\n\t\"gopkg.in\/alecthomas\/kingpin.v2\"\n)\n\nconst batchTime = time.Millisecond * 200\n\nfunc main() {\n\tpaths := kingpin.Arg(\n\t\t\"path\",\n\t\t\"Paths to monitor for changes.\",\n\t).Required().Strings()\n\n\texcludes := kingpin.Flag(\"exclude\", \"Glob pattern for files to exclude from livereload\").\n\t\tPlaceHolder(\"PATTERN\").\n\t\tShort('x').\n\t\tStrings()\n\n\tdebug := kingpin.Flag(\"debug\", \"Debugging for devd development\").\n\t\tDefault(\"false\").\n\t\tBool()\n\n\tkingpin.Version(modd.Version)\n\tkingpin.Parse()\n\tlog := termlog.NewLog()\n\tlog.Notice(\"modd v%s\", modd.Version)\n\n\tif *debug {\n\t\tlog.Enable(\"debug\")\n\t\tmodd.Logger = log\n\t}\n\n\tmodchan := make(chan modd.Mod)\n\terr := modd.Watch(*paths, *excludes, batchTime, modchan)\n\tif err != nil {\n\t\tkingpin.Fatalf(\"Fatal error: %s\", err)\n\t}\n\tfor mod := range modchan {\n\t\tif len(mod.Added) > 0 {\n\t\t\tlog.Say(\"Added: %v\\n\", mod.Added)\n\t\t}\n\t\tif len(mod.Changed) > 0 {\n\t\t\tlog.Say(\"Changed: %v\\n\", mod.Changed)\n\t\t}\n\t\tif len(mod.Deleted) > 0 {\n\t\t\tlog.Say(\"Deleted: %v\\n\", mod.Deleted)\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"package main\n\nfunc getAddon(args []string) error {\n\treturn nil\n}\ngetAddon(), comprising go get and copy routinespackage main\n\nimport (\n\t\"errors\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n)\n\n\/\/ Use `go get` to download addon and add to $GOPATH\/src, useful\n\/\/ for IDE auto-import and code completion, then copy entire directory\n\/\/ tree to project's .\/addons folder\nfunc getAddon(args []string) error {\n\n\t\/\/ error return\n\terrorFunc := func(err error) error {\n\t\treturn errors.New(\"Ponzu add failed. \" + \"\\n\" + err.Error())\n\t}\n\n\tvar cmdOptions []string\n\tvar addonPath = args[1]\n\n\t\/\/ Go get\n\tcmdOptions = append(cmdOptions, addonPath)\n\tget := exec.Command(gocmd, cmdOptions...)\n\tget.Stderr = os.Stderr\n\tget.Stdout = os.Stdout\n\n\terr := get.Start()\n\tif err != nil {\n\t\terrorFunc(err)\n\t}\n\terr = get.Wait()\n\tif err != nil {\n\t\terrorFunc(err)\n\t}\n\n\t\/\/ Copy to .\/addons folder\n\n\t\/\/ GOPATH can be a list delimited by \":\" on Linux or \";\" on Windows\n\t\/\/ go get uses the first, this should parse out the first whatever the OS\n\tenvGOPATH := os.Getenv(\"GOPATH\")\n\tgopaths := strings.Split(envGOPATH, \":\")\n\tgopath := gopaths[0]\n\tgopaths = strings.Split(envGOPATH, \";\")\n\tgopath = gopaths[0]\n\n\tsrc := filepath.Join(gopath, addonPath)\n\tdest := filepath.Join(\".\/addons\", addonPath)\n\n\terr = copyAll(src, dest)\n\tif err != nil {\n\t\terrorFunc(err)\n\t}\n\treturn nil\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"syscall\"\n\n\t\"github.com\/spf13\/cobra\"\n\n\t\"github.com\/flant\/werf\/cmd\/werf\/build\"\n\t\"github.com\/flant\/werf\/cmd\/werf\/build_and_publish\"\n\t\"github.com\/flant\/werf\/cmd\/werf\/cleanup\"\n\t\"github.com\/flant\/werf\/cmd\/werf\/publish\"\n\t\"github.com\/flant\/werf\/cmd\/werf\/purge\"\n\n\thelm_secret_edit \"github.com\/flant\/werf\/cmd\/werf\/helm\/secret\/edit\"\n\thelm_secret_extract \"github.com\/flant\/werf\/cmd\/werf\/helm\/secret\/extract\"\n\thelm_secret_generate \"github.com\/flant\/werf\/cmd\/werf\/helm\/secret\/generate\"\n\thelm_secret_key_generate \"github.com\/flant\/werf\/cmd\/werf\/helm\/secret\/key_generate\"\n\thelm_secret_regenerate \"github.com\/flant\/werf\/cmd\/werf\/helm\/secret\/regenerate\"\n\n\t\"github.com\/flant\/werf\/cmd\/werf\/tools\/slugify\"\n\n\timages_cleanup \"github.com\/flant\/werf\/cmd\/werf\/images\/cleanup\"\n\timages_publish \"github.com\/flant\/werf\/cmd\/werf\/images\/publish\"\n\timages_purge \"github.com\/flant\/werf\/cmd\/werf\/images\/purge\"\n\n\tstages_build \"github.com\/flant\/werf\/cmd\/werf\/stages\/build\"\n\tstages_cleanup \"github.com\/flant\/werf\/cmd\/werf\/stages\/cleanup\"\n\tstages_purge \"github.com\/flant\/werf\/cmd\/werf\/stages\/purge\"\n\n\thost_cleanup \"github.com\/flant\/werf\/cmd\/werf\/host\/cleanup\"\n\thost_purge \"github.com\/flant\/werf\/cmd\/werf\/host\/purge\"\n\n\thelm_get_service_values \"github.com\/flant\/werf\/cmd\/werf\/helm\/get_service_values\"\n\n\t\"github.com\/flant\/werf\/cmd\/werf\/completion\"\n\t\"github.com\/flant\/werf\/cmd\/werf\/docs\"\n\t\"github.com\/flant\/werf\/cmd\/werf\/version\"\n\n\t\"github.com\/flant\/werf\/cmd\/werf\/common\"\n\t\"github.com\/flant\/werf\/cmd\/werf\/common\/templates\"\n\t\"github.com\/flant\/werf\/pkg\/logger\"\n\t\"github.com\/flant\/werf\/pkg\/process_exterminator\"\n)\n\nfunc main() {\n\ttrapTerminationSignals()\n\n\tlogger.Init(logger.Options{})\n\n\tif err := process_exterminator.Init(); err != nil {\n\t\tlogger.LogError(fmt.Errorf(\"process exterminator initialization error: %s\", err))\n\t\tos.Exit(1)\n\t}\n\n\trootCmd := &cobra.Command{\n\t\tUse: \"werf\",\n\t\tShort: \"Werf helps to implement and support Continuous Integration and Continuous Delivery\",\n\t\tLong: common.GetLongCommandDescription(`Werf helps to implement and support Continuous Integration and Continuous Delivery.\n\nFind more information at https:\/\/flant.github.io\/werf`),\n\t\tSilenceUsage: true,\n\t\tSilenceErrors: true,\n\t}\n\n\tgroups := templates.CommandGroups{\n\t\t{\n\t\t\tMessage: \"Main Commands:\",\n\t\t\tCommands: []*cobra.Command{\n\t\t\t\tbuild.NewCmd(),\n\t\t\t\tpublish.NewCmd(),\n\t\t\t\tbuild_and_publish.NewCmd(),\n\t\t\t\tcleanup.NewCmd(),\n\t\t\t\tpurge.NewCmd(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tMessage: \"Tools Commands:\",\n\t\t\tCommands: []*cobra.Command{\n\t\t\t\tslugify.NewCmd(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tMessage: \"Lowlevel Management Commands:\",\n\t\t\tCommands: []*cobra.Command{\n\t\t\t\tstagesCmd(),\n\t\t\t\timagesCmd(),\n\t\t\t\thelmCmd(),\n\t\t\t\thostCmd(),\n\t\t\t},\n\t\t},\n\t}\n\tgroups.Add(rootCmd)\n\n\ttemplates.ActsAsRootCommand(rootCmd, groups...)\n\n\trootCmd.AddCommand(\n\t\tcompletion.NewCmd(rootCmd),\n\t\tversion.NewCmd(),\n\t\tdocs.NewCmd(),\n\t)\n\n\tif err := rootCmd.Execute(); err != nil {\n\t\tlogger.LogError(err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc imagesCmd() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"images\",\n\t\tShort: \"Commands to work with images\",\n\t}\n\tcmd.AddCommand(\n\t\timages_publish.NewCmd(),\n\t\timages_cleanup.NewCmd(),\n\t\timages_purge.NewCmd(),\n\t)\n\n\treturn cmd\n}\n\nfunc stagesCmd() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"stages\",\n\t\tShort: \"Commands to work with stages, which are cache for images\",\n\t}\n\tcmd.AddCommand(\n\t\tstages_build.NewCmd(),\n\t\tstages_cleanup.NewCmd(),\n\t\tstages_purge.NewCmd(),\n\t)\n\n\treturn cmd\n}\n\nfunc helmCmd() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"helm\",\n\t\tShort: \"Commands to manage deployment with helm\",\n\t}\n\tcmd.AddCommand(\n\t\thelm_get_service_values.NewCmd(),\n\t\tsecretCmd(),\n\t)\n\n\treturn cmd\n}\n\nfunc hostCmd() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"host\",\n\t}\n\tcmd.AddCommand(\n\t\thost_cleanup.NewCmd(),\n\t\thost_purge.NewCmd(),\n\t)\n\n\treturn cmd\n}\n\nfunc secretCmd() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"secret\",\n\t\tShort: \"Commands to work with secrets\",\n\t}\n\tcmd.AddCommand(\n\t\thelm_secret_key_generate.NewCmd(),\n\t\thelm_secret_generate.NewCmd(),\n\t\thelm_secret_extract.NewCmd(),\n\t\thelm_secret_edit.NewCmd(),\n\t\thelm_secret_regenerate.NewCmd(),\n\t)\n\n\treturn cmd\n}\n\nfunc trapTerminationSignals() {\n\tc := make(chan os.Signal, 1)\n\tsignals := []os.Signal{os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT}\n\tsignal.Notify(c, signals...)\n\tgo func() {\n\t\t<-c\n\n\t\tlogger.LogError(errors.New(\"interrupted\"))\n\t\tos.Exit(17)\n\t}()\n}\ndismisspackage main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"syscall\"\n\n\t\"github.com\/spf13\/cobra\"\n\n\t\"github.com\/flant\/werf\/cmd\/werf\/build\"\n\t\"github.com\/flant\/werf\/cmd\/werf\/build_and_publish\"\n\t\"github.com\/flant\/werf\/cmd\/werf\/cleanup\"\n\t\"github.com\/flant\/werf\/cmd\/werf\/dismiss\"\n\t\"github.com\/flant\/werf\/cmd\/werf\/publish\"\n\t\"github.com\/flant\/werf\/cmd\/werf\/purge\"\n\n\thelm_secret_edit \"github.com\/flant\/werf\/cmd\/werf\/helm\/secret\/edit\"\n\thelm_secret_extract \"github.com\/flant\/werf\/cmd\/werf\/helm\/secret\/extract\"\n\thelm_secret_generate \"github.com\/flant\/werf\/cmd\/werf\/helm\/secret\/generate\"\n\thelm_secret_key_generate \"github.com\/flant\/werf\/cmd\/werf\/helm\/secret\/key_generate\"\n\thelm_secret_regenerate \"github.com\/flant\/werf\/cmd\/werf\/helm\/secret\/regenerate\"\n\n\t\"github.com\/flant\/werf\/cmd\/werf\/tools\/slugify\"\n\n\timages_cleanup \"github.com\/flant\/werf\/cmd\/werf\/images\/cleanup\"\n\timages_publish \"github.com\/flant\/werf\/cmd\/werf\/images\/publish\"\n\timages_purge \"github.com\/flant\/werf\/cmd\/werf\/images\/purge\"\n\n\tstages_build \"github.com\/flant\/werf\/cmd\/werf\/stages\/build\"\n\tstages_cleanup \"github.com\/flant\/werf\/cmd\/werf\/stages\/cleanup\"\n\tstages_purge \"github.com\/flant\/werf\/cmd\/werf\/stages\/purge\"\n\n\thost_cleanup \"github.com\/flant\/werf\/cmd\/werf\/host\/cleanup\"\n\thost_purge \"github.com\/flant\/werf\/cmd\/werf\/host\/purge\"\n\n\thelm_get_service_values \"github.com\/flant\/werf\/cmd\/werf\/helm\/get_service_values\"\n\n\t\"github.com\/flant\/werf\/cmd\/werf\/completion\"\n\t\"github.com\/flant\/werf\/cmd\/werf\/docs\"\n\t\"github.com\/flant\/werf\/cmd\/werf\/version\"\n\n\t\"github.com\/flant\/werf\/cmd\/werf\/common\"\n\t\"github.com\/flant\/werf\/cmd\/werf\/common\/templates\"\n\t\"github.com\/flant\/werf\/pkg\/logger\"\n\t\"github.com\/flant\/werf\/pkg\/process_exterminator\"\n)\n\nfunc main() {\n\ttrapTerminationSignals()\n\n\tlogger.Init(logger.Options{})\n\n\tif err := process_exterminator.Init(); err != nil {\n\t\tlogger.LogError(fmt.Errorf(\"process exterminator initialization error: %s\", err))\n\t\tos.Exit(1)\n\t}\n\n\trootCmd := &cobra.Command{\n\t\tUse: \"werf\",\n\t\tShort: \"Werf helps to implement and support Continuous Integration and Continuous Delivery\",\n\t\tLong: common.GetLongCommandDescription(`Werf helps to implement and support Continuous Integration and Continuous Delivery.\n\nFind more information at https:\/\/flant.github.io\/werf`),\n\t\tSilenceUsage: true,\n\t\tSilenceErrors: true,\n\t}\n\n\tgroups := templates.CommandGroups{\n\t\t{\n\t\t\tMessage: \"Main Commands:\",\n\t\t\tCommands: []*cobra.Command{\n\t\t\t\tbuild.NewCmd(),\n\t\t\t\tpublish.NewCmd(),\n\t\t\t\tbuild_and_publish.NewCmd(),\n\t\t\t\tdismiss.NewCmd(),\n\t\t\t\tcleanup.NewCmd(),\n\t\t\t\tpurge.NewCmd(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tMessage: \"Tools Commands:\",\n\t\t\tCommands: []*cobra.Command{\n\t\t\t\tslugify.NewCmd(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tMessage: \"Lowlevel Management Commands:\",\n\t\t\tCommands: []*cobra.Command{\n\t\t\t\tstagesCmd(),\n\t\t\t\timagesCmd(),\n\t\t\t\thelmCmd(),\n\t\t\t\thostCmd(),\n\t\t\t},\n\t\t},\n\t}\n\tgroups.Add(rootCmd)\n\n\ttemplates.ActsAsRootCommand(rootCmd, groups...)\n\n\trootCmd.AddCommand(\n\t\tcompletion.NewCmd(rootCmd),\n\t\tversion.NewCmd(),\n\t\tdocs.NewCmd(),\n\t)\n\n\tif err := rootCmd.Execute(); err != nil {\n\t\tlogger.LogError(err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc imagesCmd() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"images\",\n\t\tShort: \"Commands to work with images\",\n\t}\n\tcmd.AddCommand(\n\t\timages_publish.NewCmd(),\n\t\timages_cleanup.NewCmd(),\n\t\timages_purge.NewCmd(),\n\t)\n\n\treturn cmd\n}\n\nfunc stagesCmd() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"stages\",\n\t\tShort: \"Commands to work with stages, which are cache for images\",\n\t}\n\tcmd.AddCommand(\n\t\tstages_build.NewCmd(),\n\t\tstages_cleanup.NewCmd(),\n\t\tstages_purge.NewCmd(),\n\t)\n\n\treturn cmd\n}\n\nfunc helmCmd() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"helm\",\n\t\tShort: \"Commands to manage deployment with helm\",\n\t}\n\tcmd.AddCommand(\n\t\thelm_get_service_values.NewCmd(),\n\t\tsecretCmd(),\n\t)\n\n\treturn cmd\n}\n\nfunc hostCmd() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"host\",\n\t}\n\tcmd.AddCommand(\n\t\thost_cleanup.NewCmd(),\n\t\thost_purge.NewCmd(),\n\t)\n\n\treturn cmd\n}\n\nfunc secretCmd() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"secret\",\n\t\tShort: \"Commands to work with secrets\",\n\t}\n\tcmd.AddCommand(\n\t\thelm_secret_key_generate.NewCmd(),\n\t\thelm_secret_generate.NewCmd(),\n\t\thelm_secret_extract.NewCmd(),\n\t\thelm_secret_edit.NewCmd(),\n\t\thelm_secret_regenerate.NewCmd(),\n\t)\n\n\treturn cmd\n}\n\nfunc trapTerminationSignals() {\n\tc := make(chan os.Signal, 1)\n\tsignals := []os.Signal{os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT}\n\tsignal.Notify(c, signals...)\n\tgo func() {\n\t\t<-c\n\n\t\tlogger.LogError(errors.New(\"interrupted\"))\n\t\tos.Exit(17)\n\t}()\n}\n<|endoftext|>"} {"text":"package cmd\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/couchbaselabs\/sgload\/sgload\"\n\t\"github.com\/spf13\/cobra\"\n)\n\nvar (\n\tnumWriters *int\n\tcreateWriters *bool\n\twriterDelayMs *int\n)\n\n\/\/ writeloadCmd respresents the writeload command\nvar writeloadCmd = &cobra.Command{\n\tUse: \"writeload\",\n\tShort: \"Generate a write load\",\n\tLong: `Generate a write load`,\n\tRun: func(cmd *cobra.Command, args []string) {\n\n\t\t\/\/ Setup logger\n\t\tlogger = sgload.Logger()\n\n\t\tloadSpec := createLoadSpecFromArgs()\n\t\tsgload.SetLogLevel(loadSpec.LogLevel)\n\n\t\twriteLoadSpec := sgload.WriteLoadSpec{\n\t\t\tLoadSpec: loadSpec,\n\t\t\tNumWriters: *numWriters,\n\t\t\tCreateWriters: *createWriters,\n\t\t}\n\t\tif err := writeLoadSpec.Validate(); err != nil {\n\n\t\t\tpanic(fmt.Sprintf(\"Invalid parameters: %+v. Error: %v\", writeLoadSpec, err))\n\t\t}\n\t\twriteLoadRunner := sgload.NewWriteLoadRunner(writeLoadSpec)\n\t\tif err := writeLoadRunner.Run(); err != nil {\n\t\t\tpanic(fmt.Sprintf(\"Writeload.Run() failed with: %v\", err))\n\t\t}\n\n\t},\n}\n\nfunc init() {\n\n\tRootCmd.AddCommand(writeloadCmd)\n\n\tnumWriters = writeloadCmd.PersistentFlags().Int(\n\t\tNUM_WRITERS_CMD_NAME,\n\t\tNUM_WRITERS_CMD_DEFAULT,\n\t\tNUM_WRITERS_CMD_DESC,\n\t)\n\n\tcreateWriters = writeloadCmd.PersistentFlags().Bool(\n\t\tCREATE_WRITERS_CMD_NAME,\n\t\tCREATE_WRITERS_CMD_DEFAULT,\n\t\tCREATE_WRITERS_CMD_DESC,\n\t)\n\n\twriterDelayMs = writeloadCmd.PersistentFlags().Int(\n\t\tWRITER_DELAY_CMD_NAME,\n\t\tWRITER_DELAY_CMD_DEFAULT,\n\t\tWRITER_DELAY_CMD_DESC,\n\t)\n\n}\nFixes #70 writerdelayms parameter is not taken into account while running sgload.package cmd\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/couchbaselabs\/sgload\/sgload\"\n\t\"github.com\/spf13\/cobra\"\n\t\"time\"\n)\n\nvar (\n\tnumWriters *int\n\tcreateWriters *bool\n\twriterDelayMs *int\n)\n\n\/\/ writeloadCmd respresents the writeload command\nvar writeloadCmd = &cobra.Command{\n\tUse: \"writeload\",\n\tShort: \"Generate a write load\",\n\tLong: `Generate a write load`,\n\tRun: func(cmd *cobra.Command, args []string) {\n\n\t\t\/\/ Setup logger\n\t\tlogger = sgload.Logger()\n\n\t\tloadSpec := createLoadSpecFromArgs()\n\t\tsgload.SetLogLevel(loadSpec.LogLevel)\n\n\t\tdelayBetweenWrites := time.Millisecond * time.Duration(*writerDelayMs)\n\n\t\twriteLoadSpec := sgload.WriteLoadSpec{\n\t\t\tLoadSpec: loadSpec,\n\t\t\tNumWriters: *numWriters,\n\t\t\tCreateWriters: *createWriters,\n\t\t\tDelayBetweenWrites: delayBetweenWrites,\n\t\t}\n\t\tif err := writeLoadSpec.Validate(); err != nil {\n\n\t\t\tpanic(fmt.Sprintf(\"Invalid parameters: %+v. Error: %v\", writeLoadSpec, err))\n\t\t}\n\t\twriteLoadRunner := sgload.NewWriteLoadRunner(writeLoadSpec)\n\t\tif err := writeLoadRunner.Run(); err != nil {\n\t\t\tpanic(fmt.Sprintf(\"Writeload.Run() failed with: %v\", err))\n\t\t}\n\n\t},\n}\n\nfunc init() {\n\n\tRootCmd.AddCommand(writeloadCmd)\n\n\tnumWriters = writeloadCmd.PersistentFlags().Int(\n\t\tNUM_WRITERS_CMD_NAME,\n\t\tNUM_WRITERS_CMD_DEFAULT,\n\t\tNUM_WRITERS_CMD_DESC,\n\t)\n\n\tcreateWriters = writeloadCmd.PersistentFlags().Bool(\n\t\tCREATE_WRITERS_CMD_NAME,\n\t\tCREATE_WRITERS_CMD_DEFAULT,\n\t\tCREATE_WRITERS_CMD_DESC,\n\t)\n\n\twriterDelayMs = writeloadCmd.PersistentFlags().Int(\n\t\tWRITER_DELAY_CMD_NAME,\n\t\tWRITER_DELAY_CMD_DEFAULT,\n\t\tWRITER_DELAY_CMD_DESC,\n\t)\n\n}\n<|endoftext|>"} {"text":"package flite\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestTextToSpeech(t *testing.T) {\n\tvoice, err := VoiceSelect(\"awb\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\ts := TextToSpeech(\"Hello World\", voice, \"play\")\n\tif s == 0 {\n\t\tt.Fatalf(\"0 seconds of speech generated\")\n\t}\n}\n\nfunc TestTextToWave(t *testing.T) {\n\tvoice, err := VoiceSelect(\"awb\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\twav := TextToWave(\"Hello World\", voice)\n\tif wav.NumChannels != 1 {\n\t\tt.Fatalf(\"Wave number of channels != 1\")\n\t}\n\n\tif wav.SampleRate != 16000 {\n\t\tt.Fatalf(\"Wave sample rate != 16000\")\n\t}\n}\n\nfunc TestVoiceSelect(t *testing.T) {\n\tvar voices = []string{\"awb\", \"kal16\", \"kal\", \"rms\", \"slt\"}\n\n\tfor _, v := range voices {\n\t\tvoice, err := VoiceSelect(v)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tTextToSpeech(\"Testing \"+v, voice, \"play\")\n\t\ttime.Sleep(1 * time.Second)\n\n\t\ts := TextToSpeech(\"Hello World\", voice, \"play\")\n\t\tif s == 0 {\n\t\t\tt.Fatalf(\"%s: 0 seconds of speech generated\", v)\n\t\t}\n\n\t\ttime.Sleep(1 * time.Second)\n\t}\n}\nFix testpackage flite\n\nimport (\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestTextToSpeech(t *testing.T) {\n\tvoice, err := VoiceSelect(\"awb\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\ts := TextToSpeech(\"Hello World\", voice, \"play\")\n\tif s == 0 {\n\t\tt.Fatalf(\"0 seconds of speech generated\")\n\t}\n}\n\nfunc TestTextToWave(t *testing.T) {\n\tvoice, err := VoiceSelect(\"awb\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\twav := TextToWave(\"Hello World\", voice)\n\tif wav.NumChannels != 1 {\n\t\tt.Fatalf(\"Wave number of channels != 1\")\n\t}\n\n\tif wav.SampleRate != 16000 {\n\t\tt.Fatalf(\"Wave sample rate != 16000\")\n\t}\n}\n\nfunc TestVoiceSelect(t *testing.T) {\n\tvar voices = []string{\"awb\", \"kal16\", \"kal\", \"rms\", \"slt\"}\n\n\tfor _, v := range voices {\n\t\tvoice, err := VoiceSelect(v)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tTextToSpeech(\"Testing \"+v, voice, \"play\")\n\t\ttime.Sleep(1 * time.Second)\n\n\t\tTextToSpeech(\"Hello World\", voice, \"play\")\n\t\ttime.Sleep(1 * time.Second)\n\t}\n}\n<|endoftext|>"} {"text":"package zmqOutput_test\n\nimport (\n\t. \"github.com\/CapillarySoftware\/goiostat\/diskStat\"\n\t. \"github.com\/CapillarySoftware\/goiostat\/zmqOutput\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t\/\/ . \"github.com\/CapillarySoftware\/goiostat\/protoStat\"\n\t\/\/ \"fmt\"\n\t. \"github.com\/onsi\/gomega\"\n)\n\nvar _ = Describe(\"ZmqOutput\", func() {\n\n\tIt(\"Testing basic send stats\", func() {\n\t\toutput := ZmqOutput{}\n\t\toutput.Connect(\"ipc:\/\/\/tmp\/zmqOutput.ipc\")\n\t\t\/\/ defer output.Close()\n\t\tstats := ExtendedIoStats{\n\t\t\t\"Device\",\n\t\t\tfloat64(0),\n\t\t\tfloat64(0),\n\t\t\tfloat64(0),\n\t\t\tfloat64(0),\n\t\t\tfloat64(0),\n\t\t\tfloat64(0),\n\t\t\tfloat64(0),\n\t\t\tfloat64(0),\n\t\t\tfloat64(0),\n\t\t\tfloat64(0),\n\t\t\tfloat64(0),\n\t\t\tfloat64(0),\n\t\t\tfloat64(0),\n\t\t}\n\t\terr := output.SendStats(&stats)\n\t\tExpect(err).Should(BeNil())\n\t})\n\n\tIt(\"Call sendStats without initializing socket\", func() {\n\t\toutput := ZmqOutput{}\n\t\tstats := ExtendedIoStats{\n\t\t\t\"Device\",\n\t\t\tfloat64(0),\n\t\t\tfloat64(0),\n\t\t\tfloat64(0),\n\t\t\tfloat64(0),\n\t\t\tfloat64(0),\n\t\t\tfloat64(0),\n\t\t\tfloat64(0),\n\t\t\tfloat64(0),\n\t\t\tfloat64(0),\n\t\t\tfloat64(0),\n\t\t\tfloat64(0),\n\t\t\tfloat64(0),\n\t\t\tfloat64(0),\n\t\t}\n\t\terr := output.SendStats(&stats)\n\t\tExpect(err).ShouldNot(BeNil())\n\t})\n})\nwoo datapackage zmqOutput_test\n\nimport (\n\t. \"github.com\/CapillarySoftware\/goiostat\/diskStat\"\n\t. \"github.com\/CapillarySoftware\/goiostat\/zmqOutput\"\n\t. \"github.com\/onsi\/ginkgo\"\n\t\/\/ . \"github.com\/CapillarySoftware\/goiostat\/protoStat\"\n\t\"fmt\"\n\t. \"github.com\/onsi\/gomega\"\n\tzmq \"github.com\/pebbe\/zmq3\"\n)\n\nfunc sendStats(output ZmqOutput, eStat *ExtendedIoStats, sendCount int) {\n\tfor i := 0; i <= sendCount; i++ {\n\t\toutput.SendStats(eStat)\n\t}\n}\n\nvar _ = Describe(\"ZmqOutput\", func() {\n\teStat := ExtendedIoStats{\n\t\t\"Device\",\n\t\tfloat64(0),\n\t\tfloat64(0),\n\t\tfloat64(0),\n\t\tfloat64(0),\n\t\tfloat64(0),\n\t\tfloat64(0),\n\t\tfloat64(0),\n\t\tfloat64(0),\n\t\tfloat64(0),\n\t\tfloat64(0),\n\t\tfloat64(0),\n\t\tfloat64(0),\n\t\tfloat64(0),\n\t}\n\n\turl := \"ipc:\/\/\/tmp\/testOutput.ipc\"\n\n\tIt(\"Testing basic send stats\", func() {\n\t\toutput := ZmqOutput{}\n\t\toutput.Connect(url)\n\t\tdefer output.Close()\n\n\t\terr := output.SendStats(&eStat)\n\t\tExpect(err).Should(BeNil())\n\t})\n\n\tIt(\"Call sendStats without initializing socket\", func() {\n\t\toutput := ZmqOutput{}\n\t\tdefer output.Close()\n\t\terr := output.SendStats(&eStat)\n\t\tExpect(err).ShouldNot(BeNil())\n\t})\n\n\tIt(\"Send to recv socket and validate we get what we expect\", func() {\n\t\toutput := ZmqOutput{}\n\t\tdefer output.Close()\n\t\toutput.Connect(url)\n\n\t\trecv, err := zmq.NewSocket(zmq.PULL)\n\t\tExpect(err).Should(BeNil())\n\t\tdefer recv.Close()\n\n\t\trecv.Bind(url)\n\t\tgo sendStats(output, &eStat, 1)\n\n\t\tfor i := 0; i <= 12; i++ {\n\t\t\ts, err := recv.RecvBytes(0)\n\t\t\tfmt.Println(\"bytes: \", s)\n\t\t\tExpect(err).Should(BeNil())\n\t\t}\n\t\ts, err := recv.RecvBytes(0)\n\t\tExpect(err).Should(BeNil())\n\t\tfmt.Println(\"last: \", s)\n\n\t})\n})\n<|endoftext|>"} {"text":"package form\n\nimport (\n\t\"html\/template\"\n\t\"net\/http\"\n\n\t\"github.com\/janekolszak\/idp\/core\"\n\t\"github.com\/janekolszak\/idp\/userdb\"\n)\n\ntype Config struct {\n\tLoginForm string\n\tLoginUsernameField string\n\tLoginPasswordField string\n\tUserStore userdb.Store\n}\n\ntype FormAuth struct {\n\tConfig\n}\n\nfunc NewFormAuth(c Config) (*FormAuth, error) {\n\tif c.LoginUsernameField == \"\" ||\n\t\tc.LoginPasswordField == \"\" ||\n\t\tc.LoginUsernameField == c.LoginPasswordField {\n\t\treturn nil, core.ErrorInvalidConfig\n\t}\n\tauth := FormAuth{Config: c}\n\treturn &auth, nil\n}\n\nfunc (f *FormAuth) Check(r *http.Request) (user string, err error) {\n\tr.ParseForm()\n\tuser = r.Form.Get(f.LoginUsernameField)\n\tpassword := r.Form.Get(f.LoginPasswordField)\n\n\terr = f.UserStore.Check(user, password)\n\tif err != nil {\n\t\tuser = \"\"\n\t\terr = core.ErrorAuthenticationFailure\n\t}\n\n\treturn\n}\n\nfunc (a *FormAuth) WriteError(w http.ResponseWriter, r *http.Request, err error) error {\n\tmsg := \"\"\n\tif r.Method == \"POST\" && err != nil {\n\t\tswitch err {\n\t\tcase core.ErrorAuthenticationFailure:\n\t\t\tmsg = \"Authentication failed\"\n\n\t\tdefault:\n\t\t\tmsg = \"An error occurred\"\n\t\t}\n\t}\n\tt := template.Must(template.New(\"tmpl\").Parse(a.LoginForm))\n\tt.Execute(w, msg)\n\treturn nil\n}\n\nfunc (a *FormAuth) Write(w http.ResponseWriter, r *http.Request) error {\n\treturn nil\n}\nproviders\/form-auth: return template parse errorpackage form\n\nimport (\n\t\"html\/template\"\n\t\"net\/http\"\n\n\t\"github.com\/janekolszak\/idp\/core\"\n\t\"github.com\/janekolszak\/idp\/userdb\"\n)\n\ntype Config struct {\n\tLoginForm string\n\tLoginUsernameField string\n\tLoginPasswordField string\n\tUserStore userdb.Store\n}\n\ntype FormAuth struct {\n\tConfig\n}\n\nfunc NewFormAuth(c Config) (*FormAuth, error) {\n\tif c.LoginUsernameField == \"\" ||\n\t\tc.LoginPasswordField == \"\" ||\n\t\tc.LoginUsernameField == c.LoginPasswordField {\n\t\treturn nil, core.ErrorInvalidConfig\n\t}\n\tauth := FormAuth{Config: c}\n\treturn &auth, nil\n}\n\nfunc (f *FormAuth) Check(r *http.Request) (user string, err error) {\n\tr.ParseForm()\n\tuser = r.Form.Get(f.LoginUsernameField)\n\tpassword := r.Form.Get(f.LoginPasswordField)\n\n\terr = f.UserStore.Check(user, password)\n\tif err != nil {\n\t\tuser = \"\"\n\t\terr = core.ErrorAuthenticationFailure\n\t}\n\n\treturn\n}\n\nfunc (a *FormAuth) WriteError(w http.ResponseWriter, r *http.Request, err error) error {\n\tmsg := \"\"\n\tif r.Method == \"POST\" && err != nil {\n\t\tswitch err {\n\t\tcase core.ErrorAuthenticationFailure:\n\t\t\tmsg = \"Authentication failed\"\n\n\t\tdefault:\n\t\t\tmsg = \"An error occurred\"\n\t\t}\n\t}\n\tt := template.Must(template.New(\"tmpl\").Parse(a.LoginForm))\n\treturn t.Execute(w, msg)\n}\n\nfunc (a *FormAuth) Write(w http.ResponseWriter, r *http.Request) error {\n\treturn nil\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\t\"time\"\n\n\tsg \"github.com\/rbastic\/dyndao\/sqlgen\"\n\n\tdorm \"github.com\/rbastic\/dyndao\/orm\"\n\n\t\"github.com\/rbastic\/dyndao\/schema\/test\/mock\"\n\n\t_ \"github.com\/mattn\/go-sqlite3\"\n\t\"github.com\/rbastic\/dyndao\/adapters\/core\"\n\tsqliteAdapter \"github.com\/rbastic\/dyndao\/adapters\/sqlite\"\n)\n\nvar (\n\tdefaultDriver = \"sqlite3\"\n\tdefaultDSN = \"file::memory:?mode=memory&cache=shared\"\n)\n\nfunc fatalIf(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc getDefaultContext() (context.Context, context.CancelFunc) {\n\treturn context.WithTimeout(context.Background(), 3*time.Second)\n}\n\nfunc getDriver() string {\n\treturn defaultDriver\n}\n\nfunc getDSN() string {\n\tdsn := os.Getenv(\"DSN\")\n\tif dsn == \"\" {\n\t\tdsn = defaultDSN\n\t}\n\n\treturn dsn\n}\n\n\/\/ TODO: refactor this so it is available from somewhere else\n\/\/ (so that user code doesn't have to replicate this)\nfunc getSQLGen() *sg.SQLGenerator {\n\tsqlGen := sqliteAdapter.New(core.New())\n\tsg.PanicIfInvalid(sqlGen)\n\treturn sqlGen\n}\n\nfunc main() {\n\tdriver := getDriver()\n\tdsn := getDSN()\n\tdb, err := dorm.GetDB(driver, dsn)\n\tfatalIf(err)\n\n\tdefer func() {\n\t\terr = db.Close()\n\t\tfatalIf(err)\n\t}()\n\n\t\/\/ Load the sample included schema\n\t\/\/ (which is used by the internal dyndao test suite)\n\tsch := mock.NestedSchema()\n\n\t\/\/ Instantiate the ORM instance\n\torm := dorm.New(getSQLGen(), sch, db)\n\n\t\/\/ CreateTables will create all tables within a given schema\n\t{\n\t\t\/\/ Instantiate our default context\n\t\tctx, cancel := getDefaultContext()\n\t\terr = orm.CreateTables(ctx)\n\t\tcancel()\n\t\tfatalIf(err)\n\t}\n\n\t{\n\t\t\/\/ Instantiate our default context\n\t\tctx, cancel := getDefaultContext()\n\n\t\t\/\/ Attempt to insert a record\n\t\tnumRows, err := orm.Insert(ctx, nil, mock.RandomPerson())\n\t\tfatalIf(err)\n\t\tif numRows == 0 {\n\t\t\tpanic(\"Insert returned zero rows affected -- something is clearly wrong\")\n\t\t} else {\n\t\t\tfmt.Println(\"Looks like we inserted something\")\n\t\t}\n\t\tcancel()\n\t}\n\n\t\/\/ DropTables will create all tables within a given schema\n\t{\n\t\tctx, cancel := getDefaultContext()\n\t\terr = orm.DropTables(ctx)\n\t\tcancel()\n\t\tfatalIf(err)\n\t}\n}\nadd comments, deferspackage main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\t\"time\"\n\n\tsg \"github.com\/rbastic\/dyndao\/sqlgen\"\n\n\tdorm \"github.com\/rbastic\/dyndao\/orm\"\n\n\t\"github.com\/rbastic\/dyndao\/schema\/test\/mock\"\n\n\t_ \"github.com\/mattn\/go-sqlite3\"\n\t\"github.com\/rbastic\/dyndao\/adapters\/core\"\n\tsqliteAdapter \"github.com\/rbastic\/dyndao\/adapters\/sqlite\"\n)\n\n\/\/ Look at the adapter Makefiles for other examples of drivers and supported DSNs.\n\/\/ TODO: Perhaps I should offer these as standard config opts.\nvar (\n\tdefaultDriver = \"sqlite3\"\n\tdefaultDSN = \"file::memory:?mode=memory&cache=shared\"\n)\n\nfunc fatalIf(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc getDefaultContext() (context.Context, context.CancelFunc) {\n\treturn context.WithTimeout(context.Background(), 3*time.Second)\n}\n\nfunc getDriver() string {\n\treturn defaultDriver\n}\n\nfunc getDSN() string {\n\tdsn := os.Getenv(\"DSN\")\n\tif dsn == \"\" {\n\t\tdsn = defaultDSN\n\t}\n\n\treturn dsn\n}\n\n\/\/ TODO: refactor this so it is available from somewhere else\n\/\/ (so that user code doesn't have to replicate this)\nfunc getSQLGen() *sg.SQLGenerator {\n\tsqlGen := sqliteAdapter.New(core.New())\n\tsg.PanicIfInvalid(sqlGen)\n\treturn sqlGen\n}\n\nfunc main() {\n\tdriver := getDriver()\n\tdsn := getDSN()\n\tdb, err := dorm.GetDB(driver, dsn)\n\tfatalIf(err)\n\n\tdefer func() {\n\t\terr = db.Close()\n\t\tfatalIf(err)\n\t}()\n\n\t\/\/ Load the sample included schema\n\t\/\/ (which is also used by the internal dyndao test suite)\n\tsch := mock.NestedSchema()\n\n\t\/\/ Instantiate the ORM instance\n\torm := dorm.New(getSQLGen(), sch, db)\n\n\t\/\/ CreateTables will create all tables within a given schema\n\t{\n\t\t\/\/ Instantiate our default context\n\t\tctx, cancel := getDefaultContext()\n\t\tdefer cancel()\n\t\terr = orm.CreateTables(ctx)\n\t\tfatalIf(err)\n\t}\n\n\t{\n\t\t\/\/ Instantiate our default context\n\t\tctx, cancel := getDefaultContext()\n\t\tdefer cancel()\n\t\t\/\/ Attempt to insert a record\n\t\tnumRows, err := orm.Insert(ctx, nil, mock.RandomPerson())\n\t\tfatalIf(err)\n\t\tif numRows == 0 {\n\t\t\tpanic(\"Insert returned zero rows affected -- something is clearly wrong\")\n\t\t} else {\n\t\t\tfmt.Println(\"Looks like we inserted something\")\n\t\t}\n\t}\n\n\t\/\/ DropTables will create all tables within a given schema\n\t{\n\t\tctx, cancel := getDefaultContext()\n\t\tdefer cancel()\n\t\terr = orm.DropTables(ctx)\n\t\tfatalIf(err)\n\t}\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com\/jsgoecke\/tesla\"\n)\n\nfunc main() {\n\tclient, err := tesla.NewClient(\n\t\t&tesla.Auth{\n\t\t\tClientID: os.Getenv(\"TESLA_CLIENT_ID\"),\n\t\t\tClientSecret: os.Getenv(\"TESLA_CLIENT_SECRET\"),\n\t\t\tEmail: os.Getenv(\"TESLA_USERNAME\"),\n\t\t\tPassword: os.Getenv(\"TESLA_PASSWORD\"),\n\t\t})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tvehicles, err := client.Vehicles()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tvehicle := vehicles[0]\n\tstatus, err := vehicle.MobileEnabled()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(status)\n\tfmt.Println(vehicle.ChargeState())\n\tfmt.Println(vehicle.ClimateState())\n\tfmt.Println(vehicle.DriveState())\n\tfmt.Println(vehicle.GuiSettings())\n\tfmt.Println(vehicle.VehicleState())\n\tfmt.Println(vehicle.HonkHorn())\n\tfmt.Println(vehicle.FlashLights())\n\tfmt.Println(vehicle.Wakeup())\n\tfmt.Println(vehicle.OpenChargePort())\n\tfmt.Println(vehicle.ResetValetPIN())\n\tfmt.Println(vehicle.SetChargeLimitStandard())\n\tfmt.Println(vehicle.SetChargeLimit(50))\n\tfmt.Println(vehicle.StartCharging())\n\tfmt.Println(vehicle.StopCharging())\n\tfmt.Println(vehicle.SetChargeLimitMax())\n\tfmt.Println(vehicle.StartAirConditioning())\n\tfmt.Println(vehicle.StopAirConditioning())\n\tfmt.Println(vehicle.UnlockDoors())\n\tfmt.Println(vehicle.LockDoors())\n\tfmt.Println(vehicle.SetTemprature(72.0, 72.0))\n\tfmt.Println(vehicle.Start(os.Getenv(\"TESLA_PASSWORD\")))\n\tfmt.Println(vehicle.OpenTrunk(\"rear\"))\n\tfmt.Println(vehicle.OpenTrunk(\"front\"))\n\tfmt.Println(vehicle.MovePanoRoof(\"vent\", 0))\n\tfmt.Println(vehicle.MovePanoRoof(\"open\", 0))\n\tfmt.Println(vehicle.MovePanoRoof(\"move\", 50))\n\tfmt.Println(vehicle.MovePanoRoof(\"close\", 0))\n\n\t\/\/ Take care with these, as the car will move\n\tfmt.Println(vehicle.AutoparkForward())\n\tfmt.Println(vehicle.AutoparkReverse())\n\t\/\/ Take care with these, as the car will move\n\n\t\/\/ Stream vehicle events\n\teventChan, err := vehicle.Stream()\n\tif err != nil {\n\t\tfor {\n\t\t\tevent := <-eventChan\n\t\t\tif event != nil {\n\t\t\t\teventJSON, _ := json.Marshal(event)\n\t\t\t\tfmt.Println(string(eventJSON))\n\t\t\t} else {\n\t\t\t\tfmt.Println(\"HTTP Stream timeout!\")\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n}\nAdded TriggerHomeLink to examplepackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com\/jsgoecke\/tesla\"\n)\n\nfunc main() {\n\tclient, err := tesla.NewClient(\n\t\t&tesla.Auth{\n\t\t\tClientID: os.Getenv(\"TESLA_CLIENT_ID\"),\n\t\t\tClientSecret: os.Getenv(\"TESLA_CLIENT_SECRET\"),\n\t\t\tEmail: os.Getenv(\"TESLA_USERNAME\"),\n\t\t\tPassword: os.Getenv(\"TESLA_PASSWORD\"),\n\t\t})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tvehicles, err := client.Vehicles()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tvehicle := vehicles[0]\n\tstatus, err := vehicle.MobileEnabled()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(status)\n\tfmt.Println(vehicle.ChargeState())\n\tfmt.Println(vehicle.ClimateState())\n\tfmt.Println(vehicle.DriveState())\n\tfmt.Println(vehicle.GuiSettings())\n\tfmt.Println(vehicle.VehicleState())\n\tfmt.Println(vehicle.HonkHorn())\n\tfmt.Println(vehicle.FlashLights())\n\tfmt.Println(vehicle.Wakeup())\n\tfmt.Println(vehicle.OpenChargePort())\n\tfmt.Println(vehicle.ResetValetPIN())\n\tfmt.Println(vehicle.SetChargeLimitStandard())\n\tfmt.Println(vehicle.SetChargeLimit(50))\n\tfmt.Println(vehicle.StartCharging())\n\tfmt.Println(vehicle.StopCharging())\n\tfmt.Println(vehicle.SetChargeLimitMax())\n\tfmt.Println(vehicle.StartAirConditioning())\n\tfmt.Println(vehicle.StopAirConditioning())\n\tfmt.Println(vehicle.UnlockDoors())\n\tfmt.Println(vehicle.LockDoors())\n\tfmt.Println(vehicle.SetTemprature(72.0, 72.0))\n\tfmt.Println(vehicle.Start(os.Getenv(\"TESLA_PASSWORD\")))\n\tfmt.Println(vehicle.OpenTrunk(\"rear\"))\n\tfmt.Println(vehicle.OpenTrunk(\"front\"))\n\tfmt.Println(vehicle.MovePanoRoof(\"vent\", 0))\n\tfmt.Println(vehicle.MovePanoRoof(\"open\", 0))\n\tfmt.Println(vehicle.MovePanoRoof(\"move\", 50))\n\tfmt.Println(vehicle.MovePanoRoof(\"close\", 0))\n\tfmt.Println(vehicle.TriggerHomeLink())\n\n\t\/\/ Take care with these, as the car will move\n\tfmt.Println(vehicle.AutoparkForward())\n\tfmt.Println(vehicle.AutoparkReverse())\n\t\/\/ Take care with these, as the car will move\n\n\t\/\/ Stream vehicle events\n\teventChan, err := vehicle.Stream()\n\tif err != nil {\n\t\tfor {\n\t\t\tevent := <-eventChan\n\t\t\tif event != nil {\n\t\t\t\teventJSON, _ := json.Marshal(event)\n\t\t\t\tfmt.Println(string(eventJSON))\n\t\t\t} else {\n\t\t\t\tfmt.Println(\"HTTP Stream timeout!\")\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"package gcsresource\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\/http\"\n\t\"os\"\n\n\t\"github.com\/cheggaaa\/pb\"\n\t\"golang.org\/x\/oauth2\"\n\toauthgoogle \"golang.org\/x\/oauth2\/google\"\n\t\"google.golang.org\/api\/storage\/v1\"\n)\n\ntype GCSClient interface {\n\tBucketObjects(bucketName string, prefix string) ([]string, error)\n\tObjectGenerations(bucketName string, objectPath string) ([]int64, error)\n\tDownloadFile(bucketName string, objectPath string, generation int64, localPath string) error\n\tUploadFile(bucketName string, objectPath string, localPath string) (int64, error)\n\tURL(bucketName string, objectPath string, generation int64) (string, error)\n\tDeleteObject(bucketName string, objectPath string, generation int64) error\n}\n\ntype gcsclient struct {\n\tclient *storage.Service\n\tprogressOutput io.Writer\n}\n\nfunc NewGCSClient(\n\tprogressOutput io.Writer,\n\tproject string,\n\tjsonKey string,\n) (GCSClient, error) {\n\tvar err error\n\tvar storageClient *http.Client\n\tvar userAgent = \"gcs-resource\/0.0.1\"\n\n\tif jsonKey != \"\" {\n\t\tstorageJwtConf, err := oauthgoogle.JWTConfigFromJSON([]byte(jsonKey), storage.DevstorageFullControlScope)\n\t\tif err != nil {\n\t\t\treturn &gcsclient{}, err\n\t\t}\n\t\tstorageClient = storageJwtConf.Client(oauth2.NoContext)\n\t} else {\n\t\tstorageClient, err = oauthgoogle.DefaultClient(oauth2.NoContext, storage.DevstorageFullControlScope)\n\t\tif err != nil {\n\t\t\treturn &gcsclient{}, err\n\t\t}\n\t}\n\n\tstorageService, err := storage.New(storageClient)\n\tif err != nil {\n\t\treturn &gcsclient{}, err\n\t}\n\tstorageService.UserAgent = userAgent\n\n\treturn &gcsclient{\n\t\tclient: storageService,\n\t\tprogressOutput: progressOutput,\n\t}, nil\n}\n\nfunc (client *gcsclient) BucketObjects(bucketName string, prefix string) ([]string, error) {\n\tbucketObjects, err := client.getBucketObjects(bucketName, prefix)\n\tif err != nil {\n\t\treturn []string{}, err\n\t}\n\n\treturn bucketObjects, nil\n}\n\nfunc (client *gcsclient) ObjectGenerations(bucketName string, objectPath string) ([]int64, error) {\n\tisBucketVersioned, err := client.getBucketVersioning(bucketName)\n\tif err != nil {\n\t\treturn []int64{}, err\n\t}\n\n\tif !isBucketVersioned {\n\t\treturn []int64{}, errors.New(\"bucket is not versioned\")\n\t}\n\n\tobjectGenerations, err := client.getObjectGenerations(bucketName, objectPath)\n\tif err != nil {\n\t\treturn []int64{}, err\n\t}\n\n\treturn objectGenerations, nil\n}\n\nfunc (client *gcsclient) DownloadFile(bucketName string, objectPath string, generation int64, localPath string) error {\n\tgetCall := client.client.Objects.Get(bucketName, objectPath)\n\tif generation != 0 {\n\t\tgetCall = getCall.Generation(generation)\n\t}\n\n\tobject, err := getCall.Do()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlocalFile, err := os.Create(localPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer localFile.Close()\n\n\tprogress := client.newProgressBar(int64(object.Size))\n\tprogress.Start()\n\tdefer progress.Finish()\n\n\t\/\/ TODO\n\t_, err = getCall.Download()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (client *gcsclient) UploadFile(bucketName string, objectPath string, localPath string) (int64, error) {\n\tstat, err := os.Stat(localPath)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tlocalFile, err := os.Open(localPath)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer localFile.Close()\n\n\tprogress := client.newProgressBar(stat.Size())\n\tprogress.Start()\n\tdefer progress.Finish()\n\n\tobject := &storage.Object{\n\t\tName: objectPath,\n\t}\n\n\tuploadedObject, err := client.client.Objects.Insert(bucketName, object).Media(progress.NewProxyReader(localFile)).Do()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn uploadedObject.Generation, nil\n}\n\nfunc (client *gcsclient) URL(bucketName string, objectPath string, generation int64) (string, error) {\n\tgetCall := client.client.Objects.Get(bucketName, objectPath)\n\tif generation != 0 {\n\t\tgetCall = getCall.Generation(generation)\n\t}\n\n\tobject, err := getCall.Do()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar url string\n\tif object.MediaLink != \"\" {\n\t\turl = object.MediaLink\n\t} else {\n\t\tif generation != 0 {\n\t\t\turl = fmt.Sprintf(\"gs:\/\/%s\/%s#%d\", bucketName, objectPath, generation)\n\t\t} else {\n\t\t\turl = fmt.Sprintf(\"gs:\/\/%s\/%s\", bucketName, objectPath)\n\t\t}\n\t}\n\n\treturn url, nil\n}\n\nfunc (client *gcsclient) DeleteObject(bucketName string, objectPath string, generation int64) error {\n\tdeleteCall := client.client.Objects.Delete(bucketName, objectPath)\n\tif generation != 0 {\n\t\tdeleteCall = deleteCall.Generation(generation)\n\t}\n\n\terr := deleteCall.Do()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (client *gcsclient) getBucketObjects(bucketName string, prefix string) ([]string, error) {\n\tvar bucketObjects []string\n\n\tpageToken := \"\"\n\tfor {\n\t\tlistCall := client.client.Objects.List(bucketName)\n\t\tlistCall = listCall.PageToken(pageToken)\n\t\tlistCall = listCall.Prefix(prefix)\n\t\tlistCall = listCall.Versions(false)\n\n\t\tobjects, err := listCall.Do()\n\t\tif err != nil {\n\t\t\treturn bucketObjects, err\n\t\t}\n\n\t\tfor _, object := range objects.Items {\n\t\t\tbucketObjects = append(bucketObjects, object.Name)\n\t\t}\n\n\t\tif objects.NextPageToken != \"\" {\n\t\t\tpageToken = objects.NextPageToken\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn bucketObjects, nil\n}\n\nfunc (client *gcsclient) getBucketVersioning(bucketName string) (bool, error) {\n\tbucket, err := client.client.Buckets.Get(bucketName).Do()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn bucket.Versioning.Enabled, nil\n}\n\nfunc (client *gcsclient) getObjectGenerations(bucketName string, objectPath string) ([]int64, error) {\n\tvar objectGenerations []int64\n\n\tpageToken := \"\"\n\tfor {\n\t\tlistCall := client.client.Objects.List(bucketName)\n\t\tlistCall = listCall.PageToken(pageToken)\n\t\tlistCall = listCall.Prefix(objectPath)\n\t\tlistCall = listCall.Versions(true)\n\n\t\tobjects, err := listCall.Do()\n\t\tif err != nil {\n\t\t\treturn objectGenerations, err\n\t\t}\n\n\t\tfor _, object := range objects.Items {\n\t\t\tif object.Name == objectPath {\n\t\t\t\tobjectGenerations = append(objectGenerations, object.Generation)\n\t\t\t}\n\t\t}\n\n\t\tif objects.NextPageToken != \"\" {\n\t\t\tpageToken = objects.NextPageToken\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn objectGenerations, nil\n}\n\nfunc (client *gcsclient) newProgressBar(total int64) *pb.ProgressBar {\n\tprogress := pb.New64(total)\n\n\tprogress.Output = client.progressOutput\n\tprogress.ShowSpeed = true\n\tprogress.Units = pb.U_BYTES\n\tprogress.NotPrint = true\n\n\treturn progress.SetWidth(80)\n}\nRemove MediaLink from URLpackage gcsresource\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\/http\"\n\t\"os\"\n\n\t\"github.com\/cheggaaa\/pb\"\n\t\"golang.org\/x\/oauth2\"\n\toauthgoogle \"golang.org\/x\/oauth2\/google\"\n\t\"google.golang.org\/api\/storage\/v1\"\n)\n\ntype GCSClient interface {\n\tBucketObjects(bucketName string, prefix string) ([]string, error)\n\tObjectGenerations(bucketName string, objectPath string) ([]int64, error)\n\tDownloadFile(bucketName string, objectPath string, generation int64, localPath string) error\n\tUploadFile(bucketName string, objectPath string, localPath string) (int64, error)\n\tURL(bucketName string, objectPath string, generation int64) (string, error)\n\tDeleteObject(bucketName string, objectPath string, generation int64) error\n}\n\ntype gcsclient struct {\n\tclient *storage.Service\n\tprogressOutput io.Writer\n}\n\nfunc NewGCSClient(\n\tprogressOutput io.Writer,\n\tproject string,\n\tjsonKey string,\n) (GCSClient, error) {\n\tvar err error\n\tvar storageClient *http.Client\n\tvar userAgent = \"gcs-resource\/0.0.1\"\n\n\tif jsonKey != \"\" {\n\t\tstorageJwtConf, err := oauthgoogle.JWTConfigFromJSON([]byte(jsonKey), storage.DevstorageFullControlScope)\n\t\tif err != nil {\n\t\t\treturn &gcsclient{}, err\n\t\t}\n\t\tstorageClient = storageJwtConf.Client(oauth2.NoContext)\n\t} else {\n\t\tstorageClient, err = oauthgoogle.DefaultClient(oauth2.NoContext, storage.DevstorageFullControlScope)\n\t\tif err != nil {\n\t\t\treturn &gcsclient{}, err\n\t\t}\n\t}\n\n\tstorageService, err := storage.New(storageClient)\n\tif err != nil {\n\t\treturn &gcsclient{}, err\n\t}\n\tstorageService.UserAgent = userAgent\n\n\treturn &gcsclient{\n\t\tclient: storageService,\n\t\tprogressOutput: progressOutput,\n\t}, nil\n}\n\nfunc (client *gcsclient) BucketObjects(bucketName string, prefix string) ([]string, error) {\n\tbucketObjects, err := client.getBucketObjects(bucketName, prefix)\n\tif err != nil {\n\t\treturn []string{}, err\n\t}\n\n\treturn bucketObjects, nil\n}\n\nfunc (client *gcsclient) ObjectGenerations(bucketName string, objectPath string) ([]int64, error) {\n\tisBucketVersioned, err := client.getBucketVersioning(bucketName)\n\tif err != nil {\n\t\treturn []int64{}, err\n\t}\n\n\tif !isBucketVersioned {\n\t\treturn []int64{}, errors.New(\"bucket is not versioned\")\n\t}\n\n\tobjectGenerations, err := client.getObjectGenerations(bucketName, objectPath)\n\tif err != nil {\n\t\treturn []int64{}, err\n\t}\n\n\treturn objectGenerations, nil\n}\n\nfunc (client *gcsclient) DownloadFile(bucketName string, objectPath string, generation int64, localPath string) error {\n\tgetCall := client.client.Objects.Get(bucketName, objectPath)\n\tif generation != 0 {\n\t\tgetCall = getCall.Generation(generation)\n\t}\n\n\tobject, err := getCall.Do()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlocalFile, err := os.Create(localPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer localFile.Close()\n\n\tprogress := client.newProgressBar(int64(object.Size))\n\tprogress.Start()\n\tdefer progress.Finish()\n\n\t\/\/ TODO\n\t_, err = getCall.Download()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (client *gcsclient) UploadFile(bucketName string, objectPath string, localPath string) (int64, error) {\n\tstat, err := os.Stat(localPath)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tlocalFile, err := os.Open(localPath)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer localFile.Close()\n\n\tprogress := client.newProgressBar(stat.Size())\n\tprogress.Start()\n\tdefer progress.Finish()\n\n\tobject := &storage.Object{\n\t\tName: objectPath,\n\t}\n\n\tuploadedObject, err := client.client.Objects.Insert(bucketName, object).Media(progress.NewProxyReader(localFile)).Do()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn uploadedObject.Generation, nil\n}\n\nfunc (client *gcsclient) URL(bucketName string, objectPath string, generation int64) (string, error) {\n\tgetCall := client.client.Objects.Get(bucketName, objectPath)\n\tif generation != 0 {\n\t\tgetCall = getCall.Generation(generation)\n\t}\n\n\t_, err := getCall.Do()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvar url string\n\tif generation != 0 {\n\t\turl = fmt.Sprintf(\"gs:\/\/%s\/%s#%d\", bucketName, objectPath, generation)\n\t} else {\n\t\turl = fmt.Sprintf(\"gs:\/\/%s\/%s\", bucketName, objectPath)\n\t}\n\n\treturn url, nil\n}\n\nfunc (client *gcsclient) DeleteObject(bucketName string, objectPath string, generation int64) error {\n\tdeleteCall := client.client.Objects.Delete(bucketName, objectPath)\n\tif generation != 0 {\n\t\tdeleteCall = deleteCall.Generation(generation)\n\t}\n\n\terr := deleteCall.Do()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (client *gcsclient) getBucketObjects(bucketName string, prefix string) ([]string, error) {\n\tvar bucketObjects []string\n\n\tpageToken := \"\"\n\tfor {\n\t\tlistCall := client.client.Objects.List(bucketName)\n\t\tlistCall = listCall.PageToken(pageToken)\n\t\tlistCall = listCall.Prefix(prefix)\n\t\tlistCall = listCall.Versions(false)\n\n\t\tobjects, err := listCall.Do()\n\t\tif err != nil {\n\t\t\treturn bucketObjects, err\n\t\t}\n\n\t\tfor _, object := range objects.Items {\n\t\t\tbucketObjects = append(bucketObjects, object.Name)\n\t\t}\n\n\t\tif objects.NextPageToken != \"\" {\n\t\t\tpageToken = objects.NextPageToken\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn bucketObjects, nil\n}\n\nfunc (client *gcsclient) getBucketVersioning(bucketName string) (bool, error) {\n\tbucket, err := client.client.Buckets.Get(bucketName).Do()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\treturn bucket.Versioning.Enabled, nil\n}\n\nfunc (client *gcsclient) getObjectGenerations(bucketName string, objectPath string) ([]int64, error) {\n\tvar objectGenerations []int64\n\n\tpageToken := \"\"\n\tfor {\n\t\tlistCall := client.client.Objects.List(bucketName)\n\t\tlistCall = listCall.PageToken(pageToken)\n\t\tlistCall = listCall.Prefix(objectPath)\n\t\tlistCall = listCall.Versions(true)\n\n\t\tobjects, err := listCall.Do()\n\t\tif err != nil {\n\t\t\treturn objectGenerations, err\n\t\t}\n\n\t\tfor _, object := range objects.Items {\n\t\t\tif object.Name == objectPath {\n\t\t\t\tobjectGenerations = append(objectGenerations, object.Generation)\n\t\t\t}\n\t\t}\n\n\t\tif objects.NextPageToken != \"\" {\n\t\t\tpageToken = objects.NextPageToken\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn objectGenerations, nil\n}\n\nfunc (client *gcsclient) newProgressBar(total int64) *pb.ProgressBar {\n\tprogress := pb.New64(total)\n\n\tprogress.Output = client.progressOutput\n\tprogress.ShowSpeed = true\n\tprogress.Units = pb.U_BYTES\n\tprogress.NotPrint = true\n\n\treturn progress.SetWidth(80)\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2015 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com\/GoogleCloudPlatform\/compute-user-accounts\/apiclient\"\n\t\"github.com\/GoogleCloudPlatform\/compute-user-accounts\/logger\"\n\t\"github.com\/GoogleCloudPlatform\/compute-user-accounts\/server\"\n\t\"github.com\/GoogleCloudPlatform\/compute-user-accounts\/store\"\n)\n\nconst majorVersion = \"0\"\n\nvar (\n\t\/\/ version is set at compile time.\n\tversion string\n\tuserAgent = fmt.Sprintf(\"gcua\/%v\", version)\n\trefreshFrequency = 4 * time.Minute\n\trefreshCooldown = 5 * time.Second\n\tkeyExpiration = 30 * time.Minute\n\tkeyCooldown = 500 * time.Millisecond\n\n\tapiBase = flag.String(\"computeaccounts\", \"https:\/\/www.googleapis.com\/computeaccounts\/alpha\/\", \"the URL to the base of the computeaccounts API\")\n\tinstanceBase = flag.String(\"compute\", \"https:\/\/www.googleapis.com\/compute\/v1\/\", \"the URL to the base of the compute API\")\n)\n\nfunc main() {\n\tflag.Parse()\n\tlogger.Info(\"Starting daemon.\")\n\tinterrupt := make(chan os.Signal, 1)\n\tsignal.Notify(interrupt, os.Interrupt, os.Kill, syscall.SIGTERM)\n\tapi, err := apiclient.New(&apiclient.Config{\n\t\tAPIBase: *apiBase,\n\t\tInstanceBase: *instanceBase,\n\t\tUserAgent: userAgent,\n\t})\n\tif err != nil {\n\t\tlogger.Fatalf(\"Init failed: %v.\", err)\n\t}\n\tsrv := &server.Server{store.New(api, &store.Config{\n\t\tRefreshFrequency: refreshFrequency,\n\t\tRefreshCooldown: refreshCooldown,\n\t\tKeyExpiration: keyExpiration,\n\t\tKeyCooldown: keyCooldown,\n\t})}\n\tgo func() {\n\t\terr := srv.Serve()\n\t\tlogger.Fatalf(\"Server failed: %v.\", err)\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase sig := <-interrupt:\n\t\t\tlogger.Fatalf(\"Got interrupt: %v.\", sig)\n\t\t}\n\t}\n}\nRemoving unused majorVersion constant.\/\/ Copyright 2015 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com\/GoogleCloudPlatform\/compute-user-accounts\/apiclient\"\n\t\"github.com\/GoogleCloudPlatform\/compute-user-accounts\/logger\"\n\t\"github.com\/GoogleCloudPlatform\/compute-user-accounts\/server\"\n\t\"github.com\/GoogleCloudPlatform\/compute-user-accounts\/store\"\n)\n\nvar (\n\t\/\/ version is set at compile time.\n\tversion string\n\tuserAgent = fmt.Sprintf(\"gcua\/%v\", version)\n\trefreshFrequency = 4 * time.Minute\n\trefreshCooldown = 5 * time.Second\n\tkeyExpiration = 30 * time.Minute\n\tkeyCooldown = 500 * time.Millisecond\n\n\tapiBase = flag.String(\"computeaccounts\", \"https:\/\/www.googleapis.com\/computeaccounts\/alpha\/\", \"the URL to the base of the computeaccounts API\")\n\tinstanceBase = flag.String(\"compute\", \"https:\/\/www.googleapis.com\/compute\/v1\/\", \"the URL to the base of the compute API\")\n)\n\nfunc main() {\n\tflag.Parse()\n\tlogger.Info(\"Starting daemon.\")\n\tinterrupt := make(chan os.Signal, 1)\n\tsignal.Notify(interrupt, os.Interrupt, os.Kill, syscall.SIGTERM)\n\tapi, err := apiclient.New(&apiclient.Config{\n\t\tAPIBase: *apiBase,\n\t\tInstanceBase: *instanceBase,\n\t\tUserAgent: userAgent,\n\t})\n\tif err != nil {\n\t\tlogger.Fatalf(\"Init failed: %v.\", err)\n\t}\n\tsrv := &server.Server{store.New(api, &store.Config{\n\t\tRefreshFrequency: refreshFrequency,\n\t\tRefreshCooldown: refreshCooldown,\n\t\tKeyExpiration: keyExpiration,\n\t\tKeyCooldown: keyCooldown,\n\t})}\n\tgo func() {\n\t\terr := srv.Serve()\n\t\tlogger.Fatalf(\"Server failed: %v.\", err)\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase sig := <-interrupt:\n\t\t\tlogger.Fatalf(\"Got interrupt: %v.\", sig)\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"\/*\nCopyright 2016 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage options\n\nimport (\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/spf13\/pflag\"\n\n\tversionedinformers \"k8s.io\/client-go\/informers\"\n\tinformers \"k8s.io\/kubernetes\/pkg\/client\/informers\/informers_generated\/internalversion\"\n\t\"k8s.io\/kubernetes\/pkg\/kubeapiserver\/authorizer\"\n\tauthzmodes \"k8s.io\/kubernetes\/pkg\/kubeapiserver\/authorizer\/modes\"\n)\n\ntype BuiltInAuthorizationOptions struct {\n\tMode string\n\tPolicyFile string\n\tWebhookConfigFile string\n\tWebhookCacheAuthorizedTTL time.Duration\n\tWebhookCacheUnauthorizedTTL time.Duration\n}\n\nfunc NewBuiltInAuthorizationOptions() *BuiltInAuthorizationOptions {\n\treturn &BuiltInAuthorizationOptions{\n\t\tMode: authzmodes.ModeAlwaysAllow,\n\t\tWebhookCacheAuthorizedTTL: 5 * time.Minute,\n\t\tWebhookCacheUnauthorizedTTL: 30 * time.Second,\n\t}\n}\n\nfunc (s *BuiltInAuthorizationOptions) Validate() []error {\n\tallErrors := []error{}\n\treturn allErrors\n}\n\nfunc (s *BuiltInAuthorizationOptions) AddFlags(fs *pflag.FlagSet) {\n\tfs.StringVar(&s.Mode, \"authorization-mode\", s.Mode, \"\"+\n\t\t\"Ordered list of plug-ins to do authorization on secure port. Comma-delimited list of: \"+\n\t\tstrings.Join(authzmodes.AuthorizationModeChoices, \",\")+\".\")\n\n\tfs.StringVar(&s.PolicyFile, \"authorization-policy-file\", s.PolicyFile, \"\"+\n\t\t\"File with authorization policy in csv format, used with --authorization-mode=ABAC, on the secure port.\")\n\n\tfs.StringVar(&s.WebhookConfigFile, \"authorization-webhook-config-file\", s.WebhookConfigFile, \"\"+\n\t\t\"File with webhook configuration in kubeconfig format, used with --authorization-mode=Webhook. \"+\n\t\t\"The API server will query the remote service to determine access on the API server's secure port.\")\n\n\tfs.DurationVar(&s.WebhookCacheAuthorizedTTL, \"authorization-webhook-cache-authorized-ttl\",\n\t\ts.WebhookCacheAuthorizedTTL,\n\t\t\"The duration to cache 'authorized' responses from the webhook authorizer.\")\n\n\tfs.DurationVar(&s.WebhookCacheUnauthorizedTTL,\n\t\t\"authorization-webhook-cache-unauthorized-ttl\", s.WebhookCacheUnauthorizedTTL,\n\t\t\"The duration to cache 'unauthorized' responses from the webhook authorizer.\")\n\n\tfs.String(\"authorization-rbac-super-user\", \"\", \"\"+\n\t\t\"If specified, a username which avoids RBAC authorization checks and role binding \"+\n\t\t\"privilege escalation checks, to be used with --authorization-mode=RBAC.\")\n\tfs.MarkDeprecated(\"authorization-rbac-super-user\", \"Removed during alpha to beta. The 'system:masters' group has privileged access.\")\n\n}\n\nfunc (s *BuiltInAuthorizationOptions) Modes() []string {\n\tmodes := []string{}\n\tif len(s.Mode) > 0 {\n\t\tmodes = strings.Split(s.Mode, \",\")\n\t}\n\treturn modes\n}\n\nfunc (s *BuiltInAuthorizationOptions) ToAuthorizationConfig(informerFactory informers.SharedInformerFactory, versionedInformerFactory versionedinformers.SharedInformerFactory) authorizer.AuthorizationConfig {\n\treturn authorizer.AuthorizationConfig{\n\t\tAuthorizationModes: s.Modes(),\n\t\tPolicyFile: s.PolicyFile,\n\t\tWebhookConfigFile: s.WebhookConfigFile,\n\t\tWebhookCacheAuthorizedTTL: s.WebhookCacheAuthorizedTTL,\n\t\tWebhookCacheUnauthorizedTTL: s.WebhookCacheUnauthorizedTTL,\n\t\tInformerFactory: informerFactory,\n\t\tVersionedInformerFactory: versionedInformerFactory,\n\t}\n}\nRemove deprecated paramter \"authorization-rbac-super-user\"\/*\nCopyright 2016 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage options\n\nimport (\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/spf13\/pflag\"\n\n\tversionedinformers \"k8s.io\/client-go\/informers\"\n\tinformers \"k8s.io\/kubernetes\/pkg\/client\/informers\/informers_generated\/internalversion\"\n\t\"k8s.io\/kubernetes\/pkg\/kubeapiserver\/authorizer\"\n\tauthzmodes \"k8s.io\/kubernetes\/pkg\/kubeapiserver\/authorizer\/modes\"\n)\n\ntype BuiltInAuthorizationOptions struct {\n\tMode string\n\tPolicyFile string\n\tWebhookConfigFile string\n\tWebhookCacheAuthorizedTTL time.Duration\n\tWebhookCacheUnauthorizedTTL time.Duration\n}\n\nfunc NewBuiltInAuthorizationOptions() *BuiltInAuthorizationOptions {\n\treturn &BuiltInAuthorizationOptions{\n\t\tMode: authzmodes.ModeAlwaysAllow,\n\t\tWebhookCacheAuthorizedTTL: 5 * time.Minute,\n\t\tWebhookCacheUnauthorizedTTL: 30 * time.Second,\n\t}\n}\n\nfunc (s *BuiltInAuthorizationOptions) Validate() []error {\n\tallErrors := []error{}\n\treturn allErrors\n}\n\nfunc (s *BuiltInAuthorizationOptions) AddFlags(fs *pflag.FlagSet) {\n\tfs.StringVar(&s.Mode, \"authorization-mode\", s.Mode, \"\"+\n\t\t\"Ordered list of plug-ins to do authorization on secure port. Comma-delimited list of: \"+\n\t\tstrings.Join(authzmodes.AuthorizationModeChoices, \",\")+\".\")\n\n\tfs.StringVar(&s.PolicyFile, \"authorization-policy-file\", s.PolicyFile, \"\"+\n\t\t\"File with authorization policy in csv format, used with --authorization-mode=ABAC, on the secure port.\")\n\n\tfs.StringVar(&s.WebhookConfigFile, \"authorization-webhook-config-file\", s.WebhookConfigFile, \"\"+\n\t\t\"File with webhook configuration in kubeconfig format, used with --authorization-mode=Webhook. \"+\n\t\t\"The API server will query the remote service to determine access on the API server's secure port.\")\n\n\tfs.DurationVar(&s.WebhookCacheAuthorizedTTL, \"authorization-webhook-cache-authorized-ttl\",\n\t\ts.WebhookCacheAuthorizedTTL,\n\t\t\"The duration to cache 'authorized' responses from the webhook authorizer.\")\n\n\tfs.DurationVar(&s.WebhookCacheUnauthorizedTTL,\n\t\t\"authorization-webhook-cache-unauthorized-ttl\", s.WebhookCacheUnauthorizedTTL,\n\t\t\"The duration to cache 'unauthorized' responses from the webhook authorizer.\")\n}\n\nfunc (s *BuiltInAuthorizationOptions) Modes() []string {\n\tmodes := []string{}\n\tif len(s.Mode) > 0 {\n\t\tmodes = strings.Split(s.Mode, \",\")\n\t}\n\treturn modes\n}\n\nfunc (s *BuiltInAuthorizationOptions) ToAuthorizationConfig(informerFactory informers.SharedInformerFactory, versionedInformerFactory versionedinformers.SharedInformerFactory) authorizer.AuthorizationConfig {\n\treturn authorizer.AuthorizationConfig{\n\t\tAuthorizationModes: s.Modes(),\n\t\tPolicyFile: s.PolicyFile,\n\t\tWebhookConfigFile: s.WebhookConfigFile,\n\t\tWebhookCacheAuthorizedTTL: s.WebhookCacheAuthorizedTTL,\n\t\tWebhookCacheUnauthorizedTTL: s.WebhookCacheUnauthorizedTTL,\n\t\tInformerFactory: informerFactory,\n\t\tVersionedInformerFactory: versionedInformerFactory,\n\t}\n}\n<|endoftext|>"} {"text":"\/*\nCopyright 2019 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage runtimeclass\n\nimport (\n\t\"context\"\n\n\t\"k8s.io\/apimachinery\/pkg\/runtime\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/validation\/field\"\n\t\"k8s.io\/apiserver\/pkg\/registry\/rest\"\n\t\"k8s.io\/apiserver\/pkg\/storage\/names\"\n\t\"k8s.io\/kubernetes\/pkg\/api\/legacyscheme\"\n\t\"k8s.io\/kubernetes\/pkg\/apis\/node\"\n\t\"k8s.io\/kubernetes\/pkg\/apis\/node\/validation\"\n)\n\n\/\/ strategy implements verification logic for RuntimeClass.\ntype strategy struct {\n\truntime.ObjectTyper\n\tnames.NameGenerator\n}\n\n\/\/ Strategy is the default logic that applies when creating and updating RuntimeClass objects.\nvar Strategy = strategy{legacyscheme.Scheme, names.SimpleNameGenerator}\n\n\/\/ Strategy should implement rest.RESTCreateStrategy\nvar _ rest.RESTCreateStrategy = Strategy\n\n\/\/ Strategy should implement rest.RESTUpdateStrategy\nvar _ rest.RESTUpdateStrategy = Strategy\n\n\/\/ NamespaceScoped is false for RuntimeClasses\nfunc (strategy) NamespaceScoped() bool {\n\treturn false\n}\n\n\/\/ AllowCreateOnUpdate is true for RuntimeClasses.\nfunc (strategy) AllowCreateOnUpdate() bool {\n\treturn true\n}\n\n\/\/ PrepareForCreate clears fields that are not allowed to be set by end users\n\/\/ on creation.\nfunc (strategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\t_ = obj.(*node.RuntimeClass)\n}\n\n\/\/ PrepareForUpdate clears fields that are not allowed to be set by end users on update.\nfunc (strategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewRuntimeClass := obj.(*node.RuntimeClass)\n\toldRuntimeClass := old.(*node.RuntimeClass)\n\n\t_, _ = newRuntimeClass, oldRuntimeClass\n}\n\n\/\/ Validate validates a new RuntimeClass. Validation must check for a correct signature.\nfunc (strategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\truntimeClass := obj.(*node.RuntimeClass)\n\treturn validation.ValidateRuntimeClass(runtimeClass)\n}\n\n\/\/ Canonicalize normalizes the object after validation.\nfunc (strategy) Canonicalize(obj runtime.Object) {\n\t_ = obj.(*node.RuntimeClass)\n}\n\n\/\/ ValidateUpdate is the default update validation for an end user.\nfunc (strategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\tnewObj := obj.(*node.RuntimeClass)\n\terrorList := validation.ValidateRuntimeClass(newObj)\n\treturn append(errorList, validation.ValidateRuntimeClassUpdate(newObj, old.(*node.RuntimeClass))...)\n}\n\n\/\/ If AllowUnconditionalUpdate() is true and the object specified by\n\/\/ the user does not have a resource version, then generic Update()\n\/\/ populates it with the latest version. Else, it checks that the\n\/\/ version specified by the user matches the version of latest etcd\n\/\/ object.\nfunc (strategy) AllowUnconditionalUpdate() bool {\n\treturn false\n}\npod overhead: drop from RuntimeClass base on feature-gate\/*\nCopyright 2019 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage runtimeclass\n\nimport (\n\t\"context\"\n\n\t\"k8s.io\/apimachinery\/pkg\/runtime\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/validation\/field\"\n\t\"k8s.io\/apiserver\/pkg\/registry\/rest\"\n\t\"k8s.io\/apiserver\/pkg\/storage\/names\"\n\tutilfeature \"k8s.io\/apiserver\/pkg\/util\/feature\"\n\t\"k8s.io\/kubernetes\/pkg\/api\/legacyscheme\"\n\t\"k8s.io\/kubernetes\/pkg\/apis\/node\"\n\t\"k8s.io\/kubernetes\/pkg\/apis\/node\/validation\"\n\t\"k8s.io\/kubernetes\/pkg\/features\"\n)\n\n\/\/ strategy implements verification logic for RuntimeClass.\ntype strategy struct {\n\truntime.ObjectTyper\n\tnames.NameGenerator\n}\n\n\/\/ Strategy is the default logic that applies when creating and updating RuntimeClass objects.\nvar Strategy = strategy{legacyscheme.Scheme, names.SimpleNameGenerator}\n\n\/\/ Strategy should implement rest.RESTCreateStrategy\nvar _ rest.RESTCreateStrategy = Strategy\n\n\/\/ Strategy should implement rest.RESTUpdateStrategy\nvar _ rest.RESTUpdateStrategy = Strategy\n\n\/\/ NamespaceScoped is false for RuntimeClasses\nfunc (strategy) NamespaceScoped() bool {\n\treturn false\n}\n\n\/\/ AllowCreateOnUpdate is true for RuntimeClasses.\nfunc (strategy) AllowCreateOnUpdate() bool {\n\treturn true\n}\n\n\/\/ PrepareForCreate clears fields that are not allowed to be set by end users\n\/\/ on creation.\nfunc (strategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {\n\trc := obj.(*node.RuntimeClass)\n\n\tif !utilfeature.DefaultFeatureGate.Enabled(features.PodOverhead) && rc != nil {\n\t\t\/\/ Set Overhead to nil only if the feature is disabled and it is not used\n\t\trc.Overhead = nil\n\t}\n}\n\n\/\/ PrepareForUpdate clears fields that are not allowed to be set by end users on update.\nfunc (strategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {\n\tnewRuntimeClass := obj.(*node.RuntimeClass)\n\toldRuntimeClass := old.(*node.RuntimeClass)\n\n\t_, _ = newRuntimeClass, oldRuntimeClass\n}\n\n\/\/ Validate validates a new RuntimeClass. Validation must check for a correct signature.\nfunc (strategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {\n\truntimeClass := obj.(*node.RuntimeClass)\n\treturn validation.ValidateRuntimeClass(runtimeClass)\n}\n\n\/\/ Canonicalize normalizes the object after validation.\nfunc (strategy) Canonicalize(obj runtime.Object) {\n\t_ = obj.(*node.RuntimeClass)\n}\n\n\/\/ ValidateUpdate is the default update validation for an end user.\nfunc (strategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {\n\tnewObj := obj.(*node.RuntimeClass)\n\terrorList := validation.ValidateRuntimeClass(newObj)\n\treturn append(errorList, validation.ValidateRuntimeClassUpdate(newObj, old.(*node.RuntimeClass))...)\n}\n\n\/\/ If AllowUnconditionalUpdate() is true and the object specified by\n\/\/ the user does not have a resource version, then generic Update()\n\/\/ populates it with the latest version. Else, it checks that the\n\/\/ version specified by the user matches the version of latest etcd\n\/\/ object.\nfunc (strategy) AllowUnconditionalUpdate() bool {\n\treturn false\n}\n<|endoftext|>"} {"text":"package alerting\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t. \"github.com\/smartystreets\/goconvey\/convey\"\n)\n\ntype conditionStub struct {\n\tfiring bool\n\toperator string\n\tmatches []*EvalMatch\n}\n\nfunc (c *conditionStub) Eval(context *EvalContext) (*ConditionResult, error) {\n\treturn &ConditionResult{Firing: c.firing, EvalMatches: c.matches, Operator: c.operator}, nil\n}\n\nfunc TestAlertingExecutor(t *testing.T) {\n\tConvey(\"Test alert execution\", t, func() {\n\t\thandler := NewEvalHandler()\n\n\t\tConvey(\"Show return triggered with single passing condition\", func() {\n\t\t\tcontext := NewEvalContext(context.TODO(), &Rule{\n\t\t\t\tConditions: []Condition{&conditionStub{\n\t\t\t\t\tfiring: true,\n\t\t\t\t}},\n\t\t\t})\n\n\t\t\thandler.Eval(context)\n\t\t\tSo(context.Firing, ShouldEqual, true)\n\t\t\tSo(context.ConditionEvals, ShouldEqual, \"true = true\")\n\t\t})\n\n\t\tConvey(\"Show return false with not passing asdf\", func() {\n\t\t\tcontext := NewEvalContext(context.TODO(), &Rule{\n\t\t\t\tConditions: []Condition{\n\t\t\t\t\t&conditionStub{firing: true, matches: []*EvalMatch{&EvalMatch{}, &EvalMatch{}}},\n\t\t\t\t\t&conditionStub{firing: false},\n\t\t\t\t},\n\t\t\t})\n\n\t\t\thandler.Eval(context)\n\t\t\tSo(context.Firing, ShouldEqual, false)\n\t\t\tSo(context.ConditionEvals, ShouldEqual, \"[true AND false] = false\")\n\t\t})\n\n\t\tConvey(\"Show return true if any of the condition is passing with OR operator\", func() {\n\t\t\tcontext := NewEvalContext(context.TODO(), &Rule{\n\t\t\t\tConditions: []Condition{\n\t\t\t\t\t&conditionStub{firing: true, operator: \"and\"},\n\t\t\t\t\t&conditionStub{firing: false, operator: \"or\"},\n\t\t\t\t},\n\t\t\t})\n\n\t\t\thandler.Eval(context)\n\t\t\tSo(context.Firing, ShouldEqual, true)\n\t\t\tSo(context.ConditionEvals, ShouldEqual, \"[true OR false] = true\")\n\t\t})\n\n\t\tConvey(\"Show return false if any of the condition is failing with AND operator\", func() {\n\t\t\tcontext := NewEvalContext(context.TODO(), &Rule{\n\t\t\t\tConditions: []Condition{\n\t\t\t\t\t&conditionStub{firing: true, operator: \"and\"},\n\t\t\t\t\t&conditionStub{firing: false, operator: \"and\"},\n\t\t\t\t},\n\t\t\t})\n\n\t\t\thandler.Eval(context)\n\t\t\tSo(context.Firing, ShouldEqual, false)\n\t\t\tSo(context.ConditionEvals, ShouldEqual, \"[true AND false] = false\")\n\t\t})\n\n\t\tConvey(\"Show return true if one condition is failing with nested OR operator\", func() {\n\t\t\tcontext := NewEvalContext(context.TODO(), &Rule{\n\t\t\t\tConditions: []Condition{\n\t\t\t\t\t&conditionStub{firing: true, operator: \"and\"},\n\t\t\t\t\t&conditionStub{firing: true, operator: \"and\"},\n\t\t\t\t\t&conditionStub{firing: false, operator: \"or\"},\n\t\t\t\t},\n\t\t\t})\n\n\t\t\thandler.Eval(context)\n\t\t\tSo(context.Firing, ShouldEqual, true)\n\t\t\tSo(context.ConditionEvals, ShouldEqual, \"[[true AND true] OR false] = true\")\n\t\t})\n\n\t\tConvey(\"Show return false if one condition is passing with nested OR operator\", func() {\n\t\t\tcontext := NewEvalContext(context.TODO(), &Rule{\n\t\t\t\tConditions: []Condition{\n\t\t\t\t\t&conditionStub{firing: true, operator: \"and\"},\n\t\t\t\t\t&conditionStub{firing: false, operator: \"and\"},\n\t\t\t\t\t&conditionStub{firing: false, operator: \"or\"},\n\t\t\t\t},\n\t\t\t})\n\n\t\t\thandler.Eval(context)\n\t\t\tSo(context.Firing, ShouldEqual, false)\n\t\t\tSo(context.ConditionEvals, ShouldEqual, \"[[true AND false] OR false] = false\")\n\t\t})\n\n\t\tConvey(\"Show return false if a condition is failing with nested AND operator\", func() {\n\t\t\tcontext := NewEvalContext(context.TODO(), &Rule{\n\t\t\t\tConditions: []Condition{\n\t\t\t\t\t&conditionStub{firing: true, operator: \"and\"},\n\t\t\t\t\t&conditionStub{firing: false, operator: \"and\"},\n\t\t\t\t\t&conditionStub{firing: true, operator: \"and\"},\n\t\t\t\t},\n\t\t\t})\n\n\t\t\thandler.Eval(context)\n\t\t\tSo(context.Firing, ShouldEqual, false)\n\t\t\tSo(context.ConditionEvals, ShouldEqual, \"[[true AND false] AND true] = false\")\n\t\t})\n\n\t\tConvey(\"Show return true if a condition is passing with nested OR operator\", func() {\n\t\t\tcontext := NewEvalContext(context.TODO(), &Rule{\n\t\t\t\tConditions: []Condition{\n\t\t\t\t\t&conditionStub{firing: true, operator: \"and\"},\n\t\t\t\t\t&conditionStub{firing: false, operator: \"or\"},\n\t\t\t\t\t&conditionStub{firing: true, operator: \"or\"},\n\t\t\t\t},\n\t\t\t})\n\n\t\t\thandler.Eval(context)\n\t\t\tSo(context.Firing, ShouldEqual, true)\n\t\t\tSo(context.ConditionEvals, ShouldEqual, \"[[true OR false] OR true] = true\")\n\t\t})\n\t})\n}\ntest(alerting): fixes broken unit testpackage alerting\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t. \"github.com\/smartystreets\/goconvey\/convey\"\n)\n\ntype conditionStub struct {\n\tfiring bool\n\toperator string\n\tmatches []*EvalMatch\n}\n\nfunc (c *conditionStub) Eval(context *EvalContext) (*ConditionResult, error) {\n\treturn &ConditionResult{Firing: c.firing, EvalMatches: c.matches, Operator: c.operator}, nil\n}\n\nfunc TestAlertingExecutor(t *testing.T) {\n\tConvey(\"Test alert execution\", t, func() {\n\t\thandler := NewEvalHandler()\n\n\t\tConvey(\"Show return triggered with single passing condition\", func() {\n\t\t\tcontext := NewEvalContext(context.TODO(), &Rule{\n\t\t\t\tConditions: []Condition{&conditionStub{\n\t\t\t\t\tfiring: true,\n\t\t\t\t}},\n\t\t\t})\n\n\t\t\thandler.Eval(context)\n\t\t\tSo(context.Firing, ShouldEqual, true)\n\t\t\tSo(context.ConditionEvals, ShouldEqual, \"true = true\")\n\t\t})\n\n\t\tConvey(\"Show return false with not passing asdf\", func() {\n\t\t\tcontext := NewEvalContext(context.TODO(), &Rule{\n\t\t\t\tConditions: []Condition{\n\t\t\t\t\t&conditionStub{firing: true, operator: \"and\", matches: []*EvalMatch{&EvalMatch{}, &EvalMatch{}}},\n\t\t\t\t\t&conditionStub{firing: false, operator: \"and\"},\n\t\t\t\t},\n\t\t\t})\n\n\t\t\thandler.Eval(context)\n\t\t\tSo(context.Firing, ShouldEqual, false)\n\t\t\tSo(context.ConditionEvals, ShouldEqual, \"[true AND false] = false\")\n\t\t})\n\n\t\tConvey(\"Show return true if any of the condition is passing with OR operator\", func() {\n\t\t\tcontext := NewEvalContext(context.TODO(), &Rule{\n\t\t\t\tConditions: []Condition{\n\t\t\t\t\t&conditionStub{firing: true, operator: \"and\"},\n\t\t\t\t\t&conditionStub{firing: false, operator: \"or\"},\n\t\t\t\t},\n\t\t\t})\n\n\t\t\thandler.Eval(context)\n\t\t\tSo(context.Firing, ShouldEqual, true)\n\t\t\tSo(context.ConditionEvals, ShouldEqual, \"[true OR false] = true\")\n\t\t})\n\n\t\tConvey(\"Show return false if any of the condition is failing with AND operator\", func() {\n\t\t\tcontext := NewEvalContext(context.TODO(), &Rule{\n\t\t\t\tConditions: []Condition{\n\t\t\t\t\t&conditionStub{firing: true, operator: \"and\"},\n\t\t\t\t\t&conditionStub{firing: false, operator: \"and\"},\n\t\t\t\t},\n\t\t\t})\n\n\t\t\thandler.Eval(context)\n\t\t\tSo(context.Firing, ShouldEqual, false)\n\t\t\tSo(context.ConditionEvals, ShouldEqual, \"[true AND false] = false\")\n\t\t})\n\n\t\tConvey(\"Show return true if one condition is failing with nested OR operator\", func() {\n\t\t\tcontext := NewEvalContext(context.TODO(), &Rule{\n\t\t\t\tConditions: []Condition{\n\t\t\t\t\t&conditionStub{firing: true, operator: \"and\"},\n\t\t\t\t\t&conditionStub{firing: true, operator: \"and\"},\n\t\t\t\t\t&conditionStub{firing: false, operator: \"or\"},\n\t\t\t\t},\n\t\t\t})\n\n\t\t\thandler.Eval(context)\n\t\t\tSo(context.Firing, ShouldEqual, true)\n\t\t\tSo(context.ConditionEvals, ShouldEqual, \"[[true AND true] OR false] = true\")\n\t\t})\n\n\t\tConvey(\"Show return false if one condition is passing with nested OR operator\", func() {\n\t\t\tcontext := NewEvalContext(context.TODO(), &Rule{\n\t\t\t\tConditions: []Condition{\n\t\t\t\t\t&conditionStub{firing: true, operator: \"and\"},\n\t\t\t\t\t&conditionStub{firing: false, operator: \"and\"},\n\t\t\t\t\t&conditionStub{firing: false, operator: \"or\"},\n\t\t\t\t},\n\t\t\t})\n\n\t\t\thandler.Eval(context)\n\t\t\tSo(context.Firing, ShouldEqual, false)\n\t\t\tSo(context.ConditionEvals, ShouldEqual, \"[[true AND false] OR false] = false\")\n\t\t})\n\n\t\tConvey(\"Show return false if a condition is failing with nested AND operator\", func() {\n\t\t\tcontext := NewEvalContext(context.TODO(), &Rule{\n\t\t\t\tConditions: []Condition{\n\t\t\t\t\t&conditionStub{firing: true, operator: \"and\"},\n\t\t\t\t\t&conditionStub{firing: false, operator: \"and\"},\n\t\t\t\t\t&conditionStub{firing: true, operator: \"and\"},\n\t\t\t\t},\n\t\t\t})\n\n\t\t\thandler.Eval(context)\n\t\t\tSo(context.Firing, ShouldEqual, false)\n\t\t\tSo(context.ConditionEvals, ShouldEqual, \"[[true AND false] AND true] = false\")\n\t\t})\n\n\t\tConvey(\"Show return true if a condition is passing with nested OR operator\", func() {\n\t\t\tcontext := NewEvalContext(context.TODO(), &Rule{\n\t\t\t\tConditions: []Condition{\n\t\t\t\t\t&conditionStub{firing: true, operator: \"and\"},\n\t\t\t\t\t&conditionStub{firing: false, operator: \"or\"},\n\t\t\t\t\t&conditionStub{firing: true, operator: \"or\"},\n\t\t\t\t},\n\t\t\t})\n\n\t\t\thandler.Eval(context)\n\t\t\tSo(context.Firing, ShouldEqual, true)\n\t\t\tSo(context.ConditionEvals, ShouldEqual, \"[[true OR false] OR true] = true\")\n\t\t})\n\t})\n}\n<|endoftext|>"} {"text":"package goinsta\n\nimport (\n\t\"crypto\/hmac\"\n\t\"crypto\/md5\"\n\t\"crypto\/rand\"\n\t\"crypto\/sha256\"\n\t\"encoding\/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\/url\"\n\t\"strings\"\n)\n\nconst (\n\tvolatileSeed = \"12345\"\n)\n\nfunc generateMD5Hash(text string) string {\n\thasher := md5.New()\n\thasher.Write([]byte(text))\n\treturn hex.EncodeToString(hasher.Sum(nil))\n}\n\nfunc generateHMAC(text, key string) string {\n\thasher := hmac.New(sha256.New, []byte(key))\n\thasher.Write([]byte(text))\n\treturn hex.EncodeToString(hasher.Sum(nil))\n}\n\nfunc generateDeviceID(seed string) string {\n\thash := generateMD5Hash(seed + volatileSeed)\n\treturn \"android-\" + hash[:16]\n}\n\nfunc generateUUID(replace bool) string {\n\tuuid := make([]byte, 16)\n\tio.ReadFull(rand.Reader, uuid)\n\tuuid[8] = uuid[8]&^0xc0 | 0x80\n\tuuid[6] = uuid[6]&^0xf0 | 0x40\n\n\ttUUID := fmt.Sprintf(\"%x-%x-%x-%x-%x\", uuid[0:4], uuid[4:6], uuid[6:8], uuid[8:10], uuid[10:])\n\n\tif replace {\n\t\treturn strings.Replace(tUUID, \"-\", \"\", -1)\n\t}\n\treturn tUUID\n}\n\nfunc generateSignature(data string) map[string]string {\n\treturn map[string]string{\n\t\t\"ig_sig_key_version\": fmt.Sprintf(\n\t\t\t\"%s&signed_body=%s.%s\",\n\t\t\tgoInstaSigKeyVersion,\n\t\t\tgenerateHMAC(data, goInstaIGSigKey),\n\t\t\turl.QueryEscape(data),\n\t\t),\n\t}\n}\nMade easier generatorspackage goinsta\n\nimport (\n\t\"crypto\/hmac\"\n\t\"crypto\/md5\"\n\t\"crypto\/rand\"\n\t\"crypto\/sha256\"\n\t\"encoding\/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\/url\"\n\t\"strings\"\n)\n\nconst (\n\tvolatileSeed = \"12345\"\n)\n\nfunc generateMD5Hash(text string) string {\n\thasher := md5.New()\n\thasher.Write([]byte(text))\n\treturn hex.EncodeToString(hasher.Sum(nil))\n}\n\nfunc generateHMAC(text, key []byte) string {\n\thasher := hmac.New(sha256.New, key)\n\thasher.Write(text)\n\treturn hex.EncodeToString(hasher.Sum(nil))\n}\n\nfunc generateDeviceID(seed string) string {\n\thash := generateMD5Hash(seed + volatileSeed)\n\treturn \"android-\" + hash[:16]\n}\n\nfunc generateUUID(replace bool) string {\n\tuuid := make([]byte, 16)\n\tio.ReadFull(rand.Reader, uuid)\n\tuuid[8] = uuid[8]&^0xc0 | 0x80\n\tuuid[6] = uuid[6]&^0xf0 | 0x40\n\n\ttUUID := fmt.Sprintf(\"%x-%x-%x-%x-%x\", uuid[0:4], uuid[4:6], uuid[6:8], uuid[8:10], uuid[10:])\n\n\tif replace {\n\t\treturn strings.Replace(tUUID, \"-\", \"\", -1)\n\t}\n\treturn tUUID\n}\n\nfunc generateSignature(data []byte) map[string]string {\n\treturn map[string]string{\n\t\t\"ig_sig_key_version\": fmt.Sprintf(\n\t\t\t\"%s&signed_body=%s.%s\",\n\t\t\tgoInstaSigKeyVersion,\n\t\t\tgenerateHMAC(data, []byte(goInstaIGSigKey)),\n\t\t\turl.QueryEscape(b2s(data)),\n\t\t),\n\t}\n}\n<|endoftext|>"} {"text":"package siad\n\n\/\/ wallet.go contains things like signatures and scans the blockchain for\n\/\/ available funds that can be spent.\n\nimport (\n\t\"errors\"\n\t\"os\"\n\n\t\"github.com\/NebulousLabs\/Andromeda\/encoding\"\n\t\"github.com\/NebulousLabs\/Andromeda\/siacore\"\n\t\"github.com\/NebulousLabs\/Andromeda\/signatures\"\n)\n\n\/\/ Contains a secret key, the spend conditions associated with that key, the\n\/\/ address associated with those spend conditions, and a list of outputs that\n\/\/ the wallet knows how to spend.\ntype Wallet struct {\n\tstate *siacore.State\n\n\tSecretKey signatures.SecretKey\n\tSpendConditions siacore.SpendConditions\n\n\tOwnedOutputs map[siacore.OutputID]struct{} \/\/ A list of outputs spendable by this wallet.\n\tSpentOutputs map[siacore.OutputID]struct{} \/\/ A list of outputs spent by this wallet which may not yet be in the blockchain.\n}\n\n\/\/ Most of the parameters are already in the file contract, but what's not\n\/\/ specified is how much of the ContractFund comes from the client, and how\n\/\/ much comes from the host. This specifies how much the client is to add to\n\/\/ the contract.\ntype FileContractParameters struct {\n\tTransaction siacore.Transaction\n\tFileContractIndex int\n\tClientContribution siacore.Currency\n}\n\n\/\/ Creates a new wallet that can receive and spend coins.\nfunc CreateWallet() (w *Wallet, err error) {\n\tw = new(Wallet)\n\n\tvar pk signatures.PublicKey\n\tw.SecretKey, pk, err = signatures.GenerateKeyPair()\n\tw.SpendConditions.PublicKeys = append(w.SpendConditions.PublicKeys, pk)\n\tw.SpendConditions.NumSignatures = 1\n\n\tw.OwnedOutputs = make(map[siacore.OutputID]struct{})\n\tw.SpentOutputs = make(map[siacore.OutputID]struct{})\n\n\treturn\n}\n\n\/\/ Scans all unspent transactions and adds the ones that are spendable by this\n\/\/ wallet.\nfunc (w *Wallet) Scan() {\n\tw.OwnedOutputs = make(map[siacore.OutputID]struct{})\n\n\t\/\/ Check for owned outputs from the standard SpendConditions.\n\tscanAddresses := make(map[siacore.CoinAddress]struct{})\n\tscanAddresses[w.SpendConditions.CoinAddress()] = struct{}{}\n\n\t\/\/ Get the matching set of outputs and add them to the OwnedOutputs map.\n\toutputs := w.state.ScanOutputs(scanAddresses)\n\tfor _, output := range outputs {\n\t\tw.OwnedOutputs[output] = struct{}{}\n\t}\n}\n\n\/\/ fundTransaction() adds `amount` Currency to the inputs, creating a refund\n\/\/ output for any excess.\nfunc (w *Wallet) FundTransaction(amount siacore.Currency, t *siacore.Transaction) (err error) {\n\t\/\/ Check that a nonzero amount of coins is being sent.\n\tif amount == siacore.Currency(0) {\n\t\terr = errors.New(\"cannot send 0 coins\")\n\t\treturn\n\t}\n\n\t\/\/ Add to the list of inputs until enough funds have been allocated.\n\ttotal := siacore.Currency(0)\n\tvar newInputs []siacore.Input\n\tfor id, _ := range w.OwnedOutputs {\n\t\t\/\/ Check that the output has not already been assigned somewhere else.\n\t\t_, exists := w.SpentOutputs[id]\n\t\tif exists {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Check that the output exists.\n\t\tvar output siacore.Output\n\t\toutput, err = w.state.Output(id)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Create an input to add to the transaction.\n\t\tnewInput := siacore.Input{\n\t\t\tOutputID: id,\n\t\t\tSpendConditions: w.SpendConditions,\n\t\t}\n\t\tnewInputs = append(newInputs, newInput)\n\n\t\t\/\/ Add the value of the output to the total and see if we've hit a\n\t\t\/\/ sufficient amount.\n\t\ttotal += output.Value\n\t\tif total >= amount {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t\/\/ Check that the sum of the inputs is sufficient to complete the\n\t\/\/ transaction.\n\tif total < amount {\n\t\terr = errors.New(\"insufficient funds\")\n\t\treturn\n\t}\n\n\t\/\/ Add all of the inputs to the transaction.\n\tt.Inputs = append(t.Inputs, newInputs...)\n\n\t\/\/ Add all of the inputs to the spent outputs map.\n\tfor _, input := range newInputs {\n\t\tw.SpentOutputs[input.OutputID] = struct{}{}\n\t}\n\n\t\/\/ Add a refund output to the transaction if needed.\n\tif total-amount > 0 {\n\t\tt.Outputs = append(t.Outputs, siacore.Output{Value: total - amount, SpendHash: w.SpendConditions.CoinAddress()})\n\t}\n\n\treturn\n}\n\n\/\/ Wallet.signTransaction() takes a transaction and adds a signature for every input\n\/\/ that the wallet understands how to spend.\nfunc (w *Wallet) SignTransaction(t *siacore.Transaction) (err error) {\n\tfor i, input := range t.Inputs {\n\t\t\/\/ If we recognize the input as something we are able to sign, we sign\n\t\t\/\/ the input.\n\t\tif input.SpendConditions.CoinAddress() == w.SpendConditions.CoinAddress() {\n\t\t\ttxnSig := siacore.TransactionSignature{\n\t\t\t\tInputID: input.OutputID,\n\t\t\t}\n\t\t\tt.Signatures = append(t.Signatures, txnSig)\n\n\t\t\tsigHash := t.SigHash(i)\n\t\t\tt.Signatures[i].Signature, err = signatures.SignBytes(sigHash[:], w.SecretKey)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}\n\n\/\/ Wallet.SpendCoins creates a transaction sending 'amount' to 'address', and\n\/\/ allocateding 'minerFee' as a miner fee. The transaction is submitted to the\n\/\/ miner pool, but is also returned.\nfunc (e *Environment) SpendCoins(amount, minerFee siacore.Currency, address siacore.CoinAddress) (t siacore.Transaction, err error) {\n\t\/\/ Scan blockchain for outputs.\n\te.wallet.Scan()\n\n\t\/\/ Add `amount` of free coins to the transaction.\n\terr = e.wallet.FundTransaction(amount+minerFee, &t)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Add the miner fee.\n\tt.MinerFees = append(t.MinerFees, minerFee)\n\n\t\/\/ Add the output to `address`.\n\tt.Outputs = append(t.Outputs, siacore.Output{Value: amount, SpendHash: address})\n\n\t\/\/ Sign each input.\n\terr = e.wallet.SignTransaction(&t)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ TODO: AcceptTransaction shoul be piped through a channel.\n\terr = e.wallet.state.AcceptTransaction(t)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\n\/\/ Environment.CoinAddress returns the CoinAddress which foreign coins should\n\/\/ be sent to.\nfunc (e *Environment) CoinAddress() siacore.CoinAddress {\n\treturn e.wallet.SpendConditions.CoinAddress()\n}\n\n\/\/ SaveCoinAddress saves the address of the wallet used within the environment.\nfunc (e *Environment) SaveCoinAddress(filename string) (err error) {\n\tpubKeyBytes := encoding.Marshal(e.wallet.SpendConditions.CoinAddress())\n\n\t\/\/ Open the file and write the key to the filename.\n\tfile, err := os.Create(filename)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer file.Close()\n\t_, err = file.Write(pubKeyBytes)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\nfunc (e *Environment) LoadCoinAddress(filename string, friendName string) (err error) {\n\t\/\/ Open the file and read the key to a friend map.\n\treturn\n}\n\nfunc (e *Environment) SaveSecretKey(filename string) (err error) {\n\treturn\n}\n\nfunc (e *Environment) LoadSecretKey(filename string) (err error) {\n\treturn\n}\nimplement envrionment friend listpackage siad\n\n\/\/ wallet.go contains things like signatures and scans the blockchain for\n\/\/ available funds that can be spent.\n\nimport (\n\t\"errors\"\n\t\"os\"\n\n\t\"github.com\/NebulousLabs\/Andromeda\/encoding\"\n\t\"github.com\/NebulousLabs\/Andromeda\/siacore\"\n\t\"github.com\/NebulousLabs\/Andromeda\/signatures\"\n)\n\n\/\/ Contains a secret key, the spend conditions associated with that key, the\n\/\/ address associated with those spend conditions, and a list of outputs that\n\/\/ the wallet knows how to spend.\ntype Wallet struct {\n\tstate *siacore.State\n\n\tSecretKey signatures.SecretKey\n\tSpendConditions siacore.SpendConditions\n\n\tOwnedOutputs map[siacore.OutputID]struct{} \/\/ A list of outputs spendable by this wallet.\n\tSpentOutputs map[siacore.OutputID]struct{} \/\/ A list of outputs spent by this wallet which may not yet be in the blockchain.\n}\n\n\/\/ Most of the parameters are already in the file contract, but what's not\n\/\/ specified is how much of the ContractFund comes from the client, and how\n\/\/ much comes from the host. This specifies how much the client is to add to\n\/\/ the contract.\ntype FileContractParameters struct {\n\tTransaction siacore.Transaction\n\tFileContractIndex int\n\tClientContribution siacore.Currency\n}\n\n\/\/ Creates a new wallet that can receive and spend coins.\nfunc CreateWallet() (w *Wallet, err error) {\n\tw = new(Wallet)\n\n\tvar pk signatures.PublicKey\n\tw.SecretKey, pk, err = signatures.GenerateKeyPair()\n\tw.SpendConditions.PublicKeys = append(w.SpendConditions.PublicKeys, pk)\n\tw.SpendConditions.NumSignatures = 1\n\n\tw.OwnedOutputs = make(map[siacore.OutputID]struct{})\n\tw.SpentOutputs = make(map[siacore.OutputID]struct{})\n\n\treturn\n}\n\n\/\/ Scans all unspent transactions and adds the ones that are spendable by this\n\/\/ wallet.\nfunc (w *Wallet) Scan() {\n\tw.OwnedOutputs = make(map[siacore.OutputID]struct{})\n\n\t\/\/ Check for owned outputs from the standard SpendConditions.\n\tscanAddresses := make(map[siacore.CoinAddress]struct{})\n\tscanAddresses[w.SpendConditions.CoinAddress()] = struct{}{}\n\n\t\/\/ Get the matching set of outputs and add them to the OwnedOutputs map.\n\toutputs := w.state.ScanOutputs(scanAddresses)\n\tfor _, output := range outputs {\n\t\tw.OwnedOutputs[output] = struct{}{}\n\t}\n}\n\n\/\/ fundTransaction() adds `amount` Currency to the inputs, creating a refund\n\/\/ output for any excess.\nfunc (w *Wallet) FundTransaction(amount siacore.Currency, t *siacore.Transaction) (err error) {\n\t\/\/ Check that a nonzero amount of coins is being sent.\n\tif amount == siacore.Currency(0) {\n\t\terr = errors.New(\"cannot send 0 coins\")\n\t\treturn\n\t}\n\n\t\/\/ Add to the list of inputs until enough funds have been allocated.\n\ttotal := siacore.Currency(0)\n\tvar newInputs []siacore.Input\n\tfor id, _ := range w.OwnedOutputs {\n\t\t\/\/ Check that the output has not already been assigned somewhere else.\n\t\t_, exists := w.SpentOutputs[id]\n\t\tif exists {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Check that the output exists.\n\t\tvar output siacore.Output\n\t\toutput, err = w.state.Output(id)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Create an input to add to the transaction.\n\t\tnewInput := siacore.Input{\n\t\t\tOutputID: id,\n\t\t\tSpendConditions: w.SpendConditions,\n\t\t}\n\t\tnewInputs = append(newInputs, newInput)\n\n\t\t\/\/ Add the value of the output to the total and see if we've hit a\n\t\t\/\/ sufficient amount.\n\t\ttotal += output.Value\n\t\tif total >= amount {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t\/\/ Check that the sum of the inputs is sufficient to complete the\n\t\/\/ transaction.\n\tif total < amount {\n\t\terr = errors.New(\"insufficient funds\")\n\t\treturn\n\t}\n\n\t\/\/ Add all of the inputs to the transaction.\n\tt.Inputs = append(t.Inputs, newInputs...)\n\n\t\/\/ Add all of the inputs to the spent outputs map.\n\tfor _, input := range newInputs {\n\t\tw.SpentOutputs[input.OutputID] = struct{}{}\n\t}\n\n\t\/\/ Add a refund output to the transaction if needed.\n\tif total-amount > 0 {\n\t\tt.Outputs = append(t.Outputs, siacore.Output{Value: total - amount, SpendHash: w.SpendConditions.CoinAddress()})\n\t}\n\n\treturn\n}\n\n\/\/ Wallet.signTransaction() takes a transaction and adds a signature for every input\n\/\/ that the wallet understands how to spend.\nfunc (w *Wallet) SignTransaction(t *siacore.Transaction) (err error) {\n\tfor i, input := range t.Inputs {\n\t\t\/\/ If we recognize the input as something we are able to sign, we sign\n\t\t\/\/ the input.\n\t\tif input.SpendConditions.CoinAddress() == w.SpendConditions.CoinAddress() {\n\t\t\ttxnSig := siacore.TransactionSignature{\n\t\t\t\tInputID: input.OutputID,\n\t\t\t}\n\t\t\tt.Signatures = append(t.Signatures, txnSig)\n\n\t\t\tsigHash := t.SigHash(i)\n\t\t\tt.Signatures[i].Signature, err = signatures.SignBytes(sigHash[:], w.SecretKey)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\treturn\n}\n\n\/\/ Wallet.SpendCoins creates a transaction sending 'amount' to 'address', and\n\/\/ allocateding 'minerFee' as a miner fee. The transaction is submitted to the\n\/\/ miner pool, but is also returned.\nfunc (e *Environment) SpendCoins(amount, minerFee siacore.Currency, address siacore.CoinAddress) (t siacore.Transaction, err error) {\n\t\/\/ Scan blockchain for outputs.\n\te.wallet.Scan()\n\n\t\/\/ Add `amount` of free coins to the transaction.\n\terr = e.wallet.FundTransaction(amount+minerFee, &t)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Add the miner fee.\n\tt.MinerFees = append(t.MinerFees, minerFee)\n\n\t\/\/ Add the output to `address`.\n\tt.Outputs = append(t.Outputs, siacore.Output{Value: amount, SpendHash: address})\n\n\t\/\/ Sign each input.\n\terr = e.wallet.SignTransaction(&t)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ TODO: AcceptTransaction shoul be piped through a channel.\n\terr = e.wallet.state.AcceptTransaction(t)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\n\/\/ Environment.CoinAddress returns the CoinAddress which foreign coins should\n\/\/ be sent to.\nfunc (e *Environment) CoinAddress() siacore.CoinAddress {\n\treturn e.wallet.SpendConditions.CoinAddress()\n}\n\n\/\/ SaveCoinAddress saves the address of the wallet used within the environment.\nfunc (e *Environment) SaveCoinAddress(filename string) (err error) {\n\tpubKeyBytes := encoding.Marshal(e.wallet.SpendConditions.CoinAddress())\n\n\t\/\/ Open the file and write the key to the filename.\n\tfile, err := os.Create(filename)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer file.Close()\n\t_, err = file.Write(pubKeyBytes)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}\n\n\/\/ LoadCoinAddress loads a coin address from a file and adds that address to\n\/\/ the friend list using the input name. An error is returned if the name is\n\/\/ already in the friend list.\nfunc (e *Environment) LoadCoinAddress(filename string, friendName string) (err error) {\n\t\/\/ Open the file and read the key to a friend map.\n\tfile, err := os.Open(filename)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer file.Close()\n\n\t\/\/ Read the contents of the file into a buffer.\n\tbuffer := make([]byte, 256)\n\tbytes, err := file.Read(buffer)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Decode the bytes into an address.\n\tvar address siacore.CoinAddress\n\terr = encoding.Unmarshal(buffer[:bytes], &address)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t\/\/ Add the address to the friends list.\n\te.friends[friendName] = address\n\n\treturn\n}\n\nfunc (e *Environment) SaveSecretKey(filename string) (err error) {\n\treturn\n}\n\nfunc (e *Environment) LoadSecretKey(filename string) (err error) {\n\treturn\n}\n<|endoftext|>"} {"text":"package aws\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/awserr\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/opsworks\"\n\t\"github.com\/hashicorp\/terraform\/helper\/resource\"\n\t\"github.com\/hashicorp\/terraform\/terraform\"\n)\n\n\/\/ These tests assume the existence of predefined Opsworks IAM roles named `aws-opsworks-ec2-role`\n\/\/ and `aws-opsworks-service-role`.\n\nfunc TestAccAWSOpsworksCustomLayer(t *testing.T) {\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck: func() { testAccPreCheck(t) },\n\t\tProviders: testAccProviders,\n\t\tCheckDestroy: testAccCheckAwsOpsworksCustomLayerDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccAwsOpsworksCustomLayerConfigCreate,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"name\", \"tf-ops-acc-custom-layer\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"auto_assign_elastic_ips\", \"false\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"auto_healing\", \"true\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"drain_elb_on_shutdown\", \"true\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"instance_shutdown_timeout\", \"300\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"custom_security_group_ids.#\", \"2\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"system_packages.#\", \"2\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"system_packages.1368285564\", \"git\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"system_packages.2937857443\", \"golang\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"ebs_volume.#\", \"1\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"ebs_volume.3575749636.type\", \"gp2\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"ebs_volume.3575749636.number_of_disks\", \"2\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"ebs_volume.3575749636.mount_point\", \"\/home\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"ebs_volume.3575749636.size\", \"100\",\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t},\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccAwsOpsworksCustomLayerConfigUpdate,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"name\", \"tf-ops-acc-custom-layer\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"drain_elb_on_shutdown\", \"false\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"instance_shutdown_timeout\", \"120\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"custom_security_group_ids.#\", \"3\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"system_packages.#\", \"3\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"system_packages.1368285564\", \"git\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"system_packages.2937857443\", \"golang\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"system_packages.4101929740\", \"subversion\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"ebs_volume.#\", \"2\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"ebs_volume.3575749636.type\", \"gp2\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"ebs_volume.3575749636.number_of_disks\", \"2\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"ebs_volume.3575749636.mount_point\", \"\/home\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"ebs_volume.3575749636.size\", \"100\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"ebs_volume.1266957920.type\", \"io1\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"ebs_volume.1266957920.number_of_disks\", \"4\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"ebs_volume.1266957920.mount_point\", \"\/var\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"ebs_volume.1266957920.size\", \"100\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"ebs_volume.1266957920.raid_level\", \"1\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"ebs_volume.1266957920.iops\", \"3000\",\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc testAccCheckAwsOpsworksCustomLayerDestroy(s *terraform.State) error {\n\topsworksconn := testAccProvider.Meta().(*AWSClient).opsworksconn\n\tfor _, rs := range s.RootModule().Resources {\n\t\tif rs.Type != \"aws_opsworks_custom_layer\" {\n\t\t\tcontinue\n\t\t}\n\t\treq := &opsworks.DescribeLayersInput{\n\t\t\tLayerIds: []*string{\n\t\t\t\taws.String(rs.Primary.ID),\n\t\t\t},\n\t\t}\n\n\t\t_, err := opsworksconn.DescribeLayers(req)\n\t\tif err != nil {\n\t\t\tif awserr, ok := err.(awserr.Error); ok {\n\t\t\t\tif awserr.Code() == \"ResourceNotFoundException\" {\n\t\t\t\t\t\/\/ not found, good to go\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn fmt.Errorf(\"Fall through error on OpsWorks custom layer test\")\n}\n\nvar testAccAwsOpsworksCustomLayerSecurityGroups = `\nresource \"aws_security_group\" \"tf-ops-acc-layer1\" {\n name = \"tf-ops-acc-layer1\"\n ingress {\n from_port = 8\n to_port = -1\n protocol = \"icmp\"\n cidr_blocks = [\"0.0.0.0\/0\"]\n }\n}\nresource \"aws_security_group\" \"tf-ops-acc-layer2\" {\n name = \"tf-ops-acc-layer2\"\n ingress {\n from_port = 8\n to_port = -1\n protocol = \"icmp\"\n cidr_blocks = [\"0.0.0.0\/0\"]\n }\n}\n`\n\nvar testAccAwsOpsworksCustomLayerConfigCreate = testAccAwsOpsworksStackConfigNoVpcCreate + testAccAwsOpsworksCustomLayerSecurityGroups + `\nprovider \"aws\" {\n\tregion = \"us-east-1\"\n}\n\nresource \"aws_opsworks_custom_layer\" \"tf-acc\" {\n stack_id = \"${aws_opsworks_stack.tf-acc.id}\"\n name = \"tf-ops-acc-custom-layer\"\n short_name = \"tf-ops-acc-custom-layer\"\n auto_assign_public_ips = true\n custom_security_group_ids = [\n \"${aws_security_group.tf-ops-acc-layer1.id}\",\n \"${aws_security_group.tf-ops-acc-layer2.id}\",\n ]\n drain_elb_on_shutdown = true\n instance_shutdown_timeout = 300\n system_packages = [\n \"git\",\n \"golang\",\n ]\n ebs_volume {\n type = \"gp2\"\n number_of_disks = 2\n mount_point = \"\/home\"\n size = 100\n raid_level = 0\n }\n}\n`\n\nvar testAccAwsOpsworksCustomLayerConfigUpdate = testAccAwsOpsworksStackConfigNoVpcCreate + testAccAwsOpsworksCustomLayerSecurityGroups + `\nresource \"aws_security_group\" \"tf-ops-acc-layer3\" {\n name = \"tf-ops-acc-layer3\"\n ingress {\n from_port = 8\n to_port = -1\n protocol = \"icmp\"\n cidr_blocks = [\"0.0.0.0\/0\"]\n }\n}\nresource \"aws_opsworks_custom_layer\" \"tf-acc\" {\n stack_id = \"${aws_opsworks_stack.tf-acc.id}\"\n name = \"tf-ops-acc-custom-layer\"\n short_name = \"tf-ops-acc-custom-layer\"\n auto_assign_public_ips = true\n custom_security_group_ids = [\n \"${aws_security_group.tf-ops-acc-layer1.id}\",\n \"${aws_security_group.tf-ops-acc-layer2.id}\",\n \"${aws_security_group.tf-ops-acc-layer3.id}\",\n ]\n drain_elb_on_shutdown = false\n instance_shutdown_timeout = 120\n system_packages = [\n \"git\",\n \"golang\",\n \"subversion\",\n ]\n ebs_volume {\n type = \"gp2\"\n number_of_disks = 2\n mount_point = \"\/home\"\n size = 100\n raid_level = 0\n }\n ebs_volume {\n type = \"io1\"\n number_of_disks = 4\n mount_point = \"\/var\"\n size = 100\n raid_level = 1\n iops = 3000\n }\n}\n`\nprovider\/aws: Fix SG leak in opsworks custom layer testpackage aws\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/aws\/aws-sdk-go\/aws\/awserr\"\n\t\"github.com\/aws\/aws-sdk-go\/service\/opsworks\"\n\t\"github.com\/hashicorp\/terraform\/helper\/resource\"\n\t\"github.com\/hashicorp\/terraform\/terraform\"\n)\n\n\/\/ These tests assume the existence of predefined Opsworks IAM roles named `aws-opsworks-ec2-role`\n\/\/ and `aws-opsworks-service-role`.\n\nfunc TestAccAWSOpsworksCustomLayer(t *testing.T) {\n\tresource.Test(t, resource.TestCase{\n\t\tPreCheck: func() { testAccPreCheck(t) },\n\t\tProviders: testAccProviders,\n\t\tCheckDestroy: testAccCheckAwsOpsworksCustomLayerDestroy,\n\t\tSteps: []resource.TestStep{\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccAwsOpsworksCustomLayerConfigCreate,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"name\", \"tf-ops-acc-custom-layer\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"auto_assign_elastic_ips\", \"false\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"auto_healing\", \"true\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"drain_elb_on_shutdown\", \"true\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"instance_shutdown_timeout\", \"300\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"custom_security_group_ids.#\", \"2\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"system_packages.#\", \"2\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"system_packages.1368285564\", \"git\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"system_packages.2937857443\", \"golang\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"ebs_volume.#\", \"1\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"ebs_volume.3575749636.type\", \"gp2\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"ebs_volume.3575749636.number_of_disks\", \"2\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"ebs_volume.3575749636.mount_point\", \"\/home\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"ebs_volume.3575749636.size\", \"100\",\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t},\n\t\t\tresource.TestStep{\n\t\t\t\tConfig: testAccAwsOpsworksCustomLayerConfigUpdate,\n\t\t\t\tCheck: resource.ComposeTestCheckFunc(\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"name\", \"tf-ops-acc-custom-layer\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"drain_elb_on_shutdown\", \"false\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"instance_shutdown_timeout\", \"120\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"custom_security_group_ids.#\", \"3\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"system_packages.#\", \"3\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"system_packages.1368285564\", \"git\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"system_packages.2937857443\", \"golang\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"system_packages.4101929740\", \"subversion\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"ebs_volume.#\", \"2\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"ebs_volume.3575749636.type\", \"gp2\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"ebs_volume.3575749636.number_of_disks\", \"2\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"ebs_volume.3575749636.mount_point\", \"\/home\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"ebs_volume.3575749636.size\", \"100\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"ebs_volume.1266957920.type\", \"io1\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"ebs_volume.1266957920.number_of_disks\", \"4\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"ebs_volume.1266957920.mount_point\", \"\/var\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"ebs_volume.1266957920.size\", \"100\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"ebs_volume.1266957920.raid_level\", \"1\",\n\t\t\t\t\t),\n\t\t\t\t\tresource.TestCheckResourceAttr(\n\t\t\t\t\t\t\"aws_opsworks_custom_layer.tf-acc\", \"ebs_volume.1266957920.iops\", \"3000\",\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t},\n\t\t},\n\t})\n}\n\nfunc testAccCheckAwsOpsworksCustomLayerDestroy(s *terraform.State) error {\n\topsworksconn := testAccProvider.Meta().(*AWSClient).opsworksconn\n\tfor _, rs := range s.RootModule().Resources {\n\t\tif rs.Type != \"aws_opsworks_custom_layer\" {\n\t\t\tcontinue\n\t\t}\n\t\treq := &opsworks.DescribeLayersInput{\n\t\t\tLayerIds: []*string{\n\t\t\t\taws.String(rs.Primary.ID),\n\t\t\t},\n\t\t}\n\n\t\t_, err := opsworksconn.DescribeLayers(req)\n\t\tif err != nil {\n\t\t\tif awserr, ok := err.(awserr.Error); ok {\n\t\t\t\tif awserr.Code() == \"ResourceNotFoundException\" {\n\t\t\t\t\t\/\/ not found, good to go\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn fmt.Errorf(\"Fall through error on OpsWorks custom layer test\")\n}\n\nvar testAccAwsOpsworksCustomLayerSecurityGroups = `\nresource \"aws_security_group\" \"tf-ops-acc-layer1\" {\n name = \"tf-ops-acc-layer1\"\n ingress {\n from_port = 8\n to_port = -1\n protocol = \"icmp\"\n cidr_blocks = [\"0.0.0.0\/0\"]\n }\n}\nresource \"aws_security_group\" \"tf-ops-acc-layer2\" {\n name = \"tf-ops-acc-layer2\"\n ingress {\n from_port = 8\n to_port = -1\n protocol = \"icmp\"\n cidr_blocks = [\"0.0.0.0\/0\"]\n }\n}\n`\n\nvar testAccAwsOpsworksCustomLayerConfigCreate = testAccAwsOpsworksStackConfigNoVpcCreate + testAccAwsOpsworksCustomLayerSecurityGroups + `\nprovider \"aws\" {\n\tregion = \"us-east-1\"\n}\n\nresource \"aws_opsworks_custom_layer\" \"tf-acc\" {\n stack_id = \"${aws_opsworks_stack.tf-acc.id}\"\n name = \"tf-ops-acc-custom-layer\"\n short_name = \"tf-ops-acc-custom-layer\"\n auto_assign_public_ips = true\n custom_security_group_ids = [\n \"${aws_security_group.tf-ops-acc-layer1.id}\",\n \"${aws_security_group.tf-ops-acc-layer2.id}\",\n ]\n drain_elb_on_shutdown = true\n instance_shutdown_timeout = 300\n system_packages = [\n \"git\",\n \"golang\",\n ]\n ebs_volume {\n type = \"gp2\"\n number_of_disks = 2\n mount_point = \"\/home\"\n size = 100\n raid_level = 0\n }\n}\n`\n\nvar testAccAwsOpsworksCustomLayerConfigUpdate = testAccAwsOpsworksStackConfigNoVpcCreate + testAccAwsOpsworksCustomLayerSecurityGroups + `\nprovider \"aws\" {\n region = \"us-east-1\"\n}\n\nresource \"aws_security_group\" \"tf-ops-acc-layer3\" {\n name = \"tf-ops-acc-layer3\"\n ingress {\n from_port = 8\n to_port = -1\n protocol = \"icmp\"\n cidr_blocks = [\"0.0.0.0\/0\"]\n }\n}\nresource \"aws_opsworks_custom_layer\" \"tf-acc\" {\n stack_id = \"${aws_opsworks_stack.tf-acc.id}\"\n name = \"tf-ops-acc-custom-layer\"\n short_name = \"tf-ops-acc-custom-layer\"\n auto_assign_public_ips = true\n custom_security_group_ids = [\n \"${aws_security_group.tf-ops-acc-layer1.id}\",\n \"${aws_security_group.tf-ops-acc-layer2.id}\",\n \"${aws_security_group.tf-ops-acc-layer3.id}\",\n ]\n drain_elb_on_shutdown = false\n instance_shutdown_timeout = 120\n system_packages = [\n \"git\",\n \"golang\",\n \"subversion\",\n ]\n ebs_volume {\n type = \"gp2\"\n number_of_disks = 2\n mount_point = \"\/home\"\n size = 100\n raid_level = 0\n }\n ebs_volume {\n type = \"io1\"\n number_of_disks = 4\n mount_point = \"\/var\"\n size = 100\n raid_level = 1\n iops = 3000\n }\n}\n`\n<|endoftext|>"} {"text":"package regionagogo\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\n\t\"bufio\"\n\t\"os\"\n\n\t\"github.com\/Workiva\/go-datastructures\/augmentedtree\"\n\t\"github.com\/golang\/geo\/s2\"\n\t\"github.com\/golang\/protobuf\/proto\"\n\t\"github.com\/kpawlik\/geojson\"\n)\n\nconst (\n\tmininumViableLevel = 3 \/\/ the minimum cell level we accept\n)\n\n\/\/ GeoSearch provides in memory storage and query engine for region lookup\ntype GeoSearch struct {\n\taugmentedtree.Tree\n\trm map[int64]Region\n\tDebug bool\n}\n\n\/\/ Regions a slice of *Region (type used mainly to return one GeoJSON of the regions)\ntype Regions []*Region\n\n\/\/ Region is region for memory use\n\/\/ it contains an S2 loop and the associated metadata\ntype Region struct {\n\tData map[string]string `json:\"data\"`\n\tLoop *s2.Loop `json:\"-\"`\n}\n\n\/\/ NewGeoSearch\nfunc NewGeoSearch() *GeoSearch {\n\tgs := &GeoSearch{\n\t\tTree: augmentedtree.New(1),\n\t\trm: make(map[int64]Region),\n\t}\n\n\treturn gs\n}\n\n\/\/ ImportGeoData loads geodata file into a map loopID->Region\n\/\/ fills the segment tree for fast lookup\nfunc (gs *GeoSearch) ImportGeoData(filename string) error {\n\tvar gd GeoDataStorage\n\n\tb, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = proto.Unmarshal(b, &gd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor loopID, r := range gd.Rs {\n\t\tvar points []s2.Point\n\n\t\tfor _, c := range r.Points {\n\t\t\tll := s2.LatLngFromDegrees(float64(c.Lat), float64(c.Lng))\n\t\t\tpoint := s2.PointFromLatLng(ll)\n\t\t\tpoints = append(points, point)\n\t\t}\n\t\t\/\/ add 1st point as last point to close the shape\n\t\tpoints = append(points, points[0])\n\n\t\t\/\/ load the loops into memory\n\t\tl := s2.LoopFromPoints(points)\n\t\tif l.IsEmpty() || l.IsFull() {\n\t\t\treturn errors.New(\"invalid loop\")\n\t\t}\n\t\tgs.rm[int64(loopID)] = Region{Data: r.Data, Loop: l}\n\n\t}\n\n\t\/\/ load the cell ranges into the tree\n\tfor _, cLoop := range gd.Cl {\n\t\tgs.Add(&S2Interval{CellID: s2.CellID(cLoop.Cell), LoopIDs: cLoop.Loops})\n\t}\n\n\t\/\/ free some space\n\tgd.Cl = nil\n\tlog.Println(\"loaded\", len(gs.rm), \"regions\")\n\n\treturn nil\n}\n\n\/\/ Query returns the country for the corresponding lat, lng point\nfunc (gs *GeoSearch) StubbingQuery(lat, lng float64) *Region {\n\tq := s2.CellIDFromLatLng(s2.LatLngFromDegrees(lat, lng))\n\ti := &S2Interval{CellID: q}\n\tr := gs.Tree.Query(i)\n\n\tmatchLoopID := int64(-1)\n\n\tfor _, itv := range r {\n\t\tsitv := itv.(*S2Interval)\n\t\tif gs.Debug {\n\t\t\tfmt.Println(\"found\", sitv, sitv.LoopIDs)\n\t\t}\n\n\t\t\/\/ a region can include a smaller region\n\t\t\/\/ return only the one that is contained in the other\n\t\tfor _, loopID := range sitv.LoopIDs {\n\t\t\tif gs.rm[loopID].Loop.ContainsPoint(q.Point()) {\n\n\t\t\t\tif matchLoopID == -1 {\n\t\t\t\t\tmatchLoopID = loopID\n\t\t\t\t} else {\n\t\t\t\t\tfoundLoop := gs.rm[loopID].Loop\n\t\t\t\t\tpreviousLoop := gs.rm[matchLoopID].Loop\n\n\t\t\t\t\t\/\/ we take the 1st vertex of the foundloop if it is contained in previousLoop\n\t\t\t\t\t\/\/ foundLoop one is more precise\n\t\t\t\t\tif previousLoop.ContainsPoint(foundLoop.Vertex(0)) {\n\t\t\t\t\t\tmatchLoopID = loopID\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif matchLoopID != -1 {\n\t\tregion := gs.rm[matchLoopID]\n\t\treturn ®ion\n\t}\n\n\treturn nil\n}\n\n\/\/ importGeoJSONFile will load a geo json and save the polygons into\n\/\/ a msgpack file named geodata\n\/\/ fields to lookup for in GeoJSON\nfunc ImportGeoJSONFile(filename string, debug bool, fields []string) error {\n\tvar loopID int64\n\n\tfi, err := os.Open(filename)\n\tdefer fi.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar geo geojson.FeatureCollection\n\tr := bufio.NewReader(fi)\n\n\td := json.NewDecoder(r)\n\tif err := d.Decode(&geo); err != nil {\n\t\treturn err\n\t}\n\n\tvar geoData GeoDataStorage\n\n\tcl := make(map[s2.CellID][]int64)\n\n\tfor _, f := range geo.Features {\n\t\tgeom, err := f.GetGeometry()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\trc := &s2.RegionCoverer{MinLevel: 1, MaxLevel: 30, MaxCells: 8}\n\n\t\tswitch geom.GetType() {\n\t\tcase \"Polygon\":\n\t\t\tmp := geom.(*geojson.Polygon)\n\t\t\t\/\/ multipolygon\n\t\t\tfor _, p := range mp.Coordinates {\n\t\t\t\t\/\/ polygon\n\t\t\t\tvar points []s2.Point\n\t\t\t\tvar cpoints []*CPoint\n\t\t\t\t\/\/ For type \"MultiPolygon\", the \"coordinates\" member must be an array of Polygon coordinate arrays.\n\t\t\t\t\/\/ \"Polygon\", the \"coordinates\" member must be an array of LinearRing coordinate arrays.\n\t\t\t\t\/\/ For Polygons with multiple rings, the first must be the exterior ring and any others must be interior rings or holes.\n\n\t\t\t\t\/\/ reverse the slice\n\t\t\t\tfor i := len(p)\/2 - 1; i >= 0; i-- {\n\t\t\t\t\topp := len(p) - 1 - i\n\t\t\t\t\tp[i], p[opp] = p[opp], p[i]\n\t\t\t\t}\n\n\t\t\t\tfor i, c := range p {\n\t\t\t\t\tll := s2.LatLngFromDegrees(float64(c[1]), float64(c[0]))\n\t\t\t\t\tpoint := s2.PointFromLatLng(ll)\n\t\t\t\t\tpoints = append(points, point)\n\t\t\t\t\t\/\/ do not add cpoint on storage (first point is last point)\n\t\t\t\t\tif i == len(p)-1 {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tcpoints = append(cpoints, &CPoint{Lat: float32(c[1]), Lng: float32(c[0])})\n\t\t\t\t}\n\n\t\t\t\tl := LoopRegionFromPoints(points)\n\n\t\t\t\tif l.IsEmpty() || l.IsFull() {\n\t\t\t\t\tlog.Println(\"invalid loop\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tcovering := rc.Covering(l)\n\n\t\t\t\tdata := make(map[string]string)\n\t\t\t\tfor _, field := range fields {\n\t\t\t\t\tif v, ok := f.Properties[field].(string); !ok {\n\t\t\t\t\t\tlog.Println(\"can't find field on\", f.Properties)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdata[field] = v\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tcu := make([]uint64, len(covering))\n\t\t\t\tvar invalidLoop bool\n\n\t\t\t\tfor i, v := range covering {\n\t\t\t\t\t\/\/ added a security there if the level is too high it probably means the polygon is bogus\n\t\t\t\t\t\/\/ this to avoid a large cell to cover everything\n\t\t\t\t\tif v.Level() < mininumViableLevel {\n\t\t\t\t\t\tlog.Print(\"cell level too big\", v.Level(), loopID)\n\t\t\t\t\t\tinvalidLoop = true\n\t\t\t\t\t}\n\t\t\t\t\tcu[i] = uint64(v)\n\t\t\t\t}\n\n\t\t\t\t\/\/ do not insert big loop\n\t\t\t\tif invalidLoop {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tif debug {\n\t\t\t\t\tfmt.Println(\"import\", loopID, data)\n\t\t\t\t}\n\n\t\t\t\trs := &RegionStorage{\n\t\t\t\t\tData: data,\n\t\t\t\t\tPoints: cpoints,\n\t\t\t\t\tCellunion: cu,\n\t\t\t\t}\n\n\t\t\t\tgeoData.Rs = append(geoData.Rs, rs)\n\n\t\t\t\tfor _, cell := range covering {\n\t\t\t\t\tcl[cell] = append(cl[cell], loopID)\n\t\t\t\t}\n\n\t\t\t\tloopID = loopID + 1\n\t\t\t}\n\n\t\tcase \"MultiPolygon\":\n\t\t\tmp := geom.(*geojson.MultiPolygon)\n\t\t\t\/\/ multipolygon\n\t\t\tfor _, m := range mp.Coordinates {\n\t\t\t\t\/\/ polygon\n\t\t\t\tvar points []s2.Point\n\t\t\t\tvar cpoints []*CPoint\n\t\t\t\t\/\/ For type \"MultiPolygon\", the \"coordinates\" member must be an array of Polygon coordinate arrays.\n\t\t\t\t\/\/ \"Polygon\", the \"coordinates\" member must be an array of LinearRing coordinate arrays.\n\t\t\t\t\/\/ For Polygons with multiple rings, the first must be the exterior ring and any others must be interior rings or holes.\n\n\t\t\t\tif len(m) < 1 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tp := m[0]\n\t\t\t\t\/\/ coordinates\n\n\t\t\t\t\/\/ reverse the slice\n\t\t\t\tfor i := len(p)\/2 - 1; i >= 0; i-- {\n\t\t\t\t\topp := len(p) - 1 - i\n\t\t\t\t\tp[i], p[opp] = p[opp], p[i]\n\t\t\t\t}\n\n\t\t\t\tfor i, c := range p {\n\t\t\t\t\tll := s2.LatLngFromDegrees(float64(c[1]), float64(c[0]))\n\t\t\t\t\tpoint := s2.PointFromLatLng(ll)\n\t\t\t\t\tpoints = append(points, point)\n\t\t\t\t\t\/\/ do not add cpoint on storage (first point is last point)\n\t\t\t\t\tif i == len(p)-1 {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tcpoints = append(cpoints, &CPoint{Lat: float32(c[1]), Lng: float32(c[0])})\n\t\t\t\t}\n\n\t\t\t\t\/\/ TODO: parallelized region cover\n\t\t\t\tl := LoopRegionFromPoints(points)\n\n\t\t\t\tif l.IsEmpty() || l.IsFull() {\n\t\t\t\t\tlog.Println(\"invalid loop\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tcovering := rc.Covering(l)\n\n\t\t\t\tdata := make(map[string]string)\n\t\t\t\tfor _, field := range fields {\n\t\t\t\t\tif v, ok := f.Properties[field].(string); !ok {\n\t\t\t\t\t\tlog.Println(\"can't find field on\", f.Properties)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdata[field] = v\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tcu := make([]uint64, len(covering))\n\t\t\t\tvar invalidLoop bool\n\n\t\t\t\tfor i, v := range covering {\n\t\t\t\t\t\/\/ added a security there if the level is too high it probably means the polygon is bogus\n\t\t\t\t\t\/\/ this to avoid a large cell to cover everything\n\t\t\t\t\tif v.Level() < mininumViableLevel {\n\t\t\t\t\t\tlog.Print(\"cell level too big\", v.Level(), loopID)\n\t\t\t\t\t\tinvalidLoop = true\n\t\t\t\t\t}\n\t\t\t\t\tcu[i] = uint64(v)\n\t\t\t\t}\n\n\t\t\t\t\/\/ do not insert big loop\n\t\t\t\tif invalidLoop {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tif debug {\n\t\t\t\t\tfmt.Println(\"import\", loopID, data)\n\t\t\t\t}\n\n\t\t\t\trs := &RegionStorage{\n\t\t\t\t\tData: data,\n\t\t\t\t\tPoints: cpoints,\n\t\t\t\t\tCellunion: cu,\n\t\t\t\t}\n\n\t\t\t\tgeoData.Rs = append(geoData.Rs, rs)\n\n\t\t\t\tfor _, cell := range covering {\n\t\t\t\t\tcl[cell] = append(cl[cell], loopID)\n\t\t\t\t}\n\n\t\t\t\tloopID = loopID + 1\n\t\t\t}\n\t\tdefault:\n\t\t\treturn errors.New(\"unknown type\")\n\t\t}\n\n\t}\n\n\tfor k, v := range cl {\n\t\tgeoData.Cl = append(geoData.Cl, &CellIDLoopStorage{Cell: uint64(k), Loops: v})\n\t}\n\n\tlog.Println(\"imported\", filename, len(geoData.Rs), \"regions\")\n\n\tb, err := proto.Marshal(&geoData)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(\"geodata\", b, 0644)\n\n\treturn nil\n}\nprepare db querypackage regionagogo\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\n\t\"bufio\"\n\t\"os\"\n\n\t\"github.com\/Workiva\/go-datastructures\/augmentedtree\"\n\t\"github.com\/golang\/geo\/s2\"\n\t\"github.com\/golang\/protobuf\/proto\"\n\t\"github.com\/kpawlik\/geojson\"\n)\n\nconst (\n\tmininumViableLevel = 3 \/\/ the minimum cell level we accept\n)\n\n\/\/ GeoSearch provides in memory storage and query engine for region lookup\ntype GeoSearch struct {\n\taugmentedtree.Tree\n\trm map[int64]Region\n\tDebug bool\n}\n\n\/\/ Regions a slice of *Region (type used mainly to return one GeoJSON of the regions)\ntype Regions []*Region\n\n\/\/ Region is region for memory use\n\/\/ it contains an S2 loop and the associated metadata\ntype Region struct {\n\tData map[string]string `json:\"data\"`\n\tLoop *s2.Loop `json:\"-\"`\n}\n\n\/\/ NewGeoSearch\nfunc NewGeoSearch() *GeoSearch {\n\tgs := &GeoSearch{\n\t\tTree: augmentedtree.New(1),\n\t\trm: make(map[int64]Region),\n\t}\n\n\treturn gs\n}\n\n\/\/ ImportGeoData loads geodata file into a map loopID->Region\n\/\/ fills the segment tree for fast lookup\nfunc (gs *GeoSearch) ImportGeoData(filename string) error {\n\tvar gd GeoDataStorage\n\n\tb, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = proto.Unmarshal(b, &gd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor loopID, r := range gd.Rs {\n\t\tvar points []s2.Point\n\n\t\tfor _, c := range r.Points {\n\t\t\tll := s2.LatLngFromDegrees(float64(c.Lat), float64(c.Lng))\n\t\t\tpoint := s2.PointFromLatLng(ll)\n\t\t\tpoints = append(points, point)\n\t\t}\n\t\t\/\/ add 1st point as last point to close the shape\n\t\tpoints = append(points, points[0])\n\n\t\t\/\/ load the loops into memory\n\t\tl := s2.LoopFromPoints(points)\n\t\tif l.IsEmpty() || l.IsFull() {\n\t\t\treturn errors.New(\"invalid loop\")\n\t\t}\n\t\tgs.rm[int64(loopID)] = Region{Data: r.Data, Loop: l}\n\n\t}\n\n\t\/\/ load the cell ranges into the tree\n\tfor _, cLoop := range gd.Cl {\n\t\tgs.Add(&S2Interval{CellID: s2.CellID(cLoop.Cell), LoopIDs: cLoop.Loops})\n\t}\n\n\t\/\/ free some space\n\tgd.Cl = nil\n\tlog.Println(\"loaded\", len(gs.rm), \"regions\")\n\n\treturn nil\n}\n\n\/\/ TODO: refactor as Fence ?\nfunc (gs *GeoSearch) RegionByID(loopID int64) *Region {\n\tif l, ok := gs.rm[loopID]; ok {\n\t\treturn &l\n\t}\n\treturn nil\n}\n\n\/\/ Query returns the country for the corresponding lat, lng point\nfunc (gs *GeoSearch) StubbingQuery(lat, lng float64) *Region {\n\tq := s2.CellIDFromLatLng(s2.LatLngFromDegrees(lat, lng))\n\ti := &S2Interval{CellID: q}\n\tr := gs.Tree.Query(i)\n\n\tmatchLoopID := int64(-1)\n\n\tfor _, itv := range r {\n\t\tsitv := itv.(*S2Interval)\n\t\tif gs.Debug {\n\t\t\tfmt.Println(\"found\", sitv, sitv.LoopIDs)\n\t\t}\n\n\t\t\/\/ a region can include a smaller region\n\t\t\/\/ return only the one that is contained in the other\n\t\tfor _, loopID := range sitv.LoopIDs {\n\t\t\tregion := gs.RegionByID(loopID)\n\t\t\tif region.Loop.ContainsPoint(q.Point()) {\n\n\t\t\t\tif matchLoopID == -1 {\n\t\t\t\t\tmatchLoopID = loopID\n\t\t\t\t} else {\n\t\t\t\t\tfoundLoop := region.Loop\n\t\t\t\t\tpreviousLoop := gs.rm[matchLoopID].Loop\n\n\t\t\t\t\t\/\/ we take the 1st vertex of the foundloop if it is contained in previousLoop\n\t\t\t\t\t\/\/ foundLoop one is more precise\n\t\t\t\t\tif previousLoop.ContainsPoint(foundLoop.Vertex(0)) {\n\t\t\t\t\t\tmatchLoopID = loopID\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif matchLoopID != -1 {\n\t\tregion := gs.rm[matchLoopID]\n\t\treturn ®ion\n\t}\n\n\treturn nil\n}\n\n\/\/ importGeoJSONFile will load a geo json and save the polygons into\n\/\/ a msgpack file named geodata\n\/\/ fields to lookup for in GeoJSON\nfunc ImportGeoJSONFile(filename string, debug bool, fields []string) error {\n\tvar loopID int64\n\n\tfi, err := os.Open(filename)\n\tdefer fi.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar geo geojson.FeatureCollection\n\tr := bufio.NewReader(fi)\n\n\td := json.NewDecoder(r)\n\tif err := d.Decode(&geo); err != nil {\n\t\treturn err\n\t}\n\n\tvar geoData GeoDataStorage\n\n\tcl := make(map[s2.CellID][]int64)\n\n\tfor _, f := range geo.Features {\n\t\tgeom, err := f.GetGeometry()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\trc := &s2.RegionCoverer{MinLevel: 1, MaxLevel: 30, MaxCells: 8}\n\n\t\tswitch geom.GetType() {\n\t\tcase \"Polygon\":\n\t\t\tmp := geom.(*geojson.Polygon)\n\t\t\t\/\/ multipolygon\n\t\t\tfor _, p := range mp.Coordinates {\n\t\t\t\t\/\/ polygon\n\t\t\t\tvar points []s2.Point\n\t\t\t\tvar cpoints []*CPoint\n\t\t\t\t\/\/ For type \"MultiPolygon\", the \"coordinates\" member must be an array of Polygon coordinate arrays.\n\t\t\t\t\/\/ \"Polygon\", the \"coordinates\" member must be an array of LinearRing coordinate arrays.\n\t\t\t\t\/\/ For Polygons with multiple rings, the first must be the exterior ring and any others must be interior rings or holes.\n\n\t\t\t\t\/\/ reverse the slice\n\t\t\t\tfor i := len(p)\/2 - 1; i >= 0; i-- {\n\t\t\t\t\topp := len(p) - 1 - i\n\t\t\t\t\tp[i], p[opp] = p[opp], p[i]\n\t\t\t\t}\n\n\t\t\t\tfor i, c := range p {\n\t\t\t\t\tll := s2.LatLngFromDegrees(float64(c[1]), float64(c[0]))\n\t\t\t\t\tpoint := s2.PointFromLatLng(ll)\n\t\t\t\t\tpoints = append(points, point)\n\t\t\t\t\t\/\/ do not add cpoint on storage (first point is last point)\n\t\t\t\t\tif i == len(p)-1 {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tcpoints = append(cpoints, &CPoint{Lat: float32(c[1]), Lng: float32(c[0])})\n\t\t\t\t}\n\n\t\t\t\tl := LoopRegionFromPoints(points)\n\n\t\t\t\tif l.IsEmpty() || l.IsFull() {\n\t\t\t\t\tlog.Println(\"invalid loop\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tcovering := rc.Covering(l)\n\n\t\t\t\tdata := make(map[string]string)\n\t\t\t\tfor _, field := range fields {\n\t\t\t\t\tif v, ok := f.Properties[field].(string); !ok {\n\t\t\t\t\t\tlog.Println(\"can't find field on\", f.Properties)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdata[field] = v\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tcu := make([]uint64, len(covering))\n\t\t\t\tvar invalidLoop bool\n\n\t\t\t\tfor i, v := range covering {\n\t\t\t\t\t\/\/ added a security there if the level is too high it probably means the polygon is bogus\n\t\t\t\t\t\/\/ this to avoid a large cell to cover everything\n\t\t\t\t\tif v.Level() < mininumViableLevel {\n\t\t\t\t\t\tlog.Print(\"cell level too big\", v.Level(), loopID)\n\t\t\t\t\t\tinvalidLoop = true\n\t\t\t\t\t}\n\t\t\t\t\tcu[i] = uint64(v)\n\t\t\t\t}\n\n\t\t\t\t\/\/ do not insert big loop\n\t\t\t\tif invalidLoop {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tif debug {\n\t\t\t\t\tfmt.Println(\"import\", loopID, data)\n\t\t\t\t}\n\n\t\t\t\trs := &RegionStorage{\n\t\t\t\t\tData: data,\n\t\t\t\t\tPoints: cpoints,\n\t\t\t\t\tCellunion: cu,\n\t\t\t\t}\n\n\t\t\t\tgeoData.Rs = append(geoData.Rs, rs)\n\n\t\t\t\tfor _, cell := range covering {\n\t\t\t\t\tcl[cell] = append(cl[cell], loopID)\n\t\t\t\t}\n\n\t\t\t\tloopID = loopID + 1\n\t\t\t}\n\n\t\tcase \"MultiPolygon\":\n\t\t\tmp := geom.(*geojson.MultiPolygon)\n\t\t\t\/\/ multipolygon\n\t\t\tfor _, m := range mp.Coordinates {\n\t\t\t\t\/\/ polygon\n\t\t\t\tvar points []s2.Point\n\t\t\t\tvar cpoints []*CPoint\n\t\t\t\t\/\/ For type \"MultiPolygon\", the \"coordinates\" member must be an array of Polygon coordinate arrays.\n\t\t\t\t\/\/ \"Polygon\", the \"coordinates\" member must be an array of LinearRing coordinate arrays.\n\t\t\t\t\/\/ For Polygons with multiple rings, the first must be the exterior ring and any others must be interior rings or holes.\n\n\t\t\t\tif len(m) < 1 {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tp := m[0]\n\t\t\t\t\/\/ coordinates\n\n\t\t\t\t\/\/ reverse the slice\n\t\t\t\tfor i := len(p)\/2 - 1; i >= 0; i-- {\n\t\t\t\t\topp := len(p) - 1 - i\n\t\t\t\t\tp[i], p[opp] = p[opp], p[i]\n\t\t\t\t}\n\n\t\t\t\tfor i, c := range p {\n\t\t\t\t\tll := s2.LatLngFromDegrees(float64(c[1]), float64(c[0]))\n\t\t\t\t\tpoint := s2.PointFromLatLng(ll)\n\t\t\t\t\tpoints = append(points, point)\n\t\t\t\t\t\/\/ do not add cpoint on storage (first point is last point)\n\t\t\t\t\tif i == len(p)-1 {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tcpoints = append(cpoints, &CPoint{Lat: float32(c[1]), Lng: float32(c[0])})\n\t\t\t\t}\n\n\t\t\t\t\/\/ TODO: parallelized region cover\n\t\t\t\tl := LoopRegionFromPoints(points)\n\n\t\t\t\tif l.IsEmpty() || l.IsFull() {\n\t\t\t\t\tlog.Println(\"invalid loop\")\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tcovering := rc.Covering(l)\n\n\t\t\t\tdata := make(map[string]string)\n\t\t\t\tfor _, field := range fields {\n\t\t\t\t\tif v, ok := f.Properties[field].(string); !ok {\n\t\t\t\t\t\tlog.Println(\"can't find field on\", f.Properties)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdata[field] = v\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tcu := make([]uint64, len(covering))\n\t\t\t\tvar invalidLoop bool\n\n\t\t\t\tfor i, v := range covering {\n\t\t\t\t\t\/\/ added a security there if the level is too high it probably means the polygon is bogus\n\t\t\t\t\t\/\/ this to avoid a large cell to cover everything\n\t\t\t\t\tif v.Level() < mininumViableLevel {\n\t\t\t\t\t\tlog.Print(\"cell level too big\", v.Level(), loopID)\n\t\t\t\t\t\tinvalidLoop = true\n\t\t\t\t\t}\n\t\t\t\t\tcu[i] = uint64(v)\n\t\t\t\t}\n\n\t\t\t\t\/\/ do not insert big loop\n\t\t\t\tif invalidLoop {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\tif debug {\n\t\t\t\t\tfmt.Println(\"import\", loopID, data)\n\t\t\t\t}\n\n\t\t\t\trs := &RegionStorage{\n\t\t\t\t\tData: data,\n\t\t\t\t\tPoints: cpoints,\n\t\t\t\t\tCellunion: cu,\n\t\t\t\t}\n\n\t\t\t\tgeoData.Rs = append(geoData.Rs, rs)\n\n\t\t\t\tfor _, cell := range covering {\n\t\t\t\t\tcl[cell] = append(cl[cell], loopID)\n\t\t\t\t}\n\n\t\t\t\tloopID = loopID + 1\n\t\t\t}\n\t\tdefault:\n\t\t\treturn errors.New(\"unknown type\")\n\t\t}\n\n\t}\n\n\tfor k, v := range cl {\n\t\tgeoData.Cl = append(geoData.Cl, &CellIDLoopStorage{Cell: uint64(k), Loops: v})\n\t}\n\n\tlog.Println(\"imported\", filename, len(geoData.Rs), \"regions\")\n\n\tb, err := proto.Marshal(&geoData)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(\"geodata\", b, 0644)\n\n\treturn nil\n}\n<|endoftext|>"} {"text":"\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License, v. 2.0. If a copy of the MPL was not distributed with this\n\/\/ file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\/\/\n\/\/ Contributor:\n\/\/ - Julien Vehent jvehent@mozilla.com [:ulfr]\npackage main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"mig\"\n\t\"os\/exec\"\n\t\"runtime\"\n\t\"strings\"\n)\n\nfunc findHostname(orig_ctx Context) (ctx Context, err error) {\n\tctx = orig_ctx\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\terr = fmt.Errorf(\"findHostname() -> %v\", e)\n\t\t}\n\t\tctx.Channels.Log <- mig.Log{Desc: \"leaving findHostname()\"}.Debug()\n\t}()\n\n\t\/\/ get the hostname\n\tout, err := exec.Command(\"hostname\", \"--fqdn\").Output()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t\/\/ remove trailing newline\n\tctx.Agent.Hostname = fmt.Sprintf(\"%s\", out[0:len(out)-1])\n\treturn\n}\n\nfunc findOSInfo(orig_ctx Context) (ctx Context, err error) {\n\tctx = orig_ctx\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\terr = fmt.Errorf(\"findOSInfo() -> %v\", e)\n\t\t}\n\t\tctx.Channels.Log <- mig.Log{Desc: \"leaving findOSInfo()\"}.Debug()\n\t}()\n\tctx.Agent.OS = runtime.GOOS\n\tctx.Channels.Log <- mig.Log{Desc: fmt.Sprintf(\"OS is %s\", ctx.Agent.OS)}.Debug()\n\tctx.Agent.Env.Arch = runtime.GOARCH\n\tctx.Channels.Log <- mig.Log{Desc: fmt.Sprintf(\"Arch is %s\", ctx.Agent.Env.Arch)}.Debug()\n\tctx.Agent.Env.Ident, err = getLSBRelease()\n\tif err != nil {\n\t\tctx.Channels.Log <- mig.Log{Desc: fmt.Sprintf(\"getLSBRelease() failed: %v\", err)}.Info()\n\t\tctx.Agent.Env.Ident, err = getIssue()\n\t\tif err != nil {\n\t\t\tctx.Channels.Log <- mig.Log{Desc: fmt.Sprintf(\"getIssue() failed: %v\", err)}.Info()\n\t\t}\n\t}\n\tctx.Channels.Log <- mig.Log{Desc: fmt.Sprintf(\"Ident is %s\", ctx.Agent.Env.Ident)}.Debug()\n\tctx.Agent.Env.Init, err = getInit()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tctx.Channels.Log <- mig.Log{Desc: fmt.Sprintf(\"Init is %s\", ctx.Agent.Env.Init)}.Debug()\n\treturn\n}\n\n\/\/ getLSBRelease reads the linux identity from lsb_release -a\nfunc getLSBRelease() (desc string, err error) {\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\terr = fmt.Errorf(\"getLSBRelease() -> %v\", e)\n\t\t}\n\t}()\n\tpath, err := exec.LookPath(\"lsb_release\")\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"lsb_release is not present\")\n\t}\n\tout, err := exec.Command(path, \"-i\", \"-r\", \"-c\", \"-s\").Output()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdesc = fmt.Sprintf(\"%s\", out[0:len(out)-1])\n\tdesc = cleanString(desc)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn\n}\n\n\/\/ getIssue parses \/etc\/issue and returns the first line\nfunc getIssue() (initname string, err error) {\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\terr = fmt.Errorf(\"getIssue() -> %v\", e)\n\t\t}\n\t}()\n\tissue, err := ioutil.ReadFile(\"\/etc\/issue\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tloc := bytes.IndexAny(issue, \"\\n\")\n\tif loc < 2 {\n\t\treturn \"\", fmt.Errorf(\"issue string not found\")\n\t}\n\tinitname = fmt.Sprintf(\"%s\", issue[0:loc])\n\treturn\n}\n\n\/\/ getInit parses \/proc\/1\/cmdline to find out which init system is used\nfunc getInit() (initname string, err error) {\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\terr = fmt.Errorf(\"getInit() -> %v\", e)\n\t\t}\n\t}()\n\tinitCmd, err := ioutil.ReadFile(\"\/proc\/1\/cmdline\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tinit := fmt.Sprintf(\"%s\", initCmd)\n\tif strings.Contains(init, \"init [\") {\n\t\tinitname = \"sysvinit\"\n\t} else if strings.Contains(init, \"systemd\") {\n\t\tinitname = \"systemd\"\n\t} else if strings.Contains(init, \"init\") {\n\t\tinitname = \"upstart\"\n\t} else {\n\t\t\/\/ failed to detect init system, falling back to sysvinit\n\t\tinitname = \"sysvinit-fallback\"\n\t}\n\treturn\n}\n\nfunc getRunDir() string {\n\treturn \"\/var\/run\/mig\/\"\n}\n[minor] fall back to os.Hostname() if linux agents fails to use --fqdn\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License, v. 2.0. If a copy of the MPL was not distributed with this\n\/\/ file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\/\/\n\/\/ Contributor:\n\/\/ - Julien Vehent jvehent@mozilla.com [:ulfr]\npackage main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"mig\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"runtime\"\n\t\"strings\"\n)\n\nfunc findHostname(orig_ctx Context) (ctx Context, err error) {\n\tctx = orig_ctx\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\terr = fmt.Errorf(\"findHostname() -> %v\", e)\n\t\t}\n\t\tctx.Channels.Log <- mig.Log{Desc: \"leaving findHostname()\"}.Debug()\n\t}()\n\n\t\/\/ get the hostname\n\tout, err := exec.Command(\"hostname\", \"--fqdn\").Output()\n\tif err != nil {\n\t\t\/\/ --fqdn can fail sometimes. when that happens, use Go's builtin\n\t\t\/\/ hostname lookup (reads \/proc\/sys\/kernel\/hostname)\n\t\thostname, err := os.Hostname()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tctx.Agent.Hostname = hostname\n\t\treturn ctx, err\n\t}\n\t\/\/ remove trailing newline\n\tctx.Agent.Hostname = fmt.Sprintf(\"%s\", out[0:len(out)-1])\n\treturn\n}\n\nfunc findOSInfo(orig_ctx Context) (ctx Context, err error) {\n\tctx = orig_ctx\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\terr = fmt.Errorf(\"findOSInfo() -> %v\", e)\n\t\t}\n\t\tctx.Channels.Log <- mig.Log{Desc: \"leaving findOSInfo()\"}.Debug()\n\t}()\n\tctx.Agent.OS = runtime.GOOS\n\tctx.Channels.Log <- mig.Log{Desc: fmt.Sprintf(\"OS is %s\", ctx.Agent.OS)}.Debug()\n\tctx.Agent.Env.Arch = runtime.GOARCH\n\tctx.Channels.Log <- mig.Log{Desc: fmt.Sprintf(\"Arch is %s\", ctx.Agent.Env.Arch)}.Debug()\n\tctx.Agent.Env.Ident, err = getLSBRelease()\n\tif err != nil {\n\t\tctx.Channels.Log <- mig.Log{Desc: fmt.Sprintf(\"getLSBRelease() failed: %v\", err)}.Info()\n\t\tctx.Agent.Env.Ident, err = getIssue()\n\t\tif err != nil {\n\t\t\tctx.Channels.Log <- mig.Log{Desc: fmt.Sprintf(\"getIssue() failed: %v\", err)}.Info()\n\t\t}\n\t}\n\tctx.Channels.Log <- mig.Log{Desc: fmt.Sprintf(\"Ident is %s\", ctx.Agent.Env.Ident)}.Debug()\n\tctx.Agent.Env.Init, err = getInit()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tctx.Channels.Log <- mig.Log{Desc: fmt.Sprintf(\"Init is %s\", ctx.Agent.Env.Init)}.Debug()\n\treturn\n}\n\n\/\/ getLSBRelease reads the linux identity from lsb_release -a\nfunc getLSBRelease() (desc string, err error) {\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\terr = fmt.Errorf(\"getLSBRelease() -> %v\", e)\n\t\t}\n\t}()\n\tpath, err := exec.LookPath(\"lsb_release\")\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"lsb_release is not present\")\n\t}\n\tout, err := exec.Command(path, \"-i\", \"-r\", \"-c\", \"-s\").Output()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdesc = fmt.Sprintf(\"%s\", out[0:len(out)-1])\n\tdesc = cleanString(desc)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn\n}\n\n\/\/ getIssue parses \/etc\/issue and returns the first line\nfunc getIssue() (initname string, err error) {\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\terr = fmt.Errorf(\"getIssue() -> %v\", e)\n\t\t}\n\t}()\n\tissue, err := ioutil.ReadFile(\"\/etc\/issue\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tloc := bytes.IndexAny(issue, \"\\n\")\n\tif loc < 2 {\n\t\treturn \"\", fmt.Errorf(\"issue string not found\")\n\t}\n\tinitname = fmt.Sprintf(\"%s\", issue[0:loc])\n\treturn\n}\n\n\/\/ getInit parses \/proc\/1\/cmdline to find out which init system is used\nfunc getInit() (initname string, err error) {\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\terr = fmt.Errorf(\"getInit() -> %v\", e)\n\t\t}\n\t}()\n\tinitCmd, err := ioutil.ReadFile(\"\/proc\/1\/cmdline\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tinit := fmt.Sprintf(\"%s\", initCmd)\n\tif strings.Contains(init, \"init [\") {\n\t\tinitname = \"sysvinit\"\n\t} else if strings.Contains(init, \"systemd\") {\n\t\tinitname = \"systemd\"\n\t} else if strings.Contains(init, \"init\") {\n\t\tinitname = \"upstart\"\n\t} else {\n\t\t\/\/ failed to detect init system, falling back to sysvinit\n\t\tinitname = \"sysvinit-fallback\"\n\t}\n\treturn\n}\n\nfunc getRunDir() string {\n\treturn \"\/var\/run\/mig\/\"\n}\n<|endoftext|>"} {"text":"package extkeys\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"testing\"\n)\n\ntype VectorsFile struct {\n\tData map[string][][6]string\n\tvectors []*Vector\n}\n\ntype Vector struct {\n\tlanguage, salt, password, input, mnemonic, seed, xprv string\n}\n\n\/\/ TestMnemonicPhrase\nfunc TestMnemonicPhrase(t *testing.T) {\n\n\tmnemonic := NewMnemonic(Salt)\n\n\t\/\/ test strength validation\n\tstrengths := []int{127, 129, 257}\n\tfor _, s := range strengths {\n\t\t_, err := mnemonic.MnemonicPhrase(s, EnglishLanguage)\n\t\tif err != ErrInvalidEntropyStrength {\n\t\t\tt.Errorf(\"Entropy strength '%d' should be invalid\", s)\n\t\t}\n\t}\n\n\t\/\/ test mnemonic generation\n\tt.Log(\"Test mnemonic generation:\")\n\tfor _, language := range mnemonic.AvailableLanguages() {\n\t\tphrase, err := mnemonic.MnemonicPhrase(128, language)\n\t\tt.Logf(\"Mnemonic (%s): %s\", Languages[language], phrase)\n\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Test failed: could not create seed: %s\", err)\n\t\t}\n\n\t\tif !mnemonic.ValidMnemonic(phrase, language) {\n\t\t\tt.Error(\"Seed is not valid Mnenomic\")\n\t\t}\n\t}\n\n\t\/\/ run against test vectors\n\tvectorsFile, err := LoadVectorsFile(\"mnemonic_vectors.json\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tt.Log(\"Test against pre-computed seed vectors:\")\n\tstats := map[string]int{}\n\tfor _, vector := range vectorsFile.vectors {\n\t\tstats[vector.language] += 1\n\t\tmnemonic := NewMnemonic(vector.salt)\n\t\tseed := mnemonic.MnemonicSeed(vector.mnemonic, vector.password)\n\t\tif fmt.Sprintf(\"%x\", seed) != vector.seed {\n\t\t\tt.Errorf(\"Test failed (%s): incorrect seed (%x) generated (expected: %s)\", vector.language, seed, vector.seed)\n\t\t\treturn\n\t\t}\n\t\t\/\/t.Logf(\"Test passed: correct seed (%x) generated (expected: %s)\", seed, vector.seed)\n\t}\n\tfor language, count := range stats {\n\t\tt.Logf(\"[%s]: %d tests completed\", language, count)\n\t}\n}\n\nfunc LoadVectorsFile(path string) (*VectorsFile, error) {\n\tfp, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Test failed: cannot open vectors file: %s\", err)\n\t}\n\n\tvar vectorsFile VectorsFile\n\tif err := json.NewDecoder(fp).Decode(&vectorsFile); err != nil {\n\t\treturn nil, fmt.Errorf(\"Test failed: cannot parse vectors file: %s\", err)\n\t}\n\n\t\/\/ load data into Vector structs\n\tfor language, data := range vectorsFile.Data {\n\t\tfor _, item := range data {\n\t\t\tvectorsFile.vectors = append(vectorsFile.vectors, &Vector{language, item[0], item[1], item[2], item[3], item[4], item[5]})\n\t\t}\n\t}\n\n\treturn &vectorsFile, nil\n}\n\nfunc (v *Vector) String() string {\n\treturn fmt.Sprintf(\"{salt: %s, password: %s, input: %s, mnemonic: %s, seed: %s, xprv: %s}\",\n\t\tv.salt, v.password, v.input, v.mnemonic, v.seed, v.xprv)\n}\nuse `stats[vector.language]++` to prevent lint errors when using `+= 1`package extkeys\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"os\"\n\t\"testing\"\n)\n\ntype VectorsFile struct {\n\tData map[string][][6]string\n\tvectors []*Vector\n}\n\ntype Vector struct {\n\tlanguage, salt, password, input, mnemonic, seed, xprv string\n}\n\n\/\/ TestMnemonicPhrase\nfunc TestMnemonicPhrase(t *testing.T) {\n\n\tmnemonic := NewMnemonic(Salt)\n\n\t\/\/ test strength validation\n\tstrengths := []int{127, 129, 257}\n\tfor _, s := range strengths {\n\t\t_, err := mnemonic.MnemonicPhrase(s, EnglishLanguage)\n\t\tif err != ErrInvalidEntropyStrength {\n\t\t\tt.Errorf(\"Entropy strength '%d' should be invalid\", s)\n\t\t}\n\t}\n\n\t\/\/ test mnemonic generation\n\tt.Log(\"Test mnemonic generation:\")\n\tfor _, language := range mnemonic.AvailableLanguages() {\n\t\tphrase, err := mnemonic.MnemonicPhrase(128, language)\n\t\tt.Logf(\"Mnemonic (%s): %s\", Languages[language], phrase)\n\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Test failed: could not create seed: %s\", err)\n\t\t}\n\n\t\tif !mnemonic.ValidMnemonic(phrase, language) {\n\t\t\tt.Error(\"Seed is not valid Mnenomic\")\n\t\t}\n\t}\n\n\t\/\/ run against test vectors\n\tvectorsFile, err := LoadVectorsFile(\"mnemonic_vectors.json\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tt.Log(\"Test against pre-computed seed vectors:\")\n\tstats := map[string]int{}\n\tfor _, vector := range vectorsFile.vectors {\n\t\tstats[vector.language]++\n\t\tmnemonic := NewMnemonic(vector.salt)\n\t\tseed := mnemonic.MnemonicSeed(vector.mnemonic, vector.password)\n\t\tif fmt.Sprintf(\"%x\", seed) != vector.seed {\n\t\t\tt.Errorf(\"Test failed (%s): incorrect seed (%x) generated (expected: %s)\", vector.language, seed, vector.seed)\n\t\t\treturn\n\t\t}\n\t\t\/\/t.Logf(\"Test passed: correct seed (%x) generated (expected: %s)\", seed, vector.seed)\n\t}\n\tfor language, count := range stats {\n\t\tt.Logf(\"[%s]: %d tests completed\", language, count)\n\t}\n}\n\nfunc LoadVectorsFile(path string) (*VectorsFile, error) {\n\tfp, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Test failed: cannot open vectors file: %s\", err)\n\t}\n\n\tvar vectorsFile VectorsFile\n\tif err := json.NewDecoder(fp).Decode(&vectorsFile); err != nil {\n\t\treturn nil, fmt.Errorf(\"Test failed: cannot parse vectors file: %s\", err)\n\t}\n\n\t\/\/ load data into Vector structs\n\tfor language, data := range vectorsFile.Data {\n\t\tfor _, item := range data {\n\t\t\tvectorsFile.vectors = append(vectorsFile.vectors, &Vector{language, item[0], item[1], item[2], item[3], item[4], item[5]})\n\t\t}\n\t}\n\n\treturn &vectorsFile, nil\n}\n\nfunc (v *Vector) String() string {\n\treturn fmt.Sprintf(\"{salt: %s, password: %s, input: %s, mnemonic: %s, seed: %s, xprv: %s}\",\n\t\tv.salt, v.password, v.input, v.mnemonic, v.seed, v.xprv)\n}\n<|endoftext|>"} {"text":"\/\/ Scrape the \/slave(1)\/state endpoint to get information on the tasks running\n\/\/ on executors. Information scraped at this point:\n\/\/\n\/\/ * Labels of running tasks (\"mesos_slave_task_labels\" series)\npackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"log\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"time\"\n\t\"regexp\"\n\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n)\n\ntype (\n\tslaveFramework struct {\n\t\tExecutors []executor `json:\"executors\"`\n\t}\n\n\tslaveState struct {\n\t\tFrameworks []slaveFramework `json:\"frameworks\"`\n\t}\n\n\tslaveStateCollector struct {\n\t\t*http.Client\n\t\turl string\n\t\tmetrics map[prometheus.Collector]func(*slaveState, prometheus.Collector)\n\t}\n)\n\n\/\/ Task labels must be alphanumeric, no leading digits.\nvar invalidLabelNameCharRE = regexp.MustCompile(\"[^a-zA-Z_0-9]\")\n\/\/ Replace invalid task label digits by underscores\nfunc normaliseLabel(label string) string {\n\tif len(label) > 0 && '0' <= label[0] && label[0] <= '9' {\n\t\treturn \"_\" + invalidLabelNameCharRE.ReplaceAllString(label[1:], \"_\");\n\t}\n\treturn invalidLabelNameCharRE.ReplaceAllString(label, \"_\");\n}\n\n\/\/ Return true if `needle` is in `haystack`\nfunc inArray(needle string, haystack []string) bool {\n\tfor _, elem := range haystack {\n\t\tif needle == elem {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc newSlaveStateCollector(url string, timeout time.Duration, userTaskLabelList []string) *slaveStateCollector {\n\tdefaultLabels := []string{\"source\", \"framework_id\", \"executor_id\"}\n\n\t\/\/ Sanitise user-supplied list of task labels that should be included in the series\n\tnormalisedUserTaskLabelList := []string{}\n\tfor _, label := range userTaskLabelList {\n\t\tnormalisedUserTaskLabelList = append(normalisedUserTaskLabelList, normaliseLabel(label))\n\t}\n\n\ttaskLabelList := append(defaultLabels, normalisedUserTaskLabelList...)\n\n\tmetrics := map[prometheus.Collector]func(*slaveState, prometheus.Collector){\n\t\tprometheus.NewGaugeVec(prometheus.GaugeOpts{\n\t\t\tHelp: \"Task labels\",\n\t\t\tNamespace: \"mesos\",\n\t\t\tSubsystem: \"slave\",\n\t\t\tName: \"task_labels\",\n\t\t}, taskLabelList): func(st *slaveState, c prometheus.Collector) {\n\t\t\tfor _, f := range st.Frameworks {\n\t\t\t\tfor _, e := range f.Executors {\n\t\t\t\t\tfor _, t := range e.Tasks {\n\t\t\t\t\t\t\/\/ Default labels\n\t\t\t\t\t\ttaskLabels := map[string]string{\n\t\t\t\t\t\t\t\"source\": e.Source,\n\t\t\t\t\t\t\t\"framework_id\": t.FrameworkID,\n\t\t\t\t\t\t\t\"executor_id\": t.ID,\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\/\/ User labels\n\t\t\t\t\t\tfor _, label := range t.Labels {\n\t\t\t\t\t\t\tnormalisedLabel := normaliseLabel(label.Key)\n\t\t\t\t\t\t\t\/\/ Ignore labels not explicitly whitelisted by user\n\t\t\t\t\t\t\tif (inArray(normalisedLabel, normalisedUserTaskLabelList)) {\n\t\t\t\t\t\t\t\ttaskLabels[normalisedLabel] = label.Value\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tc.(*prometheus.GaugeVec).With(taskLabels).Set(1)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t}\n\n\treturn &slaveStateCollector{\n\t\tClient: &http.Client{Timeout: timeout},\n\t\turl: url,\n\t\tmetrics: metrics,\n\t}\n}\n\nfunc (c *slaveStateCollector) Collect(ch chan<- prometheus.Metric) {\n\tu := strings.TrimSuffix(c.url, \"\/\") + \"\/slave(1)\/state\"\n\tres, err := c.Get(u)\n\tif err != nil {\n\t\tlog.Printf(\"Error fetching %s: %s\", u, err)\n\t\treturn\n\t}\n\tdefer res.Body.Close()\n\n\tvar s slaveState\n\tif err := json.NewDecoder(res.Body).Decode(&s); err != nil {\n\t\tlog.Print(\"Error decoding response body from %s: %s\", err)\n\t\treturn\n\t}\n\n\tfor c, set := range c.metrics {\n\t\tset(&s, c)\n\t\tc.Collect(ch)\n\t}\n}\n\nfunc (c *slaveStateCollector) Describe(ch chan<- *prometheus.Desc) {\n\tfor metric := range c.metrics {\n\t\tmetric.Describe(ch)\n\t}\n}\nmesos_slave_task_labels: Fix executor_id\/\/ Scrape the \/slave(1)\/state endpoint to get information on the tasks running\n\/\/ on executors. Information scraped at this point:\n\/\/\n\/\/ * Labels of running tasks (\"mesos_slave_task_labels\" series)\npackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"log\"\n\t\"net\/http\"\n\t\"strings\"\n\t\"time\"\n\t\"regexp\"\n\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n)\n\ntype (\n\tslaveFramework struct {\n\t\tID string `json:\"ID\"`\n\t\tExecutors []executor `json:\"executors\"`\n\t}\n\n\tslaveState struct {\n\t\tFrameworks []slaveFramework `json:\"frameworks\"`\n\t}\n\n\tslaveStateCollector struct {\n\t\t*http.Client\n\t\turl string\n\t\tmetrics map[prometheus.Collector]func(*slaveState, prometheus.Collector)\n\t}\n)\n\n\/\/ Task labels must be alphanumeric, no leading digits.\nvar invalidLabelNameCharRE = regexp.MustCompile(\"[^a-zA-Z_0-9]\")\n\/\/ Replace invalid task label digits by underscores\nfunc normaliseLabel(label string) string {\n\tif len(label) > 0 && '0' <= label[0] && label[0] <= '9' {\n\t\treturn \"_\" + invalidLabelNameCharRE.ReplaceAllString(label[1:], \"_\");\n\t}\n\treturn invalidLabelNameCharRE.ReplaceAllString(label, \"_\");\n}\n\n\/\/ Return true if `needle` is in `haystack`\nfunc inArray(needle string, haystack []string) bool {\n\tfor _, elem := range haystack {\n\t\tif needle == elem {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc newSlaveStateCollector(url string, timeout time.Duration, userTaskLabelList []string) *slaveStateCollector {\n\tdefaultLabels := []string{\"source\", \"framework_id\", \"executor_id\"}\n\n\t\/\/ Sanitise user-supplied list of task labels that should be included in the series\n\tnormalisedUserTaskLabelList := []string{}\n\tfor _, label := range userTaskLabelList {\n\t\tnormalisedUserTaskLabelList = append(normalisedUserTaskLabelList, normaliseLabel(label))\n\t}\n\n\ttaskLabelList := append(defaultLabels, normalisedUserTaskLabelList...)\n\n\tmetrics := map[prometheus.Collector]func(*slaveState, prometheus.Collector){\n\t\tprometheus.NewGaugeVec(prometheus.GaugeOpts{\n\t\t\tHelp: \"Task labels\",\n\t\t\tNamespace: \"mesos\",\n\t\t\tSubsystem: \"slave\",\n\t\t\tName: \"task_labels\",\n\t\t}, taskLabelList): func(st *slaveState, c prometheus.Collector) {\n\t\t\tfor _, f := range st.Frameworks {\n\t\t\t\tfor _, e := range f.Executors {\n\t\t\t\t\tfor _, t := range e.Tasks {\n\t\t\t\t\t\t\/\/ Default labels\n\t\t\t\t\t\ttaskLabels := map[string]string{\n\t\t\t\t\t\t\t\"source\": e.Source,\n\t\t\t\t\t\t\t\"framework_id\": f.ID,\n\t\t\t\t\t\t\t\"executor_id\": e.ID,\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\/\/ User labels\n\t\t\t\t\t\tfor _, label := range t.Labels {\n\t\t\t\t\t\t\tnormalisedLabel := normaliseLabel(label.Key)\n\t\t\t\t\t\t\t\/\/ Ignore labels not explicitly whitelisted by user\n\t\t\t\t\t\t\tif (inArray(normalisedLabel, normalisedUserTaskLabelList)) {\n\t\t\t\t\t\t\t\ttaskLabels[normalisedLabel] = label.Value\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tc.(*prometheus.GaugeVec).With(taskLabels).Set(1)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t}\n\n\treturn &slaveStateCollector{\n\t\tClient: &http.Client{Timeout: timeout},\n\t\turl: url,\n\t\tmetrics: metrics,\n\t}\n}\n\nfunc (c *slaveStateCollector) Collect(ch chan<- prometheus.Metric) {\n\tu := strings.TrimSuffix(c.url, \"\/\") + \"\/slave(1)\/state\"\n\tres, err := c.Get(u)\n\tif err != nil {\n\t\tlog.Printf(\"Error fetching %s: %s\", u, err)\n\t\treturn\n\t}\n\tdefer res.Body.Close()\n\n\tvar s slaveState\n\tif err := json.NewDecoder(res.Body).Decode(&s); err != nil {\n\t\tlog.Print(\"Error decoding response body from %s: %s\", err)\n\t\treturn\n\t}\n\n\tfor c, set := range c.metrics {\n\t\tset(&s, c)\n\t\tc.Collect(ch)\n\t}\n}\n\nfunc (c *slaveStateCollector) Describe(ch chan<- *prometheus.Desc) {\n\tfor metric := range c.metrics {\n\t\tmetric.Describe(ch)\n\t}\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2016 The Serviced Authors.\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage facade\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"strings\"\n\n\t\/\/\"github.com\/control-center\/serviced\/dao\"\n\t\"github.com\/control-center\/serviced\/datastore\"\n\t\"github.com\/control-center\/serviced\/domain\/service\"\n\t\"github.com\/control-center\/serviced\/domain\/servicedefinition\"\n\t\/\/\"github.com\/control-center\/serviced\/domain\/servicestate\"\n\t\"github.com\/zenoss\/glog\"\n)\n\n\/\/ Adds a port public endpoint to a service\nfunc (f *Facade) AddPublicEndpointPort(ctx datastore.Context, serviceID, endpointName, portAddr string,\n\tusetls bool, protocol string, isEnabled bool, restart bool) (*servicedefinition.Port, error) {\n\t\/\/ Validate the port number\n\tscrubbedPort := service.ScrubPortString(portAddr)\n\tportParts := strings.Split(scrubbedPort, \":\")\n\tif len(portParts) < 2 {\n\t\terr := fmt.Errorf(\"Invalid port address. Port address be \\\":[PORT NUMBER]\\\" or \\\"[IP ADDRESS]:[PORT NUMBER]\\\"\")\n\t\tglog.Error(err)\n\t\treturn nil, err\n\t}\n\n\t\/\/ Check to make sure the port is available. Don't allow adding a port if it's already being used.\n\t\/\/ This has the added benefit of validating the port address before it gets added to the service\n\t\/\/ definition.\n\tif err := checkPort(\"tcp\", fmt.Sprintf(\"%s\", scrubbedPort)); err != nil {\n\t\tglog.Error(err)\n\t\treturn nil, err\n\t}\n\n\t\/\/ Get the service for this service id.\n\tsvc, err := f.GetService(ctx, serviceID)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Could not find service %s: %s\", serviceID, err)\n\t\tglog.Error(err)\n\t\treturn nil, err\n\t}\n\n\t\/\/ check other ports for redundancy\n\tif services, err := f.GetAllServices(ctx); err != nil {\n\t\terr = fmt.Errorf(\"Could not get the list of services: %s\", err)\n\t\tglog.Error(err)\n\t\treturn nil, err\n\t} else {\n\t\tfor _, service := range services {\n\t\t\tif service.Endpoints == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfor _, endpoint := range service.Endpoints {\n\t\t\t\tfor _, epPort := range endpoint.PortList {\n\t\t\t\t\tif scrubbedPort == epPort.PortAddr {\n\t\t\t\t\t\terr := fmt.Errorf(\"Port %s already defined for service: %s\", epPort.PortAddr, service.Name)\n\t\t\t\t\t\tglog.Error(err)\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Add the port to the service definition.\n\tport, err := svc.AddPort(endpointName, portAddr, usetls, protocol, isEnabled)\n\tif err != nil {\n\t\tglog.Error(err)\n\t\treturn nil, err\n\t}\n\n\tglog.V(2).Infof(\"Added port public endpoint %s to service %s\", portAddr, svc.Name)\n\n\t\/\/ If the restart flag is given and the service is running, shut down all running instances.\n\tif restart && (svc.DesiredState == int(service.SVCRun) || svc.DesiredState == int(service.SVCRestart)) {\n\t\tif err := f.shutdownInstances(svc); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t\/\/ Update the service. This saves the new port configuration and will restart the\n\t\/\/ service if svc.DesiredState was configured for service.SVCRun or service.SVCRestart.\n\tif err = f.UpdateService(ctx, *svc); err != nil {\n\t\tglog.Error(err)\n\t\treturn nil, err\n\t}\n\n\tglog.V(2).Infof(\"Service %s updated after adding port public endpoint\", svc.Name)\n\treturn port, nil\n}\n\n\/\/ Try to open the port. If the port opens, we're good. Otherwise return the error.\nfunc checkPort(network string, laddr string) error {\n\tglog.V(2).Infof(\"Checking %s port %s\", network, laddr)\n\tlistener, err := net.Listen(network, laddr)\n\tif err != nil {\n\t\t\/\/ Port isn't available.\n\t\tglog.V(2).Infof(\"Port Listen failed; something else is using this port.\")\n\t\treturn err\n\t} else {\n\t\t\/\/ Port was opened. Make sure we close it.\n\t\tglog.V(2).Infof(\"Port Listen succeeded. Closing the listener.\")\n\t\tlistener.Close()\n\t}\n\treturn nil\n}\nAdd port 0 validation\/\/ Copyright 2016 The Serviced Authors.\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage facade\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"strings\"\n\n\t\"github.com\/control-center\/serviced\/datastore\"\n\t\"github.com\/control-center\/serviced\/domain\/service\"\n\t\"github.com\/control-center\/serviced\/domain\/servicedefinition\"\n\t\"github.com\/zenoss\/glog\"\n)\n\n\/\/ Adds a port public endpoint to a service\nfunc (f *Facade) AddPublicEndpointPort(ctx datastore.Context, serviceID, endpointName, portAddr string,\n\tusetls bool, protocol string, isEnabled bool, restart bool) (*servicedefinition.Port, error) {\n\t\/\/ Validate the port number\n\tscrubbedPort := service.ScrubPortString(portAddr)\n\tportParts := strings.Split(scrubbedPort, \":\")\n\tif len(portParts) < 2 {\n\t\terr := fmt.Errorf(\"Invalid port address. Port address be \\\":[PORT NUMBER]\\\" or \\\"[IP ADDRESS]:[PORT NUMBER]\\\"\")\n\t\tglog.Error(err)\n\t\treturn nil, err\n\t}\n\n\tif portAddr == \"0\" || strings.HasSuffix(portAddr, \":0\") {\n\t\terr := fmt.Errorf(\"Invalid port address. Port 0 is invalid.\")\n\t\tglog.Error(err)\n\t\treturn nil, err\n\t}\n\n\t\/\/ Check to make sure the port is available. Don't allow adding a port if it's already being used.\n\t\/\/ This has the added benefit of validating the port address before it gets added to the service\n\t\/\/ definition.\n\tif err := checkPort(\"tcp\", fmt.Sprintf(\"%s\", scrubbedPort)); err != nil {\n\t\tglog.Error(err)\n\t\treturn nil, err\n\t}\n\n\t\/\/ Get the service for this service id.\n\tsvc, err := f.GetService(ctx, serviceID)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Could not find service %s: %s\", serviceID, err)\n\t\tglog.Error(err)\n\t\treturn nil, err\n\t}\n\n\t\/\/ check other ports for redundancy\n\tif services, err := f.GetAllServices(ctx); err != nil {\n\t\terr = fmt.Errorf(\"Could not get the list of services: %s\", err)\n\t\tglog.Error(err)\n\t\treturn nil, err\n\t} else {\n\t\tfor _, service := range services {\n\t\t\tif service.Endpoints == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tfor _, endpoint := range service.Endpoints {\n\t\t\t\tfor _, epPort := range endpoint.PortList {\n\t\t\t\t\tif scrubbedPort == epPort.PortAddr {\n\t\t\t\t\t\terr := fmt.Errorf(\"Port %s already defined for service: %s\", epPort.PortAddr, service.Name)\n\t\t\t\t\t\tglog.Error(err)\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Add the port to the service definition.\n\tport, err := svc.AddPort(endpointName, portAddr, usetls, protocol, isEnabled)\n\tif err != nil {\n\t\tglog.Error(err)\n\t\treturn nil, err\n\t}\n\n\tglog.V(2).Infof(\"Added port public endpoint %s to service %s\", portAddr, svc.Name)\n\n\t\/\/ If the restart flag is given and the service is running, shut down all running instances.\n\tif restart && (svc.DesiredState == int(service.SVCRun) || svc.DesiredState == int(service.SVCRestart)) {\n\t\tif err := f.shutdownInstances(svc); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t\/\/ Update the service. This saves the new port configuration and will restart the\n\t\/\/ service if svc.DesiredState was configured for service.SVCRun or service.SVCRestart.\n\tif err = f.UpdateService(ctx, *svc); err != nil {\n\t\tglog.Error(err)\n\t\treturn nil, err\n\t}\n\n\tglog.V(2).Infof(\"Service %s updated after adding port public endpoint\", svc.Name)\n\treturn port, nil\n}\n\n\/\/ Try to open the port. If the port opens, we're good. Otherwise return the error.\nfunc checkPort(network string, laddr string) error {\n\tglog.V(2).Infof(\"Checking %s port %s\", network, laddr)\n\tlistener, err := net.Listen(network, laddr)\n\tif err != nil {\n\t\t\/\/ Port isn't available.\n\t\tglog.V(2).Infof(\"Port Listen failed; something else is using this port.\")\n\t\treturn err\n\t} else {\n\t\t\/\/ Port was opened. Make sure we close it.\n\t\tglog.V(2).Infof(\"Port Listen succeeded. Closing the listener.\")\n\t\tlistener.Close()\n\t}\n\treturn nil\n}\n<|endoftext|>"} {"text":"package network\n\nimport (\n\t\"common\"\n\t\"encoding\/json\"\n\t\"log\"\n\t\"net\"\n\t\"common\/log\"\n)\n\ntype NetworkMultiplexer struct {\n\tin chan common.NetworkMessage\n\tout chan idHandler\n\thosts map[string][]common.NetworkMessageHandler\n\tcreatedServer bool\n}\n\ntype idHandler struct {\n\thandler common.NetworkMessageHandler\n\tSwarmId string\n}\n\nfunc NewNetworkMultiplexer() common.NetworkMultiplexer {\n\tm := new(NetworkMultiplexer)\n\tm.in = make(chan common.NetworkMessage)\n\tm.out = make(chan idHandler)\n\tm.hosts = make(map[string][]common.NetworkMessageHandler)\n\tm.createdServer = false\n\tgo m.listen()\n\treturn m\n}\n\nfunc (m *NetworkMultiplexer) listen() {\n\tfor {\n\t\tselect {\n\t\tcase c := <-m.out:\n\t\t\tm.hosts[c.SwarmId] = append(m.hosts[c.SwarmId], c.handler)\n\t\tcase o := <-m.in:\n\t\t\tlog.Debugln(\"MULTI: Transaction \", o, \"to be sent to\", len(m.hosts[o.SwarmId]))\n\t\t\tfor _, s := range m.hosts[o.SwarmId] {\n\t\t\t\tgo s.HandleNetworkMessage(o)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (m *NetworkMultiplexer) AddListener(SwarmId string, c common.NetworkMessageHandler) {\n\tm.out <- idHandler{c, SwarmId}\n}\n\nfunc (m *NetworkMultiplexer) SendNetworkMessage(o common.NetworkMessage) {\n\tm.in <- o\n}\n\nfunc (m *NetworkMultiplexer) Listen(addr string) {\n\n\tln, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\tlog.Println(\"MULTI: ERROR COULD NOT CREATE SERVER WITH ADDRESS:\", addr)\n\t\tlog.Fatal(\"MULTI ERROR MESSAGE:\", err)\n\t}\n\n\tlog.Println(\"MULTI: SUCCESSFULLY CREATED ADDRESS: addr\")\n\tlog.Println(\"MULTI: LISTENING FOR CONNECTORS\")\n\n\tfor {\n\t\tconn, err := ln.Accept()\n\t\tif err != nil {\n\t\t\t\/\/ Or it might be conn.LocalAddr().String(), unsure which to use\n\t\t\tlog.Println(\"MULTI: ERROR CONNECTION REFUSED FOR ADDRESS:\", conn.RemoteAddr().String())\n\t\t\tlog.Println(\"MULTI ERROR MESSAGE:\", err)\n\t\t\tcontinue\n\t\t}\n\t\tlog.Println(\"MULTI: CONNECTED TO ADDRESS: \", conn.RemoteAddr().String())\n\t\tlog.Println(\"MULTI: SENDING MESSAGE TO ADDRESS: \", conn.RemoteAddr().String())\n\n\t\tmsg := \"TESTING CONNECTION WITH \" + addr\n\t\ten := json.NewEncoder(conn)\n\t\ten.Encode(msg)\n\n\t\tde := json.NewDecoder(conn)\n\t\tde.Decode(msg)\n\n\t\tlog.Println(\"MULTI: MESSAGE RECEIVED FROM:\", conn.RemoteAddr().String())\n\t\tlog.Println(msg)\n\n\t\tdefer conn.Close()\n\t}\n\n\tdefer ln.Close()\n\n}\n\nfunc (m *NetworkMultiplexer) Connect(addr string) {\n\tconn, err := net.Dial(\"tcp\", addr)\n\n\tif err != nil {\n\t\tlog.Println(\"MULTI: ERROR CANNOT CONNECT TO SPECIFIED ADDRESS\")\n\t\tlog.Fatal(\"MULTI ERROR MESSAGE:\", err)\n\t}\n\n\tlog.Println(\"MULTI: CONNECTED TO ADDRESS:\", addr)\n\n\tvar msg string\n\n\tde := json.NewDecoder(conn)\n\tde.Decode(msg)\n\n\tlog.Println(\"MULTI: MESSAGE RECEIVED FROM:\", addr)\n\tlog.Println(msg)\n\n\tmsg = \"MESSAGE CONFIRMED AS RECEIVED\"\n\n\ten := json.NewEncoder(conn)\n\ten.Encode(msg)\n\n\tdefer conn.Close()\n}\nEdited Mutiplexer.go to Implement New Packagepackage network\n\nimport (\n\t\"common\"\n\t\"common\/log\"\n\t\"encoding\/json\"\n\t\"net\"\n)\n\ntype NetworkMultiplexer struct {\n\tin chan common.NetworkMessage\n\tout chan idHandler\n\thosts map[string][]common.NetworkMessageHandler\n\tcreatedServer bool\n}\n\ntype idHandler struct {\n\thandler common.NetworkMessageHandler\n\tSwarmId string\n}\n\nfunc NewNetworkMultiplexer() common.NetworkMultiplexer {\n\tm := new(NetworkMultiplexer)\n\tm.in = make(chan common.NetworkMessage)\n\tm.out = make(chan idHandler)\n\tm.hosts = make(map[string][]common.NetworkMessageHandler)\n\tm.createdServer = false\n\tgo m.listen()\n\treturn m\n}\n\nfunc (m *NetworkMultiplexer) listen() {\n\tfor {\n\t\tselect {\n\t\tcase c := <-m.out:\n\t\t\tm.hosts[c.SwarmId] = append(m.hosts[c.SwarmId], c.handler)\n\t\tcase o := <-m.in:\n\t\t\tlog.Debugln(\"MULTI: Transaction \", o, \"to be sent to\", len(m.hosts[o.SwarmId]))\n\t\t\tfor _, s := range m.hosts[o.SwarmId] {\n\t\t\t\tgo s.HandleNetworkMessage(o)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (m *NetworkMultiplexer) AddListener(SwarmId string, c common.NetworkMessageHandler) {\n\tm.out <- idHandler{c, SwarmId}\n}\n\nfunc (m *NetworkMultiplexer) SendNetworkMessage(o common.NetworkMessage) {\n\tm.in <- o\n}\n\nfunc (m *NetworkMultiplexer) Listen(addr string) {\n\n\tln, err := net.Listen(\"tcp\", addr)\n\tif err != nil {\n\t\tlog.Debugln(\"MULTI: ERROR COULD NOT CREATE SERVER WITH ADDRESS:\", addr)\n\t\tlog.Fatal(\"MULTI ERROR MESSAGE:\", err)\n\t}\n\n\tlog.Debugln(\"MULTI: SUCCESSFULLY CREATED ADDRESS: addr\")\n\tlog.Debugln(\"MULTI: LISTENING FOR CONNECTORS\")\n\n\tfor {\n\t\tconn, err := ln.Accept()\n\t\tif err != nil {\n\t\t\t\/\/ Or it might be conn.LocalAddr().String(), unsure which to use\n\t\t\tlog.Debugln(\"MULTI: ERROR CONNECTION REFUSED FOR ADDRESS:\", conn.RemoteAddr().String())\n\t\t\tlog.Debugln(\"MULTI ERROR MESSAGE:\", err)\n\t\t\tcontinue\n\t\t}\n\t\tlog.Debugln(\"MULTI: CONNECTED TO ADDRESS: \", conn.RemoteAddr().String())\n\t\tlog.Debugln(\"MULTI: SENDING MESSAGE TO ADDRESS: \", conn.RemoteAddr().String())\n\n\t\tmsg := \"TESTING CONNECTION WITH \" + addr\n\t\ten := json.NewEncoder(conn)\n\t\ten.Encode(msg)\n\n\t\tde := json.NewDecoder(conn)\n\t\tde.Decode(msg)\n\n\t\tlog.Debugln(\"MULTI: MESSAGE RECEIVED FROM:\", conn.RemoteAddr().String())\n\t\tlog.Debugln(msg)\n\n\t\tdefer conn.Close()\n\t}\n\n\tdefer ln.Close()\n\n}\n\nfunc (m *NetworkMultiplexer) Connect(addr string) {\n\tconn, err := net.Dial(\"tcp\", addr)\n\n\tif err != nil {\n\t\tlog.Debugln(\"MULTI: ERROR CANNOT CONNECT TO SPECIFIED ADDRESS\")\n\t\tlog.Fatal(\"MULTI ERROR MESSAGE:\", err)\n\t}\n\n\tlog.Debugln(\"MULTI: CONNECTED TO ADDRESS:\", addr)\n\n\tvar msg string\n\n\tde := json.NewDecoder(conn)\n\tde.Decode(msg)\n\n\tlog.Debugln(\"MULTI: MESSAGE RECEIVED FROM:\", addr)\n\tlog.Debugln(msg)\n\n\tmsg = \"MESSAGE CONFIRMED AS RECEIVED\"\n\n\ten := json.NewEncoder(conn)\n\ten.Encode(msg)\n\n\tdefer conn.Close()\n}\n<|endoftext|>"} {"text":"\/\/ Package client provides a client for the fluctus REST API.\npackage client\n\nimport (\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"net\/http\/cookiejar\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"encoding\/json\"\n\/\/\t\"regexp\"\n\t\"fmt\"\n\t\"bytes\"\n\t\"log\"\n\t\"time\"\n\t\"github.com\/APTrust\/bagman\"\n\/\/\t\"github.com\/APTrust\/bagman\/fluctus\/models\"\n)\n\ntype Client struct {\n\thostUrl string\n\tapiUser string\n\tapiKey string\n\thttpClient *http.Client\n\ttransport *http.Transport\n\tlogger *log.Logger\n\trequestCount int\n}\n\n\/\/ Creates a new fluctus client. Param hostUrl should come from\n\/\/ the config.json file.\nfunc New(hostUrl, apiUser, apiKey string, logger *log.Logger) (*Client, error) {\n\t\/\/ see security warning on nil PublicSuffixList here:\n\t\/\/ http:\/\/gotour.golang.org\/src\/pkg\/net\/http\/cookiejar\/jar.go?s=1011:1492#L24\n\tcookieJar, err := cookiejar.New(nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Can't create cookie jar for HTTP client: %v\", err)\n\t}\n\ttransport := &http.Transport{ MaxIdleConnsPerHost: 12 }\n\thttpClient := &http.Client{ Jar: cookieJar, Transport: transport }\n\treturn &Client{hostUrl, apiUser, apiKey, httpClient, transport, logger, 0}, nil\n}\n\n\n\/\/ BuildUrl combines the host and protocol in client.hostUrl with\n\/\/ relativeUrl to create an absolute URL. For example, if client.hostUrl\n\/\/ is \"http:\/\/localhost:3456\", then client.BuildUrl(\"\/path\/to\/action.json\")\n\/\/ would return \"http:\/\/localhost:3456\/path\/to\/action.json\".\nfunc (client *Client) BuildUrl (relativeUrl string) (absoluteUrl *url.URL) {\n\tabsoluteUrl, err := url.Parse(client.hostUrl + relativeUrl)\n\tif err != nil {\n\t\t\/\/ TODO: Check validity of Fluctus url on app init,\n\t\t\/\/ so we don't have to panic here.\n\t\tpanic(fmt.Sprintf(\"Can't parse URL '%s': %v\", absoluteUrl, err))\n\t}\n\treturn absoluteUrl\n}\n\n\n\/\/ newJsonGet returns a new request with headers indicating\n\/\/ JSON request and response formats.\nfunc (client *Client) NewJsonRequest(method, url string, body io.Reader) (*http.Request, error) {\n\treq, err := http.NewRequest(method, url, body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Add(\"Content-Type\", \"application\/json\")\n\treq.Header.Add(\"Accept\", \"application\/json\")\n\treq.Header.Add(\"X-Fluctus-API-User\", client.apiUser)\n\treq.Header.Add(\"X-Fluctus-API-Key\", client.apiKey)\n\t\/\/req.Close = true \/\/ Leaving connections open causes system to run out of file handles\n\treturn req, nil\n}\n\n\n\/\/ GetBagStatus returns the status of a bag from a prior round of processing.\n\/\/ This function will return nil if Fluctus has no record of this bag.\nfunc (client *Client) GetBagStatus(etag, name string, bag_date time.Time) (status *bagman.ProcessStatus, err error) {\n\t\/\/ TODO: Add bag_date to url\n\turl := client.BuildUrl(fmt.Sprintf(\"\/itemresults\/%s\/%s\/%s\", etag, name, bag_date.Format(time.RFC3339)))\n\treq, err := client.NewJsonRequest(\"GET\", url.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstatus, err = client.doStatusRequest(req, 200)\n\treturn status, err\n}\n\n\/\/ UpdateBagStatus sends a message to Fluctus describing whether bag\n\/\/ processing succeeded or failed. If it failed, the ProcessStatus\n\/\/ object includes some details of what went wrong.\nfunc (client *Client) UpdateBagStatus(status *bagman.ProcessStatus) (err error) {\n\trelativeUrl := \"\/itemresults\"\n\thttpMethod := \"POST\"\n\tif status.Id > 0 {\n\t\trelativeUrl = fmt.Sprintf(\"\/itemresults\/%s\/%s\/%s\",\n\t\t\tstatus.ETag, status.Name, status.BagDate.Format(time.RFC3339))\n\t\thttpMethod = \"PUT\"\n\t}\n\turl := client.BuildUrl(relativeUrl)\n\tpostData, err := status.SerializeForFluctus()\n\tif err != nil {\n\t\treturn err\n\t}\n\treq, err := client.NewJsonRequest(httpMethod, url.String(), bytes.NewBuffer(postData))\n\tif err != nil {\n\t\treturn err\n\t}\n\tstatus, err = client.doStatusRequest(req, 201)\n\tif err != nil {\n\t\tclient.logger.Printf(\"[ERROR] JSON for failed Fluctus request: %s\",\n\t\t\tstring(postData))\n\t}\n\treturn err\n}\n\nfunc (client *Client) doStatusRequest(request *http.Request, expectedStatus int) (status *bagman.ProcessStatus, err error) {\n\t\/\/ Trying to fix problem with too many connections in CLOSE_WAIT state.\n\tclient.requestCount++\n\tif client.requestCount % 100 == 0 {\n\t\tclient.logger.Println(\"[INFO] Fluctus client is forcibly closing idle HTTP connections\")\n\t\tclient.transport.CloseIdleConnections()\n\t}\n\n\tresponse, err := client.httpClient.Do(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ OK to return 404 on a status check. It just means the bag has not\n\t\/\/ been processed before.\n\tif response.StatusCode == 404 && request.Method == \"GET\" {\n\t\treturn nil, nil\n\t}\n\n\tif response.StatusCode != expectedStatus {\n\t\terr = fmt.Errorf(\"Expected status code %d but got %d. URL: %s\",\n\t\t\texpectedStatus, response.StatusCode, request.URL)\n\t\treturn nil, err\n\t}\n\tdefer response.Body.Close()\n\tbody, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Build and return the data structure\n\terr = json.Unmarshal(body, &status)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn status, nil\n}\n\n\/*\nPOST: http:\/\/localhost:3000\/institutions\/changeme:3\/objects.json\n{\n\"title\": \"Sample Postman Object\",\n\"description\": \"This object was posted from Postman.\",\n\"identifier\": \"fe986240-cf11-11e3-9c1a-0800200c9a66\",\n\"rights\": \"consortial\",\n\"authenticity_token\": \"i5tOg3jccd8XQm49SfdMiCb6S9QeZm3GrGVDsCJuGxs=\"\n}\nResponse: {\"title\":[\"Sample Postman Object\"],\"description\":[\"This object was posted from Postman.\"],\"rights\":[\"consortial\"]}\n\nRetrieve object by searching on identifier, like this (html, json):\n\nhttp:\/\/localhost:3000\/institutions\/changeme:3\/objects?utf8=%E2%9C%93&q=fe986240-cf11-11e3-9c1a-0800200c9a66\nhttp:\/\/localhost:3000\/institutions\/changeme:3\/objects.json?utf8=%E2%9C%93&q=fe986240-cf11-11e3-9c1a-0800200c9a66\n\nWould be nice if Rails returned the internal id of the new object. That id is in the Location Header, e.g.:\nhttp:\/\/localhost:3000\/catalog\/changeme:96\n\nResponse code should be 201.\n\nGet events for this object:\n\nGET http:\/\/localhost:3000\/objects\/changeme:95\/events.json\n\nPost a new event:\n\nPOST http:\/\/localhost:3000\/objects\/changeme:96\/events.json\n\n{\n \"type\": \"fixodent-6765\",\n \"date_time\": \"\",\n \"detail\": \"Glued dentures to gums\",\n \"outcome\": \"success\",\n \"outcome_detail\": \"MD5:012345678ABCDEF01234\",\n \"outcome_information\": \"Multipart Put using md5 checksum\",\n \"object\": \"ruby aws-s3 gem\",\n \"agent\": \"https:\/\/github.com\/marcel\/aws-s3\/tree\/master\",\n \"authenticity_token\": \"i5tOg3jccd8XQm49SfdMiCb6S9QeZm3GrGVDsCJuGxs=\"\n}\n\nThis endpoint is returning HTML. Should be returning JSON.\n\n*\/\nUpdated comments\/\/ Package client provides a client for the fluctus REST API.\npackage client\n\nimport (\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"net\/http\/cookiejar\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"encoding\/json\"\n\/\/\t\"regexp\"\n\t\"fmt\"\n\t\"bytes\"\n\t\"log\"\n\t\"time\"\n\t\"github.com\/APTrust\/bagman\"\n\/\/\t\"github.com\/APTrust\/bagman\/fluctus\/models\"\n)\n\ntype Client struct {\n\thostUrl string\n\tapiUser string\n\tapiKey string\n\thttpClient *http.Client\n\ttransport *http.Transport\n\tlogger *log.Logger\n\trequestCount int\n}\n\n\/\/ Creates a new fluctus client. Param hostUrl should come from\n\/\/ the config.json file.\nfunc New(hostUrl, apiUser, apiKey string, logger *log.Logger) (*Client, error) {\n\t\/\/ see security warning on nil PublicSuffixList here:\n\t\/\/ http:\/\/gotour.golang.org\/src\/pkg\/net\/http\/cookiejar\/jar.go?s=1011:1492#L24\n\tcookieJar, err := cookiejar.New(nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Can't create cookie jar for HTTP client: %v\", err)\n\t}\n\ttransport := &http.Transport{ MaxIdleConnsPerHost: 12 }\n\thttpClient := &http.Client{ Jar: cookieJar, Transport: transport }\n\treturn &Client{hostUrl, apiUser, apiKey, httpClient, transport, logger, 0}, nil\n}\n\n\n\/\/ BuildUrl combines the host and protocol in client.hostUrl with\n\/\/ relativeUrl to create an absolute URL. For example, if client.hostUrl\n\/\/ is \"http:\/\/localhost:3456\", then client.BuildUrl(\"\/path\/to\/action.json\")\n\/\/ would return \"http:\/\/localhost:3456\/path\/to\/action.json\".\nfunc (client *Client) BuildUrl (relativeUrl string) (absoluteUrl *url.URL) {\n\tabsoluteUrl, err := url.Parse(client.hostUrl + relativeUrl)\n\tif err != nil {\n\t\t\/\/ TODO: Check validity of Fluctus url on app init,\n\t\t\/\/ so we don't have to panic here.\n\t\tpanic(fmt.Sprintf(\"Can't parse URL '%s': %v\", absoluteUrl, err))\n\t}\n\treturn absoluteUrl\n}\n\n\n\/\/ newJsonGet returns a new request with headers indicating\n\/\/ JSON request and response formats.\nfunc (client *Client) NewJsonRequest(method, url string, body io.Reader) (*http.Request, error) {\n\treq, err := http.NewRequest(method, url, body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Add(\"Content-Type\", \"application\/json\")\n\treq.Header.Add(\"Accept\", \"application\/json\")\n\treq.Header.Add(\"X-Fluctus-API-User\", client.apiUser)\n\treq.Header.Add(\"X-Fluctus-API-Key\", client.apiKey)\n\treturn req, nil\n}\n\n\n\/\/ GetBagStatus returns the status of a bag from a prior round of processing.\n\/\/ This function will return nil if Fluctus has no record of this bag.\nfunc (client *Client) GetBagStatus(etag, name string, bag_date time.Time) (status *bagman.ProcessStatus, err error) {\n\turl := client.BuildUrl(fmt.Sprintf(\"\/itemresults\/%s\/%s\/%s\", etag, name, bag_date.Format(time.RFC3339)))\n\treq, err := client.NewJsonRequest(\"GET\", url.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tstatus, err = client.doStatusRequest(req, 200)\n\treturn status, err\n}\n\n\/\/ UpdateBagStatus sends a message to Fluctus describing whether bag\n\/\/ processing succeeded or failed. If it failed, the ProcessStatus\n\/\/ object includes some details of what went wrong.\nfunc (client *Client) UpdateBagStatus(status *bagman.ProcessStatus) (err error) {\n\trelativeUrl := \"\/itemresults\"\n\thttpMethod := \"POST\"\n\tif status.Id > 0 {\n\t\trelativeUrl = fmt.Sprintf(\"\/itemresults\/%s\/%s\/%s\",\n\t\t\tstatus.ETag, status.Name, status.BagDate.Format(time.RFC3339))\n\t\thttpMethod = \"PUT\"\n\t}\n\turl := client.BuildUrl(relativeUrl)\n\tpostData, err := status.SerializeForFluctus()\n\tif err != nil {\n\t\treturn err\n\t}\n\treq, err := client.NewJsonRequest(httpMethod, url.String(), bytes.NewBuffer(postData))\n\tif err != nil {\n\t\treturn err\n\t}\n\tstatus, err = client.doStatusRequest(req, 201)\n\tif err != nil {\n\t\tclient.logger.Printf(\"[ERROR] JSON for failed Fluctus request: %s\",\n\t\t\tstring(postData))\n\t}\n\treturn err\n}\n\nfunc (client *Client) doStatusRequest(request *http.Request, expectedStatus int) (status *bagman.ProcessStatus, err error) {\n\t\/\/ Trying to fix problem with too many connections in CLOSE_WAIT state.\n\t\/\/ If we don't forcibly close idle connections, they'll pile up\n\t\/\/ and the system fails with \"too many open files\" error.\n\t\/\/ The call to CloseIdleConnections will close some idle connections\n\t\/\/ that are in TIME_WAIT \/ keepalive, but we can pay that price.\n\tclient.requestCount++\n\tif client.requestCount % 100 == 0 {\n\t\tclient.logger.Println(\"[INFO] Fluctus client is forcibly closing idle HTTP connections\")\n\t\tclient.transport.CloseIdleConnections()\n\t}\n\n\tresponse, err := client.httpClient.Do(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ OK to return 404 on a status check. It just means the bag has not\n\t\/\/ been processed before.\n\tif response.StatusCode == 404 && request.Method == \"GET\" {\n\t\treturn nil, nil\n\t}\n\n\tif response.StatusCode != expectedStatus {\n\t\terr = fmt.Errorf(\"Expected status code %d but got %d. URL: %s\",\n\t\t\texpectedStatus, response.StatusCode, request.URL)\n\t\treturn nil, err\n\t}\n\tdefer response.Body.Close()\n\tbody, err := ioutil.ReadAll(response.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Build and return the data structure\n\terr = json.Unmarshal(body, &status)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn status, nil\n}\n\n\/*\nPOST: http:\/\/localhost:3000\/institutions\/changeme:3\/objects.json\n{\n\"title\": \"Sample Postman Object\",\n\"description\": \"This object was posted from Postman.\",\n\"identifier\": \"fe986240-cf11-11e3-9c1a-0800200c9a66\",\n\"rights\": \"consortial\",\n\"authenticity_token\": \"i5tOg3jccd8XQm49SfdMiCb6S9QeZm3GrGVDsCJuGxs=\"\n}\nResponse: {\"title\":[\"Sample Postman Object\"],\"description\":[\"This object was posted from Postman.\"],\"rights\":[\"consortial\"]}\n\nRetrieve object by searching on identifier, like this (html, json):\n\nhttp:\/\/localhost:3000\/institutions\/changeme:3\/objects?utf8=%E2%9C%93&q=fe986240-cf11-11e3-9c1a-0800200c9a66\nhttp:\/\/localhost:3000\/institutions\/changeme:3\/objects.json?utf8=%E2%9C%93&q=fe986240-cf11-11e3-9c1a-0800200c9a66\n\nWould be nice if Rails returned the internal id of the new object. That id is in the Location Header, e.g.:\nhttp:\/\/localhost:3000\/catalog\/changeme:96\n\nResponse code should be 201.\n\nGet events for this object:\n\nGET http:\/\/localhost:3000\/objects\/changeme:95\/events.json\n\nPost a new event:\n\nPOST http:\/\/localhost:3000\/objects\/changeme:96\/events.json\n\n{\n \"type\": \"fixodent-6765\",\n \"date_time\": \"\",\n \"detail\": \"Glued dentures to gums\",\n \"outcome\": \"success\",\n \"outcome_detail\": \"MD5:012345678ABCDEF01234\",\n \"outcome_information\": \"Multipart Put using md5 checksum\",\n \"object\": \"ruby aws-s3 gem\",\n \"agent\": \"https:\/\/github.com\/marcel\/aws-s3\/tree\/master\",\n \"authenticity_token\": \"i5tOg3jccd8XQm49SfdMiCb6S9QeZm3GrGVDsCJuGxs=\"\n}\n\nThis endpoint is returning HTML. Should be returning JSON.\n\n*\/\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"encoding\/json\"\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"os\"\n\t\"testing\"\n\t\"fmt\"\n)\n\nconst (\n\tmetricCount = 4\n)\n\nvar (\n\tfluentdJson = Message{1, 4, 456, 0}\n)\n\ntype Message struct {\n\tup int\n\tbufferQueueLength int\n\tbufferTotalQueuedSize float64\n\tretryCount int\n}\n\nfunc checkFluentdStatus(t *testing.T, status []byte, metricCount int) {\n\thandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Write([]byte(status))\n\t})\n\tserver := httptest.NewServer(handler)\n\n\te := NewExporter(server.URL)\n\tch := make(chan prometheus.Metric)\n\n\tgo func() {\n\t\tdefer close(ch)\n\t\te.Collect(ch)\n\t}()\n\n\tm := <-ch\n\tif m == nil {\n\t\tt.Error(\"expected metric but got nil\")\n\t}\n\n\tif <-ch != nil {\n\t\tt.Error(\"expected closed channel\")\n\t}\n}\n\nfunc TestFluentdStatus(t *testing.T) {\n\t\/\/marshal json data\n\tdata, err := json.Marshal(fluentdJson)\n\tif err != nil {\n\t\tt.Error(err)\n\t\tos.Exit(1)\n\t}\n\n\tcheckFluentdStatus(t, data, metricCount)\n}\nremoved unused importpackage main\n\nimport (\n\t\"encoding\/json\"\n\t\"github.com\/prometheus\/client_golang\/prometheus\"\n\t\"net\/http\"\n\t\"net\/http\/httptest\"\n\t\"os\"\n\t\"testing\"\n)\n\nconst (\n\tmetricCount = 4\n)\n\nvar (\n\tfluentdJson = Message{1, 4, 456, 0}\n)\n\ntype Message struct {\n\tup int\n\tbufferQueueLength int\n\tbufferTotalQueuedSize float64\n\tretryCount int\n}\n\nfunc checkFluentdStatus(t *testing.T, status []byte, metricCount int) {\n\thandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.Write([]byte(status))\n\t})\n\tserver := httptest.NewServer(handler)\n\n\te := NewExporter(server.URL)\n\tch := make(chan prometheus.Metric)\n\n\tgo func() {\n\t\tdefer close(ch)\n\t\te.Collect(ch)\n\t}()\n\n\tm := <-ch\n\tif m == nil {\n\t\tt.Error(\"expected metric but got nil\")\n\t}\n\n\tif <-ch != nil {\n\t\tt.Error(\"expected closed channel\")\n\t}\n}\n\nfunc TestFluentdStatus(t *testing.T) {\n\t\/\/marshal json data\n\tdata, err := json.Marshal(fluentdJson)\n\tif err != nil {\n\t\tt.Error(err)\n\t\tos.Exit(1)\n\t}\n\n\tcheckFluentdStatus(t, data, metricCount)\n}\n<|endoftext|>"} {"text":"package chef\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"testing\"\n)\n\nconst policyListResponseFile = \"test\/policies_response.json\"\nconst policyRevisionResponseFile = \"test\/policy_revision_response.json\"\n\nfunc TestListPolicies(t *testing.T) {\n\tsetup()\n\tdefer teardown()\n\n\tfile, err := ioutil.ReadFile(policyListResponseFile)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tmux.HandleFunc(\"\/policies\", func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprintf(w, string(file))\n\t})\n\n\tdata, err := client.Policies.List()\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif data == nil {\n\t\tt.Fatal(\"We should have some data\")\n\t}\n\n\tif len(data) != 2 {\n\t\tt.Error(\"Mismatch in expected policies count. Expected 2, Got: \", len(data))\n\t}\n\n\tif _, ok := data[\"aar\"]; !ok {\n\t\tt.Error(\"aar policy should be listed\")\n\t}\n\n\tif _, ok := data[\"jenkins\"]; !ok {\n\t\tt.Error(\"jenkins policy should be listed\")\n\t}\n\n}\n\nfunc TestGetPolicy(t *testing.T) {\n\tsetup()\n\tdefer teardown()\n\n\tpolicyGetJSON := `{\n\t\t\t\t\t\t\"revisions\": {\n\t\t \t\t\t\t\t\"8228b0e381fe1de3ee39bf51e93029dbbdcecc61fb5abea4ca8c82591c0b529b\": {\n\t \n\t\t \t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t \t\t\t\t }`\n\tmux.HandleFunc(\"\/policies\/base\", func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprintf(w, policyGetJSON)\n\t})\n\tmux.HandleFunc(\"\/policies\/bad\", func(w http.ResponseWriter, r *http.Request) {\n\t\thttp.Error(w, \"Not Found\", 404)\n\t})\n\n\tdata, err := client.Policies.Get(\"base\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif _, ok := data[\"revisions\"][\"8228b0e381fe1de3ee39bf51e93029dbbdcecc61fb5abea4ca8c82591c0b529b\"]; !ok {\n\t\tt.Error(\"Missing expected revision for this policy\")\n\t}\n\n\t_, err = client.Policies.Get(\"bad\")\n\tif err == nil {\n\t\tt.Error(\"We expected this bad request to error\", err)\n\t}\n}\n\nfunc TestGetPolicyRevision(t *testing.T) {\n\tsetup()\n\tdefer teardown()\n\n\tconst policyName = \"base\"\n\tconst policyRevision = \"8228b0e381fe1de3ee39bf51e93029dbbdcecc61fb5abea4ca8c82591c0b529b\"\n\n\tfile, err := ioutil.ReadFile(policyRevisionResponseFile)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tmux.HandleFunc(fmt.Sprintf(\"\/policies\/%s\/revisions\/%s\", policyName, policyRevision), func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprintf(w, string(file))\n\t})\n\n\tdata, err := client.Policies.GetRevisionDetails(policyName, policyRevision)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif data.Name != policyName {\n\t\tt.Errorf(\"Unexpected policy name: %+v\", data.Name)\n\t}\n\n\tif data.RevisionID != policyRevision {\n\t\tt.Errorf(\"Unexpected policy revision ID: %+v\", data.RevisionID)\n\t}\n\n\tif data.RunList[0] != \"recipe[base::default]\" {\n\t\tt.Errorf(\"Unexpected policy run list: %+v\", data.RevisionID)\n\t}\n\n\tif val, ok := data.NamedRunList[\"os\"]; !ok {\n\t\tt.Error(\"Expected os NamedRunList policy to be present in the policy information\")\n\t} else if val[0] != \"recipe[hardening::default]\" {\n\t\tt.Error(\"Expected named run list for the policy, got: \", val[0])\n\t}\n\n\tif val, ok := data.CookbookLocks[\"hardening\"]; !ok {\n\t\tt.Error(\"Expected hardening policy to be present in the policy information\")\n\t} else if val.Version != \"0.1.0\" {\n\t\tt.Error(\"Expected hardening policy version to be 0.1.0, got: \", val.Version)\n\t}\n\n}\nCover included policy locks test casespackage chef\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"testing\"\n)\n\nconst policyListResponseFile = \"test\/policies_response.json\"\nconst policyRevisionResponseFile = \"test\/policy_revision_response.json\"\n\nfunc TestListPolicies(t *testing.T) {\n\tsetup()\n\tdefer teardown()\n\n\tfile, err := ioutil.ReadFile(policyListResponseFile)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tmux.HandleFunc(\"\/policies\", func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprintf(w, string(file))\n\t})\n\n\tdata, err := client.Policies.List()\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif data == nil {\n\t\tt.Fatal(\"We should have some data\")\n\t}\n\n\tif len(data) != 2 {\n\t\tt.Error(\"Mismatch in expected policies count. Expected 2, Got: \", len(data))\n\t}\n\n\tif _, ok := data[\"aar\"]; !ok {\n\t\tt.Error(\"aar policy should be listed\")\n\t}\n\n\tif _, ok := data[\"jenkins\"]; !ok {\n\t\tt.Error(\"jenkins policy should be listed\")\n\t}\n\n}\n\nfunc TestGetPolicy(t *testing.T) {\n\tsetup()\n\tdefer teardown()\n\n\tpolicyGetJSON := `{\n\t\t\t\t\t\t\"revisions\": {\n\t\t \t\t\t\t\t\"8228b0e381fe1de3ee39bf51e93029dbbdcecc61fb5abea4ca8c82591c0b529b\": {\n\t \n\t\t \t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t \t\t\t\t }`\n\tmux.HandleFunc(\"\/policies\/base\", func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprintf(w, policyGetJSON)\n\t})\n\tmux.HandleFunc(\"\/policies\/bad\", func(w http.ResponseWriter, r *http.Request) {\n\t\thttp.Error(w, \"Not Found\", 404)\n\t})\n\n\tdata, err := client.Policies.Get(\"base\")\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif _, ok := data[\"revisions\"][\"8228b0e381fe1de3ee39bf51e93029dbbdcecc61fb5abea4ca8c82591c0b529b\"]; !ok {\n\t\tt.Error(\"Missing expected revision for this policy\")\n\t}\n\n\t_, err = client.Policies.Get(\"bad\")\n\tif err == nil {\n\t\tt.Error(\"We expected this bad request to error\", err)\n\t}\n}\n\nfunc TestGetPolicyRevision(t *testing.T) {\n\tsetup()\n\tdefer teardown()\n\n\tconst policyName = \"base\"\n\tconst policyRevision = \"8228b0e381fe1de3ee39bf51e93029dbbdcecc61fb5abea4ca8c82591c0b529b\"\n\n\tfile, err := ioutil.ReadFile(policyRevisionResponseFile)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tmux.HandleFunc(fmt.Sprintf(\"\/policies\/%s\/revisions\/%s\", policyName, policyRevision), func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprintf(w, string(file))\n\t})\n\n\tdata, err := client.Policies.GetRevisionDetails(policyName, policyRevision)\n\tif err != nil {\n\t\tt.Error(err)\n\t}\n\n\tif data.Name != policyName {\n\t\tt.Errorf(\"Unexpected policy name: %+v\", data.Name)\n\t}\n\n\tif data.RevisionID != policyRevision {\n\t\tt.Errorf(\"Unexpected policy revision ID: %+v\", data.RevisionID)\n\t}\n\n\tif data.RunList[0] != \"recipe[base::default]\" {\n\t\tt.Errorf(\"Unexpected policy run list: %+v\", data.RevisionID)\n\t}\n\n\tif val, ok := data.NamedRunList[\"os\"]; !ok {\n\t\tt.Error(\"Expected os NamedRunList policy to be present in the policy information\")\n\t} else if val[0] != \"recipe[hardening::default]\" {\n\t\tt.Error(\"Expected named run list for the policy, got: \", val[0])\n\t}\n\n\tif data.IncludedPolicyLocks[0].Name != \"other\" {\n\t\tt.Error(\"Expected included policy name to be present in the policy information\")\n\t} else if data.IncludedPolicyLocks[0].RevisionID != \"7b40995ad1150ec56950c757872d6732aa00e76382dfcd2fddeb3a971e57ba9c\" {\n\t\tt.Error(\"Expected included policy revision ID to be present in the policy information\")\n\t}\n\n\tif val, ok := data.CookbookLocks[\"hardening\"]; !ok {\n\t\tt.Error(\"Expected hardening policy to be present in the policy information\")\n\t} else if val.Version != \"0.1.0\" {\n\t\tt.Error(\"Expected hardening policy version to be 0.1.0, got: \", val.Version)\n\t}\n\n}\n<|endoftext|>"} {"text":"package libvirt\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n\t\"time\"\n\t\"unicode\/utf8\"\n\n\t\"github.com\/mitchellh\/multistep\"\n\t\"github.com\/mitchellh\/packer\/packer\"\n\t\"gopkg.in\/alexzorin\/libvirt-go.v2\"\n)\n\nconst KeyLeftShift uint32 = 0xFFE1\n\ntype bootCommandTemplateData struct {\n\tHTTPIP string\n\tHTTPPort uint\n\tName string\n}\n\n\/\/ This step \"types\" the boot command into the VM over VNC.\n\/\/\n\/\/ Uses:\n\/\/ config *config\n\/\/ http_port int\n\/\/ ui packer.Ui\n\/\/\n\/\/ Produces:\n\/\/ \ntype stepTypeBootCommand struct{}\n\nfunc (s *stepTypeBootCommand) Run(state multistep.StateBag) multistep.StepAction {\n\tconfig := state.Get(\"config\").(*Config)\n\t\/\/\thttpPort := state.Get(\"http_port\").(uint)\n\t\/\/\thostIp := state.Get(\"host_ip\").(string)\n\tui := state.Get(\"ui\").(packer.Ui)\n\n\tvar lvd libvirt.VirDomain\n\tlv, err := libvirt.NewVirConnection(config.LibvirtUrl)\n\tif err != nil {\n\t\terr := fmt.Errorf(\"Error connecting to libvirt: %s\", err)\n\t\tstate.Put(\"error\", err)\n\t\tui.Error(err.Error())\n\t\treturn multistep.ActionHalt\n\t}\n\tdefer lv.CloseConnection()\n\tif lvd, err = lv.LookupDomainByName(config.VMName); err != nil {\n\t\terr := fmt.Errorf(\"Error lookup domain: %s\", err)\n\t\tstate.Put(\"error\", err)\n\t\tui.Error(err.Error())\n\t\treturn multistep.ActionHalt\n\t}\n\tdefer lvd.Free()\n\n\t\/\/\ttplData := &bootCommandTemplateData{\n\t\/\/\t\thostIp,\n\t\/\/\t\thttpPort,\n\t\/\/\t\tconfig.VMName,\n\t\/\/\t}\n\n\tui.Say(\"Typing the boot command...\")\n\tfor _, command := range config.BootCommand {\n\t\t\/\/\t\tcommand, err := config.tpl.Process(command, tplData)\n\t\t\/\/\t\tif err != nil {\n\t\t\/\/\t\t\terr := fmt.Errorf(\"Error preparing boot command: %s\", err)\n\t\t\/\/\t\t\tstate.Put(\"error\", err)\n\t\t\/\/\t\t\tui.Error(err.Error())\n\t\t\/\/\t\t\treturn multistep.ActionHalt\n\t\t\/\/\t\t}\n\n\t\t\/\/ Check for interrupts between typing things so we can cancel\n\t\t\/\/ since this isn't the fastest thing.\n\t\tif _, ok := state.GetOk(multistep.StateCancelled); ok {\n\t\t\treturn multistep.ActionHalt\n\t\t}\n\n\t\tsendBootString(lvd, command)\n\t}\n\n\treturn multistep.ActionContinue\n}\n\nfunc (*stepTypeBootCommand) Cleanup(multistep.StateBag) {}\n\nfunc sendBootString(d libvirt.VirDomain, original string) {\n\tvar err error\n\tvar key uint\n\n\tfor len(original) > 0 {\n\t\tif strings.HasPrefix(original, \"\") {\n\t\t\tlog.Printf(\"Special code '' found, sleeping one second\")\n\t\t\ttime.Sleep(1 * time.Second)\n\t\t\toriginal = original[len(\"\"):]\n\t\t\tcontinue\n\t\t}\n\n\t\tif strings.HasPrefix(original, \"\") {\n\t\t\tlog.Printf(\"Special code '' found, sleeping 5 seconds\")\n\t\t\ttime.Sleep(5 * time.Second)\n\t\t\toriginal = original[len(\"\"):]\n\t\t\tcontinue\n\t\t}\n\n\t\tif strings.HasPrefix(original, \"\") {\n\t\t\tlog.Printf(\"Special code '' found, sleeping 10 seconds\")\n\t\t\ttime.Sleep(10 * time.Second)\n\t\t\toriginal = original[len(\"\"):]\n\t\t\tcontinue\n\t\t}\n\n\t\tif strings.HasPrefix(original, \"\") {\n\t\t\td.SendKey(libvirt.VIR_KEYCODE_SET_RFB, 400, []uint{ecodes[\"\"]}, 0)\n\t\t\toriginal = original[len(\"\"):]\n\t\t\tcontinue\n\t\t}\n\n\t\tif strings.HasPrefix(original, \"\") {\n\t\t\td.SendKey(libvirt.VIR_KEYCODE_SET_RFB, 400, []uint{ecodes[\"\"]}, 0)\n\t\t\toriginal = original[len(\"\"):]\n\t\t\tcontinue\n\t\t}\n\n\t\tlog.Printf(\"command %s\", original)\n\t\tr, size := utf8.DecodeRuneInString(original)\n\t\toriginal = original[size:]\n\t\tkey = ecodes[string(r)]\n\t\tlog.Printf(\"find code for char %s %d\", string(r), key)\n\t\t\/\/VIR_KEYCODE_SET_LINUX, VIR_KEYCODE_SET_USB, VIR_KEYCODE_SET_RFB, VIR_KEYCODE_SET_WIN32, VIR_KEYCODE_SET_XT_KBD\n\t\tif err = d.SendKey(libvirt.VIR_KEYCODE_SET_RFB, 400, []uint{key}, 0); err != nil {\n\t\t\tlog.Printf(\"Sending code %d failed: %s\", key, err.Error())\n\t\t}\n\t}\n\n}\nfixpackage libvirt\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n\t\"time\"\n\t\"unicode\/utf8\"\n\n\t\"github.com\/mitchellh\/multistep\"\n\t\"github.com\/mitchellh\/packer\/packer\"\n\t\"gopkg.in\/alexzorin\/libvirt-go.v2\"\n)\n\nconst KeyLeftShift uint32 = 0xFFE1\n\ntype bootCommandTemplateData struct {\n\tHTTPIP string\n\tHTTPPort uint\n\tName string\n}\n\n\/\/ This step \"types\" the boot command into the VM over VNC.\n\/\/\n\/\/ Uses:\n\/\/ config *config\n\/\/ http_port int\n\/\/ ui packer.Ui\n\/\/\n\/\/ Produces:\n\/\/ \ntype stepTypeBootCommand struct{}\n\nfunc (s *stepTypeBootCommand) Run(state multistep.StateBag) multistep.StepAction {\n\tconfig := state.Get(\"config\").(*Config)\n\t\/\/\thttpPort := state.Get(\"http_port\").(uint)\n\t\/\/\thostIp := state.Get(\"host_ip\").(string)\n\tui := state.Get(\"ui\").(packer.Ui)\n\n\tvar lvd libvirt.VirDomain\n\tlv, err := libvirt.NewVirConnection(config.LibvirtUrl)\n\tif err != nil {\n\t\terr := fmt.Errorf(\"Error connecting to libvirt: %s\", err)\n\t\tstate.Put(\"error\", err)\n\t\tui.Error(err.Error())\n\t\treturn multistep.ActionHalt\n\t}\n\tdefer lv.CloseConnection()\n\tif lvd, err = lv.LookupDomainByName(config.VMName); err != nil {\n\t\terr := fmt.Errorf(\"Error lookup domain: %s\", err)\n\t\tstate.Put(\"error\", err)\n\t\tui.Error(err.Error())\n\t\treturn multistep.ActionHalt\n\t}\n\tdefer lvd.Free()\n\n\t\/\/\ttplData := &bootCommandTemplateData{\n\t\/\/\t\thostIp,\n\t\/\/\t\thttpPort,\n\t\/\/\t\tconfig.VMName,\n\t\/\/\t}\n\n\tui.Say(\"Typing the boot command...\")\n\tfor _, command := range config.BootCommand {\n\t\t\/\/\t\tcommand, err := config.tpl.Process(command, tplData)\n\t\t\/\/\t\tif err != nil {\n\t\t\/\/\t\t\terr := fmt.Errorf(\"Error preparing boot command: %s\", err)\n\t\t\/\/\t\t\tstate.Put(\"error\", err)\n\t\t\/\/\t\t\tui.Error(err.Error())\n\t\t\/\/\t\t\treturn multistep.ActionHalt\n\t\t\/\/\t\t}\n\n\t\t\/\/ Check for interrupts between typing things so we can cancel\n\t\t\/\/ since this isn't the fastest thing.\n\t\tif _, ok := state.GetOk(multistep.StateCancelled); ok {\n\t\t\treturn multistep.ActionHalt\n\t\t}\n\n\t\tsendBootString(lvd, command)\n\t}\n\n\treturn multistep.ActionContinue\n}\n\nfunc (*stepTypeBootCommand) Cleanup(multistep.StateBag) {}\n\nfunc sendBootString(d libvirt.VirDomain, original string) {\n\tvar err error\n\tvar key uint\n\n\tfor len(original) > 0 {\n\t\tif strings.HasPrefix(original, \"\") {\n\t\t\tlog.Printf(\"Special code '' found, sleeping one second\")\n\t\t\ttime.Sleep(1 * time.Second)\n\t\t\toriginal = original[len(\"\"):]\n\t\t\tcontinue\n\t\t}\n\n\t\tif strings.HasPrefix(original, \"\") {\n\t\t\tlog.Printf(\"Special code '' found, sleeping 5 seconds\")\n\t\t\ttime.Sleep(5 * time.Second)\n\t\t\toriginal = original[len(\"\"):]\n\t\t\tcontinue\n\t\t}\n\n\t\tif strings.HasPrefix(original, \"\") {\n\t\t\tlog.Printf(\"Special code '' found, sleeping 10 seconds\")\n\t\t\ttime.Sleep(10 * time.Second)\n\t\t\toriginal = original[len(\"\"):]\n\t\t\tcontinue\n\t\t}\n\n\t\tif strings.HasPrefix(original, \"\") {\n\t\t\td.SendKey(libvirt.VIR_KEYCODE_SET_RFB, 300, []uint{ecodes[\"\"]}, 0)\n\t\t\toriginal = original[len(\"\"):]\n\t\t\tcontinue\n\t\t}\n\n\t\tif strings.HasPrefix(original, \"\") {\n\t\t\td.SendKey(libvirt.VIR_KEYCODE_SET_RFB, 300, []uint{ecodes[\"\"]}, 0)\n\t\t\toriginal = original[len(\"\"):]\n\t\t\tcontinue\n\t\t}\n\n\t\tlog.Printf(\"command %s\", original)\n\t\tr, size := utf8.DecodeRuneInString(original)\n\t\toriginal = original[size:]\n\t\tkey = ecodes[string(r)]\n\t\tlog.Printf(\"find code for char %s %d\", string(r), key)\n\t\t\/\/VIR_KEYCODE_SET_LINUX, VIR_KEYCODE_SET_USB, VIR_KEYCODE_SET_RFB, VIR_KEYCODE_SET_WIN32, VIR_KEYCODE_SET_XT_KBD\n\t\tif err = d.SendKey(libvirt.VIR_KEYCODE_SET_RFB, 300, []uint{key}, 0); err != nil {\n\t\t\tlog.Printf(\"Sending code %d failed: %s\", key, err.Error())\n\t\t}\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}\n\n}\n<|endoftext|>"} {"text":"\/\/ Package log provides logging for rclone\npackage log\n\nimport (\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"reflect\"\n\t\"runtime\"\n\t\"strings\"\n\n\t\"github.com\/rclone\/rclone\/fs\"\n\t\"github.com\/rclone\/rclone\/fs\/config\/flags\"\n)\n\n\/\/ Flags\nvar (\n\tlogFile = flags.StringP(\"log-file\", \"\", \"\", \"Log everything to this file\")\n\tlogFormat = flags.StringP(\"log-format\", \"\", \"date,time\", \"Comma separated list of log format options\")\n\tuseSyslog = flags.BoolP(\"syslog\", \"\", false, \"Use Syslog for logging\")\n\tsyslogFacility = flags.StringP(\"syslog-facility\", \"\", \"DAEMON\", \"Facility for syslog, eg KERN,USER,...\")\n)\n\n\/\/ fnName returns the name of the calling +2 function\nfunc fnName() string {\n\tpc, _, _, ok := runtime.Caller(2)\n\tname := \"*Unknown*\"\n\tif ok {\n\t\tname = runtime.FuncForPC(pc).Name()\n\t\tdot := strings.LastIndex(name, \".\")\n\t\tif dot >= 0 {\n\t\t\tname = name[dot+1:]\n\t\t}\n\t}\n\treturn name\n}\n\n\/\/ Trace debugs the entry and exit of the calling function\n\/\/\n\/\/ It is designed to be used in a defer statement so it returns a\n\/\/ function that logs the exit parameters.\n\/\/\n\/\/ Any pointers in the exit function will be dereferenced\nfunc Trace(o interface{}, format string, a ...interface{}) func(string, ...interface{}) {\n\tif fs.Config.LogLevel < fs.LogLevelDebug {\n\t\treturn func(format string, a ...interface{}) {}\n\t}\n\tname := fnName()\n\tfs.LogPrintf(fs.LogLevelDebug, o, name+\": \"+format, a...)\n\treturn func(format string, a ...interface{}) {\n\t\tfor i := range a {\n\t\t\t\/\/ read the values of the pointed to items\n\t\t\ttyp := reflect.TypeOf(a[i])\n\t\t\tif typ.Kind() == reflect.Ptr {\n\t\t\t\tvalue := reflect.ValueOf(a[i])\n\t\t\t\tif value.IsNil() {\n\t\t\t\t\ta[i] = nil\n\t\t\t\t} else {\n\t\t\t\t\tpointedToValue := reflect.Indirect(value)\n\t\t\t\t\ta[i] = pointedToValue.Interface()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfs.LogPrintf(fs.LogLevelDebug, o, \">\"+name+\": \"+format, a...)\n\t}\n}\n\n\/\/ InitLogging start the logging as per the command line flags\nfunc InitLogging() {\n\tflagsStr := \",\" + *logFormat + \",\"\n\tvar flags int\n\tif strings.Contains(flagsStr, \",date,\") {\n\t\tflags |= log.Ldate\n\t}\n\tif strings.Contains(flagsStr, \",time,\") {\n\t\tflags |= log.Ltime\n\t}\n\tif strings.Contains(flagsStr, \",microseconds,\") {\n\t\tflags |= log.Lmicroseconds\n\t}\n\tif strings.Contains(flagsStr, \",longfile,\") {\n\t\tflags |= log.Llongfile\n\t}\n\tif strings.Contains(flagsStr, \",shortfile,\") {\n\t\tflags |= log.Lshortfile\n\t}\n\tif strings.Contains(flagsStr, \",UTC,\") {\n\t\tflags |= log.LUTC\n\t}\n\tlog.SetFlags(flags)\n\n\t\/\/ Log file output\n\tif *logFile != \"\" {\n\t\tf, err := os.OpenFile(*logFile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0640)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Failed to open log file: %v\", err)\n\t\t}\n\t\t_, err = f.Seek(0, io.SeekEnd)\n\t\tif err != nil {\n\t\t\tfs.Errorf(nil, \"Failed to seek log file to end: %v\", err)\n\t\t}\n\t\tlog.SetOutput(f)\n\t\tredirectStderr(f)\n\t}\n\n\t\/\/ Syslog output\n\tif *useSyslog {\n\t\tif *logFile != \"\" {\n\t\t\tlog.Fatalf(\"Can't use --syslog and --log-file together\")\n\t\t}\n\t\tstartSysLog()\n\t}\n}\n\n\/\/ Redirected returns true if the log has been redirected from stdout\nfunc Redirected() bool {\n\treturn *useSyslog || *logFile != \"\"\n}\nlog: add Stack() function for debugging who calls what\/\/ Package log provides logging for rclone\npackage log\n\nimport (\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"reflect\"\n\t\"runtime\"\n\t\"strings\"\n\n\t\"github.com\/rclone\/rclone\/fs\"\n\t\"github.com\/rclone\/rclone\/fs\/config\/flags\"\n)\n\n\/\/ Flags\nvar (\n\tlogFile = flags.StringP(\"log-file\", \"\", \"\", \"Log everything to this file\")\n\tlogFormat = flags.StringP(\"log-format\", \"\", \"date,time\", \"Comma separated list of log format options\")\n\tuseSyslog = flags.BoolP(\"syslog\", \"\", false, \"Use Syslog for logging\")\n\tsyslogFacility = flags.StringP(\"syslog-facility\", \"\", \"DAEMON\", \"Facility for syslog, eg KERN,USER,...\")\n)\n\n\/\/ fnName returns the name of the calling +2 function\nfunc fnName() string {\n\tpc, _, _, ok := runtime.Caller(2)\n\tname := \"*Unknown*\"\n\tif ok {\n\t\tname = runtime.FuncForPC(pc).Name()\n\t\tdot := strings.LastIndex(name, \".\")\n\t\tif dot >= 0 {\n\t\t\tname = name[dot+1:]\n\t\t}\n\t}\n\treturn name\n}\n\n\/\/ Trace debugs the entry and exit of the calling function\n\/\/\n\/\/ It is designed to be used in a defer statement so it returns a\n\/\/ function that logs the exit parameters.\n\/\/\n\/\/ Any pointers in the exit function will be dereferenced\nfunc Trace(o interface{}, format string, a ...interface{}) func(string, ...interface{}) {\n\tif fs.Config.LogLevel < fs.LogLevelDebug {\n\t\treturn func(format string, a ...interface{}) {}\n\t}\n\tname := fnName()\n\tfs.LogPrintf(fs.LogLevelDebug, o, name+\": \"+format, a...)\n\treturn func(format string, a ...interface{}) {\n\t\tfor i := range a {\n\t\t\t\/\/ read the values of the pointed to items\n\t\t\ttyp := reflect.TypeOf(a[i])\n\t\t\tif typ.Kind() == reflect.Ptr {\n\t\t\t\tvalue := reflect.ValueOf(a[i])\n\t\t\t\tif value.IsNil() {\n\t\t\t\t\ta[i] = nil\n\t\t\t\t} else {\n\t\t\t\t\tpointedToValue := reflect.Indirect(value)\n\t\t\t\t\ta[i] = pointedToValue.Interface()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfs.LogPrintf(fs.LogLevelDebug, o, \">\"+name+\": \"+format, a...)\n\t}\n}\n\n\/\/ Stack logs a stack trace of callers with the o and info passed in\nfunc Stack(o interface{}, info string) {\n\tif fs.Config.LogLevel < fs.LogLevelDebug {\n\t\treturn\n\t}\n\tarr := [16 * 1024]byte{}\n\tbuf := arr[:]\n\tn := runtime.Stack(buf, false)\n\tbuf = buf[:n]\n\tfs.LogPrintf(fs.LogLevelDebug, o, \"%s\\nStack trace:\\n%s\", info, buf)\n}\n\n\/\/ InitLogging start the logging as per the command line flags\nfunc InitLogging() {\n\tflagsStr := \",\" + *logFormat + \",\"\n\tvar flags int\n\tif strings.Contains(flagsStr, \",date,\") {\n\t\tflags |= log.Ldate\n\t}\n\tif strings.Contains(flagsStr, \",time,\") {\n\t\tflags |= log.Ltime\n\t}\n\tif strings.Contains(flagsStr, \",microseconds,\") {\n\t\tflags |= log.Lmicroseconds\n\t}\n\tif strings.Contains(flagsStr, \",longfile,\") {\n\t\tflags |= log.Llongfile\n\t}\n\tif strings.Contains(flagsStr, \",shortfile,\") {\n\t\tflags |= log.Lshortfile\n\t}\n\tif strings.Contains(flagsStr, \",UTC,\") {\n\t\tflags |= log.LUTC\n\t}\n\tlog.SetFlags(flags)\n\n\t\/\/ Log file output\n\tif *logFile != \"\" {\n\t\tf, err := os.OpenFile(*logFile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0640)\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Failed to open log file: %v\", err)\n\t\t}\n\t\t_, err = f.Seek(0, io.SeekEnd)\n\t\tif err != nil {\n\t\t\tfs.Errorf(nil, \"Failed to seek log file to end: %v\", err)\n\t\t}\n\t\tlog.SetOutput(f)\n\t\tredirectStderr(f)\n\t}\n\n\t\/\/ Syslog output\n\tif *useSyslog {\n\t\tif *logFile != \"\" {\n\t\t\tlog.Fatalf(\"Can't use --syslog and --log-file together\")\n\t\t}\n\t\tstartSysLog()\n\t}\n}\n\n\/\/ Redirected returns true if the log has been redirected from stdout\nfunc Redirected() bool {\n\treturn *useSyslog || *logFile != \"\"\n}\n<|endoftext|>"} {"text":"package storage\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/docker\/distribution\"\n\t\"github.com\/docker\/distribution\/context\"\n\t\"github.com\/docker\/distribution\/digest\"\n\t\"github.com\/docker\/distribution\/manifest\/schema1\"\n\t\"github.com\/docker\/distribution\/reference\"\n\t\"github.com\/docker\/libtrust\"\n)\n\ntype manifestStore struct {\n\trepository *repository\n\trevisionStore *revisionStore\n\ttagStore *tagStore\n\tctx context.Context\n\tskipDependencyVerification bool\n}\n\nvar _ distribution.ManifestService = &manifestStore{}\n\nfunc (ms *manifestStore) Exists(dgst digest.Digest) (bool, error) {\n\tcontext.GetLogger(ms.ctx).Debug(\"(*manifestStore).Exists\")\n\n\t_, err := ms.revisionStore.blobStore.Stat(ms.ctx, dgst)\n\tif err != nil {\n\t\tif err == distribution.ErrBlobUnknown {\n\t\t\treturn false, nil\n\t\t}\n\n\t\treturn false, err\n\t}\n\n\treturn true, nil\n}\n\nfunc (ms *manifestStore) Get(dgst digest.Digest) (*schema1.SignedManifest, error) {\n\tcontext.GetLogger(ms.ctx).Debug(\"(*manifestStore).Get\")\n\treturn ms.revisionStore.get(ms.ctx, dgst)\n}\n\n\/\/ SkipLayerVerification allows a manifest to be Put before it's\n\/\/ layers are on the filesystem\nfunc SkipLayerVerification(ms distribution.ManifestService) error {\n\tif ms, ok := ms.(*manifestStore); ok {\n\t\tms.skipDependencyVerification = true\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"skip layer verification only valid for manifestStore\")\n}\n\nfunc (ms *manifestStore) Put(manifest *schema1.SignedManifest) error {\n\tcontext.GetLogger(ms.ctx).Debug(\"(*manifestStore).Put\")\n\n\tif err := ms.verifyManifest(ms.ctx, manifest); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Store the revision of the manifest\n\trevision, err := ms.revisionStore.put(ms.ctx, manifest)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Now, tag the manifest\n\treturn ms.tagStore.tag(manifest.Tag, revision.Digest)\n}\n\n\/\/ Delete removes the revision of the specified manfiest.\nfunc (ms *manifestStore) Delete(dgst digest.Digest) error {\n\tcontext.GetLogger(ms.ctx).Debug(\"(*manifestStore).Delete\")\n\treturn ms.revisionStore.delete(ms.ctx, dgst)\n}\n\nfunc (ms *manifestStore) Tags() ([]string, error) {\n\tcontext.GetLogger(ms.ctx).Debug(\"(*manifestStore).Tags\")\n\treturn ms.tagStore.tags()\n}\n\nfunc (ms *manifestStore) ExistsByTag(tag string) (bool, error) {\n\tcontext.GetLogger(ms.ctx).Debug(\"(*manifestStore).ExistsByTag\")\n\treturn ms.tagStore.exists(tag)\n}\n\nfunc (ms *manifestStore) GetByTag(tag string, options ...distribution.ManifestServiceOption) (*schema1.SignedManifest, error) {\n\tfor _, option := range options {\n\t\terr := option(ms)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tcontext.GetLogger(ms.ctx).Debug(\"(*manifestStore).GetByTag\")\n\tdgst, err := ms.tagStore.resolve(tag)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ms.revisionStore.get(ms.ctx, dgst)\n}\n\n\/\/ verifyManifest ensures that the manifest content is valid from the\n\/\/ perspective of the registry. It ensures that the signature is valid for the\n\/\/ enclosed payload. As a policy, the registry only tries to store valid\n\/\/ content, leaving trust policies of that content up to consumers.\nfunc (ms *manifestStore) verifyManifest(ctx context.Context, mnfst *schema1.SignedManifest) error {\n\tvar errs distribution.ErrManifestVerification\n\n\tif len(mnfst.Name) > reference.NameTotalLengthMax {\n\t\terrs = append(errs, fmt.Errorf(\"manifest name must not be more than %v characters\", reference.NameTotalLengthMax))\n\t}\n\n\tif !reference.NameRegexp.MatchString(mnfst.Name) {\n\t\terrs = append(errs, fmt.Errorf(\"invalid manifest name format\"))\n\t}\n\n\tif len(mnfst.History) != len(mnfst.FSLayers) {\n\t\terrs = append(errs, fmt.Errorf(\"mismatched history and fslayer cardinality %d != %d\",\n\t\t\tlen(mnfst.History), len(mnfst.FSLayers)))\n\t}\n\n\tif _, err := schema1.Verify(mnfst); err != nil {\n\t\tswitch err {\n\t\tcase libtrust.ErrMissingSignatureKey, libtrust.ErrInvalidJSONContent, libtrust.ErrMissingSignatureKey:\n\t\t\terrs = append(errs, distribution.ErrManifestUnverified{})\n\t\tdefault:\n\t\t\tif err.Error() == \"invalid signature\" { \/\/ TODO(stevvooe): This should be exported by libtrust\n\t\t\t\terrs = append(errs, distribution.ErrManifestUnverified{})\n\t\t\t} else {\n\t\t\t\terrs = append(errs, err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif !ms.skipDependencyVerification {\n\t\tfor _, fsLayer := range mnfst.FSLayers {\n\t\t\t_, err := ms.repository.Blobs(ctx).Stat(ctx, fsLayer.BlobSum)\n\t\t\tif err != nil {\n\t\t\t\tif err != distribution.ErrBlobUnknown {\n\t\t\t\t\terrs = append(errs, err)\n\t\t\t\t}\n\n\t\t\t\t\/\/ On error here, we always append unknown blob errors.\n\t\t\t\terrs = append(errs, distribution.ErrManifestBlobUnknown{Digest: fsLayer.BlobSum})\n\t\t\t}\n\t\t}\n\t}\n\tif len(errs) != 0 {\n\t\treturn errs\n\t}\n\n\treturn nil\n}\nUse well-known error typepackage storage\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/docker\/distribution\"\n\t\"github.com\/docker\/distribution\/context\"\n\t\"github.com\/docker\/distribution\/digest\"\n\t\"github.com\/docker\/distribution\/manifest\/schema1\"\n\t\"github.com\/docker\/distribution\/reference\"\n\t\"github.com\/docker\/libtrust\"\n)\n\ntype manifestStore struct {\n\trepository *repository\n\trevisionStore *revisionStore\n\ttagStore *tagStore\n\tctx context.Context\n\tskipDependencyVerification bool\n}\n\nvar _ distribution.ManifestService = &manifestStore{}\n\nfunc (ms *manifestStore) Exists(dgst digest.Digest) (bool, error) {\n\tcontext.GetLogger(ms.ctx).Debug(\"(*manifestStore).Exists\")\n\n\t_, err := ms.revisionStore.blobStore.Stat(ms.ctx, dgst)\n\tif err != nil {\n\t\tif err == distribution.ErrBlobUnknown {\n\t\t\treturn false, nil\n\t\t}\n\n\t\treturn false, err\n\t}\n\n\treturn true, nil\n}\n\nfunc (ms *manifestStore) Get(dgst digest.Digest) (*schema1.SignedManifest, error) {\n\tcontext.GetLogger(ms.ctx).Debug(\"(*manifestStore).Get\")\n\treturn ms.revisionStore.get(ms.ctx, dgst)\n}\n\n\/\/ SkipLayerVerification allows a manifest to be Put before it's\n\/\/ layers are on the filesystem\nfunc SkipLayerVerification(ms distribution.ManifestService) error {\n\tif ms, ok := ms.(*manifestStore); ok {\n\t\tms.skipDependencyVerification = true\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"skip layer verification only valid for manifestStore\")\n}\n\nfunc (ms *manifestStore) Put(manifest *schema1.SignedManifest) error {\n\tcontext.GetLogger(ms.ctx).Debug(\"(*manifestStore).Put\")\n\n\tif err := ms.verifyManifest(ms.ctx, manifest); err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Store the revision of the manifest\n\trevision, err := ms.revisionStore.put(ms.ctx, manifest)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ Now, tag the manifest\n\treturn ms.tagStore.tag(manifest.Tag, revision.Digest)\n}\n\n\/\/ Delete removes the revision of the specified manfiest.\nfunc (ms *manifestStore) Delete(dgst digest.Digest) error {\n\tcontext.GetLogger(ms.ctx).Debug(\"(*manifestStore).Delete\")\n\treturn ms.revisionStore.delete(ms.ctx, dgst)\n}\n\nfunc (ms *manifestStore) Tags() ([]string, error) {\n\tcontext.GetLogger(ms.ctx).Debug(\"(*manifestStore).Tags\")\n\treturn ms.tagStore.tags()\n}\n\nfunc (ms *manifestStore) ExistsByTag(tag string) (bool, error) {\n\tcontext.GetLogger(ms.ctx).Debug(\"(*manifestStore).ExistsByTag\")\n\treturn ms.tagStore.exists(tag)\n}\n\nfunc (ms *manifestStore) GetByTag(tag string, options ...distribution.ManifestServiceOption) (*schema1.SignedManifest, error) {\n\tfor _, option := range options {\n\t\terr := option(ms)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tcontext.GetLogger(ms.ctx).Debug(\"(*manifestStore).GetByTag\")\n\tdgst, err := ms.tagStore.resolve(tag)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ms.revisionStore.get(ms.ctx, dgst)\n}\n\n\/\/ verifyManifest ensures that the manifest content is valid from the\n\/\/ perspective of the registry. It ensures that the signature is valid for the\n\/\/ enclosed payload. As a policy, the registry only tries to store valid\n\/\/ content, leaving trust policies of that content up to consumers.\nfunc (ms *manifestStore) verifyManifest(ctx context.Context, mnfst *schema1.SignedManifest) error {\n\tvar errs distribution.ErrManifestVerification\n\n\tif len(mnfst.Name) > reference.NameTotalLengthMax {\n\t\terrs = append(errs,\n\t\t\tdistribution.ErrManifestNameInvalid{\n\t\t\t\tName: mnfst.Name,\n\t\t\t\tReason: fmt.Errorf(\"manifest name must not be more than %v characters\", reference.NameTotalLengthMax),\n\t\t\t})\n\t}\n\n\tif !reference.NameRegexp.MatchString(mnfst.Name) {\n\t\terrs = append(errs,\n\t\t\tdistribution.ErrManifestNameInvalid{\n\t\t\t\tName: mnfst.Name,\n\t\t\t\tReason: fmt.Errorf(\"invalid manifest name format\"),\n\t\t\t})\n\t}\n\n\tif len(mnfst.History) != len(mnfst.FSLayers) {\n\t\terrs = append(errs, fmt.Errorf(\"mismatched history and fslayer cardinality %d != %d\",\n\t\t\tlen(mnfst.History), len(mnfst.FSLayers)))\n\t}\n\n\tif _, err := schema1.Verify(mnfst); err != nil {\n\t\tswitch err {\n\t\tcase libtrust.ErrMissingSignatureKey, libtrust.ErrInvalidJSONContent, libtrust.ErrMissingSignatureKey:\n\t\t\terrs = append(errs, distribution.ErrManifestUnverified{})\n\t\tdefault:\n\t\t\tif err.Error() == \"invalid signature\" { \/\/ TODO(stevvooe): This should be exported by libtrust\n\t\t\t\terrs = append(errs, distribution.ErrManifestUnverified{})\n\t\t\t} else {\n\t\t\t\terrs = append(errs, err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif !ms.skipDependencyVerification {\n\t\tfor _, fsLayer := range mnfst.FSLayers {\n\t\t\t_, err := ms.repository.Blobs(ctx).Stat(ctx, fsLayer.BlobSum)\n\t\t\tif err != nil {\n\t\t\t\tif err != distribution.ErrBlobUnknown {\n\t\t\t\t\terrs = append(errs, err)\n\t\t\t\t}\n\n\t\t\t\t\/\/ On error here, we always append unknown blob errors.\n\t\t\t\terrs = append(errs, distribution.ErrManifestBlobUnknown{Digest: fsLayer.BlobSum})\n\t\t\t}\n\t\t}\n\t}\n\tif len(errs) != 0 {\n\t\treturn errs\n\t}\n\n\treturn nil\n}\n<|endoftext|>"} {"text":"package fsm\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\n\t\"time\"\n\n\t\"github.com\/awslabs\/aws-sdk-go\/aws\"\n\t\"github.com\/awslabs\/aws-sdk-go\/gen\/swf\"\n\t\"github.com\/juju\/errors\"\n\t. \"github.com\/sclasen\/swfsm\/sugar\"\n)\n\ntype FSMClient interface {\n\tListOpenIds() ([]string, string, error)\n\tListNextOpenIds(previousPageToken string) ([]string, string, error)\n\tListClosedIds() ([]string, string, error)\n\tListNextClosedIds(previousPageToken string) ([]string, string, error)\n\tGetState(id string) (string, interface{}, error)\n\tSignal(id string, signal string, input interface{}) error\n\tStart(startTemplate swf.StartWorkflowExecutionInput, id string, input interface{}) (*swf.Run, error)\n}\n\ntype ClientSWFOps interface {\n\tListOpenWorkflowExecutions(req *swf.ListOpenWorkflowExecutionsInput) (resp *swf.WorkflowExecutionInfos, err error)\n\tListClosedWorkflowExecutions(req *swf.ListClosedWorkflowExecutionsInput) (resp *swf.WorkflowExecutionInfos, err error)\n\tGetWorkflowExecutionHistory(req *swf.GetWorkflowExecutionHistoryInput) (resp *swf.History, err error)\n\tSignalWorkflowExecution(req *swf.SignalWorkflowExecutionInput) (err error)\n\tStartWorkflowExecution(req *swf.StartWorkflowExecutionInput) (resp *swf.Run, err error)\n\tTerminateWorkflowExecution(req *swf.TerminateWorkflowExecutionInput) (err error)\n\tRequestCancelWorkflowExecution(req *swf.RequestCancelWorkflowExecutionInput) (err error)\n}\n\nfunc NewFSMClient(f *FSM, c ClientSWFOps) FSMClient {\n\treturn &client{\n\t\tf: f,\n\t\tc: c,\n\t}\n}\n\ntype client struct {\n\tf *FSM\n\tc ClientSWFOps\n}\n\nfunc (c *client) ListOpenIds() ([]string, string, error) {\n\treturn c.listIds(func() (*swf.WorkflowExecutionInfos, error) {\n\t\treturn c.c.ListOpenWorkflowExecutions(&swf.ListOpenWorkflowExecutionsInput{\n\t\t\tDomain: S(c.f.Domain),\n\t\t\tStartTimeFilter: &swf.ExecutionTimeFilter{OldestDate: &aws.UnixTimestamp{time.Unix(0, 0)}},\n\t\t\tTypeFilter: &swf.WorkflowTypeFilter{Name: S(c.f.Name)},\n\t\t})\n\t})\n}\n\nfunc (c *client) ListNextOpenIds(previousPageToken string) ([]string, string, error) {\n\treturn c.listIds(func() (*swf.WorkflowExecutionInfos, error) {\n\t\treturn c.c.ListOpenWorkflowExecutions(&swf.ListOpenWorkflowExecutionsInput{\n\t\t\tDomain: S(c.f.Domain),\n\t\t\tStartTimeFilter: &swf.ExecutionTimeFilter{OldestDate: &aws.UnixTimestamp{time.Unix(0, 0)}},\n\t\t\tTypeFilter: &swf.WorkflowTypeFilter{Name: S(c.f.Name)},\n\t\t\tNextPageToken: S(previousPageToken),\n\t\t})\n\t})\n}\n\nfunc (c *client) ListClosedIds() ([]string, string, error) {\n\treturn c.listIds(func() (*swf.WorkflowExecutionInfos, error) {\n\t\treturn c.c.ListClosedWorkflowExecutions(&swf.ListClosedWorkflowExecutionsInput{\n\t\t\tDomain: S(c.f.Domain),\n\t\t\tStartTimeFilter: &swf.ExecutionTimeFilter{OldestDate: &aws.UnixTimestamp{time.Unix(0, 0)}},\n\t\t\tTypeFilter: &swf.WorkflowTypeFilter{Name: S(c.f.Name)},\n\t\t})\n\t})\n}\n\nfunc (c *client) ListNextClosedIds(previousPageToken string) ([]string, string, error) {\n\treturn c.listIds(func() (*swf.WorkflowExecutionInfos, error) {\n\t\treturn c.c.ListClosedWorkflowExecutions(&swf.ListClosedWorkflowExecutionsInput{\n\t\t\tDomain: S(c.f.Domain),\n\t\t\tStartTimeFilter: &swf.ExecutionTimeFilter{OldestDate: &aws.UnixTimestamp{time.Unix(0, 0)}},\n\t\t\tTypeFilter: &swf.WorkflowTypeFilter{Name: S(c.f.Name)},\n\t\t\tNextPageToken: S(previousPageToken),\n\t\t})\n\t})\n}\n\nfunc (c *client) listIds(executionInfosFunc func() (*swf.WorkflowExecutionInfos, error)) ([]string, string, error) {\n\texecutionInfos, err := executionInfosFunc()\n\n\tif err != nil {\n\t\tif ae, ok := err.(aws.APIError); ok {\n\t\t\tlog.Printf(\"component=client fn=listIds at=list-infos-func error-type=%s message=%s\", ae.Type, ae.Message)\n\t\t} else {\n\t\t\tlog.Printf(\"component=client fn=listIds at=list-infos-func error=%s\", err)\n\t\t}\n\t\treturn []string{}, \"\", err\n\t}\n\n\tvar ids []string\n\tfor _, info := range executionInfos.ExecutionInfos {\n\t\tids = append(ids, *info.Execution.WorkflowID)\n\t}\n\n\tnextPageToken := \"\"\n\tif executionInfos.NextPageToken != nil {\n\t\tnextPageToken = *executionInfos.NextPageToken\n\t}\n\n\treturn ids, nextPageToken, nil\n}\n\nfunc (c *client) GetState(id string) (string, interface{}, error) {\n\tvar execution *swf.WorkflowExecution\n\topen, err := c.c.ListOpenWorkflowExecutions(&swf.ListOpenWorkflowExecutionsInput{\n\t\tDomain: S(c.f.Domain),\n\t\tMaximumPageSize: aws.Integer(1),\n\t\tStartTimeFilter: &swf.ExecutionTimeFilter{OldestDate: &aws.UnixTimestamp{time.Unix(0, 0)}},\n\t\tExecutionFilter: &swf.WorkflowExecutionFilter{\n\t\t\tWorkflowID: S(id),\n\t\t},\n\t})\n\n\tif err != nil {\n\t\tif ae, ok := err.(aws.APIError); ok {\n\t\t\tlog.Printf(\"component=client fn=GetState at=list-open error-type=%s message=%s\", ae.Type, ae.Message)\n\t\t} else {\n\t\t\tlog.Printf(\"component=client fn=GetState at=list-open error=%s\", err)\n\t\t}\n\t\treturn \"\", nil, err\n\t}\n\n\tif len(open.ExecutionInfos) == 1 {\n\t\texecution = open.ExecutionInfos[0].Execution\n\t} else {\n\t\tclosed, err := c.c.ListClosedWorkflowExecutions(&swf.ListClosedWorkflowExecutionsInput{\n\t\t\tDomain: S(c.f.Domain),\n\t\t\tMaximumPageSize: aws.Integer(1),\n\t\t\tStartTimeFilter: &swf.ExecutionTimeFilter{OldestDate: &aws.UnixTimestamp{time.Unix(0, 0)}},\n\t\t\tExecutionFilter: &swf.WorkflowExecutionFilter{\n\t\t\t\tWorkflowID: S(id),\n\t\t\t},\n\t\t})\n\n\t\tif err != nil {\n\t\t\tif ae, ok := err.(aws.APIError); ok {\n\t\t\t\tlog.Printf(\"component=client fn=GetState at=list-closed error-type=%s message=%s\", ae.Type, ae.Message)\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"component=client fn=GetState at=list-closed error=%s\", err)\n\t\t\t}\n\t\t\treturn \"\", nil, err\n\t\t}\n\n\t\tif len(closed.ExecutionInfos) > 0 {\n\t\t\texecution = closed.ExecutionInfos[0].Execution\n\t\t} else {\n\t\t\treturn \"\", nil, errors.Trace(fmt.Errorf(\"workflow not found for id %s\", id))\n\t\t}\n\t}\n\n\thistory, err := c.c.GetWorkflowExecutionHistory(&swf.GetWorkflowExecutionHistoryInput{\n\t\tDomain: S(c.f.Domain),\n\t\tExecution: execution,\n\t\tReverseOrder: aws.True(),\n\t})\n\n\tif err != nil {\n\t\tif ae, ok := err.(aws.APIError); ok {\n\t\t\tlog.Printf(\"component=client fn=GetState at=get-history error-type=%s message=%s\", ae.Type, ae.Message)\n\t\t} else {\n\t\t\tlog.Printf(\"component=client fn=GetState at=get-history error=%s\", err)\n\t\t}\n\t\treturn \"\", nil, err\n\t}\n\n\tserialized, err := c.f.findSerializedState(history.Events)\n\n\tif err != nil {\n\t\tlog.Printf(\"component=client fn=GetState at=find-serialized-state error=%s\", err)\n\t\treturn \"\", nil, err\n\t}\n\n\tdata := c.f.zeroStateData()\n\terr = c.f.Serializer.Deserialize(serialized.StateData, data)\n\tif err != nil {\n\t\tlog.Printf(\"component=client fn=GetState at=deserialize-serialized-state error=%s\", err)\n\t\treturn \"\", nil, err\n\t}\n\n\treturn serialized.StateName, data, nil\n\n}\n\nfunc (c *client) Signal(id string, signal string, input interface{}) error {\n\tvar serializedInput aws.StringValue\n\tif input != nil {\n\t\tswitch it := input.(type) {\n\t\tcase string:\n\t\t\tserializedInput = S(it)\n\t\tdefault:\n\t\t\tser, err := c.f.Serializer.Serialize(input)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Trace(err)\n\t\t\t}\n\t\t\tserializedInput = S(ser)\n\t\t}\n\t}\n\treturn c.c.SignalWorkflowExecution(&swf.SignalWorkflowExecutionInput{\n\t\tDomain: S(c.f.Domain),\n\t\tSignalName: S(signal),\n\t\tInput: serializedInput,\n\t\tWorkflowID: S(id),\n\t})\n}\n\nfunc (c *client) Start(startTemplate swf.StartWorkflowExecutionInput, id string, input interface{}) (*swf.Run, error) {\n\tvar serializedInput aws.StringValue\n\tif input != nil {\n\t\tser, err := c.f.Serializer.Serialize(input)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\tserializedInput = S(ser)\n\t}\n\tstartTemplate.Domain = S(c.f.Domain)\n\tstartTemplate.WorkflowID = S(id)\n\tstartTemplate.Input = serializedInput\n\treturn c.c.StartWorkflowExecution(&startTemplate)\n}\nFix empty ids to return empty slice instead of nilpackage fsm\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\n\t\"time\"\n\n\t\"github.com\/awslabs\/aws-sdk-go\/aws\"\n\t\"github.com\/awslabs\/aws-sdk-go\/gen\/swf\"\n\t\"github.com\/juju\/errors\"\n\t. \"github.com\/sclasen\/swfsm\/sugar\"\n)\n\ntype FSMClient interface {\n\tListOpenIds() ([]string, string, error)\n\tListNextOpenIds(previousPageToken string) ([]string, string, error)\n\tListClosedIds() ([]string, string, error)\n\tListNextClosedIds(previousPageToken string) ([]string, string, error)\n\tGetState(id string) (string, interface{}, error)\n\tSignal(id string, signal string, input interface{}) error\n\tStart(startTemplate swf.StartWorkflowExecutionInput, id string, input interface{}) (*swf.Run, error)\n}\n\ntype ClientSWFOps interface {\n\tListOpenWorkflowExecutions(req *swf.ListOpenWorkflowExecutionsInput) (resp *swf.WorkflowExecutionInfos, err error)\n\tListClosedWorkflowExecutions(req *swf.ListClosedWorkflowExecutionsInput) (resp *swf.WorkflowExecutionInfos, err error)\n\tGetWorkflowExecutionHistory(req *swf.GetWorkflowExecutionHistoryInput) (resp *swf.History, err error)\n\tSignalWorkflowExecution(req *swf.SignalWorkflowExecutionInput) (err error)\n\tStartWorkflowExecution(req *swf.StartWorkflowExecutionInput) (resp *swf.Run, err error)\n\tTerminateWorkflowExecution(req *swf.TerminateWorkflowExecutionInput) (err error)\n\tRequestCancelWorkflowExecution(req *swf.RequestCancelWorkflowExecutionInput) (err error)\n}\n\nfunc NewFSMClient(f *FSM, c ClientSWFOps) FSMClient {\n\treturn &client{\n\t\tf: f,\n\t\tc: c,\n\t}\n}\n\ntype client struct {\n\tf *FSM\n\tc ClientSWFOps\n}\n\nfunc (c *client) ListOpenIds() ([]string, string, error) {\n\treturn c.listIds(func() (*swf.WorkflowExecutionInfos, error) {\n\t\treturn c.c.ListOpenWorkflowExecutions(&swf.ListOpenWorkflowExecutionsInput{\n\t\t\tDomain: S(c.f.Domain),\n\t\t\tStartTimeFilter: &swf.ExecutionTimeFilter{OldestDate: &aws.UnixTimestamp{time.Unix(0, 0)}},\n\t\t\tTypeFilter: &swf.WorkflowTypeFilter{Name: S(c.f.Name)},\n\t\t})\n\t})\n}\n\nfunc (c *client) ListNextOpenIds(previousPageToken string) ([]string, string, error) {\n\treturn c.listIds(func() (*swf.WorkflowExecutionInfos, error) {\n\t\treturn c.c.ListOpenWorkflowExecutions(&swf.ListOpenWorkflowExecutionsInput{\n\t\t\tDomain: S(c.f.Domain),\n\t\t\tStartTimeFilter: &swf.ExecutionTimeFilter{OldestDate: &aws.UnixTimestamp{time.Unix(0, 0)}},\n\t\t\tTypeFilter: &swf.WorkflowTypeFilter{Name: S(c.f.Name)},\n\t\t\tNextPageToken: S(previousPageToken),\n\t\t})\n\t})\n}\n\nfunc (c *client) ListClosedIds() ([]string, string, error) {\n\treturn c.listIds(func() (*swf.WorkflowExecutionInfos, error) {\n\t\treturn c.c.ListClosedWorkflowExecutions(&swf.ListClosedWorkflowExecutionsInput{\n\t\t\tDomain: S(c.f.Domain),\n\t\t\tStartTimeFilter: &swf.ExecutionTimeFilter{OldestDate: &aws.UnixTimestamp{time.Unix(0, 0)}},\n\t\t\tTypeFilter: &swf.WorkflowTypeFilter{Name: S(c.f.Name)},\n\t\t})\n\t})\n}\n\nfunc (c *client) ListNextClosedIds(previousPageToken string) ([]string, string, error) {\n\treturn c.listIds(func() (*swf.WorkflowExecutionInfos, error) {\n\t\treturn c.c.ListClosedWorkflowExecutions(&swf.ListClosedWorkflowExecutionsInput{\n\t\t\tDomain: S(c.f.Domain),\n\t\t\tStartTimeFilter: &swf.ExecutionTimeFilter{OldestDate: &aws.UnixTimestamp{time.Unix(0, 0)}},\n\t\t\tTypeFilter: &swf.WorkflowTypeFilter{Name: S(c.f.Name)},\n\t\t\tNextPageToken: S(previousPageToken),\n\t\t})\n\t})\n}\n\nfunc (c *client) listIds(executionInfosFunc func() (*swf.WorkflowExecutionInfos, error)) ([]string, string, error) {\n\texecutionInfos, err := executionInfosFunc()\n\n\tif err != nil {\n\t\tif ae, ok := err.(aws.APIError); ok {\n\t\t\tlog.Printf(\"component=client fn=listIds at=list-infos-func error-type=%s message=%s\", ae.Type, ae.Message)\n\t\t} else {\n\t\t\tlog.Printf(\"component=client fn=listIds at=list-infos-func error=%s\", err)\n\t\t}\n\t\treturn []string{}, \"\", err\n\t}\n\n\tids := []string{}\n\tfor _, info := range executionInfos.ExecutionInfos {\n\t\tids = append(ids, *info.Execution.WorkflowID)\n\t}\n\n\tnextPageToken := \"\"\n\tif executionInfos.NextPageToken != nil {\n\t\tnextPageToken = *executionInfos.NextPageToken\n\t}\n\n\treturn ids, nextPageToken, nil\n}\n\nfunc (c *client) GetState(id string) (string, interface{}, error) {\n\tvar execution *swf.WorkflowExecution\n\topen, err := c.c.ListOpenWorkflowExecutions(&swf.ListOpenWorkflowExecutionsInput{\n\t\tDomain: S(c.f.Domain),\n\t\tMaximumPageSize: aws.Integer(1),\n\t\tStartTimeFilter: &swf.ExecutionTimeFilter{OldestDate: &aws.UnixTimestamp{time.Unix(0, 0)}},\n\t\tExecutionFilter: &swf.WorkflowExecutionFilter{\n\t\t\tWorkflowID: S(id),\n\t\t},\n\t})\n\n\tif err != nil {\n\t\tif ae, ok := err.(aws.APIError); ok {\n\t\t\tlog.Printf(\"component=client fn=GetState at=list-open error-type=%s message=%s\", ae.Type, ae.Message)\n\t\t} else {\n\t\t\tlog.Printf(\"component=client fn=GetState at=list-open error=%s\", err)\n\t\t}\n\t\treturn \"\", nil, err\n\t}\n\n\tif len(open.ExecutionInfos) == 1 {\n\t\texecution = open.ExecutionInfos[0].Execution\n\t} else {\n\t\tclosed, err := c.c.ListClosedWorkflowExecutions(&swf.ListClosedWorkflowExecutionsInput{\n\t\t\tDomain: S(c.f.Domain),\n\t\t\tMaximumPageSize: aws.Integer(1),\n\t\t\tStartTimeFilter: &swf.ExecutionTimeFilter{OldestDate: &aws.UnixTimestamp{time.Unix(0, 0)}},\n\t\t\tExecutionFilter: &swf.WorkflowExecutionFilter{\n\t\t\t\tWorkflowID: S(id),\n\t\t\t},\n\t\t})\n\n\t\tif err != nil {\n\t\t\tif ae, ok := err.(aws.APIError); ok {\n\t\t\t\tlog.Printf(\"component=client fn=GetState at=list-closed error-type=%s message=%s\", ae.Type, ae.Message)\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"component=client fn=GetState at=list-closed error=%s\", err)\n\t\t\t}\n\t\t\treturn \"\", nil, err\n\t\t}\n\n\t\tif len(closed.ExecutionInfos) > 0 {\n\t\t\texecution = closed.ExecutionInfos[0].Execution\n\t\t} else {\n\t\t\treturn \"\", nil, errors.Trace(fmt.Errorf(\"workflow not found for id %s\", id))\n\t\t}\n\t}\n\n\thistory, err := c.c.GetWorkflowExecutionHistory(&swf.GetWorkflowExecutionHistoryInput{\n\t\tDomain: S(c.f.Domain),\n\t\tExecution: execution,\n\t\tReverseOrder: aws.True(),\n\t})\n\n\tif err != nil {\n\t\tif ae, ok := err.(aws.APIError); ok {\n\t\t\tlog.Printf(\"component=client fn=GetState at=get-history error-type=%s message=%s\", ae.Type, ae.Message)\n\t\t} else {\n\t\t\tlog.Printf(\"component=client fn=GetState at=get-history error=%s\", err)\n\t\t}\n\t\treturn \"\", nil, err\n\t}\n\n\tserialized, err := c.f.findSerializedState(history.Events)\n\n\tif err != nil {\n\t\tlog.Printf(\"component=client fn=GetState at=find-serialized-state error=%s\", err)\n\t\treturn \"\", nil, err\n\t}\n\n\tdata := c.f.zeroStateData()\n\terr = c.f.Serializer.Deserialize(serialized.StateData, data)\n\tif err != nil {\n\t\tlog.Printf(\"component=client fn=GetState at=deserialize-serialized-state error=%s\", err)\n\t\treturn \"\", nil, err\n\t}\n\n\treturn serialized.StateName, data, nil\n\n}\n\nfunc (c *client) Signal(id string, signal string, input interface{}) error {\n\tvar serializedInput aws.StringValue\n\tif input != nil {\n\t\tswitch it := input.(type) {\n\t\tcase string:\n\t\t\tserializedInput = S(it)\n\t\tdefault:\n\t\t\tser, err := c.f.Serializer.Serialize(input)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Trace(err)\n\t\t\t}\n\t\t\tserializedInput = S(ser)\n\t\t}\n\t}\n\treturn c.c.SignalWorkflowExecution(&swf.SignalWorkflowExecutionInput{\n\t\tDomain: S(c.f.Domain),\n\t\tSignalName: S(signal),\n\t\tInput: serializedInput,\n\t\tWorkflowID: S(id),\n\t})\n}\n\nfunc (c *client) Start(startTemplate swf.StartWorkflowExecutionInput, id string, input interface{}) (*swf.Run, error) {\n\tvar serializedInput aws.StringValue\n\tif input != nil {\n\t\tser, err := c.f.Serializer.Serialize(input)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\tserializedInput = S(ser)\n\t}\n\tstartTemplate.Domain = S(c.f.Domain)\n\tstartTemplate.WorkflowID = S(id)\n\tstartTemplate.Input = serializedInput\n\treturn c.c.StartWorkflowExecution(&startTemplate)\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2016 PingCAP, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage executor\n\nimport (\n\t\"sort\"\n\n\t\"github.com\/juju\/errors\"\n\t\"github.com\/pingcap\/tidb\/expression\"\n\t\"github.com\/pingcap\/tidb\/model\"\n\t\"github.com\/pingcap\/tidb\/sessionctx\"\n\t\"github.com\/pingcap\/tidb\/types\"\n\t\"github.com\/pingcap\/tidb\/util\/chunk\"\n\t\"golang.org\/x\/net\/context\"\n)\n\n\/\/ DirtyDB stores uncommitted write operations for a transaction.\n\/\/ It is stored and retrieved by context.Value and context.SetValue method.\ntype DirtyDB struct {\n\t\/\/ tables is a map whose key is tableID.\n\ttables map[int64]*DirtyTable\n}\n\n\/\/ AddRow adds a row to the DirtyDB.\nfunc (udb *DirtyDB) AddRow(tid, handle int64, row []types.Datum) {\n\tdt := udb.GetDirtyTable(tid)\n\tfor i := range row {\n\t\tif row[i].Kind() == types.KindString {\n\t\t\trow[i].SetBytes(row[i].GetBytes())\n\t\t}\n\t}\n\tdt.addedRows[handle] = row\n}\n\n\/\/ DeleteRow deletes a row from the DirtyDB.\nfunc (udb *DirtyDB) DeleteRow(tid int64, handle int64) {\n\tdt := udb.GetDirtyTable(tid)\n\tdelete(dt.addedRows, handle)\n\tdt.deletedRows[handle] = struct{}{}\n}\n\n\/\/ TruncateTable truncates a table.\nfunc (udb *DirtyDB) TruncateTable(tid int64) {\n\tdt := udb.GetDirtyTable(tid)\n\tdt.addedRows = make(map[int64]Row)\n\tdt.truncated = true\n}\n\n\/\/ GetDirtyTable gets the DirtyTable by id from the DirtyDB.\nfunc (udb *DirtyDB) GetDirtyTable(tid int64) *DirtyTable {\n\tdt, ok := udb.tables[tid]\n\tif !ok {\n\t\tdt = &DirtyTable{\n\t\t\taddedRows: make(map[int64]Row),\n\t\t\tdeletedRows: make(map[int64]struct{}),\n\t\t}\n\t\tudb.tables[tid] = dt\n\t}\n\treturn dt\n}\n\n\/\/ DirtyTable stores uncommitted write operation for a transaction.\ntype DirtyTable struct {\n\t\/\/ addedRows ...\n\t\/\/ the key is handle.\n\taddedRows map[int64]Row\n\tdeletedRows map[int64]struct{}\n\ttruncated bool\n}\n\n\/\/ GetDirtyDB returns the DirtyDB bind to the context.\nfunc GetDirtyDB(ctx sessionctx.Context) *DirtyDB {\n\tvar udb *DirtyDB\n\tx := ctx.GetSessionVars().TxnCtx.DirtyDB\n\tif x == nil {\n\t\tudb = &DirtyDB{tables: make(map[int64]*DirtyTable)}\n\t\tctx.GetSessionVars().TxnCtx.DirtyDB = udb\n\t} else {\n\t\tudb = x.(*DirtyDB)\n\t}\n\treturn udb\n}\n\n\/\/ UnionScanExec merges the rows from dirty table and the rows from XAPI request.\ntype UnionScanExec struct {\n\tbaseExecutor\n\n\tdirty *DirtyTable\n\t\/\/ usedIndex is the column offsets of the index which Src executor has used.\n\tusedIndex []int\n\tdesc bool\n\tconditions []expression.Expression\n\tcolumns []*model.ColumnInfo\n\n\t\/\/ belowHandleIndex is the handle's position of the below scan plan.\n\tbelowHandleIndex int\n\n\taddedRows []Row\n\tcursor int\n\tsortErr error\n\tsnapshotRow Row\n}\n\n\/\/ Next implements Execution Next interface.\nfunc (us *UnionScanExec) Next(ctx context.Context) (Row, error) {\n\trow, err := us.getOneRow(ctx)\n\treturn row, errors.Trace(err)\n}\n\n\/\/ NextChunk implements the Executor NextChunk interface.\nfunc (us *UnionScanExec) NextChunk(ctx context.Context, chk *chunk.Chunk) error {\n\tchk.Reset()\n\tmutableRow := chunk.MutRowFromTypes(us.retTypes())\n\tfor i, batchSize := 0, us.ctx.GetSessionVars().MaxChunkSize; i < batchSize; i++ {\n\t\trow, err := us.getOneRow(ctx)\n\t\tif err != nil {\n\t\t\treturn errors.Trace(err)\n\t\t}\n\t\t\/\/ no more data.\n\t\tif row == nil {\n\t\t\treturn nil\n\t\t}\n\t\tmutableRow.SetDatums(row...)\n\t\tchk.AppendRow(mutableRow.ToRow())\n\t}\n\treturn nil\n}\n\n\/\/ getOneRow gets one result row from dirty table or child.\nfunc (us *UnionScanExec) getOneRow(ctx context.Context) (Row, error) {\n\tfor {\n\t\tsnapshotRow, err := us.getSnapshotRow(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\taddedRow := us.getAddedRow()\n\t\tvar row Row\n\t\tvar isSnapshotRow bool\n\t\tif addedRow == nil {\n\t\t\trow = snapshotRow\n\t\t\tisSnapshotRow = true\n\t\t} else if snapshotRow == nil {\n\t\t\trow = addedRow\n\t\t} else {\n\t\t\tisSnapshotRow, err = us.shouldPickFirstRow(snapshotRow, addedRow)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Trace(err)\n\t\t\t}\n\t\t\tif isSnapshotRow {\n\t\t\t\trow = snapshotRow\n\t\t\t} else {\n\t\t\t\trow = addedRow\n\t\t\t}\n\t\t}\n\t\tif row == nil {\n\t\t\treturn nil, nil\n\t\t}\n\n\t\tif isSnapshotRow {\n\t\t\tus.snapshotRow = nil\n\t\t} else {\n\t\t\tus.cursor++\n\t\t}\n\t\treturn row, nil\n\t}\n}\n\nfunc (us *UnionScanExec) getSnapshotRow(ctx context.Context) (Row, error) {\n\tif us.dirty.truncated {\n\t\treturn nil, nil\n\t}\n\tvar err error\n\tif us.snapshotRow == nil {\n\t\tfor {\n\t\t\tus.snapshotRow, err = us.children[0].Next(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Trace(err)\n\t\t\t}\n\t\t\tif us.snapshotRow == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tsnapshotHandle := us.snapshotRow[us.belowHandleIndex].GetInt64()\n\t\t\tif _, ok := us.dirty.deletedRows[snapshotHandle]; ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif _, ok := us.dirty.addedRows[snapshotHandle]; ok {\n\t\t\t\t\/\/ If src handle appears in added rows, it means there is conflict and the transaction will fail to\n\t\t\t\t\/\/ commit, but for simplicity, we don't handle it here.\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\treturn us.snapshotRow, nil\n}\n\nfunc (us *UnionScanExec) getAddedRow() Row {\n\tvar addedRow Row\n\tif us.cursor < len(us.addedRows) {\n\t\taddedRow = us.addedRows[us.cursor]\n\t}\n\treturn addedRow\n}\n\n\/\/ shouldPickFirstRow picks the suitable row in order.\n\/\/ The value returned is used to determine whether to pick the first input row.\nfunc (us *UnionScanExec) shouldPickFirstRow(a, b Row) (bool, error) {\n\tvar isFirstRow bool\n\taddedCmpSrc, err := us.compare(a, b)\n\tif err != nil {\n\t\treturn isFirstRow, errors.Trace(err)\n\t}\n\t\/\/ Compare result will never be 0.\n\tif us.desc {\n\t\tif addedCmpSrc > 0 {\n\t\t\tisFirstRow = true\n\t\t}\n\t} else {\n\t\tif addedCmpSrc < 0 {\n\t\t\tisFirstRow = true\n\t\t}\n\t}\n\treturn isFirstRow, nil\n}\n\nfunc (us *UnionScanExec) compare(a, b Row) (int, error) {\n\tsc := us.ctx.GetSessionVars().StmtCtx\n\tfor _, colOff := range us.usedIndex {\n\t\taColumn := a[colOff]\n\t\tbColumn := b[colOff]\n\t\tcmp, err := aColumn.CompareDatum(sc, &bColumn)\n\t\tif err != nil {\n\t\t\treturn 0, errors.Trace(err)\n\t\t}\n\t\tif cmp != 0 {\n\t\t\treturn cmp, nil\n\t\t}\n\t}\n\taHandle := a[us.belowHandleIndex].GetInt64()\n\tbHandle := b[us.belowHandleIndex].GetInt64()\n\tvar cmp int\n\tif aHandle == bHandle {\n\t\tcmp = 0\n\t} else if aHandle > bHandle {\n\t\tcmp = 1\n\t} else {\n\t\tcmp = -1\n\t}\n\treturn cmp, nil\n}\n\nfunc (us *UnionScanExec) buildAndSortAddedRows() error {\n\tus.addedRows = make([]Row, 0, len(us.dirty.addedRows))\n\tfor h, data := range us.dirty.addedRows {\n\t\tnewData := make(types.DatumRow, 0, us.schema.Len())\n\t\tfor _, col := range us.columns {\n\t\t\tif col.ID == model.ExtraHandleID {\n\t\t\t\tnewData = append(newData, types.NewIntDatum(h))\n\t\t\t} else {\n\t\t\t\tnewData = append(newData, data[col.Offset])\n\t\t\t}\n\t\t}\n\t\tmatched, err := expression.EvalBool(us.ctx, us.conditions, newData)\n\t\tif err != nil {\n\t\t\treturn errors.Trace(err)\n\t\t}\n\t\tif !matched {\n\t\t\tcontinue\n\t\t}\n\t\tus.addedRows = append(us.addedRows, newData)\n\t}\n\tif us.desc {\n\t\tsort.Sort(sort.Reverse(us))\n\t} else {\n\t\tsort.Sort(us)\n\t}\n\tif us.sortErr != nil {\n\t\treturn errors.Trace(us.sortErr)\n\t}\n\treturn nil\n}\n\n\/\/ Len implements sort.Interface interface.\nfunc (us *UnionScanExec) Len() int {\n\treturn len(us.addedRows)\n}\n\n\/\/ Less implements sort.Interface interface.\nfunc (us *UnionScanExec) Less(i, j int) bool {\n\tcmp, err := us.compare(us.addedRows[i], us.addedRows[j])\n\tif err != nil {\n\t\tus.sortErr = errors.Trace(err)\n\t\treturn true\n\t}\n\treturn cmp < 0\n}\n\n\/\/ Swap implements sort.Interface interface.\nfunc (us *UnionScanExec) Swap(i, j int) {\n\tus.addedRows[i], us.addedRows[j] = us.addedRows[j], us.addedRows[i]\n}\nexecutor: remove Next function for UnionScanExec (#5996)\/\/ Copyright 2016 PingCAP, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage executor\n\nimport (\n\t\"sort\"\n\n\t\"github.com\/juju\/errors\"\n\t\"github.com\/pingcap\/tidb\/expression\"\n\t\"github.com\/pingcap\/tidb\/model\"\n\t\"github.com\/pingcap\/tidb\/sessionctx\"\n\t\"github.com\/pingcap\/tidb\/types\"\n\t\"github.com\/pingcap\/tidb\/util\/chunk\"\n\t\"golang.org\/x\/net\/context\"\n)\n\n\/\/ DirtyDB stores uncommitted write operations for a transaction.\n\/\/ It is stored and retrieved by context.Value and context.SetValue method.\ntype DirtyDB struct {\n\t\/\/ tables is a map whose key is tableID.\n\ttables map[int64]*DirtyTable\n}\n\n\/\/ AddRow adds a row to the DirtyDB.\nfunc (udb *DirtyDB) AddRow(tid, handle int64, row []types.Datum) {\n\tdt := udb.GetDirtyTable(tid)\n\tfor i := range row {\n\t\tif row[i].Kind() == types.KindString {\n\t\t\trow[i].SetBytes(row[i].GetBytes())\n\t\t}\n\t}\n\tdt.addedRows[handle] = row\n}\n\n\/\/ DeleteRow deletes a row from the DirtyDB.\nfunc (udb *DirtyDB) DeleteRow(tid int64, handle int64) {\n\tdt := udb.GetDirtyTable(tid)\n\tdelete(dt.addedRows, handle)\n\tdt.deletedRows[handle] = struct{}{}\n}\n\n\/\/ TruncateTable truncates a table.\nfunc (udb *DirtyDB) TruncateTable(tid int64) {\n\tdt := udb.GetDirtyTable(tid)\n\tdt.addedRows = make(map[int64]Row)\n\tdt.truncated = true\n}\n\n\/\/ GetDirtyTable gets the DirtyTable by id from the DirtyDB.\nfunc (udb *DirtyDB) GetDirtyTable(tid int64) *DirtyTable {\n\tdt, ok := udb.tables[tid]\n\tif !ok {\n\t\tdt = &DirtyTable{\n\t\t\taddedRows: make(map[int64]Row),\n\t\t\tdeletedRows: make(map[int64]struct{}),\n\t\t}\n\t\tudb.tables[tid] = dt\n\t}\n\treturn dt\n}\n\n\/\/ DirtyTable stores uncommitted write operation for a transaction.\ntype DirtyTable struct {\n\t\/\/ addedRows ...\n\t\/\/ the key is handle.\n\taddedRows map[int64]Row\n\tdeletedRows map[int64]struct{}\n\ttruncated bool\n}\n\n\/\/ GetDirtyDB returns the DirtyDB bind to the context.\nfunc GetDirtyDB(ctx sessionctx.Context) *DirtyDB {\n\tvar udb *DirtyDB\n\tx := ctx.GetSessionVars().TxnCtx.DirtyDB\n\tif x == nil {\n\t\tudb = &DirtyDB{tables: make(map[int64]*DirtyTable)}\n\t\tctx.GetSessionVars().TxnCtx.DirtyDB = udb\n\t} else {\n\t\tudb = x.(*DirtyDB)\n\t}\n\treturn udb\n}\n\n\/\/ UnionScanExec merges the rows from dirty table and the rows from XAPI request.\ntype UnionScanExec struct {\n\tbaseExecutor\n\n\tdirty *DirtyTable\n\t\/\/ usedIndex is the column offsets of the index which Src executor has used.\n\tusedIndex []int\n\tdesc bool\n\tconditions []expression.Expression\n\tcolumns []*model.ColumnInfo\n\n\t\/\/ belowHandleIndex is the handle's position of the below scan plan.\n\tbelowHandleIndex int\n\n\taddedRows []Row\n\tcursor int\n\tsortErr error\n\tsnapshotRow Row\n}\n\n\/\/ NextChunk implements the Executor NextChunk interface.\nfunc (us *UnionScanExec) NextChunk(ctx context.Context, chk *chunk.Chunk) error {\n\tchk.Reset()\n\tmutableRow := chunk.MutRowFromTypes(us.retTypes())\n\tfor i, batchSize := 0, us.ctx.GetSessionVars().MaxChunkSize; i < batchSize; i++ {\n\t\trow, err := us.getOneRow(ctx)\n\t\tif err != nil {\n\t\t\treturn errors.Trace(err)\n\t\t}\n\t\t\/\/ no more data.\n\t\tif row == nil {\n\t\t\treturn nil\n\t\t}\n\t\tmutableRow.SetDatums(row...)\n\t\tchk.AppendRow(mutableRow.ToRow())\n\t}\n\treturn nil\n}\n\n\/\/ getOneRow gets one result row from dirty table or child.\nfunc (us *UnionScanExec) getOneRow(ctx context.Context) (Row, error) {\n\tfor {\n\t\tsnapshotRow, err := us.getSnapshotRow(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\taddedRow := us.getAddedRow()\n\t\tvar row Row\n\t\tvar isSnapshotRow bool\n\t\tif addedRow == nil {\n\t\t\trow = snapshotRow\n\t\t\tisSnapshotRow = true\n\t\t} else if snapshotRow == nil {\n\t\t\trow = addedRow\n\t\t} else {\n\t\t\tisSnapshotRow, err = us.shouldPickFirstRow(snapshotRow, addedRow)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Trace(err)\n\t\t\t}\n\t\t\tif isSnapshotRow {\n\t\t\t\trow = snapshotRow\n\t\t\t} else {\n\t\t\t\trow = addedRow\n\t\t\t}\n\t\t}\n\t\tif row == nil {\n\t\t\treturn nil, nil\n\t\t}\n\n\t\tif isSnapshotRow {\n\t\t\tus.snapshotRow = nil\n\t\t} else {\n\t\t\tus.cursor++\n\t\t}\n\t\treturn row, nil\n\t}\n}\n\nfunc (us *UnionScanExec) getSnapshotRow(ctx context.Context) (Row, error) {\n\tif us.dirty.truncated {\n\t\treturn nil, nil\n\t}\n\tvar err error\n\tif us.snapshotRow == nil {\n\t\tfor {\n\t\t\tus.snapshotRow, err = us.children[0].Next(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Trace(err)\n\t\t\t}\n\t\t\tif us.snapshotRow == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tsnapshotHandle := us.snapshotRow[us.belowHandleIndex].GetInt64()\n\t\t\tif _, ok := us.dirty.deletedRows[snapshotHandle]; ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif _, ok := us.dirty.addedRows[snapshotHandle]; ok {\n\t\t\t\t\/\/ If src handle appears in added rows, it means there is conflict and the transaction will fail to\n\t\t\t\t\/\/ commit, but for simplicity, we don't handle it here.\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\treturn us.snapshotRow, nil\n}\n\nfunc (us *UnionScanExec) getAddedRow() Row {\n\tvar addedRow Row\n\tif us.cursor < len(us.addedRows) {\n\t\taddedRow = us.addedRows[us.cursor]\n\t}\n\treturn addedRow\n}\n\n\/\/ shouldPickFirstRow picks the suitable row in order.\n\/\/ The value returned is used to determine whether to pick the first input row.\nfunc (us *UnionScanExec) shouldPickFirstRow(a, b Row) (bool, error) {\n\tvar isFirstRow bool\n\taddedCmpSrc, err := us.compare(a, b)\n\tif err != nil {\n\t\treturn isFirstRow, errors.Trace(err)\n\t}\n\t\/\/ Compare result will never be 0.\n\tif us.desc {\n\t\tif addedCmpSrc > 0 {\n\t\t\tisFirstRow = true\n\t\t}\n\t} else {\n\t\tif addedCmpSrc < 0 {\n\t\t\tisFirstRow = true\n\t\t}\n\t}\n\treturn isFirstRow, nil\n}\n\nfunc (us *UnionScanExec) compare(a, b Row) (int, error) {\n\tsc := us.ctx.GetSessionVars().StmtCtx\n\tfor _, colOff := range us.usedIndex {\n\t\taColumn := a[colOff]\n\t\tbColumn := b[colOff]\n\t\tcmp, err := aColumn.CompareDatum(sc, &bColumn)\n\t\tif err != nil {\n\t\t\treturn 0, errors.Trace(err)\n\t\t}\n\t\tif cmp != 0 {\n\t\t\treturn cmp, nil\n\t\t}\n\t}\n\taHandle := a[us.belowHandleIndex].GetInt64()\n\tbHandle := b[us.belowHandleIndex].GetInt64()\n\tvar cmp int\n\tif aHandle == bHandle {\n\t\tcmp = 0\n\t} else if aHandle > bHandle {\n\t\tcmp = 1\n\t} else {\n\t\tcmp = -1\n\t}\n\treturn cmp, nil\n}\n\nfunc (us *UnionScanExec) buildAndSortAddedRows() error {\n\tus.addedRows = make([]Row, 0, len(us.dirty.addedRows))\n\tfor h, data := range us.dirty.addedRows {\n\t\tnewData := make(types.DatumRow, 0, us.schema.Len())\n\t\tfor _, col := range us.columns {\n\t\t\tif col.ID == model.ExtraHandleID {\n\t\t\t\tnewData = append(newData, types.NewIntDatum(h))\n\t\t\t} else {\n\t\t\t\tnewData = append(newData, data[col.Offset])\n\t\t\t}\n\t\t}\n\t\tmatched, err := expression.EvalBool(us.ctx, us.conditions, newData)\n\t\tif err != nil {\n\t\t\treturn errors.Trace(err)\n\t\t}\n\t\tif !matched {\n\t\t\tcontinue\n\t\t}\n\t\tus.addedRows = append(us.addedRows, newData)\n\t}\n\tif us.desc {\n\t\tsort.Sort(sort.Reverse(us))\n\t} else {\n\t\tsort.Sort(us)\n\t}\n\tif us.sortErr != nil {\n\t\treturn errors.Trace(us.sortErr)\n\t}\n\treturn nil\n}\n\n\/\/ Len implements sort.Interface interface.\nfunc (us *UnionScanExec) Len() int {\n\treturn len(us.addedRows)\n}\n\n\/\/ Less implements sort.Interface interface.\nfunc (us *UnionScanExec) Less(i, j int) bool {\n\tcmp, err := us.compare(us.addedRows[i], us.addedRows[j])\n\tif err != nil {\n\t\tus.sortErr = errors.Trace(err)\n\t\treturn true\n\t}\n\treturn cmp < 0\n}\n\n\/\/ Swap implements sort.Interface interface.\nfunc (us *UnionScanExec) Swap(i, j int) {\n\tus.addedRows[i], us.addedRows[j] = us.addedRows[j], us.addedRows[i]\n}\n<|endoftext|>"} {"text":"package command\n\nimport (\n\t\"encoding\/json\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"strings\"\n\n\tconsul \"github.com\/hashicorp\/consul\/api\"\n)\n\nconst (\n\tlocalConsulURL = \"127.0.0.1:8500\"\n\tdefaultFileName = \"data.json\"\n)\n\nfunc getKVClient(ipaddress string) (*consul.KV, error) {\n\tconfig := consul.DefaultConfig()\n\tconfig.Address = ipaddress\n\n\tclient, err := consul.NewClient(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn client.KV(), nil\n}\n\nfunc readJSON(filename string, prefix string) (consul.KVPairs, error) {\n\tdata, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinpairs := map[string]string{}\n\terr = json.Unmarshal(data, &inpairs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar kvs consul.KVPairs\n\tfor key, value := range inpairs {\n\t\tif prefix == \"\" || strings.HasPrefix(key, prefix) {\n\t\t\tkvs = append(kvs, &consul.KVPair{Key: key, Value: []byte(value)})\n\t\t}\n\t}\n\treturn kvs, nil\n}\n\nfunc saveKVsToFile(fullKVs consul.KVPairs, fileName string) error {\n\tkvs := map[string]string{}\n\tfor _, element := range fullKVs {\n\t\tkvs[element.Key] = string(element.Value)\n\t}\n\n\tdata, err := json.MarshalIndent(kvs, \"\", \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfile, err := os.Create(fileName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif _, err := file.Write([]byte(data)[:]); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\ntrim http \/ https off consul addressespackage command\n\nimport (\n\t\"encoding\/json\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"strings\"\n\n\tconsul \"github.com\/hashicorp\/consul\/api\"\n)\n\nconst (\n\tlocalConsulURL = \"127.0.0.1:8500\"\n\tdefaultFileName = \"data.json\"\n\thttp = \"http:\/\/\"\n\thttps = \"https:\/\/\"\n)\n\nfunc getKVClient(ipaddress string) (*consul.KV, error) {\n\tipaddress = strings.TrimPrefix(ipaddress, http)\n\tipaddress = strings.TrimPrefix(ipaddress, https)\n\n\tconfig := consul.DefaultConfig()\n\tconfig.Address = ipaddress\n\n\tclient, err := consul.NewClient(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn client.KV(), nil\n}\n\nfunc readJSON(filename string, prefix string) (consul.KVPairs, error) {\n\tdata, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinpairs := map[string]string{}\n\terr = json.Unmarshal(data, &inpairs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar kvs consul.KVPairs\n\tfor key, value := range inpairs {\n\t\tif prefix == \"\" || strings.HasPrefix(key, prefix) {\n\t\t\tkvs = append(kvs, &consul.KVPair{Key: key, Value: []byte(value)})\n\t\t}\n\t}\n\treturn kvs, nil\n}\n\nfunc saveKVsToFile(fullKVs consul.KVPairs, fileName string) error {\n\tkvs := map[string]string{}\n\tfor _, element := range fullKVs {\n\t\tkvs[element.Key] = string(element.Value)\n\t}\n\n\tdata, err := json.MarshalIndent(kvs, \"\", \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfile, err := os.Create(fileName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif _, err := file.Write([]byte(data)[:]); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n<|endoftext|>"} {"text":"package imap\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nvar registeredFetchParams []fetchParamDefinition\nvar peekRE *regexp.Regexp\n\n\/\/ ErrUnrecognisedParameter indicates that the parameter requested in a FETCH\n\/\/ command is unrecognised or not implemented in this IMAP server\nvar ErrUnrecognisedParameter = errors.New(\"Unrecognised Parameter\")\n\ntype fetchParamDefinition struct {\n\tre *regexp.Regexp\n\thandler func([]string, *Conn, Message, bool) string\n}\n\nfunc cmdFetch(args commandArgs, c *Conn) {\n\tstart, _ := strconv.Atoi(args.Arg(1))\n\n\tsearchByUID := args.Arg(0) == \"UID \"\n\n\t\/\/ Fetch the messages\n\tvar msg Message\n\tif searchByUID {\n\t\tfmt.Printf(\"Searching by UID\\n\")\n\t\tmsg = c.selectedMailbox.MessageByUid(uint32(start))\n\t} else {\n\t\tmsg = c.selectedMailbox.MessageBySequenceNumber(uint32(start))\n\t}\n\n\tfetchParamString := args.Arg(3)\n\tif searchByUID && !strings.Contains(fetchParamString, \"UID\") {\n\t\tfetchParamString += \" UID\"\n\t}\n\n\tfetchParams, err := fetch(fetchParamString, c, msg)\n\tif err != nil {\n\t\tif err == ErrUnrecognisedParameter {\n\t\t\tc.writeResponse(args.Id(), \"BAD Unrecognised Parameter\")\n\t\t\treturn\n\t\t} else {\n\t\t\tc.writeResponse(args.Id(), \"BAD\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tfullReply := fmt.Sprintf(\"%d FETCH (%s)\",\n\t\tmsg.SequenceNumber(),\n\t\tfetchParams)\n\n\tc.writeResponse(\"\", fullReply)\n\tif searchByUID {\n\t\tc.writeResponse(args.Id(), \"OK UID FETCH Completed\")\n\t} else {\n\t\tc.writeResponse(args.Id(), \"OK FETCH Completed\")\n\t}\n}\n\n\/\/ Fetch requested params from a given message\n\/\/ eg fetch(\"UID BODY[TEXT] RFC822.SIZE\", c, message)\nfunc fetch(params string, c *Conn, m Message) (string, error) {\n\t\/\/ Prepare the list of responses\n\tresponseParams := make([]string, 0)\n\n\tparamList := splitParams(params)\n\tfor _, param := range paramList {\n\t\tparamResponse, err := fetchParam(param, c, m)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tresponseParams = append(responseParams, paramResponse)\n\t}\n\treturn strings.Join(responseParams, \" \"), nil\n}\n\n\/\/ Match a single fetch parameter and return the data\nfunc fetchParam(param string, c *Conn, m Message) (string, error) {\n\tpeek := false\n\tif peekRE.MatchString(param) {\n\t\tpeek = true\n\t}\n\t\/\/ Search through the parameter list until a parameter handler is found\n\tfor _, element := range registeredFetchParams {\n\t\tif element.re.MatchString(param) {\n\t\t\treturn element.handler(element.re.FindStringSubmatch(param), c, m, peek), nil\n\t\t}\n\t}\n\treturn \"\", ErrUnrecognisedParameter\n}\n\n\/\/ Register all supported fetch parameters\nfunc init() {\n\tpeekRE = regexp.MustCompile(\"\\\\.PEEK\")\n\tregisteredFetchParams = make([]fetchParamDefinition, 0)\n\tregisterFetchParam(\"UID\", fetchUID)\n\tregisterFetchParam(\"FLAGS\", fetchFlags)\n\tregisterFetchParam(\"RFC822\\\\.SIZE\", fetchRfcSize)\n\tregisterFetchParam(\"INTERNALDATE\", fetchInternalDate)\n\tregisterFetchParam(\"BODY(?:\\\\.PEEK)?\\\\[HEADER\\\\]\", fetchHeaders)\n\tregisterFetchParam(\"BODY(?:\\\\.PEEK)?\"+\n\t\t\"\\\\[HEADER\\\\.FIELDS \\\\(([A-z\\\\s-]+)\\\\)\\\\]\", fetchHeaderSpecificFields)\n\tregisterFetchParam(\"BODY(?:\\\\.PEEK)?\\\\[TEXT\\\\]\", fetchBody)\n\tregisterFetchParam(\"BODY(?:\\\\.PEEK)?\\\\[\\\\]\", fetchFullText)\n}\n\nfunc registerFetchParam(regex string, handler func([]string, *Conn, Message, bool) string) {\n\tnewParam := fetchParamDefinition{\n\t\tre: regexp.MustCompile(regex),\n\t\thandler: handler,\n\t}\n\tregisteredFetchParams = append(registeredFetchParams, newParam)\n}\n\n\/\/ Fetch the UID of the mail message\nfunc fetchUID(args []string, c *Conn, m Message, peekOnly bool) string {\n\treturn fmt.Sprintf(\"UID %d\", m.Uid())\n}\n\nfunc fetchFlags(args []string, c *Conn, m Message, peekOnly bool) string {\n\tflags := append(messageFlags(m), m.Keywords()...)\n\tflagList := strings.Join(flags, \" \")\n\treturn fmt.Sprintf(\"FLAGS (%s)\", flagList)\n}\n\nfunc fetchRfcSize(args []string, c *Conn, m Message, peekOnly bool) string {\n\treturn fmt.Sprintf(\"RFC822.SIZE %d\", m.Size())\n}\n\nfunc fetchInternalDate(args []string, c *Conn, m Message, peekOnly bool) string {\n\tdateStr := m.InternalDate().Format(internalDate)\n\treturn fmt.Sprintf(\"INTERNALDATE \\\"%s\\\"\", dateStr)\n}\n\nfunc fetchHeaders(args []string, c *Conn, m Message, peekOnly bool) string {\n\thdr := fmt.Sprintf(\"\\r\\n%s\\r\\n\\r\\n\", m.Header())\n\thdrLen := len(hdr)\n\n\tpeekStr := \"\"\n\tif peekOnly {\n\t\tpeekStr = \".PEEK\"\n\t}\n\n\treturn fmt.Sprintf(\"BODY%s[HEADER] {%d}%s\", peekStr, hdrLen, hdr)\n}\n\nfunc fetchHeaderSpecificFields(args []string, c *Conn, m Message, peekOnly bool) string {\n\tif !peekOnly {\n\t\tfmt.Printf(\"TODO: Peek not requested, mark all as non-recent\\n\")\n\t}\n\tfields := strings.Split(args[1], \" \")\n\thdrs := m.Header()\n\trequestedHeaders := make(MIMEHeader)\n\treplyFieldList := make([]string, len(fields))\n\tfor i, key := range fields {\n\t\treplyFieldList[i] = \"\\\"\" + key + \"\\\"\"\n\t\t\/\/ If the key exists in the headers, copy it over\n\t\tif k, v, ok := hdrs.FindKey(key); ok {\n\t\t\trequestedHeaders[k] = v\n\t\t}\n\t}\n\thdr := fmt.Sprintf(\"\\r\\n%s\\r\\n\\r\\n\", requestedHeaders)\n\thdrLen := len(hdr)\n\n\treturn fmt.Sprintf(\"BODY[HEADER.FIELDS (%s)] {%d}%s\",\n\t\tstrings.Join(replyFieldList, \" \"),\n\t\thdrLen,\n\t\thdr)\n\n}\n\nfunc fetchBody(args []string, c *Conn, m Message, peekOnly bool) string {\n\tbody := fmt.Sprintf(\"\\r\\n%s\\r\\n\", m.Body())\n\tbodyLen := len(body)\n\n\treturn fmt.Sprintf(\"BODY[TEXT] {%d}%s\",\n\t\tbodyLen, body)\n}\n\nfunc fetchFullText(args []string, c *Conn, m Message, peekOnly bool) string {\n\tmail := fmt.Sprintf(\"\\r\\n%s\\r\\n\\r\\n%s\\r\\n\", m.Header(), m.Body())\n\tmailLen := len(mail)\n\n\treturn fmt.Sprintf(\"BODY[] {%d}%s\",\n\t\tmailLen, mail)\n}\nOutdent else statement. #8package imap\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nvar registeredFetchParams []fetchParamDefinition\nvar peekRE *regexp.Regexp\n\n\/\/ ErrUnrecognisedParameter indicates that the parameter requested in a FETCH\n\/\/ command is unrecognised or not implemented in this IMAP server\nvar ErrUnrecognisedParameter = errors.New(\"Unrecognised Parameter\")\n\ntype fetchParamDefinition struct {\n\tre *regexp.Regexp\n\thandler func([]string, *Conn, Message, bool) string\n}\n\nfunc cmdFetch(args commandArgs, c *Conn) {\n\tstart, _ := strconv.Atoi(args.Arg(1))\n\n\tsearchByUID := args.Arg(0) == \"UID \"\n\n\t\/\/ Fetch the messages\n\tvar msg Message\n\tif searchByUID {\n\t\tfmt.Printf(\"Searching by UID\\n\")\n\t\tmsg = c.selectedMailbox.MessageByUid(uint32(start))\n\t} else {\n\t\tmsg = c.selectedMailbox.MessageBySequenceNumber(uint32(start))\n\t}\n\n\tfetchParamString := args.Arg(3)\n\tif searchByUID && !strings.Contains(fetchParamString, \"UID\") {\n\t\tfetchParamString += \" UID\"\n\t}\n\n\tfetchParams, err := fetch(fetchParamString, c, msg)\n\tif err != nil {\n\t\tif err == ErrUnrecognisedParameter {\n\t\t\tc.writeResponse(args.Id(), \"BAD Unrecognised Parameter\")\n\t\t\treturn\n\t\t}\n\n\t\tc.writeResponse(args.Id(), \"BAD\")\n\t\treturn\n\t}\n\n\tfullReply := fmt.Sprintf(\"%d FETCH (%s)\",\n\t\tmsg.SequenceNumber(),\n\t\tfetchParams)\n\n\tc.writeResponse(\"\", fullReply)\n\tif searchByUID {\n\t\tc.writeResponse(args.Id(), \"OK UID FETCH Completed\")\n\t} else {\n\t\tc.writeResponse(args.Id(), \"OK FETCH Completed\")\n\t}\n}\n\n\/\/ Fetch requested params from a given message\n\/\/ eg fetch(\"UID BODY[TEXT] RFC822.SIZE\", c, message)\nfunc fetch(params string, c *Conn, m Message) (string, error) {\n\t\/\/ Prepare the list of responses\n\tresponseParams := make([]string, 0)\n\n\tparamList := splitParams(params)\n\tfor _, param := range paramList {\n\t\tparamResponse, err := fetchParam(param, c, m)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tresponseParams = append(responseParams, paramResponse)\n\t}\n\treturn strings.Join(responseParams, \" \"), nil\n}\n\n\/\/ Match a single fetch parameter and return the data\nfunc fetchParam(param string, c *Conn, m Message) (string, error) {\n\tpeek := false\n\tif peekRE.MatchString(param) {\n\t\tpeek = true\n\t}\n\t\/\/ Search through the parameter list until a parameter handler is found\n\tfor _, element := range registeredFetchParams {\n\t\tif element.re.MatchString(param) {\n\t\t\treturn element.handler(element.re.FindStringSubmatch(param), c, m, peek), nil\n\t\t}\n\t}\n\treturn \"\", ErrUnrecognisedParameter\n}\n\n\/\/ Register all supported fetch parameters\nfunc init() {\n\tpeekRE = regexp.MustCompile(\"\\\\.PEEK\")\n\tregisteredFetchParams = make([]fetchParamDefinition, 0)\n\tregisterFetchParam(\"UID\", fetchUID)\n\tregisterFetchParam(\"FLAGS\", fetchFlags)\n\tregisterFetchParam(\"RFC822\\\\.SIZE\", fetchRfcSize)\n\tregisterFetchParam(\"INTERNALDATE\", fetchInternalDate)\n\tregisterFetchParam(\"BODY(?:\\\\.PEEK)?\\\\[HEADER\\\\]\", fetchHeaders)\n\tregisterFetchParam(\"BODY(?:\\\\.PEEK)?\"+\n\t\t\"\\\\[HEADER\\\\.FIELDS \\\\(([A-z\\\\s-]+)\\\\)\\\\]\", fetchHeaderSpecificFields)\n\tregisterFetchParam(\"BODY(?:\\\\.PEEK)?\\\\[TEXT\\\\]\", fetchBody)\n\tregisterFetchParam(\"BODY(?:\\\\.PEEK)?\\\\[\\\\]\", fetchFullText)\n}\n\nfunc registerFetchParam(regex string, handler func([]string, *Conn, Message, bool) string) {\n\tnewParam := fetchParamDefinition{\n\t\tre: regexp.MustCompile(regex),\n\t\thandler: handler,\n\t}\n\tregisteredFetchParams = append(registeredFetchParams, newParam)\n}\n\n\/\/ Fetch the UID of the mail message\nfunc fetchUID(args []string, c *Conn, m Message, peekOnly bool) string {\n\treturn fmt.Sprintf(\"UID %d\", m.Uid())\n}\n\nfunc fetchFlags(args []string, c *Conn, m Message, peekOnly bool) string {\n\tflags := append(messageFlags(m), m.Keywords()...)\n\tflagList := strings.Join(flags, \" \")\n\treturn fmt.Sprintf(\"FLAGS (%s)\", flagList)\n}\n\nfunc fetchRfcSize(args []string, c *Conn, m Message, peekOnly bool) string {\n\treturn fmt.Sprintf(\"RFC822.SIZE %d\", m.Size())\n}\n\nfunc fetchInternalDate(args []string, c *Conn, m Message, peekOnly bool) string {\n\tdateStr := m.InternalDate().Format(internalDate)\n\treturn fmt.Sprintf(\"INTERNALDATE \\\"%s\\\"\", dateStr)\n}\n\nfunc fetchHeaders(args []string, c *Conn, m Message, peekOnly bool) string {\n\thdr := fmt.Sprintf(\"\\r\\n%s\\r\\n\\r\\n\", m.Header())\n\thdrLen := len(hdr)\n\n\tpeekStr := \"\"\n\tif peekOnly {\n\t\tpeekStr = \".PEEK\"\n\t}\n\n\treturn fmt.Sprintf(\"BODY%s[HEADER] {%d}%s\", peekStr, hdrLen, hdr)\n}\n\nfunc fetchHeaderSpecificFields(args []string, c *Conn, m Message, peekOnly bool) string {\n\tif !peekOnly {\n\t\tfmt.Printf(\"TODO: Peek not requested, mark all as non-recent\\n\")\n\t}\n\tfields := strings.Split(args[1], \" \")\n\thdrs := m.Header()\n\trequestedHeaders := make(MIMEHeader)\n\treplyFieldList := make([]string, len(fields))\n\tfor i, key := range fields {\n\t\treplyFieldList[i] = \"\\\"\" + key + \"\\\"\"\n\t\t\/\/ If the key exists in the headers, copy it over\n\t\tif k, v, ok := hdrs.FindKey(key); ok {\n\t\t\trequestedHeaders[k] = v\n\t\t}\n\t}\n\thdr := fmt.Sprintf(\"\\r\\n%s\\r\\n\\r\\n\", requestedHeaders)\n\thdrLen := len(hdr)\n\n\treturn fmt.Sprintf(\"BODY[HEADER.FIELDS (%s)] {%d}%s\",\n\t\tstrings.Join(replyFieldList, \" \"),\n\t\thdrLen,\n\t\thdr)\n\n}\n\nfunc fetchBody(args []string, c *Conn, m Message, peekOnly bool) string {\n\tbody := fmt.Sprintf(\"\\r\\n%s\\r\\n\", m.Body())\n\tbodyLen := len(body)\n\n\treturn fmt.Sprintf(\"BODY[TEXT] {%d}%s\",\n\t\tbodyLen, body)\n}\n\nfunc fetchFullText(args []string, c *Conn, m Message, peekOnly bool) string {\n\tmail := fmt.Sprintf(\"\\r\\n%s\\r\\n\\r\\n%s\\r\\n\", m.Header(), m.Body())\n\tmailLen := len(mail)\n\n\treturn fmt.Sprintf(\"BODY[] {%d}%s\",\n\t\tmailLen, mail)\n}\n<|endoftext|>"} {"text":"package commands\n\n\/\/ Init sits here\n\nimport (\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/spf13\/cobra\"\n)\n\nfunc init() {\n\n\t\/\/ Define Deploy Flags\n\tdeployCmd.Flags().StringArrayVarP(&run.tplSources, \"template\", \"t\", []string{}, \"path to template file(s) Or stack::url\")\n\tdeployCmd.Flags().BoolVarP(&run.rollback, \"disable-rollback\", \"\", false, \"Set Stack to rollback on deployment failures\")\n\tdeployCmd.Flags().BoolVarP(&run.all, \"all\", \"A\", false, \"deploy all stacks with defined Sources in config\")\n\n\t\/\/ Define Git Deploy Flags\n\tgitDeployCmd.Flags().BoolVarP(&run.rollback, \"disable-rollback\", \"\", false, \"Set Stack to rollback on deployment failures\")\n\tgitDeployCmd.Flags().BoolVarP(&run.all, \"all\", \"A\", false, \"deploy all stacks with defined Sources in config\")\n\tgitDeployCmd.Flags().StringVarP(&run.gituser, \"user\", \"u\", \"\", \"git username\")\n\tgitDeployCmd.Flags().StringVarP(&run.gitpass, \"password\", \"\", \"\", \"git password\")\n\tgitDeployCmd.Flags().StringVarP(&run.gitrsa, \"ssh-rsa\", \"\", filepath.Join(os.Getenv(\"HOME\"), \".ssh\/id_rsa\"), \"path to git SSH id_rsa\")\n\n\t\/\/ Define Git Status Command\n\tgitStatusCmd.Flags().StringVarP(&run.gitrsa, \"ssh-rsa\", \"\", filepath.Join(os.Getenv(\"HOME\"), \".ssh\/id_rsa\"), \"path to git SSH id_rsa\")\n\tgitStatusCmd.Flags().StringVarP(&run.gitpass, \"password\", \"\", \"\", \"git password\")\n\tgitStatusCmd.Flags().StringVarP(&run.gituser, \"user\", \"u\", \"\", \"git username\")\n\n\t\/\/ Define Terminate Flags\n\tterminateCmd.Flags().BoolVarP(&run.all, \"all\", \"A\", false, \"terminate all stacks\")\n\n\t\/\/ Define Output Flags\n\toutputsCmd.Flags().StringVarP(&run.profile, \"profile\", \"p\", \"default\", \"configured aws profile\")\n\n\t\/\/ Define Root Flags\n\tRootCmd.Flags().BoolVarP(&run.version, \"version\", \"\", false, \"print current\/running version\")\n\tRootCmd.PersistentFlags().BoolVarP(&run.colors, \"no-colors\", \"\", false, \"disable colors in outputs\")\n\tRootCmd.PersistentFlags().StringVarP(&run.profile, \"profile\", \"p\", \"default\", \"configured aws profile\")\n\tRootCmd.PersistentFlags().StringVarP(&run.region, \"region\", \"r\", \"\", \"configured aws region: if blank, the region is acquired via the profile\")\n\tRootCmd.PersistentFlags().BoolVarP(&run.debug, \"debug\", \"\", false, \"Run in debug mode...\")\n\n\t\/\/ Define Lambda Invoke Flags\n\tinvokeCmd.Flags().StringVarP(&run.funcEvent, \"event\", \"e\", \"\", \"JSON Event data for AWS Lambda invoke\")\n\tinvokeCmd.Flags().BoolVarP(&run.lambdAsync, \"async\", \"x\", false, \"invoke lambda function asynchronously \")\n\n\t\/\/ Define Changes Command\n\tchangeCmd.AddCommand(create, rm, list, execute, desc)\n\n\t\/\/ Define Protect Command\n\tprotectCmd.Flags().BoolVarP(&run.protectOff, \"off\", \"\", false, \"set termination protection to off\")\n\tprotectCmd.Flags().BoolVarP(&run.all, \"all\", \"A\", false, \"protect all stacks\")\n\n\t\/\/ Add Config --config common flag\n\tfor _, cmd := range []interface{}{\n\t\tcheckCmd,\n\t\tupdateCmd,\n\t\toutputsCmd,\n\t\tstatusCmd,\n\t\tterminateCmd,\n\t\tgenerateCmd,\n\t\tdeployCmd,\n\t\tgitDeployCmd,\n\t\tgitStatusCmd,\n\t\tpolicyCmd,\n\t\tvaluesCmd,\n\t\tshellCmd,\n\t\tprotectCmd,\n\t} {\n\t\tcmd.(*cobra.Command).Flags().StringVarP(&run.cfgSource, \"config\", \"c\", defaultConfig(), \"path to config file\")\n\t}\n\n\t\/\/ Add Template --template common flag\n\tfor _, cmd := range []interface{}{\n\t\tgenerateCmd,\n\t\tupdateCmd,\n\t\tcheckCmd,\n\t} {\n\t\tcmd.(*cobra.Command).Flags().StringVarP(&run.tplSource, \"template\", \"t\", \"\", \"path to template source Or stack::source\")\n\t}\n\n\tfor _, cmd := range []interface{}{\n\t\tcreate,\n\t\tlist,\n\t\trm,\n\t\texecute,\n\t\tdesc,\n\t} {\n\t\tcmd.(*cobra.Command).Flags().StringVarP(&run.cfgSource, \"config\", \"c\", defaultConfig(), \"path to config file [Required]\")\n\t\tcmd.(*cobra.Command).Flags().StringVarP(&run.stackName, \"stack\", \"s\", \"\", \"Qaz local project Stack Name [Required]\")\n\t}\n\n\tcreate.Flags().StringVarP(&run.tplSource, \"template\", \"t\", \"\", \"path to template file Or stack::url\")\n\tchangeCmd.Flags().StringVarP(&run.cfgSource, \"config\", \"c\", defaultConfig(), \"path to config file\")\n\n\t\/\/ add commands\n\tRootCmd.AddCommand(\n\t\tgenerateCmd,\n\t\tdeployCmd,\n\t\tterminateCmd,\n\t\tstatusCmd,\n\t\toutputsCmd,\n\t\tinitCmd,\n\t\tupdateCmd,\n\t\tcheckCmd,\n\t\texportsCmd,\n\t\tinvokeCmd,\n\t\tchangeCmd,\n\t\tpolicyCmd,\n\t\tgitDeployCmd,\n\t\tgitStatusCmd,\n\t\tvaluesCmd,\n\t\tshellCmd,\n\t\tprotectCmd,\n\t\tcompletionCmd,\n\t)\n\n}\nSquare brackets in description interferred with zsh completion syntaxpackage commands\n\n\/\/ Init sits here\n\nimport (\n\t\"os\"\n\t\"path\/filepath\"\n\n\t\"github.com\/spf13\/cobra\"\n)\n\nfunc init() {\n\n\t\/\/ Define Deploy Flags\n\tdeployCmd.Flags().StringArrayVarP(&run.tplSources, \"template\", \"t\", []string{}, \"path to template file(s) Or stack::url\")\n\tdeployCmd.Flags().BoolVarP(&run.rollback, \"disable-rollback\", \"\", false, \"Set Stack to rollback on deployment failures\")\n\tdeployCmd.Flags().BoolVarP(&run.all, \"all\", \"A\", false, \"deploy all stacks with defined Sources in config\")\n\n\t\/\/ Define Git Deploy Flags\n\tgitDeployCmd.Flags().BoolVarP(&run.rollback, \"disable-rollback\", \"\", false, \"Set Stack to rollback on deployment failures\")\n\tgitDeployCmd.Flags().BoolVarP(&run.all, \"all\", \"A\", false, \"deploy all stacks with defined Sources in config\")\n\tgitDeployCmd.Flags().StringVarP(&run.gituser, \"user\", \"u\", \"\", \"git username\")\n\tgitDeployCmd.Flags().StringVarP(&run.gitpass, \"password\", \"\", \"\", \"git password\")\n\tgitDeployCmd.Flags().StringVarP(&run.gitrsa, \"ssh-rsa\", \"\", filepath.Join(os.Getenv(\"HOME\"), \".ssh\/id_rsa\"), \"path to git SSH id_rsa\")\n\n\t\/\/ Define Git Status Command\n\tgitStatusCmd.Flags().StringVarP(&run.gitrsa, \"ssh-rsa\", \"\", filepath.Join(os.Getenv(\"HOME\"), \".ssh\/id_rsa\"), \"path to git SSH id_rsa\")\n\tgitStatusCmd.Flags().StringVarP(&run.gitpass, \"password\", \"\", \"\", \"git password\")\n\tgitStatusCmd.Flags().StringVarP(&run.gituser, \"user\", \"u\", \"\", \"git username\")\n\n\t\/\/ Define Terminate Flags\n\tterminateCmd.Flags().BoolVarP(&run.all, \"all\", \"A\", false, \"terminate all stacks\")\n\n\t\/\/ Define Output Flags\n\toutputsCmd.Flags().StringVarP(&run.profile, \"profile\", \"p\", \"default\", \"configured aws profile\")\n\n\t\/\/ Define Root Flags\n\tRootCmd.Flags().BoolVarP(&run.version, \"version\", \"\", false, \"print current\/running version\")\n\tRootCmd.PersistentFlags().BoolVarP(&run.colors, \"no-colors\", \"\", false, \"disable colors in outputs\")\n\tRootCmd.PersistentFlags().StringVarP(&run.profile, \"profile\", \"p\", \"default\", \"configured aws profile\")\n\tRootCmd.PersistentFlags().StringVarP(&run.region, \"region\", \"r\", \"\", \"configured aws region: if blank, the region is acquired via the profile\")\n\tRootCmd.PersistentFlags().BoolVarP(&run.debug, \"debug\", \"\", false, \"Run in debug mode...\")\n\n\t\/\/ Define Lambda Invoke Flags\n\tinvokeCmd.Flags().StringVarP(&run.funcEvent, \"event\", \"e\", \"\", \"JSON Event data for AWS Lambda invoke\")\n\tinvokeCmd.Flags().BoolVarP(&run.lambdAsync, \"async\", \"x\", false, \"invoke lambda function asynchronously \")\n\n\t\/\/ Define Changes Command\n\tchangeCmd.AddCommand(create, rm, list, execute, desc)\n\n\t\/\/ Define Protect Command\n\tprotectCmd.Flags().BoolVarP(&run.protectOff, \"off\", \"\", false, \"set termination protection to off\")\n\tprotectCmd.Flags().BoolVarP(&run.all, \"all\", \"A\", false, \"protect all stacks\")\n\n\t\/\/ Add Config --config common flag\n\tfor _, cmd := range []interface{}{\n\t\tcheckCmd,\n\t\tupdateCmd,\n\t\toutputsCmd,\n\t\tstatusCmd,\n\t\tterminateCmd,\n\t\tgenerateCmd,\n\t\tdeployCmd,\n\t\tgitDeployCmd,\n\t\tgitStatusCmd,\n\t\tpolicyCmd,\n\t\tvaluesCmd,\n\t\tshellCmd,\n\t\tprotectCmd,\n\t} {\n\t\tcmd.(*cobra.Command).Flags().StringVarP(&run.cfgSource, \"config\", \"c\", defaultConfig(), \"path to config file\")\n\t}\n\n\t\/\/ Add Template --template common flag\n\tfor _, cmd := range []interface{}{\n\t\tgenerateCmd,\n\t\tupdateCmd,\n\t\tcheckCmd,\n\t} {\n\t\tcmd.(*cobra.Command).Flags().StringVarP(&run.tplSource, \"template\", \"t\", \"\", \"path to template source Or stack::source\")\n\t}\n\n\tfor _, cmd := range []interface{}{\n\t\tcreate,\n\t\tlist,\n\t\trm,\n\t\texecute,\n\t\tdesc,\n\t} {\n\t\tcmd.(*cobra.Command).Flags().StringVarP(&run.cfgSource, \"config\", \"c\", defaultConfig(), \"path to config file (Required)\")\n\t\tcmd.(*cobra.Command).Flags().StringVarP(&run.stackName, \"stack\", \"s\", \"\", \"Qaz local project Stack Name (Required)\")\n\t}\n\n\tcreate.Flags().StringVarP(&run.tplSource, \"template\", \"t\", \"\", \"path to template file Or stack::url\")\n\tchangeCmd.Flags().StringVarP(&run.cfgSource, \"config\", \"c\", defaultConfig(), \"path to config file\")\n\n\t\/\/ add commands\n\tRootCmd.AddCommand(\n\t\tgenerateCmd,\n\t\tdeployCmd,\n\t\tterminateCmd,\n\t\tstatusCmd,\n\t\toutputsCmd,\n\t\tinitCmd,\n\t\tupdateCmd,\n\t\tcheckCmd,\n\t\texportsCmd,\n\t\tinvokeCmd,\n\t\tchangeCmd,\n\t\tpolicyCmd,\n\t\tgitDeployCmd,\n\t\tgitStatusCmd,\n\t\tvaluesCmd,\n\t\tshellCmd,\n\t\tprotectCmd,\n\t\tcompletionCmd,\n\t)\n\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/AlexanderThaller\/logger\"\n)\n\nfunc Test_RunNoDataPath(t *testing.T) {\n\tl := logger.New(Name, \"Test\", \"Command\", \"Run\", \"NoDataPath\")\n\n\tcommand := new(Command)\n\terr := command.Run()\n\n\tgot := err.Error()\n\texpected := \"the datapath can not be empty\"\n\n\ttesterr_output(t, l, err, got, expected)\n}\n\nfunc Test_RunDates(t *testing.T) {\n\tl := logger.New(Name, \"Test\", \"Command\", \"Run\", \"Dates\")\n\n\taction := ActionDates\n\n\texpected := `2014-10-30\n2014-10-31\n2014-11-01\n`\n\n\ttestCommandRunOutput(t, l, action, expected)\n}\n\nfunc Test_RunList(t *testing.T) {\n\tl := logger.New(Name, \"Test\", \"Command\", \"Run\", \"List\")\n\n\taction := ActionList\n\texpected := `TestNotes\nTestTodos\nTestTracks\n`\n\n\ttestCommandRunOutput(t, l, action, expected)\n}\n\nfunc Test_RunListProject(t *testing.T) {\n\tl := logger.New(Name, \"Test\", \"Command\", \"Run\", \"List\", \"Project\")\n\n\taction := ActionList\n\tcommand, buffer := testCommand(action)\n\tcommand.Project = \"TestNotes\"\n\n\texpected := \"= TestNotes -- List\\n\"\n\texpected += AsciiDocSettings + \"\\n\\n\"\n\texpected += `== 2014-10-30T21:36:31.49146148+01:00\nTest1\n\n== 2014-10-30T21:36:33.49871531+01:00\nTest2\n\n== 2014-10-30T21:36:35.138412374+01:00\nTest3\n\n== 2014-10-30T21:36:36.810478305+01:00\nTest4\n\n== 2014-10-30T21:36:38.450479686+01:00\nTest5\n\n`\n\n\terr := command.Run()\n\tgot := buffer.String()\n\n\ttesterr_output(t, l, err, got, expected)\n}\n\nfunc Test_RunListProjectNoDataDir(t *testing.T) {\n\tl := logger.New(Name, \"Test\", \"Command\", \"Run\", \"List\", \"Project\", \"NoDataDir\")\n\n\taction := ActionList\n\tcommand, buffer := testCommand(action)\n\tcommand.DataPath = TestDataPathFail\n\n\texpected := \"\"\n\terr := command.Run()\n\tgot := buffer.String()\n\n\ttesterr_output(t, l, err, got, expected)\n}\n\nfunc Test_RunListProjectNoNotes(t *testing.T) {\n\tl := logger.New(Name, \"Test\", \"Command\", \"Run\", \"List\", \"Project\", \"NoNotes\")\n\n\taction := ActionList\n\tcommand, buffer := testCommand(action)\n\tcommand.Project = \"TestTodos\"\n\n\texpected := \"= TestTodos -- List\\n\"\n\texpected += AsciiDocSettings + \"\\n\\n\"\n\texpected += `* Test1\n* Test2\n* Test3\n* Test4\n* Test5\n* Test7\n\n`\n\n\terr := command.Run()\n\tgot := buffer.String()\n\n\ttesterr_output(t, l, err, got, expected)\n}\n\nfunc Test_RunListProjectNoNotesNoTodos(t *testing.T) {\n\tl := logger.New(Name, \"Test\", \"Command\", \"Run\", \"List\", \"Project\", \"NoNotesNoTodos\")\n\n\taction := ActionList\n\tcommand, buffer := testCommand(action)\n\tcommand.Project = \"TestTracks\"\n\n\texpected := \"= TestTracks -- List\\n\"\n\texpected += AsciiDocSettings + \"\\n\\n\"\n\texpected += `* 2014-11-01T00:46:27.250010094+01:00 -- Test1\n* 2014-11-01T00:46:31.186052306+01:00 -- Test2\n* 2014-11-01T00:46:32.794131714+01:00 -- Test3\n* 2014-11-01T00:46:34.322047221+01:00 -- Test4\n* 2014-11-01T00:46:35.658221386+01:00 -- Test5\n* 2014-11-01T00:46:57.953493565+01:00 -- Test7\n\n`\n\n\terr := command.Run()\n\tgot := buffer.String()\n\n\ttesterr_output(t, l, err, got, expected)\n}\n\nfunc Test_RunListProjectNoExists(t *testing.T) {\n\tl := logger.New(Name, \"Test\", \"Command\", \"Run\", \"List\", \"Project\", \"NoExists\")\n\n\taction := ActionList\n\tcommand, buffer := testCommand(action)\n\tcommand.Project = \"DOES NOT EXIST\"\n\n\texpected := \"\"\n\terr := command.Run()\n\tgot := buffer.String()\n\n\ttesterr_output(t, l, err, got, expected)\n}\n\nfunc Test_RunNotes(t *testing.T) {\n\tl := logger.New(Name, \"Test\", \"Command\", \"Run\", \"Notes\")\n\tl.SetLevel(logger.Info)\n\n\taction := ActionNotes\n\tcommand, buffer := testCommand(action)\n\tcommand.Project = \"TestNotes\"\n\n\texpected := \"= TestNotes -- Notes\\n\"\n\texpected += AsciiDocSettings + \"\\n\\n\"\n\texpected += `== 2014-10-30T21:36:31.49146148+01:00\nTest1\n\n== 2014-10-30T21:36:33.49871531+01:00\nTest2\n\n== 2014-10-30T21:36:35.138412374+01:00\nTest3\n\n== 2014-10-30T21:36:36.810478305+01:00\nTest4\n\n== 2014-10-30T21:36:38.450479686+01:00\nTest5\n\n`\n\n\terr := command.Run()\n\tgot := buffer.String()\n\n\ttesterr_output(t, l, err, got, expected)\n}\n\nfunc Test_RunNotesProject(t *testing.T) {\n\tl := logger.New(Name, \"Test\", \"Command\", \"Run\", \"Notes\", \"Project\")\n\tl.SetLevel(logger.Info)\n\n\taction := ActionNotes\n\texpected := \"= Lablog -- Notes\\n\"\n\texpected += AsciiDocSettings + \"\\n\\n\"\n\texpected += `== TestNotes\n\n=== 2014-10-30T21:36:31.49146148+01:00\nTest1\n\n=== 2014-10-30T21:36:33.49871531+01:00\nTest2\n\n=== 2014-10-30T21:36:35.138412374+01:00\nTest3\n\n=== 2014-10-30T21:36:36.810478305+01:00\nTest4\n\n=== 2014-10-30T21:36:38.450479686+01:00\nTest5\n\n`\n\n\ttestCommandRunOutput(t, l, action, expected)\n}\n\nfunc Test_RunProjects(t *testing.T) {\n\tl := logger.New(Name, \"Test\", \"Command\", \"Run\", \"Projects\")\n\n\taction := ActionProjects\n\texpected := `TestNotes\nTestTodos\nTestTracks\n`\n\n\ttestCommandRunOutput(t, l, action, expected)\n}\n\nfunc Test_RunTodos(t *testing.T) {\n\tl := logger.New(Name, \"Test\", \"Command\", \"Run\", \"Todos\")\n\tl.SetLevel(logger.Info)\n\n\taction := ActionTodos\n\texpected := \"= Lablog -- Todos\\n\"\n\texpected += AsciiDocSettings + \"\\n\\n\"\n\texpected += `== TestTodos\n\n* Test1\n* Test2\n* Test3\n* Test4\n* Test5\n* Test7\n\n`\n\n\ttestCommandRunOutput(t, l, action, expected)\n}\n\nfunc Test_RunTracks(t *testing.T) {\n\tl := logger.New(Name, \"Test\", \"Command\", \"Run\", \"Tracks\")\n\tl.SetLevel(logger.Info)\n\n\taction := ActionTracks\n\texpected := \"= Lablog -- Tracks\\n\"\n\texpected += AsciiDocSettings + \"\\n\\n\"\n\texpected += `== TestTracks\n\n* 2014-11-01T00:46:27.250010094+01:00 -- Test1\n* 2014-11-01T00:46:31.186052306+01:00 -- Test2\n* 2014-11-01T00:46:32.794131714+01:00 -- Test3\n* 2014-11-01T00:46:34.322047221+01:00 -- Test4\n* 2014-11-01T00:46:35.658221386+01:00 -- Test5\n* 2014-11-01T00:46:38.385921461+01:00\n* 2014-11-01T00:46:51.833861322+01:00 -- Test6\n* 2014-11-01T00:46:53.713763133+01:00 -- Test6\n* 2014-11-01T00:46:55.609688812+01:00 -- Test7\n* 2014-11-01T00:46:56.713668447+01:00 -- Test7\n* 2014-11-01T00:46:57.953493565+01:00 -- Test7\n* 2014-11-01T00:54:54.778921093+01:00\n\n`\n\n\ttestCommandRunOutput(t, l, action, expected)\n}\n\nfunc Test_RunTracksActive(t *testing.T) {\n\tl := logger.New(Name, \"Test\", \"Command\", \"Run\", \"TracksActive\")\n\tl.SetLevel(logger.Info)\n\n\taction := ActionTracksActive\n\texpected := \"= Lablog -- TracksActive\\n\"\n\texpected += AsciiDocSettings + \"\\n\\n\"\n\texpected += `== TestTracks\n\n* 2014-11-01T00:46:27.250010094+01:00 -- Test1\n* 2014-11-01T00:46:31.186052306+01:00 -- Test2\n* 2014-11-01T00:46:32.794131714+01:00 -- Test3\n* 2014-11-01T00:46:34.322047221+01:00 -- Test4\n* 2014-11-01T00:46:35.658221386+01:00 -- Test5\n* 2014-11-01T00:46:57.953493565+01:00 -- Test7\n\n`\n\n\ttestCommandRunOutput(t, l, action, expected)\n}\n\nfunc Test_RunTracksDurations(t *testing.T) {\n\tl := logger.New(Name, \"Test\", \"Command\", \"Run\", \"TracksDurations\")\n\tl.SetLevel(logger.Info)\n\n\taction := ActionTracksDurations\n\texpected := \"= Lablog -- Durations\\n\"\n\texpected += AsciiDocSettings + \"\\n\\n\"\n\texpected += `== TestTracks\n\n* 8m16.392999632s\n* Test6 -- 1.879901811s\n* Test7 -- 1.103979635s\n\n`\n\n\ttestCommandRunOutput(t, l, action, expected)\n}\nfixed some tests and added some benchmarks.package main\n\nimport (\n\t\"testing\"\n\n\t\"github.com\/AlexanderThaller\/logger\"\n)\n\nfunc Test_RunNoDataPath(t *testing.T) {\n\tl := logger.New(Name, \"Test\", \"Command\", \"Run\", \"NoDataPath\")\n\n\tcommand := new(Command)\n\terr := command.Run()\n\n\tgot := err.Error()\n\texpected := \"the datapath can not be empty\"\n\n\ttesterr_output(t, l, err, got, expected)\n}\n\nfunc Test_RunDates(t *testing.T) {\n\tl := logger.New(Name, \"Test\", \"Command\", \"Run\", \"Dates\")\n\n\taction := ActionDates\n\n\texpected := `2014-10-30\n2014-10-31\n2014-11-01\n`\n\n\ttestCommandRunOutput(t, l, action, expected)\n}\n\nfunc Test_RunList(t *testing.T) {\n\tl := logger.New(Name, \"Test\", \"Command\", \"Run\", \"List\")\n\n\taction := ActionList\n\texpected := `TestNotes\nTestTodos\nTestTracks\n`\n\n\ttestCommandRunOutput(t, l, action, expected)\n}\n\nfunc Test_RunListProject(t *testing.T) {\n\tl := logger.New(Name, \"Test\", \"Command\", \"Run\", \"List\", \"Project\")\n\n\taction := ActionList\n\tcommand, buffer := testCommand(action)\n\tcommand.Project = \"TestNotes\"\n\n\texpected := \"= TestNotes -- List\\n\"\n\texpected += AsciiDocSettings + \"\\n\\n\"\n\texpected += `== 2014-10-30T21:36:31.49146148+01:00\nTest1\n\n== 2014-10-30T21:36:33.49871531+01:00\nTest2\n\n== 2014-10-30T21:36:35.138412374+01:00\nTest3\n\n== 2014-10-30T21:36:36.810478305+01:00\nTest4\n\n== 2014-10-30T21:36:38.450479686+01:00\nTest5\n\n`\n\n\terr := command.Run()\n\tgot := buffer.String()\n\n\ttesterr_output(t, l, err, got, expected)\n}\n\nfunc Test_RunListProjectNoDataDir(t *testing.T) {\n\tl := logger.New(Name, \"Test\", \"Command\", \"Run\", \"List\", \"Project\", \"NoDataDir\")\n\n\taction := ActionList\n\tcommand, buffer := testCommand(action)\n\tcommand.DataPath = TestDataPathFail\n\n\texpected := \"\"\n\terr := command.Run()\n\tgot := buffer.String()\n\n\ttesterr_output(t, l, err, got, expected)\n}\n\nfunc Test_RunListProjectNoNotes(t *testing.T) {\n\tl := logger.New(Name, \"Test\", \"Command\", \"Run\", \"List\", \"Project\", \"NoNotes\")\n\n\taction := ActionList\n\tcommand, buffer := testCommand(action)\n\tcommand.Project = \"TestTodos\"\n\n\texpected := \"= TestTodos -- List\\n\"\n\texpected += AsciiDocSettings + \"\\n\\n\"\n\texpected += `* Test1\n* Test2\n* Test3\n* Test4\n* Test5\n* Test7\n\n`\n\n\terr := command.Run()\n\tgot := buffer.String()\n\n\ttesterr_output(t, l, err, got, expected)\n}\n\nfunc Test_RunListProjectNoNotesNoTodos(t *testing.T) {\n\tl := logger.New(Name, \"Test\", \"Command\", \"Run\", \"List\", \"Project\", \"NoNotesNoTodos\")\n\n\taction := ActionList\n\tcommand, buffer := testCommand(action)\n\tcommand.Project = \"TestTracks\"\n\n\texpected := \"= TestTracks -- List\\n\"\n\texpected += AsciiDocSettings + \"\\n\\n\"\n\texpected += `* 2014-11-01T00:46:27.250010094+01:00 -- Test1\n* 2014-11-01T00:46:31.186052306+01:00 -- Test2\n* 2014-11-01T00:46:32.794131714+01:00 -- Test3\n* 2014-11-01T00:46:34.322047221+01:00 -- Test4\n* 2014-11-01T00:46:35.658221386+01:00 -- Test5\n* 2014-11-01T00:46:57.953493565+01:00 -- Test7\n\n`\n\n\terr := command.Run()\n\tgot := buffer.String()\n\n\ttesterr_output(t, l, err, got, expected)\n}\n\nfunc Test_RunListProjectNoExists(t *testing.T) {\n\tl := logger.New(Name, \"Test\", \"Command\", \"Run\", \"List\", \"Project\", \"NoExists\")\n\n\taction := ActionList\n\tcommand, buffer := testCommand(action)\n\tcommand.Project = \"DOES NOT EXIST\"\n\n\texpected := \"\"\n\terr := command.Run()\n\tgot := buffer.String()\n\n\ttesterr_output(t, l, err, got, expected)\n}\n\nfunc Test_RunNotes(t *testing.T) {\n\tl := logger.New(Name, \"Test\", \"Command\", \"Run\", \"Notes\")\n\tl.SetLevel(logger.Info)\n\n\taction := ActionNotes\n\texpected := \"= Lablog -- Notes\\n\"\n\texpected += AsciiDocSettings + \"\\n\\n\"\n\texpected += `== TestNotes\n\n=== 2014-10-30T21:36:31.49146148+01:00\nTest1\n\n=== 2014-10-30T21:36:33.49871531+01:00\nTest2\n\n=== 2014-10-30T21:36:35.138412374+01:00\nTest3\n\n=== 2014-10-30T21:36:36.810478305+01:00\nTest4\n\n=== 2014-10-30T21:36:38.450479686+01:00\nTest5\n\n`\n\n\ttestCommandRunOutput(t, l, action, expected)\n}\n\nfunc Benchmark_RunNotes(b *testing.B) {\n\taction := ActionNotes\n\tcommand, _ := testCommand(action)\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tcommand.Run()\n\t}\n}\n\nfunc Test_RunNotesProject(t *testing.T) {\n\tl := logger.New(Name, \"Test\", \"Command\", \"Run\", \"Notes\", \"Project\")\n\tl.SetLevel(logger.Info)\n\n\taction := ActionNotes\n\tcommand, buffer := testCommand(action)\n\tcommand.Project = \"TestNotes\"\n\n\texpected := \"= TestNotes -- Notes\\n\"\n\texpected += AsciiDocSettings + \"\\n\\n\"\n\texpected += `== 2014-10-30T21:36:31.49146148+01:00\nTest1\n\n== 2014-10-30T21:36:33.49871531+01:00\nTest2\n\n== 2014-10-30T21:36:35.138412374+01:00\nTest3\n\n== 2014-10-30T21:36:36.810478305+01:00\nTest4\n\n== 2014-10-30T21:36:38.450479686+01:00\nTest5\n\n`\n\n\terr := command.Run()\n\tgot := buffer.String()\n\n\ttesterr_output(t, l, err, got, expected)\n}\n\nfunc Test_RunProjects(t *testing.T) {\n\tl := logger.New(Name, \"Test\", \"Command\", \"Run\", \"Projects\")\n\n\taction := ActionProjects\n\texpected := `TestNotes\nTestTodos\nTestTracks\n`\n\n\ttestCommandRunOutput(t, l, action, expected)\n}\n\nfunc Test_RunTodos(t *testing.T) {\n\tl := logger.New(Name, \"Test\", \"Command\", \"Run\", \"Todos\")\n\tl.SetLevel(logger.Info)\n\n\taction := ActionTodos\n\texpected := \"= Lablog -- Todos\\n\"\n\texpected += AsciiDocSettings + \"\\n\\n\"\n\texpected += `== TestTodos\n\n* Test1\n* Test2\n* Test3\n* Test4\n* Test5\n* Test7\n\n`\n\n\ttestCommandRunOutput(t, l, action, expected)\n}\n\nfunc Benchmark_RunTodos(b *testing.B) {\n\taction := ActionTodos\n\tcommand, _ := testCommand(action)\n\n\tb.ResetTimer()\n\tfor i := 0; i < b.N; i++ {\n\t\tcommand.Run()\n\t}\n}\n\nfunc Test_RunTracks(t *testing.T) {\n\tl := logger.New(Name, \"Test\", \"Command\", \"Run\", \"Tracks\")\n\tl.SetLevel(logger.Info)\n\n\taction := ActionTracks\n\texpected := \"= Lablog -- Tracks\\n\"\n\texpected += AsciiDocSettings + \"\\n\\n\"\n\texpected += `== TestTracks\n\n* 2014-11-01T00:46:27.250010094+01:00 -- Test1\n* 2014-11-01T00:46:31.186052306+01:00 -- Test2\n* 2014-11-01T00:46:32.794131714+01:00 -- Test3\n* 2014-11-01T00:46:34.322047221+01:00 -- Test4\n* 2014-11-01T00:46:35.658221386+01:00 -- Test5\n* 2014-11-01T00:46:38.385921461+01:00\n* 2014-11-01T00:46:51.833861322+01:00 -- Test6\n* 2014-11-01T00:46:53.713763133+01:00 -- Test6\n* 2014-11-01T00:46:55.609688812+01:00 -- Test7\n* 2014-11-01T00:46:56.713668447+01:00 -- Test7\n* 2014-11-01T00:46:57.953493565+01:00 -- Test7\n* 2014-11-01T00:54:54.778921093+01:00\n\n`\n\n\ttestCommandRunOutput(t, l, action, expected)\n}\n\nfunc Test_RunTracksActive(t *testing.T) {\n\tl := logger.New(Name, \"Test\", \"Command\", \"Run\", \"TracksActive\")\n\tl.SetLevel(logger.Info)\n\n\taction := ActionTracksActive\n\texpected := \"= Lablog -- TracksActive\\n\"\n\texpected += AsciiDocSettings + \"\\n\\n\"\n\texpected += `== TestTracks\n\n* 2014-11-01T00:46:27.250010094+01:00 -- Test1\n* 2014-11-01T00:46:31.186052306+01:00 -- Test2\n* 2014-11-01T00:46:32.794131714+01:00 -- Test3\n* 2014-11-01T00:46:34.322047221+01:00 -- Test4\n* 2014-11-01T00:46:35.658221386+01:00 -- Test5\n* 2014-11-01T00:46:57.953493565+01:00 -- Test7\n\n`\n\n\ttestCommandRunOutput(t, l, action, expected)\n}\n\nfunc Test_RunTracksDurations(t *testing.T) {\n\tl := logger.New(Name, \"Test\", \"Command\", \"Run\", \"TracksDurations\")\n\tl.SetLevel(logger.Info)\n\n\taction := ActionTracksDurations\n\texpected := \"= Lablog -- Durations\\n\"\n\texpected += AsciiDocSettings + \"\\n\\n\"\n\texpected += `== TestTracks\n\n* 8m16.392999632s\n* Test6 -- 1.879901811s\n* Test7 -- 1.103979635s\n\n`\n\n\ttestCommandRunOutput(t, l, action, expected)\n}\n<|endoftext|>"} {"text":"package windows_test\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/apcera\/nats\"\n\t\"github.com\/cloudfoundry\/bosh-agent\/agent\/action\"\n\n\t. \"github.com\/onsi\/gomega\"\n)\n\nconst (\n\tprepareTemplate = `{\n \"arguments\": [\n {\n \"deployment\": \"test\",\n \"job\": {\n \"name\": \"test-job\",\n \"template\": \"test-job\",\n \"templates\": [\n {\n \"name\": \"say-hello\",\n\t\t\t\t\t\t\"blobstore_id\": \"%s\",\n\t\t\t\t\t\t\"sha1\": \"eb9bebdb1f11494b27440ec6ccbefba00e713cd9\"\n }\n ]\n },\n \"packages\": {},\n \"rendered_templates_archive\": {\n \"blobstore_id\": \"%s\",\n \"sha1\": \"6760d464064ee036db9898c736ff71c6d4457792\"\n }\n }\n ],\n \"method\": \"prepare\",\n \"reply_to\": \"%s\"\n}`\n\terrandTemplate = `\n\t{\"protocol\":2,\"method\":\"run_errand\",\"arguments\":[],\"reply_to\":\"%s\"}\n\t`\n\tapplyTemplate = `\n{\n \"arguments\": [\n {\n \"configuration_hash\": \"foo\",\n \"deployment\": \"hello-world-windows-deployment\",\n \"id\": \"62236318-6632-4318-94c7-c3dd6e8e5698\",\n \"index\": 0,\n \"job\": {\n \"blobstore_id\": \"%[1]s\",\n \"name\": \"say-hello\",\n \"sha1\": \"eb6e6c8bd1b1bc3dd91c741ec5c628b61a4d8f1d\",\n \"template\": \"say-hello\",\n \"templates\": [\n {\n \"blobstore_id\": \"%[1]s\",\n \"name\": \"say-hello\",\n \"sha1\": \"eb6e6c8bd1b1bc3dd91c741ec5c628b61a4d8f1d\",\n \"version\": \"8fe0a4982b28ffe4e59d7c1e573c4f30a526770d\"\n }\n ],\n \"version\": \"8fe0a4982b28ffe4e59d7c1e573c4f30a526770d\"\n },\n \"networks\": {},\n\t\t\t\"rendered_templates_archive\": {\n\t\t\t\t\t\"blobstore_id\": \"%[2]s\",\n\t\t\t\t\t\"sha1\": \"6760d464064ee036db9898c736ff71c6d4457792\"\n\t\t\t}\n }\n ],\n \"method\": \"apply\",\n \"protocol\": 2,\n \"reply_to\": \"%[3]s\"\n}\n\t`\n\n\tfetchLogsTemplate = `\n{\n \"arguments\": [\n \"job\",\n null\n ],\n \"method\": \"fetch_logs\",\n \"protocol\": 2,\n \"reply_to\": \"%s\"\n}\n\t`\n\n\tstartTemplate = `\n{\n\t\"arguments\":[],\n\t\"method\":\"start\",\n\t\"protocol\":2,\n\t\"reply_to\":\"%s\"\n}\n\t`\n\tstopTemplate = `\n{\n\t\"protocol\":2,\n\t\"method\":\"stop\",\n\t\"arguments\":[],\n\t\"reply_to\":\"%s\"\n}\n\t`\n)\n\ntype natsClient struct {\n\tnc *nats.Conn\n\tsub *nats.Subscription\n}\n\nfunc NewNatsClient() *natsClient {\n\treturn &natsClient{}\n}\n\nfunc (n *natsClient) Setup() error {\n\tvar err error\n\tn.nc, err = nats.Connect(natsURI())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tn.sub, err = n.nc.SubscribeSync(senderID)\n\treturn err\n}\n\nfunc (n *natsClient) Cleanup() {\n\t_, err := n.RunStop()\n\tExpect(err).NotTo(HaveOccurred())\n\n\tn.nc.Close()\n}\n\nfunc (n *natsClient) PrepareJob(templateID, renderedTemplateArchiveID string) error {\n\tmessage := fmt.Sprintf(prepareTemplate, templateID, renderedTemplateArchiveID, senderID)\n\tprepareResponse, err := n.SendMessage(message)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcheck := n.checkStatus(prepareResponse[\"value\"][\"agent_task_id\"])\n\tEventually(check, 30*time.Second, 1*time.Second).Should(Equal(\"prepared\"))\n\n\tmessage = fmt.Sprintf(applyTemplate, templateID, renderedTemplateArchiveID, senderID)\n\tapplyResponse, err := n.SendMessage(message)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcheck = n.checkStatus(applyResponse[\"value\"][\"agent_task_id\"])\n\tEventually(check, 30*time.Second, 1*time.Second).Should(Equal(\"applied\"))\n\n\treturn nil\n}\n\nfunc (n *natsClient) RunStart() (map[string]string, error) {\n\tmessage := fmt.Sprintf(startTemplate, senderID)\n\trawResponse, err := n.SendRawMessage(message)\n\tif err != nil {\n\t\treturn map[string]string{}, err\n\t}\n\n\tresponse := map[string]string{}\n\terr = json.Unmarshal(rawResponse, &response)\n\treturn response, err\n}\n\nfunc (n *natsClient) RunStop() (map[string]map[string]string, error) {\n\tmessage := fmt.Sprintf(stopTemplate, senderID)\n\trawResponse, err := n.SendRawMessage(message)\n\tif err != nil {\n\t\treturn map[string]map[string]string{}, err\n\t}\n\n\tresponse := map[string]map[string]string{}\n\n\terr = json.Unmarshal(rawResponse, &response)\n\treturn response, err\n}\n\nfunc (n *natsClient) RunErrand() (map[string]map[string]string, error) {\n\tmessage := fmt.Sprintf(errandTemplate, senderID)\n\treturn n.SendMessage(message)\n}\n\nfunc (n *natsClient) RunFetchLogs() (map[string]map[string]string, error) {\n\tmessage := fmt.Sprintf(fetchLogsTemplate, senderID)\n\treturn n.SendMessage(message)\n}\n\nfunc (n *natsClient) CheckFetchLogsStatus(taskID string) func() (map[string]string, error) {\n\treturn func() (map[string]string, error) {\n\t\tvar result map[string]map[string]string\n\t\tvalueResponse, err := n.getTask(taskID)\n\t\tif err != nil {\n\t\t\treturn map[string]string{}, err\n\t\t}\n\n\t\terr = json.Unmarshal(valueResponse, &result)\n\t\tif err != nil {\n\t\t\treturn map[string]string{}, err\n\t\t}\n\n\t\treturn result[\"value\"], nil\n\t}\n}\n\nfunc (n *natsClient) CheckErrandResultStatus(taskID string) func() (action.ErrandResult, error) {\n\treturn func() (action.ErrandResult, error) {\n\t\tvar result map[string]action.ErrandResult\n\t\tvalueResponse, err := n.getTask(taskID)\n\t\tif err != nil {\n\t\t\treturn action.ErrandResult{}, err\n\t\t}\n\n\t\terr = json.Unmarshal(valueResponse, &result)\n\t\tif err != nil {\n\t\t\treturn action.ErrandResult{}, err\n\t\t}\n\n\t\treturn result[\"value\"], nil\n\t}\n}\n\nfunc (n *natsClient) SendRawMessage(message string) ([]byte, error) {\n\terr := n.nc.Publish(agentID, []byte(message))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\traw, err := n.sub.NextMsg(5 * time.Second)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn raw.Data, nil\n}\n\nfunc (n *natsClient) SendMessage(message string) (map[string]map[string]string, error) {\n\trawMessage, err := n.SendRawMessage(message)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := map[string]map[string]string{}\n\terr = json.Unmarshal(rawMessage, &response)\n\treturn response, err\n}\n\nfunc (n *natsClient) getTask(taskID string) ([]byte, error) {\n\tmessage := fmt.Sprintf(`{\"method\": \"get_task\", \"arguments\": [\"%s\"], \"reply_to\": \"%s\"}`, taskID, senderID)\n\treturn n.SendRawMessage(message)\n}\n\nfunc (n *natsClient) checkStatus(taskID string) func() (string, error) {\n\treturn func() (string, error) {\n\t\tvar result map[string]string\n\t\tvalueResponse, err := n.getTask(taskID)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\terr = json.Unmarshal(valueResponse, &result)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\treturn result[\"value\"], nil\n\t}\n}\nIncrease the timeout for receiving a response to the 'start' taskpackage windows_test\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com\/apcera\/nats\"\n\t\"github.com\/cloudfoundry\/bosh-agent\/agent\/action\"\n\n\t. \"github.com\/onsi\/gomega\"\n)\n\nconst (\n\tprepareTemplate = `{\n \"arguments\": [\n {\n \"deployment\": \"test\",\n \"job\": {\n \"name\": \"test-job\",\n \"template\": \"test-job\",\n \"templates\": [\n {\n \"name\": \"say-hello\",\n\t\t\t\t\t\t\"blobstore_id\": \"%s\",\n\t\t\t\t\t\t\"sha1\": \"eb9bebdb1f11494b27440ec6ccbefba00e713cd9\"\n }\n ]\n },\n \"packages\": {},\n \"rendered_templates_archive\": {\n \"blobstore_id\": \"%s\",\n \"sha1\": \"6760d464064ee036db9898c736ff71c6d4457792\"\n }\n }\n ],\n \"method\": \"prepare\",\n \"reply_to\": \"%s\"\n}`\n\terrandTemplate = `\n\t{\"protocol\":2,\"method\":\"run_errand\",\"arguments\":[],\"reply_to\":\"%s\"}\n\t`\n\tapplyTemplate = `\n{\n \"arguments\": [\n {\n \"configuration_hash\": \"foo\",\n \"deployment\": \"hello-world-windows-deployment\",\n \"id\": \"62236318-6632-4318-94c7-c3dd6e8e5698\",\n \"index\": 0,\n \"job\": {\n \"blobstore_id\": \"%[1]s\",\n \"name\": \"say-hello\",\n \"sha1\": \"eb6e6c8bd1b1bc3dd91c741ec5c628b61a4d8f1d\",\n \"template\": \"say-hello\",\n \"templates\": [\n {\n \"blobstore_id\": \"%[1]s\",\n \"name\": \"say-hello\",\n \"sha1\": \"eb6e6c8bd1b1bc3dd91c741ec5c628b61a4d8f1d\",\n \"version\": \"8fe0a4982b28ffe4e59d7c1e573c4f30a526770d\"\n }\n ],\n \"version\": \"8fe0a4982b28ffe4e59d7c1e573c4f30a526770d\"\n },\n \"networks\": {},\n\t\t\t\"rendered_templates_archive\": {\n\t\t\t\t\t\"blobstore_id\": \"%[2]s\",\n\t\t\t\t\t\"sha1\": \"6760d464064ee036db9898c736ff71c6d4457792\"\n\t\t\t}\n }\n ],\n \"method\": \"apply\",\n \"protocol\": 2,\n \"reply_to\": \"%[3]s\"\n}\n\t`\n\n\tfetchLogsTemplate = `\n{\n \"arguments\": [\n \"job\",\n null\n ],\n \"method\": \"fetch_logs\",\n \"protocol\": 2,\n \"reply_to\": \"%s\"\n}\n\t`\n\n\tstartTemplate = `\n{\n\t\"arguments\":[],\n\t\"method\":\"start\",\n\t\"protocol\":2,\n\t\"reply_to\":\"%s\"\n}\n\t`\n\tstopTemplate = `\n{\n\t\"protocol\":2,\n\t\"method\":\"stop\",\n\t\"arguments\":[],\n\t\"reply_to\":\"%s\"\n}\n\t`\n)\n\ntype natsClient struct {\n\tnc *nats.Conn\n\tsub *nats.Subscription\n}\n\nfunc NewNatsClient() *natsClient {\n\treturn &natsClient{}\n}\n\nfunc (n *natsClient) Setup() error {\n\tvar err error\n\tn.nc, err = nats.Connect(natsURI())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tn.sub, err = n.nc.SubscribeSync(senderID)\n\treturn err\n}\n\nfunc (n *natsClient) Cleanup() {\n\terr := n.RunStop()\n\tExpect(err).NotTo(HaveOccurred())\n\n\tn.nc.Close()\n}\n\nfunc (n *natsClient) PrepareJob(templateID, renderedTemplateArchiveID string) error {\n\tmessage := fmt.Sprintf(prepareTemplate, templateID, renderedTemplateArchiveID, senderID)\n\tprepareResponse, err := n.SendMessage(message)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcheck := n.checkStatus(prepareResponse[\"value\"][\"agent_task_id\"])\n\tEventually(check, 30*time.Second, 1*time.Second).Should(Equal(\"prepared\"))\n\n\tmessage = fmt.Sprintf(applyTemplate, templateID, renderedTemplateArchiveID, senderID)\n\tapplyResponse, err := n.SendMessage(message)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcheck = n.checkStatus(applyResponse[\"value\"][\"agent_task_id\"])\n\tEventually(check, 30*time.Second, 1*time.Second).Should(Equal(\"applied\"))\n\n\treturn nil\n}\n\nfunc (n *natsClient) RunStart() (map[string]string, error) {\n\tmessage := fmt.Sprintf(startTemplate, senderID)\n\trawResponse, err := n.SendRawMessageWithTimeout(message, time.Minute)\n\tif err != nil {\n\t\treturn map[string]string{}, err\n\t}\n\n\tresponse := map[string]string{}\n\terr = json.Unmarshal(rawResponse, &response)\n\treturn response, err\n}\n\nfunc (n *natsClient) RunStop() error {\n\tmessage := fmt.Sprintf(stopTemplate, senderID)\n\trawResponse, err := n.SendRawMessage(message)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tresponse := map[string]map[string]string{}\n\n\terr = json.Unmarshal(rawResponse, &response)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcheck := n.checkStatus(response[\"value\"][\"agent_task_id\"])\n\tEventually(check, 30*time.Second, 1*time.Second).Should(Equal(\"stopped\"))\n\n\treturn nil\n}\n\nfunc (n *natsClient) RunErrand() (map[string]map[string]string, error) {\n\tmessage := fmt.Sprintf(errandTemplate, senderID)\n\treturn n.SendMessage(message)\n}\n\nfunc (n *natsClient) RunFetchLogs() (map[string]map[string]string, error) {\n\tmessage := fmt.Sprintf(fetchLogsTemplate, senderID)\n\treturn n.SendMessage(message)\n}\n\nfunc (n *natsClient) CheckFetchLogsStatus(taskID string) func() (map[string]string, error) {\n\treturn func() (map[string]string, error) {\n\t\tvar result map[string]map[string]string\n\t\tvalueResponse, err := n.getTask(taskID)\n\t\tif err != nil {\n\t\t\treturn map[string]string{}, err\n\t\t}\n\n\t\terr = json.Unmarshal(valueResponse, &result)\n\t\tif err != nil {\n\t\t\treturn map[string]string{}, err\n\t\t}\n\n\t\treturn result[\"value\"], nil\n\t}\n}\n\nfunc (n *natsClient) CheckErrandResultStatus(taskID string) func() (action.ErrandResult, error) {\n\treturn func() (action.ErrandResult, error) {\n\t\tvar result map[string]action.ErrandResult\n\t\tvalueResponse, err := n.getTask(taskID)\n\t\tif err != nil {\n\t\t\treturn action.ErrandResult{}, err\n\t\t}\n\n\t\terr = json.Unmarshal(valueResponse, &result)\n\t\tif err != nil {\n\t\t\treturn action.ErrandResult{}, err\n\t\t}\n\n\t\treturn result[\"value\"], nil\n\t}\n}\n\nfunc (n *natsClient) SendRawMessageWithTimeout(message string, timeout time.Duration) ([]byte, error) {\n\terr := n.nc.Publish(agentID, []byte(message))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\traw, err := n.sub.NextMsg(timeout)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn raw.Data, nil\n}\n\nfunc (n *natsClient) SendRawMessage(message string) ([]byte, error) {\n\treturn n.SendRawMessageWithTimeout(message, 5*time.Second)\n}\n\nfunc (n *natsClient) SendMessage(message string) (map[string]map[string]string, error) {\n\trawMessage, err := n.SendRawMessage(message)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := map[string]map[string]string{}\n\terr = json.Unmarshal(rawMessage, &response)\n\treturn response, err\n}\n\nfunc (n *natsClient) getTask(taskID string) ([]byte, error) {\n\tmessage := fmt.Sprintf(`{\"method\": \"get_task\", \"arguments\": [\"%s\"], \"reply_to\": \"%s\"}`, taskID, senderID)\n\treturn n.SendRawMessage(message)\n}\n\nfunc (n *natsClient) checkStatus(taskID string) func() (string, error) {\n\treturn func() (string, error) {\n\t\tvar result map[string]string\n\t\tvalueResponse, err := n.getTask(taskID)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\terr = json.Unmarshal(valueResponse, &result)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\treturn result[\"value\"], nil\n\t}\n}\n<|endoftext|>"} {"text":"package common\n\nimport (\n\t\"crypto\/hmac\"\n\t\"crypto\/sha256\"\n\t\"encoding\/base64\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"math\/rand\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/sirupsen\/logrus\"\n)\n\nconst (\n\tRequestMethodGET = \"GET\"\n\tRequestMethodPOST = \"POST\"\n\n\tSignatureMethodHMacSha256 = \"HmacSHA256\"\n)\n\ntype Client struct {\n\t*http.Client\n\n\tcredential CredentialInterface\n\topts Opts\n}\n\ntype Opts struct {\n\tMethod string\n\tRegion string\n\tHost string\n\tPath string\n\tSignatureMethod string\n\tSchema string\n\n\tLogger *logrus.Logger\n}\n\ntype CredentialInterface interface {\n\tGetSecretId() (string, error)\n\tGetSecretKey() (string, error)\n\n\tValues() (CredentialValues, error)\n}\n\ntype CredentialValues map[string]string\n\ntype Credential struct {\n\tSecretId string\n\tSecretKey string\n}\n\nfunc (cred Credential) GetSecretId() (string, error) {\n\treturn cred.SecretId, nil\n}\n\nfunc (cred Credential) GetSecretKey() (string, error) {\n\treturn cred.SecretKey, nil\n}\n\nfunc (cred Credential) Values() (CredentialValues, error) {\n\treturn CredentialValues{}, nil\n}\n\nfunc NewClient(credential CredentialInterface, opts Opts) (*Client, error) {\n\tif opts.Method == \"\" {\n\t\topts.Method = RequestMethodGET\n\t}\n\tif opts.SignatureMethod == \"\" {\n\t\topts.SignatureMethod = SignatureMethodHMacSha256\n\t}\n\tif opts.Schema == \"\" {\n\t\topts.Schema = \"https\"\n\t}\n\tif opts.Logger == nil {\n\t\topts.Logger = logrus.New()\n\t}\n\treturn &Client{\n\t\t&http.Client{},\n\t\tcredential,\n\t\topts,\n\t}, nil\n}\n\nfunc (client *Client) Invoke(action string, args interface{}, response interface{}) error {\n\tswitch client.opts.Method {\n\tcase \"GET\":\n\t\treturn client.InvokeWithGET(action, args, response)\n\tdefault:\n\t\treturn client.InvokeWithPOST(action, args, response)\n\t}\n}\n\nfunc (client *Client) initCommonArgs(args *url.Values) {\n\targs.Set(\"Region\", client.opts.Region)\n\targs.Set(\"Timestamp\", fmt.Sprint(uint(time.Now().Unix())))\n\targs.Set(\"Nonce\", fmt.Sprint(uint(rand.Int())))\n\targs.Set(\"SignatureMethod\", client.opts.SignatureMethod)\n}\n\nfunc (client *Client) signGetRequest(secretId, secretKey string, values *url.Values) string {\n\n\tvalues.Set(\"SecretId\", secretId)\n\n\tkeys := make([]string, 0, len(*values))\n\tfor k := range *values {\n\t\tkeys = append(keys, k)\n\t}\n\tsort.Strings(keys)\n\tkvs := make([]string, 0, len(keys))\n\tfor _, k := range keys {\n\t\tkvs = append(kvs, fmt.Sprintf(\"%s=%s\", k, values.Get(k)))\n\t}\n\tqueryStr := strings.Join(kvs, \"&\")\n\treqStr := fmt.Sprintf(\"GET%s%s?%s\", client.opts.Host, client.opts.Path, queryStr)\n\n\tmac := hmac.New(sha256.New, []byte(secretKey))\n\tmac.Write([]byte(reqStr))\n\tsignature := mac.Sum(nil)\n\n\tb64Encoded := base64.StdEncoding.EncodeToString(signature)\n\n\treturn b64Encoded\n}\n\nfunc (client *Client) InvokeWithGET(action string, args interface{}, response interface{}) error {\n\treqValues := url.Values{}\n\n\tcredValues, err := client.credential.Values()\n\tif err != nil {\n\t\treturn makeClientError(err)\n\t}\n\n\tfor k, v := range credValues {\n\t\treqValues.Set(k, v)\n\t}\n\n\terr = EncodeStruct(args, &reqValues)\n\tif err != nil {\n\t\treturn makeClientError(err)\n\t}\n\treqValues.Set(\"Action\", action)\n\tclient.initCommonArgs(&reqValues)\n\n\tsecretId, err := client.credential.GetSecretId()\n\tif err != nil {\n\t\treturn makeClientError(err)\n\t}\n\tsecretKey, err := client.credential.GetSecretKey()\n\tif err != nil {\n\t\treturn makeClientError(err)\n\t}\n\n\tsignature := client.signGetRequest(secretId, secretKey, &reqValues)\n\treqValues.Set(\"Signature\", signature)\n\n\treqQuery := reqValues.Encode()\n\n\treq, err := http.NewRequest(\n\t\t\"GET\",\n\t\tfmt.Sprintf(\"%s:\/\/%s%s?%s\", client.opts.Schema, client.opts.Host, client.opts.Path, reqQuery),\n\t\tnil,\n\t)\n\n\tif err != nil {\n\t\treturn makeClientError(err)\n\t}\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn makeClientError(err)\n\t}\n\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn makeClientError(err)\n\t}\n\n\tclient.opts.Logger.WithField(\"Action\", action).Infof(\n\t\t\"%s %s %d %s\", \"GET\", req.URL, resp.StatusCode, body,\n\t)\n\n\tlegacyErrorResponse := LegacyAPIError{}\n\n\tif err = json.Unmarshal(body, &legacyErrorResponse); err != nil {\n\t\treturn makeClientError(err)\n\t}\n\n\tversionErrorResponse := VersionAPIError{}\n\n\tif err = json.Unmarshal(body, &versionErrorResponse); err != nil {\n\t\treturn makeClientError(err)\n\t}\n\n\tif legacyErrorResponse.Code != NoErr || (legacyErrorResponse.CodeDesc != \"\" && legacyErrorResponse.CodeDesc != NoErrCodeDesc) {\n\t\tclient.opts.Logger.WithField(\"Action\", action).Errorf(\n\t\t\t\"%s %s %d %s %v\", \"GET\", req.URL, resp.StatusCode, body, legacyErrorResponse,\n\t\t)\n\t\treturn legacyErrorResponse\n\t}\n\n\tif versionErrorResponse.Response.Error.Code != \"\" {\n\t\tclient.opts.Logger.WithField(\"Action\", action).Errorf(\n\t\t\t\"%s %s %d %s %v\", \"GET\", req.URL, resp.StatusCode, body, versionErrorResponse,\n\t\t)\n\t\treturn versionErrorResponse\n\t}\n\n\tif err = json.Unmarshal(body, response); err != nil {\n\t\treturn makeClientError(err)\n\t}\n\n\treturn nil\n}\n\nfunc (client *Client) InvokeWithPOST(action string, args interface{}, response interface{}) error {\n\treturn nil\n}\nadd client timeoutpackage common\n\nimport (\n\t\"crypto\/hmac\"\n\t\"crypto\/sha256\"\n\t\"encoding\/base64\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"math\/rand\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"sort\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/sirupsen\/logrus\"\n)\n\nconst (\n\tRequestMethodGET = \"GET\"\n\tRequestMethodPOST = \"POST\"\n\n\tSignatureMethodHMacSha256 = \"HmacSHA256\"\n)\n\ntype Client struct {\n\t*http.Client\n\n\tcredential CredentialInterface\n\topts Opts\n}\n\ntype Opts struct {\n\tMethod string\n\tRegion string\n\tHost string\n\tPath string\n\tSignatureMethod string\n\tSchema string\n\n\tLogger *logrus.Logger\n}\n\ntype CredentialInterface interface {\n\tGetSecretId() (string, error)\n\tGetSecretKey() (string, error)\n\n\tValues() (CredentialValues, error)\n}\n\ntype CredentialValues map[string]string\n\ntype Credential struct {\n\tSecretId string\n\tSecretKey string\n}\n\nfunc (cred Credential) GetSecretId() (string, error) {\n\treturn cred.SecretId, nil\n}\n\nfunc (cred Credential) GetSecretKey() (string, error) {\n\treturn cred.SecretKey, nil\n}\n\nfunc (cred Credential) Values() (CredentialValues, error) {\n\treturn CredentialValues{}, nil\n}\n\nfunc NewClient(credential CredentialInterface, opts Opts) (*Client, error) {\n\tif opts.Method == \"\" {\n\t\topts.Method = RequestMethodGET\n\t}\n\tif opts.SignatureMethod == \"\" {\n\t\topts.SignatureMethod = SignatureMethodHMacSha256\n\t}\n\tif opts.Schema == \"\" {\n\t\topts.Schema = \"https\"\n\t}\n\tif opts.Logger == nil {\n\t\topts.Logger = logrus.New()\n\t}\n\treturn &Client{\n\t\t&http.Client{\n\t\t\tTimeout: time.Second * 60,\n\t\t},\n\t\tcredential,\n\t\topts,\n\t}, nil\n}\n\nfunc (client *Client) Invoke(action string, args interface{}, response interface{}) error {\n\tswitch client.opts.Method {\n\tcase \"GET\":\n\t\treturn client.InvokeWithGET(action, args, response)\n\tdefault:\n\t\treturn client.InvokeWithPOST(action, args, response)\n\t}\n}\n\nfunc (client *Client) initCommonArgs(args *url.Values) {\n\targs.Set(\"Region\", client.opts.Region)\n\targs.Set(\"Timestamp\", fmt.Sprint(uint(time.Now().Unix())))\n\targs.Set(\"Nonce\", fmt.Sprint(uint(rand.Int())))\n\targs.Set(\"SignatureMethod\", client.opts.SignatureMethod)\n}\n\nfunc (client *Client) signGetRequest(secretId, secretKey string, values *url.Values) string {\n\n\tvalues.Set(\"SecretId\", secretId)\n\n\tkeys := make([]string, 0, len(*values))\n\tfor k := range *values {\n\t\tkeys = append(keys, k)\n\t}\n\tsort.Strings(keys)\n\tkvs := make([]string, 0, len(keys))\n\tfor _, k := range keys {\n\t\tkvs = append(kvs, fmt.Sprintf(\"%s=%s\", k, values.Get(k)))\n\t}\n\tqueryStr := strings.Join(kvs, \"&\")\n\treqStr := fmt.Sprintf(\"GET%s%s?%s\", client.opts.Host, client.opts.Path, queryStr)\n\n\tmac := hmac.New(sha256.New, []byte(secretKey))\n\tmac.Write([]byte(reqStr))\n\tsignature := mac.Sum(nil)\n\n\tb64Encoded := base64.StdEncoding.EncodeToString(signature)\n\n\treturn b64Encoded\n}\n\nfunc (client *Client) InvokeWithGET(action string, args interface{}, response interface{}) error {\n\treqValues := url.Values{}\n\n\tcredValues, err := client.credential.Values()\n\tif err != nil {\n\t\treturn makeClientError(err)\n\t}\n\n\tfor k, v := range credValues {\n\t\treqValues.Set(k, v)\n\t}\n\n\terr = EncodeStruct(args, &reqValues)\n\tif err != nil {\n\t\treturn makeClientError(err)\n\t}\n\treqValues.Set(\"Action\", action)\n\tclient.initCommonArgs(&reqValues)\n\n\tsecretId, err := client.credential.GetSecretId()\n\tif err != nil {\n\t\treturn makeClientError(err)\n\t}\n\tsecretKey, err := client.credential.GetSecretKey()\n\tif err != nil {\n\t\treturn makeClientError(err)\n\t}\n\n\tsignature := client.signGetRequest(secretId, secretKey, &reqValues)\n\treqValues.Set(\"Signature\", signature)\n\n\treqQuery := reqValues.Encode()\n\n\treq, err := http.NewRequest(\n\t\t\"GET\",\n\t\tfmt.Sprintf(\"%s:\/\/%s%s?%s\", client.opts.Schema, client.opts.Host, client.opts.Path, reqQuery),\n\t\tnil,\n\t)\n\n\tif err != nil {\n\t\treturn makeClientError(err)\n\t}\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn makeClientError(err)\n\t}\n\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn makeClientError(err)\n\t}\n\n\tclient.opts.Logger.WithField(\"Action\", action).Infof(\n\t\t\"%s %s %d %s\", \"GET\", req.URL, resp.StatusCode, body,\n\t)\n\n\tlegacyErrorResponse := LegacyAPIError{}\n\n\tif err = json.Unmarshal(body, &legacyErrorResponse); err != nil {\n\t\treturn makeClientError(err)\n\t}\n\n\tversionErrorResponse := VersionAPIError{}\n\n\tif err = json.Unmarshal(body, &versionErrorResponse); err != nil {\n\t\treturn makeClientError(err)\n\t}\n\n\tif legacyErrorResponse.Code != NoErr || (legacyErrorResponse.CodeDesc != \"\" && legacyErrorResponse.CodeDesc != NoErrCodeDesc) {\n\t\tclient.opts.Logger.WithField(\"Action\", action).Errorf(\n\t\t\t\"%s %s %d %s %v\", \"GET\", req.URL, resp.StatusCode, body, legacyErrorResponse,\n\t\t)\n\t\treturn legacyErrorResponse\n\t}\n\n\tif versionErrorResponse.Response.Error.Code != \"\" {\n\t\tclient.opts.Logger.WithField(\"Action\", action).Errorf(\n\t\t\t\"%s %s %d %s %v\", \"GET\", req.URL, resp.StatusCode, body, versionErrorResponse,\n\t\t)\n\t\treturn versionErrorResponse\n\t}\n\n\tif err = json.Unmarshal(body, response); err != nil {\n\t\treturn makeClientError(err)\n\t}\n\n\treturn nil\n}\n\nfunc (client *Client) InvokeWithPOST(action string, args interface{}, response interface{}) error {\n\treturn nil\n}\n<|endoftext|>"} {"text":"\/\/ Package common contains common utilities that are shared among other packages.\n\/\/ See each sub-package for detail.\npackage common\n\nimport (\n\t\"fmt\"\n\t\"go\/build\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"v2ray.com\/core\/common\/errors\"\n)\n\n\/\/go:generate errorgen\n\nvar (\n\t\/\/ ErrNoClue is for the situation that existing information is not enough to make a decision. For example, Router may return this error when there is no suitable route.\n\tErrNoClue = errors.New(\"not enough information for making a decision\")\n)\n\n\/\/ Must panics if err is not nil.\nfunc Must(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\n\/\/ Must2 panics if the second parameter is not nil, otherwise returns the first parameter.\nfunc Must2(v interface{}, err error) interface{} {\n\tMust(err)\n\treturn v\n}\n\n\/\/ Error2 returns the err from the 2nd parameter.\nfunc Error2(v interface{}, err error) error {\n\treturn err\n}\n\n\/\/ envFile returns the name of the Go environment configuration file.\n\/\/ Copy from https:\/\/github.com\/golang\/go\/blob\/c4f2a9788a7be04daf931ac54382fbe2cb754938\/src\/cmd\/go\/internal\/cfg\/cfg.go#L150-L166\nfunc envFile() (string, error) {\n\tif file := os.Getenv(\"GOENV\"); file != \"\" {\n\t\tif file == \"off\" {\n\t\t\treturn \"\", fmt.Errorf(\"GOENV=off\")\n\t\t}\n\t\treturn file, nil\n\t}\n\tdir, err := os.UserConfigDir()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif dir == \"\" {\n\t\treturn \"\", fmt.Errorf(\"missing user-config dir\")\n\t}\n\treturn filepath.Join(dir, \"go\", \"env\"), nil\n}\n\n\/\/ GetRuntimeEnv returns the value of runtime environment variable,\n\/\/ that is set by running following command: `go env -w key=value`.\nfunc GetRuntimeEnv(key string) (string, error) {\n\tfile, err := envFile()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif file == \"\" {\n\t\treturn \"\", fmt.Errorf(\"missing runtime env file\")\n\t}\n\tvar data []byte\n\tvar runtimeEnv string\n\tdata, readErr := ioutil.ReadFile(file)\n\tif readErr != nil {\n\t\treturn \"\", readErr\n\t}\n\tenvStrings := strings.Split(string(data), \"\\n\")\n\tfor _, envItem := range envStrings {\n\t\tenvItem = strings.TrimSuffix(envItem, \"\\r\")\n\t\tenvKeyValue := strings.Split(envItem, \"=\")\n\t\tif strings.EqualFold(strings.TrimSpace(envKeyValue[0]), key) {\n\t\t\truntimeEnv = strings.TrimSpace(envKeyValue[1])\n\t\t}\n\t}\n\treturn runtimeEnv, nil\n}\n\n\/\/ GetGOBIN returns GOBIN environment variable as a string. It will NOT be empty.\nfunc GetGOBIN() string {\n\t\/\/ The one set by user explicitly by `export GOBIN=\/path` or `env GOBIN=\/path command`\n\tGOBIN := os.Getenv(\"GOBIN\")\n\tif GOBIN == \"\" {\n\t\tvar err error\n\t\t\/\/ The one set by user by running `go env -w GOBIN=\/path`\n\t\tGOBIN, err = GetRuntimeEnv(\"GOBIN\")\n\t\tif err != nil {\n\t\t\t\/\/ The default one that Golang uses\n\t\t\treturn filepath.Join(build.Default.GOPATH, \"bin\")\n\t\t}\n\t\tif GOBIN == \"\" {\n\t\t\treturn filepath.Join(build.Default.GOPATH, \"bin\")\n\t\t}\n\t\treturn GOBIN\n\t}\n\treturn GOBIN\n}\n\n\/\/ GetGOPATH returns GOPATH environment variable as a string. It will NOT be empty.\nfunc GetGOPATH() string {\n\t\/\/ The one set by user explicitly by `export GOPATH=\/path` or `env GOPATH=\/path command`\n\tGOPATH := os.Getenv(\"GOPATH\")\n\tif GOPATH == \"\" {\n\t\tvar err error\n\t\t\/\/ The one set by user by running `go env -w GOPATH=\/path`\n\t\tGOPATH, err = GetRuntimeEnv(\"GOPATH\")\n\t\tif err != nil {\n\t\t\t\/\/ The default one that Golang uses\n\t\t\treturn build.Default.GOPATH\n\t\t}\n\t\tif GOPATH == \"\" {\n\t\t\treturn build.Default.GOPATH\n\t\t}\n\t\treturn GOPATH\n\t}\n\treturn GOPATH\n}\n\n\/\/ GetModuleName returns the value of module in `go.mod` file.\nfunc GetModuleName(pathToProjectRoot string) (string, error) {\n\tgomodPath := filepath.Join(pathToProjectRoot, \"go.mod\")\n\tgomodBytes, err := ioutil.ReadFile(gomodPath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tgomodContent := string(gomodBytes)\n\tmoduleIdx := strings.Index(gomodContent, \"module \")\n\tnewLineIdx := strings.Index(gomodContent, \"\\n\")\n\n\tvar moduleName string\n\tif moduleIdx >= 0 {\n\t\tif newLineIdx >= 0 {\n\t\t\tmoduleName = strings.TrimSpace(gomodContent[moduleIdx+6 : newLineIdx])\n\t\t\tmoduleName = strings.TrimSuffix(moduleName, \"\\r\")\n\t\t} else {\n\t\t\tmoduleName = strings.TrimSpace(gomodContent[moduleIdx+6:])\n\t\t}\n\t} else {\n\t\treturn \"\", fmt.Errorf(\"can not get module path in `%s`\", gomodPath)\n\t}\n\treturn moduleName, nil\n}\nSupport to read go.mod recursively to get module path\/\/ Package common contains common utilities that are shared among other packages.\n\/\/ See each sub-package for detail.\npackage common\n\nimport (\n\t\"fmt\"\n\t\"go\/build\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"v2ray.com\/core\/common\/errors\"\n)\n\n\/\/go:generate errorgen\n\nvar (\n\t\/\/ ErrNoClue is for the situation that existing information is not enough to make a decision. For example, Router may return this error when there is no suitable route.\n\tErrNoClue = errors.New(\"not enough information for making a decision\")\n)\n\n\/\/ Must panics if err is not nil.\nfunc Must(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\n\/\/ Must2 panics if the second parameter is not nil, otherwise returns the first parameter.\nfunc Must2(v interface{}, err error) interface{} {\n\tMust(err)\n\treturn v\n}\n\n\/\/ Error2 returns the err from the 2nd parameter.\nfunc Error2(v interface{}, err error) error {\n\treturn err\n}\n\n\/\/ envFile returns the name of the Go environment configuration file.\n\/\/ Copy from https:\/\/github.com\/golang\/go\/blob\/c4f2a9788a7be04daf931ac54382fbe2cb754938\/src\/cmd\/go\/internal\/cfg\/cfg.go#L150-L166\nfunc envFile() (string, error) {\n\tif file := os.Getenv(\"GOENV\"); file != \"\" {\n\t\tif file == \"off\" {\n\t\t\treturn \"\", fmt.Errorf(\"GOENV=off\")\n\t\t}\n\t\treturn file, nil\n\t}\n\tdir, err := os.UserConfigDir()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif dir == \"\" {\n\t\treturn \"\", fmt.Errorf(\"missing user-config dir\")\n\t}\n\treturn filepath.Join(dir, \"go\", \"env\"), nil\n}\n\n\/\/ GetRuntimeEnv returns the value of runtime environment variable,\n\/\/ that is set by running following command: `go env -w key=value`.\nfunc GetRuntimeEnv(key string) (string, error) {\n\tfile, err := envFile()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif file == \"\" {\n\t\treturn \"\", fmt.Errorf(\"missing runtime env file\")\n\t}\n\tvar data []byte\n\tvar runtimeEnv string\n\tdata, readErr := ioutil.ReadFile(file)\n\tif readErr != nil {\n\t\treturn \"\", readErr\n\t}\n\tenvStrings := strings.Split(string(data), \"\\n\")\n\tfor _, envItem := range envStrings {\n\t\tenvItem = strings.TrimSuffix(envItem, \"\\r\")\n\t\tenvKeyValue := strings.Split(envItem, \"=\")\n\t\tif strings.EqualFold(strings.TrimSpace(envKeyValue[0]), key) {\n\t\t\truntimeEnv = strings.TrimSpace(envKeyValue[1])\n\t\t}\n\t}\n\treturn runtimeEnv, nil\n}\n\n\/\/ GetGOBIN returns GOBIN environment variable as a string. It will NOT be empty.\nfunc GetGOBIN() string {\n\t\/\/ The one set by user explicitly by `export GOBIN=\/path` or `env GOBIN=\/path command`\n\tGOBIN := os.Getenv(\"GOBIN\")\n\tif GOBIN == \"\" {\n\t\tvar err error\n\t\t\/\/ The one set by user by running `go env -w GOBIN=\/path`\n\t\tGOBIN, err = GetRuntimeEnv(\"GOBIN\")\n\t\tif err != nil {\n\t\t\t\/\/ The default one that Golang uses\n\t\t\treturn filepath.Join(build.Default.GOPATH, \"bin\")\n\t\t}\n\t\tif GOBIN == \"\" {\n\t\t\treturn filepath.Join(build.Default.GOPATH, \"bin\")\n\t\t}\n\t\treturn GOBIN\n\t}\n\treturn GOBIN\n}\n\n\/\/ GetGOPATH returns GOPATH environment variable as a string. It will NOT be empty.\nfunc GetGOPATH() string {\n\t\/\/ The one set by user explicitly by `export GOPATH=\/path` or `env GOPATH=\/path command`\n\tGOPATH := os.Getenv(\"GOPATH\")\n\tif GOPATH == \"\" {\n\t\tvar err error\n\t\t\/\/ The one set by user by running `go env -w GOPATH=\/path`\n\t\tGOPATH, err = GetRuntimeEnv(\"GOPATH\")\n\t\tif err != nil {\n\t\t\t\/\/ The default one that Golang uses\n\t\t\treturn build.Default.GOPATH\n\t\t}\n\t\tif GOPATH == \"\" {\n\t\t\treturn build.Default.GOPATH\n\t\t}\n\t\treturn GOPATH\n\t}\n\treturn GOPATH\n}\n\n\/\/ GetModuleName returns the value of module in `go.mod` file.\nfunc GetModuleName(pathToProjectRoot string) (string, error) {\n\tvar moduleName string\n\tloopPath := pathToProjectRoot\n\tfor {\n\t\tif idx := strings.LastIndex(loopPath, string(filepath.Separator)); idx >= 0 {\n\t\t\tgomodPath := filepath.Join(loopPath, \"go.mod\")\n\t\t\tgomodBytes, err := ioutil.ReadFile(gomodPath)\n\t\t\tif err != nil {\n\t\t\t\tloopPath = loopPath[:idx]\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tgomodContent := string(gomodBytes)\n\t\t\tmoduleIdx := strings.Index(gomodContent, \"module \")\n\t\t\tnewLineIdx := strings.Index(gomodContent, \"\\n\")\n\n\t\t\tif moduleIdx >= 0 {\n\t\t\t\tif newLineIdx >= 0 {\n\t\t\t\t\tmoduleName = strings.TrimSpace(gomodContent[moduleIdx+6 : newLineIdx])\n\t\t\t\t\tmoduleName = strings.TrimSuffix(moduleName, \"\\r\")\n\t\t\t\t} else {\n\t\t\t\t\tmoduleName = strings.TrimSpace(gomodContent[moduleIdx+6:])\n\t\t\t\t}\n\t\t\t\treturn moduleName, nil\n\t\t\t}\n\t\t\treturn \"\", fmt.Errorf(\"can not get module path in `%s`\", gomodPath)\n\t\t}\n\t\tbreak\n\t}\n\treturn moduleName, fmt.Errorf(\"no `go.mod` file in every parent directory of `%s`\", pathToProjectRoot)\n}\n<|endoftext|>"} {"text":"\/\/ Package common contains common types, constants and functions used over different demoinfocs packages.\n\/\/ Some constants prefixes:\n\/\/ MVPReason - the reason why someone got the MVP award.\n\/\/ HG - HitGroup - where a bullet hit the player.\n\/\/ EE - EquipmentElement - basically the weapon identifiers.\n\/\/ RER - RoundEndReason - why the round ended (bomb exploded, defused, time ran out. . .).\n\/\/ EC - EquipmentClass - type of equipment (pistol, smg, heavy. . .).\npackage common\n\nimport (\n\t\"strings\"\n)\n\nvar eqNameToWeapon map[string]EquipmentElement\n\nvar eqElementToName map[EquipmentElement]string\n\nfunc init() {\n\tinitEqNameToWeapon()\n\tinitEqEementToName()\n}\n\nfunc initEqNameToWeapon() {\n\teqNameToWeapon = make(map[string]EquipmentElement)\n\n\teqNameToWeapon[\"ak47\"] = EqAK47\n\teqNameToWeapon[\"aug\"] = EqAUG\n\teqNameToWeapon[\"awp\"] = EqAWP\n\teqNameToWeapon[\"bizon\"] = EqBizon\n\teqNameToWeapon[\"c4\"] = EqBomb\n\teqNameToWeapon[\"deagle\"] = EqDeagle\n\teqNameToWeapon[\"decoy\"] = EqDecoy\n\teqNameToWeapon[\"decoygrenade\"] = EqDecoy\n\teqNameToWeapon[\"decoyprojectile\"] = EqDecoy\n\teqNameToWeapon[\"elite\"] = EqDualBarettas\n\teqNameToWeapon[\"famas\"] = EqFamas\n\teqNameToWeapon[\"fiveseven\"] = EqFiveSeven\n\teqNameToWeapon[\"flashbang\"] = EqFlash\n\teqNameToWeapon[\"g3sg1\"] = EqG3SG1\n\teqNameToWeapon[\"galil\"] = EqGalil\n\teqNameToWeapon[\"galilar\"] = EqGalil\n\teqNameToWeapon[\"glock\"] = EqGlock\n\teqNameToWeapon[\"hegrenade\"] = EqHE\n\teqNameToWeapon[\"hkp2000\"] = EqP2000\n\teqNameToWeapon[\"incgrenade\"] = EqIncendiary\n\teqNameToWeapon[\"incendiarygrenade\"] = EqIncendiary\n\teqNameToWeapon[\"m249\"] = EqM249\n\teqNameToWeapon[\"m4a1\"] = EqM4A4\n\teqNameToWeapon[\"mac10\"] = EqMac10\n\teqNameToWeapon[\"mag7\"] = EqSwag7\n\teqNameToWeapon[\"molotov\"] = EqMolotov\n\teqNameToWeapon[\"molotovgrenade\"] = EqMolotov\n\teqNameToWeapon[\"molotovprojectile\"] = EqMolotov\n\teqNameToWeapon[\"mp7\"] = EqMP7\n\teqNameToWeapon[\"mp9\"] = EqMP9\n\teqNameToWeapon[\"negev\"] = EqNegev\n\teqNameToWeapon[\"nova\"] = EqNova\n\teqNameToWeapon[\"p250\"] = EqP250\n\teqNameToWeapon[\"p90\"] = EqP90\n\teqNameToWeapon[\"sawedoff\"] = EqSawedOff\n\teqNameToWeapon[\"scar20\"] = EqScar20\n\teqNameToWeapon[\"sg556\"] = EqSG556\n\teqNameToWeapon[\"smokegrenade\"] = EqSmoke\n\teqNameToWeapon[\"smokegrenadeprojectile\"] = EqSmoke\n\teqNameToWeapon[\"taser\"] = EqZeus\n\teqNameToWeapon[\"tec9\"] = EqTec9\n\teqNameToWeapon[\"ump45\"] = EqUMP\n\teqNameToWeapon[\"xm1014\"] = EqXM1014\n\teqNameToWeapon[\"m4a1_silencer\"] = EqM4A1\n\teqNameToWeapon[\"m4a1_silencer_off\"] = EqM4A1\n\teqNameToWeapon[\"cz75a\"] = EqCZ\n\teqNameToWeapon[\"usp\"] = EqUSP\n\teqNameToWeapon[\"usp_silencer\"] = EqUSP\n\teqNameToWeapon[\"usp_silencer_off\"] = EqUSP\n\teqNameToWeapon[\"world\"] = EqWorld\n\teqNameToWeapon[\"inferno\"] = EqIncendiary\n\teqNameToWeapon[\"revolver\"] = EqRevolver\n\teqNameToWeapon[\"vest\"] = EqKevlar\n\teqNameToWeapon[\"vesthelm\"] = EqHelmet\n\teqNameToWeapon[\"defuser\"] = EqDefuseKit\n\n\t\/\/ These don't exist and \/ or used to crash the game with the give command\n\teqNameToWeapon[\"scar17\"] = EqUnknown\n\teqNameToWeapon[\"sensorgrenade\"] = EqUnknown\n\teqNameToWeapon[\"mp5navy\"] = EqUnknown\n\teqNameToWeapon[\"p228\"] = EqUnknown\n\teqNameToWeapon[\"scout\"] = EqUnknown\n\teqNameToWeapon[\"sg550\"] = EqUnknown\n\teqNameToWeapon[\"sg552\"] = EqUnknown \/\/ This one still crashes the game :)\n\teqNameToWeapon[\"tmp\"] = EqUnknown\n\teqNameToWeapon[\"worldspawn\"] = EqUnknown\n}\n\nfunc initEqEementToName() {\n\teqElementToName = make(map[EquipmentElement]string)\n\teqElementToName[EqAK47] = \"AK-47\"\n\teqElementToName[EqAUG] = \"AUG\"\n\teqElementToName[EqAWP] = \"AWP\"\n\teqElementToName[EqBizon] = \"PP-Bizon\"\n\teqElementToName[EqBomb] = \"C4\"\n\teqElementToName[EqDeagle] = \"Desert Eagle\"\n\teqElementToName[EqDecoy] = \"Decoy Grenade\"\n\teqElementToName[EqDualBarettas] = \"Dual Barettas\"\n\teqElementToName[EqFamas] = \"FAMAS\"\n\teqElementToName[EqFiveSeven] = \"Five-SeveN\"\n\teqElementToName[EqFlash] = \"Flashbang\"\n\teqElementToName[EqG3SG1] = \"G3SG1\"\n\teqElementToName[EqGalil] = \"Galil AR\"\n\teqElementToName[EqGlock] = \"Glock-18\"\n\teqElementToName[EqHE] = \"HE Grenade\"\n\teqElementToName[EqP2000] = \"P2000\"\n\teqElementToName[EqIncendiary] = \"Incendiary Grenade\"\n\teqElementToName[EqM249] = \"M249\"\n\teqElementToName[EqM4A4] = \"M4A1\"\n\teqElementToName[EqMac10] = \"MAC-10\"\n\teqElementToName[EqSwag7] = \"MAG-7\"\n\teqElementToName[EqMolotov] = \"Molotov\"\n\teqElementToName[EqMP7] = \"MP7\"\n\teqElementToName[EqMP9] = \"MP9\"\n\teqElementToName[EqNegev] = \"Negev\"\n\teqElementToName[EqNova] = \"Nova\"\n\teqElementToName[EqP250] = \"p250\"\n\teqElementToName[EqP90] = \"P90\"\n\teqElementToName[EqSawedOff] = \"Sawed-Off\"\n\teqElementToName[EqScar20] = \"SCAR-20\"\n\teqElementToName[EqSG553] = \"SG 553\"\n\teqElementToName[EqSmoke] = \"Smoke Grenade\"\n\teqElementToName[EqScout] = \"SSG 08\"\n\teqElementToName[EqZeus] = \"Zeus x27\"\n\teqElementToName[EqTec9] = \"Tec-9\"\n\teqElementToName[EqUMP] = \"UMP-45\"\n\teqElementToName[EqXM1014] = \"XM1014\"\n\teqElementToName[EqM4A1] = \"M4A1\"\n\teqElementToName[EqCZ] = \"CZ75 Auto\"\n\teqElementToName[EqUSP] = \"USP-S\"\n\teqElementToName[EqWorld] = \"World\"\n\teqElementToName[EqRevolver] = \"R8 Revolver\"\n\teqElementToName[EqKevlar] = \"Kevlar Vest\"\n\teqElementToName[EqHelmet] = \"Kevlar + Helmet\"\n\teqElementToName[EqDefuseKit] = \"Defuse Kit\"\n\teqElementToName[EqKnife] = \"Knife\"\n}\n\n\/\/ MapEquipment creates an EquipmentElement from the name of the weapon \/ equipment.\nfunc MapEquipment(eqName string) EquipmentElement {\n\teqName = strings.TrimPrefix(eqName, weaponPrefix)\n\n\tvar wep EquipmentElement\n\tif strings.Contains(eqName, \"knife\") || strings.Contains(eqName, \"bayonet\") {\n\t\twep = EqKnife\n\t} else {\n\t\t\/\/ If the eqName isn't known it will be EqUnknown as that is the default value for EquipmentElement\n\t\tvar ok bool\n\t\tif wep, ok = eqNameToWeapon[eqName]; !ok {\n\t\t\t\/\/ TODO: Return error \/ warning for unmapped weapons\n\t\t}\n\t}\n\n\treturn wep\n}\ncommon: fix typo initEqEementToName -> initEqElementToName.\/\/ Package common contains common types, constants and functions used over different demoinfocs packages.\n\/\/ Some constants prefixes:\n\/\/ MVPReason - the reason why someone got the MVP award.\n\/\/ HG - HitGroup - where a bullet hit the player.\n\/\/ EE - EquipmentElement - basically the weapon identifiers.\n\/\/ RER - RoundEndReason - why the round ended (bomb exploded, defused, time ran out. . .).\n\/\/ EC - EquipmentClass - type of equipment (pistol, smg, heavy. . .).\npackage common\n\nimport (\n\t\"strings\"\n)\n\nvar eqNameToWeapon map[string]EquipmentElement\n\nvar eqElementToName map[EquipmentElement]string\n\nfunc init() {\n\tinitEqNameToWeapon()\n\tinitEqElementToName()\n}\n\nfunc initEqNameToWeapon() {\n\teqNameToWeapon = make(map[string]EquipmentElement)\n\n\teqNameToWeapon[\"ak47\"] = EqAK47\n\teqNameToWeapon[\"aug\"] = EqAUG\n\teqNameToWeapon[\"awp\"] = EqAWP\n\teqNameToWeapon[\"bizon\"] = EqBizon\n\teqNameToWeapon[\"c4\"] = EqBomb\n\teqNameToWeapon[\"deagle\"] = EqDeagle\n\teqNameToWeapon[\"decoy\"] = EqDecoy\n\teqNameToWeapon[\"decoygrenade\"] = EqDecoy\n\teqNameToWeapon[\"decoyprojectile\"] = EqDecoy\n\teqNameToWeapon[\"elite\"] = EqDualBarettas\n\teqNameToWeapon[\"famas\"] = EqFamas\n\teqNameToWeapon[\"fiveseven\"] = EqFiveSeven\n\teqNameToWeapon[\"flashbang\"] = EqFlash\n\teqNameToWeapon[\"g3sg1\"] = EqG3SG1\n\teqNameToWeapon[\"galil\"] = EqGalil\n\teqNameToWeapon[\"galilar\"] = EqGalil\n\teqNameToWeapon[\"glock\"] = EqGlock\n\teqNameToWeapon[\"hegrenade\"] = EqHE\n\teqNameToWeapon[\"hkp2000\"] = EqP2000\n\teqNameToWeapon[\"incgrenade\"] = EqIncendiary\n\teqNameToWeapon[\"incendiarygrenade\"] = EqIncendiary\n\teqNameToWeapon[\"m249\"] = EqM249\n\teqNameToWeapon[\"m4a1\"] = EqM4A4\n\teqNameToWeapon[\"mac10\"] = EqMac10\n\teqNameToWeapon[\"mag7\"] = EqSwag7\n\teqNameToWeapon[\"molotov\"] = EqMolotov\n\teqNameToWeapon[\"molotovgrenade\"] = EqMolotov\n\teqNameToWeapon[\"molotovprojectile\"] = EqMolotov\n\teqNameToWeapon[\"mp7\"] = EqMP7\n\teqNameToWeapon[\"mp9\"] = EqMP9\n\teqNameToWeapon[\"negev\"] = EqNegev\n\teqNameToWeapon[\"nova\"] = EqNova\n\teqNameToWeapon[\"p250\"] = EqP250\n\teqNameToWeapon[\"p90\"] = EqP90\n\teqNameToWeapon[\"sawedoff\"] = EqSawedOff\n\teqNameToWeapon[\"scar20\"] = EqScar20\n\teqNameToWeapon[\"sg556\"] = EqSG556\n\teqNameToWeapon[\"smokegrenade\"] = EqSmoke\n\teqNameToWeapon[\"smokegrenadeprojectile\"] = EqSmoke\n\teqNameToWeapon[\"taser\"] = EqZeus\n\teqNameToWeapon[\"tec9\"] = EqTec9\n\teqNameToWeapon[\"ump45\"] = EqUMP\n\teqNameToWeapon[\"xm1014\"] = EqXM1014\n\teqNameToWeapon[\"m4a1_silencer\"] = EqM4A1\n\teqNameToWeapon[\"m4a1_silencer_off\"] = EqM4A1\n\teqNameToWeapon[\"cz75a\"] = EqCZ\n\teqNameToWeapon[\"usp\"] = EqUSP\n\teqNameToWeapon[\"usp_silencer\"] = EqUSP\n\teqNameToWeapon[\"usp_silencer_off\"] = EqUSP\n\teqNameToWeapon[\"world\"] = EqWorld\n\teqNameToWeapon[\"inferno\"] = EqIncendiary\n\teqNameToWeapon[\"revolver\"] = EqRevolver\n\teqNameToWeapon[\"vest\"] = EqKevlar\n\teqNameToWeapon[\"vesthelm\"] = EqHelmet\n\teqNameToWeapon[\"defuser\"] = EqDefuseKit\n\n\t\/\/ These don't exist and \/ or used to crash the game with the give command\n\teqNameToWeapon[\"scar17\"] = EqUnknown\n\teqNameToWeapon[\"sensorgrenade\"] = EqUnknown\n\teqNameToWeapon[\"mp5navy\"] = EqUnknown\n\teqNameToWeapon[\"p228\"] = EqUnknown\n\teqNameToWeapon[\"scout\"] = EqUnknown\n\teqNameToWeapon[\"sg550\"] = EqUnknown\n\teqNameToWeapon[\"sg552\"] = EqUnknown \/\/ This one still crashes the game :)\n\teqNameToWeapon[\"tmp\"] = EqUnknown\n\teqNameToWeapon[\"worldspawn\"] = EqUnknown\n}\n\nfunc initEqElementToName() {\n\teqElementToName = make(map[EquipmentElement]string)\n\teqElementToName[EqAK47] = \"AK-47\"\n\teqElementToName[EqAUG] = \"AUG\"\n\teqElementToName[EqAWP] = \"AWP\"\n\teqElementToName[EqBizon] = \"PP-Bizon\"\n\teqElementToName[EqBomb] = \"C4\"\n\teqElementToName[EqDeagle] = \"Desert Eagle\"\n\teqElementToName[EqDecoy] = \"Decoy Grenade\"\n\teqElementToName[EqDualBarettas] = \"Dual Barettas\"\n\teqElementToName[EqFamas] = \"FAMAS\"\n\teqElementToName[EqFiveSeven] = \"Five-SeveN\"\n\teqElementToName[EqFlash] = \"Flashbang\"\n\teqElementToName[EqG3SG1] = \"G3SG1\"\n\teqElementToName[EqGalil] = \"Galil AR\"\n\teqElementToName[EqGlock] = \"Glock-18\"\n\teqElementToName[EqHE] = \"HE Grenade\"\n\teqElementToName[EqP2000] = \"P2000\"\n\teqElementToName[EqIncendiary] = \"Incendiary Grenade\"\n\teqElementToName[EqM249] = \"M249\"\n\teqElementToName[EqM4A4] = \"M4A1\"\n\teqElementToName[EqMac10] = \"MAC-10\"\n\teqElementToName[EqSwag7] = \"MAG-7\"\n\teqElementToName[EqMolotov] = \"Molotov\"\n\teqElementToName[EqMP7] = \"MP7\"\n\teqElementToName[EqMP9] = \"MP9\"\n\teqElementToName[EqNegev] = \"Negev\"\n\teqElementToName[EqNova] = \"Nova\"\n\teqElementToName[EqP250] = \"p250\"\n\teqElementToName[EqP90] = \"P90\"\n\teqElementToName[EqSawedOff] = \"Sawed-Off\"\n\teqElementToName[EqScar20] = \"SCAR-20\"\n\teqElementToName[EqSG553] = \"SG 553\"\n\teqElementToName[EqSmoke] = \"Smoke Grenade\"\n\teqElementToName[EqScout] = \"SSG 08\"\n\teqElementToName[EqZeus] = \"Zeus x27\"\n\teqElementToName[EqTec9] = \"Tec-9\"\n\teqElementToName[EqUMP] = \"UMP-45\"\n\teqElementToName[EqXM1014] = \"XM1014\"\n\teqElementToName[EqM4A1] = \"M4A1\"\n\teqElementToName[EqCZ] = \"CZ75 Auto\"\n\teqElementToName[EqUSP] = \"USP-S\"\n\teqElementToName[EqWorld] = \"World\"\n\teqElementToName[EqRevolver] = \"R8 Revolver\"\n\teqElementToName[EqKevlar] = \"Kevlar Vest\"\n\teqElementToName[EqHelmet] = \"Kevlar + Helmet\"\n\teqElementToName[EqDefuseKit] = \"Defuse Kit\"\n\teqElementToName[EqKnife] = \"Knife\"\n}\n\n\/\/ MapEquipment creates an EquipmentElement from the name of the weapon \/ equipment.\nfunc MapEquipment(eqName string) EquipmentElement {\n\teqName = strings.TrimPrefix(eqName, weaponPrefix)\n\n\tvar wep EquipmentElement\n\tif strings.Contains(eqName, \"knife\") || strings.Contains(eqName, \"bayonet\") {\n\t\twep = EqKnife\n\t} else {\n\t\t\/\/ If the eqName isn't known it will be EqUnknown as that is the default value for EquipmentElement\n\t\tvar ok bool\n\t\tif wep, ok = eqNameToWeapon[eqName]; !ok {\n\t\t\t\/\/ TODO: Return error \/ warning for unmapped weapons\n\t\t}\n\t}\n\n\treturn wep\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (C) 2019 Google Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage adreno\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com\/google\/gapid\/core\/log\"\n\t\"github.com\/google\/gapid\/core\/os\/device\"\n\t\"github.com\/google\/gapid\/gapis\/perfetto\"\n\tperfetto_service \"github.com\/google\/gapid\/gapis\/perfetto\/service\"\n\t\"github.com\/google\/gapid\/gapis\/service\"\n)\n\nvar (\n\tslicesQuery = \"\" +\n\t\t\"SELECT s.context_id, s.render_target, s.frame_id, s.submission_id, s.hw_queue_id, s.ts, s.dur, s.name, depth, arg_set_id, track_id, t.name \" +\n\t\t\"FROM gpu_track t LEFT JOIN gpu_slice s \" +\n\t\t\"ON s.track_id = t.id AND t.scope = 'gpu_render_stage'\"\n\targsQueryFmt = \"\" +\n\t\t\"SELECT key, string_value FROM args WHERE args.arg_set_id = %d\"\n\tcounterTracksQuery = \"\" +\n\t\t\"SELECT id, name, unit, description FROM gpu_counter_track ORDER BY id\"\n\tcountersQueryFmt = \"\" +\n\t\t\"SELECT ts, value FROM counter c WHERE c.track_id = %d ORDER BY ts\"\n)\n\nfunc ProcessProfilingData(ctx context.Context, processor *perfetto.Processor, desc *device.GpuCounterDescriptor, handleMapping *map[uint64][]service.VulkanHandleMappingItem) (*service.ProfilingData, error) {\n\tslices, err := processGpuSlices(ctx, processor, handleMapping)\n\tif err != nil {\n\t\tlog.Err(ctx, err, \"Failed to get GPU slices\")\n\t}\n\tcounters, err := processCounters(ctx, processor, desc)\n\tif err != nil {\n\t\tlog.Err(ctx, err, \"Failed to get GPU counters\")\n\t}\n\treturn &service.ProfilingData{Slices: slices, Counters: counters}, nil\n}\n\nfunc processGpuSlices(ctx context.Context, processor *perfetto.Processor, handleMapping *map[uint64][]service.VulkanHandleMappingItem) (*service.ProfilingData_GpuSlices, error) {\n\tslicesQueryResult, err := processor.Query(slicesQuery)\n\tif err != nil {\n\t\treturn nil, log.Errf(ctx, err, \"SQL query failed: %v\", slicesQuery)\n\t}\n\n\ttrackIdCache := make(map[int64]bool)\n\targsQueryCache := make(map[int64]*perfetto_service.QueryResult)\n\tslicesColumns := slicesQueryResult.GetColumns()\n\tnumSliceRows := slicesQueryResult.GetNumRecords()\n\tslices := make([]*service.ProfilingData_GpuSlices_Slice, numSliceRows)\n\tvar tracks []*service.ProfilingData_GpuSlices_Track\n\t\/\/ Grab all the column values. Depends on the order of columns selected in slicesQuery\n\n\tcontextIds := slicesColumns[0].GetLongValues()\n\tfor i, v := range contextIds {\n\t\tif m, ok := (*handleMapping)[uint64(v)]; ok {\n\t\t\tcontextIds[i] = int64(m[0].TraceValue)\n\t\t} else {\n\t\t\tlog.E(ctx, \"Context Id could not found: %v\", v)\n\t\t}\n\t}\n\n\trenderTargets := slicesColumns[1].GetLongValues()\n\tfor i, v := range renderTargets {\n\t\tif m, ok := (*handleMapping)[uint64(v)]; ok {\n\t\t\trenderTargets[i] = int64(m[0].TraceValue)\n\t\t} else {\n\t\t\tlog.E(ctx, \"Render Target could not found: %v\", v)\n\t\t}\n\t}\n\n\tframeIds := slicesColumns[2].GetLongValues()\n\tsubmissionIds := slicesColumns[3].GetLongValues()\n\thwQueueIds := slicesColumns[4].GetLongValues()\n\ttimestamps := slicesColumns[5].GetLongValues()\n\tdurations := slicesColumns[6].GetLongValues()\n\tnames := slicesColumns[7].GetStringValues()\n\tdepths := slicesColumns[8].GetLongValues()\n\targSetIds := slicesColumns[9].GetLongValues()\n\ttrackIds := slicesColumns[10].GetLongValues()\n\ttrackNames := slicesColumns[11].GetStringValues()\n\n\tfor i := uint64(0); i < numSliceRows; i++ {\n\t\tvar argsQueryResult *perfetto_service.QueryResult\n\t\tvar ok bool\n\t\tif argsQueryResult, ok = argsQueryCache[argSetIds[i]]; !ok {\n\t\t\targsQuery := fmt.Sprintf(argsQueryFmt, argSetIds[i])\n\t\t\targsQueryResult, err = processor.Query(argsQuery)\n\t\t\tif err != nil {\n\t\t\t\tlog.W(ctx, \"SQL query failed: %v\", argsQuery)\n\t\t\t}\n\t\t\targsQueryCache[argSetIds[i]] = argsQueryResult\n\t\t}\n\t\targsColumns := argsQueryResult.GetColumns()\n\t\tnumArgsRows := argsQueryResult.GetNumRecords()\n\t\tvar extras []*service.ProfilingData_GpuSlices_Slice_Extra\n\t\tfor j := uint64(0); j < numArgsRows; j++ {\n\t\t\tkeys := argsColumns[0].GetStringValues()\n\t\t\tvalues := argsColumns[1].GetStringValues()\n\t\t\textras = append(extras, &service.ProfilingData_GpuSlices_Slice_Extra{\n\t\t\t\tName: keys[j],\n\t\t\t\tValue: &service.ProfilingData_GpuSlices_Slice_Extra_StringValue{StringValue: values[j]},\n\t\t\t})\n\t\t}\n\t\textras = append(extras, &service.ProfilingData_GpuSlices_Slice_Extra{\n\t\t\tName: \"contextId\",\n\t\t\tValue: &service.ProfilingData_GpuSlices_Slice_Extra_IntValue{IntValue: uint64(contextIds[i])},\n\t\t})\n\t\textras = append(extras, &service.ProfilingData_GpuSlices_Slice_Extra{\n\t\t\tName: \"renderTarget\",\n\t\t\tValue: &service.ProfilingData_GpuSlices_Slice_Extra_IntValue{IntValue: uint64(renderTargets[i])},\n\t\t})\n\t\textras = append(extras, &service.ProfilingData_GpuSlices_Slice_Extra{\n\t\t\tName: \"frameId\",\n\t\t\tValue: &service.ProfilingData_GpuSlices_Slice_Extra_IntValue{IntValue: uint64(frameIds[i])},\n\t\t})\n\t\textras = append(extras, &service.ProfilingData_GpuSlices_Slice_Extra{\n\t\t\tName: \"submissionId\",\n\t\t\tValue: &service.ProfilingData_GpuSlices_Slice_Extra_IntValue{IntValue: uint64(submissionIds[i])},\n\t\t})\n\t\textras = append(extras, &service.ProfilingData_GpuSlices_Slice_Extra{\n\t\t\tName: \"hwQueueId\",\n\t\t\tValue: &service.ProfilingData_GpuSlices_Slice_Extra_IntValue{IntValue: uint64(hwQueueIds[i])},\n\t\t})\n\n\t\tslices[i] = &service.ProfilingData_GpuSlices_Slice{\n\t\t\tTs: uint64(timestamps[i]),\n\t\t\tDur: uint64(durations[i]),\n\t\t\tLabel: names[i],\n\t\t\tDepth: int32(depths[i]),\n\t\t\tExtras: extras,\n\t\t\tTrackId: int32(trackIds[i]),\n\t\t}\n\n\t\tif _, ok := trackIdCache[trackIds[i]]; !ok {\n\t\t\ttrackIdCache[trackIds[i]] = true\n\t\t\ttracks = append(tracks, &service.ProfilingData_GpuSlices_Track{\n\t\t\t\tId: int32(trackIds[i]),\n\t\t\t\tName: trackNames[i],\n\t\t\t})\n\t\t}\n\t}\n\n\treturn &service.ProfilingData_GpuSlices{\n\t\tSlices: slices,\n\t\tTracks: tracks,\n\t}, nil\n}\n\nfunc processCounters(ctx context.Context, processor *perfetto.Processor, desc *device.GpuCounterDescriptor) ([]*service.ProfilingData_Counter, error) {\n\tcounterTracksQueryResult, err := processor.Query(counterTracksQuery)\n\tif err != nil {\n\t\treturn nil, log.Errf(ctx, err, \"SQL query failed: %v\", counterTracksQuery)\n\t}\n\t\/\/ t.id, name, unit, description, ts, value\n\ttracksColumns := counterTracksQueryResult.GetColumns()\n\tnumTracksRows := counterTracksQueryResult.GetNumRecords()\n\tcounters := make([]*service.ProfilingData_Counter, numTracksRows)\n\t\/\/ Grab all the column values. Depends on the order of columns selected in countersQuery\n\ttrackIds := tracksColumns[0].GetLongValues()\n\tnames := tracksColumns[1].GetStringValues()\n\tunits := tracksColumns[2].GetStringValues()\n\tdescriptions := tracksColumns[3].GetStringValues()\n\n\tfor i := uint64(0); i < numTracksRows; i++ {\n\t\tcountersQuery := fmt.Sprintf(countersQueryFmt, trackIds[i])\n\t\tcountersQueryResult, err := processor.Query(countersQuery)\n\t\tcountersColumns := countersQueryResult.GetColumns()\n\t\tif err != nil {\n\t\t\treturn nil, log.Errf(ctx, err, \"SQL query failed: %v\", counterTracksQuery)\n\t\t}\n\t\ttimestampsLong := countersColumns[0].GetLongValues()\n\t\ttimestamps := make([]uint64, len(timestampsLong))\n\t\tfor i, t := range timestampsLong {\n\t\t\ttimestamps[i] = uint64(t)\n\t\t}\n\t\tvalues := countersColumns[1].GetDoubleValues()\n\t\t\/\/ TODO(apbodnar) Populate the `default` field once the trace processor supports it (b\/147432390)\n\t\tcounters[i] = &service.ProfilingData_Counter{\n\t\t\tId: uint32(trackIds[i]),\n\t\t\tName: names[i],\n\t\t\tUnit: units[i],\n\t\t\tDescription: descriptions[i],\n\t\t\tTimestamps: timestamps,\n\t\t\tValues: values,\n\t\t}\n\t}\n\treturn counters, nil\n}\nAdd translation for command buffer handles in GPU slices (#3674)\/\/ Copyright (C) 2019 Google Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage adreno\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com\/google\/gapid\/core\/log\"\n\t\"github.com\/google\/gapid\/core\/os\/device\"\n\t\"github.com\/google\/gapid\/gapis\/perfetto\"\n\tperfetto_service \"github.com\/google\/gapid\/gapis\/perfetto\/service\"\n\t\"github.com\/google\/gapid\/gapis\/service\"\n)\n\nvar (\n\tslicesQuery = \"\" +\n\t\t\"SELECT s.context_id, s.render_target, s.frame_id, s.submission_id, s.hw_queue_id, s.command_buffer, s.ts, s.dur, s.name, depth, arg_set_id, track_id, t.name \" +\n\t\t\"FROM gpu_track t LEFT JOIN gpu_slice s \" +\n\t\t\"ON s.track_id = t.id AND t.scope = 'gpu_render_stage'\"\n\targsQueryFmt = \"\" +\n\t\t\"SELECT key, string_value FROM args WHERE args.arg_set_id = %d\"\n\tcounterTracksQuery = \"\" +\n\t\t\"SELECT id, name, unit, description FROM gpu_counter_track ORDER BY id\"\n\tcountersQueryFmt = \"\" +\n\t\t\"SELECT ts, value FROM counter c WHERE c.track_id = %d ORDER BY ts\"\n)\n\nfunc ProcessProfilingData(ctx context.Context, processor *perfetto.Processor, desc *device.GpuCounterDescriptor, handleMapping *map[uint64][]service.VulkanHandleMappingItem) (*service.ProfilingData, error) {\n\tslices, err := processGpuSlices(ctx, processor, handleMapping)\n\tif err != nil {\n\t\tlog.Err(ctx, err, \"Failed to get GPU slices\")\n\t}\n\tcounters, err := processCounters(ctx, processor, desc)\n\tif err != nil {\n\t\tlog.Err(ctx, err, \"Failed to get GPU counters\")\n\t}\n\treturn &service.ProfilingData{Slices: slices, Counters: counters}, nil\n}\n\nfunc processGpuSlices(ctx context.Context, processor *perfetto.Processor, handleMapping *map[uint64][]service.VulkanHandleMappingItem) (*service.ProfilingData_GpuSlices, error) {\n\tslicesQueryResult, err := processor.Query(slicesQuery)\n\tif err != nil {\n\t\treturn nil, log.Errf(ctx, err, \"SQL query failed: %v\", slicesQuery)\n\t}\n\n\ttrackIdCache := make(map[int64]bool)\n\targsQueryCache := make(map[int64]*perfetto_service.QueryResult)\n\tslicesColumns := slicesQueryResult.GetColumns()\n\tnumSliceRows := slicesQueryResult.GetNumRecords()\n\tslices := make([]*service.ProfilingData_GpuSlices_Slice, numSliceRows)\n\tvar tracks []*service.ProfilingData_GpuSlices_Track\n\t\/\/ Grab all the column values. Depends on the order of columns selected in slicesQuery\n\n\tcontextIds := slicesColumns[0].GetLongValues()\n\tfor i, v := range contextIds {\n\t\tif m, ok := (*handleMapping)[uint64(v)]; ok {\n\t\t\tcontextIds[i] = int64(m[0].TraceValue)\n\t\t} else {\n\t\t\tlog.E(ctx, \"Context Id not found: %v\", v)\n\t\t}\n\t}\n\n\trenderTargets := slicesColumns[1].GetLongValues()\n\tfor i, v := range renderTargets {\n\t\tif m, ok := (*handleMapping)[uint64(v)]; ok {\n\t\t\trenderTargets[i] = int64(m[0].TraceValue)\n\t\t} else {\n\t\t\tlog.E(ctx, \"Render Target not found: %v\", v)\n\t\t}\n\t}\n\n\tcommandBuffers := slicesColumns[5].GetLongValues()\n\tfor i, v := range commandBuffers {\n\t\tif m, ok := (*handleMapping)[uint64(v)]; ok {\n\t\t\tcommandBuffers[i] = int64(m[0].TraceValue)\n\t\t} else {\n\t\t\tlog.E(ctx, \"Command Buffer not found: %v\", v)\n\t\t}\n\t}\n\n\tframeIds := slicesColumns[2].GetLongValues()\n\tsubmissionIds := slicesColumns[3].GetLongValues()\n\thwQueueIds := slicesColumns[4].GetLongValues()\n\ttimestamps := slicesColumns[6].GetLongValues()\n\tdurations := slicesColumns[7].GetLongValues()\n\tnames := slicesColumns[8].GetStringValues()\n\tdepths := slicesColumns[9].GetLongValues()\n\targSetIds := slicesColumns[10].GetLongValues()\n\ttrackIds := slicesColumns[11].GetLongValues()\n\ttrackNames := slicesColumns[12].GetStringValues()\n\n\tfor i := uint64(0); i < numSliceRows; i++ {\n\t\tvar argsQueryResult *perfetto_service.QueryResult\n\t\tvar ok bool\n\t\tif argsQueryResult, ok = argsQueryCache[argSetIds[i]]; !ok {\n\t\t\targsQuery := fmt.Sprintf(argsQueryFmt, argSetIds[i])\n\t\t\targsQueryResult, err = processor.Query(argsQuery)\n\t\t\tif err != nil {\n\t\t\t\tlog.W(ctx, \"SQL query failed: %v\", argsQuery)\n\t\t\t}\n\t\t\targsQueryCache[argSetIds[i]] = argsQueryResult\n\t\t}\n\t\targsColumns := argsQueryResult.GetColumns()\n\t\tnumArgsRows := argsQueryResult.GetNumRecords()\n\t\tvar extras []*service.ProfilingData_GpuSlices_Slice_Extra\n\t\tfor j := uint64(0); j < numArgsRows; j++ {\n\t\t\tkeys := argsColumns[0].GetStringValues()\n\t\t\tvalues := argsColumns[1].GetStringValues()\n\t\t\textras = append(extras, &service.ProfilingData_GpuSlices_Slice_Extra{\n\t\t\t\tName: keys[j],\n\t\t\t\tValue: &service.ProfilingData_GpuSlices_Slice_Extra_StringValue{StringValue: values[j]},\n\t\t\t})\n\t\t}\n\t\textras = append(extras, &service.ProfilingData_GpuSlices_Slice_Extra{\n\t\t\tName: \"contextId\",\n\t\t\tValue: &service.ProfilingData_GpuSlices_Slice_Extra_IntValue{IntValue: uint64(contextIds[i])},\n\t\t})\n\t\textras = append(extras, &service.ProfilingData_GpuSlices_Slice_Extra{\n\t\t\tName: \"renderTarget\",\n\t\t\tValue: &service.ProfilingData_GpuSlices_Slice_Extra_IntValue{IntValue: uint64(renderTargets[i])},\n\t\t})\n\t\textras = append(extras, &service.ProfilingData_GpuSlices_Slice_Extra{\n\t\t\tName: \"commandBuffer\",\n\t\t\tValue: &service.ProfilingData_GpuSlices_Slice_Extra_IntValue{IntValue: uint64(commandBuffers[i])},\n\t\t})\n\t\textras = append(extras, &service.ProfilingData_GpuSlices_Slice_Extra{\n\t\t\tName: \"frameId\",\n\t\t\tValue: &service.ProfilingData_GpuSlices_Slice_Extra_IntValue{IntValue: uint64(frameIds[i])},\n\t\t})\n\t\textras = append(extras, &service.ProfilingData_GpuSlices_Slice_Extra{\n\t\t\tName: \"submissionId\",\n\t\t\tValue: &service.ProfilingData_GpuSlices_Slice_Extra_IntValue{IntValue: uint64(submissionIds[i])},\n\t\t})\n\t\textras = append(extras, &service.ProfilingData_GpuSlices_Slice_Extra{\n\t\t\tName: \"hwQueueId\",\n\t\t\tValue: &service.ProfilingData_GpuSlices_Slice_Extra_IntValue{IntValue: uint64(hwQueueIds[i])},\n\t\t})\n\n\t\tslices[i] = &service.ProfilingData_GpuSlices_Slice{\n\t\t\tTs: uint64(timestamps[i]),\n\t\t\tDur: uint64(durations[i]),\n\t\t\tLabel: names[i],\n\t\t\tDepth: int32(depths[i]),\n\t\t\tExtras: extras,\n\t\t\tTrackId: int32(trackIds[i]),\n\t\t}\n\n\t\tif _, ok := trackIdCache[trackIds[i]]; !ok {\n\t\t\ttrackIdCache[trackIds[i]] = true\n\t\t\ttracks = append(tracks, &service.ProfilingData_GpuSlices_Track{\n\t\t\t\tId: int32(trackIds[i]),\n\t\t\t\tName: trackNames[i],\n\t\t\t})\n\t\t}\n\t}\n\n\treturn &service.ProfilingData_GpuSlices{\n\t\tSlices: slices,\n\t\tTracks: tracks,\n\t}, nil\n}\n\nfunc processCounters(ctx context.Context, processor *perfetto.Processor, desc *device.GpuCounterDescriptor) ([]*service.ProfilingData_Counter, error) {\n\tcounterTracksQueryResult, err := processor.Query(counterTracksQuery)\n\tif err != nil {\n\t\treturn nil, log.Errf(ctx, err, \"SQL query failed: %v\", counterTracksQuery)\n\t}\n\t\/\/ t.id, name, unit, description, ts, value\n\ttracksColumns := counterTracksQueryResult.GetColumns()\n\tnumTracksRows := counterTracksQueryResult.GetNumRecords()\n\tcounters := make([]*service.ProfilingData_Counter, numTracksRows)\n\t\/\/ Grab all the column values. Depends on the order of columns selected in countersQuery\n\ttrackIds := tracksColumns[0].GetLongValues()\n\tnames := tracksColumns[1].GetStringValues()\n\tunits := tracksColumns[2].GetStringValues()\n\tdescriptions := tracksColumns[3].GetStringValues()\n\n\tfor i := uint64(0); i < numTracksRows; i++ {\n\t\tcountersQuery := fmt.Sprintf(countersQueryFmt, trackIds[i])\n\t\tcountersQueryResult, err := processor.Query(countersQuery)\n\t\tcountersColumns := countersQueryResult.GetColumns()\n\t\tif err != nil {\n\t\t\treturn nil, log.Errf(ctx, err, \"SQL query failed: %v\", counterTracksQuery)\n\t\t}\n\t\ttimestampsLong := countersColumns[0].GetLongValues()\n\t\ttimestamps := make([]uint64, len(timestampsLong))\n\t\tfor i, t := range timestampsLong {\n\t\t\ttimestamps[i] = uint64(t)\n\t\t}\n\t\tvalues := countersColumns[1].GetDoubleValues()\n\t\t\/\/ TODO(apbodnar) Populate the `default` field once the trace processor supports it (b\/147432390)\n\t\tcounters[i] = &service.ProfilingData_Counter{\n\t\t\tId: uint32(trackIds[i]),\n\t\t\tName: names[i],\n\t\t\tUnit: units[i],\n\t\t\tDescription: descriptions[i],\n\t\t\tTimestamps: timestamps,\n\t\t\tValues: values,\n\t\t}\n\t}\n\treturn counters, nil\n}\n<|endoftext|>"} {"text":"package compat\n\nimport (\n\t\"github.com\/gonfire\/jsonapi\"\n\t\"github.com\/labstack\/echo\/engine\/standard\"\n\t\"net\/http\"\n)\n\n\/\/ ParseRequest is a convenience method to parse a standard http.Request.\n\/\/\n\/\/ See: https:\/\/godoc.org\/github.com\/gonfire\/jsonapi#ParseRequest.\nfunc ParseRequest(r *http.Request, prefix string) (*jsonapi.Request, error) {\n\treturn jsonapi.ParseRequest(standard.NewRequest(r, nil), prefix)\n}\n\n\/\/ WriteResponse is a convenience method to write to a standard\n\/\/ http.ResponseWriter.\n\/\/\n\/\/ See: https:\/\/godoc.org\/github.com\/gonfire\/jsonapi#WriteResponse.\nfunc WriteResponse(res http.ResponseWriter, status int, doc *jsonapi.Document) error {\n\treturn jsonapi.WriteResponse(standard.NewResponse(res, nil), status, doc)\n}\n\n\/\/ WriteResource is a convenience method to write to a standard\n\/\/ http.ResponseWriter.\n\/\/\n\/\/ See: https:\/\/godoc.org\/github.com\/gonfire\/jsonapi#WriteResource.\nfunc WriteResource(w http.ResponseWriter, status int, resource *jsonapi.Resource, links *jsonapi.DocumentLinks, included ...*jsonapi.Resource) error {\n\treturn jsonapi.WriteResource(standard.NewResponse(w, nil), status, resource, links, included...)\n}\n\n\/\/ WriteResources is a convenience method to write to a standard\n\/\/ http.ResponseWriter.\n\/\/\n\/\/ See: https:\/\/godoc.org\/github.com\/gonfire\/jsonapi#WriteResources.\nfunc WriteResources(w http.ResponseWriter, status int, resources []*jsonapi.Resource, links *jsonapi.DocumentLinks, included ...*jsonapi.Resource) error {\n\treturn jsonapi.WriteResources(standard.NewResponse(w, nil), status, resources, links, included...)\n}\n\n\/\/ WriteError is a convenience method to write to a standard\n\/\/ http.ResponseWriter.\n\/\/\n\/\/ See: https:\/\/godoc.org\/github.com\/gonfire\/jsonapi#WriteError.\nfunc WriteError(w http.ResponseWriter, err error) error {\n\treturn jsonapi.WriteError(standard.NewResponse(w, nil), err)\n}\n\n\/\/ WriteErrorList is a convenience method to write to a standard\n\/\/ http.ResponseWriter.\n\/\/\n\/\/ See: https:\/\/godoc.org\/github.com\/gonfire\/jsonapi#WriteErrorList.\nfunc WriteErrorList(w http.ResponseWriter, errors ...*jsonapi.Error) error {\n\treturn jsonapi.WriteErrorList(standard.NewResponse(w, nil), errors...)\n}\ncleanuppackage compat\n\nimport (\n\t\"net\/http\"\n\n\t\"github.com\/gonfire\/jsonapi\"\n\t\"github.com\/labstack\/echo\/engine\/standard\"\n)\n\n\/\/ ParseRequest is a convenience method to parse a standard http.Request.\n\/\/\n\/\/ See: https:\/\/godoc.org\/github.com\/gonfire\/jsonapi#ParseRequest.\nfunc ParseRequest(r *http.Request, prefix string) (*jsonapi.Request, error) {\n\treturn jsonapi.ParseRequest(standard.NewRequest(r, nil), prefix)\n}\n\n\/\/ WriteResponse is a convenience method to write to a standard\n\/\/ http.ResponseWriter.\n\/\/\n\/\/ See: https:\/\/godoc.org\/github.com\/gonfire\/jsonapi#WriteResponse.\nfunc WriteResponse(res http.ResponseWriter, status int, doc *jsonapi.Document) error {\n\treturn jsonapi.WriteResponse(standard.NewResponse(res, nil), status, doc)\n}\n\n\/\/ WriteResource is a convenience method to write to a standard\n\/\/ http.ResponseWriter.\n\/\/\n\/\/ See: https:\/\/godoc.org\/github.com\/gonfire\/jsonapi#WriteResource.\nfunc WriteResource(w http.ResponseWriter, status int, resource *jsonapi.Resource, links *jsonapi.DocumentLinks, included ...*jsonapi.Resource) error {\n\treturn jsonapi.WriteResource(standard.NewResponse(w, nil), status, resource, links, included...)\n}\n\n\/\/ WriteResources is a convenience method to write to a standard\n\/\/ http.ResponseWriter.\n\/\/\n\/\/ See: https:\/\/godoc.org\/github.com\/gonfire\/jsonapi#WriteResources.\nfunc WriteResources(w http.ResponseWriter, status int, resources []*jsonapi.Resource, links *jsonapi.DocumentLinks, included ...*jsonapi.Resource) error {\n\treturn jsonapi.WriteResources(standard.NewResponse(w, nil), status, resources, links, included...)\n}\n\n\/\/ WriteError is a convenience method to write to a standard\n\/\/ http.ResponseWriter.\n\/\/\n\/\/ See: https:\/\/godoc.org\/github.com\/gonfire\/jsonapi#WriteError.\nfunc WriteError(w http.ResponseWriter, err error) error {\n\treturn jsonapi.WriteError(standard.NewResponse(w, nil), err)\n}\n\n\/\/ WriteErrorList is a convenience method to write to a standard\n\/\/ http.ResponseWriter.\n\/\/\n\/\/ See: https:\/\/godoc.org\/github.com\/gonfire\/jsonapi#WriteErrorList.\nfunc WriteErrorList(w http.ResponseWriter, errors ...*jsonapi.Error) error {\n\treturn jsonapi.WriteErrorList(standard.NewResponse(w, nil), errors...)\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2015-2022 MinIO, Inc.\n\/\/\n\/\/ This file is part of MinIO Object Storage stack\n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Affero General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Affero General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public License\n\/\/ along with this program. If not, see .\n\n\/\/go:build (linux && arm) || (linux && ppc64) || (linux && ppc64le) || (linux && s390x)\n\/\/ +build linux,arm linux,ppc64 linux,ppc64le linux,s390x\n\npackage kernel\n\nfunc utsnameStr(in []uint8) string {\n\tout := make([]byte, 0, len(in))\n\tfor i := 0; i < len(in); i++ {\n\t\tif in[i] == 0x00 {\n\t\t\tbreak\n\t\t}\n\t\tout = append(out, byte(in[i]))\n\t}\n\treturn string(out)\n}\nAdd riscv64 support (#14601)\/\/ Copyright (c) 2015-2022 MinIO, Inc.\n\/\/\n\/\/ This file is part of MinIO Object Storage stack\n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Affero General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Affero General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public License\n\/\/ along with this program. If not, see .\n\n\/\/go:build (linux && arm) || (linux && ppc64) || (linux && ppc64le) || (linux && s390x)|| (linux && riscv64)\n\/\/ +build linux,arm linux,ppc64 linux,ppc64le linux,s390x linux,riscv64\n\npackage kernel\n\nfunc utsnameStr(in []uint8) string {\n\tout := make([]byte, 0, len(in))\n\tfor i := 0; i < len(in); i++ {\n\t\tif in[i] == 0x00 {\n\t\t\tbreak\n\t\t}\n\t\tout = append(out, byte(in[i]))\n\t}\n\treturn string(out)\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/PuerkitoBio\/goquery\"\n\t\"github.com\/urfave\/cli\"\n)\n\nfunc CrawlTrending(lang string, count int) error {\n\tdoc, err := goquery.NewDocument(\"https:\/\/github.com\/trending\/\" + lang)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn err\n\t}\n\n\trepoList := doc.Find(\".d-inline-block > h3 > a\").Slice(0, count)\n\n\trepoList.Each(func(i int, s *goquery.Selection) {\n\t\trepoName := strings.Trim(s.Text(), \" \\n\")\n\t\tfmt.Printf(\"%d - %s\\n\", i+1, repoName)\n\t})\n\treturn nil\n}\n\nfunc main() {\n\tapp := cli.NewApp()\n\tapp.Name = \"gorending\"\n\tapp.Usage = \"Show Github trending in Terminal!\"\n\tapp.Version = \"1.0.0\"\n\tapp.Compiled = time.Now()\n\tapp.Copyright = \"(c) 2017 Myungseo Kang\"\n\tapp.Authors = []cli.Author{\n\t\tcli.Author{\n\t\t\tName: \"Myungseo Kang\",\n\t\t\tEmail: \"l3opold7@gmail.com\",\n\t\t},\n\t}\n\n\tapp.Flags = []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName: \"lang, l\",\n\t\t\tValue: \"\",\n\t\t\tUsage: \"language that you want to see, default all language\",\n\t\t},\n\t\tcli.IntFlag{\n\t\t\tName: \"count, c\",\n\t\t\tValue: 10,\n\t\t\tUsage: \"count that you want to see, defalut 10\",\n\t\t},\n\t}\n\n\tapp.Action = func(c *cli.Context) error {\n\t\tlang := c.String(\"lang\")\n\t\tcount := c.Int(\"count\")\n\n\t\terr := CrawlTrending(lang, count)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tapp.Run(os.Args)\n}\nAdd comment for CrawlTrending functionpackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/PuerkitoBio\/goquery\"\n\t\"github.com\/urfave\/cli\"\n)\n\n\/\/ CrawlTrending is function for printing parsed trending\nfunc CrawlTrending(lang string, count int) error {\n\tdoc, err := goquery.NewDocument(\"https:\/\/github.com\/trending\/\" + lang)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn err\n\t}\n\n\trepoList := doc.Find(\".d-inline-block > h3 > a\").Slice(0, count)\n\n\trepoList.Each(func(i int, s *goquery.Selection) {\n\t\trepoName := strings.Trim(s.Text(), \" \\n\")\n\t\tfmt.Printf(\"%d - %s\\n\", i+1, repoName)\n\t})\n\treturn nil\n}\n\nfunc main() {\n\tapp := cli.NewApp()\n\tapp.Name = \"gorending\"\n\tapp.Usage = \"Show Github trending in Terminal!\"\n\tapp.Version = \"1.0.0\"\n\tapp.Compiled = time.Now()\n\tapp.Copyright = \"(c) 2017 Myungseo Kang\"\n\tapp.Authors = []cli.Author{\n\t\tcli.Author{\n\t\t\tName: \"Myungseo Kang\",\n\t\t\tEmail: \"l3opold7@gmail.com\",\n\t\t},\n\t}\n\n\tapp.Flags = []cli.Flag{\n\t\tcli.StringFlag{\n\t\t\tName: \"lang, l\",\n\t\t\tValue: \"\",\n\t\t\tUsage: \"language that you want to see, default all language\",\n\t\t},\n\t\tcli.IntFlag{\n\t\t\tName: \"count, c\",\n\t\t\tValue: 10,\n\t\t\tUsage: \"count that you want to see, defalut 10\",\n\t\t},\n\t}\n\n\tapp.Action = func(c *cli.Context) error {\n\t\tlang := c.String(\"lang\")\n\t\tcount := c.Int(\"count\")\n\n\t\terr := CrawlTrending(lang, count)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tapp.Run(os.Args)\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\tgoopt \"github.com\/droundy\/goopt\"\n\t\"os\"\n\t\"path\"\n\t\"fmt\"\n\t\"regexp\"\n\t\"bytes\"\n\t\".\/highlight\"\n)\n\nvar Pattern *regexp.Regexp\nvar byteNewLine []byte = []byte(\"\\n\")\n\nfunc main() {\n\tgoopt.Description = func() string {\n\t\treturn \"Go search and replace in files\"\n\t}\n\tgoopt.Version = \"0.1\"\n\tgoopt.Parse(nil)\n\n\tif len(goopt.Args) == 0 {\n\t\tprintln(goopt.Usage())\n\t\treturn\n\t}\n\n\tvar err os.Error\n\tPattern, err = regexp.Compile(goopt.Args[0])\n\terrhandle(err, \"can't compile regexp %s\", goopt.Args[0])\n\n\tsearchFiles()\n}\n\nfunc errhandle(err os.Error, moreinfo string, a ...interface{}) {\n\tif err == nil {\n\t\treturn\n\t}\n\tfmt.Fprintf(os.Stderr, \"ERR %s\\n%s\\n\", err,\n\t\tfmt.Sprintf(moreinfo, a...))\n\tos.Exit(1)\n}\n\ntype Visitor struct{}\n\nfunc (v *Visitor) VisitDir(p string, fi *os.FileInfo) bool {\n\tif fi.Name == \".hg\" {\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc (v *Visitor) VisitFile(p string, fi *os.FileInfo) {\n\tif fi.Size >= 1024*1024*10 {\n\t\tfmt.Fprintf(os.Stderr, \"Skipping %s, too big: %d\\n\", p, fi.Size)\n\t\treturn\n\t}\n\n\tif fi.Size == 0 {\n\t\treturn\n\t}\n\n\tf, err := os.Open(p, os.O_RDONLY, 0666)\n\terrhandle(err, \"can't open file %s\", p)\n\n\tcontent := make([]byte, fi.Size)\n\tn, err := f.Read(content)\n\terrhandle(err, \"can't read file %s\", p)\n\tif int64(n) != fi.Size {\n\t\tpanic(fmt.Sprintf(\"Not whole file was read, only %d from %d\",\n\t\t\tn, fi.Size))\n\t}\n\n\tsearchFile(p, content)\n\n\tf.Close()\n}\n\nfunc searchFile(p string, content []byte) {\n\tlinenum := 1\n\tlast := 0\n\thadOutput := false\n\tbinary := false\n\n\tif bytes.IndexByte(content, 0) != -1 {\n\t\tbinary = true\n\t}\n\n\tfor _, bounds := range Pattern.FindAllIndex(content, -1) {\n\t\tif binary {\n\t\t\tfmt.Printf(\"Binary file %s matches\\n\", p)\n\t\t\thadOutput = true\n\t\t\tbreak\n\t\t}\n\n\t\tif !hadOutput {\n\t\t\thighlight.Printf(\"green\", \"%s\\n\", p)\n\t\t\thadOutput = true\n\t\t}\n\n\t\tlinenum += bytes.Count(content[last:bounds[0]], byteNewLine)\n\t\tlast = bounds[0]\n\t\tbegin, end := beginend(content, bounds[0], bounds[1])\n\n\t\tif content[begin] == '\\r' {\n\t\t\tbegin += 1\n\t\t}\n\n\t\thighlight.Printf(\"bold yellow\", \"%d:\", linenum)\n\t\thighlight.Reprintf(\"on_yellow\", Pattern, \"%s\\n\", content[begin:end])\n\t}\n\n\tif hadOutput {\n\t\tfmt.Println(\"\")\n\t}\n}\n\n\/\/ Given a []byte, start and finish of some inner slice, will find nearest\n\/\/ newlines on both ends of this slice\nfunc beginend(s []byte, start int, finish int) (begin int, end int) {\n\tbegin = 0\n\tend = len(s)\n\n\tfor i := start; i >= 0; i-- {\n\t\tif s[i] == byteNewLine[0] {\n\t\t\t\/\/ skip newline itself\n\t\t\tbegin = i + 1\n\t\t\tbreak\n\t\t}\n\t}\n\n\tfor i := finish; i < len(s); i++ {\n\t\tif s[i] == byteNewLine[0] {\n\t\t\tend = i\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc searchFiles() {\n\tv := &Visitor{}\n\n\terrors := make(chan os.Error, 64)\n\n\tpath.Walk(\".\", v, errors)\n\n\tselect {\n\tcase err := <-errors:\n\t\terrhandle(err, \"some error\")\n\tdefault:\n\t}\n}\nfile exclusion by maskpackage main\n\nimport (\n\t\"os\"\n\t\"path\"\n\t\"fmt\"\n\t\"regexp\"\n\t\"bytes\"\n\tgoopt \"github.com\/droundy\/goopt\"\n\t\".\/highlight\"\n)\n\nvar byteNewLine []byte = []byte(\"\\n\")\n\/\/ Used to prevent appear of sparse newline at the end of output\nvar prependNewLine = false\n\ntype StringList []string\nvar IgnoreDirs = StringList{\"autom4te.cache\", \"blib\", \"_build\", \".bzr\", \".cdv\",\n\t\"cover_db\", \"CVS\", \"_darcs\", \"~.dep\", \"~.dot\", \".git\", \".hg\", \"~.nib\",\n \".pc\", \"~.plst\", \"RCS\", \"SCCS\", \"_sgbak\", \".svn\"}\n\ntype RegexpList []*regexp.Regexp\nvar IgnoreFiles = regexpList([]string{`~$`, `#.+#$`, `[._].*\\.swp$`, `core\\.[0-9]+$`,\n\t`\\.pyc$`, `\\.o$`, `\\.6$`})\n\nvar onlyName = goopt.Flag([]string{\"-n\", \"--filename\"}, []string{},\n\t\"print only filenames\", \"\")\nvar ignoreFiles = goopt.Strings([]string{\"-x\", \"--exclude\"}, \"RE\",\n\t\"exclude files that match the regexp from search\")\n\nfunc main() {\n\tgoopt.Description = func() string {\n\t\treturn \"Go search and replace in files\"\n\t}\n\tgoopt.Version = \"0.1\"\n\tgoopt.Parse(nil)\n\n\tif len(goopt.Args) == 0 {\n\t\tprintln(goopt.Usage())\n\t\treturn\n\t}\n\n\tIgnoreFiles = append(IgnoreFiles, regexpList(*ignoreFiles)...)\n\n\tpattern, err := regexp.Compile(goopt.Args[0])\n\terrhandle(err, \"can't compile regexp %s\", goopt.Args[0])\n\n\tsearchFiles(pattern)\n}\n\nfunc errhandle(err os.Error, moreinfo string, a ...interface{}) {\n\tif err == nil {\n\t\treturn\n\t}\n\tfmt.Fprintf(os.Stderr, \"ERR %s\\n%s\\n\", err,\n\t\tfmt.Sprintf(moreinfo, a...))\n\tos.Exit(1)\n}\n\nfunc regexpList(sa []string) RegexpList {\n\tra := make(RegexpList, len(sa))\n\tfor i, s := range sa {\n\t\tra[i] = regexp.MustCompile(s)\n\t}\n\treturn ra\n}\n\nfunc searchFiles(pattern *regexp.Regexp) {\n\tv := &GRVisitor{pattern}\n\n\terrors := make(chan os.Error, 64)\n\n\tpath.Walk(\".\", v, errors)\n\n\tselect {\n\tcase err := <-errors:\n\t\terrhandle(err, \"some error\")\n\tdefault:\n\t}\n}\n\ntype GRVisitor struct{\n\tpattern *regexp.Regexp\n}\n\nfunc (v *GRVisitor) VisitDir(fn string, fi *os.FileInfo) bool {\n\tif IgnoreDirs.Contains(fi.Name) {\n\t\treturn false\n\t}\n\treturn true\n}\n\nfunc (v *GRVisitor) VisitFile(fn string, fi *os.FileInfo) {\n\tif IgnoreFiles.Match(fn) {\n\t\treturn\n\t}\n\n\tif fi.Size >= 1024*1024*10 {\n\t\tfmt.Fprintf(os.Stderr, \"Skipping %s, too big: %d\\n\", fn, fi.Size)\n\t\treturn\n\t}\n\n\tif fi.Size == 0 {\n\t\treturn\n\t}\n\n\tf, err := os.Open(fn, os.O_RDONLY, 0666)\n\terrhandle(err, \"can't open file %s\", fn)\n\n\tcontent := make([]byte, fi.Size)\n\tn, err := f.Read(content)\n\terrhandle(err, \"can't read file %s\", fn)\n\tif int64(n) != fi.Size {\n\t\tpanic(fmt.Sprintf(\"Not whole file was read, only %d from %d\",\n\t\t\tn, fi.Size))\n\t}\n\n\tv.SearchFile(fn, content)\n\n\tf.Close()\n}\n\nfunc (v *GRVisitor) SearchFile(p string, content []byte) {\n\tlinenum := 1\n\tlast := 0\n\thadOutput := false\n\tbinary := false\n\n\tif bytes.IndexByte(content, 0) != -1 {\n\t\tbinary = true\n\t}\n\n\tfor _, bounds := range v.pattern.FindAllIndex(content, -1) {\n\t\tif prependNewLine {\n\t\t\tfmt.Println(\"\")\n\t\t\tprependNewLine = false\n\t\t}\n\n\t\tif !hadOutput {\n\t\t\thadOutput = true\n\t\t\tif binary && !*onlyName{\n\t\t\t\tfmt.Printf(\"Binary file %s matches\\n\", p)\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\thighlight.Printf(\"green\", \"%s\\n\", p)\n\t\t\t}\n\t\t}\n\n\t\tif *onlyName {\n\t\t\treturn\n\t\t}\n\n\t\tlinenum += bytes.Count(content[last:bounds[0]], byteNewLine)\n\t\tlast = bounds[0]\n\t\tbegin, end := beginend(content, bounds[0], bounds[1])\n\n\t\tif content[begin] == '\\r' {\n\t\t\tbegin += 1\n\t\t}\n\n\t\thighlight.Printf(\"bold yellow\", \"%d:\", linenum)\n\t\thighlight.Reprintf(\"on_yellow\", v.pattern, \"%s\\n\", content[begin:end])\n\t}\n\n\tif hadOutput {\n\t\tprependNewLine = true\n\t}\n}\n\n\/\/ Given a []byte, start and finish of some inner slice, will find nearest\n\/\/ newlines on both ends of this slice\nfunc beginend(s []byte, start int, finish int) (begin int, end int) {\n\tbegin = 0\n\tend = len(s)\n\n\tfor i := start; i >= 0; i-- {\n\t\tif s[i] == byteNewLine[0] {\n\t\t\t\/\/ skip newline itself\n\t\t\tbegin = i + 1\n\t\t\tbreak\n\t\t}\n\t}\n\n\tfor i := finish; i < len(s); i++ {\n\t\tif s[i] == byteNewLine[0] {\n\t\t\tend = i\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc (sl StringList) Contains(s string) bool {\n\tfor _, x := range sl {\n\t\tif x == s {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (rl RegexpList) Match(s string) bool {\n\tfor _, x := range rl {\n\t\tif x.Match([]byte(s)) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n<|endoftext|>"} {"text":"package gosh\n\nimport \"testing\"\n\nfunc TestGosh(t *testing.T) {\n\tEchoTime = true\n\tEchoIn = true\n\tEchoOut = true\n\terr := Run(\"date\")\n\tif err != nil {\n\t\tt.Error(\"gosh run error.\")\n\t}\n}\nupdate test case.package gosh\n\nimport \"testing\"\n\nfunc TestGosh(t *testing.T) {\n\terr := Run(\"date\")\n\tif err != nil {\n\t\tt.Error(\"gosh run error.\")\n\t}\n}\n<|endoftext|>"} {"text":"package game\n\nimport (\n\t\"errors\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/ghthor\/engine\/net\/protocol\"\n\t\"github.com\/ghthor\/engine\/rpg2d\"\n\t\"github.com\/ghthor\/engine\/rpg2d\/coord\"\n\t\"github.com\/ghthor\/engine\/rpg2d\/entity\"\n\t\"github.com\/ghthor\/engine\/sim\/stime\"\n)\n\ntype actorCmd struct {\n\ttimeIssued stime.Time\n\tcmd string\n\tparams string\n}\n\ntype moveRequest struct {\n\tstime.Time\n\tcoord.Direction\n}\n\ntype actorCmdRequest struct {\n\tmoveRequest\n}\n\ntype actorConn struct {\n\t\/\/ Comm interface to muxer used by WriteInput() method\n\tsubmitCmd chan<- actorCmd\n\n\t\/\/ Comm interface to muxer used by getEntity() method\n\treadCmdReq <-chan actorCmdRequest\n\n\t\/\/ Comm interface to muxer used by SendState() method\n\tsendState chan<- *rpg2d.WorldState\n\n\t\/\/ Comm interface to muxer used by stopIO() method\n\tstop chan<- chan<- struct{}\n\n\t\/\/ External connection used to publish the world state\n\tprotocol.Conn\n\n\tlastState rpg2d.WorldState\n}\n\nfunc newActorConn(conn protocol.Conn) actorConn {\n\treturn actorConn{Conn: conn}\n}\n\n\/\/ Object stored in the quad tree\ntype actorEntity struct {\n\tid int64\n\n\tname string\n\n\tcell coord.Cell\n\tfacing coord.Direction\n\n\tpathAction *coord.PathAction\n}\n\ntype actorEntityState struct {\n\tEntityId int64 `json:\"id\"`\n\n\tName string `json:\"name\"`\n\n\tFacing string `json:\"facing\"`\n\tCell coord.Cell `json:\"cell\"`\n\tbounds coord.Bounds\n\n\tPathAction *coord.PathAction `json:\"pathAction\"`\n}\n\ntype actor struct {\n\tactorEntity\n\tactorConn\n}\n\nfunc (a actor) Entity() entity.Entity { return a.actorEntity }\nfunc (e actorEntity) Id() int64 { return e.id }\nfunc (e actorEntity) Cell() coord.Cell { return e.cell }\nfunc (e actorEntity) Bounds() coord.Bounds {\n\tbounds := coord.Bounds{\n\t\te.cell,\n\t\te.cell,\n\t}\n\n\tif e.pathAction != nil {\n\t\tbounds = coord.JoinBounds(bounds, e.pathAction.Bounds())\n\t}\n\n\treturn bounds\n}\n\nfunc (e actorEntity) ToState() entity.State {\n\treturn actorEntityState{\n\t\tEntityId: e.id,\n\n\t\tCell: e.cell,\n\t\tFacing: e.facing.String(),\n\n\t\tbounds: e.Bounds(),\n\n\t\tPathAction: e.pathAction,\n\t}\n}\n\nfunc (e actorEntityState) Id() int64 { return e.EntityId }\nfunc (e actorEntityState) Bounds() coord.Bounds { return e.bounds }\nfunc (e actorEntityState) IsDifferentFrom(other entity.State) bool {\n\to := other.(actorEntityState)\n\n\tswitch {\n\tcase e.Facing != o.Facing:\n\t\treturn true\n\n\tcase e.PathAction != nil && o.PathAction != nil:\n\t\tif *e.PathAction != *o.PathAction {\n\t\t\treturn true\n\t\t}\n\n\tcase e.PathAction == nil && o.PathAction != nil:\n\t\treturn true\n\tcase e.PathAction != nil && o.PathAction == nil:\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc (a *actorConn) startIO() {\n\t\/\/ Setup communication channels\n\tcmdCh := make(chan actorCmd)\n\tcmdReqCh := make(chan actorCmdRequest)\n\toutputCh := make(chan *rpg2d.WorldState)\n\tstopCh := make(chan chan<- struct{})\n\n\t\/\/ Set the channels accessible to the outside world\n\ta.submitCmd = cmdCh\n\ta.readCmdReq = cmdReqCh\n\ta.sendState = outputCh\n\ta.stop = stopCh\n\n\t\/\/ Establish the channel endpoints used inside the go routine\n\tvar newCmd <-chan actorCmd\n\tvar sendCmdReq chan<- actorCmdRequest\n\tvar newState <-chan *rpg2d.WorldState\n\tvar stopReq <-chan chan<- struct{}\n\n\tnewCmd = cmdCh\n\tsendCmdReq = cmdReqCh\n\tnewState = outputCh\n\tstopReq = stopCh\n\n\tgo func() {\n\t\tvar hasStopped chan<- struct{}\n\n\t\t\/\/ Buffer of 1 used to store the most recently\n\t\t\/\/ received actor cmd from the network.\n\t\tvar cmdReq actorCmdRequest\n\n\t\tupdateCmdReqWith := func(c actorCmd) {\n\t\t\tswitch c.cmd {\n\t\t\tcase \"move\":\n\t\t\t\t\/\/ TODO This is a shit place to be having an error to deal with\n\t\t\t\t\/\/ TODO It needs to be dealt with at the packet handler level\n\t\t\t\td, _ := coord.NewDirectionWithString(c.params)\n\n\t\t\t\tcmdReq.moveRequest = moveRequest{\n\t\t\t\t\tTime: stime.Time(c.timeIssued),\n\t\t\t\t\tDirection: d,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\tunlocked:\n\t\t\/\/ # This select prioritizes the following events.\n\t\t\/\/ ## 2 potential events to respond to\n\t\t\/\/ 1. ReadCmdRequest() method requests the actor command request\n\t\t\/\/ 2. stopIO() method has been called\n\t\tselect {\n\t\tcase sendCmdReq <- cmdReq:\n\t\t\t\/\/ Transition: unlocked -> locked\n\t\t\tgoto locked\n\n\t\tcase hasStopped = <-stopReq:\n\t\t\t\/\/ Transition: unlocked -> exit\n\t\t\tgoto exit\n\t\tdefault:\n\t\t}\n\n\t\t\/\/ ## 3 potential events to respond to\n\t\t\/\/ 1. SubmitInput() method has been called with a new command\n\t\t\/\/ 2. ReadCmdRequest() method requests the actor command request\n\t\t\/\/ 3. stopIO() method has been called\n\t\tselect {\n\t\tcase c := <-newCmd:\n\t\t\tupdateCmdReqWith(c)\n\n\t\t\t\/\/ Transition: unlocked -> unlocked\n\t\t\tgoto unlocked\n\n\t\tcase sendCmdReq <- cmdReq:\n\t\t\t\/\/ Transition: unlocked -> locked\n\t\t\tgoto locked\n\n\t\tcase hasStopped = <-stopReq:\n\t\t\t\/\/ Transition: unlocked -> exit\n\t\t\tgoto exit\n\t\t}\n\n\t\tpanic(\"unclosed case in unlocked state select\")\n\n\tlocked:\n\t\t\/\/ Accepting and processing input commands is now on hold\n\n\t\t\/\/ ## 3 potential events to respond to\n\t\t\/\/ 1. WriteState() method has been called with a new world state\n\t\t\/\/ 2. ReadCmdRequest() method requests the actor command request.. again!\n\t\t\/\/ 3. stopIO() method has been called\n\t\tselect {\n\t\tcase state := <-newState:\n\t\t\tif state != nil {\n\t\t\t\ta.SendJson(\"update\", state)\n\t\t\t}\n\n\t\t\t\/\/ Reset the cmdReq object\n\t\t\tcmdReq = actorCmdRequest{}\n\n\t\t\t\/\/ Transition: locked -> unlocked\n\t\t\tgoto unlocked\n\n\t\tcase sendCmdReq <- cmdReq:\n\t\t\t\/\/ Transition: locked -> locked\n\t\t\tgoto locked\n\n\t\tcase hasStopped = <-stopReq:\n\t\t\t\/\/ Transition: locked -> exit\n\t\t\tgoto exit\n\t\t}\n\n\t\tpanic(\"unclosed case in locked state select\")\n\texit:\n\t\thasStopped <- struct{}{}\n\t}()\n}\n\nfunc (c actorConn) SubmitCmd(cmd, params string) error {\n\tparts := strings.Split(cmd, \"=\")\n\n\tif len(parts) != 2 {\n\t\treturn errors.New(\"invalid command\")\n\t}\n\n\ttimeIssued, err := strconv.ParseInt(parts[1], 10, 64)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.submitCmd <- actorCmd{\n\t\ttimeIssued: stime.Time(timeIssued),\n\t\tcmd: parts[0],\n\t\tparams: params,\n\t}\n\n\treturn nil\n}\n\n\/\/ Culls the world state to the actor's viewport\nfunc (a *actor) WriteState(state rpg2d.WorldState) {\n\tc := a.Cell()\n\n\tstate = state.Cull(coord.Bounds{\n\t\tc.Add(-26, 26),\n\t\tc.Add(26, -26),\n\t})\n\n\ta.actorConn.WriteState(state)\n}\n\n\/\/ Diffs the world state so only the changes are sent\nfunc (a *actorConn) WriteState(state rpg2d.WorldState) {\n\tdiff := a.lastState.Diff(state)\n\ta.lastState = state\n\n\t\/\/ Will need this when I start comparing for terrain type changes\n\t\/\/ a.lastState.Prepare()\n\n\tif len(diff.Entities) > 0 || len(diff.Removed) > 0 || diff.TerrainMap != nil {\n\t\tdiff.Prepare()\n\t\ta.sendState <- &diff\n\t} else {\n\t\ta.sendState <- nil\n\t}\n}\n\nfunc (a actorConn) stopIO() {\n\thasStopped := make(chan struct{})\n\n\ta.stop <- hasStopped\n\t<-hasStopped\n}\nImplement a method used by the input phase to retrieve the command requestpackage game\n\nimport (\n\t\"errors\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/ghthor\/engine\/net\/protocol\"\n\t\"github.com\/ghthor\/engine\/rpg2d\"\n\t\"github.com\/ghthor\/engine\/rpg2d\/coord\"\n\t\"github.com\/ghthor\/engine\/rpg2d\/entity\"\n\t\"github.com\/ghthor\/engine\/sim\/stime\"\n)\n\ntype actorCmd struct {\n\ttimeIssued stime.Time\n\tcmd string\n\tparams string\n}\n\ntype moveRequest struct {\n\tstime.Time\n\tcoord.Direction\n}\n\ntype actorCmdRequest struct {\n\tmoveRequest\n}\n\ntype actorConn struct {\n\t\/\/ Comm interface to muxer used by WriteInput() method\n\tsubmitCmd chan<- actorCmd\n\n\t\/\/ Comm interface to muxer used by getEntity() method\n\treadCmdReq <-chan actorCmdRequest\n\n\t\/\/ Comm interface to muxer used by SendState() method\n\tsendState chan<- *rpg2d.WorldState\n\n\t\/\/ Comm interface to muxer used by stopIO() method\n\tstop chan<- chan<- struct{}\n\n\t\/\/ External connection used to publish the world state\n\tprotocol.Conn\n\n\tlastState rpg2d.WorldState\n}\n\nfunc newActorConn(conn protocol.Conn) actorConn {\n\treturn actorConn{Conn: conn}\n}\n\n\/\/ Object stored in the quad tree\ntype actorEntity struct {\n\tid int64\n\n\tname string\n\n\tcell coord.Cell\n\tfacing coord.Direction\n\n\tpathAction *coord.PathAction\n}\n\ntype actorEntityState struct {\n\tEntityId int64 `json:\"id\"`\n\n\tName string `json:\"name\"`\n\n\tFacing string `json:\"facing\"`\n\tCell coord.Cell `json:\"cell\"`\n\tbounds coord.Bounds\n\n\tPathAction *coord.PathAction `json:\"pathAction\"`\n}\n\ntype actor struct {\n\tactorEntity\n\tactorConn\n}\n\nfunc (a actor) Entity() entity.Entity { return a.actorEntity }\nfunc (e actorEntity) Id() int64 { return e.id }\nfunc (e actorEntity) Cell() coord.Cell { return e.cell }\nfunc (e actorEntity) Bounds() coord.Bounds {\n\tbounds := coord.Bounds{\n\t\te.cell,\n\t\te.cell,\n\t}\n\n\tif e.pathAction != nil {\n\t\tbounds = coord.JoinBounds(bounds, e.pathAction.Bounds())\n\t}\n\n\treturn bounds\n}\n\nfunc (e actorEntity) ToState() entity.State {\n\treturn actorEntityState{\n\t\tEntityId: e.id,\n\n\t\tCell: e.cell,\n\t\tFacing: e.facing.String(),\n\n\t\tbounds: e.Bounds(),\n\n\t\tPathAction: e.pathAction,\n\t}\n}\n\nfunc (e actorEntityState) Id() int64 { return e.EntityId }\nfunc (e actorEntityState) Bounds() coord.Bounds { return e.bounds }\nfunc (e actorEntityState) IsDifferentFrom(other entity.State) bool {\n\to := other.(actorEntityState)\n\n\tswitch {\n\tcase e.Facing != o.Facing:\n\t\treturn true\n\n\tcase e.PathAction != nil && o.PathAction != nil:\n\t\tif *e.PathAction != *o.PathAction {\n\t\t\treturn true\n\t\t}\n\n\tcase e.PathAction == nil && o.PathAction != nil:\n\t\treturn true\n\tcase e.PathAction != nil && o.PathAction == nil:\n\t\treturn true\n\t}\n\n\treturn false\n}\n\nfunc (a *actorConn) startIO() {\n\t\/\/ Setup communication channels\n\tcmdCh := make(chan actorCmd)\n\tcmdReqCh := make(chan actorCmdRequest)\n\toutputCh := make(chan *rpg2d.WorldState)\n\tstopCh := make(chan chan<- struct{})\n\n\t\/\/ Set the channels accessible to the outside world\n\ta.submitCmd = cmdCh\n\ta.readCmdReq = cmdReqCh\n\ta.sendState = outputCh\n\ta.stop = stopCh\n\n\t\/\/ Establish the channel endpoints used inside the go routine\n\tvar newCmd <-chan actorCmd\n\tvar sendCmdReq chan<- actorCmdRequest\n\tvar newState <-chan *rpg2d.WorldState\n\tvar stopReq <-chan chan<- struct{}\n\n\tnewCmd = cmdCh\n\tsendCmdReq = cmdReqCh\n\tnewState = outputCh\n\tstopReq = stopCh\n\n\tgo func() {\n\t\tvar hasStopped chan<- struct{}\n\n\t\t\/\/ Buffer of 1 used to store the most recently\n\t\t\/\/ received actor cmd from the network.\n\t\tvar cmdReq actorCmdRequest\n\n\t\tupdateCmdReqWith := func(c actorCmd) {\n\t\t\tswitch c.cmd {\n\t\t\tcase \"move\":\n\t\t\t\t\/\/ TODO This is a shit place to be having an error to deal with\n\t\t\t\t\/\/ TODO It needs to be dealt with at the packet handler level\n\t\t\t\td, _ := coord.NewDirectionWithString(c.params)\n\n\t\t\t\tcmdReq.moveRequest = moveRequest{\n\t\t\t\t\tTime: stime.Time(c.timeIssued),\n\t\t\t\t\tDirection: d,\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\tunlocked:\n\t\t\/\/ # This select prioritizes the following events.\n\t\t\/\/ ## 2 potential events to respond to\n\t\t\/\/ 1. ReadCmdRequest() method requests the actor command request\n\t\t\/\/ 2. stopIO() method has been called\n\t\tselect {\n\t\tcase sendCmdReq <- cmdReq:\n\t\t\t\/\/ Transition: unlocked -> locked\n\t\t\tgoto locked\n\n\t\tcase hasStopped = <-stopReq:\n\t\t\t\/\/ Transition: unlocked -> exit\n\t\t\tgoto exit\n\t\tdefault:\n\t\t}\n\n\t\t\/\/ ## 3 potential events to respond to\n\t\t\/\/ 1. SubmitInput() method has been called with a new command\n\t\t\/\/ 2. ReadCmdRequest() method requests the actor command request\n\t\t\/\/ 3. stopIO() method has been called\n\t\tselect {\n\t\tcase c := <-newCmd:\n\t\t\tupdateCmdReqWith(c)\n\n\t\t\t\/\/ Transition: unlocked -> unlocked\n\t\t\tgoto unlocked\n\n\t\tcase sendCmdReq <- cmdReq:\n\t\t\t\/\/ Transition: unlocked -> locked\n\t\t\tgoto locked\n\n\t\tcase hasStopped = <-stopReq:\n\t\t\t\/\/ Transition: unlocked -> exit\n\t\t\tgoto exit\n\t\t}\n\n\t\tpanic(\"unclosed case in unlocked state select\")\n\n\tlocked:\n\t\t\/\/ Accepting and processing input commands is now on hold\n\n\t\t\/\/ ## 3 potential events to respond to\n\t\t\/\/ 1. WriteState() method has been called with a new world state\n\t\t\/\/ 2. ReadCmdRequest() method requests the actor command request.. again!\n\t\t\/\/ 3. stopIO() method has been called\n\t\tselect {\n\t\tcase state := <-newState:\n\t\t\tif state != nil {\n\t\t\t\ta.SendJson(\"update\", state)\n\t\t\t}\n\n\t\t\t\/\/ Reset the cmdReq object\n\t\t\tcmdReq = actorCmdRequest{}\n\n\t\t\t\/\/ Transition: locked -> unlocked\n\t\t\tgoto unlocked\n\n\t\tcase sendCmdReq <- cmdReq:\n\t\t\t\/\/ Transition: locked -> locked\n\t\t\tgoto locked\n\n\t\tcase hasStopped = <-stopReq:\n\t\t\t\/\/ Transition: locked -> exit\n\t\t\tgoto exit\n\t\t}\n\n\t\tpanic(\"unclosed case in locked state select\")\n\texit:\n\t\thasStopped <- struct{}{}\n\t}()\n}\n\nfunc (c actorConn) SubmitCmd(cmd, params string) error {\n\tparts := strings.Split(cmd, \"=\")\n\n\tif len(parts) != 2 {\n\t\treturn errors.New(\"invalid command\")\n\t}\n\n\ttimeIssued, err := strconv.ParseInt(parts[1], 10, 64)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.submitCmd <- actorCmd{\n\t\ttimeIssued: stime.Time(timeIssued),\n\t\tcmd: parts[0],\n\t\tparams: params,\n\t}\n\n\treturn nil\n}\n\nfunc (c actorConn) ReadCmdRequest() actorCmdRequest {\n\treturn <-c.readCmdReq\n}\n\n\/\/ Culls the world state to the actor's viewport\nfunc (a *actor) WriteState(state rpg2d.WorldState) {\n\tc := a.Cell()\n\n\tstate = state.Cull(coord.Bounds{\n\t\tc.Add(-26, 26),\n\t\tc.Add(26, -26),\n\t})\n\n\ta.actorConn.WriteState(state)\n}\n\n\/\/ Diffs the world state so only the changes are sent\nfunc (a *actorConn) WriteState(state rpg2d.WorldState) {\n\tdiff := a.lastState.Diff(state)\n\ta.lastState = state\n\n\t\/\/ Will need this when I start comparing for terrain type changes\n\t\/\/ a.lastState.Prepare()\n\n\tif len(diff.Entities) > 0 || len(diff.Removed) > 0 || diff.TerrainMap != nil {\n\t\tdiff.Prepare()\n\t\ta.sendState <- &diff\n\t} else {\n\t\ta.sendState <- nil\n\t}\n}\n\nfunc (a actorConn) stopIO() {\n\thasStopped := make(chan struct{})\n\n\ta.stop <- hasStopped\n\t<-hasStopped\n}\n<|endoftext|>"} {"text":"package game\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/ghthor\/engine\/rpg2d\/coord\"\n\t\"github.com\/ghthor\/engine\/rpg2d\/entity\"\n\t\"github.com\/ghthor\/engine\/sim\/stime\"\n)\n\ntype updatePhase struct {\n\tindex actorIndex\n}\n\ntype inputPhase struct {\n\tindex actorIndex\n\tnextId func() entity.Id\n}\n\nfunc (phase updatePhase) Update(e entity.Entity, now stime.Time) entity.Entity {\n\tswitch e := e.(type) {\n\tcase actorEntity:\n\t\tactor := phase.index[e.ActorId()]\n\n\t\t\/\/ Remove any movement actions that have completed\n\t\tif actor.pathAction != nil && actor.pathAction.End() <= now {\n\t\t\tactor.lastMoveAction = actor.pathAction\n\t\t\tactor.cell = actor.pathAction.Dest\n\t\t\tactor.pathAction = nil\n\t\t}\n\n\t\treturn actor.Entity()\n\n\tcase assailEntity:\n\t\t\/\/ Destroy all assail entities\n\t\treturn nil\n\n\tcase sayEntity:\n\t\t\/\/ TODO parametize server fps\n\t\tif e.saidAt+(sayEntityDuration*40) <= now {\n\t\t\t\/\/ Destroy all say entities\n\t\t\treturn nil\n\t\t}\n\n\t\treturn e\n\n\tdefault:\n\t\tpanic(fmt.Sprint(\"unexpected entity type:\", e))\n\t}\n}\n\nfunc (phase inputPhase) ApplyInputsTo(e entity.Entity, now stime.Time) []entity.Entity {\n\tswitch e := e.(type) {\n\tcase actorEntity:\n\t\tvar entities []entity.Entity\n\t\tactor := phase.index[e.ActorId()]\n\n\t\tphase.processMoveCmd(actor, now)\n\t\tentities = append(entities,\n\t\t\tphase.processUseCmd(actor, now)...,\n\t\t)\n\n\t\tentities = append(entities,\n\t\t\tphase.processChatCmd(actor, now)...,\n\t\t)\n\n\t\treturn append(entities, actor.Entity())\n\n\tcase sayEntity:\n\t\treturn []entity.Entity{e}\n\n\tdefault:\n\t\tpanic(fmt.Sprint(\"unexpected entity type:\", e))\n\t}\n}\n\ntype moveRequestType int\n\nconst (\n\tMR_ERROR moveRequestType = iota\n\tMR_MOVE\n\tMR_MOVE_CANCEL\n)\n\ntype moveRequest struct {\n\tmoveRequestType\n\tstime.Time\n\tcoord.Direction\n}\n\ntype moveCmd struct {\n\tstime.Time\n\tcoord.Direction\n}\n\ntype useRequestType int\n\nconst (\n\tUR_ERROR useRequestType = iota\n\tUR_USE\n\tUR_USE_CANCEL\n)\n\ntype useRequest struct {\n\tuseRequestType\n\tstime.Time\n\tskill string\n}\n\ntype useCmd struct {\n\tstime.Time\n\tskill string\n}\n\ntype chatType int\n\nconst (\n\tCR_ERROR chatType = iota\n\tCR_SAY\n)\n\ntype chatRequest struct {\n\tchatType\n\tstime.Time\n\tmsg string\n}\n\ntype chatCmd struct {\n\tchatType\n\tstime.Time\n\tmsg string\n}\n\nfunc newMoveRequest(t moveRequestType, timeIssued stime.Time, params string) (moveRequest, error) {\n\td, err := coord.NewDirectionWithString(params)\n\tif err != nil {\n\t\treturn moveRequest{}, err\n\t}\n\n\treturn moveRequest{\n\t\tt,\n\t\ttimeIssued,\n\t\td,\n\t}, nil\n}\n\nfunc newUseRequest(t useRequestType, timeIssued stime.Time, params string) (useRequest, error) {\n\tswitch params {\n\tcase \"assail\":\n\t\treturn useRequest{t, timeIssued, params}, nil\n\tdefault:\n\t\treturn useRequest{}, fmt.Errorf(\"unknown skill: %s\", params)\n\t}\n}\n\nfunc newChatRequest(t chatType, timeIssued stime.Time, params string) (chatRequest, error) {\n\tif len(params) > 120 {\n\t\treturn chatRequest{}, errors.New(\"chat message exceeded 120 char limit\")\n\t}\n\n\treturn chatRequest{\n\t\tchatType: t,\n\t\tTime: timeIssued,\n\t\tmsg: params,\n\t}, nil\n}\n\n\/\/ If the cmd and params are a valid combination\n\/\/ a request will be made and passed into the\n\/\/ IO muxer. SubmitCmd() will return an error\n\/\/ if the submitted cmd and params are invalid.\nfunc (c actorConn) SubmitCmd(cmd, params string) error {\n\tparts := strings.Split(cmd, \"=\")\n\n\tif len(parts) != 2 {\n\t\treturn errors.New(\"invalid command syntax\")\n\t}\n\n\ttimeIssued, err := strconv.ParseInt(parts[1], 10, 64)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch parts[0] {\n\tcase \"move\":\n\t\tr, err := newMoveRequest(MR_MOVE, stime.Time(timeIssued), params)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tc.submitMoveRequest <- r\n\n\tcase \"moveCancel\":\n\t\tr, err := newMoveRequest(MR_MOVE_CANCEL, stime.Time(timeIssued), params)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tc.submitMoveRequest <- r\n\n\tcase \"use\":\n\t\tr, err := newUseRequest(UR_USE, stime.Time(timeIssued), params)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tc.submitUseRequest <- r\n\n\tcase \"useCancel\":\n\t\tr, err := newUseRequest(UR_USE_CANCEL, stime.Time(timeIssued), params)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tc.submitUseRequest <- r\n\n\tcase \"say\":\n\t\tr, err := newChatRequest(CR_SAY, stime.Time(timeIssued), params)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tc.submitChatRequest <- r\n\n\tdefault:\n\t\treturn fmt.Errorf(\"unknown command: %s\", parts[0])\n\t}\n\n\treturn nil\n}\n\nfunc (c actorConn) ReadMoveCmd() *moveCmd {\n\treturn <-c.readMoveCmd\n}\n\nfunc (a *actor) applyPathAction(pa *coord.PathAction) {\n\tprevPathAction := a.pathAction\n\tprevFacing := a.facing\n\n\ta.undoLastMoveAction = func() {\n\t\ta.pathAction = prevPathAction\n\t\ta.facing = prevFacing\n\t\ta.undoLastMoveAction = nil\n\t}\n\n\ta.pathAction = pa\n\ta.facing = pa.Direction()\n}\n\nfunc (a *actor) applyTurnAction(ta coord.TurnAction) {\n\tprevAction := a.lastMoveAction\n\tprevFacing := a.facing\n\n\ta.undoLastMoveAction = func() {\n\t\ta.lastMoveAction = prevAction\n\t\ta.facing = prevFacing\n\t\ta.undoLastMoveAction = nil\n\t}\n\n\ta.lastMoveAction = ta\n\ta.facing = ta.To\n}\n\nfunc (a *actor) revertMoveAction() {\n\tif a.undoLastMoveAction != nil {\n\t\ta.undoLastMoveAction()\n\t}\n}\n\nfunc (phase inputPhase) processMoveCmd(a *actor, now stime.Time) {\n\tcmd := a.ReadMoveCmd()\n\tif cmd == nil {\n\t\t\/\/ The client has canceled all move requests\n\t\treturn\n\t}\n\n\t\/\/ Actor is already moving so the moveRequest won't be\n\t\/\/ consumed until the path action has been completed\n\tif a.pathAction != nil {\n\t\treturn\n\t}\n\n\t\/\/ Actor may be able to move\n\tpathAction := &coord.PathAction{\n\t\tSpan: stime.NewSpan(now, now+stime.Time(a.speed)),\n\t\tOrig: a.Cell(),\n\t\tDest: a.Cell().Neighbor(cmd.Direction),\n\t}\n\n\tif pathAction.CanHappenAfter(a.lastMoveAction) {\n\t\ta.applyPathAction(pathAction)\n\t\treturn\n\t}\n\n\t\/\/ Actor must change facing\n\tif a.facing != cmd.Direction {\n\t\tturnAction := coord.TurnAction{\n\t\t\tFrom: a.facing,\n\t\t\tTo: cmd.Direction,\n\t\t\tTime: now,\n\t\t}\n\n\t\tif turnAction.CanHappenAfter(a.lastMoveAction) {\n\t\t\ta.applyTurnAction(turnAction)\n\t\t}\n\t}\n}\n\n\/\/ In frames\nconst assailCooldown = 40\n\ntype assailEntity struct {\n\tid entity.Id\n\n\tspawnedBy entity.Id\n\tspawnedAt stime.Time\n\n\tcell coord.Cell\n\n\tdamage int\n}\n\ntype assailEntityState struct {\n\tType string `json:\"type\"`\n\n\tEntityId entity.Id `json:\"id\"`\n\n\tSpawnedBy entity.Id `json:\"spawnedBy\"`\n\tSpawnedAt stime.Time `json:\"spawnedAt\"`\n\n\tCell coord.Cell `json:\"cell\"`\n}\n\nfunc (e assailEntity) Id() entity.Id { return e.id }\nfunc (e assailEntity) Cell() coord.Cell { return e.cell }\nfunc (e assailEntity) Bounds() coord.Bounds {\n\treturn coord.Bounds{e.cell, e.cell}\n}\n\nfunc (e assailEntity) ToState() entity.State {\n\treturn assailEntityState{\n\t\tType: \"assail\",\n\n\t\tEntityId: e.id,\n\n\t\tSpawnedBy: e.spawnedBy,\n\t\tSpawnedAt: e.spawnedAt,\n\n\t\tCell: e.cell,\n\t}\n}\n\nfunc (e assailEntityState) Id() entity.Id { return e.EntityId }\nfunc (e assailEntityState) Bounds() coord.Bounds {\n\treturn coord.Bounds{e.Cell, e.Cell}\n}\n\nfunc (e assailEntityState) IsDifferentFrom(entity.State) bool {\n\treturn true\n}\n\nfunc (c actorConn) ReadUseCmd() *useCmd {\n\treturn <-c.readUseCmd\n}\n\nfunc (phase inputPhase) processUseCmd(a *actor, now stime.Time) []entity.Entity {\n\tcmd := a.ReadUseCmd()\n\tif cmd == nil {\n\t\treturn nil\n\t}\n\n\t\/\/ TODO Only allow when stationary\n\t\/\/ TODO Trigger a cooldown\n\tswitch cmd.skill {\n\tcase \"assail\":\n\t\t\/\/ Implement a cooldown\n\t\tif a.lastAssail.spawnedAt+assailCooldown > now {\n\t\t\treturn nil\n\t\t}\n\n\t\te := assailEntity{\n\t\t\tid: phase.nextId(),\n\n\t\t\tspawnedBy: a.actorEntity.Id(),\n\t\t\tspawnedAt: now,\n\n\t\t\tcell: a.Cell().Neighbor(a.facing),\n\n\t\t\tdamage: 25,\n\t\t}\n\n\t\ta.lastAssail = e\n\n\t\treturn []entity.Entity{e}\n\t}\n\treturn nil\n}\n\n\/\/ In seconds\nconst sayEntityDuration = 3\n\ntype sayEntity struct {\n\tid entity.Id\n\n\tsaidBy entity.Id\n\tsaidAt stime.Time\n\n\tcell coord.Cell\n\n\tmsg string\n}\n\ntype sayEntityState struct {\n\tType string `json:\"type\"`\n\n\tEntityId entity.Id `json:\"id\"`\n\n\tSaidBy entity.Id `json:\"saidBy\"`\n\tSaidAt stime.Time `json:\"saidAt\"`\n\n\tCell coord.Cell `json:\"cell\"`\n\n\tMsg string `json:\"msg\"`\n}\n\nfunc (e sayEntity) Id() entity.Id { return e.id }\nfunc (e sayEntity) Cell() coord.Cell { return e.cell }\nfunc (e sayEntity) Bounds() coord.Bounds {\n\treturn coord.Bounds{e.cell, e.cell}\n}\n\nfunc (e sayEntity) ToState() entity.State {\n\treturn sayEntityState{\n\t\tType: \"say\",\n\n\t\tEntityId: e.id,\n\n\t\tSaidBy: e.saidBy,\n\t\tSaidAt: e.saidAt,\n\n\t\tCell: e.cell,\n\n\t\tMsg: e.msg,\n\t}\n}\n\nfunc (e sayEntityState) Id() entity.Id { return e.EntityId }\nfunc (e sayEntityState) Bounds() coord.Bounds {\n\treturn coord.Bounds{e.Cell, e.Cell}\n}\nfunc (e sayEntityState) IsDifferentFrom(other entity.State) bool {\n\treturn false\n}\n\nfunc (a *actor) ReadChatCmd() *chatCmd {\n\treturn <-a.readChatCmd\n}\n\nfunc (phase inputPhase) processChatCmd(a *actor, now stime.Time) []entity.Entity {\n\tcmd := a.ReadChatCmd()\n\tif cmd == nil {\n\t\treturn nil\n\t}\n\n\tswitch cmd.chatType {\n\tcase CR_SAY:\n\t\treturn []entity.Entity{sayEntity{\n\t\t\tid: phase.nextId(),\n\n\t\t\tsaidBy: a.actorEntity.Id(),\n\t\t\tsaidAt: now,\n\n\t\t\tcell: a.Cell(),\n\n\t\t\tmsg: cmd.msg,\n\t\t}}\n\t}\n\n\treturn nil\n}\n[game] publicize Assail and Say entity statespackage game\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com\/ghthor\/engine\/rpg2d\/coord\"\n\t\"github.com\/ghthor\/engine\/rpg2d\/entity\"\n\t\"github.com\/ghthor\/engine\/sim\/stime\"\n)\n\ntype updatePhase struct {\n\tindex actorIndex\n}\n\ntype inputPhase struct {\n\tindex actorIndex\n\tnextId func() entity.Id\n}\n\nfunc (phase updatePhase) Update(e entity.Entity, now stime.Time) entity.Entity {\n\tswitch e := e.(type) {\n\tcase actorEntity:\n\t\tactor := phase.index[e.ActorId()]\n\n\t\t\/\/ Remove any movement actions that have completed\n\t\tif actor.pathAction != nil && actor.pathAction.End() <= now {\n\t\t\tactor.lastMoveAction = actor.pathAction\n\t\t\tactor.cell = actor.pathAction.Dest\n\t\t\tactor.pathAction = nil\n\t\t}\n\n\t\treturn actor.Entity()\n\n\tcase assailEntity:\n\t\t\/\/ Destroy all assail entities\n\t\treturn nil\n\n\tcase sayEntity:\n\t\t\/\/ TODO parametize server fps\n\t\tif e.saidAt+(sayEntityDuration*40) <= now {\n\t\t\t\/\/ Destroy all say entities\n\t\t\treturn nil\n\t\t}\n\n\t\treturn e\n\n\tdefault:\n\t\tpanic(fmt.Sprint(\"unexpected entity type:\", e))\n\t}\n}\n\nfunc (phase inputPhase) ApplyInputsTo(e entity.Entity, now stime.Time) []entity.Entity {\n\tswitch e := e.(type) {\n\tcase actorEntity:\n\t\tvar entities []entity.Entity\n\t\tactor := phase.index[e.ActorId()]\n\n\t\tphase.processMoveCmd(actor, now)\n\t\tentities = append(entities,\n\t\t\tphase.processUseCmd(actor, now)...,\n\t\t)\n\n\t\tentities = append(entities,\n\t\t\tphase.processChatCmd(actor, now)...,\n\t\t)\n\n\t\treturn append(entities, actor.Entity())\n\n\tcase sayEntity:\n\t\treturn []entity.Entity{e}\n\n\tdefault:\n\t\tpanic(fmt.Sprint(\"unexpected entity type:\", e))\n\t}\n}\n\ntype moveRequestType int\n\nconst (\n\tMR_ERROR moveRequestType = iota\n\tMR_MOVE\n\tMR_MOVE_CANCEL\n)\n\ntype moveRequest struct {\n\tmoveRequestType\n\tstime.Time\n\tcoord.Direction\n}\n\ntype moveCmd struct {\n\tstime.Time\n\tcoord.Direction\n}\n\ntype useRequestType int\n\nconst (\n\tUR_ERROR useRequestType = iota\n\tUR_USE\n\tUR_USE_CANCEL\n)\n\ntype useRequest struct {\n\tuseRequestType\n\tstime.Time\n\tskill string\n}\n\ntype useCmd struct {\n\tstime.Time\n\tskill string\n}\n\ntype chatType int\n\nconst (\n\tCR_ERROR chatType = iota\n\tCR_SAY\n)\n\ntype chatRequest struct {\n\tchatType\n\tstime.Time\n\tmsg string\n}\n\ntype chatCmd struct {\n\tchatType\n\tstime.Time\n\tmsg string\n}\n\nfunc newMoveRequest(t moveRequestType, timeIssued stime.Time, params string) (moveRequest, error) {\n\td, err := coord.NewDirectionWithString(params)\n\tif err != nil {\n\t\treturn moveRequest{}, err\n\t}\n\n\treturn moveRequest{\n\t\tt,\n\t\ttimeIssued,\n\t\td,\n\t}, nil\n}\n\nfunc newUseRequest(t useRequestType, timeIssued stime.Time, params string) (useRequest, error) {\n\tswitch params {\n\tcase \"assail\":\n\t\treturn useRequest{t, timeIssued, params}, nil\n\tdefault:\n\t\treturn useRequest{}, fmt.Errorf(\"unknown skill: %s\", params)\n\t}\n}\n\nfunc newChatRequest(t chatType, timeIssued stime.Time, params string) (chatRequest, error) {\n\tif len(params) > 120 {\n\t\treturn chatRequest{}, errors.New(\"chat message exceeded 120 char limit\")\n\t}\n\n\treturn chatRequest{\n\t\tchatType: t,\n\t\tTime: timeIssued,\n\t\tmsg: params,\n\t}, nil\n}\n\n\/\/ If the cmd and params are a valid combination\n\/\/ a request will be made and passed into the\n\/\/ IO muxer. SubmitCmd() will return an error\n\/\/ if the submitted cmd and params are invalid.\nfunc (c actorConn) SubmitCmd(cmd, params string) error {\n\tparts := strings.Split(cmd, \"=\")\n\n\tif len(parts) != 2 {\n\t\treturn errors.New(\"invalid command syntax\")\n\t}\n\n\ttimeIssued, err := strconv.ParseInt(parts[1], 10, 64)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch parts[0] {\n\tcase \"move\":\n\t\tr, err := newMoveRequest(MR_MOVE, stime.Time(timeIssued), params)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tc.submitMoveRequest <- r\n\n\tcase \"moveCancel\":\n\t\tr, err := newMoveRequest(MR_MOVE_CANCEL, stime.Time(timeIssued), params)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tc.submitMoveRequest <- r\n\n\tcase \"use\":\n\t\tr, err := newUseRequest(UR_USE, stime.Time(timeIssued), params)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tc.submitUseRequest <- r\n\n\tcase \"useCancel\":\n\t\tr, err := newUseRequest(UR_USE_CANCEL, stime.Time(timeIssued), params)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tc.submitUseRequest <- r\n\n\tcase \"say\":\n\t\tr, err := newChatRequest(CR_SAY, stime.Time(timeIssued), params)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tc.submitChatRequest <- r\n\n\tdefault:\n\t\treturn fmt.Errorf(\"unknown command: %s\", parts[0])\n\t}\n\n\treturn nil\n}\n\nfunc (c actorConn) ReadMoveCmd() *moveCmd {\n\treturn <-c.readMoveCmd\n}\n\nfunc (a *actor) applyPathAction(pa *coord.PathAction) {\n\tprevPathAction := a.pathAction\n\tprevFacing := a.facing\n\n\ta.undoLastMoveAction = func() {\n\t\ta.pathAction = prevPathAction\n\t\ta.facing = prevFacing\n\t\ta.undoLastMoveAction = nil\n\t}\n\n\ta.pathAction = pa\n\ta.facing = pa.Direction()\n}\n\nfunc (a *actor) applyTurnAction(ta coord.TurnAction) {\n\tprevAction := a.lastMoveAction\n\tprevFacing := a.facing\n\n\ta.undoLastMoveAction = func() {\n\t\ta.lastMoveAction = prevAction\n\t\ta.facing = prevFacing\n\t\ta.undoLastMoveAction = nil\n\t}\n\n\ta.lastMoveAction = ta\n\ta.facing = ta.To\n}\n\nfunc (a *actor) revertMoveAction() {\n\tif a.undoLastMoveAction != nil {\n\t\ta.undoLastMoveAction()\n\t}\n}\n\nfunc (phase inputPhase) processMoveCmd(a *actor, now stime.Time) {\n\tcmd := a.ReadMoveCmd()\n\tif cmd == nil {\n\t\t\/\/ The client has canceled all move requests\n\t\treturn\n\t}\n\n\t\/\/ Actor is already moving so the moveRequest won't be\n\t\/\/ consumed until the path action has been completed\n\tif a.pathAction != nil {\n\t\treturn\n\t}\n\n\t\/\/ Actor may be able to move\n\tpathAction := &coord.PathAction{\n\t\tSpan: stime.NewSpan(now, now+stime.Time(a.speed)),\n\t\tOrig: a.Cell(),\n\t\tDest: a.Cell().Neighbor(cmd.Direction),\n\t}\n\n\tif pathAction.CanHappenAfter(a.lastMoveAction) {\n\t\ta.applyPathAction(pathAction)\n\t\treturn\n\t}\n\n\t\/\/ Actor must change facing\n\tif a.facing != cmd.Direction {\n\t\tturnAction := coord.TurnAction{\n\t\t\tFrom: a.facing,\n\t\t\tTo: cmd.Direction,\n\t\t\tTime: now,\n\t\t}\n\n\t\tif turnAction.CanHappenAfter(a.lastMoveAction) {\n\t\t\ta.applyTurnAction(turnAction)\n\t\t}\n\t}\n}\n\n\/\/ In frames\nconst assailCooldown = 40\n\ntype assailEntity struct {\n\tid entity.Id\n\n\tspawnedBy entity.Id\n\tspawnedAt stime.Time\n\n\tcell coord.Cell\n\n\tdamage int\n}\n\ntype AssailEntityState struct {\n\tType string `json:\"type\"`\n\n\tEntityId entity.Id `json:\"id\"`\n\n\tSpawnedBy entity.Id `json:\"spawnedBy\"`\n\tSpawnedAt stime.Time `json:\"spawnedAt\"`\n\n\tCell coord.Cell `json:\"cell\"`\n}\n\nfunc (e assailEntity) Id() entity.Id { return e.id }\nfunc (e assailEntity) Cell() coord.Cell { return e.cell }\nfunc (e assailEntity) Bounds() coord.Bounds {\n\treturn coord.Bounds{e.cell, e.cell}\n}\n\nfunc (e assailEntity) ToState() entity.State {\n\treturn AssailEntityState{\n\t\tType: \"assail\",\n\n\t\tEntityId: e.id,\n\n\t\tSpawnedBy: e.spawnedBy,\n\t\tSpawnedAt: e.spawnedAt,\n\n\t\tCell: e.cell,\n\t}\n}\n\nfunc (e AssailEntityState) Id() entity.Id { return e.EntityId }\nfunc (e AssailEntityState) Bounds() coord.Bounds {\n\treturn coord.Bounds{e.Cell, e.Cell}\n}\n\nfunc (e AssailEntityState) IsDifferentFrom(entity.State) bool {\n\treturn true\n}\n\nfunc (c actorConn) ReadUseCmd() *useCmd {\n\treturn <-c.readUseCmd\n}\n\nfunc (phase inputPhase) processUseCmd(a *actor, now stime.Time) []entity.Entity {\n\tcmd := a.ReadUseCmd()\n\tif cmd == nil {\n\t\treturn nil\n\t}\n\n\t\/\/ TODO Only allow when stationary\n\t\/\/ TODO Trigger a cooldown\n\tswitch cmd.skill {\n\tcase \"assail\":\n\t\t\/\/ Implement a cooldown\n\t\tif a.lastAssail.spawnedAt+assailCooldown > now {\n\t\t\treturn nil\n\t\t}\n\n\t\te := assailEntity{\n\t\t\tid: phase.nextId(),\n\n\t\t\tspawnedBy: a.actorEntity.Id(),\n\t\t\tspawnedAt: now,\n\n\t\t\tcell: a.Cell().Neighbor(a.facing),\n\n\t\t\tdamage: 25,\n\t\t}\n\n\t\ta.lastAssail = e\n\n\t\treturn []entity.Entity{e}\n\t}\n\treturn nil\n}\n\n\/\/ In seconds\nconst sayEntityDuration = 3\n\ntype sayEntity struct {\n\tid entity.Id\n\n\tsaidBy entity.Id\n\tsaidAt stime.Time\n\n\tcell coord.Cell\n\n\tmsg string\n}\n\ntype SayEntityState struct {\n\tType string `json:\"type\"`\n\n\tEntityId entity.Id `json:\"id\"`\n\n\tSaidBy entity.Id `json:\"saidBy\"`\n\tSaidAt stime.Time `json:\"saidAt\"`\n\n\tCell coord.Cell `json:\"cell\"`\n\n\tMsg string `json:\"msg\"`\n}\n\nfunc (e sayEntity) Id() entity.Id { return e.id }\nfunc (e sayEntity) Cell() coord.Cell { return e.cell }\nfunc (e sayEntity) Bounds() coord.Bounds {\n\treturn coord.Bounds{e.cell, e.cell}\n}\n\nfunc (e sayEntity) ToState() entity.State {\n\treturn SayEntityState{\n\t\tType: \"say\",\n\n\t\tEntityId: e.id,\n\n\t\tSaidBy: e.saidBy,\n\t\tSaidAt: e.saidAt,\n\n\t\tCell: e.cell,\n\n\t\tMsg: e.msg,\n\t}\n}\n\nfunc (e SayEntityState) Id() entity.Id { return e.EntityId }\nfunc (e SayEntityState) Bounds() coord.Bounds {\n\treturn coord.Bounds{e.Cell, e.Cell}\n}\nfunc (e SayEntityState) IsDifferentFrom(other entity.State) bool {\n\treturn false\n}\n\nfunc (a *actor) ReadChatCmd() *chatCmd {\n\treturn <-a.readChatCmd\n}\n\nfunc (phase inputPhase) processChatCmd(a *actor, now stime.Time) []entity.Entity {\n\tcmd := a.ReadChatCmd()\n\tif cmd == nil {\n\t\treturn nil\n\t}\n\n\tswitch cmd.chatType {\n\tcase CR_SAY:\n\t\treturn []entity.Entity{sayEntity{\n\t\t\tid: phase.nextId(),\n\n\t\t\tsaidBy: a.actorEntity.Id(),\n\t\t\tsaidAt: now,\n\n\t\t\tcell: a.Cell(),\n\n\t\t\tmsg: cmd.msg,\n\t\t}}\n\t}\n\n\treturn nil\n}\n<|endoftext|>"} {"text":"\/*\n Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n\n This file is licensed under the Apache License, Version 2.0 (the \"License\").\n You may not use this file except in compliance with the License. A copy of\n the License is located at\n\n http:\/\/aws.amazon.com\/apache2.0\/\n\n This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n CONDITIONS OF ANY KIND, either express or implied. See the License for the\n specific language governing permissions and limitations under the License.\n*\/\n\npackage main\n\nimport (\n \"github.com\/aws\/aws-sdk-go\/aws\"\n \"github.com\/aws\/aws-sdk-go\/aws\/session\"\n \"github.com\/aws\/aws-sdk-go\/service\/cloudwatch\"\n\n \"fmt\"\n)\n\nfunc main() {\n if len(os.Args) != 4 {\n fmt.Println(\"You must supply a metric name, dimension, value, and namespace\")\n os.Exit(1)\n }\n\n metric := os.Args[1]\n dimensions := os.Args[3]\n namespace := os.Args[2]\n \n \/\/ Initialize a session that the SDK uses to load\n \/\/ credentials from the shared credentials file ~\/.aws\/credentials\n \/\/ and configuration from the shared configuration file ~\/.aws\/config.\n sess := session.Must(session.NewSessionWithOptions(session.Options{\n SharedConfigState: session.SharedConfigEnable,\n }))\n\n \/\/ Create new cloudwatch client.\n svc := cloudwatch.New(sess)\n\n \/\/ This will disable the alarm.\n result, err := svc.PutMetricData(&cloudwatch.PutMetricDataInput{\n MetricData: []*cloudwatch.MetricDatum{\n &cloudwatch.MetricDatum{\n MetricName: aws.String(metric),\n Unit: aws.String(cloudwatch.StandardUnitNone),\n Value: aws.Float64(1.0),\n Dimensions: []*cloudwatch.Dimension{\n &cloudwatch.Dimension{\n Name: aws.String(dimension),\n Value: aws.String(value),\n },\n },\n },\n },\n Namespace: aws.String(namespace),\n })\n if err != nil {\n fmt.Println(\"Error\", err)\n return\n }\n\n fmt.Println(\"Success\", result)\n}\nUpdated Go CloudWatch example\/*\n Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n\n This file is licensed under the Apache License, Version 2.0 (the \"License\").\n You may not use this file except in compliance with the License. A copy of\n the License is located at\n\n http:\/\/aws.amazon.com\/apache2.0\/\n\n This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n CONDITIONS OF ANY KIND, either express or implied. See the License for the\n specific language governing permissions and limitations under the License.\n*\/\n\npackage main\n\nimport (\n \"github.com\/aws\/aws-sdk-go\/aws\"\n \"github.com\/aws\/aws-sdk-go\/aws\/session\"\n \"github.com\/aws\/aws-sdk-go\/service\/cloudwatch\"\n\n \"fmt\"\n)\n\nfunc main() {\n \/\/ Initialize a session that the SDK uses to load\n \/\/ credentials from the shared credentials file ~\/.aws\/credentials\n \/\/ and configuration from the shared configuration file ~\/.aws\/config.\n sess := session.Must(session.NewSessionWithOptions(session.Options{\n SharedConfigState: session.SharedConfigEnable,\n }))\n\n \/\/ Create new cloudwatch client.\n svc := cloudwatch.New(sess)\n\n _, err := svc.PutMetricData(&cloudwatch.PutMetricDataInput{\n Namespace: aws.String(\"Site\/Traffic\"),\n MetricData: []*cloudwatch.MetricDatum{\n &cloudwatch.MetricDatum{\n MetricName: aws.String(\"UniqueVisitors\"),\n Unit: aws.String(\"Count\"),\n Value: aws.Float64(5885.0),\n Dimensions: []*cloudwatch.Dimension{\n &cloudwatch.Dimension{\n Name: aws.String(\"SiteName\"),\n Value: aws.String(\"example.com\"),\n },\n },\n },\n &cloudwatch.MetricDatum{\n MetricName: aws.String(\"UniqueVisits\"),\n Unit: aws.String(\"Count\"),\n Value: aws.Float64(8628.0),\n Dimensions: []*cloudwatch.Dimension{\n &cloudwatch.Dimension{\n Name: aws.String(\"SiteName\"),\n Value: aws.String(\"example.com\"),\n },\n },\n },\n &cloudwatch.MetricDatum{\n MetricName: aws.String(\"PageViews\"),\n Unit: aws.String(\"Count\"),\n Value: aws.Float64(18057.0),\n Dimensions: []*cloudwatch.Dimension{\n &cloudwatch.Dimension{\n Name: aws.String(\"PageURL\"),\n Value: aws.String(\"my-page.html\"),\n },\n },\n },\n },\n })\n if err != nil {\n fmt.Println(\"Error adding metrics:\", err.Error())\n return\n }\n\n \/\/ Get information about metrics\n result, err := svc.ListMetrics(&cloudwatch.ListMetricsInput{\n Namespace: aws.String(\"Site\/Traffic\"),\n })\n if err != nil {\n fmt.Println(\"Error getting metrics:\", err.Error())\n return\n }\n\n for _, metric := range result.Metrics {\n fmt.Println(*metric.MetricName)\n\n for _, dim := range metric.Dimensions {\n fmt.Println(*dim.Name + \":\", *dim.Value)\n fmt.Println()\n }\n }\n}\n<|endoftext|>"} {"text":"package koding\n\nimport (\n\t\"koding\/kites\/kloud\/eventer\"\n\t\"koding\/kites\/kloud\/machinestate\"\n\t\"koding\/kites\/kloud\/multierrors\"\n\t\"koding\/kites\/kloud\/protocol\"\n\t\"sync\"\n\t\"time\"\n\n\t\"labix.org\/v2\/mgo\"\n\t\"labix.org\/v2\/mgo\/bson\"\n)\n\nvar (\n\t\/\/ Be cautious if your try to lower this. A build might really last more\n\t\/\/ than 10 minutes.\n\tCleanUpTimeout = time.Minute * 10\n)\n\n\/\/ RunCleaner runs the given cleaners for the given timeout duration. It cleans\n\/\/ up\/resets machine documents and VM leftovers.\nfunc (p *Provider) RunCleaners(interval time.Duration) {\n\tcleaners := func() {\n\t\t\/\/ run for the first time\n\t\tif err := p.CleanLocks(CleanUpTimeout); err != nil {\n\t\t\tp.Log.Warning(\"Cleaning locks: %s\", err)\n\t\t}\n\n\t\tif err := p.CleanDeletedVMs(); err != nil {\n\t\t\tp.Log.Warning(\"Cleaning deleted vms: %s\", err)\n\t\t}\n\n\t\tif err := p.CleanStates(CleanUpTimeout); err != nil {\n\t\t\tp.Log.Warning(\"Cleaning states vms: %s\", err)\n\t\t}\n\t}\n\n\tcleaners()\n\tfor _ = range time.Tick(interval) {\n\t\tgo cleaners() \/\/ do not block\n\t}\n}\n\n\/\/ CleanDeletedVMS deletes VMs that have userDeleted set to true. This happens\n\/\/ when the user deletes their account but kloud couldn't delete\/terminate\n\/\/ their VM's. This can happen for example if the user deletes their VM during\n\/\/ an ongoing (build, start, stop...) process. There will be a lock due Build\n\/\/ which will prevent to delete it.\nfunc (p *Provider) CleanDeletedVMs() error {\n\tmachines := make([]MachineDocument, 0)\n\n\tquery := func(c *mgo.Collection) error {\n\t\tdeletedMachines := bson.M{\n\t\t\t\"userDeleted\": true,\n\t\t}\n\n\t\tmachine := MachineDocument{}\n\t\titer := c.Find(deletedMachines).Batch(50).Iter()\n\t\tfor iter.Next(&machine) {\n\t\t\tmachines = append(machines, machine)\n\t\t}\n\n\t\treturn iter.Close()\n\t}\n\n\tif err := p.Session.Run(\"jMachines\", query); err != nil {\n\t\treturn err\n\t}\n\n\tdeleteMachine := func(id string) error {\n\t\t\/\/ we don't use p.Get() because it checks the user existence too,\n\t\t\/\/ however for deleted machines there are no users\n\t\tmachine := &MachineDocument{}\n\t\tif err := p.Session.Run(\"jMachines\", func(c *mgo.Collection) error {\n\t\t\treturn c.FindId(bson.ObjectIdHex(id)).One(&machine)\n\t\t}); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tm := &protocol.Machine{\n\t\t\tId: id,\n\t\t\tUsername: machine.Credential, \/\/ contains the username for koding provider\n\t\t\tProvider: machine.Provider,\n\t\t\tBuilder: machine.Meta,\n\t\t\tState: machine.State(),\n\t\t\tIpAddress: machine.IpAddress,\n\t\t\tQueryString: machine.QueryString,\n\t\t\tEventer: &eventer.Events{},\n\t\t}\n\t\tm.Domain.Name = machine.Domain\n\n\t\t\/\/ if there is no instance Id just remove the document\n\t\tif _, ok := m.Builder[\"instanceId\"]; !ok {\n\t\t\treturn p.Delete(id)\n\t\t}\n\n\t\tp.Log.Info(\"[%s] cleaner: terminating user deleted machine. User %s\",\n\t\t\tid, m.Username)\n\n\t\tp.Destroy(m)\n\n\t\treturn p.Delete(id)\n\t}\n\n\tfor _, machine := range machines {\n\t\tif err := deleteMachine(machine.Id.Hex()); err != nil {\n\t\t\tp.Log.Error(\"[%s] couldn't terminate user deleted machine: %s\",\n\t\t\t\tmachine.Id.Hex(), err.Error())\n\t\t}\n\t}\n\n\tmachines = nil \/\/ garbage collect it\n\n\treturn nil\n}\n\n\/\/ CleanLocks resets documents that where locked by workers who died and left\n\/\/ the documents untouched\/unlocked. These documents are *ghost* documents,\n\/\/ because they have an assignee that is not nil no worker will pick it up. The\n\/\/ given timeout specificies to look up documents from now on.\nfunc (p *Provider) CleanLocks(timeout time.Duration) error {\n\tquery := func(c *mgo.Collection) error {\n\t\t\/\/ machines that can't be updated because they seems to be in progress\n\t\tghostMachines := bson.M{\n\t\t\t\"assignee.inProgress\": true,\n\t\t\t\"assignee.assignedAt\": bson.M{\"$lt\": time.Now().UTC().Add(-timeout)},\n\t\t}\n\n\t\tcleanMachines := bson.M{\n\t\t\t\"assignee.inProgress\": false,\n\t\t\t\"assignee.assignedAt\": time.Now().UTC(),\n\t\t}\n\n\t\t\/\/ reset all machines\n\t\tinfo, err := c.UpdateAll(ghostMachines, bson.M{\"$set\": cleanMachines})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ only show if there is something, that will prevent spamming the\n\t\t\/\/ output with the same content over and over\n\t\tif info.Updated != 0 {\n\t\t\tp.Log.Info(\"[checker] cleaned up %d documents\", info.Updated)\n\t\t}\n\n\t\treturn nil\n\t}\n\n\treturn p.Session.Run(\"jMachines\", query)\n}\n\n\/\/ CleanStates resets documents that has machine states in progress mode\n\/\/ (building, stopping, etc..) which weren't updated since 10 minutes. This\n\/\/ could be caused because of Kloud restarts or panics.\nfunc (p *Provider) CleanStates(timeout time.Duration) error {\n\tcleanstateFunc := func(badstate, goodstate string) error {\n\t\treturn p.Session.Run(\"jMachines\", func(c *mgo.Collection) error {\n\t\t\t\/\/ machines that can't be updated because they seems to be in progress\n\t\t\tbadstateMachines := bson.M{\n\t\t\t\t\"status.state\": badstate,\n\t\t\t\t\"status.modifiedAt\": bson.M{\"$lt\": time.Now().UTC().Add(-timeout)},\n\t\t\t}\n\n\t\t\tcleanMachines := bson.M{\n\t\t\t\t\"status.state\": goodstate,\n\t\t\t\t\"status.modifiedAt\": time.Now().UTC(),\n\t\t\t}\n\n\t\t\t\/\/ reset all machines\n\t\t\tinfo, err := c.UpdateAll(badstateMachines, bson.M{\"$set\": cleanMachines})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t\/\/ only show if there is something, that will prevent spamming the\n\t\t\t\/\/ output with the same content over and over\n\t\t\tif info.Updated != 0 {\n\t\t\t\tp.Log.Info(\"[state cleaner] fixed %d documents from '%s' to '%s'\",\n\t\t\t\t\tinfo.Updated, badstate, goodstate)\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\t}\n\n\tprogressModes := []struct {\n\t\tbad string\n\t\tgood string\n\t}{\n\t\t{machinestate.Building.String(), machinestate.NotInitialized.String()},\n\t\t{machinestate.Terminating.String(), machinestate.Terminated.String()},\n\t\t{machinestate.Stopping.String(), machinestate.Stopped.String()},\n\t\t{machinestate.Starting.String(), machinestate.Stopped.String()},\n\t}\n\n\terrs := multierrors.New()\n\n\tvar wg sync.WaitGroup\n\tfor _, state := range progressModes {\n\t\twg.Add(1)\n\t\tgo func(bad, good string) {\n\t\t\tdefer wg.Done()\n\t\t\terr := cleanstateFunc(bad, good)\n\t\t\terrs.Add(err)\n\t\t}(state.bad, state.good)\n\t}\n\n\twg.Wait()\n\n\t\/\/ if there is no errors just return a nil\n\tif errs.Len() == 0 {\n\t\treturn nil\n\t}\n\n\treturn errs\n}\nkloud\/cleaners: only update when there is no more any lockpackage koding\n\nimport (\n\t\"koding\/kites\/kloud\/eventer\"\n\t\"koding\/kites\/kloud\/machinestate\"\n\t\"koding\/kites\/kloud\/multierrors\"\n\t\"koding\/kites\/kloud\/protocol\"\n\t\"sync\"\n\t\"time\"\n\n\t\"labix.org\/v2\/mgo\"\n\t\"labix.org\/v2\/mgo\/bson\"\n)\n\nvar (\n\t\/\/ Be cautious if your try to lower this. A build might really last more\n\t\/\/ than 10 minutes.\n\tCleanUpTimeout = time.Minute * 10\n)\n\n\/\/ RunCleaner runs the given cleaners for the given timeout duration. It cleans\n\/\/ up\/resets machine documents and VM leftovers.\nfunc (p *Provider) RunCleaners(interval time.Duration) {\n\tcleaners := func() {\n\t\t\/\/ run for the first time\n\t\tif err := p.CleanLocks(CleanUpTimeout); err != nil {\n\t\t\tp.Log.Warning(\"Cleaning locks: %s\", err)\n\t\t}\n\n\t\tif err := p.CleanDeletedVMs(); err != nil {\n\t\t\tp.Log.Warning(\"Cleaning deleted vms: %s\", err)\n\t\t}\n\n\t\tif err := p.CleanStates(CleanUpTimeout); err != nil {\n\t\t\tp.Log.Warning(\"Cleaning states vms: %s\", err)\n\t\t}\n\t}\n\n\tcleaners()\n\tfor _ = range time.Tick(interval) {\n\t\tgo cleaners() \/\/ do not block\n\t}\n}\n\n\/\/ CleanDeletedVMS deletes VMs that have userDeleted set to true. This happens\n\/\/ when the user deletes their account but kloud couldn't delete\/terminate\n\/\/ their VM's. This can happen for example if the user deletes their VM during\n\/\/ an ongoing (build, start, stop...) process. There will be a lock due Build\n\/\/ which will prevent to delete it.\nfunc (p *Provider) CleanDeletedVMs() error {\n\tmachines := make([]MachineDocument, 0)\n\n\tquery := func(c *mgo.Collection) error {\n\t\tdeletedMachines := bson.M{\n\t\t\t\"userDeleted\": true,\n\t\t}\n\n\t\tmachine := MachineDocument{}\n\t\titer := c.Find(deletedMachines).Batch(50).Iter()\n\t\tfor iter.Next(&machine) {\n\t\t\tmachines = append(machines, machine)\n\t\t}\n\n\t\treturn iter.Close()\n\t}\n\n\tif err := p.Session.Run(\"jMachines\", query); err != nil {\n\t\treturn err\n\t}\n\n\tdeleteMachine := func(id string) error {\n\t\t\/\/ we don't use p.Get() because it checks the user existence too,\n\t\t\/\/ however for deleted machines there are no users\n\t\tmachine := &MachineDocument{}\n\t\tif err := p.Session.Run(\"jMachines\", func(c *mgo.Collection) error {\n\t\t\treturn c.FindId(bson.ObjectIdHex(id)).One(&machine)\n\t\t}); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tm := &protocol.Machine{\n\t\t\tId: id,\n\t\t\tUsername: machine.Credential, \/\/ contains the username for koding provider\n\t\t\tProvider: machine.Provider,\n\t\t\tBuilder: machine.Meta,\n\t\t\tState: machine.State(),\n\t\t\tIpAddress: machine.IpAddress,\n\t\t\tQueryString: machine.QueryString,\n\t\t\tEventer: &eventer.Events{},\n\t\t}\n\t\tm.Domain.Name = machine.Domain\n\n\t\t\/\/ if there is no instance Id just remove the document\n\t\tif _, ok := m.Builder[\"instanceId\"]; !ok {\n\t\t\treturn p.Delete(id)\n\t\t}\n\n\t\tp.Log.Info(\"[%s] cleaner: terminating user deleted machine. User %s\",\n\t\t\tid, m.Username)\n\n\t\tp.Destroy(m)\n\n\t\treturn p.Delete(id)\n\t}\n\n\tfor _, machine := range machines {\n\t\tif err := deleteMachine(machine.Id.Hex()); err != nil {\n\t\t\tp.Log.Error(\"[%s] couldn't terminate user deleted machine: %s\",\n\t\t\t\tmachine.Id.Hex(), err.Error())\n\t\t}\n\t}\n\n\tmachines = nil \/\/ garbage collect it\n\n\treturn nil\n}\n\n\/\/ CleanLocks resets documents that where locked by workers who died and left\n\/\/ the documents untouched\/unlocked. These documents are *ghost* documents,\n\/\/ because they have an assignee that is not nil no worker will pick it up. The\n\/\/ given timeout specificies to look up documents from now on.\nfunc (p *Provider) CleanLocks(timeout time.Duration) error {\n\tquery := func(c *mgo.Collection) error {\n\t\t\/\/ machines that can't be updated because they seems to be in progress\n\t\tghostMachines := bson.M{\n\t\t\t\"assignee.inProgress\": true,\n\t\t\t\"assignee.assignedAt\": bson.M{\"$lt\": time.Now().UTC().Add(-timeout)},\n\t\t}\n\n\t\tcleanMachines := bson.M{\n\t\t\t\"assignee.inProgress\": false,\n\t\t\t\"assignee.assignedAt\": time.Now().UTC(),\n\t\t}\n\n\t\t\/\/ reset all machines\n\t\tinfo, err := c.UpdateAll(ghostMachines, bson.M{\"$set\": cleanMachines})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ only show if there is something, that will prevent spamming the\n\t\t\/\/ output with the same content over and over\n\t\tif info.Updated != 0 {\n\t\t\tp.Log.Info(\"[checker] cleaned up %d documents\", info.Updated)\n\t\t}\n\n\t\treturn nil\n\t}\n\n\treturn p.Session.Run(\"jMachines\", query)\n}\n\n\/\/ CleanStates resets documents that has machine states in progress mode\n\/\/ (building, stopping, etc..) which weren't updated since 10 minutes. This\n\/\/ could be caused because of Kloud restarts or panics.\nfunc (p *Provider) CleanStates(timeout time.Duration) error {\n\tcleanstateFunc := func(badstate, goodstate string) error {\n\t\treturn p.Session.Run(\"jMachines\", func(c *mgo.Collection) error {\n\t\t\t\/\/ machines that can't be updated because they seems to be in progress\n\t\t\tbadstateMachines := bson.M{\n\t\t\t\t\"assignee.inProgress\": false, \/\/ never update during a onging process :)\n\t\t\t\t\"status.state\": badstate,\n\t\t\t\t\"status.modifiedAt\": bson.M{\"$lt\": time.Now().UTC().Add(-timeout)},\n\t\t\t}\n\n\t\t\tcleanMachines := bson.M{\n\t\t\t\t\"status.state\": goodstate,\n\t\t\t\t\"status.modifiedAt\": time.Now().UTC(),\n\t\t\t}\n\n\t\t\t\/\/ reset all machines\n\t\t\tinfo, err := c.UpdateAll(badstateMachines, bson.M{\"$set\": cleanMachines})\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t\/\/ only show if there is something, that will prevent spamming the\n\t\t\t\/\/ output with the same content over and over\n\t\t\tif info.Updated != 0 {\n\t\t\t\tp.Log.Info(\"[state cleaner] fixed %d documents from '%s' to '%s'\",\n\t\t\t\t\tinfo.Updated, badstate, goodstate)\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\t}\n\n\tprogressModes := []struct {\n\t\tbad string\n\t\tgood string\n\t}{\n\t\t{machinestate.Building.String(), machinestate.NotInitialized.String()},\n\t\t{machinestate.Terminating.String(), machinestate.Terminated.String()},\n\t\t{machinestate.Stopping.String(), machinestate.Stopped.String()},\n\t\t{machinestate.Starting.String(), machinestate.Stopped.String()},\n\t}\n\n\terrs := multierrors.New()\n\n\tvar wg sync.WaitGroup\n\tfor _, state := range progressModes {\n\t\twg.Add(1)\n\t\tgo func(bad, good string) {\n\t\t\tdefer wg.Done()\n\t\t\terr := cleanstateFunc(bad, good)\n\t\t\terrs.Add(err)\n\t\t}(state.bad, state.good)\n\t}\n\n\twg.Wait()\n\n\t\/\/ if there is no errors just return a nil\n\tif errs.Len() == 0 {\n\t\treturn nil\n\t}\n\n\treturn errs\n}\n<|endoftext|>"} {"text":"\/*\nCopyright 2021 The Vitess Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n\thttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage grpctmclient\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"io\"\n\t\"sort\"\n\t\"sync\"\n\t\"time\"\n\n\t\"google.golang.org\/grpc\"\n\n\t\"vitess.io\/vitess\/go\/netutil\"\n\t\"vitess.io\/vitess\/go\/stats\"\n\t\"vitess.io\/vitess\/go\/sync2\"\n\t\"vitess.io\/vitess\/go\/vt\/grpcclient\"\n\t\"vitess.io\/vitess\/go\/vt\/vttablet\/tmclient\"\n\n\ttabletmanagerservicepb \"vitess.io\/vitess\/go\/vt\/proto\/tabletmanagerservice\"\n\ttopodatapb \"vitess.io\/vitess\/go\/vt\/proto\/topodata\"\n)\n\nvar (\n\tdefaultPoolCapacity = flag.Int(\"tablet_manager_grpc_connpool_size\", 100, \"number of tablets to keep tmclient connections open to\")\n)\n\nfunc init() {\n\ttmclient.RegisterTabletManagerClientFactory(\"grpc-cached\", func() tmclient.TabletManagerClient {\n\t\treturn NewCachedConnClient(*defaultPoolCapacity)\n\t})\n}\n\n\/\/ closeFunc allows a standalone function to implement io.Closer, similar to\n\/\/ how http.HandlerFunc allows standalone functions to implement http.Handler.\ntype closeFunc func() error\n\nfunc (fn closeFunc) Close() error {\n\treturn fn()\n}\n\nvar _ io.Closer = (*closeFunc)(nil)\n\ntype cachedConn struct {\n\ttabletmanagerservicepb.TabletManagerClient\n\tcc *grpc.ClientConn\n\n\taddr string\n\tlastAccessTime time.Time\n\trefs int\n}\n\ntype cachedConnDialer struct {\n\tm sync.Mutex\n\tconns map[string]*cachedConn\n\tevict []*cachedConn\n\tevictSorted bool\n\tconnWaitSema *sync2.Semaphore\n}\n\nvar dialerStats = struct {\n\tConnReuse *stats.Gauge\n\tConnNew *stats.Gauge\n\tDialTimeouts *stats.Gauge\n\tDialTimings *stats.Timings\n}{\n\tConnReuse: stats.NewGauge(\"tabletmanagerclient_cachedconn_reuse\", \"number of times a call to dial() was able to reuse an existing connection\"),\n\tConnNew: stats.NewGauge(\"tabletmanagerclient_cachedconn_new\", \"number of times a call to dial() resulted in a dialing a new grpc clientconn\"),\n\tDialTimeouts: stats.NewGauge(\"tabletmanagerclient_cachedconn_dial_timeouts\", \"number of context timeouts during dial()\"),\n\tDialTimings: stats.NewTimings(\"tabletmanagerclient_cachedconn_dialtimings\", \"timings for various dial paths\", \"path\", \"rlock_fast\", \"sema_fast\", \"sema_poll\"),\n}\n\n\/\/ NewCachedConnClient returns a grpc Client that caches connections to the different tablets\nfunc NewCachedConnClient(capacity int) *Client {\n\tdialer := &cachedConnDialer{\n\t\tconns: make(map[string]*cachedConn, capacity),\n\t\tevict: make([]*cachedConn, 0, capacity),\n\t\tconnWaitSema: sync2.NewSemaphore(capacity, 0),\n\t}\n\treturn &Client{dialer}\n}\n\nvar _ dialer = (*cachedConnDialer)(nil)\n\nfunc (dialer *cachedConnDialer) sortEvictionsLocked() {\n\tif !dialer.evictSorted {\n\t\tsort.Slice(dialer.evict, func(i, j int) bool {\n\t\t\tleft, right := dialer.evict[i], dialer.evict[j]\n\t\t\tif left.refs == right.refs {\n\t\t\t\treturn left.lastAccessTime.After(right.lastAccessTime)\n\t\t\t}\n\t\t\treturn left.refs > right.refs\n\t\t})\n\t\tdialer.evictSorted = true\n\t}\n}\n\nfunc (dialer *cachedConnDialer) dial(ctx context.Context, tablet *topodatapb.Tablet) (tabletmanagerservicepb.TabletManagerClient, io.Closer, error) {\n\tstart := time.Now()\n\taddr := getTabletAddr(tablet)\n\n\tif client, closer, found, err := dialer.tryFromCache(addr, &dialer.m); found {\n\t\tdialerStats.DialTimings.Add(\"rlock_fast\", time.Since(start))\n\t\treturn client, closer, err\n\t}\n\n\tif dialer.connWaitSema.TryAcquire() {\n\t\tdefer func() {\n\t\t\tdialerStats.DialTimings.Add(\"sema_fast\", time.Since(start))\n\t\t}()\n\n\t\t\/\/ Check if another goroutine managed to dial a conn for the same addr\n\t\t\/\/ while we were waiting for the write lock. This is identical to the\n\t\t\/\/ read-lock section above.\n\t\tif client, closer, found, err := dialer.tryFromCache(addr, &dialer.m); found {\n\t\t\treturn client, closer, err\n\t\t}\n\t\treturn dialer.newdial(addr)\n\t}\n\n\tdefer func() {\n\t\tdialerStats.DialTimings.Add(\"sema_poll\", time.Since(start))\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tdialerStats.DialTimeouts.Add(1)\n\t\t\treturn nil, nil, ctx.Err()\n\t\tdefault:\n\t\t\tif client, closer, found, err := dialer.pollOnce(addr); found {\n\t\t\t\treturn client, closer, err\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ tryFromCache tries to get a connection from the cache, performing a redial\n\/\/ on that connection if it exists. It returns a TabletManagerClient impl, an\n\/\/ io.Closer, a flag to indicate whether a connection was found in the cache,\n\/\/ and an error, which is always nil.\n\/\/\n\/\/ In addition to the addr being dialed, tryFromCache takes a sync.Locker which,\n\/\/ if not nil, will be used to wrap the lookup and redial in that lock. This\n\/\/ function can be called in situations where the conns map is locked\n\/\/ externally (like in pollOnce), so we do not want to manage the locks here. In\n\/\/ other cases (like in the rlock_fast path of dial()), we pass in the RLocker\n\/\/ to ensure we have a read lock on the cache for the duration of the call.\nfunc (dialer *cachedConnDialer) tryFromCache(addr string, locker sync.Locker) (client tabletmanagerservicepb.TabletManagerClient, closer io.Closer, found bool, err error) {\n\tif locker != nil {\n\t\tlocker.Lock()\n\t\tdefer locker.Unlock()\n\t}\n\n\tif conn, ok := dialer.conns[addr]; ok {\n\t\tclient, closer, err := dialer.redialLocked(conn)\n\t\treturn client, closer, ok, err\n\t}\n\n\treturn nil, nil, false, nil\n}\n\n\/\/ pollOnce is called on each iteration of the polling loop in dial(). It:\n\/\/ - locks the conns cache for writes\n\/\/ - attempts to get a connection from the cache. If found, redial() it and exit.\n\/\/ - locks the queue\n\/\/ - peeks at the head of the eviction queue. if the peeked conn has no refs, it\n\/\/ is unused, and can be evicted to make room for the new connection to addr.\n\/\/ If the peeked conn has refs, exit.\n\/\/ - pops the conn we just peeked from the queue, delete it from the cache, and\n\/\/ close the underlying ClientConn for that conn.\n\/\/ - attempt a newdial. if the newdial fails, it will release a slot on the\n\/\/ connWaitSema, so another dial() call can successfully acquire it to dial\n\/\/ a new conn. if the newdial succeeds, we will have evicted one conn, but\n\/\/ added another, so the net change is 0, and no changes to the connWaitSema\n\/\/ are made.\n\/\/\n\/\/ It returns a TabletManagerClient impl, an io.Closer, a flag to indicate\n\/\/ whether the dial() poll loop should exit, and an error.\nfunc (dialer *cachedConnDialer) pollOnce(addr string) (client tabletmanagerservicepb.TabletManagerClient, closer io.Closer, found bool, err error) {\n\tdialer.m.Lock()\n\n\tif client, closer, found, err := dialer.tryFromCache(addr, nil); found {\n\t\tdialer.m.Unlock()\n\t\treturn client, closer, found, err\n\t}\n\n\tdialer.sortEvictionsLocked()\n\n\tconn := dialer.evict[len(dialer.evict)-1]\n\tif conn.refs != 0 {\n\t\tdialer.m.Unlock()\n\t\treturn nil, nil, false, nil\n\t}\n\n\tdialer.evict = dialer.evict[:len(dialer.evict)-1]\n\tdelete(dialer.conns, conn.addr)\n\tconn.cc.Close()\n\tdialer.m.Unlock()\n\n\tclient, closer, err = dialer.newdial(addr)\n\treturn client, closer, true, err\n}\n\n\/\/ newdial creates a new cached connection, and updates the cache and eviction\n\/\/ queue accordingly. If newdial fails to create the underlying\n\/\/ gRPC connection, it will make a call to Release the connWaitSema for other\n\/\/ newdial calls.\n\/\/\n\/\/ It returns the three-tuple of client-interface, closer, and error that the\n\/\/ main dial func returns.\nfunc (dialer *cachedConnDialer) newdial(addr string) (tabletmanagerservicepb.TabletManagerClient, io.Closer, error) {\n\tdialerStats.ConnNew.Add(1)\n\n\topt, err := grpcclient.SecureDialOption(*cert, *key, *ca, *name)\n\tif err != nil {\n\t\tdialer.connWaitSema.Release()\n\t\treturn nil, nil, err\n\t}\n\n\tcc, err := grpcclient.Dial(addr, grpcclient.FailFast(false), opt)\n\tif err != nil {\n\t\tdialer.connWaitSema.Release()\n\t\treturn nil, nil, err\n\t}\n\n\tdialer.m.Lock()\n\tdefer dialer.m.Unlock()\n\n\tif conn, existing := dialer.conns[addr]; existing {\n\t\t\/\/ race condition: some other goroutine has dialed our tablet before we have;\n\t\t\/\/ this is not great, but shouldn't happen often (if at all), so we're going to\n\t\t\/\/ close this connection and reuse the existing one. by doing this, we can keep\n\t\t\/\/ the actual Dial out of the global lock and significantly increase throughput\n\t\tcc.Close()\n\t\treturn dialer.redialLocked(conn)\n\t}\n\n\tconn := &cachedConn{\n\t\tTabletManagerClient: tabletmanagerservicepb.NewTabletManagerClient(cc),\n\t\tcc: cc,\n\t\tlastAccessTime: time.Now(),\n\t\trefs: 1,\n\t\taddr: addr,\n\t}\n\tdialer.evict = append(dialer.evict, conn)\n\tdialer.evictSorted = false\n\tdialer.conns[addr] = conn\n\n\treturn dialer.connWithCloser(conn)\n}\n\n\/\/ redialLocked takes an already-dialed connection in the cache does all the work of\n\/\/ lending that connection out to one more caller. this should only ever be\n\/\/ called while holding at least the RLock on dialer.m (but the write lock is\n\/\/ fine too), to prevent the connection from getting evicted out from under us.\n\/\/\n\/\/ It returns the three-tuple of client-interface, closer, and error that the\n\/\/ main dial func returns.\nfunc (dialer *cachedConnDialer) redialLocked(conn *cachedConn) (tabletmanagerservicepb.TabletManagerClient, io.Closer, error) {\n\tdialerStats.ConnReuse.Add(1)\n\tconn.lastAccessTime = time.Now()\n\tconn.refs++\n\tdialer.evictSorted = false\n\treturn dialer.connWithCloser(conn)\n}\n\n\/\/ connWithCloser returns the three-tuple expected by the main dial func, where\n\/\/ the closer handles the correct state management for updating the conns place\n\/\/ in the eviction queue.\nfunc (dialer *cachedConnDialer) connWithCloser(conn *cachedConn) (tabletmanagerservicepb.TabletManagerClient, io.Closer, error) {\n\treturn conn, closeFunc(func() error {\n\t\tdialer.m.Lock()\n\t\tdefer dialer.m.Unlock()\n\t\tconn.refs--\n\t\tdialer.evictSorted = false\n\t\treturn nil\n\t}), nil\n}\n\n\/\/ Close closes all currently cached connections, ***regardless of whether\n\/\/ those connections are in use***. Calling Close therefore will fail any RPCs\n\/\/ using currently lent-out connections, and, furthermore, will invalidate the\n\/\/ io.Closer that was returned for that connection from dialer.dial().\n\/\/\n\/\/ As a result, it is not safe to reuse a cachedConnDialer after calling Close,\n\/\/ and you should instead obtain a new one by calling either\n\/\/ tmclient.TabletManagerClient() with\n\/\/ TabletManagerProtocol set to \"grpc-cached\", or by calling\n\/\/ grpctmclient.NewCachedConnClient directly.\nfunc (dialer *cachedConnDialer) Close() {\n\tdialer.m.Lock()\n\tdefer dialer.m.Unlock()\n\n\tfor _, conn := range dialer.evict {\n\t\tconn.cc.Close()\n\t\tdelete(dialer.conns, conn.addr)\n\t\tdialer.connWaitSema.Release()\n\t}\n\tdialer.evict = nil\n}\n\nfunc getTabletAddr(tablet *topodatapb.Tablet) string {\n\treturn netutil.JoinHostPort(tablet.Hostname, int32(tablet.PortMap[\"grpc\"]))\n}\nAdd missing connwaitsema release on a not-actually-new newdial\/*\nCopyright 2021 The Vitess Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n\thttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage grpctmclient\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"io\"\n\t\"sort\"\n\t\"sync\"\n\t\"time\"\n\n\t\"google.golang.org\/grpc\"\n\n\t\"vitess.io\/vitess\/go\/netutil\"\n\t\"vitess.io\/vitess\/go\/stats\"\n\t\"vitess.io\/vitess\/go\/sync2\"\n\t\"vitess.io\/vitess\/go\/vt\/grpcclient\"\n\t\"vitess.io\/vitess\/go\/vt\/vttablet\/tmclient\"\n\n\ttabletmanagerservicepb \"vitess.io\/vitess\/go\/vt\/proto\/tabletmanagerservice\"\n\ttopodatapb \"vitess.io\/vitess\/go\/vt\/proto\/topodata\"\n)\n\nvar (\n\tdefaultPoolCapacity = flag.Int(\"tablet_manager_grpc_connpool_size\", 100, \"number of tablets to keep tmclient connections open to\")\n)\n\nfunc init() {\n\ttmclient.RegisterTabletManagerClientFactory(\"grpc-cached\", func() tmclient.TabletManagerClient {\n\t\treturn NewCachedConnClient(*defaultPoolCapacity)\n\t})\n}\n\n\/\/ closeFunc allows a standalone function to implement io.Closer, similar to\n\/\/ how http.HandlerFunc allows standalone functions to implement http.Handler.\ntype closeFunc func() error\n\nfunc (fn closeFunc) Close() error {\n\treturn fn()\n}\n\nvar _ io.Closer = (*closeFunc)(nil)\n\ntype cachedConn struct {\n\ttabletmanagerservicepb.TabletManagerClient\n\tcc *grpc.ClientConn\n\n\taddr string\n\tlastAccessTime time.Time\n\trefs int\n}\n\ntype cachedConnDialer struct {\n\tm sync.Mutex\n\tconns map[string]*cachedConn\n\tevict []*cachedConn\n\tevictSorted bool\n\tconnWaitSema *sync2.Semaphore\n}\n\nvar dialerStats = struct {\n\tConnReuse *stats.Gauge\n\tConnNew *stats.Gauge\n\tDialTimeouts *stats.Gauge\n\tDialTimings *stats.Timings\n}{\n\tConnReuse: stats.NewGauge(\"tabletmanagerclient_cachedconn_reuse\", \"number of times a call to dial() was able to reuse an existing connection\"),\n\tConnNew: stats.NewGauge(\"tabletmanagerclient_cachedconn_new\", \"number of times a call to dial() resulted in a dialing a new grpc clientconn\"),\n\tDialTimeouts: stats.NewGauge(\"tabletmanagerclient_cachedconn_dial_timeouts\", \"number of context timeouts during dial()\"),\n\tDialTimings: stats.NewTimings(\"tabletmanagerclient_cachedconn_dialtimings\", \"timings for various dial paths\", \"path\", \"rlock_fast\", \"sema_fast\", \"sema_poll\"),\n}\n\n\/\/ NewCachedConnClient returns a grpc Client that caches connections to the different tablets\nfunc NewCachedConnClient(capacity int) *Client {\n\tdialer := &cachedConnDialer{\n\t\tconns: make(map[string]*cachedConn, capacity),\n\t\tevict: make([]*cachedConn, 0, capacity),\n\t\tconnWaitSema: sync2.NewSemaphore(capacity, 0),\n\t}\n\treturn &Client{dialer}\n}\n\nvar _ dialer = (*cachedConnDialer)(nil)\n\nfunc (dialer *cachedConnDialer) sortEvictionsLocked() {\n\tif !dialer.evictSorted {\n\t\tsort.Slice(dialer.evict, func(i, j int) bool {\n\t\t\tleft, right := dialer.evict[i], dialer.evict[j]\n\t\t\tif left.refs == right.refs {\n\t\t\t\treturn left.lastAccessTime.After(right.lastAccessTime)\n\t\t\t}\n\t\t\treturn left.refs > right.refs\n\t\t})\n\t\tdialer.evictSorted = true\n\t}\n}\n\nfunc (dialer *cachedConnDialer) dial(ctx context.Context, tablet *topodatapb.Tablet) (tabletmanagerservicepb.TabletManagerClient, io.Closer, error) {\n\tstart := time.Now()\n\taddr := getTabletAddr(tablet)\n\n\tif client, closer, found, err := dialer.tryFromCache(addr, &dialer.m); found {\n\t\tdialerStats.DialTimings.Add(\"rlock_fast\", time.Since(start))\n\t\treturn client, closer, err\n\t}\n\n\tif dialer.connWaitSema.TryAcquire() {\n\t\tdefer func() {\n\t\t\tdialerStats.DialTimings.Add(\"sema_fast\", time.Since(start))\n\t\t}()\n\n\t\t\/\/ Check if another goroutine managed to dial a conn for the same addr\n\t\t\/\/ while we were waiting for the write lock. This is identical to the\n\t\t\/\/ read-lock section above.\n\t\tif client, closer, found, err := dialer.tryFromCache(addr, &dialer.m); found {\n\t\t\treturn client, closer, err\n\t\t}\n\t\treturn dialer.newdial(addr)\n\t}\n\n\tdefer func() {\n\t\tdialerStats.DialTimings.Add(\"sema_poll\", time.Since(start))\n\t}()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\tdialerStats.DialTimeouts.Add(1)\n\t\t\treturn nil, nil, ctx.Err()\n\t\tdefault:\n\t\t\tif client, closer, found, err := dialer.pollOnce(addr); found {\n\t\t\t\treturn client, closer, err\n\t\t\t}\n\t\t}\n\t}\n}\n\n\/\/ tryFromCache tries to get a connection from the cache, performing a redial\n\/\/ on that connection if it exists. It returns a TabletManagerClient impl, an\n\/\/ io.Closer, a flag to indicate whether a connection was found in the cache,\n\/\/ and an error, which is always nil.\n\/\/\n\/\/ In addition to the addr being dialed, tryFromCache takes a sync.Locker which,\n\/\/ if not nil, will be used to wrap the lookup and redial in that lock. This\n\/\/ function can be called in situations where the conns map is locked\n\/\/ externally (like in pollOnce), so we do not want to manage the locks here. In\n\/\/ other cases (like in the rlock_fast path of dial()), we pass in the RLocker\n\/\/ to ensure we have a read lock on the cache for the duration of the call.\nfunc (dialer *cachedConnDialer) tryFromCache(addr string, locker sync.Locker) (client tabletmanagerservicepb.TabletManagerClient, closer io.Closer, found bool, err error) {\n\tif locker != nil {\n\t\tlocker.Lock()\n\t\tdefer locker.Unlock()\n\t}\n\n\tif conn, ok := dialer.conns[addr]; ok {\n\t\tclient, closer, err := dialer.redialLocked(conn)\n\t\treturn client, closer, ok, err\n\t}\n\n\treturn nil, nil, false, nil\n}\n\n\/\/ pollOnce is called on each iteration of the polling loop in dial(). It:\n\/\/ - locks the conns cache for writes\n\/\/ - attempts to get a connection from the cache. If found, redial() it and exit.\n\/\/ - locks the queue\n\/\/ - peeks at the head of the eviction queue. if the peeked conn has no refs, it\n\/\/ is unused, and can be evicted to make room for the new connection to addr.\n\/\/ If the peeked conn has refs, exit.\n\/\/ - pops the conn we just peeked from the queue, delete it from the cache, and\n\/\/ close the underlying ClientConn for that conn.\n\/\/ - attempt a newdial. if the newdial fails, it will release a slot on the\n\/\/ connWaitSema, so another dial() call can successfully acquire it to dial\n\/\/ a new conn. if the newdial succeeds, we will have evicted one conn, but\n\/\/ added another, so the net change is 0, and no changes to the connWaitSema\n\/\/ are made.\n\/\/\n\/\/ It returns a TabletManagerClient impl, an io.Closer, a flag to indicate\n\/\/ whether the dial() poll loop should exit, and an error.\nfunc (dialer *cachedConnDialer) pollOnce(addr string) (client tabletmanagerservicepb.TabletManagerClient, closer io.Closer, found bool, err error) {\n\tdialer.m.Lock()\n\n\tif client, closer, found, err := dialer.tryFromCache(addr, nil); found {\n\t\tdialer.m.Unlock()\n\t\treturn client, closer, found, err\n\t}\n\n\tdialer.sortEvictionsLocked()\n\n\tconn := dialer.evict[len(dialer.evict)-1]\n\tif conn.refs != 0 {\n\t\tdialer.m.Unlock()\n\t\treturn nil, nil, false, nil\n\t}\n\n\tdialer.evict = dialer.evict[:len(dialer.evict)-1]\n\tdelete(dialer.conns, conn.addr)\n\tconn.cc.Close()\n\tdialer.m.Unlock()\n\n\tclient, closer, err = dialer.newdial(addr)\n\treturn client, closer, true, err\n}\n\n\/\/ newdial creates a new cached connection, and updates the cache and eviction\n\/\/ queue accordingly. If newdial fails to create the underlying\n\/\/ gRPC connection, it will make a call to Release the connWaitSema for other\n\/\/ newdial calls.\n\/\/\n\/\/ It returns the three-tuple of client-interface, closer, and error that the\n\/\/ main dial func returns.\nfunc (dialer *cachedConnDialer) newdial(addr string) (tabletmanagerservicepb.TabletManagerClient, io.Closer, error) {\n\tdialerStats.ConnNew.Add(1)\n\n\topt, err := grpcclient.SecureDialOption(*cert, *key, *ca, *name)\n\tif err != nil {\n\t\tdialer.connWaitSema.Release()\n\t\treturn nil, nil, err\n\t}\n\n\tcc, err := grpcclient.Dial(addr, grpcclient.FailFast(false), opt)\n\tif err != nil {\n\t\tdialer.connWaitSema.Release()\n\t\treturn nil, nil, err\n\t}\n\n\tdialer.m.Lock()\n\tdefer dialer.m.Unlock()\n\n\tif conn, existing := dialer.conns[addr]; existing {\n\t\t\/\/ race condition: some other goroutine has dialed our tablet before we have;\n\t\t\/\/ this is not great, but shouldn't happen often (if at all), so we're going to\n\t\t\/\/ close this connection and reuse the existing one. by doing this, we can keep\n\t\t\/\/ the actual Dial out of the global lock and significantly increase throughput\n\t\tcc.Close()\n\t\tdialer.connWaitSema.Release()\n\t\treturn dialer.redialLocked(conn)\n\t}\n\n\tconn := &cachedConn{\n\t\tTabletManagerClient: tabletmanagerservicepb.NewTabletManagerClient(cc),\n\t\tcc: cc,\n\t\tlastAccessTime: time.Now(),\n\t\trefs: 1,\n\t\taddr: addr,\n\t}\n\tdialer.evict = append(dialer.evict, conn)\n\tdialer.evictSorted = false\n\tdialer.conns[addr] = conn\n\n\treturn dialer.connWithCloser(conn)\n}\n\n\/\/ redialLocked takes an already-dialed connection in the cache does all the work of\n\/\/ lending that connection out to one more caller. this should only ever be\n\/\/ called while holding at least the RLock on dialer.m (but the write lock is\n\/\/ fine too), to prevent the connection from getting evicted out from under us.\n\/\/\n\/\/ It returns the three-tuple of client-interface, closer, and error that the\n\/\/ main dial func returns.\nfunc (dialer *cachedConnDialer) redialLocked(conn *cachedConn) (tabletmanagerservicepb.TabletManagerClient, io.Closer, error) {\n\tdialerStats.ConnReuse.Add(1)\n\tconn.lastAccessTime = time.Now()\n\tconn.refs++\n\tdialer.evictSorted = false\n\treturn dialer.connWithCloser(conn)\n}\n\n\/\/ connWithCloser returns the three-tuple expected by the main dial func, where\n\/\/ the closer handles the correct state management for updating the conns place\n\/\/ in the eviction queue.\nfunc (dialer *cachedConnDialer) connWithCloser(conn *cachedConn) (tabletmanagerservicepb.TabletManagerClient, io.Closer, error) {\n\treturn conn, closeFunc(func() error {\n\t\tdialer.m.Lock()\n\t\tdefer dialer.m.Unlock()\n\t\tconn.refs--\n\t\tdialer.evictSorted = false\n\t\treturn nil\n\t}), nil\n}\n\n\/\/ Close closes all currently cached connections, ***regardless of whether\n\/\/ those connections are in use***. Calling Close therefore will fail any RPCs\n\/\/ using currently lent-out connections, and, furthermore, will invalidate the\n\/\/ io.Closer that was returned for that connection from dialer.dial().\n\/\/\n\/\/ As a result, it is not safe to reuse a cachedConnDialer after calling Close,\n\/\/ and you should instead obtain a new one by calling either\n\/\/ tmclient.TabletManagerClient() with\n\/\/ TabletManagerProtocol set to \"grpc-cached\", or by calling\n\/\/ grpctmclient.NewCachedConnClient directly.\nfunc (dialer *cachedConnDialer) Close() {\n\tdialer.m.Lock()\n\tdefer dialer.m.Unlock()\n\n\tfor _, conn := range dialer.evict {\n\t\tconn.cc.Close()\n\t\tdelete(dialer.conns, conn.addr)\n\t\tdialer.connWaitSema.Release()\n\t}\n\tdialer.evict = nil\n}\n\nfunc getTabletAddr(tablet *topodatapb.Tablet) string {\n\treturn netutil.JoinHostPort(tablet.Hostname, int32(tablet.PortMap[\"grpc\"]))\n}\n<|endoftext|>"} {"text":"\/*\nCopyright 2019 The Vitess Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage connpool\n\nimport (\n\t\"net\"\n\t\"sync\"\n\t\"time\"\n\n\t\"vitess.io\/vitess\/go\/netutil\"\n\n\t\"context\"\n\n\t\"vitess.io\/vitess\/go\/pools\"\n\t\"vitess.io\/vitess\/go\/sync2\"\n\t\"vitess.io\/vitess\/go\/trace\"\n\t\"vitess.io\/vitess\/go\/vt\/callerid\"\n\t\"vitess.io\/vitess\/go\/vt\/dbconfigs\"\n\t\"vitess.io\/vitess\/go\/vt\/dbconnpool\"\n\t\"vitess.io\/vitess\/go\/vt\/log\"\n\t\"vitess.io\/vitess\/go\/vt\/mysqlctl\"\n\t\"vitess.io\/vitess\/go\/vt\/vterrors\"\n\t\"vitess.io\/vitess\/go\/vt\/vttablet\/tabletserver\/tabletenv\"\n\n\tvtrpcpb \"vitess.io\/vitess\/go\/vt\/proto\/vtrpc\"\n)\n\n\/\/ ErrConnPoolClosed is returned when the connection pool is closed.\nvar ErrConnPoolClosed = vterrors.New(vtrpcpb.Code_INTERNAL, \"internal error: unexpected: conn pool is closed\")\n\n\/\/ Pool implements a custom connection pool for tabletserver.\n\/\/ It's similar to dbconnpool.ConnPool, but the connections it creates\n\/\/ come with built-in ability to kill in-flight queries. These connections\n\/\/ also trigger a CheckMySQL call if we fail to connect to MySQL.\n\/\/ Other than the connection type, ConnPool maintains an additional\n\/\/ pool of dba connections that are used to kill connections.\ntype Pool struct {\n\tenv tabletenv.Env\n\tname string\n\tmu sync.Mutex\n\tconnections *pools.ResourcePool\n\tcapacity int\n\tprefillParallelism int\n\ttimeout time.Duration\n\tidleTimeout time.Duration\n\twaiterCap int64\n\twaiterCount sync2.AtomicInt64\n\tdbaPool *dbconnpool.ConnectionPool\n\tappDebugParams dbconfigs.Connector\n}\n\n\/\/ NewPool creates a new Pool. The name is used\n\/\/ to publish stats only.\nfunc NewPool(env tabletenv.Env, name string, cfg tabletenv.ConnPoolConfig) *Pool {\n\tidleTimeout := cfg.IdleTimeoutSeconds.Get()\n\tcp := &Pool{\n\t\tenv: env,\n\t\tname: name,\n\t\tcapacity: cfg.Size,\n\t\tprefillParallelism: cfg.PrefillParallelism,\n\t\ttimeout: cfg.TimeoutSeconds.Get(),\n\t\tidleTimeout: idleTimeout,\n\t\twaiterCap: int64(cfg.MaxWaiters),\n\t\tdbaPool: dbconnpool.NewConnectionPool(\"\", 1, idleTimeout, 0),\n\t}\n\tif name == \"\" {\n\t\treturn cp\n\t}\n\tenv.Exporter().NewGaugeFunc(name+\"Capacity\", \"Tablet server conn pool capacity\", cp.Capacity)\n\tenv.Exporter().NewGaugeFunc(name+\"Available\", \"Tablet server conn pool available\", cp.Available)\n\tenv.Exporter().NewGaugeFunc(name+\"Active\", \"Tablet server conn pool active\", cp.Active)\n\tenv.Exporter().NewGaugeFunc(name+\"InUse\", \"Tablet server conn pool in use\", cp.InUse)\n\tenv.Exporter().NewGaugeFunc(name+\"MaxCap\", \"Tablet server conn pool max cap\", cp.MaxCap)\n\tenv.Exporter().NewCounterFunc(name+\"WaitCount\", \"Tablet server conn pool wait count\", cp.WaitCount)\n\tenv.Exporter().NewCounterDurationFunc(name+\"WaitTime\", \"Tablet server wait time\", cp.WaitTime)\n\tenv.Exporter().NewGaugeDurationFunc(name+\"IdleTimeout\", \"Tablet server idle timeout\", cp.IdleTimeout)\n\tenv.Exporter().NewCounterFunc(name+\"IdleClosed\", \"Tablet server conn pool idle closed\", cp.IdleClosed)\n\tenv.Exporter().NewCounterFunc(name+\"Exhausted\", \"Number of times pool had zero available slots\", cp.Exhausted)\n\treturn cp\n}\n\nfunc (cp *Pool) pool() (p *pools.ResourcePool) {\n\tcp.mu.Lock()\n\tp = cp.connections\n\tcp.mu.Unlock()\n\treturn p\n}\n\n\/\/ Open must be called before starting to use the pool.\nfunc (cp *Pool) Open(appParams, dbaParams, appDebugParams dbconfigs.Connector) {\n\tcp.mu.Lock()\n\tdefer cp.mu.Unlock()\n\n\tif cp.prefillParallelism != 0 {\n\t\tlog.Infof(\"Opening pool: '%s'\", cp.name)\n\t\tdefer log.Infof(\"Done opening pool: '%s'\", cp.name)\n\t}\n\n\tf := func(ctx context.Context) (pools.Resource, error) {\n\t\treturn NewDBConn(ctx, cp, appParams)\n\t}\n\n\tvar refreshCheck pools.RefreshCheck\n\tif net.ParseIP(appParams.Host()) == nil {\n\t\trefreshCheck = netutil.DNSTracker(appParams.Host())\n\t}\n\n\tcp.connections = pools.NewResourcePool(f, cp.capacity, cp.capacity, cp.idleTimeout, cp.prefillParallelism, cp.getLogWaitCallback(), refreshCheck, *mysqlctl.PoolDynamicHostnameResolution)\n\tcp.appDebugParams = appDebugParams\n\n\tcp.dbaPool.Open(dbaParams)\n}\n\nfunc (cp *Pool) getLogWaitCallback() func(time.Time) {\n\tif cp.name == \"\" {\n\t\treturn func(start time.Time) {} \/\/ no op\n\t}\n\treturn func(start time.Time) {\n\t\tcp.env.Stats().WaitTimings.Record(cp.name+\"ResourceWaitTime\", start)\n\t}\n}\n\n\/\/ Close will close the pool and wait for connections to be returned before\n\/\/ exiting.\nfunc (cp *Pool) Close() {\n\tp := cp.pool()\n\tif p == nil {\n\t\treturn\n\t}\n\t\/\/ We should not hold the lock while calling Close\n\t\/\/ because it waits for connections to be returned.\n\tp.Close()\n\tcp.mu.Lock()\n\tcp.connections = nil\n\tcp.mu.Unlock()\n\tcp.dbaPool.Close()\n}\n\n\/\/ Get returns a connection.\n\/\/ You must call Recycle on DBConn once done.\nfunc (cp *Pool) Get(ctx context.Context) (*DBConn, error) {\n\tspan, ctx := trace.NewSpan(ctx, \"Pool.Get\")\n\tdefer span.Finish()\n\n\tif cp.waiterCap > 0 {\n\t\twaiterCount := cp.waiterCount.Add(1)\n\t\tdefer cp.waiterCount.Add(-1)\n\t\tif waiterCount > cp.waiterCap {\n\t\t\treturn nil, vterrors.Errorf(vtrpcpb.Code_RESOURCE_EXHAUSTED, \"pool %s waiter count exceeded\", cp.name)\n\t\t}\n\t}\n\n\tif cp.isCallerIDAppDebug(ctx) {\n\t\treturn NewDBConnNoPool(ctx, cp.appDebugParams, cp.dbaPool)\n\t}\n\tp := cp.pool()\n\tif p == nil {\n\t\treturn nil, ErrConnPoolClosed\n\t}\n\tspan.Annotate(\"capacity\", p.Capacity())\n\tspan.Annotate(\"in_use\", p.InUse())\n\tspan.Annotate(\"available\", p.Available())\n\tspan.Annotate(\"active\", p.Active())\n\n\tif cp.timeout != 0 {\n\t\tvar cancel context.CancelFunc\n\t\tctx, cancel = context.WithTimeout(ctx, cp.timeout)\n\t\tdefer cancel()\n\t}\n\tr, err := p.Get(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn r.(*DBConn), nil\n}\n\n\/\/ Put puts a connection into the pool.\nfunc (cp *Pool) Put(conn *DBConn) {\n\tp := cp.pool()\n\tif p == nil {\n\t\tpanic(ErrConnPoolClosed)\n\t}\n\tif conn == nil {\n\t\tp.Put(nil)\n\t} else {\n\t\tp.Put(conn)\n\t}\n}\n\n\/\/ SetCapacity alters the size of the pool at runtime.\nfunc (cp *Pool) SetCapacity(capacity int) (err error) {\n\tcp.mu.Lock()\n\tdefer cp.mu.Unlock()\n\tif cp.connections != nil {\n\t\terr = cp.connections.SetCapacity(capacity)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tcp.capacity = capacity\n\treturn nil\n}\n\n\/\/ SetIdleTimeout sets the idleTimeout on the pool.\nfunc (cp *Pool) SetIdleTimeout(idleTimeout time.Duration) {\n\tcp.mu.Lock()\n\tdefer cp.mu.Unlock()\n\tif cp.connections != nil {\n\t\tcp.connections.SetIdleTimeout(idleTimeout)\n\t}\n\tcp.dbaPool.SetIdleTimeout(idleTimeout)\n\tcp.idleTimeout = idleTimeout\n}\n\n\/\/ StatsJSON returns the pool stats as a JSON object.\nfunc (cp *Pool) StatsJSON() string {\n\tp := cp.pool()\n\tif p == nil {\n\t\treturn \"{}\"\n\t}\n\treturn p.StatsJSON()\n}\n\n\/\/ Capacity returns the pool capacity.\nfunc (cp *Pool) Capacity() int64 {\n\tp := cp.pool()\n\tif p == nil {\n\t\treturn 0\n\t}\n\treturn p.Capacity()\n}\n\n\/\/ Available returns the number of available connections in the pool\nfunc (cp *Pool) Available() int64 {\n\tp := cp.pool()\n\tif p == nil {\n\t\treturn 0\n\t}\n\treturn p.Available()\n}\n\n\/\/ Active returns the number of active connections in the pool\nfunc (cp *Pool) Active() int64 {\n\tp := cp.pool()\n\tif p == nil {\n\t\treturn 0\n\t}\n\treturn p.Active()\n}\n\n\/\/ InUse returns the number of in-use connections in the pool\nfunc (cp *Pool) InUse() int64 {\n\tp := cp.pool()\n\tif p == nil {\n\t\treturn 0\n\t}\n\treturn p.InUse()\n}\n\n\/\/ MaxCap returns the maximum size of the pool\nfunc (cp *Pool) MaxCap() int64 {\n\tp := cp.pool()\n\tif p == nil {\n\t\treturn 0\n\t}\n\treturn p.MaxCap()\n}\n\n\/\/ WaitCount returns how many clients are waiting for a connection\nfunc (cp *Pool) WaitCount() int64 {\n\tp := cp.pool()\n\tif p == nil {\n\t\treturn 0\n\t}\n\treturn p.WaitCount()\n}\n\n\/\/ WaitTime return the pool WaitTime.\nfunc (cp *Pool) WaitTime() time.Duration {\n\tp := cp.pool()\n\tif p == nil {\n\t\treturn 0\n\t}\n\treturn p.WaitTime()\n}\n\n\/\/ IdleTimeout returns the idle timeout for the pool.\nfunc (cp *Pool) IdleTimeout() time.Duration {\n\tp := cp.pool()\n\tif p == nil {\n\t\treturn 0\n\t}\n\treturn p.IdleTimeout()\n}\n\n\/\/ IdleClosed returns the number of closed connections for the pool.\nfunc (cp *Pool) IdleClosed() int64 {\n\tp := cp.pool()\n\tif p == nil {\n\t\treturn 0\n\t}\n\treturn p.IdleClosed()\n}\n\n\/\/ Exhausted returns the number of times available went to zero for the pool.\nfunc (cp *Pool) Exhausted() int64 {\n\tp := cp.pool()\n\tif p == nil {\n\t\treturn 0\n\t}\n\treturn p.Exhausted()\n}\n\nfunc (cp *Pool) isCallerIDAppDebug(ctx context.Context) bool {\n\tparams, err := cp.appDebugParams.MysqlParams()\n\tif err != nil {\n\t\treturn false\n\t}\n\tif params == nil || params.Uname == \"\" {\n\t\treturn false\n\t}\n\tcallerID := callerid.ImmediateCallerIDFromContext(ctx)\n\treturn callerID != nil && callerID.Username == params.Uname\n}\nAdd stats to track when a pool's waiter queue is full\/*\nCopyright 2019 The Vitess Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage connpool\n\nimport (\n\t\"net\"\n\t\"sync\"\n\t\"time\"\n\n\t\"vitess.io\/vitess\/go\/netutil\"\n\n\t\"context\"\n\n\t\"vitess.io\/vitess\/go\/pools\"\n\t\"vitess.io\/vitess\/go\/sync2\"\n\t\"vitess.io\/vitess\/go\/trace\"\n\t\"vitess.io\/vitess\/go\/vt\/callerid\"\n\t\"vitess.io\/vitess\/go\/vt\/dbconfigs\"\n\t\"vitess.io\/vitess\/go\/vt\/dbconnpool\"\n\t\"vitess.io\/vitess\/go\/vt\/log\"\n\t\"vitess.io\/vitess\/go\/vt\/mysqlctl\"\n\t\"vitess.io\/vitess\/go\/vt\/vterrors\"\n\t\"vitess.io\/vitess\/go\/vt\/vttablet\/tabletserver\/tabletenv\"\n\n\tvtrpcpb \"vitess.io\/vitess\/go\/vt\/proto\/vtrpc\"\n)\n\n\/\/ ErrConnPoolClosed is returned when the connection pool is closed.\nvar ErrConnPoolClosed = vterrors.New(vtrpcpb.Code_INTERNAL, \"internal error: unexpected: conn pool is closed\")\n\n\/\/ Pool implements a custom connection pool for tabletserver.\n\/\/ It's similar to dbconnpool.ConnPool, but the connections it creates\n\/\/ come with built-in ability to kill in-flight queries. These connections\n\/\/ also trigger a CheckMySQL call if we fail to connect to MySQL.\n\/\/ Other than the connection type, ConnPool maintains an additional\n\/\/ pool of dba connections that are used to kill connections.\ntype Pool struct {\n\tenv tabletenv.Env\n\tname string\n\tmu sync.Mutex\n\tconnections *pools.ResourcePool\n\tcapacity int\n\tprefillParallelism int\n\ttimeout time.Duration\n\tidleTimeout time.Duration\n\twaiterCap int64\n\twaiterCount sync2.AtomicInt64\n\twaiterQueueFull sync2.AtomicInt64\n\tdbaPool *dbconnpool.ConnectionPool\n\tappDebugParams dbconfigs.Connector\n}\n\n\/\/ NewPool creates a new Pool. The name is used\n\/\/ to publish stats only.\nfunc NewPool(env tabletenv.Env, name string, cfg tabletenv.ConnPoolConfig) *Pool {\n\tidleTimeout := cfg.IdleTimeoutSeconds.Get()\n\tcp := &Pool{\n\t\tenv: env,\n\t\tname: name,\n\t\tcapacity: cfg.Size,\n\t\tprefillParallelism: cfg.PrefillParallelism,\n\t\ttimeout: cfg.TimeoutSeconds.Get(),\n\t\tidleTimeout: idleTimeout,\n\t\twaiterCap: int64(cfg.MaxWaiters),\n\t\tdbaPool: dbconnpool.NewConnectionPool(\"\", 1, idleTimeout, 0),\n\t}\n\tif name == \"\" {\n\t\treturn cp\n\t}\n\tenv.Exporter().NewGaugeFunc(name+\"Capacity\", \"Tablet server conn pool capacity\", cp.Capacity)\n\tenv.Exporter().NewGaugeFunc(name+\"Available\", \"Tablet server conn pool available\", cp.Available)\n\tenv.Exporter().NewGaugeFunc(name+\"Active\", \"Tablet server conn pool active\", cp.Active)\n\tenv.Exporter().NewGaugeFunc(name+\"InUse\", \"Tablet server conn pool in use\", cp.InUse)\n\tenv.Exporter().NewGaugeFunc(name+\"MaxCap\", \"Tablet server conn pool max cap\", cp.MaxCap)\n\tenv.Exporter().NewCounterFunc(name+\"WaitCount\", \"Tablet server conn pool wait count\", cp.WaitCount)\n\tenv.Exporter().NewCounterDurationFunc(name+\"WaitTime\", \"Tablet server wait time\", cp.WaitTime)\n\tenv.Exporter().NewGaugeDurationFunc(name+\"IdleTimeout\", \"Tablet server idle timeout\", cp.IdleTimeout)\n\tenv.Exporter().NewCounterFunc(name+\"IdleClosed\", \"Tablet server conn pool idle closed\", cp.IdleClosed)\n\tenv.Exporter().NewCounterFunc(name+\"Exhausted\", \"Number of times pool had zero available slots\", cp.Exhausted)\n\tenv.Exporter().NewCounterFunc(name+\"WaiterQueueFull\", \"Number of times the waiter queue was full\", cp.waiterQueueFull.Get)\n\treturn cp\n}\n\nfunc (cp *Pool) pool() (p *pools.ResourcePool) {\n\tcp.mu.Lock()\n\tp = cp.connections\n\tcp.mu.Unlock()\n\treturn p\n}\n\n\/\/ Open must be called before starting to use the pool.\nfunc (cp *Pool) Open(appParams, dbaParams, appDebugParams dbconfigs.Connector) {\n\tcp.mu.Lock()\n\tdefer cp.mu.Unlock()\n\n\tif cp.prefillParallelism != 0 {\n\t\tlog.Infof(\"Opening pool: '%s'\", cp.name)\n\t\tdefer log.Infof(\"Done opening pool: '%s'\", cp.name)\n\t}\n\n\tf := func(ctx context.Context) (pools.Resource, error) {\n\t\treturn NewDBConn(ctx, cp, appParams)\n\t}\n\n\tvar refreshCheck pools.RefreshCheck\n\tif net.ParseIP(appParams.Host()) == nil {\n\t\trefreshCheck = netutil.DNSTracker(appParams.Host())\n\t}\n\n\tcp.connections = pools.NewResourcePool(f, cp.capacity, cp.capacity, cp.idleTimeout, cp.prefillParallelism, cp.getLogWaitCallback(), refreshCheck, *mysqlctl.PoolDynamicHostnameResolution)\n\tcp.appDebugParams = appDebugParams\n\n\tcp.dbaPool.Open(dbaParams)\n}\n\nfunc (cp *Pool) getLogWaitCallback() func(time.Time) {\n\tif cp.name == \"\" {\n\t\treturn func(start time.Time) {} \/\/ no op\n\t}\n\treturn func(start time.Time) {\n\t\tcp.env.Stats().WaitTimings.Record(cp.name+\"ResourceWaitTime\", start)\n\t}\n}\n\n\/\/ Close will close the pool and wait for connections to be returned before\n\/\/ exiting.\nfunc (cp *Pool) Close() {\n\tp := cp.pool()\n\tif p == nil {\n\t\treturn\n\t}\n\t\/\/ We should not hold the lock while calling Close\n\t\/\/ because it waits for connections to be returned.\n\tp.Close()\n\tcp.mu.Lock()\n\tcp.connections = nil\n\tcp.mu.Unlock()\n\tcp.dbaPool.Close()\n}\n\n\/\/ Get returns a connection.\n\/\/ You must call Recycle on DBConn once done.\nfunc (cp *Pool) Get(ctx context.Context) (*DBConn, error) {\n\tspan, ctx := trace.NewSpan(ctx, \"Pool.Get\")\n\tdefer span.Finish()\n\n\tif cp.waiterCap > 0 {\n\t\twaiterCount := cp.waiterCount.Add(1)\n\t\tdefer cp.waiterCount.Add(-1)\n\t\tif waiterCount > cp.waiterCap {\n\t\t\tcp.waiterQueueFull.Add(1)\n\t\t\treturn nil, vterrors.Errorf(vtrpcpb.Code_RESOURCE_EXHAUSTED, \"pool %s waiter count exceeded\", cp.name)\n\t\t}\n\t}\n\n\tif cp.isCallerIDAppDebug(ctx) {\n\t\treturn NewDBConnNoPool(ctx, cp.appDebugParams, cp.dbaPool)\n\t}\n\tp := cp.pool()\n\tif p == nil {\n\t\treturn nil, ErrConnPoolClosed\n\t}\n\tspan.Annotate(\"capacity\", p.Capacity())\n\tspan.Annotate(\"in_use\", p.InUse())\n\tspan.Annotate(\"available\", p.Available())\n\tspan.Annotate(\"active\", p.Active())\n\n\tif cp.timeout != 0 {\n\t\tvar cancel context.CancelFunc\n\t\tctx, cancel = context.WithTimeout(ctx, cp.timeout)\n\t\tdefer cancel()\n\t}\n\tr, err := p.Get(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn r.(*DBConn), nil\n}\n\n\/\/ Put puts a connection into the pool.\nfunc (cp *Pool) Put(conn *DBConn) {\n\tp := cp.pool()\n\tif p == nil {\n\t\tpanic(ErrConnPoolClosed)\n\t}\n\tif conn == nil {\n\t\tp.Put(nil)\n\t} else {\n\t\tp.Put(conn)\n\t}\n}\n\n\/\/ SetCapacity alters the size of the pool at runtime.\nfunc (cp *Pool) SetCapacity(capacity int) (err error) {\n\tcp.mu.Lock()\n\tdefer cp.mu.Unlock()\n\tif cp.connections != nil {\n\t\terr = cp.connections.SetCapacity(capacity)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tcp.capacity = capacity\n\treturn nil\n}\n\n\/\/ SetIdleTimeout sets the idleTimeout on the pool.\nfunc (cp *Pool) SetIdleTimeout(idleTimeout time.Duration) {\n\tcp.mu.Lock()\n\tdefer cp.mu.Unlock()\n\tif cp.connections != nil {\n\t\tcp.connections.SetIdleTimeout(idleTimeout)\n\t}\n\tcp.dbaPool.SetIdleTimeout(idleTimeout)\n\tcp.idleTimeout = idleTimeout\n}\n\n\/\/ StatsJSON returns the pool stats as a JSON object.\nfunc (cp *Pool) StatsJSON() string {\n\tp := cp.pool()\n\tif p == nil {\n\t\treturn \"{}\"\n\t}\n\treturn p.StatsJSON()\n}\n\n\/\/ Capacity returns the pool capacity.\nfunc (cp *Pool) Capacity() int64 {\n\tp := cp.pool()\n\tif p == nil {\n\t\treturn 0\n\t}\n\treturn p.Capacity()\n}\n\n\/\/ Available returns the number of available connections in the pool\nfunc (cp *Pool) Available() int64 {\n\tp := cp.pool()\n\tif p == nil {\n\t\treturn 0\n\t}\n\treturn p.Available()\n}\n\n\/\/ Active returns the number of active connections in the pool\nfunc (cp *Pool) Active() int64 {\n\tp := cp.pool()\n\tif p == nil {\n\t\treturn 0\n\t}\n\treturn p.Active()\n}\n\n\/\/ InUse returns the number of in-use connections in the pool\nfunc (cp *Pool) InUse() int64 {\n\tp := cp.pool()\n\tif p == nil {\n\t\treturn 0\n\t}\n\treturn p.InUse()\n}\n\n\/\/ MaxCap returns the maximum size of the pool\nfunc (cp *Pool) MaxCap() int64 {\n\tp := cp.pool()\n\tif p == nil {\n\t\treturn 0\n\t}\n\treturn p.MaxCap()\n}\n\n\/\/ WaitCount returns how many clients are waiting for a connection\nfunc (cp *Pool) WaitCount() int64 {\n\tp := cp.pool()\n\tif p == nil {\n\t\treturn 0\n\t}\n\treturn p.WaitCount()\n}\n\n\/\/ WaitTime return the pool WaitTime.\nfunc (cp *Pool) WaitTime() time.Duration {\n\tp := cp.pool()\n\tif p == nil {\n\t\treturn 0\n\t}\n\treturn p.WaitTime()\n}\n\n\/\/ IdleTimeout returns the idle timeout for the pool.\nfunc (cp *Pool) IdleTimeout() time.Duration {\n\tp := cp.pool()\n\tif p == nil {\n\t\treturn 0\n\t}\n\treturn p.IdleTimeout()\n}\n\n\/\/ IdleClosed returns the number of closed connections for the pool.\nfunc (cp *Pool) IdleClosed() int64 {\n\tp := cp.pool()\n\tif p == nil {\n\t\treturn 0\n\t}\n\treturn p.IdleClosed()\n}\n\n\/\/ Exhausted returns the number of times available went to zero for the pool.\nfunc (cp *Pool) Exhausted() int64 {\n\tp := cp.pool()\n\tif p == nil {\n\t\treturn 0\n\t}\n\treturn p.Exhausted()\n}\n\nfunc (cp *Pool) isCallerIDAppDebug(ctx context.Context) bool {\n\tparams, err := cp.appDebugParams.MysqlParams()\n\tif err != nil {\n\t\treturn false\n\t}\n\tif params == nil || params.Uname == \"\" {\n\t\treturn false\n\t}\n\tcallerID := callerid.ImmediateCallerIDFromContext(ctx)\n\treturn callerID != nil && callerID.Username == params.Uname\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2015 Google Inc. All Rights Reserved.\n\/\/ Author: jacobsa@google.com (Aaron Jacobs)\n\npackage gcs\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"net\/http\"\n\t\"unicode\/utf8\"\n\n\t\"golang.org\/x\/net\/context\"\n\t\"google.golang.org\/cloud\"\n\t\"google.golang.org\/cloud\/storage\"\n)\n\n\/\/ A request to create an object, accepted by Bucket.CreateObject.\ntype CreateObjectRequest struct {\n\t\/\/ Attributes with which the object should be created. The Name field must be\n\t\/\/ set; other zero-valued fields are ignored.\n\t\/\/\n\t\/\/ Object names must:\n\t\/\/\n\t\/\/ * be non-empty.\n\t\/\/ * be no longer than 1024 bytes.\n\t\/\/ * be valid UTF-8.\n\t\/\/ * not contain the code point U+000A (line feed).\n\t\/\/ * not contain the code point U+000D (carriage return).\n\t\/\/\n\t\/\/ See here for authoritative documentation:\n\t\/\/ https:\/\/cloud.google.com\/storage\/docs\/bucket-naming#objectnames\n\tAttrs storage.ObjectAttrs\n\n\t\/\/ A reader from which to obtain the contents of the object. Must be non-nil.\n\t\/\/ Will be closed when CreateObject returns, regardless of whether it succeeds.\n\tContents io.ReadCloser\n}\n\n\/\/ Bucket represents a GCS bucket, pre-bound with a bucket name and necessary\n\/\/ authorization information.\n\/\/\n\/\/ Each method that may block accepts a context object that is used for\n\/\/ deadlines and cancellation. Users need not package authorization information\n\/\/ into the context object (using cloud.WithContext or similar).\ntype Bucket interface {\n\tName() string\n\n\t\/\/ List the objects in the bucket that meet the criteria defined by the\n\t\/\/ query, returning a result object that contains the results and potentially\n\t\/\/ a cursor for retrieving the next portion of the larger set of results.\n\tListObjects(ctx context.Context, query *storage.Query) (*storage.Objects, error)\n\n\t\/\/ Create a reader for the contents of the object with the given name. The\n\t\/\/ caller must arrange for the reader to be closed when it is no longer\n\t\/\/ needed.\n\tNewReader(ctx context.Context, objectName string) (io.ReadCloser, error)\n\n\t\/\/ Create or overwrite an object according to the supplied request. The new\n\t\/\/ object is guaranteed to exist immediately for the purposes of reading (and\n\t\/\/ eventually for listing) after this method returns a nil error. It is\n\t\/\/ guaranteed not to exist before req.Contents returns io.EOF.\n\tCreateObject(ctx context.Context, req *CreateObjectRequest) (*storage.Object, error)\n\n\t\/\/ Delete the object with the given name.\n\tDeleteObject(ctx context.Context, name string) error\n}\n\ntype bucket struct {\n\tprojID string\n\tclient *http.Client\n\tname string\n}\n\nfunc (b *bucket) Name() string {\n\treturn b.name\n}\n\nfunc (b *bucket) ListObjects(ctx context.Context, query *storage.Query) (*storage.Objects, error) {\n\tauthContext := cloud.WithContext(ctx, b.projID, b.client)\n\treturn storage.ListObjects(authContext, b.name, query)\n}\n\nfunc (b *bucket) NewReader(ctx context.Context, objectName string) (io.ReadCloser, error) {\n\tauthContext := cloud.WithContext(ctx, b.projID, b.client)\n\treturn storage.NewReader(authContext, b.name, objectName)\n}\n\nfunc (b *bucket) NewWriter(\n\tctx context.Context,\n\tattrs *storage.ObjectAttrs) (ObjectWriter, error) {\n\tauthContext := cloud.WithContext(ctx, b.projID, b.client)\n\n\t\/\/ As of 2015-02, the wrapped storage package doesn't check this for us,\n\t\/\/ causing silently transformed names:\n\t\/\/ https:\/\/github.com\/GoogleCloudPlatform\/gcloud-golang\/issues\/111\n\tif !utf8.ValidString(attrs.Name) {\n\t\treturn nil, errors.New(\"Invalid object name: not valid UTF-8\")\n\t}\n\n\t\/\/ Create and initialize the wrapped writer.\n\twrapped := storage.NewWriter(authContext, b.name, attrs.Name)\n\twrapped.ObjectAttrs = *attrs\n\n\tw := &objectWriter{\n\t\twrapped: wrapped,\n\t}\n\n\treturn w, nil\n}\n\nfunc (b *bucket) DeleteObject(ctx context.Context, name string) error {\n\tauthContext := cloud.WithContext(ctx, b.projID, b.client)\n\treturn storage.DeleteObject(authContext, b.name, name)\n}\nContents doesn't need to be a ReadCloser, I think.\/\/ Copyright 2015 Google Inc. All Rights Reserved.\n\/\/ Author: jacobsa@google.com (Aaron Jacobs)\n\npackage gcs\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"net\/http\"\n\t\"unicode\/utf8\"\n\n\t\"golang.org\/x\/net\/context\"\n\t\"google.golang.org\/cloud\"\n\t\"google.golang.org\/cloud\/storage\"\n)\n\n\/\/ A request to create an object, accepted by Bucket.CreateObject.\ntype CreateObjectRequest struct {\n\t\/\/ Attributes with which the object should be created. The Name field must be\n\t\/\/ set; other zero-valued fields are ignored.\n\t\/\/\n\t\/\/ Object names must:\n\t\/\/\n\t\/\/ * be non-empty.\n\t\/\/ * be no longer than 1024 bytes.\n\t\/\/ * be valid UTF-8.\n\t\/\/ * not contain the code point U+000A (line feed).\n\t\/\/ * not contain the code point U+000D (carriage return).\n\t\/\/\n\t\/\/ See here for authoritative documentation:\n\t\/\/ https:\/\/cloud.google.com\/storage\/docs\/bucket-naming#objectnames\n\tAttrs storage.ObjectAttrs\n\n\t\/\/ A reader from which to obtain the contents of the object. Must be non-nil.\n\tContents io.Reader\n}\n\n\/\/ Bucket represents a GCS bucket, pre-bound with a bucket name and necessary\n\/\/ authorization information.\n\/\/\n\/\/ Each method that may block accepts a context object that is used for\n\/\/ deadlines and cancellation. Users need not package authorization information\n\/\/ into the context object (using cloud.WithContext or similar).\ntype Bucket interface {\n\tName() string\n\n\t\/\/ List the objects in the bucket that meet the criteria defined by the\n\t\/\/ query, returning a result object that contains the results and potentially\n\t\/\/ a cursor for retrieving the next portion of the larger set of results.\n\tListObjects(ctx context.Context, query *storage.Query) (*storage.Objects, error)\n\n\t\/\/ Create a reader for the contents of the object with the given name. The\n\t\/\/ caller must arrange for the reader to be closed when it is no longer\n\t\/\/ needed.\n\tNewReader(ctx context.Context, objectName string) (io.ReadCloser, error)\n\n\t\/\/ Create or overwrite an object according to the supplied request. The new\n\t\/\/ object is guaranteed to exist immediately for the purposes of reading (and\n\t\/\/ eventually for listing) after this method returns a nil error. It is\n\t\/\/ guaranteed not to exist before req.Contents returns io.EOF.\n\tCreateObject(ctx context.Context, req *CreateObjectRequest) (*storage.Object, error)\n\n\t\/\/ Delete the object with the given name.\n\tDeleteObject(ctx context.Context, name string) error\n}\n\ntype bucket struct {\n\tprojID string\n\tclient *http.Client\n\tname string\n}\n\nfunc (b *bucket) Name() string {\n\treturn b.name\n}\n\nfunc (b *bucket) ListObjects(ctx context.Context, query *storage.Query) (*storage.Objects, error) {\n\tauthContext := cloud.WithContext(ctx, b.projID, b.client)\n\treturn storage.ListObjects(authContext, b.name, query)\n}\n\nfunc (b *bucket) NewReader(ctx context.Context, objectName string) (io.ReadCloser, error) {\n\tauthContext := cloud.WithContext(ctx, b.projID, b.client)\n\treturn storage.NewReader(authContext, b.name, objectName)\n}\n\nfunc (b *bucket) NewWriter(\n\tctx context.Context,\n\tattrs *storage.ObjectAttrs) (ObjectWriter, error) {\n\tauthContext := cloud.WithContext(ctx, b.projID, b.client)\n\n\t\/\/ As of 2015-02, the wrapped storage package doesn't check this for us,\n\t\/\/ causing silently transformed names:\n\t\/\/ https:\/\/github.com\/GoogleCloudPlatform\/gcloud-golang\/issues\/111\n\tif !utf8.ValidString(attrs.Name) {\n\t\treturn nil, errors.New(\"Invalid object name: not valid UTF-8\")\n\t}\n\n\t\/\/ Create and initialize the wrapped writer.\n\twrapped := storage.NewWriter(authContext, b.name, attrs.Name)\n\twrapped.ObjectAttrs = *attrs\n\n\tw := &objectWriter{\n\t\twrapped: wrapped,\n\t}\n\n\treturn w, nil\n}\n\nfunc (b *bucket) DeleteObject(ctx context.Context, name string) error {\n\tauthContext := cloud.WithContext(ctx, b.projID, b.client)\n\treturn storage.DeleteObject(authContext, b.name, name)\n}\n<|endoftext|>"} {"text":"\/*\nCopyright (C) 2016 Red Hat, Inc.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage cluster\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/jimmidyson\/minishift\/pkg\/minikube\/constants\"\n)\n\n\/\/ Kill any running instances.\nvar stopCommand = \"sudo killall openshift || true\"\n\nvar startCommandFmtStr = `\n# Run with nohup so it stays up. Redirect logs to useful places.\ncd \/var\/lib\/minishift;\nif [ ! -f openshift.local.config\/master\/master-config.yaml ]; then\n sudo \/usr\/local\/bin\/openshift start --listen=https:\/\/0.0.0.0:%d --cors-allowed-origins=.* --master=https:\/\/%s:%d --write-config=openshift.local.config;\n sudo \/usr\/local\/bin\/openshift ex config patch openshift.local.config\/master\/master-config.yaml --patch='{\"routingConfig\": {\"subdomain\": \"%s.xip.io\"}}' > \/tmp\/master-config.yaml;\n sudo mv \/tmp\/master-config.yaml openshift.local.config\/master\/master-config.yaml;\n sudo \/usr\/local\/bin\/openshift ex config patch openshift.local.config\/node-minishift\/node-config.yaml --patch='{\"nodeIP\": \"%s\"}}' > \/tmp\/node-config.yaml;\n sudo mv \/tmp\/node-config.yaml openshift.local.config\/node-minishift\/node-config.yaml;\nfi;\nsudo sh -c 'PATH=\/usr\/local\/sbin:$PATH nohup \/usr\/local\/bin\/openshift start --master-config=openshift.local.config\/master\/master-config.yaml --node-config=openshift.local.config\/node-$(hostname | tr '[:upper:]' '[:lower:]')\/node-config.yaml> %s 2> %s < \/dev\/null &'\nuntil $(curl --output \/dev\/null --silent --fail -k https:\/\/localhost:%d\/healthz\/ready); do\n printf '.'\n sleep 1\ndone;\nsudo \/usr\/local\/bin\/openshift admin policy add-cluster-role-to-user cluster-admin admin --config=openshift.local.config\/master\/admin.kubeconfig\n`\n\nvar (\n\tlogsCommand = fmt.Sprintf(\"tail -n +1 %s %s\", constants.RemoteOpenShiftErrPath, constants.RemoteOpenShiftOutPath)\n\tgetCACertCommand = fmt.Sprintf(\"cat %s\", constants.RemoteOpenShiftCAPath)\n)\n\nfunc GetStartCommand(ip string) string {\n\treturn fmt.Sprintf(startCommandFmtStr, constants.APIServerPort, ip, constants.APIServerPort, ip, ip, constants.RemoteOpenShiftErrPath, constants.RemoteOpenShiftOutPath, constants.APIServerPort)\n}\nEnable hostPath provisioner\/*\nCopyright (C) 2016 Red Hat, Inc.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage cluster\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/jimmidyson\/minishift\/pkg\/minikube\/constants\"\n)\n\n\/\/ Kill any running instances.\nvar stopCommand = \"sudo killall openshift || true\"\n\nvar startCommandFmtStr = `\n# Run with nohup so it stays up. Redirect logs to useful places.\ncd \/var\/lib\/minishift;\nif [ ! -f openshift.local.config\/master\/master-config.yaml ]; then\n sudo \/usr\/local\/bin\/openshift start --listen=https:\/\/0.0.0.0:%d --cors-allowed-origins=.* --master=https:\/\/%s:%d --write-config=openshift.local.config;\n sudo \/usr\/local\/bin\/openshift ex config patch openshift.local.config\/master\/master-config.yaml --patch='{\"routingConfig\": {\"subdomain\": \"%s.xip.io\"}}' > \/tmp\/master-config.yaml;\n sudo mv \/tmp\/master-config.yaml openshift.local.config\/master\/master-config.yaml;\n\t\tsudo \/usr\/local\/bin\/openshift ex config patch openshift.local.config\/master\/master-config.yaml --patch='{\"kubernetesMasterConfig\": {\"controllerArguments\": {\"enable-hostpath-provisioner\": [\"true\"]}}}' > \/tmp\/master-config.yaml;\n sudo mv \/tmp\/master-config.yaml openshift.local.config\/master\/master-config.yaml;\n sudo \/usr\/local\/bin\/openshift ex config patch openshift.local.config\/node-minishift\/node-config.yaml --patch='{\"nodeIP\": \"%s\"}}' > \/tmp\/node-config.yaml;\n sudo mv \/tmp\/node-config.yaml openshift.local.config\/node-minishift\/node-config.yaml;\nfi;\nsudo sh -c 'PATH=\/usr\/local\/sbin:$PATH nohup \/usr\/local\/bin\/openshift start --master-config=openshift.local.config\/master\/master-config.yaml --node-config=openshift.local.config\/node-$(hostname | tr '[:upper:]' '[:lower:]')\/node-config.yaml> %s 2> %s < \/dev\/null &'\nuntil $(curl --output \/dev\/null --silent --fail -k https:\/\/localhost:%d\/healthz\/ready); do\n printf '.'\n sleep 1\ndone;\nsudo \/usr\/local\/bin\/openshift admin policy add-cluster-role-to-user cluster-admin admin --config=openshift.local.config\/master\/admin.kubeconfig\n`\n\nvar (\n\tlogsCommand = fmt.Sprintf(\"tail -n +1 %s %s\", constants.RemoteOpenShiftErrPath, constants.RemoteOpenShiftOutPath)\n\tgetCACertCommand = fmt.Sprintf(\"cat %s\", constants.RemoteOpenShiftCAPath)\n)\n\nfunc GetStartCommand(ip string) string {\n\treturn fmt.Sprintf(startCommandFmtStr, constants.APIServerPort, ip, constants.APIServerPort, ip, ip, constants.RemoteOpenShiftErrPath, constants.RemoteOpenShiftOutPath, constants.APIServerPort)\n}\n<|endoftext|>"} {"text":"\/*\nCopyright 2018 The Rook Authors. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n\thttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage object\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/pkg\/errors\"\n\tcephv1 \"github.com\/rook\/rook\/pkg\/apis\/ceph.rook.io\/v1\"\n\tcephconfig \"github.com\/rook\/rook\/pkg\/operator\/ceph\/config\"\n\t\"github.com\/rook\/rook\/pkg\/operator\/ceph\/controller\"\n\t\"github.com\/rook\/rook\/pkg\/operator\/k8sutil\"\n\tapps \"k8s.io\/api\/apps\/v1\"\n\tv1 \"k8s.io\/api\/core\/v1\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/intstr\"\n\t\"sigs.k8s.io\/controller-runtime\/pkg\/controller\/controllerutil\"\n)\n\nconst (\n\tlivenessProbePath = \"\/swift\/healthcheck\"\n)\n\nfunc (c *clusterConfig) createDeployment(rgwConfig *rgwConfig) (*apps.Deployment, error) {\n\tpod, err := c.makeRGWPodSpec(rgwConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treplicas := int32(1)\n\td := &apps.Deployment{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: rgwConfig.ResourceName,\n\t\t\tNamespace: c.store.Namespace,\n\t\t\tLabels: getLabels(c.store.Name, c.store.Namespace, true),\n\t\t},\n\t\tSpec: apps.DeploymentSpec{\n\t\t\tSelector: &metav1.LabelSelector{\n\t\t\t\tMatchLabels: getLabels(c.store.Name, c.store.Namespace, false),\n\t\t\t},\n\t\t\tTemplate: pod,\n\t\t\tReplicas: &replicas,\n\t\t\tStrategy: apps.DeploymentStrategy{\n\t\t\t\tType: apps.RecreateDeploymentStrategyType,\n\t\t\t},\n\t\t},\n\t}\n\tk8sutil.AddRookVersionLabelToDeployment(d)\n\tc.store.Spec.Gateway.Annotations.ApplyToObjectMeta(&d.ObjectMeta)\n\tc.store.Spec.Gateway.Labels.ApplyToObjectMeta(&d.ObjectMeta)\n\tcontroller.AddCephVersionLabelToDeployment(c.clusterInfo.CephVersion, d)\n\n\treturn d, nil\n}\n\nfunc (c *clusterConfig) makeRGWPodSpec(rgwConfig *rgwConfig) (v1.PodTemplateSpec, error) {\n\tpodSpec := v1.PodSpec{\n\t\tInitContainers: []v1.Container{\n\t\t\tc.makeChownInitContainer(rgwConfig),\n\t\t},\n\t\tContainers: []v1.Container{c.makeDaemonContainer(rgwConfig)},\n\t\tRestartPolicy: v1.RestartPolicyAlways,\n\t\tVolumes: append(\n\t\t\tcontroller.DaemonVolumes(c.DataPathMap, rgwConfig.ResourceName),\n\t\t\tc.mimeTypesVolume(),\n\t\t),\n\t\tHostNetwork: c.clusterSpec.Network.IsHost(),\n\t\tPriorityClassName: c.store.Spec.Gateway.PriorityClassName,\n\t}\n\n\t\/\/ If the log collector is enabled we add the side-car container\n\tif c.clusterSpec.LogCollector.Enabled {\n\t\tshareProcessNamespace := true\n\t\tpodSpec.ShareProcessNamespace = &shareProcessNamespace\n\t\tpodSpec.Containers = append(podSpec.Containers, *controller.LogCollectorContainer(strings.TrimPrefix(generateCephXUser(fmt.Sprintf(\"ceph-client.%s\", rgwConfig.ResourceName)), \"client.\"), c.clusterInfo.Namespace, *c.clusterSpec))\n\t}\n\n\t\/\/ Replace default unreachable node toleration\n\tk8sutil.AddUnreachableNodeToleration(&podSpec)\n\n\t\/\/ Set the ssl cert if specified\n\tif c.store.Spec.Gateway.SSLCertificateRef != \"\" {\n\t\t\/\/ Keep the SSL secret as secure as possible in the container. Give only user read perms.\n\t\t\/\/ Because the Secret mount is owned by \"root\" and fsGroup breaks on OCP since we cannot predict it\n\t\t\/\/ Also, we don't want to change the SCC for fsGroup to RunAsAny since it has a major broader impact\n\t\t\/\/ Let's open the permissions a bit more so that everyone can read the cert.\n\t\tuserReadOnly := int32(0444)\n\t\tcertVol := v1.Volume{\n\t\t\tName: certVolumeName,\n\t\t\tVolumeSource: v1.VolumeSource{\n\t\t\t\tSecret: &v1.SecretVolumeSource{\n\t\t\t\t\tSecretName: c.store.Spec.Gateway.SSLCertificateRef,\n\t\t\t\t\tItems: []v1.KeyToPath{\n\t\t\t\t\t\t{Key: certKeyName, Path: certFilename, Mode: &userReadOnly},\n\t\t\t\t\t}}}}\n\t\tpodSpec.Volumes = append(podSpec.Volumes, certVol)\n\t}\n\n\t\/\/ If host networking is not enabled, preferred pod anti-affinity is added to the rgw daemons\n\tlabels := getLabels(c.store.Name, c.store.Namespace, false)\n\tk8sutil.SetNodeAntiAffinityForPod(&podSpec, c.store.Spec.Gateway.Placement, c.clusterSpec.Network.IsHost(), labels, nil)\n\n\tpodTemplateSpec := v1.PodTemplateSpec{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: rgwConfig.ResourceName,\n\t\t\tLabels: getLabels(c.store.Name, c.store.Namespace, true),\n\t\t},\n\t\tSpec: podSpec,\n\t}\n\tc.store.Spec.Gateway.Annotations.ApplyToObjectMeta(&podTemplateSpec.ObjectMeta)\n\tc.store.Spec.Gateway.Labels.ApplyToObjectMeta(&podTemplateSpec.ObjectMeta)\n\n\tif c.clusterSpec.Network.IsHost() {\n\t\tpodTemplateSpec.Spec.DNSPolicy = v1.DNSClusterFirstWithHostNet\n\t} else if c.clusterSpec.Network.IsMultus() {\n\t\tif err := k8sutil.ApplyMultus(c.clusterSpec.Network.NetworkSpec, &podTemplateSpec.ObjectMeta); err != nil {\n\t\t\treturn podTemplateSpec, err\n\t\t}\n\t}\n\n\treturn podTemplateSpec, nil\n}\n\nfunc (c *clusterConfig) makeChownInitContainer(rgwConfig *rgwConfig) v1.Container {\n\treturn controller.ChownCephDataDirsInitContainer(\n\t\t*c.DataPathMap,\n\t\tc.clusterSpec.CephVersion.Image,\n\t\tcontroller.DaemonVolumeMounts(c.DataPathMap, rgwConfig.ResourceName),\n\t\tc.store.Spec.Gateway.Resources,\n\t\tcontroller.PodSecurityContext(),\n\t)\n}\n\nfunc (c *clusterConfig) makeDaemonContainer(rgwConfig *rgwConfig) v1.Container {\n\t\/\/ start the rgw daemon in the foreground\n\tcontainer := v1.Container{\n\t\tName: \"rgw\",\n\t\tImage: c.clusterSpec.CephVersion.Image,\n\t\tCommand: []string{\n\t\t\t\"radosgw\",\n\t\t},\n\t\tArgs: append(\n\t\t\tcontroller.DaemonFlags(c.clusterInfo, c.clusterSpec,\n\t\t\t\tstrings.TrimPrefix(generateCephXUser(rgwConfig.ResourceName), \"client.\")),\n\t\t\t\"--foreground\",\n\t\t\tcephconfig.NewFlag(\"rgw frontends\", fmt.Sprintf(\"%s %s\", rgwFrontendName, c.portString())),\n\t\t\tcephconfig.NewFlag(\"host\", controller.ContainerEnvVarReference(k8sutil.PodNameEnvVar)),\n\t\t\tcephconfig.NewFlag(\"rgw-mime-types-file\", mimeTypesMountPath()),\n\t\t\tcephconfig.NewFlag(\"rgw realm\", rgwConfig.Realm),\n\t\t\tcephconfig.NewFlag(\"rgw zonegroup\", rgwConfig.ZoneGroup),\n\t\t\tcephconfig.NewFlag(\"rgw zone\", rgwConfig.Zone),\n\t\t),\n\t\tVolumeMounts: append(\n\t\t\tcontroller.DaemonVolumeMounts(c.DataPathMap, rgwConfig.ResourceName),\n\t\t\tc.mimeTypesVolumeMount(),\n\t\t),\n\t\tEnv: controller.DaemonEnvVars(c.clusterSpec.CephVersion.Image),\n\t\tResources: c.store.Spec.Gateway.Resources,\n\t\tLivenessProbe: c.generateLiveProbe(),\n\t\tSecurityContext: controller.PodSecurityContext(),\n\t}\n\n\t\/\/ If the liveness probe is enabled\n\tconfigureLivenessProbe(&container, c.store.Spec.HealthCheck)\n\tif c.store.Spec.Gateway.SSLCertificateRef != \"\" {\n\t\t\/\/ Add a volume mount for the ssl certificate\n\t\tmount := v1.VolumeMount{Name: certVolumeName, MountPath: certDir, ReadOnly: true}\n\t\tcontainer.VolumeMounts = append(container.VolumeMounts, mount)\n\t}\n\n\treturn container\n}\n\n\/\/ configureLivenessProbe returns the desired liveness probe for a given daemon\nfunc configureLivenessProbe(container *v1.Container, healthCheck cephv1.BucketHealthCheckSpec) {\n\tif ok := healthCheck.LivenessProbe; ok != nil {\n\t\tif !healthCheck.LivenessProbe.Disabled {\n\t\t\tprobe := healthCheck.LivenessProbe.Probe\n\t\t\t\/\/ If the spec value is empty, let's use a default\n\t\t\tif probe != nil {\n\t\t\t\tcontainer.LivenessProbe = probe\n\t\t\t}\n\t\t} else {\n\t\t\tcontainer.LivenessProbe = nil\n\t\t}\n\t}\n}\n\nfunc (c *clusterConfig) generateLiveProbe() *v1.Probe {\n\treturn &v1.Probe{\n\t\tHandler: v1.Handler{\n\t\t\tHTTPGet: &v1.HTTPGetAction{\n\t\t\t\tPath: livenessProbePath,\n\t\t\t\tPort: c.generateLiveProbePort(),\n\t\t\t\tScheme: c.generateLiveProbeScheme(),\n\t\t\t},\n\t\t},\n\t\tInitialDelaySeconds: 10,\n\t}\n}\n\nfunc (c *clusterConfig) generateLiveProbeScheme() v1.URIScheme {\n\t\/\/ Default to HTTP\n\turiScheme := v1.URISchemeHTTP\n\n\t\/\/ If rgw is configured to use a secured port we need get on https:\/\/\n\t\/\/ Only do this when the Non-SSL port is not used\n\tif c.store.Spec.Gateway.Port == 0 && c.store.Spec.Gateway.SecurePort != 0 && c.store.Spec.Gateway.SSLCertificateRef != \"\" {\n\t\turiScheme = v1.URISchemeHTTPS\n\t}\n\n\treturn uriScheme\n}\n\nfunc (c *clusterConfig) generateLiveProbePort() intstr.IntOrString {\n\t\/\/ The port the liveness probe needs to probe\n\t\/\/ Assume we run on SDN by default\n\tport := intstr.FromInt(int(rgwPortInternalPort))\n\n\t\/\/ If Host Networking is enabled, the port from the spec must be reflected\n\tif c.clusterSpec.Network.IsHost() {\n\t\tif c.store.Spec.Gateway.Port == 0 && c.store.Spec.Gateway.SecurePort != 0 && c.store.Spec.Gateway.SSLCertificateRef != \"\" {\n\t\t\tport = intstr.FromInt(int(c.store.Spec.Gateway.SecurePort))\n\t\t} else {\n\t\t\tport = intstr.FromInt(int(c.store.Spec.Gateway.Port))\n\t\t}\n\t}\n\n\treturn port\n}\n\nfunc (c *clusterConfig) generateService(cephObjectStore *cephv1.CephObjectStore) *v1.Service {\n\tlabels := getLabels(cephObjectStore.Name, cephObjectStore.Namespace, true)\n\tsvc := &v1.Service{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: instanceName(cephObjectStore.Name),\n\t\t\tNamespace: cephObjectStore.Namespace,\n\t\t\tLabels: labels,\n\t\t},\n\t}\n\n\tif c.clusterSpec.Network.IsHost() {\n\t\tsvc.Spec.ClusterIP = v1.ClusterIPNone\n\t}\n\n\tdestPort := c.generateLiveProbePort()\n\n\t\/\/ When the cluster is external we must use the same one as the gateways are listening on\n\tif c.clusterSpec.External.Enable {\n\t\tdestPort.IntVal = cephObjectStore.Spec.Gateway.Port\n\t} else {\n\t\t\/\/ If the cluster is not external we add the Selector\n\t\tsvc.Spec = v1.ServiceSpec{\n\t\t\tSelector: labels,\n\t\t}\n\t}\n\taddPort(svc, \"http\", cephObjectStore.Spec.Gateway.Port, destPort.IntVal)\n\taddPort(svc, \"https\", cephObjectStore.Spec.Gateway.SecurePort, cephObjectStore.Spec.Gateway.SecurePort)\n\n\treturn svc\n}\n\nfunc (c *clusterConfig) generateEndpoint(cephObjectStore *cephv1.CephObjectStore) *v1.Endpoints {\n\tlabels := getLabels(cephObjectStore.Name, cephObjectStore.Namespace, true)\n\n\tendpoints := &v1.Endpoints{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: instanceName(cephObjectStore.Name),\n\t\t\tNamespace: cephObjectStore.Namespace,\n\t\t\tLabels: labels,\n\t\t},\n\t\tSubsets: []v1.EndpointSubset{\n\t\t\t{\n\t\t\t\tAddresses: cephObjectStore.Spec.Gateway.ExternalRgwEndpoints,\n\t\t\t},\n\t\t},\n\t}\n\n\taddPortToEndpoint(endpoints, \"http\", cephObjectStore.Spec.Gateway.Port)\n\taddPortToEndpoint(endpoints, \"https\", cephObjectStore.Spec.Gateway.SecurePort)\n\n\treturn endpoints\n}\n\nfunc (c *clusterConfig) reconcileExternalEndpoint(cephObjectStore *cephv1.CephObjectStore) error {\n\tlogger.Info(\"reconciling external object store service\")\n\n\tendpoint := c.generateEndpoint(cephObjectStore)\n\t\/\/ Set owner ref to the parent object\n\terr := controllerutil.SetControllerReference(cephObjectStore, endpoint, c.scheme)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to set owner reference to ceph object store endpoint\")\n\t}\n\n\t_, err = k8sutil.CreateOrUpdateEndpoint(c.context.Clientset, cephObjectStore.Namespace, endpoint)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to create or update object store %q endpoint\", cephObjectStore.Name)\n\t}\n\n\treturn nil\n}\n\nfunc (c *clusterConfig) reconcileService(cephObjectStore *cephv1.CephObjectStore) (string, error) {\n\tservice := c.generateService(cephObjectStore)\n\t\/\/ Set owner ref to the parent object\n\terr := controllerutil.SetControllerReference(cephObjectStore, service, c.scheme)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"failed to set owner reference to ceph object store service\")\n\t}\n\n\tsvc, err := k8sutil.CreateOrUpdateService(c.context.Clientset, cephObjectStore.Namespace, service)\n\tif err != nil {\n\t\treturn \"\", errors.Wrapf(err, \"failed to create or update object store %q service\", cephObjectStore.Name)\n\t}\n\n\tlogger.Infof(\"ceph object store gateway service running at %s\", svc.Spec.ClusterIP)\n\n\treturn svc.Spec.ClusterIP, nil\n}\n\nfunc addPort(service *v1.Service, name string, port, destPort int32) {\n\tif port == 0 || destPort == 0 {\n\t\treturn\n\t}\n\tservice.Spec.Ports = append(service.Spec.Ports, v1.ServicePort{\n\t\tName: name,\n\t\tPort: port,\n\t\tTargetPort: intstr.FromInt(int(destPort)),\n\t\tProtocol: v1.ProtocolTCP,\n\t})\n}\n\nfunc addPortToEndpoint(endpoints *v1.Endpoints, name string, port int32) {\n\tif port == 0 {\n\t\treturn\n\t}\n\tendpoints.Subsets[0].Ports = append(endpoints.Subsets[0].Ports, v1.EndpointPort{\n\t\tName: name,\n\t\tPort: port,\n\t\tProtocol: v1.ProtocolTCP,\n\t},\n\t)\n}\n\nfunc getLabels(name, namespace string, includeNewLabels bool) map[string]string {\n\tlabels := controller.CephDaemonAppLabels(AppName, namespace, \"rgw\", name, includeNewLabels)\n\tlabels[\"rook_object_store\"] = name\n\treturn labels\n}\nceph: rgw service selector should not change\/*\nCopyright 2018 The Rook Authors. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n\thttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage object\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/pkg\/errors\"\n\tcephv1 \"github.com\/rook\/rook\/pkg\/apis\/ceph.rook.io\/v1\"\n\tcephconfig \"github.com\/rook\/rook\/pkg\/operator\/ceph\/config\"\n\t\"github.com\/rook\/rook\/pkg\/operator\/ceph\/controller\"\n\t\"github.com\/rook\/rook\/pkg\/operator\/k8sutil\"\n\tapps \"k8s.io\/api\/apps\/v1\"\n\tv1 \"k8s.io\/api\/core\/v1\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/util\/intstr\"\n\t\"sigs.k8s.io\/controller-runtime\/pkg\/controller\/controllerutil\"\n)\n\nconst (\n\tlivenessProbePath = \"\/swift\/healthcheck\"\n)\n\nfunc (c *clusterConfig) createDeployment(rgwConfig *rgwConfig) (*apps.Deployment, error) {\n\tpod, err := c.makeRGWPodSpec(rgwConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treplicas := int32(1)\n\td := &apps.Deployment{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: rgwConfig.ResourceName,\n\t\t\tNamespace: c.store.Namespace,\n\t\t\tLabels: getLabels(c.store.Name, c.store.Namespace, true),\n\t\t},\n\t\tSpec: apps.DeploymentSpec{\n\t\t\tSelector: &metav1.LabelSelector{\n\t\t\t\tMatchLabels: getLabels(c.store.Name, c.store.Namespace, false),\n\t\t\t},\n\t\t\tTemplate: pod,\n\t\t\tReplicas: &replicas,\n\t\t\tStrategy: apps.DeploymentStrategy{\n\t\t\t\tType: apps.RecreateDeploymentStrategyType,\n\t\t\t},\n\t\t},\n\t}\n\tk8sutil.AddRookVersionLabelToDeployment(d)\n\tc.store.Spec.Gateway.Annotations.ApplyToObjectMeta(&d.ObjectMeta)\n\tc.store.Spec.Gateway.Labels.ApplyToObjectMeta(&d.ObjectMeta)\n\tcontroller.AddCephVersionLabelToDeployment(c.clusterInfo.CephVersion, d)\n\n\treturn d, nil\n}\n\nfunc (c *clusterConfig) makeRGWPodSpec(rgwConfig *rgwConfig) (v1.PodTemplateSpec, error) {\n\tpodSpec := v1.PodSpec{\n\t\tInitContainers: []v1.Container{\n\t\t\tc.makeChownInitContainer(rgwConfig),\n\t\t},\n\t\tContainers: []v1.Container{c.makeDaemonContainer(rgwConfig)},\n\t\tRestartPolicy: v1.RestartPolicyAlways,\n\t\tVolumes: append(\n\t\t\tcontroller.DaemonVolumes(c.DataPathMap, rgwConfig.ResourceName),\n\t\t\tc.mimeTypesVolume(),\n\t\t),\n\t\tHostNetwork: c.clusterSpec.Network.IsHost(),\n\t\tPriorityClassName: c.store.Spec.Gateway.PriorityClassName,\n\t}\n\n\t\/\/ If the log collector is enabled we add the side-car container\n\tif c.clusterSpec.LogCollector.Enabled {\n\t\tshareProcessNamespace := true\n\t\tpodSpec.ShareProcessNamespace = &shareProcessNamespace\n\t\tpodSpec.Containers = append(podSpec.Containers, *controller.LogCollectorContainer(strings.TrimPrefix(generateCephXUser(fmt.Sprintf(\"ceph-client.%s\", rgwConfig.ResourceName)), \"client.\"), c.clusterInfo.Namespace, *c.clusterSpec))\n\t}\n\n\t\/\/ Replace default unreachable node toleration\n\tk8sutil.AddUnreachableNodeToleration(&podSpec)\n\n\t\/\/ Set the ssl cert if specified\n\tif c.store.Spec.Gateway.SSLCertificateRef != \"\" {\n\t\t\/\/ Keep the SSL secret as secure as possible in the container. Give only user read perms.\n\t\t\/\/ Because the Secret mount is owned by \"root\" and fsGroup breaks on OCP since we cannot predict it\n\t\t\/\/ Also, we don't want to change the SCC for fsGroup to RunAsAny since it has a major broader impact\n\t\t\/\/ Let's open the permissions a bit more so that everyone can read the cert.\n\t\tuserReadOnly := int32(0444)\n\t\tcertVol := v1.Volume{\n\t\t\tName: certVolumeName,\n\t\t\tVolumeSource: v1.VolumeSource{\n\t\t\t\tSecret: &v1.SecretVolumeSource{\n\t\t\t\t\tSecretName: c.store.Spec.Gateway.SSLCertificateRef,\n\t\t\t\t\tItems: []v1.KeyToPath{\n\t\t\t\t\t\t{Key: certKeyName, Path: certFilename, Mode: &userReadOnly},\n\t\t\t\t\t}}}}\n\t\tpodSpec.Volumes = append(podSpec.Volumes, certVol)\n\t}\n\n\t\/\/ If host networking is not enabled, preferred pod anti-affinity is added to the rgw daemons\n\tlabels := getLabels(c.store.Name, c.store.Namespace, false)\n\tk8sutil.SetNodeAntiAffinityForPod(&podSpec, c.store.Spec.Gateway.Placement, c.clusterSpec.Network.IsHost(), labels, nil)\n\n\tpodTemplateSpec := v1.PodTemplateSpec{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: rgwConfig.ResourceName,\n\t\t\tLabels: getLabels(c.store.Name, c.store.Namespace, true),\n\t\t},\n\t\tSpec: podSpec,\n\t}\n\tc.store.Spec.Gateway.Annotations.ApplyToObjectMeta(&podTemplateSpec.ObjectMeta)\n\tc.store.Spec.Gateway.Labels.ApplyToObjectMeta(&podTemplateSpec.ObjectMeta)\n\n\tif c.clusterSpec.Network.IsHost() {\n\t\tpodTemplateSpec.Spec.DNSPolicy = v1.DNSClusterFirstWithHostNet\n\t} else if c.clusterSpec.Network.IsMultus() {\n\t\tif err := k8sutil.ApplyMultus(c.clusterSpec.Network.NetworkSpec, &podTemplateSpec.ObjectMeta); err != nil {\n\t\t\treturn podTemplateSpec, err\n\t\t}\n\t}\n\n\treturn podTemplateSpec, nil\n}\n\nfunc (c *clusterConfig) makeChownInitContainer(rgwConfig *rgwConfig) v1.Container {\n\treturn controller.ChownCephDataDirsInitContainer(\n\t\t*c.DataPathMap,\n\t\tc.clusterSpec.CephVersion.Image,\n\t\tcontroller.DaemonVolumeMounts(c.DataPathMap, rgwConfig.ResourceName),\n\t\tc.store.Spec.Gateway.Resources,\n\t\tcontroller.PodSecurityContext(),\n\t)\n}\n\nfunc (c *clusterConfig) makeDaemonContainer(rgwConfig *rgwConfig) v1.Container {\n\t\/\/ start the rgw daemon in the foreground\n\tcontainer := v1.Container{\n\t\tName: \"rgw\",\n\t\tImage: c.clusterSpec.CephVersion.Image,\n\t\tCommand: []string{\n\t\t\t\"radosgw\",\n\t\t},\n\t\tArgs: append(\n\t\t\tcontroller.DaemonFlags(c.clusterInfo, c.clusterSpec,\n\t\t\t\tstrings.TrimPrefix(generateCephXUser(rgwConfig.ResourceName), \"client.\")),\n\t\t\t\"--foreground\",\n\t\t\tcephconfig.NewFlag(\"rgw frontends\", fmt.Sprintf(\"%s %s\", rgwFrontendName, c.portString())),\n\t\t\tcephconfig.NewFlag(\"host\", controller.ContainerEnvVarReference(k8sutil.PodNameEnvVar)),\n\t\t\tcephconfig.NewFlag(\"rgw-mime-types-file\", mimeTypesMountPath()),\n\t\t\tcephconfig.NewFlag(\"rgw realm\", rgwConfig.Realm),\n\t\t\tcephconfig.NewFlag(\"rgw zonegroup\", rgwConfig.ZoneGroup),\n\t\t\tcephconfig.NewFlag(\"rgw zone\", rgwConfig.Zone),\n\t\t),\n\t\tVolumeMounts: append(\n\t\t\tcontroller.DaemonVolumeMounts(c.DataPathMap, rgwConfig.ResourceName),\n\t\t\tc.mimeTypesVolumeMount(),\n\t\t),\n\t\tEnv: controller.DaemonEnvVars(c.clusterSpec.CephVersion.Image),\n\t\tResources: c.store.Spec.Gateway.Resources,\n\t\tLivenessProbe: c.generateLiveProbe(),\n\t\tSecurityContext: controller.PodSecurityContext(),\n\t}\n\n\t\/\/ If the liveness probe is enabled\n\tconfigureLivenessProbe(&container, c.store.Spec.HealthCheck)\n\tif c.store.Spec.Gateway.SSLCertificateRef != \"\" {\n\t\t\/\/ Add a volume mount for the ssl certificate\n\t\tmount := v1.VolumeMount{Name: certVolumeName, MountPath: certDir, ReadOnly: true}\n\t\tcontainer.VolumeMounts = append(container.VolumeMounts, mount)\n\t}\n\n\treturn container\n}\n\n\/\/ configureLivenessProbe returns the desired liveness probe for a given daemon\nfunc configureLivenessProbe(container *v1.Container, healthCheck cephv1.BucketHealthCheckSpec) {\n\tif ok := healthCheck.LivenessProbe; ok != nil {\n\t\tif !healthCheck.LivenessProbe.Disabled {\n\t\t\tprobe := healthCheck.LivenessProbe.Probe\n\t\t\t\/\/ If the spec value is empty, let's use a default\n\t\t\tif probe != nil {\n\t\t\t\tcontainer.LivenessProbe = probe\n\t\t\t}\n\t\t} else {\n\t\t\tcontainer.LivenessProbe = nil\n\t\t}\n\t}\n}\n\nfunc (c *clusterConfig) generateLiveProbe() *v1.Probe {\n\treturn &v1.Probe{\n\t\tHandler: v1.Handler{\n\t\t\tHTTPGet: &v1.HTTPGetAction{\n\t\t\t\tPath: livenessProbePath,\n\t\t\t\tPort: c.generateLiveProbePort(),\n\t\t\t\tScheme: c.generateLiveProbeScheme(),\n\t\t\t},\n\t\t},\n\t\tInitialDelaySeconds: 10,\n\t}\n}\n\nfunc (c *clusterConfig) generateLiveProbeScheme() v1.URIScheme {\n\t\/\/ Default to HTTP\n\turiScheme := v1.URISchemeHTTP\n\n\t\/\/ If rgw is configured to use a secured port we need get on https:\/\/\n\t\/\/ Only do this when the Non-SSL port is not used\n\tif c.store.Spec.Gateway.Port == 0 && c.store.Spec.Gateway.SecurePort != 0 && c.store.Spec.Gateway.SSLCertificateRef != \"\" {\n\t\turiScheme = v1.URISchemeHTTPS\n\t}\n\n\treturn uriScheme\n}\n\nfunc (c *clusterConfig) generateLiveProbePort() intstr.IntOrString {\n\t\/\/ The port the liveness probe needs to probe\n\t\/\/ Assume we run on SDN by default\n\tport := intstr.FromInt(int(rgwPortInternalPort))\n\n\t\/\/ If Host Networking is enabled, the port from the spec must be reflected\n\tif c.clusterSpec.Network.IsHost() {\n\t\tif c.store.Spec.Gateway.Port == 0 && c.store.Spec.Gateway.SecurePort != 0 && c.store.Spec.Gateway.SSLCertificateRef != \"\" {\n\t\t\tport = intstr.FromInt(int(c.store.Spec.Gateway.SecurePort))\n\t\t} else {\n\t\t\tport = intstr.FromInt(int(c.store.Spec.Gateway.Port))\n\t\t}\n\t}\n\n\treturn port\n}\n\nfunc (c *clusterConfig) generateService(cephObjectStore *cephv1.CephObjectStore) *v1.Service {\n\tsvc := &v1.Service{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: instanceName(cephObjectStore.Name),\n\t\t\tNamespace: cephObjectStore.Namespace,\n\t\t\tLabels: getLabels(cephObjectStore.Name, cephObjectStore.Namespace, true),\n\t\t},\n\t}\n\n\tif c.clusterSpec.Network.IsHost() {\n\t\tsvc.Spec.ClusterIP = v1.ClusterIPNone\n\t}\n\n\tdestPort := c.generateLiveProbePort()\n\n\t\/\/ When the cluster is external we must use the same one as the gateways are listening on\n\tif c.clusterSpec.External.Enable {\n\t\tdestPort.IntVal = cephObjectStore.Spec.Gateway.Port\n\t} else {\n\t\t\/\/ If the cluster is not external we add the Selector\n\t\tsvc.Spec = v1.ServiceSpec{\n\t\t\tSelector: getLabels(cephObjectStore.Name, cephObjectStore.Namespace, false),\n\t\t}\n\t}\n\taddPort(svc, \"http\", cephObjectStore.Spec.Gateway.Port, destPort.IntVal)\n\taddPort(svc, \"https\", cephObjectStore.Spec.Gateway.SecurePort, cephObjectStore.Spec.Gateway.SecurePort)\n\n\treturn svc\n}\n\nfunc (c *clusterConfig) generateEndpoint(cephObjectStore *cephv1.CephObjectStore) *v1.Endpoints {\n\tlabels := getLabels(cephObjectStore.Name, cephObjectStore.Namespace, true)\n\n\tendpoints := &v1.Endpoints{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: instanceName(cephObjectStore.Name),\n\t\t\tNamespace: cephObjectStore.Namespace,\n\t\t\tLabels: labels,\n\t\t},\n\t\tSubsets: []v1.EndpointSubset{\n\t\t\t{\n\t\t\t\tAddresses: cephObjectStore.Spec.Gateway.ExternalRgwEndpoints,\n\t\t\t},\n\t\t},\n\t}\n\n\taddPortToEndpoint(endpoints, \"http\", cephObjectStore.Spec.Gateway.Port)\n\taddPortToEndpoint(endpoints, \"https\", cephObjectStore.Spec.Gateway.SecurePort)\n\n\treturn endpoints\n}\n\nfunc (c *clusterConfig) reconcileExternalEndpoint(cephObjectStore *cephv1.CephObjectStore) error {\n\tlogger.Info(\"reconciling external object store service\")\n\n\tendpoint := c.generateEndpoint(cephObjectStore)\n\t\/\/ Set owner ref to the parent object\n\terr := controllerutil.SetControllerReference(cephObjectStore, endpoint, c.scheme)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to set owner reference to ceph object store endpoint\")\n\t}\n\n\t_, err = k8sutil.CreateOrUpdateEndpoint(c.context.Clientset, cephObjectStore.Namespace, endpoint)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to create or update object store %q endpoint\", cephObjectStore.Name)\n\t}\n\n\treturn nil\n}\n\nfunc (c *clusterConfig) reconcileService(cephObjectStore *cephv1.CephObjectStore) (string, error) {\n\tservice := c.generateService(cephObjectStore)\n\t\/\/ Set owner ref to the parent object\n\terr := controllerutil.SetControllerReference(cephObjectStore, service, c.scheme)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"failed to set owner reference to ceph object store service\")\n\t}\n\n\tsvc, err := k8sutil.CreateOrUpdateService(c.context.Clientset, cephObjectStore.Namespace, service)\n\tif err != nil {\n\t\treturn \"\", errors.Wrapf(err, \"failed to create or update object store %q service\", cephObjectStore.Name)\n\t}\n\n\tlogger.Infof(\"ceph object store gateway service running at %s\", svc.Spec.ClusterIP)\n\n\treturn svc.Spec.ClusterIP, nil\n}\n\nfunc addPort(service *v1.Service, name string, port, destPort int32) {\n\tif port == 0 || destPort == 0 {\n\t\treturn\n\t}\n\tservice.Spec.Ports = append(service.Spec.Ports, v1.ServicePort{\n\t\tName: name,\n\t\tPort: port,\n\t\tTargetPort: intstr.FromInt(int(destPort)),\n\t\tProtocol: v1.ProtocolTCP,\n\t})\n}\n\nfunc addPortToEndpoint(endpoints *v1.Endpoints, name string, port int32) {\n\tif port == 0 {\n\t\treturn\n\t}\n\tendpoints.Subsets[0].Ports = append(endpoints.Subsets[0].Ports, v1.EndpointPort{\n\t\tName: name,\n\t\tPort: port,\n\t\tProtocol: v1.ProtocolTCP,\n\t},\n\t)\n}\n\nfunc getLabels(name, namespace string, includeNewLabels bool) map[string]string {\n\tlabels := controller.CephDaemonAppLabels(AppName, namespace, \"rgw\", name, includeNewLabels)\n\tlabels[\"rook_object_store\"] = name\n\treturn labels\n}\n<|endoftext|>"} {"text":"\/*\nCopyright 2018 The Rook Authors. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n\thttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n\/\/ Package to manage a Minio object store.\npackage minio\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\n\t\"github.com\/coreos\/pkg\/capnslog\"\n\topkit \"github.com\/rook\/operator-kit\"\n\tminiov1alpha1 \"github.com\/rook\/rook\/pkg\/apis\/minio.rook.io\/v1alpha1\"\n\t\"github.com\/rook\/rook\/pkg\/clusterd\"\n\t\"github.com\/rook\/rook\/pkg\/operator\/k8sutil\"\n\t\"k8s.io\/api\/apps\/v1beta2\"\n\t\"k8s.io\/api\/core\/v1\"\n\tapiextensionsv1beta1 \"k8s.io\/apiextensions-apiserver\/pkg\/apis\/apiextensions\/v1beta1\"\n\t\"k8s.io\/apimachinery\/pkg\/api\/resource\"\n\tmeta_v1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/types\"\n\t\"k8s.io\/client-go\/tools\/cache\"\n)\n\n\/\/ TODO: A lot of these constants are specific to the KubeCon demo. Let's\n\/\/ revisit these and determine what should be specified in the resource spec.\nconst (\n\tcustomResourceName = \"objectstore\"\n\tcustomResourceNamePlural = \"objectstores\"\n\tminioCtrName = \"minio\"\n\tminioLabel = \"minio\"\n\tminioPVCName = \"minio-pvc\"\n\tminioServerSuffixFmt = \"%s.svc.cluster.local\"\n\tminioVolumeName = \"data\"\n\tobjectStoreDataDir = \"\/data\"\n)\n\nvar logger = capnslog.NewPackageLogger(\"github.com\/rook\/rook\", \"minio-op-object\")\n\n\/\/ ObjectStoreResource represents the object store custom resource\nvar ObjectStoreResource = opkit.CustomResource{\n\tName: customResourceName,\n\tPlural: customResourceNamePlural,\n\tGroup: miniov1alpha1.CustomResourceGroup,\n\tVersion: miniov1alpha1.Version,\n\tScope: apiextensionsv1beta1.NamespaceScoped,\n\tKind: reflect.TypeOf(miniov1alpha1.ObjectStore{}).Name(),\n}\n\n\/\/ MinioController represents a controller object for object store custom resources\ntype MinioController struct {\n\tcontext *clusterd.Context\n\trookImage string\n}\n\n\/\/ NewMinioController create controller for watching object store custom resources created\nfunc NewMinioController(context *clusterd.Context, rookImage string) *MinioController {\n\treturn &MinioController{\n\t\tcontext: context,\n\t\trookImage: rookImage,\n\t}\n}\n\n\/\/ StartWatch watches for instances of ObjectStore custom resources and acts on them\nfunc (c *MinioController) StartWatch(namespace string, stopCh chan struct{}) error {\n\tresourceHandlerFuncs := cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: c.onAdd,\n\t\tUpdateFunc: c.onUpdate,\n\t\tDeleteFunc: c.onDelete,\n\t}\n\n\tlogger.Infof(\"start watching object store resources in namespace %s\", namespace)\n\twatcher := opkit.NewWatcher(ObjectStoreResource, namespace, resourceHandlerFuncs, c.context.RookClientset.MinioV1alpha1().RESTClient())\n\tgo watcher.Watch(&miniov1alpha1.ObjectStore{}, stopCh)\n\n\treturn nil\n}\n\nfunc (c *MinioController) makeMinioHeadlessService(name, namespace string, spec miniov1alpha1.ObjectStoreSpec, ownerRef meta_v1.OwnerReference) (*v1.Service, error) {\n\tcoreV1Client := c.context.Clientset.CoreV1()\n\n\tsvc, err := coreV1Client.Services(namespace).Create(&v1.Service{\n\t\tObjectMeta: meta_v1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: map[string]string{k8sutil.AppAttr: minioLabel},\n\t\t\tOwnerReferences: []meta_v1.OwnerReference{ownerRef},\n\t\t},\n\t\tSpec: v1.ServiceSpec{\n\t\t\tSelector: map[string]string{k8sutil.AppAttr: minioLabel},\n\t\t\tPorts: []v1.ServicePort{{Port: spec.Port}},\n\t\t\tClusterIP: v1.ClusterIPNone,\n\t\t},\n\t})\n\n\treturn svc, err\n}\n\nfunc (c *MinioController) buildMinioCtrArgs(statefulSetPrefix, headlessServiceName, namespace string, serverCount int32) []string {\n\targs := []string{\"server\"}\n\tfor i := int32(0); i < serverCount; i++ {\n\t\tserverAddress := fmt.Sprintf(\"http:\/\/%s-%d.%s.%s%s\", statefulSetPrefix, i, headlessServiceName, fmt.Sprintf(minioServerSuffixFmt, namespace), objectStoreDataDir)\n\t\targs = append(args, serverAddress)\n\t}\n\n\tlogger.Infof(\"Building Minio container args: %v\", args)\n\treturn args\n}\n\nfunc (c *MinioController) makeMinioPodSpec(name, namespace string, ctrName string, ctrImage string, port int32, envVars map[string]string, numServers int32) v1.PodTemplateSpec {\n\tvar env []v1.EnvVar\n\tfor k, v := range envVars {\n\t\tenv = append(env, v1.EnvVar{Name: k, Value: v})\n\t}\n\n\tpodSpec := v1.PodTemplateSpec{\n\t\tObjectMeta: meta_v1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: map[string]string{k8sutil.AppAttr: minioLabel},\n\t\t},\n\t\tSpec: v1.PodSpec{\n\t\t\tContainers: []v1.Container{\n\t\t\t\t{\n\t\t\t\t\tName: ctrName,\n\t\t\t\t\tImage: ctrImage,\n\t\t\t\t\tEnv: env,\n\t\t\t\t\tCommand: []string{\"\/usr\/bin\/minio\"},\n\t\t\t\t\tPorts: []v1.ContainerPort{{ContainerPort: port}},\n\t\t\t\t\tArgs: c.buildMinioCtrArgs(name, name, namespace, numServers),\n\t\t\t\t\tVolumeMounts: []v1.VolumeMount{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: minioVolumeName,\n\t\t\t\t\t\t\tMountPath: objectStoreDataDir,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tVolumes: []v1.Volume{\n\t\t\t\t{\n\t\t\t\t\tName: minioVolumeName,\n\t\t\t\t\tVolumeSource: v1.VolumeSource{\n\t\t\t\t\t\tPersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{\n\t\t\t\t\t\t\tClaimName: minioPVCName,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\treturn podSpec\n}\n\nfunc (c *MinioController) getAccessCredentials(secretName, namespace string) (string, string, error) {\n\tcoreV1Client := c.context.Clientset.CoreV1()\n\tvar getOpts meta_v1.GetOptions\n\tval, err := coreV1Client.Secrets(namespace).Get(secretName, getOpts)\n\tif err != nil {\n\t\tlogger.Errorf(\"Unable to get secret with name=%s in namespace=%s: %v\", secretName, namespace, err)\n\t\treturn \"\", \"\", err\n\t}\n\n\treturn string(val.Data[\"username\"]), string(val.Data[\"password\"]), nil\n}\n\nfunc validateObjectStoreSpec(spec miniov1alpha1.ObjectStoreSpec) error {\n\t\/\/ Verify node count.\n\tcount := spec.Storage.NodeCount\n\tif count < 4 || count%2 != 0 {\n\t\treturn fmt.Errorf(\"Node count must be greater than 3 and even.\")\n\t}\n\n\t\/\/ Verify sane port.\n\tif spec.Port < 1024 {\n\t\treturn fmt.Errorf(\"Invalid port %d\", spec.Port)\n\t}\n\n\treturn nil\n}\n\nfunc (c *MinioController) makeMinioStatefulSet(name, namespace string, spec miniov1alpha1.ObjectStoreSpec, ownerRef meta_v1.OwnerReference) (*v1beta2.StatefulSet, error) {\n\tappsClient := c.context.Clientset.AppsV1beta2()\n\n\taccessKey, secretKey, err := c.getAccessCredentials(spec.Credentials.Name, spec.Credentials.Namespace)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tenvVars := map[string]string{\n\t\t\"MINIO_ACCESS_KEY\": accessKey,\n\t\t\"MINIO_SECRET_KEY\": secretKey,\n\t}\n\n\tpodSpec := c.makeMinioPodSpec(name, namespace, minioCtrName, c.rookImage, spec.Port, envVars, int32(spec.Storage.NodeCount))\n\n\tnodeCount := int32(spec.Storage.NodeCount)\n\tss := v1beta2.StatefulSet{\n\t\tObjectMeta: meta_v1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: map[string]string{k8sutil.AppAttr: minioLabel},\n\t\t\tOwnerReferences: []meta_v1.OwnerReference{ownerRef},\n\t\t},\n\t\tSpec: v1beta2.StatefulSetSpec{\n\t\t\tReplicas: &nodeCount,\n\t\t\tSelector: &meta_v1.LabelSelector{\n\t\t\t\tMatchLabels: map[string]string{k8sutil.AppAttr: minioLabel},\n\t\t\t},\n\t\t\tTemplate: podSpec,\n\t\t\tVolumeClaimTemplates: []v1.PersistentVolumeClaim{\n\t\t\t\t{\n\t\t\t\t\tObjectMeta: meta_v1.ObjectMeta{\n\t\t\t\t\t\tName: minioVolumeName,\n\t\t\t\t\t\tNamespace: namespace,\n\t\t\t\t\t},\n\t\t\t\t\tSpec: v1.PersistentVolumeClaimSpec{\n\t\t\t\t\t\tAccessModes: []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce},\n\t\t\t\t\t\tResources: v1.ResourceRequirements{\n\t\t\t\t\t\t\tRequests: v1.ResourceList{\n\t\t\t\t\t\t\t\tv1.ResourceStorage: resource.MustParse(spec.StorageSize),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tServiceName: name,\n\t\t\t\/\/ TODO: liveness probe\n\t\t},\n\t}\n\n\treturn appsClient.StatefulSets(namespace).Create(&ss)\n}\n\nfunc (c *MinioController) onAdd(obj interface{}) {\n\tobjectstore := obj.(*miniov1alpha1.ObjectStore).DeepCopy()\n\n\townerRef := meta_v1.OwnerReference{\n\t\tAPIVersion: ObjectStoreResource.Version,\n\t\tKind: ObjectStoreResource.Kind,\n\t\tName: objectstore.Namespace,\n\t\tUID: types.UID(objectstore.ObjectMeta.UID),\n\t}\n\n\t\/\/ Validate object store config.\n\terr := validateObjectStoreSpec(objectstore.Spec)\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to validate object store config\")\n\t\treturn\n\t}\n\n\t\/\/ Create the headless service.\n\tlogger.Infof(\"Creating Minio headless service %s in namespace %s.\", objectstore.Name, objectstore.Namespace)\n\t_, err = c.makeMinioHeadlessService(objectstore.Name, objectstore.Namespace, objectstore.Spec, ownerRef)\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to create minio headless service: %v\", err)\n\t\treturn\n\t}\n\tlogger.Infof(\"Finished creating Minio headless service %s in namespace %s.\", objectstore.Name, objectstore.Namespace)\n\n\t\/\/ Create the stateful set.\n\tlogger.Infof(\"Creating Minio stateful set %s.\", objectstore.Name)\n\t_, err = c.makeMinioStatefulSet(objectstore.Name, objectstore.Namespace, objectstore.Spec, ownerRef)\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to create minio stateful set: %v\", err)\n\t\treturn\n\t}\n\tlogger.Infof(\"Finished creating Minio stateful set %s in namespace %s.\", objectstore.Name, objectstore.Namespace)\n}\n\nfunc (c *MinioController) onUpdate(oldObj, newObj interface{}) {\n\toldStore := oldObj.(*miniov1alpha1.ObjectStore).DeepCopy()\n\tnewStore := newObj.(*miniov1alpha1.ObjectStore).DeepCopy()\n\n\t_ = oldStore\n\t_ = newStore\n\n\tlogger.Infof(\"Received update on object store %s in namespace %s. This is currently unsupported.\", oldStore.Name, oldStore.Namespace)\n}\n\nfunc (c *MinioController) onDelete(obj interface{}) {\n\tobjectstore := obj.(*miniov1alpha1.ObjectStore).DeepCopy()\n\tlogger.Infof(\"Delete Minio object store %s\", objectstore.Name)\n\n\t\/\/ Cleanup is handled by the owner references set in 'onAdd' and the k8s garbage collector.\n}\nremove svc.cluster.local from serverAddress\/*\nCopyright 2018 The Rook Authors. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n\thttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n\/\/ Package to manage a Minio object store.\npackage minio\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\n\t\"github.com\/coreos\/pkg\/capnslog\"\n\topkit \"github.com\/rook\/operator-kit\"\n\tminiov1alpha1 \"github.com\/rook\/rook\/pkg\/apis\/minio.rook.io\/v1alpha1\"\n\t\"github.com\/rook\/rook\/pkg\/clusterd\"\n\t\"github.com\/rook\/rook\/pkg\/operator\/k8sutil\"\n\t\"k8s.io\/api\/apps\/v1beta2\"\n\t\"k8s.io\/api\/core\/v1\"\n\tapiextensionsv1beta1 \"k8s.io\/apiextensions-apiserver\/pkg\/apis\/apiextensions\/v1beta1\"\n\t\"k8s.io\/apimachinery\/pkg\/api\/resource\"\n\tmeta_v1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/types\"\n\t\"k8s.io\/client-go\/tools\/cache\"\n)\n\n\/\/ TODO: A lot of these constants are specific to the KubeCon demo. Let's\n\/\/ revisit these and determine what should be specified in the resource spec.\nconst (\n\tcustomResourceName = \"objectstore\"\n\tcustomResourceNamePlural = \"objectstores\"\n\tminioCtrName = \"minio\"\n\tminioLabel = \"minio\"\n\tminioPVCName = \"minio-pvc\"\n\tminioVolumeName = \"data\"\n\tobjectStoreDataDir = \"\/data\"\n)\n\nvar logger = capnslog.NewPackageLogger(\"github.com\/rook\/rook\", \"minio-op-object\")\n\n\/\/ ObjectStoreResource represents the object store custom resource\nvar ObjectStoreResource = opkit.CustomResource{\n\tName: customResourceName,\n\tPlural: customResourceNamePlural,\n\tGroup: miniov1alpha1.CustomResourceGroup,\n\tVersion: miniov1alpha1.Version,\n\tScope: apiextensionsv1beta1.NamespaceScoped,\n\tKind: reflect.TypeOf(miniov1alpha1.ObjectStore{}).Name(),\n}\n\n\/\/ MinioController represents a controller object for object store custom resources\ntype MinioController struct {\n\tcontext *clusterd.Context\n\trookImage string\n}\n\n\/\/ NewMinioController create controller for watching object store custom resources created\nfunc NewMinioController(context *clusterd.Context, rookImage string) *MinioController {\n\treturn &MinioController{\n\t\tcontext: context,\n\t\trookImage: rookImage,\n\t}\n}\n\n\/\/ StartWatch watches for instances of ObjectStore custom resources and acts on them\nfunc (c *MinioController) StartWatch(namespace string, stopCh chan struct{}) error {\n\tresourceHandlerFuncs := cache.ResourceEventHandlerFuncs{\n\t\tAddFunc: c.onAdd,\n\t\tUpdateFunc: c.onUpdate,\n\t\tDeleteFunc: c.onDelete,\n\t}\n\n\tlogger.Infof(\"start watching object store resources in namespace %s\", namespace)\n\twatcher := opkit.NewWatcher(ObjectStoreResource, namespace, resourceHandlerFuncs, c.context.RookClientset.MinioV1alpha1().RESTClient())\n\tgo watcher.Watch(&miniov1alpha1.ObjectStore{}, stopCh)\n\n\treturn nil\n}\n\nfunc (c *MinioController) makeMinioHeadlessService(name, namespace string, spec miniov1alpha1.ObjectStoreSpec, ownerRef meta_v1.OwnerReference) (*v1.Service, error) {\n\tcoreV1Client := c.context.Clientset.CoreV1()\n\n\tsvc, err := coreV1Client.Services(namespace).Create(&v1.Service{\n\t\tObjectMeta: meta_v1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: map[string]string{k8sutil.AppAttr: minioLabel},\n\t\t\tOwnerReferences: []meta_v1.OwnerReference{ownerRef},\n\t\t},\n\t\tSpec: v1.ServiceSpec{\n\t\t\tSelector: map[string]string{k8sutil.AppAttr: minioLabel},\n\t\t\tPorts: []v1.ServicePort{{Port: spec.Port}},\n\t\t\tClusterIP: v1.ClusterIPNone,\n\t\t},\n\t})\n\n\treturn svc, err\n}\n\nfunc (c *MinioController) buildMinioCtrArgs(statefulSetPrefix, headlessServiceName, namespace string, serverCount int32) []string {\n\targs := []string{\"server\"}\n\tfor i := int32(0); i < serverCount; i++ {\n\t\tserverAddress := fmt.Sprintf(\"http:\/\/%s-%d.%s.%s%s\", statefulSetPrefix, i, headlessServiceName, namespace, objectStoreDataDir)\n\t\targs = append(args, serverAddress)\n\t}\n\n\tlogger.Infof(\"Building Minio container args: %v\", args)\n\treturn args\n}\n\nfunc (c *MinioController) makeMinioPodSpec(name, namespace string, ctrName string, ctrImage string, port int32, envVars map[string]string, numServers int32) v1.PodTemplateSpec {\n\tvar env []v1.EnvVar\n\tfor k, v := range envVars {\n\t\tenv = append(env, v1.EnvVar{Name: k, Value: v})\n\t}\n\n\tpodSpec := v1.PodTemplateSpec{\n\t\tObjectMeta: meta_v1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: map[string]string{k8sutil.AppAttr: minioLabel},\n\t\t},\n\t\tSpec: v1.PodSpec{\n\t\t\tContainers: []v1.Container{\n\t\t\t\t{\n\t\t\t\t\tName: ctrName,\n\t\t\t\t\tImage: ctrImage,\n\t\t\t\t\tEnv: env,\n\t\t\t\t\tCommand: []string{\"\/usr\/bin\/minio\"},\n\t\t\t\t\tPorts: []v1.ContainerPort{{ContainerPort: port}},\n\t\t\t\t\tArgs: c.buildMinioCtrArgs(name, name, namespace, numServers),\n\t\t\t\t\tVolumeMounts: []v1.VolumeMount{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: minioVolumeName,\n\t\t\t\t\t\t\tMountPath: objectStoreDataDir,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tVolumes: []v1.Volume{\n\t\t\t\t{\n\t\t\t\t\tName: minioVolumeName,\n\t\t\t\t\tVolumeSource: v1.VolumeSource{\n\t\t\t\t\t\tPersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{\n\t\t\t\t\t\t\tClaimName: minioPVCName,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\treturn podSpec\n}\n\nfunc (c *MinioController) getAccessCredentials(secretName, namespace string) (string, string, error) {\n\tcoreV1Client := c.context.Clientset.CoreV1()\n\tvar getOpts meta_v1.GetOptions\n\tval, err := coreV1Client.Secrets(namespace).Get(secretName, getOpts)\n\tif err != nil {\n\t\tlogger.Errorf(\"Unable to get secret with name=%s in namespace=%s: %v\", secretName, namespace, err)\n\t\treturn \"\", \"\", err\n\t}\n\n\treturn string(val.Data[\"username\"]), string(val.Data[\"password\"]), nil\n}\n\nfunc validateObjectStoreSpec(spec miniov1alpha1.ObjectStoreSpec) error {\n\t\/\/ Verify node count.\n\tcount := spec.Storage.NodeCount\n\tif count < 4 || count%2 != 0 {\n\t\treturn fmt.Errorf(\"Node count must be greater than 3 and even.\")\n\t}\n\n\t\/\/ Verify sane port.\n\tif spec.Port < 1024 {\n\t\treturn fmt.Errorf(\"Invalid port %d\", spec.Port)\n\t}\n\n\treturn nil\n}\n\nfunc (c *MinioController) makeMinioStatefulSet(name, namespace string, spec miniov1alpha1.ObjectStoreSpec, ownerRef meta_v1.OwnerReference) (*v1beta2.StatefulSet, error) {\n\tappsClient := c.context.Clientset.AppsV1beta2()\n\n\taccessKey, secretKey, err := c.getAccessCredentials(spec.Credentials.Name, spec.Credentials.Namespace)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tenvVars := map[string]string{\n\t\t\"MINIO_ACCESS_KEY\": accessKey,\n\t\t\"MINIO_SECRET_KEY\": secretKey,\n\t}\n\n\tpodSpec := c.makeMinioPodSpec(name, namespace, minioCtrName, c.rookImage, spec.Port, envVars, int32(spec.Storage.NodeCount))\n\n\tnodeCount := int32(spec.Storage.NodeCount)\n\tss := v1beta2.StatefulSet{\n\t\tObjectMeta: meta_v1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: namespace,\n\t\t\tLabels: map[string]string{k8sutil.AppAttr: minioLabel},\n\t\t\tOwnerReferences: []meta_v1.OwnerReference{ownerRef},\n\t\t},\n\t\tSpec: v1beta2.StatefulSetSpec{\n\t\t\tReplicas: &nodeCount,\n\t\t\tSelector: &meta_v1.LabelSelector{\n\t\t\t\tMatchLabels: map[string]string{k8sutil.AppAttr: minioLabel},\n\t\t\t},\n\t\t\tTemplate: podSpec,\n\t\t\tVolumeClaimTemplates: []v1.PersistentVolumeClaim{\n\t\t\t\t{\n\t\t\t\t\tObjectMeta: meta_v1.ObjectMeta{\n\t\t\t\t\t\tName: minioVolumeName,\n\t\t\t\t\t\tNamespace: namespace,\n\t\t\t\t\t},\n\t\t\t\t\tSpec: v1.PersistentVolumeClaimSpec{\n\t\t\t\t\t\tAccessModes: []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce},\n\t\t\t\t\t\tResources: v1.ResourceRequirements{\n\t\t\t\t\t\t\tRequests: v1.ResourceList{\n\t\t\t\t\t\t\t\tv1.ResourceStorage: resource.MustParse(spec.StorageSize),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tServiceName: name,\n\t\t\t\/\/ TODO: liveness probe\n\t\t},\n\t}\n\n\treturn appsClient.StatefulSets(namespace).Create(&ss)\n}\n\nfunc (c *MinioController) onAdd(obj interface{}) {\n\tobjectstore := obj.(*miniov1alpha1.ObjectStore).DeepCopy()\n\n\townerRef := meta_v1.OwnerReference{\n\t\tAPIVersion: ObjectStoreResource.Version,\n\t\tKind: ObjectStoreResource.Kind,\n\t\tName: objectstore.Namespace,\n\t\tUID: types.UID(objectstore.ObjectMeta.UID),\n\t}\n\n\t\/\/ Validate object store config.\n\terr := validateObjectStoreSpec(objectstore.Spec)\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to validate object store config\")\n\t\treturn\n\t}\n\n\t\/\/ Create the headless service.\n\tlogger.Infof(\"Creating Minio headless service %s in namespace %s.\", objectstore.Name, objectstore.Namespace)\n\t_, err = c.makeMinioHeadlessService(objectstore.Name, objectstore.Namespace, objectstore.Spec, ownerRef)\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to create minio headless service: %v\", err)\n\t\treturn\n\t}\n\tlogger.Infof(\"Finished creating Minio headless service %s in namespace %s.\", objectstore.Name, objectstore.Namespace)\n\n\t\/\/ Create the stateful set.\n\tlogger.Infof(\"Creating Minio stateful set %s.\", objectstore.Name)\n\t_, err = c.makeMinioStatefulSet(objectstore.Name, objectstore.Namespace, objectstore.Spec, ownerRef)\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to create minio stateful set: %v\", err)\n\t\treturn\n\t}\n\tlogger.Infof(\"Finished creating Minio stateful set %s in namespace %s.\", objectstore.Name, objectstore.Namespace)\n}\n\nfunc (c *MinioController) onUpdate(oldObj, newObj interface{}) {\n\toldStore := oldObj.(*miniov1alpha1.ObjectStore).DeepCopy()\n\tnewStore := newObj.(*miniov1alpha1.ObjectStore).DeepCopy()\n\n\t_ = oldStore\n\t_ = newStore\n\n\tlogger.Infof(\"Received update on object store %s in namespace %s. This is currently unsupported.\", oldStore.Name, oldStore.Namespace)\n}\n\nfunc (c *MinioController) onDelete(obj interface{}) {\n\tobjectstore := obj.(*miniov1alpha1.ObjectStore).DeepCopy()\n\tlogger.Infof(\"Delete Minio object store %s\", objectstore.Name)\n\n\t\/\/ Cleanup is handled by the owner references set in 'onAdd' and the k8s garbage collector.\n}\n<|endoftext|>"} {"text":"\/*\nCopyright 2018, 2019 the Velero contributors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage restic\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/sirupsen\/logrus\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/labels\"\n\t\"k8s.io\/client-go\/tools\/cache\"\n\n\tvelerov1api \"github.com\/heptio\/velero\/pkg\/apis\/velero\/v1\"\n\tvelerov1client \"github.com\/heptio\/velero\/pkg\/generated\/clientset\/versioned\/typed\/velero\/v1\"\n\tvelerov1informers \"github.com\/heptio\/velero\/pkg\/generated\/informers\/externalversions\/velero\/v1\"\n\tvelerov1listers \"github.com\/heptio\/velero\/pkg\/generated\/listers\/velero\/v1\"\n)\n\n\/\/ repositoryEnsurer ensures that Velero restic repositories are created and ready.\ntype repositoryEnsurer struct {\n\tlog logrus.FieldLogger\n\trepoLister velerov1listers.ResticRepositoryLister\n\trepoClient velerov1client.ResticRepositoriesGetter\n\n\treadyChansLock sync.Mutex\n\treadyChans map[string]chan *velerov1api.ResticRepository\n\n\t\/\/ repoLocksMu synchronizes reads\/writes to the repoLocks map itself\n\t\/\/ since maps are not threadsafe.\n\trepoLocksMu sync.Mutex\n\trepoLocks map[repoKey]*sync.Mutex\n}\n\ntype repoKey struct {\n\tvolumeNamespace string\n\tbackupLocation string\n}\n\nfunc newRepositoryEnsurer(repoInformer velerov1informers.ResticRepositoryInformer, repoClient velerov1client.ResticRepositoriesGetter, log logrus.FieldLogger) *repositoryEnsurer {\n\tr := &repositoryEnsurer{\n\t\tlog: log,\n\t\trepoLister: repoInformer.Lister(),\n\t\trepoClient: repoClient,\n\t\treadyChans: make(map[string]chan *velerov1api.ResticRepository),\n\t\trepoLocks: make(map[repoKey]*sync.Mutex),\n\t}\n\n\trepoInformer.Informer().AddEventHandler(\n\t\tcache.ResourceEventHandlerFuncs{\n\t\t\tUpdateFunc: func(old, upd interface{}) {\n\t\t\t\toldObj := old.(*velerov1api.ResticRepository)\n\t\t\t\tnewObj := upd.(*velerov1api.ResticRepository)\n\n\t\t\t\t\/\/ we're only interested in phase-changing updates\n\t\t\t\tif oldObj.Status.Phase == newObj.Status.Phase {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t\/\/ we're only interested in updates where the updated object is either Ready or NotReady\n\t\t\t\tif newObj.Status.Phase != velerov1api.ResticRepositoryPhaseReady && newObj.Status.Phase != velerov1api.ResticRepositoryPhaseNotReady {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tr.readyChansLock.Lock()\n\t\t\t\tdefer r.readyChansLock.Unlock()\n\n\t\t\t\tkey := repoLabels(newObj.Spec.VolumeNamespace, newObj.Spec.BackupStorageLocation).String()\n\t\t\t\treadyChan, ok := r.readyChans[key]\n\t\t\t\tif !ok {\n\t\t\t\t\tlog.Debugf(\"No ready channel found for repository %s\/%s\", newObj.Namespace, newObj.Name)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\treadyChan <- newObj\n\t\t\t\tdelete(r.readyChans, key)\n\t\t\t},\n\t\t},\n\t)\n\n\treturn r\n}\n\nfunc repoLabels(volumeNamespace, backupLocation string) labels.Set {\n\treturn map[string]string{\n\t\tvelerov1api.ResticVolumeNamespaceLabel: volumeNamespace,\n\t\tvelerov1api.StorageLocationLabel: backupLocation,\n\t}\n}\n\nfunc (r *repositoryEnsurer) EnsureRepo(ctx context.Context, namespace, volumeNamespace, backupLocation string) (*velerov1api.ResticRepository, error) {\n\tlog := r.log.WithField(\"volumeNamespace\", volumeNamespace).WithField(\"backupLocation\", backupLocation)\n\n\t\/\/ It's only safe to have one instance of this method executing concurrently for a\n\t\/\/ given volumeNamespace + backupLocation, so synchronize based on that. It's fine\n\t\/\/ to run concurrently for *different* namespaces\/locations. If you had 2 goroutines\n\t\/\/ running this for the same inputs, both might find no ResticRepository exists, then\n\t\/\/ both would create new ones for the same namespace\/location.\n\t\/\/\n\t\/\/ This issue could probably be avoided if we had a deterministic name for\n\t\/\/ each restic repository, and we just tried to create it, checked for an\n\t\/\/ AlreadyExists err, and then waited for it to be ready. However, there are\n\t\/\/ already repositories in the wild with non-deterministic names (i.e. using\n\t\/\/ GenerateName) which poses a backwards compatibility problem.\n\tlog.Debug(\"Acquiring lock\")\n\n\trepoMu := r.repoLock(volumeNamespace, backupLocation)\n\trepoMu.Lock()\n\tdefer func() {\n\t\trepoMu.Unlock()\n\t\tlog.Debug(\"Released lock\")\n\t}()\n\n\tlog.Debug(\"Acquired lock\")\n\n\tselector := labels.SelectorFromSet(repoLabels(volumeNamespace, backupLocation))\n\n\trepos, err := r.repoLister.ResticRepositories(namespace).List(selector)\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\tif len(repos) > 1 {\n\t\treturn nil, errors.Errorf(\"more than one ResticRepository found for workload namespace %q, backup storage location %q\", volumeNamespace, backupLocation)\n\t}\n\tif len(repos) == 1 {\n\t\tif repos[0].Status.Phase != velerov1api.ResticRepositoryPhaseReady {\n\t\t\treturn nil, errors.Errorf(\"restic repository is not ready: %s\", repos[0].Status.Message)\n\t\t}\n\n\t\tlog.Debug(\"Ready repository found\")\n\t\treturn repos[0], nil\n\t}\n\n\tlog.Debug(\"No repository found, creating one\")\n\n\t\/\/ no repo found: create one and wait for it to be ready\n\trepo := &velerov1api.ResticRepository{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tNamespace: namespace,\n\t\t\tGenerateName: fmt.Sprintf(\"%s-%s-\", volumeNamespace, backupLocation),\n\t\t\tLabels: repoLabels(volumeNamespace, backupLocation),\n\t\t},\n\t\tSpec: velerov1api.ResticRepositorySpec{\n\t\t\tVolumeNamespace: volumeNamespace,\n\t\t\tBackupStorageLocation: backupLocation,\n\t\t\tMaintenanceFrequency: metav1.Duration{Duration: DefaultMaintenanceFrequency},\n\t\t},\n\t}\n\n\treadyChan := r.getReadyChan(selector.String())\n\tdefer close(readyChan)\n\n\tif _, err := r.repoClient.ResticRepositories(namespace).Create(repo); err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to create restic repository resource\")\n\t}\n\n\tselect {\n\t\/\/ repositories should become either ready or not ready quickly if they're\n\t\/\/ newly created.\n\tcase <-time.After(time.Minute):\n\t\treturn nil, errors.New(\"timed out waiting for restic repository to become ready\")\n\tcase <-ctx.Done():\n\t\treturn nil, errors.New(\"timed out waiting for restic repository to become ready\")\n\tcase res := <-readyChan:\n\t\tif res.Status.Phase == velerov1api.ResticRepositoryPhaseNotReady {\n\t\t\treturn nil, errors.Errorf(\"restic repository is not ready: %s\", res.Status.Message)\n\t\t}\n\n\t\treturn res, nil\n\t}\n}\n\nfunc (r *repositoryEnsurer) getReadyChan(name string) chan *velerov1api.ResticRepository {\n\tr.readyChansLock.Lock()\n\tdefer r.readyChansLock.Unlock()\n\n\tr.readyChans[name] = make(chan *velerov1api.ResticRepository)\n\treturn r.readyChans[name]\n}\n\nfunc (r *repositoryEnsurer) repoLock(volumeNamespace, backupLocation string) *sync.Mutex {\n\tr.repoLocksMu.Lock()\n\tdefer r.repoLocksMu.Unlock()\n\n\tkey := repoKey{\n\t\tvolumeNamespace: volumeNamespace,\n\t\tbackupLocation: backupLocation,\n\t}\n\n\tif r.repoLocks[key] == nil {\n\t\tr.repoLocks[key] = new(sync.Mutex)\n\t}\n\n\treturn r.repoLocks[key]\n}\nrepo ensurer: rename readyChans to repoChans\/*\nCopyright 2018, 2019 the Velero contributors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage restic\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/sirupsen\/logrus\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/labels\"\n\t\"k8s.io\/client-go\/tools\/cache\"\n\n\tvelerov1api \"github.com\/heptio\/velero\/pkg\/apis\/velero\/v1\"\n\tvelerov1client \"github.com\/heptio\/velero\/pkg\/generated\/clientset\/versioned\/typed\/velero\/v1\"\n\tvelerov1informers \"github.com\/heptio\/velero\/pkg\/generated\/informers\/externalversions\/velero\/v1\"\n\tvelerov1listers \"github.com\/heptio\/velero\/pkg\/generated\/listers\/velero\/v1\"\n)\n\n\/\/ repositoryEnsurer ensures that Velero restic repositories are created and ready.\ntype repositoryEnsurer struct {\n\tlog logrus.FieldLogger\n\trepoLister velerov1listers.ResticRepositoryLister\n\trepoClient velerov1client.ResticRepositoriesGetter\n\n\trepoChansLock sync.Mutex\n\trepoChans map[string]chan *velerov1api.ResticRepository\n\n\t\/\/ repoLocksMu synchronizes reads\/writes to the repoLocks map itself\n\t\/\/ since maps are not threadsafe.\n\trepoLocksMu sync.Mutex\n\trepoLocks map[repoKey]*sync.Mutex\n}\n\ntype repoKey struct {\n\tvolumeNamespace string\n\tbackupLocation string\n}\n\nfunc newRepositoryEnsurer(repoInformer velerov1informers.ResticRepositoryInformer, repoClient velerov1client.ResticRepositoriesGetter, log logrus.FieldLogger) *repositoryEnsurer {\n\tr := &repositoryEnsurer{\n\t\tlog: log,\n\t\trepoLister: repoInformer.Lister(),\n\t\trepoClient: repoClient,\n\t\trepoChans: make(map[string]chan *velerov1api.ResticRepository),\n\t\trepoLocks: make(map[repoKey]*sync.Mutex),\n\t}\n\n\trepoInformer.Informer().AddEventHandler(\n\t\tcache.ResourceEventHandlerFuncs{\n\t\t\tUpdateFunc: func(old, upd interface{}) {\n\t\t\t\toldObj := old.(*velerov1api.ResticRepository)\n\t\t\t\tnewObj := upd.(*velerov1api.ResticRepository)\n\n\t\t\t\t\/\/ we're only interested in phase-changing updates\n\t\t\t\tif oldObj.Status.Phase == newObj.Status.Phase {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t\/\/ we're only interested in updates where the updated object is either Ready or NotReady\n\t\t\t\tif newObj.Status.Phase != velerov1api.ResticRepositoryPhaseReady && newObj.Status.Phase != velerov1api.ResticRepositoryPhaseNotReady {\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tr.repoChansLock.Lock()\n\t\t\t\tdefer r.repoChansLock.Unlock()\n\n\t\t\t\tkey := repoLabels(newObj.Spec.VolumeNamespace, newObj.Spec.BackupStorageLocation).String()\n\t\t\t\trepoChan, ok := r.repoChans[key]\n\t\t\t\tif !ok {\n\t\t\t\t\tlog.Debugf(\"No ready channel found for repository %s\/%s\", newObj.Namespace, newObj.Name)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\trepoChan <- newObj\n\t\t\t\tdelete(r.repoChans, key)\n\t\t\t},\n\t\t},\n\t)\n\n\treturn r\n}\n\nfunc repoLabels(volumeNamespace, backupLocation string) labels.Set {\n\treturn map[string]string{\n\t\tvelerov1api.ResticVolumeNamespaceLabel: volumeNamespace,\n\t\tvelerov1api.StorageLocationLabel: backupLocation,\n\t}\n}\n\nfunc (r *repositoryEnsurer) EnsureRepo(ctx context.Context, namespace, volumeNamespace, backupLocation string) (*velerov1api.ResticRepository, error) {\n\tlog := r.log.WithField(\"volumeNamespace\", volumeNamespace).WithField(\"backupLocation\", backupLocation)\n\n\t\/\/ It's only safe to have one instance of this method executing concurrently for a\n\t\/\/ given volumeNamespace + backupLocation, so synchronize based on that. It's fine\n\t\/\/ to run concurrently for *different* namespaces\/locations. If you had 2 goroutines\n\t\/\/ running this for the same inputs, both might find no ResticRepository exists, then\n\t\/\/ both would create new ones for the same namespace\/location.\n\t\/\/\n\t\/\/ This issue could probably be avoided if we had a deterministic name for\n\t\/\/ each restic repository, and we just tried to create it, checked for an\n\t\/\/ AlreadyExists err, and then waited for it to be ready. However, there are\n\t\/\/ already repositories in the wild with non-deterministic names (i.e. using\n\t\/\/ GenerateName) which poses a backwards compatibility problem.\n\tlog.Debug(\"Acquiring lock\")\n\n\trepoMu := r.repoLock(volumeNamespace, backupLocation)\n\trepoMu.Lock()\n\tdefer func() {\n\t\trepoMu.Unlock()\n\t\tlog.Debug(\"Released lock\")\n\t}()\n\n\tlog.Debug(\"Acquired lock\")\n\n\tselector := labels.SelectorFromSet(repoLabels(volumeNamespace, backupLocation))\n\n\trepos, err := r.repoLister.ResticRepositories(namespace).List(selector)\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\tif len(repos) > 1 {\n\t\treturn nil, errors.Errorf(\"more than one ResticRepository found for workload namespace %q, backup storage location %q\", volumeNamespace, backupLocation)\n\t}\n\tif len(repos) == 1 {\n\t\tif repos[0].Status.Phase != velerov1api.ResticRepositoryPhaseReady {\n\t\t\treturn nil, errors.Errorf(\"restic repository is not ready: %s\", repos[0].Status.Message)\n\t\t}\n\n\t\tlog.Debug(\"Ready repository found\")\n\t\treturn repos[0], nil\n\t}\n\n\tlog.Debug(\"No repository found, creating one\")\n\n\t\/\/ no repo found: create one and wait for it to be ready\n\trepo := &velerov1api.ResticRepository{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tNamespace: namespace,\n\t\t\tGenerateName: fmt.Sprintf(\"%s-%s-\", volumeNamespace, backupLocation),\n\t\t\tLabels: repoLabels(volumeNamespace, backupLocation),\n\t\t},\n\t\tSpec: velerov1api.ResticRepositorySpec{\n\t\t\tVolumeNamespace: volumeNamespace,\n\t\t\tBackupStorageLocation: backupLocation,\n\t\t\tMaintenanceFrequency: metav1.Duration{Duration: DefaultMaintenanceFrequency},\n\t\t},\n\t}\n\n\trepoChan := r.getrepoChan(selector.String())\n\tdefer close(repoChan)\n\n\tif _, err := r.repoClient.ResticRepositories(namespace).Create(repo); err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to create restic repository resource\")\n\t}\n\n\tselect {\n\t\/\/ repositories should become either ready or not ready quickly if they're\n\t\/\/ newly created.\n\tcase <-time.After(time.Minute):\n\t\treturn nil, errors.New(\"timed out waiting for restic repository to become ready\")\n\tcase <-ctx.Done():\n\t\treturn nil, errors.New(\"timed out waiting for restic repository to become ready\")\n\tcase res := <-repoChan:\n\t\tif res.Status.Phase == velerov1api.ResticRepositoryPhaseNotReady {\n\t\t\treturn nil, errors.Errorf(\"restic repository is not ready: %s\", res.Status.Message)\n\t\t}\n\n\t\treturn res, nil\n\t}\n}\n\nfunc (r *repositoryEnsurer) getrepoChan(name string) chan *velerov1api.ResticRepository {\n\tr.repoChansLock.Lock()\n\tdefer r.repoChansLock.Unlock()\n\n\tr.repoChans[name] = make(chan *velerov1api.ResticRepository)\n\treturn r.repoChans[name]\n}\n\nfunc (r *repositoryEnsurer) repoLock(volumeNamespace, backupLocation string) *sync.Mutex {\n\tr.repoLocksMu.Lock()\n\tdefer r.repoLocksMu.Unlock()\n\n\tkey := repoKey{\n\t\tvolumeNamespace: volumeNamespace,\n\t\tbackupLocation: backupLocation,\n\t}\n\n\tif r.repoLocks[key] == nil {\n\t\tr.repoLocks[key] = new(sync.Mutex)\n\t}\n\n\treturn r.repoLocks[key]\n}\n<|endoftext|>"} {"text":"package hitGox\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"github.com\/valyala\/fasthttp\"\n)\n\ntype (\n\t\/\/ HostersList is a response body about hosters.\n\tHostersList struct {\n\t\tHosters []Hoster `json:\"hosters\"`\n\t}\n\n\t\/\/ Hoster is a single list item about hoster.\n\tHoster struct {\n\t\tUserName\n\t\tUserLogo string `json:\"user_logo\"`\n\t}\n)\n\n\/\/ GetHosters returns channel hosters.\n\/\/\n\/\/ When a user isn’t found, this API returns a regular response but with all values containing null.\n\/\/\n\/\/ Editors can read this API.\nfunc GetHosters(channel string, authToken AuthToken) (HostersList, error) {\n\tvar args fasthttp.Args\n\targs.Add(\"authToken\", authToken.AuthToken)\n\trequestURL := fmt.Sprintf(\"%s\/hosters\/%s?%s\", API, channel, args.String())\n\t_, body, err := fasthttp.Get(nil, requestURL)\n\tif err != nil {\n\t\treturn HostersList{}, err\n\t}\n\tvar obj HostersList\n\tif err = json.NewDecoder(bytes.NewReader(body)).Decode(&obj); err != nil {\n\t\treturn HostersList{}, err\n\t}\n\treturn obj, nil\n}\n✅ Updated getHosterspackage hitGox\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/valyala\/fasthttp\"\n)\n\n\/\/ HostersList contains information about hosted channels.\ntype HostersList struct {\n\tHosters []struct {\n\t\tUserLogo string `json:\"user_logo\"`\n\t\tUserName string `json:\"user_name\"`\n\t} `json:\"hosters\"`\n}\n\n\/\/ GetHosters returns a list of channels hosting channel.\n\/\/\n\/\/ Editors can read this API.\nfunc (account *Account) GetHosters(channel string) (*HostersList, error) {\n\tswitch {\n\tcase account.AuthToken == \"\":\n\t\treturn nil, errors.New(\"authtoken in account can not be empty\")\n\tcase channel == \"\":\n\t\treturn nil, errors.New(\"channel can not be empty\")\n\t}\n\n\tvar args fasthttp.Args\n\targs.Add(\"authToken\", account.AuthToken)\n\n\turl := fmt.Sprint(APIEndpoint, \"\/hosters\/\", channel)\n\tresp, err := get(url, &args)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar obj HostersList\n\tif err = json.NewDecoder(bytes.NewReader(resp)).Decode(&obj); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &obj, nil\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2013 Xing Xing .\n\/\/ All rights reserved.\n\/\/ Use of this source code is governed by a commercial\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"flag\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\"\n\t\"time\"\n\n\t\"github.com\/mikespook\/ghoko\"\n\t\"github.com\/mikespook\/golib\/log\"\n\t\"github.com\/mikespook\/golib\/pid\"\n\t\"github.com\/mikespook\/golib\/signal\"\n)\n\nvar (\n\taddr string\n\tscriptPath string\n\tsecret string\n\ttlsCert string\n\ttlsKey string\n\tpidFile string\n\trootUrl string\n)\n\nfunc init() {\n\tif !flag.Parsed() {\n\t\tflag.StringVar(&addr, \"addr\", \":3080\", \"Address of HTTP service\")\n\t\tflag.StringVar(&scriptPath, \"script\", path.Dir(os.Args[0]), \"Path of lua files\")\n\t\tflag.StringVar(&secret, \"secret\", \"\", \"Secret token\")\n\t\tflag.StringVar(&tlsCert, \"tls-cert\", \"\", \"TLS cert file\")\n\t\tflag.StringVar(&tlsKey, \"tls-key\", \"\", \"TLS key file\")\n\t\tflag.StringVar(&pidFile, \"pid\", \"\", \"PID file\")\n\t\tflag.StringVar(&rootUrl, \"root\", \"\/\", \"Root path of URL\")\n\t\tflag.Parse()\n\t}\n\tlog.InitWithFlag()\n}\n\nfunc main() {\n\tlog.Messagef(\"Starting: webhook=%q script=%q\", ghoko.CallbackUrl(tlsCert, tlsKey, addr, rootUrl), scriptPath)\n\tif pidFile != \"\" {\n\t\tif p, err := pid.New(pidFile); err != nil {\n\t\t\tlog.Error(err)\n\t\t} else {\n\t\t\tdefer func() {\n\t\t\t\tif err := p.Close(); err != nil {\n\t\t\t\t\tlog.Error(err)\n\t\t\t\t}\n\t\t\t}()\n\t\t\tlog.Messagef(\"PID: %d file=%q\", p.Pid, pidFile)\n\t\t}\n\t}\n\tdefer func() {\n\t\tlog.Message(\"Exited!\")\n\t\ttime.Sleep(time.Millisecond * 100)\n\t}()\n\n\t\/\/ Begin\n\tp := path.Clean(scriptPath)\n\tghk := ghoko.New(p, secret, rootUrl)\n\tgo func() {\n\t\tdefer func() {\n\t\t\tif err := signal.Send(os.Getpid(), os.Interrupt); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}()\n\t\tvar err error\n\t\tif tlsCert == \"\" || tlsKey == \"\" {\n\t\t\terr = http.ListenAndServe(addr, ghk)\n\t\t} else {\n\t\t\terr = http.ListenAndServeTLS(addr, tlsCert, tlsKey, ghk)\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t}()\n\t\/\/ End\n\n\tsh := signal.NewHandler()\n\tsh.Bind(os.Interrupt, func() bool { return true })\n\tsh.Loop()\n}\nremoved waiting when exit\/\/ Copyright 2013 Xing Xing .\n\/\/ All rights reserved.\n\/\/ Use of this source code is governed by a commercial\n\/\/ license that can be found in the LICENSE file.\n\npackage main\n\nimport (\n\t\"flag\"\n\t\"net\/http\"\n\t\"os\"\n\t\"path\"\n\n\t\"github.com\/mikespook\/ghoko\"\n\t\"github.com\/mikespook\/golib\/log\"\n\t\"github.com\/mikespook\/golib\/pid\"\n\t\"github.com\/mikespook\/golib\/signal\"\n)\n\nvar (\n\taddr string\n\tscriptPath string\n\tsecret string\n\ttlsCert string\n\ttlsKey string\n\tpidFile string\n\trootUrl string\n)\n\nfunc init() {\n\tif !flag.Parsed() {\n\t\tflag.StringVar(&addr, \"addr\", \":3080\", \"Address of HTTP service\")\n\t\tflag.StringVar(&scriptPath, \"script\", path.Dir(os.Args[0]), \"Path of lua files\")\n\t\tflag.StringVar(&secret, \"secret\", \"\", \"Secret token\")\n\t\tflag.StringVar(&tlsCert, \"tls-cert\", \"\", \"TLS cert file\")\n\t\tflag.StringVar(&tlsKey, \"tls-key\", \"\", \"TLS key file\")\n\t\tflag.StringVar(&pidFile, \"pid\", \"\", \"PID file\")\n\t\tflag.StringVar(&rootUrl, \"root\", \"\/\", \"Root path of URL\")\n\t\tflag.Parse()\n\t}\n\tlog.InitWithFlag()\n}\n\nfunc main() {\n\tlog.Messagef(\"Starting: webhook=%q script=%q\", ghoko.CallbackUrl(tlsCert, tlsKey, addr, rootUrl), scriptPath)\n\tif pidFile != \"\" {\n\t\tif p, err := pid.New(pidFile); err != nil {\n\t\t\tlog.Error(err)\n\t\t} else {\n\t\t\tdefer func() {\n\t\t\t\tif err := p.Close(); err != nil {\n\t\t\t\t\tlog.Error(err)\n\t\t\t\t}\n\t\t\t}()\n\t\t\tlog.Messagef(\"PID: %d file=%q\", p.Pid, pidFile)\n\t\t}\n\t}\n\tdefer func() {\n\t\tlog.Message(\"Exited!\")\n\t}()\n\n\t\/\/ Begin\n\tp := path.Clean(scriptPath)\n\tghk := ghoko.New(p, secret, rootUrl)\n\tgo func() {\n\t\tdefer func() {\n\t\t\tif err := signal.Send(os.Getpid(), os.Interrupt); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}()\n\t\tvar err error\n\t\tif tlsCert == \"\" || tlsKey == \"\" {\n\t\t\terr = http.ListenAndServe(addr, ghk)\n\t\t} else {\n\t\t\terr = http.ListenAndServeTLS(addr, tlsCert, tlsKey, ghk)\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t}\n\t}()\n\t\/\/ End\n\n\tsh := signal.NewHandler()\n\tsh.Bind(os.Interrupt, func() bool { return true })\n\tsh.Loop()\n}\n<|endoftext|>"} {"text":"\/\/ Keybase file system\n\npackage main\n\nimport (\n\t\"flag\"\n\t_ \"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"runtime\/pprof\"\n\n\t\"github.com\/hanwen\/go-fuse\/fuse\/nodefs\"\n\tlibkb \"github.com\/keybase\/go-libkb\"\n\tlibkbfs \"github.com\/keybase\/go-libkbfs-priv\"\n)\n\nfunc GetUI() libkb.UI {\n\tui := &libkbfs.UI{}\n\tui.Configure()\n\treturn ui\n}\n\nvar cpuprofile = flag.String(\"cpuprofile\", \"\", \"write cpu profile to file\")\nvar memprofile = flag.String(\"memprofile\", \"\", \"write memory profile to file\")\n\nfunc main() {\n\tflag.Parse()\n\tif len(flag.Args()) < 1 {\n\t\tlog.Fatal(\"Usage:\\n kbfs MOUNTPOINT\")\n\t}\n\n\tvar cpuProfFile *os.File\n\tif *cpuprofile != \"\" {\n\t\tvar err error\n\t\tcpuProfFile, err = os.Create(*cpuprofile)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tpprof.StartCPUProfile(cpuProfFile)\n\t\tdefer cpuProfFile.Close()\n\t}\n\n\tsigchan := make(chan os.Signal, 1)\n\tsignal.Notify(sigchan, os.Interrupt, os.Kill)\n\tgo func() {\n\t\t_ = <-sigchan\n\t\tif *cpuprofile != \"\" {\n\t\t\tpprof.StopCPUProfile()\n\t\t}\n\n\t\tif *memprofile != \"\" {\n\t\t\tf, err := os.Create(*memprofile)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\tpprof.WriteHeapProfile(f)\n\t\t\tf.Close()\n\t\t}\n\t\tos.Exit(1)\n\t}()\n\n\t\/\/ TODO: make this an option:\n\tlocalUsers := true\n\n\tconfig := libkbfs.NewConfigLocal()\n\n\tlibkb.G.Init()\n\tlibkb.G.ConfigureConfig()\n\tlibkb.G.ConfigureLogging()\n\tlibkb.G.ConfigureCaches()\n\tlibkb.G.ConfigureMerkleClient()\n\tlibkb.G.SetUI(GetUI())\n\n\tif !localUsers {\n\t\tlibkb.G.ConfigureAPI()\n\t\tif ok, err := libkb.G.Session.LoadAndCheck(); !ok || err != nil {\n\t\t\tlog.Fatalf(\"Couldn't load session: %v\\n\", err)\n\t\t}\n\t} else {\n\t\tk := libkbfs.NewKBPKILocal(libkb.UID{1}, []*libkbfs.LocalUser{\n\t\t\t&libkbfs.LocalUser{\"strib\", libkb.UID{1}, []string{\"github:strib\"}},\n\t\t\t&libkbfs.LocalUser{\"max\", libkb.UID{2}, []string{\"twitter:maxtaco\"}},\n\t\t\t&libkbfs.LocalUser{\n\t\t\t\t\"chris\", libkb.UID{3}, []string{\"twitter:malgorithms\"}},\n\t\t})\n\t\tconfig.SetKBPKI(k)\n\t}\n\n\troot := libkbfs.NewFuseRoot(config)\n\n\tserver, _, err := nodefs.MountRoot(flag.Arg(0), root, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"Mount fail: %v\\n\", err)\n\t}\n\n\t\/\/server.SetDebug(true)\n\tserver.Serve()\n}\nkbfsd: add a few more flags to make debugging stuff optional\/\/ Keybase file system\n\npackage main\n\nimport (\n\t\"flag\"\n\t_ \"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"os\/signal\"\n\t\"runtime\/pprof\"\n\n\t\"github.com\/hanwen\/go-fuse\/fuse\/nodefs\"\n\tlibkb \"github.com\/keybase\/go-libkb\"\n\tlibkbfs \"github.com\/keybase\/go-libkbfs-priv\"\n)\n\nfunc GetUI() libkb.UI {\n\tui := &libkbfs.UI{}\n\tui.Configure()\n\treturn ui\n}\n\nvar cpuprofile = flag.String(\"cpuprofile\", \"\", \"write cpu profile to file\")\nvar memprofile = flag.String(\"memprofile\", \"\", \"write memory profile to file\")\nvar local = flag.Bool(\"local\", false,\n\t\"use a fake local user DB instead of Keybase\")\nvar localUser = flag.String(\"localuser\", \"strib\",\n\t\"fake local user (only valid when local=true\")\nvar debug = flag.Bool(\"debug\", false, \"Print FUSE debug messages\")\n\nfunc main() {\n\tflag.Parse()\n\tif len(flag.Args()) < 1 {\n\t\tlog.Fatal(\"Usage:\\n kbfs MOUNTPOINT\")\n\t}\n\n\tvar cpuProfFile *os.File\n\tif *cpuprofile != \"\" {\n\t\tvar err error\n\t\tcpuProfFile, err = os.Create(*cpuprofile)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tpprof.StartCPUProfile(cpuProfFile)\n\t\tdefer cpuProfFile.Close()\n\t}\n\n\tsigchan := make(chan os.Signal, 1)\n\tsignal.Notify(sigchan, os.Interrupt, os.Kill)\n\tgo func() {\n\t\t_ = <-sigchan\n\t\tif *cpuprofile != \"\" {\n\t\t\tpprof.StopCPUProfile()\n\t\t}\n\n\t\tif *memprofile != \"\" {\n\t\t\tf, err := os.Create(*memprofile)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\tpprof.WriteHeapProfile(f)\n\t\t\tf.Close()\n\t\t}\n\t\tos.Exit(1)\n\t}()\n\n\tconfig := libkbfs.NewConfigLocal()\n\n\tlibkb.G.Init()\n\tlibkb.G.ConfigureConfig()\n\tlibkb.G.ConfigureLogging()\n\tlibkb.G.ConfigureCaches()\n\tlibkb.G.ConfigureMerkleClient()\n\tlibkb.G.SetUI(GetUI())\n\n\tif !*local {\n\t\tlibkb.G.ConfigureAPI()\n\t\tif ok, err := libkb.G.Session.LoadAndCheck(); !ok || err != nil {\n\t\t\tlog.Fatalf(\"Couldn't load session: %v\\n\", err)\n\t\t}\n\t} else {\n\t\tvar localUid libkb.UID\n\t\tswitch {\n\t\tcase *localUser == \"strib\":\n\t\t\tlocalUid = libkb.UID{1}\n\t\tcase *localUser == \"max\":\n\t\t\tlocalUid = libkb.UID{2}\n\t\tcase *localUser == \"chris\":\n\t\t\tlocalUid = libkb.UID{3}\n\t\t}\n\t\tk := libkbfs.NewKBPKILocal(localUid, []*libkbfs.LocalUser{\n\t\t\t&libkbfs.LocalUser{\"strib\", libkb.UID{1}, []string{\"github:strib\"}},\n\t\t\t&libkbfs.LocalUser{\"max\", libkb.UID{2}, []string{\"twitter:maxtaco\"}},\n\t\t\t&libkbfs.LocalUser{\n\t\t\t\t\"chris\", libkb.UID{3}, []string{\"twitter:malgorithms\"}},\n\t\t})\n\t\tconfig.SetKBPKI(k)\n\t}\n\n\troot := libkbfs.NewFuseRoot(config)\n\n\tserver, _, err := nodefs.MountRoot(flag.Arg(0), root, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"Mount fail: %v\\n\", err)\n\t}\n\n\tif *debug {\n\t\tserver.SetDebug(true)\n\t}\n\tserver.Serve()\n}\n<|endoftext|>"} {"text":"\/*\n Copyright (c) 2014, Percona LLC and\/or its affiliates. All rights reserved.\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with this program. If not, see \n*\/\n\npackage main\n\nimport (\n\t\"fmt\"\n\t_ \"github.com\/go-sql-driver\/mysql\"\n\t\"github.com\/percona\/cloud-protocol\/proto\"\n\t\"github.com\/percona\/percona-agent\/agent\"\n\t\"github.com\/percona\/percona-agent\/mysql\"\n\t\"github.com\/percona\/percona-agent\/pct\"\n\t\"log\"\n\t\"net\"\n\t\"net\/url\"\n\t\"os\"\n\t\"regexp\"\n\t\"time\"\n)\n\ntype Flags map[string]bool\n\nvar portNumberRe = regexp.MustCompile(`\\.\\d+$`)\n\ntype Installer struct {\n\tterm *Terminal\n\tbasedir string\n\tapi pct.APIConnector\n\tagentConfig *agent.Config\n\tflags Flags\n\t\/\/ --\n\thostname string\n}\n\nfunc NewInstaller(term *Terminal, basedir string, api pct.APIConnector, agentConfig *agent.Config, flags Flags) *Installer {\n\tif agentConfig.ApiHostname == \"\" {\n\t\tagentConfig.ApiHostname = agent.DEFAULT_API_HOSTNAME\n\t}\n\thostname, _ := os.Hostname()\n\tinstaller := &Installer{\n\t\tterm: term,\n\t\tbasedir: basedir,\n\t\tapi: api,\n\t\tagentConfig: agentConfig,\n\t\tflags: flags,\n\t\t\/\/ --\n\t\thostname: hostname,\n\t}\n\treturn installer\n}\n\nfunc (i *Installer) Run() error {\n\n\t\/**\n\t * Check for pt-agent, upgrade if found.\n\t *\/\n\n\tvar ptagentDSN *mysql.DSN\n\tptagentUpgrade := false\n\tptagentConf := \"\/root\/.pt-agent.conf\"\n\tif pct.FileExists(ptagentConf) {\n\t\tfmt.Println(\"Found pt-agent, upgrading and removing because it is no longer supported...\")\n\t\tptagentUpgrade = true\n\n\t\t\/\/ Stop pt-agent\n\t\tif err := StopPTAgent(); err != nil {\n\t\t\tfmt.Printf(\"Error stopping pt-agent: %s\\n\\n\", err)\n\t\t\tfmt.Println(\"WARNING: pt-agent must be stopped before installing percona-agent. \" +\n\t\t\t\t\"Please verify that pt-agent is not running and has been removed from cron. \" +\n\t\t\t\t\"Enter 'Y' to confirm and continue installing percona-agent.\")\n\t\t\tok, err := i.term.PromptBool(\"pt-agent has stopped?\", \"N\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !ok {\n\t\t\t\treturn fmt.Errorf(\"Failed to stop pt-agent\")\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Get its settings (API key, UUID, etc.).\n\t\tagent, dsn, err := GetPTAgentSettings(ptagentConf)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error upgrading pt-agent: %s\", err)\n\t\t}\n\t\tif agent.ApiKey != \"\" {\n\t\t\ti.agentConfig.ApiKey = agent.ApiKey\n\t\t}\n\t\tif agent.AgentUuid != \"\" {\n\t\t\ti.agentConfig.AgentUuid = agent.AgentUuid\n\t\t\tfmt.Printf(\"Upgrading pt-agent %s...\\n\", agent.AgentUuid)\n\t\t}\n\t\tptagentDSN = dsn\n\t}\n\n\t\/**\n\t * Get the API key.\n\t *\/\n\n\tfmt.Printf(\"API host: %s\\n\", i.agentConfig.ApiHostname)\n\n\tfor i.agentConfig.ApiKey == \"\" {\n\t\tapiKey, err := i.term.PromptString(\"API key\", \"\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif apiKey == \"\" {\n\t\t\tfmt.Println(\"API key is required, please try again.\")\n\t\t\tcontinue\n\t\t}\n\t\ti.agentConfig.ApiKey = apiKey\n\t\tbreak\n\t}\n\n\t\/**\n\t * Verify the API key by pinging the API.\n\t *\/\n\nVERIFY_API_KEY:\n\tfor {\n\t\tstartTime := time.Now()\n\t\tfmt.Printf(\"Verifying API key %s...\\n\", i.agentConfig.ApiKey)\n\t\tcode, err := pct.Ping(i.agentConfig.ApiHostname, i.agentConfig.ApiKey)\n\t\telapsedTime := time.Since(startTime)\n\t\telapsedTimeInSeconds := elapsedTime \/ time.Second\n\n\t\ttimeout := false\n\t\tif urlErr, ok := err.(*url.Error); ok {\n\t\t\tif netOpErr, ok := urlErr.Err.(*net.OpError); ok && netOpErr.Timeout() {\n\t\t\t\ttimeout = true\n\t\t\t}\n\t\t}\n\t\tif i.flags[\"debug\"] {\n\t\t\tlog.Printf(\"code=%d\\n\", code)\n\t\t\tlog.Printf(\"err=%s\\n\", err)\n\t\t}\n\t\tok := false\n\t\tif timeout {\n\t\t\tfmt.Printf(\n\t\t\t\t\"Error: API connection timeout (%ds): %s\\n\"+\n\t\t\t\t\t\"Before you try again, please check your connection and DNS configuration.\\n\",\n\t\t\t\telapsedTimeInSeconds,\n\t\t\t\terr,\n\t\t\t)\n\t\t} else if err != nil {\n\t\t\tfmt.Printf(\"Error: %s\\n\", err)\n\t\t} else if code >= 500 {\n\t\t\tfmt.Printf(\"Sorry, there's an API problem (status code %d). \"+\n\t\t\t\t\"Please try to install again. If the problem continues, contact Percona.\\n\",\n\t\t\t\tcode)\n\t\t} else if code == 401 {\n\t\t\treturn fmt.Errorf(\"Access denied. Check the API key and try again.\")\n\t\t} else if code >= 300 {\n\t\t\tfmt.Printf(\"Sorry, there's an installer problem (status code %d). \"+\n\t\t\t\t\"Please try to install again. If the problem continues, contact Percona.\\n\",\n\t\t\t\tcode)\n\t\t} else if code != 200 {\n\t\t\tfmt.Printf(\"Sorry, there's an installer problem (status code %d). \"+\n\t\t\t\t\"Please try to install again. If the problem continues, contact Percona.\\n\",\n\t\t\t\tcode)\n\t\t} else {\n\t\t\tok = true\n\t\t}\n\n\t\tif !ok {\n\t\t\tagain, err := i.term.PromptBool(\"Try again?\", \"Y\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !again {\n\t\t\t\treturn fmt.Errorf(\"Failed to verify API key\")\n\t\t\t}\n\t\t\tcontinue VERIFY_API_KEY\n\t\t}\n\n\t\tfmt.Printf(\"API key %s is OK\\n\", i.agentConfig.ApiKey)\n\n\t\tif elapsedTimeInSeconds >= 0 {\n\t\t\tfmt.Printf(\n\t\t\t\t\"WARNING: We have detected that request to api took %d second(-s) while usually it shouldn't take more than 1s.\\n\"+\n\t\t\t\t\t\"This might be due to connection problems or slow DNS resolution.\\n\"+\n\t\t\t\t\t\"Before you continue please check your connection and DNS configuration as this might impact performance of percona-agent.\\n\"+\n\t\t\t\t\t\"If you are using CentOS or Fedora 19+ in a vagrant box then you might be interested in this bug report:\\n\"+\n\t\t\t\t\t\"https:\/\/github.com\/mitchellh\/vagrant\/issues\/1172\\n\",\n\t\t\t\telapsedTimeInSeconds,\n\t\t\t)\n\t\t\tproceed, err := i.term.PromptBool(\"Continue anyway?\", \"Y\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !proceed {\n\t\t\t\treturn fmt.Errorf(\"Failed because of slow connection\")\n\t\t\t}\n\t\t}\n\n\t\tbreak\n\t}\n\n\tvar si *proto.ServerInstance\n\tvar mi *proto.MySQLInstance\n\n\t\/**\n\t * Create new service instances.\n\t *\/\n\n\tvar err error\n\n\tif i.flags[\"create-server-instance\"] {\n\t\tsi, err = i.createServerInstance()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Printf(\"Created server instance: hostname=%s id=%d\\n\", si.Hostname, si.Id)\n\t} else {\n\t\tfmt.Println(\"Not creating server instance (-create-server-instance=false)\")\n\t}\n\n\tif i.flags[\"create-mysql-instance\"] {\n\t\t\/\/ Create MySQL user for agent, or using existing one, then verify MySQL connection.\n\t\tagentDSN, err := i.doMySQL(ptagentDSN)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t\/\/ Create MySQL instance in API.\n\t\tmi, err = i.createMySQLInstance(agentDSN)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Printf(\"Created MySQL instance: dsn=%s hostname=%s id=%d\\n\", mi.DSN, mi.Hostname, si.Id)\n\t} else {\n\t\tfmt.Println(\"Not creating MySQL instance (-create-mysql-instance=false)\")\n\t}\n\n\tif err := i.writeInstances(si, mi); err != nil {\n\t\treturn fmt.Errorf(\"Created agent but failed to write service instances: %s\", err)\n\t}\n\n\t\/**\n\t * Get default configs for all services.\n\t *\/\n\n\tconfigs := []proto.AgentConfig{}\n\n\tif i.flags[\"start-services\"] {\n\t\t\/\/ Server metrics monitor\n\t\tconfig, err := i.getMmServerConfig(si)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tfmt.Println(\"WARNING: cannot start server metrics monitor\")\n\t\t} else {\n\t\t\tconfigs = append(configs, *config)\n\t\t}\n\n\t\tif i.flags[\"start-mysql-services\"] {\n\t\t\t\/\/ MySQL metrics tracker\n\t\t\tconfig, err = i.getMmMySQLConfig(mi)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\tfmt.Println(\"WARNING: cannot start MySQL metrics monitor\")\n\t\t\t} else {\n\t\t\t\tconfigs = append(configs, *config)\n\t\t\t}\n\n\t\t\t\/\/ MySQL config tracker\n\t\t\tconfig, err = i.getSysconfigMySQLConfig(mi)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\tfmt.Println(\"WARNING: cannot start MySQL configuration monitor\")\n\t\t\t} else {\n\t\t\t\tconfigs = append(configs, *config)\n\t\t\t}\n\n\t\t\t\/\/ QAN\n\t\t\t\/\/ MySQL is local if the server hostname == MySQL hostname without port number.\n\t\t\tif i.hostname == portNumberRe.ReplaceAllLiteralString(mi.Hostname, \"\") {\n\t\t\t\tif i.flags[\"debug\"] {\n\t\t\t\t\tlog.Printf(\"MySQL is local\")\n\t\t\t\t}\n\t\t\t\tconfig, err := i.getQanConfig(mi)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Println(err)\n\t\t\t\t\tfmt.Println(\"WARNING: cannot start Query Analytics\")\n\t\t\t\t} else {\n\t\t\t\t\tconfigs = append(configs, *config)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Println(\"Not starting MySQL services (-start-mysql-services=false)\")\n\t\t}\n\t} else {\n\t\tfmt.Println(\"Not starting default services (-start-services=false)\")\n\t}\n\n\t\/**\n\t * Create agent with initial service configs.\n\t *\/\n\n\tif ptagentUpgrade {\n\t\tagent, err := i.updateAgent(i.agentConfig.AgentUuid)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Println(\"pt-agent upgraded to percona-agent\")\n\t\tif err := i.writeConfigs(agent, configs); err != nil {\n\t\t\treturn fmt.Errorf(\"Upgraded pt-agent but failed to write percona-agent configs: %s\", err)\n\t\t}\n\t} else if i.flags[\"create-agent\"] {\n\t\tagent, err := i.createAgent(configs)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Printf(\"Created agent: uuid=%s\\n\", agent.Uuid)\n\n\t\tif err := i.writeConfigs(agent, configs); err != nil {\n\t\t\treturn fmt.Errorf(\"Created agent but failed to write configs: %s\", err)\n\t\t}\n\t} else {\n\t\tfmt.Println(\"Not creating agent (-create-agent=false)\")\n\t}\n\n\t\/**\n\t * Remove pt-agent if upgrading.\n\t *\/\n\n\tif ptagentUpgrade {\n\t\tRemovePTAgent(ptagentConf)\n\t\tfmt.Println(\"pt-agent removed\")\n\t}\n\n\treturn nil \/\/ success\n}\nPCT-617: hotfix, user should be warn if request took at least 5s, not 0s\/*\n Copyright (c) 2014, Percona LLC and\/or its affiliates. All rights reserved.\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with this program. If not, see \n*\/\n\npackage main\n\nimport (\n\t\"fmt\"\n\t_ \"github.com\/go-sql-driver\/mysql\"\n\t\"github.com\/percona\/cloud-protocol\/proto\"\n\t\"github.com\/percona\/percona-agent\/agent\"\n\t\"github.com\/percona\/percona-agent\/mysql\"\n\t\"github.com\/percona\/percona-agent\/pct\"\n\t\"log\"\n\t\"net\"\n\t\"net\/url\"\n\t\"os\"\n\t\"regexp\"\n\t\"time\"\n)\n\ntype Flags map[string]bool\n\nvar portNumberRe = regexp.MustCompile(`\\.\\d+$`)\n\ntype Installer struct {\n\tterm *Terminal\n\tbasedir string\n\tapi pct.APIConnector\n\tagentConfig *agent.Config\n\tflags Flags\n\t\/\/ --\n\thostname string\n}\n\nfunc NewInstaller(term *Terminal, basedir string, api pct.APIConnector, agentConfig *agent.Config, flags Flags) *Installer {\n\tif agentConfig.ApiHostname == \"\" {\n\t\tagentConfig.ApiHostname = agent.DEFAULT_API_HOSTNAME\n\t}\n\thostname, _ := os.Hostname()\n\tinstaller := &Installer{\n\t\tterm: term,\n\t\tbasedir: basedir,\n\t\tapi: api,\n\t\tagentConfig: agentConfig,\n\t\tflags: flags,\n\t\t\/\/ --\n\t\thostname: hostname,\n\t}\n\treturn installer\n}\n\nfunc (i *Installer) Run() error {\n\n\t\/**\n\t * Check for pt-agent, upgrade if found.\n\t *\/\n\n\tvar ptagentDSN *mysql.DSN\n\tptagentUpgrade := false\n\tptagentConf := \"\/root\/.pt-agent.conf\"\n\tif pct.FileExists(ptagentConf) {\n\t\tfmt.Println(\"Found pt-agent, upgrading and removing because it is no longer supported...\")\n\t\tptagentUpgrade = true\n\n\t\t\/\/ Stop pt-agent\n\t\tif err := StopPTAgent(); err != nil {\n\t\t\tfmt.Printf(\"Error stopping pt-agent: %s\\n\\n\", err)\n\t\t\tfmt.Println(\"WARNING: pt-agent must be stopped before installing percona-agent. \" +\n\t\t\t\t\"Please verify that pt-agent is not running and has been removed from cron. \" +\n\t\t\t\t\"Enter 'Y' to confirm and continue installing percona-agent.\")\n\t\t\tok, err := i.term.PromptBool(\"pt-agent has stopped?\", \"N\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !ok {\n\t\t\t\treturn fmt.Errorf(\"Failed to stop pt-agent\")\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Get its settings (API key, UUID, etc.).\n\t\tagent, dsn, err := GetPTAgentSettings(ptagentConf)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error upgrading pt-agent: %s\", err)\n\t\t}\n\t\tif agent.ApiKey != \"\" {\n\t\t\ti.agentConfig.ApiKey = agent.ApiKey\n\t\t}\n\t\tif agent.AgentUuid != \"\" {\n\t\t\ti.agentConfig.AgentUuid = agent.AgentUuid\n\t\t\tfmt.Printf(\"Upgrading pt-agent %s...\\n\", agent.AgentUuid)\n\t\t}\n\t\tptagentDSN = dsn\n\t}\n\n\t\/**\n\t * Get the API key.\n\t *\/\n\n\tfmt.Printf(\"API host: %s\\n\", i.agentConfig.ApiHostname)\n\n\tfor i.agentConfig.ApiKey == \"\" {\n\t\tapiKey, err := i.term.PromptString(\"API key\", \"\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif apiKey == \"\" {\n\t\t\tfmt.Println(\"API key is required, please try again.\")\n\t\t\tcontinue\n\t\t}\n\t\ti.agentConfig.ApiKey = apiKey\n\t\tbreak\n\t}\n\n\t\/**\n\t * Verify the API key by pinging the API.\n\t *\/\n\nVERIFY_API_KEY:\n\tfor {\n\t\tstartTime := time.Now()\n\t\tfmt.Printf(\"Verifying API key %s...\\n\", i.agentConfig.ApiKey)\n\t\tcode, err := pct.Ping(i.agentConfig.ApiHostname, i.agentConfig.ApiKey)\n\t\telapsedTime := time.Since(startTime)\n\t\telapsedTimeInSeconds := elapsedTime \/ time.Second\n\n\t\ttimeout := false\n\t\tif urlErr, ok := err.(*url.Error); ok {\n\t\t\tif netOpErr, ok := urlErr.Err.(*net.OpError); ok && netOpErr.Timeout() {\n\t\t\t\ttimeout = true\n\t\t\t}\n\t\t}\n\t\tif i.flags[\"debug\"] {\n\t\t\tlog.Printf(\"code=%d\\n\", code)\n\t\t\tlog.Printf(\"err=%s\\n\", err)\n\t\t}\n\t\tok := false\n\t\tif timeout {\n\t\t\tfmt.Printf(\n\t\t\t\t\"Error: API connection timeout (%ds): %s\\n\"+\n\t\t\t\t\t\"Before you try again, please check your connection and DNS configuration.\\n\",\n\t\t\t\telapsedTimeInSeconds,\n\t\t\t\terr,\n\t\t\t)\n\t\t} else if err != nil {\n\t\t\tfmt.Printf(\"Error: %s\\n\", err)\n\t\t} else if code >= 500 {\n\t\t\tfmt.Printf(\"Sorry, there's an API problem (status code %d). \"+\n\t\t\t\t\"Please try to install again. If the problem continues, contact Percona.\\n\",\n\t\t\t\tcode)\n\t\t} else if code == 401 {\n\t\t\treturn fmt.Errorf(\"Access denied. Check the API key and try again.\")\n\t\t} else if code >= 300 {\n\t\t\tfmt.Printf(\"Sorry, there's an installer problem (status code %d). \"+\n\t\t\t\t\"Please try to install again. If the problem continues, contact Percona.\\n\",\n\t\t\t\tcode)\n\t\t} else if code != 200 {\n\t\t\tfmt.Printf(\"Sorry, there's an installer problem (status code %d). \"+\n\t\t\t\t\"Please try to install again. If the problem continues, contact Percona.\\n\",\n\t\t\t\tcode)\n\t\t} else {\n\t\t\tok = true\n\t\t}\n\n\t\tif !ok {\n\t\t\tagain, err := i.term.PromptBool(\"Try again?\", \"Y\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !again {\n\t\t\t\treturn fmt.Errorf(\"Failed to verify API key\")\n\t\t\t}\n\t\t\tcontinue VERIFY_API_KEY\n\t\t}\n\n\t\tfmt.Printf(\"API key %s is OK\\n\", i.agentConfig.ApiKey)\n\n\t\t\/\/ https:\/\/jira.percona.com\/browse\/PCT-617\n\t\t\/\/ Warn user if request took at least 5s\n\t\tif elapsedTimeInSeconds >= 5 {\n\t\t\tfmt.Printf(\n\t\t\t\t\"WARNING: We have detected that request to api took %d second(-s) while usually it shouldn't take more than 1s.\\n\"+\n\t\t\t\t\t\"This might be due to connection problems or slow DNS resolution.\\n\"+\n\t\t\t\t\t\"Before you continue please check your connection and DNS configuration as this might impact performance of percona-agent.\\n\"+\n\t\t\t\t\t\"If you are using CentOS or Fedora 19+ in a vagrant box then you might be interested in this bug report:\\n\"+\n\t\t\t\t\t\"https:\/\/github.com\/mitchellh\/vagrant\/issues\/1172\\n\",\n\t\t\t\telapsedTimeInSeconds,\n\t\t\t)\n\t\t\tproceed, err := i.term.PromptBool(\"Continue anyway?\", \"Y\")\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !proceed {\n\t\t\t\treturn fmt.Errorf(\"Failed because of slow connection\")\n\t\t\t}\n\t\t}\n\n\t\tbreak\n\t}\n\n\tvar si *proto.ServerInstance\n\tvar mi *proto.MySQLInstance\n\n\t\/**\n\t * Create new service instances.\n\t *\/\n\n\tvar err error\n\n\tif i.flags[\"create-server-instance\"] {\n\t\tsi, err = i.createServerInstance()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Printf(\"Created server instance: hostname=%s id=%d\\n\", si.Hostname, si.Id)\n\t} else {\n\t\tfmt.Println(\"Not creating server instance (-create-server-instance=false)\")\n\t}\n\n\tif i.flags[\"create-mysql-instance\"] {\n\t\t\/\/ Create MySQL user for agent, or using existing one, then verify MySQL connection.\n\t\tagentDSN, err := i.doMySQL(ptagentDSN)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t\/\/ Create MySQL instance in API.\n\t\tmi, err = i.createMySQLInstance(agentDSN)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Printf(\"Created MySQL instance: dsn=%s hostname=%s id=%d\\n\", mi.DSN, mi.Hostname, si.Id)\n\t} else {\n\t\tfmt.Println(\"Not creating MySQL instance (-create-mysql-instance=false)\")\n\t}\n\n\tif err := i.writeInstances(si, mi); err != nil {\n\t\treturn fmt.Errorf(\"Created agent but failed to write service instances: %s\", err)\n\t}\n\n\t\/**\n\t * Get default configs for all services.\n\t *\/\n\n\tconfigs := []proto.AgentConfig{}\n\n\tif i.flags[\"start-services\"] {\n\t\t\/\/ Server metrics monitor\n\t\tconfig, err := i.getMmServerConfig(si)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\tfmt.Println(\"WARNING: cannot start server metrics monitor\")\n\t\t} else {\n\t\t\tconfigs = append(configs, *config)\n\t\t}\n\n\t\tif i.flags[\"start-mysql-services\"] {\n\t\t\t\/\/ MySQL metrics tracker\n\t\t\tconfig, err = i.getMmMySQLConfig(mi)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\tfmt.Println(\"WARNING: cannot start MySQL metrics monitor\")\n\t\t\t} else {\n\t\t\t\tconfigs = append(configs, *config)\n\t\t\t}\n\n\t\t\t\/\/ MySQL config tracker\n\t\t\tconfig, err = i.getSysconfigMySQLConfig(mi)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t\tfmt.Println(\"WARNING: cannot start MySQL configuration monitor\")\n\t\t\t} else {\n\t\t\t\tconfigs = append(configs, *config)\n\t\t\t}\n\n\t\t\t\/\/ QAN\n\t\t\t\/\/ MySQL is local if the server hostname == MySQL hostname without port number.\n\t\t\tif i.hostname == portNumberRe.ReplaceAllLiteralString(mi.Hostname, \"\") {\n\t\t\t\tif i.flags[\"debug\"] {\n\t\t\t\t\tlog.Printf(\"MySQL is local\")\n\t\t\t\t}\n\t\t\t\tconfig, err := i.getQanConfig(mi)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Println(err)\n\t\t\t\t\tfmt.Println(\"WARNING: cannot start Query Analytics\")\n\t\t\t\t} else {\n\t\t\t\t\tconfigs = append(configs, *config)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tfmt.Println(\"Not starting MySQL services (-start-mysql-services=false)\")\n\t\t}\n\t} else {\n\t\tfmt.Println(\"Not starting default services (-start-services=false)\")\n\t}\n\n\t\/**\n\t * Create agent with initial service configs.\n\t *\/\n\n\tif ptagentUpgrade {\n\t\tagent, err := i.updateAgent(i.agentConfig.AgentUuid)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Println(\"pt-agent upgraded to percona-agent\")\n\t\tif err := i.writeConfigs(agent, configs); err != nil {\n\t\t\treturn fmt.Errorf(\"Upgraded pt-agent but failed to write percona-agent configs: %s\", err)\n\t\t}\n\t} else if i.flags[\"create-agent\"] {\n\t\tagent, err := i.createAgent(configs)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Printf(\"Created agent: uuid=%s\\n\", agent.Uuid)\n\n\t\tif err := i.writeConfigs(agent, configs); err != nil {\n\t\t\treturn fmt.Errorf(\"Created agent but failed to write configs: %s\", err)\n\t\t}\n\t} else {\n\t\tfmt.Println(\"Not creating agent (-create-agent=false)\")\n\t}\n\n\t\/**\n\t * Remove pt-agent if upgrading.\n\t *\/\n\n\tif ptagentUpgrade {\n\t\tRemovePTAgent(ptagentConf)\n\t\tfmt.Println(\"pt-agent removed\")\n\t}\n\n\treturn nil \/\/ success\n}\n<|endoftext|>"} {"text":"package k8s\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n\t\"reflect\"\n\n\t\"github.com\/scaleway\/scaleway-cli\/internal\/core\"\n\tk8s \"github.com\/scaleway\/scaleway-sdk-go\/api\/k8s\/v1\"\n\t\"github.com\/scaleway\/scaleway-sdk-go\/scw\"\n)\n\nconst (\n\tkubeLocationDir = \".kube\"\n\tkubeconfigAPIVersion = \"v1\"\n\tkubeconfigKind = \"Config\"\n)\n\ntype k8sKubeconfigInstallRequest struct {\n\tClusterID string\n\tRegion scw.Region\n\tKeepCurentContext bool\n}\n\nfunc k8sKubeconfigInstallCommand() *core.Command {\n\treturn &core.Command{\n\t\tShort: `Install a kubeconfig`,\n\t\tLong: `Retrieve the kubeconfig for a specified cluster and write it on disk. \nIt will merge the new kubeconfig in the file pointed by the KUBECONFIG variable. If empty it will default to $HOME\/.kube\/config.`,\n\t\tNamespace: \"k8s\",\n\t\tVerb: \"install\",\n\t\tResource: \"kubeconfig\",\n\t\tArgsType: reflect.TypeOf(k8sKubeconfigInstallRequest{}),\n\t\tArgSpecs: core.ArgSpecs{\n\t\t\t{\n\t\t\t\tName: \"cluster-id\",\n\t\t\t\tShort: \"Cluster ID from which to retrieve the kubeconfig\",\n\t\t\t\tRequired: true,\n\t\t\t\tPositional: true,\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"keep-current-context\",\n\t\t\t\tShort: \"Whether or not to keep the current kubeconfig context unmodified\",\n\t\t\t},\n\t\t\tcore.RegionArgSpec(),\n\t\t},\n\t\tRun: k8sKubeconfigInstallRun,\n\t\tExamples: []*core.Example{\n\t\t\t{\n\t\t\t\tShort: \"Install the kubeconfig for a given cluster and using the new context\",\n\t\t\t\tRequest: `{\"cluster_id\": \"11111111-1111-1111-1111-111111111111\"}`,\n\t\t\t},\n\t\t},\n\t\tSeeAlsos: []*core.SeeAlso{\n\t\t\t{\n\t\t\t\tCommand: \"scw k8s kubeconfig uninstall\",\n\t\t\t\tShort: \"Uninstall a kubeconfig\",\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc k8sKubeconfigInstallRun(ctx context.Context, argsI interface{}) (i interface{}, e error) {\n\trequest := argsI.(*k8sKubeconfigInstallRequest)\n\n\tkubeconfigRequest := &k8s.GetClusterKubeConfigRequest{\n\t\tRegion: request.Region,\n\t\tClusterID: request.ClusterID,\n\t}\n\n\tclient := core.ExtractClient(ctx)\n\tapiK8s := k8s.NewAPI(client)\n\n\t\/\/ get the wanted kubeconfig\n\tkubeconfig, err := apiK8s.GetClusterKubeConfig(kubeconfigRequest)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkubeconfigPath, err := getKubeconfigPath(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ create the kubeconfig file if it does not exist\n\tif _, err := os.Stat(kubeconfigPath); os.IsNotExist(err) {\n\t\t\/\/ make sure the directory exists\n\t\terr = os.MkdirAll(path.Dir(kubeconfigPath), 0755)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t\/\/ create the file\n\t\tf, err := os.OpenFile(kubeconfigPath, os.O_CREATE, 0644)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tf.Close()\n\t}\n\n\texistingKubeconfig, err := openAndUnmarshalKubeconfig(kubeconfigPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ loop through all clusters and insert the wanted one if it does not exist\n\tclusterFoundInExistingKubeconfig := false\n\tfor _, cluster := range existingKubeconfig.Clusters {\n\t\tif cluster.Name == kubeconfig.Clusters[0].Name+\"-\"+request.ClusterID {\n\t\t\tclusterFoundInExistingKubeconfig = true\n\t\t\tcluster.Cluster = kubeconfig.Clusters[0].Cluster\n\t\t\tbreak\n\t\t}\n\t}\n\tif !clusterFoundInExistingKubeconfig {\n\t\texistingKubeconfig.Clusters = append(existingKubeconfig.Clusters, &k8s.KubeconfigClusterWithName{\n\t\t\tName: kubeconfig.Clusters[0].Name + \"-\" + request.ClusterID,\n\t\t\tCluster: kubeconfig.Clusters[0].Cluster,\n\t\t})\n\t}\n\n\t\/\/ loop through all contexts and insert the wanted one if it does not exist\n\tcontextFoundInExistingKubeconfig := false\n\tfor _, kubeconfigContext := range existingKubeconfig.Contexts {\n\t\tif kubeconfigContext.Name == kubeconfig.Contexts[0].Name+\"-\"+request.ClusterID {\n\t\t\tcontextFoundInExistingKubeconfig = true\n\t\t\tkubeconfigContext.Context = k8s.KubeconfigContext{\n\t\t\t\tCluster: kubeconfig.Clusters[0].Name + \"-\" + request.ClusterID,\n\t\t\t\tUser: kubeconfig.Users[0].Name + \"-\" + request.ClusterID,\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\tif !contextFoundInExistingKubeconfig {\n\t\texistingKubeconfig.Contexts = append(existingKubeconfig.Contexts, &k8s.KubeconfigContextWithName{\n\t\t\tName: kubeconfig.Contexts[0].Name + \"-\" + request.ClusterID,\n\t\t\tContext: k8s.KubeconfigContext{\n\t\t\t\tCluster: kubeconfig.Clusters[0].Name + \"-\" + request.ClusterID,\n\t\t\t\tUser: kubeconfig.Users[0].Name + \"-\" + request.ClusterID,\n\t\t\t},\n\t\t})\n\t}\n\n\t\/\/ loop through all users and insert the wanted one if it does not exist\n\tuserFoundInExistingKubeconfig := false\n\tfor _, user := range existingKubeconfig.Users {\n\t\tif user.Name == kubeconfig.Users[0].Name+\"-\"+request.ClusterID {\n\t\t\tuserFoundInExistingKubeconfig = true\n\t\t\tuser.User = kubeconfig.Users[0].User\n\t\t\tbreak\n\t\t}\n\t}\n\tif !userFoundInExistingKubeconfig {\n\t\texistingKubeconfig.Users = append(existingKubeconfig.Users, &k8s.KubeconfigUserWithName{\n\t\t\tName: kubeconfig.Users[0].Name + \"-\" + request.ClusterID,\n\t\t\tUser: kubeconfig.Users[0].User,\n\t\t})\n\t}\n\n\t\/\/ set the current context to the new one\n\tif !request.KeepCurentContext {\n\t\texistingKubeconfig.CurrentContext = kubeconfig.Contexts[0].Name + \"-\" + request.ClusterID\n\t}\n\n\t\/\/ if it's a new file, set the correct config in the file\n\tif existingKubeconfig.APIVersion == \"\" {\n\t\texistingKubeconfig.APIVersion = kubeconfigAPIVersion\n\t}\n\tif existingKubeconfig.Kind == \"\" {\n\t\texistingKubeconfig.Kind = kubeconfigKind\n\t}\n\n\terr = marshalAndWriteKubeconfig(existingKubeconfig, kubeconfigPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn fmt.Sprintf(\"Kubeconfig for cluster %s successfully written at %s\", request.ClusterID, kubeconfigPath), nil\n}\nfix(k8s): fix typo in arg name (#970)package k8s\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n\t\"reflect\"\n\n\t\"github.com\/scaleway\/scaleway-cli\/internal\/core\"\n\tk8s \"github.com\/scaleway\/scaleway-sdk-go\/api\/k8s\/v1\"\n\t\"github.com\/scaleway\/scaleway-sdk-go\/scw\"\n)\n\nconst (\n\tkubeLocationDir = \".kube\"\n\tkubeconfigAPIVersion = \"v1\"\n\tkubeconfigKind = \"Config\"\n)\n\ntype k8sKubeconfigInstallRequest struct {\n\tClusterID string\n\tRegion scw.Region\n\tKeepCurrentContext bool\n}\n\nfunc k8sKubeconfigInstallCommand() *core.Command {\n\treturn &core.Command{\n\t\tShort: `Install a kubeconfig`,\n\t\tLong: `Retrieve the kubeconfig for a specified cluster and write it on disk. \nIt will merge the new kubeconfig in the file pointed by the KUBECONFIG variable. If empty it will default to $HOME\/.kube\/config.`,\n\t\tNamespace: \"k8s\",\n\t\tVerb: \"install\",\n\t\tResource: \"kubeconfig\",\n\t\tArgsType: reflect.TypeOf(k8sKubeconfigInstallRequest{}),\n\t\tArgSpecs: core.ArgSpecs{\n\t\t\t{\n\t\t\t\tName: \"cluster-id\",\n\t\t\t\tShort: \"Cluster ID from which to retrieve the kubeconfig\",\n\t\t\t\tRequired: true,\n\t\t\t\tPositional: true,\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"keep-current-context\",\n\t\t\t\tShort: \"Whether or not to keep the current kubeconfig context unmodified\",\n\t\t\t},\n\t\t\tcore.RegionArgSpec(),\n\t\t},\n\t\tRun: k8sKubeconfigInstallRun,\n\t\tExamples: []*core.Example{\n\t\t\t{\n\t\t\t\tShort: \"Install the kubeconfig for a given cluster and using the new context\",\n\t\t\t\tRequest: `{\"cluster_id\": \"11111111-1111-1111-1111-111111111111\"}`,\n\t\t\t},\n\t\t},\n\t\tSeeAlsos: []*core.SeeAlso{\n\t\t\t{\n\t\t\t\tCommand: \"scw k8s kubeconfig uninstall\",\n\t\t\t\tShort: \"Uninstall a kubeconfig\",\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc k8sKubeconfigInstallRun(ctx context.Context, argsI interface{}) (i interface{}, e error) {\n\trequest := argsI.(*k8sKubeconfigInstallRequest)\n\n\tkubeconfigRequest := &k8s.GetClusterKubeConfigRequest{\n\t\tRegion: request.Region,\n\t\tClusterID: request.ClusterID,\n\t}\n\n\tclient := core.ExtractClient(ctx)\n\tapiK8s := k8s.NewAPI(client)\n\n\t\/\/ get the wanted kubeconfig\n\tkubeconfig, err := apiK8s.GetClusterKubeConfig(kubeconfigRequest)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkubeconfigPath, err := getKubeconfigPath(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ create the kubeconfig file if it does not exist\n\tif _, err := os.Stat(kubeconfigPath); os.IsNotExist(err) {\n\t\t\/\/ make sure the directory exists\n\t\terr = os.MkdirAll(path.Dir(kubeconfigPath), 0755)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t\/\/ create the file\n\t\tf, err := os.OpenFile(kubeconfigPath, os.O_CREATE, 0644)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tf.Close()\n\t}\n\n\texistingKubeconfig, err := openAndUnmarshalKubeconfig(kubeconfigPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ loop through all clusters and insert the wanted one if it does not exist\n\tclusterFoundInExistingKubeconfig := false\n\tfor _, cluster := range existingKubeconfig.Clusters {\n\t\tif cluster.Name == kubeconfig.Clusters[0].Name+\"-\"+request.ClusterID {\n\t\t\tclusterFoundInExistingKubeconfig = true\n\t\t\tcluster.Cluster = kubeconfig.Clusters[0].Cluster\n\t\t\tbreak\n\t\t}\n\t}\n\tif !clusterFoundInExistingKubeconfig {\n\t\texistingKubeconfig.Clusters = append(existingKubeconfig.Clusters, &k8s.KubeconfigClusterWithName{\n\t\t\tName: kubeconfig.Clusters[0].Name + \"-\" + request.ClusterID,\n\t\t\tCluster: kubeconfig.Clusters[0].Cluster,\n\t\t})\n\t}\n\n\t\/\/ loop through all contexts and insert the wanted one if it does not exist\n\tcontextFoundInExistingKubeconfig := false\n\tfor _, kubeconfigContext := range existingKubeconfig.Contexts {\n\t\tif kubeconfigContext.Name == kubeconfig.Contexts[0].Name+\"-\"+request.ClusterID {\n\t\t\tcontextFoundInExistingKubeconfig = true\n\t\t\tkubeconfigContext.Context = k8s.KubeconfigContext{\n\t\t\t\tCluster: kubeconfig.Clusters[0].Name + \"-\" + request.ClusterID,\n\t\t\t\tUser: kubeconfig.Users[0].Name + \"-\" + request.ClusterID,\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t}\n\tif !contextFoundInExistingKubeconfig {\n\t\texistingKubeconfig.Contexts = append(existingKubeconfig.Contexts, &k8s.KubeconfigContextWithName{\n\t\t\tName: kubeconfig.Contexts[0].Name + \"-\" + request.ClusterID,\n\t\t\tContext: k8s.KubeconfigContext{\n\t\t\t\tCluster: kubeconfig.Clusters[0].Name + \"-\" + request.ClusterID,\n\t\t\t\tUser: kubeconfig.Users[0].Name + \"-\" + request.ClusterID,\n\t\t\t},\n\t\t})\n\t}\n\n\t\/\/ loop through all users and insert the wanted one if it does not exist\n\tuserFoundInExistingKubeconfig := false\n\tfor _, user := range existingKubeconfig.Users {\n\t\tif user.Name == kubeconfig.Users[0].Name+\"-\"+request.ClusterID {\n\t\t\tuserFoundInExistingKubeconfig = true\n\t\t\tuser.User = kubeconfig.Users[0].User\n\t\t\tbreak\n\t\t}\n\t}\n\tif !userFoundInExistingKubeconfig {\n\t\texistingKubeconfig.Users = append(existingKubeconfig.Users, &k8s.KubeconfigUserWithName{\n\t\t\tName: kubeconfig.Users[0].Name + \"-\" + request.ClusterID,\n\t\t\tUser: kubeconfig.Users[0].User,\n\t\t})\n\t}\n\n\t\/\/ set the current context to the new one\n\tif !request.KeepCurrentContext {\n\t\texistingKubeconfig.CurrentContext = kubeconfig.Contexts[0].Name + \"-\" + request.ClusterID\n\t}\n\n\t\/\/ if it's a new file, set the correct config in the file\n\tif existingKubeconfig.APIVersion == \"\" {\n\t\texistingKubeconfig.APIVersion = kubeconfigAPIVersion\n\t}\n\tif existingKubeconfig.Kind == \"\" {\n\t\texistingKubeconfig.Kind = kubeconfigKind\n\t}\n\n\terr = marshalAndWriteKubeconfig(existingKubeconfig, kubeconfigPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn fmt.Sprintf(\"Kubeconfig for cluster %s successfully written at %s\", request.ClusterID, kubeconfigPath), nil\n}\n<|endoftext|>"} {"text":"package gpio\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"syscall\"\n\n\t\"github.com\/ungerik\/go-quick\"\n)\n\nconst (\n\tHIGH = true\n\tLOW = false\n\n\t_EPOLLET = 1 << 31\n)\n\ntype Edge string\n\nconst (\n\tNO_EDGE Edge = \"none\"\n\tRISING_EDGE Edge = \"rising\"\n\tFALLING_EDGE Edge = \"falling\"\n\tBOTH_EDGES Edge = \"both\"\n)\n\ntype Direction string\n\nconst (\n\tINPUT Direction = \"in\"\n\tOUTPUT Direction = \"out\"\n\t\/\/ ALT0 Direction = 4\n)\n\n\/\/ TODO: How is this configured?\n\/\/ Maybe see https:\/\/github.com\/adafruit\/PyBBIO\/blob\/master\/bbio\/bbio.py\ntype PullUpDown int\n\nconst (\n\tPUD_OFF PullUpDown = 0\n\tPUD_DOWN PullUpDown = 1\n\tPUD_UP PullUpDown = 2\n)\n\ntype GPIO struct {\n\tnr int\n\tvalue *os.File\n\tepfd quick.SyncInt\n}\n\n\/\/ NewGPIO exports the GPIO pin nr.\nfunc NewGPIO(nr int) (*GPIO, error) {\n\tgpio := &GPIO{nr: nr}\n\n\texport, err := os.OpenFile(\"\/sys\/class\/gpio\/export\", os.O_WRONLY, 0666)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer export.Close()\n\n\t_, err = fmt.Fprintf(export, \"%d\", gpio.nr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn gpio, nil\n}\n\n\/\/ Close unexports the GPIO pin.\nfunc (gpio *GPIO) Close() error {\n\tgpio.RemoveEdgeDetect()\n\n\tif gpio.value != nil {\n\t\tgpio.value.Close()\n\t}\n\n\tunexport, err := os.OpenFile(\"\/sys\/class\/gpio\/unexport\", os.O_WRONLY, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer unexport.Close()\n\n\t_, err = fmt.Fprintf(unexport, \"%d\", gpio.nr)\n\treturn err\n}\n\nfunc (gpio *GPIO) Direction() (Direction, error) {\n\tfilename := fmt.Sprintf(\"\/sys\/class\/gpio\/gpio%d\/direction\", gpio.nr)\n\tfile, err := os.OpenFile(filename, os.O_RDONLY|syscall.O_NONBLOCK, 0666)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer file.Close()\n\tdirection := make([]byte, 3)\n\t_, err = file.Read(direction)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif Direction(direction) == OUTPUT {\n\t\treturn OUTPUT, nil\n\t} else {\n\t\treturn INPUT, nil\n\t}\n}\n\nfunc (gpio *GPIO) SetDirection(direction Direction) error {\n\tfilename := fmt.Sprintf(\"\/sys\/class\/gpio\/gpio%d\/direction\", gpio.nr)\n\tfile, err := os.OpenFile(filename, os.O_WRONLY, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\t_, err = file.Write([]byte(direction))\n\treturn err\n}\n\nfunc (gpio *GPIO) openValueFile() error {\n\tif gpio.value != nil {\n\t\treturn nil\n\t}\n\tfilename := fmt.Sprintf(\"\/sys\/class\/gpio\/gpio%d\/value\", gpio.nr)\n\tfile, err := os.OpenFile(filename, os.O_RDWR, 0666)\n\tif err == nil {\n\t\tgpio.value = file\n\t}\n\treturn err\n}\n\nfunc (gpio *GPIO) Value() (bool, error) {\n\tif err := gpio.openValueFile(); err != nil {\n\t\treturn false, err\n\t}\n\tgpio.value.Seek(0, os.SEEK_SET)\n\tval := make([]byte, 1)\n\t_, err := gpio.value.Read(val)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn val[0] == '1', nil\n}\n\nfunc (gpio *GPIO) SetValue(value bool) (err error) {\n\tif err = gpio.openValueFile(); err != nil {\n\t\treturn err\n\t}\n\tgpio.value.Seek(0, os.SEEK_SET)\n\tif value {\n\t\t_, err = gpio.value.Write([]byte{'1'})\n\t} else {\n\t\t_, err = gpio.value.Write([]byte{'0'})\n\t}\n\treturn err\n}\n\nfunc (gpio *GPIO) SetEdge(edge Edge) error {\n\tfilename := fmt.Sprintf(\"\/sys\/class\/gpio\/gpio%d\/edge\", gpio.nr)\n\tfile, err := os.OpenFile(filename, os.O_WRONLY, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\t_, err = file.Write([]byte(edge))\n\treturn err\n}\n\nfunc (gpio *GPIO) AddEdgeDetect(edge Edge) (chan bool, error) {\n\tgpio.RemoveEdgeDetect()\n\n\terr := gpio.SetDirection(INPUT)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = gpio.SetEdge(edge)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = gpio.openValueFile()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tepfd, err := syscall.EpollCreate(1)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tevent := &syscall.EpollEvent{\n\t\tEvents: syscall.EPOLLIN | _EPOLLET | syscall.EPOLLPRI,\n\t\tFd: int32(gpio.value.Fd()),\n\t}\n\terr = syscall.EpollCtl(epfd, syscall.EPOLL_CTL_ADD, int(gpio.value.Fd()), event)\n\tif err != nil {\n\t\tsyscall.Close(epfd)\n\t\treturn nil, err\n\t}\n\n\t\/\/ \/ first time triggers with current state, so ignore\n\t_, err = syscall.EpollWait(epfd, make([]syscall.EpollEvent, 1), -1)\n\tif err != nil {\n\t\tsyscall.Close(epfd)\n\t\treturn nil, err\n\t}\n\n\tgpio.epfd.Set(epfd)\n\n\tvalueChan := make(chan bool)\n\tgo func() {\n\t\tfor gpio.epfd.Get() != 0 {\n\t\t\tn, _ := syscall.EpollWait(epfd, make([]syscall.EpollEvent, 1), -1)\n\t\t\tif n > 0 {\n\t\t\t\tvalue, err := gpio.Value()\n\t\t\t\tif err == nil {\n\t\t\t\t\tvalueChan <- value\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\treturn valueChan, nil\n}\n\nfunc (gpio *GPIO) RemoveEdgeDetect() {\n\tepfd := gpio.epfd.Swap(0)\n\tif epfd != 0 {\n\t\tsyscall.Close(epfd)\n\t}\n}\n\nfunc (gpio *GPIO) BlockingWaitForEdge(edge Edge) (value bool, err error) {\n\tvalueChan, err := gpio.AddEdgeDetect(edge)\n\tif err == nil {\n\t\tvalue = <-valueChan\n\t\tgpio.RemoveEdgeDetect()\n\t}\n\treturn value, err\n}\nadded direction to NewGPIOpackage gpio\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"syscall\"\n\n\t\"github.com\/ungerik\/go-quick\"\n)\n\nconst (\n\tHIGH = true\n\tLOW = false\n\n\t_EPOLLET = 1 << 31\n)\n\ntype Edge string\n\nconst (\n\tNO_EDGE Edge = \"none\"\n\tRISING_EDGE Edge = \"rising\"\n\tFALLING_EDGE Edge = \"falling\"\n\tBOTH_EDGES Edge = \"both\"\n)\n\ntype Direction string\n\nconst (\n\tINPUT Direction = \"in\"\n\tOUTPUT Direction = \"out\"\n\t\/\/ ALT0 Direction = 4\n)\n\n\/\/ TODO: How is this configured?\n\/\/ Maybe see https:\/\/github.com\/adafruit\/PyBBIO\/blob\/master\/bbio\/bbio.py\ntype PullUpDown int\n\nconst (\n\tPUD_OFF PullUpDown = 0\n\tPUD_DOWN PullUpDown = 1\n\tPUD_UP PullUpDown = 2\n)\n\ntype GPIO struct {\n\tnr int\n\tvalue *os.File\n\tepfd quick.SyncInt\n}\n\n\/\/ NewGPIO exports the GPIO pin nr.\nfunc NewGPIO(nr int, direction Direction) (*GPIO, error) {\n\tgpio := &GPIO{nr: nr}\n\n\texport, err := os.OpenFile(\"\/sys\/class\/gpio\/export\", os.O_WRONLY, 0666)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer export.Close()\n\n\t_, err = fmt.Fprintf(export, \"%d\", gpio.nr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = gpio.SetDirection(direction)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn gpio, nil\n}\n\n\/\/ Close unexports the GPIO pin.\nfunc (gpio *GPIO) Close() error {\n\tgpio.RemoveEdgeDetect()\n\n\tif gpio.value != nil {\n\t\tgpio.value.Close()\n\t}\n\n\tunexport, err := os.OpenFile(\"\/sys\/class\/gpio\/unexport\", os.O_WRONLY, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer unexport.Close()\n\n\t_, err = fmt.Fprintf(unexport, \"%d\", gpio.nr)\n\treturn err\n}\n\nfunc (gpio *GPIO) Direction() (Direction, error) {\n\tfilename := fmt.Sprintf(\"\/sys\/class\/gpio\/gpio%d\/direction\", gpio.nr)\n\tfile, err := os.OpenFile(filename, os.O_RDONLY|syscall.O_NONBLOCK, 0666)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer file.Close()\n\tdirection := make([]byte, 3)\n\t_, err = file.Read(direction)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif Direction(direction) == OUTPUT {\n\t\treturn OUTPUT, nil\n\t} else {\n\t\treturn INPUT, nil\n\t}\n}\n\nfunc (gpio *GPIO) SetDirection(direction Direction) error {\n\tfilename := fmt.Sprintf(\"\/sys\/class\/gpio\/gpio%d\/direction\", gpio.nr)\n\tfile, err := os.OpenFile(filename, os.O_WRONLY, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\t_, err = file.Write([]byte(direction))\n\treturn err\n}\n\nfunc (gpio *GPIO) openValueFile() error {\n\tif gpio.value != nil {\n\t\treturn nil\n\t}\n\tfilename := fmt.Sprintf(\"\/sys\/class\/gpio\/gpio%d\/value\", gpio.nr)\n\tfile, err := os.OpenFile(filename, os.O_RDWR, 0666)\n\tif err == nil {\n\t\tgpio.value = file\n\t}\n\treturn err\n}\n\nfunc (gpio *GPIO) Value() (bool, error) {\n\tif err := gpio.openValueFile(); err != nil {\n\t\treturn false, err\n\t}\n\tgpio.value.Seek(0, os.SEEK_SET)\n\tval := make([]byte, 1)\n\t_, err := gpio.value.Read(val)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn val[0] == '1', nil\n}\n\nfunc (gpio *GPIO) SetValue(value bool) (err error) {\n\tif err = gpio.openValueFile(); err != nil {\n\t\treturn err\n\t}\n\tgpio.value.Seek(0, os.SEEK_SET)\n\tif value {\n\t\t_, err = gpio.value.Write([]byte{'1'})\n\t} else {\n\t\t_, err = gpio.value.Write([]byte{'0'})\n\t}\n\treturn err\n}\n\nfunc (gpio *GPIO) SetEdge(edge Edge) error {\n\tfilename := fmt.Sprintf(\"\/sys\/class\/gpio\/gpio%d\/edge\", gpio.nr)\n\tfile, err := os.OpenFile(filename, os.O_WRONLY, 0666)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\t_, err = file.Write([]byte(edge))\n\treturn err\n}\n\nfunc (gpio *GPIO) AddEdgeDetect(edge Edge) (chan bool, error) {\n\tgpio.RemoveEdgeDetect()\n\n\terr := gpio.SetDirection(INPUT)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = gpio.SetEdge(edge)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = gpio.openValueFile()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tepfd, err := syscall.EpollCreate(1)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tevent := &syscall.EpollEvent{\n\t\tEvents: syscall.EPOLLIN | _EPOLLET | syscall.EPOLLPRI,\n\t\tFd: int32(gpio.value.Fd()),\n\t}\n\terr = syscall.EpollCtl(epfd, syscall.EPOLL_CTL_ADD, int(gpio.value.Fd()), event)\n\tif err != nil {\n\t\tsyscall.Close(epfd)\n\t\treturn nil, err\n\t}\n\n\t\/\/ \/ first time triggers with current state, so ignore\n\t_, err = syscall.EpollWait(epfd, make([]syscall.EpollEvent, 1), -1)\n\tif err != nil {\n\t\tsyscall.Close(epfd)\n\t\treturn nil, err\n\t}\n\n\tgpio.epfd.Set(epfd)\n\n\tvalueChan := make(chan bool)\n\tgo func() {\n\t\tfor gpio.epfd.Get() != 0 {\n\t\t\tn, _ := syscall.EpollWait(epfd, make([]syscall.EpollEvent, 1), -1)\n\t\t\tif n > 0 {\n\t\t\t\tvalue, err := gpio.Value()\n\t\t\t\tif err == nil {\n\t\t\t\t\tvalueChan <- value\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\treturn valueChan, nil\n}\n\nfunc (gpio *GPIO) RemoveEdgeDetect() {\n\tepfd := gpio.epfd.Swap(0)\n\tif epfd != 0 {\n\t\tsyscall.Close(epfd)\n\t}\n}\n\nfunc (gpio *GPIO) BlockingWaitForEdge(edge Edge) (value bool, err error) {\n\tvalueChan, err := gpio.AddEdgeDetect(edge)\n\tif err == nil {\n\t\tvalue = <-valueChan\n\t\tgpio.RemoveEdgeDetect()\n\t}\n\treturn value, err\n}\n<|endoftext|>"} {"text":"package navigator\n\nimport (\n\t\"go\/ast\"\n\t\"go\/parser\"\n\t\"go\/token\"\n\t\"strings\"\n\n\t\"github.com\/nelsam\/gxui\"\n\t\"github.com\/nelsam\/gxui\/math\"\n)\n\ntype genericTreeNode struct {\n\tgxui.AdapterBase\n\n\tname string\n\tpath string\n\tcolor gxui.Color\n\tchildren []gxui.TreeNode\n}\n\nfunc (t genericTreeNode) Count() int {\n\treturn len(t.children)\n}\n\nfunc (t genericTreeNode) ItemIndex(item gxui.AdapterItem) int {\n\tfor i, child := range t.children {\n\t\tif strings.HasPrefix(item.(string), child.Item().(string)) {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}\n\nfunc (t genericTreeNode) Size(theme gxui.Theme) math.Size {\n\treturn math.Size{\n\t\tW: 20 * theme.DefaultMonospaceFont().GlyphMaxSize().W,\n\t\tH: theme.DefaultMonospaceFont().GlyphMaxSize().H,\n\t}\n}\n\nfunc (t genericTreeNode) Item() gxui.AdapterItem {\n\treturn t.path\n}\n\nfunc (t genericTreeNode) NodeAt(index int) gxui.TreeNode {\n\treturn t.children[index]\n}\n\nfunc (t genericTreeNode) Create(theme gxui.Theme) gxui.Control {\n\tlabel := theme.CreateLabel()\n\tlabel.SetText(t.name)\n\tlabel.SetColor(t.color)\n\treturn label\n}\n\ntype Location struct {\n\tfilename string\n\tpos int\n}\n\nfunc (l Location) File() string {\n\treturn l.filename\n}\n\nfunc (l Location) Pos() int {\n\treturn l.pos\n}\n\ntype Name struct {\n\tgenericTreeNode\n\tLocation\n}\n\ntype TOC struct {\n\tgenericTreeNode\n\n\tpkg string\n\tpath string\n}\n\nfunc NewTOC(path string) *TOC {\n\ttoc := &TOC{}\n\ttoc.Init(path)\n\treturn toc\n}\n\nfunc (t *TOC) Init(path string) {\n\tt.path = path\n\tt.Reload()\n}\n\nfunc (t *TOC) Reload() {\n\tpkgs, err := parser.ParseDir(token.NewFileSet(), t.path, nil, 0)\n\tif err != nil {\n\t\treturn\n\t}\n\tfor name, pkg := range pkgs {\n\t\tif strings.HasSuffix(name, \"_test\") {\n\t\t\tcontinue\n\t\t}\n\t\tt.pkg = name\n\t\tt.addPkg(pkg)\n\t}\n}\n\nfunc (t *TOC) addPkg(pkg *ast.Package) {\n\tvar (\n\t\tconsts []gxui.TreeNode\n\t\tvars []gxui.TreeNode\n\t\ttypeMap = make(map[string]*Name)\n\t\ttypes []gxui.TreeNode\n\t\tfuncs []gxui.TreeNode\n\t)\n\tfor filename, f := range pkg.Files {\n\t\tif strings.HasSuffix(filename, \"_test.go\") {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, decl := range f.Decls {\n\t\t\tswitch src := decl.(type) {\n\t\t\tcase *ast.GenDecl:\n\t\t\t\tswitch src.Tok.String() {\n\t\t\t\tcase \"const\":\n\t\t\t\t\tconsts = append(consts, valueNamesFrom(filename, \"constants\", src.Specs)...)\n\t\t\t\tcase \"var\":\n\t\t\t\t\tvars = append(vars, valueNamesFrom(filename, \"global vars\", src.Specs)...)\n\t\t\t\tcase \"type\":\n\t\t\t\t\t\/\/ I have yet to see a case where a type declaration has more than one Specs.\n\t\t\t\t\ttypeSpec := src.Specs[0].(*ast.TypeSpec)\n\t\t\t\t\ttypeName := typeSpec.Name.String()\n\n\t\t\t\t\t\/\/ We can't guarantee that the type declaration was found before method\n\t\t\t\t\t\/\/ declarations, so the value may already exist in the map.\n\t\t\t\t\ttyp, ok := typeMap[typeName]\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\ttyp = &Name{}\n\t\t\t\t\t\ttypeMap[typeName] = typ\n\t\t\t\t\t}\n\t\t\t\t\ttyp.name = typeName\n\t\t\t\t\ttyp.path = \"types.\" + typ.name\n\t\t\t\t\ttyp.color = dirColor\n\t\t\t\t\ttyp.filename = filename\n\t\t\t\t\ttyp.pos = int(typeSpec.Pos())\n\t\t\t\t\ttypes = append(types, typ)\n\t\t\t\t}\n\t\t\tcase *ast.FuncDecl:\n\t\t\t\tvar name Name\n\t\t\t\tname.name = src.Name.String()\n\t\t\t\tname.path = \"funcs.\" + name.name\n\t\t\t\tname.color = dirColor\n\t\t\t\tname.filename = filename\n\t\t\t\tname.pos = int(src.Pos())\n\t\t\t\tif src.Recv == nil {\n\t\t\t\t\tfuncs = append(funcs, name)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\trecvTyp := src.Recv.List[0].Type\n\t\t\t\tif starExpr, ok := recvTyp.(*ast.StarExpr); ok {\n\t\t\t\t\trecvTyp = starExpr.X\n\t\t\t\t}\n\t\t\t\trecvTypeName := recvTyp.(*ast.Ident).String()\n\t\t\t\ttyp, ok := typeMap[recvTypeName]\n\t\t\t\tif !ok {\n\t\t\t\t\ttyp = &Name{}\n\t\t\t\t\ttypeMap[recvTypeName] = typ\n\t\t\t\t}\n\t\t\t\tname.path = \"types.\" + recvTypeName + \".\" + name.name\n\t\t\t\ttyp.children = append(typ.children, name)\n\t\t\t}\n\t\t}\n\t}\n\tt.children = append(t.children,\n\t\tgenericTreeNode{name: \"constants\", path: \"constants\", color: dirColor, children: consts},\n\t\tgenericTreeNode{name: \"global vars\", path: \"global vars\", color: dirColor, children: vars},\n\t\tgenericTreeNode{name: \"types\", path: \"types\", color: dirColor, children: types},\n\t\tgenericTreeNode{name: \"funcs\", path: \"funcs\", color: dirColor, children: funcs},\n\t)\n}\n\nfunc valueNamesFrom(filename, parentName string, specs []ast.Spec) (names []gxui.TreeNode) {\n\tfor _, spec := range specs {\n\t\tvalSpec, ok := spec.(*ast.ValueSpec)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, name := range valSpec.Names {\n\t\t\tvar newName Name\n\t\t\tnewName.name = name.String()\n\t\t\tnewName.path = parentName + \".\" + newName.name\n\t\t\tnewName.color = dirColor\n\t\t\tnewName.filename = filename\n\t\t\tnewName.pos = int(name.Pos())\n\t\t\tnames = append(names, newName)\n\t\t}\n\t}\n\treturn\n}\nMake the package TOC support test packagespackage navigator\n\nimport (\n\t\"go\/ast\"\n\t\"go\/parser\"\n\t\"go\/token\"\n\t\"log\"\n\t\"strings\"\n\n\t\"github.com\/nelsam\/gxui\"\n\t\"github.com\/nelsam\/gxui\/math\"\n)\n\ntype genericTreeNode struct {\n\tgxui.AdapterBase\n\n\tname string\n\tpath string\n\tcolor gxui.Color\n\tchildren []gxui.TreeNode\n}\n\nfunc (t genericTreeNode) Count() int {\n\treturn len(t.children)\n}\n\nfunc (t genericTreeNode) ItemIndex(item gxui.AdapterItem) int {\n\tpath := item.(string)\n\tfor i, child := range t.children {\n\t\tchildPath := child.Item().(string)\n\t\tif path == childPath || strings.HasPrefix(path, childPath+\".\") {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}\n\nfunc (t genericTreeNode) Size(theme gxui.Theme) math.Size {\n\treturn math.Size{\n\t\tW: 20 * theme.DefaultMonospaceFont().GlyphMaxSize().W,\n\t\tH: theme.DefaultMonospaceFont().GlyphMaxSize().H,\n\t}\n}\n\nfunc (t genericTreeNode) Item() gxui.AdapterItem {\n\treturn t.path\n}\n\nfunc (t genericTreeNode) NodeAt(index int) gxui.TreeNode {\n\treturn t.children[index]\n}\n\nfunc (t genericTreeNode) Create(theme gxui.Theme) gxui.Control {\n\tlabel := theme.CreateLabel()\n\tlabel.SetText(t.name)\n\tlabel.SetColor(t.color)\n\treturn label\n}\n\n\/\/ skippingTreeNode is a gxui.TreeNode that will skip to the child\n\/\/ node if there is exactly one child node on implementations of all\n\/\/ gxui.TreeNode methods. This means that any number of nested\n\/\/ skippingTreeNodes will display as a single node, so long as no\n\/\/ child contains more than one child.\ntype skippingTreeNode struct {\n\tgenericTreeNode\n}\n\nfunc (t skippingTreeNode) Count() int {\n\tif len(t.children) == 1 {\n\t\treturn t.children[0].Count()\n\t}\n\treturn t.genericTreeNode.Count()\n}\n\nfunc (t skippingTreeNode) ItemIndex(item gxui.AdapterItem) int {\n\tif len(t.children) == 1 {\n\t\treturn t.children[0].ItemIndex(item)\n\t}\n\treturn t.genericTreeNode.ItemIndex(item)\n}\n\nfunc (t skippingTreeNode) Item() gxui.AdapterItem {\n\tif len(t.children) == 1 {\n\t\treturn t.children[0].Item()\n\t}\n\treturn t.genericTreeNode.Item()\n}\n\nfunc (t skippingTreeNode) NodeAt(index int) gxui.TreeNode {\n\tif len(t.children) == 1 {\n\t\treturn t.children[0].NodeAt(index)\n\t}\n\treturn t.genericTreeNode.NodeAt(index)\n}\n\nfunc (t skippingTreeNode) Create(theme gxui.Theme) gxui.Control {\n\tif len(t.children) == 1 {\n\t\treturn t.children[0].Create(theme)\n\t}\n\treturn t.genericTreeNode.Create(theme)\n}\n\ntype Location struct {\n\tfilename string\n\tpos int\n}\n\nfunc (l Location) File() string {\n\treturn l.filename\n}\n\nfunc (l Location) Pos() int {\n\treturn l.pos\n}\n\ntype Name struct {\n\tgenericTreeNode\n\tLocation\n}\n\ntype TOC struct {\n\tskippingTreeNode\n\n\tpath string\n}\n\nfunc NewTOC(path string) *TOC {\n\ttoc := &TOC{}\n\ttoc.Init(path)\n\treturn toc\n}\n\nfunc (t *TOC) Init(path string) {\n\tt.path = path\n\tt.Reload()\n}\n\nfunc (t *TOC) Reload() {\n\tpkgs, err := parser.ParseDir(token.NewFileSet(), t.path, nil, 0)\n\tif err != nil {\n\t\tlog.Printf(\"Error parsing dir: %s\", err)\n\t}\n\tfor _, pkg := range pkgs {\n\t\tt.children = append(t.children, t.parsePkg(pkg))\n\t}\n}\n\nfunc (t *TOC) parsePkg(pkg *ast.Package) genericTreeNode {\n\tvar (\n\t\tpkgNode = genericTreeNode{name: pkg.Name, path: pkg.Name, color: dirColor}\n\n\t\tconsts []gxui.TreeNode\n\t\tvars []gxui.TreeNode\n\t\ttypeMap = make(map[string]*Name)\n\t\ttypes []gxui.TreeNode\n\t\tfuncs []gxui.TreeNode\n\t)\n\tfor filename, f := range pkg.Files {\n\t\tfor _, decl := range f.Decls {\n\t\t\tswitch src := decl.(type) {\n\t\t\tcase *ast.GenDecl:\n\t\t\t\tswitch src.Tok.String() {\n\t\t\t\tcase \"const\":\n\t\t\t\t\tconsts = append(consts, valueNamesFrom(filename, pkg.Name+\".constants\", src.Specs)...)\n\t\t\t\tcase \"var\":\n\t\t\t\t\tvars = append(vars, valueNamesFrom(filename, pkg.Name+\".global vars\", src.Specs)...)\n\t\t\t\tcase \"type\":\n\t\t\t\t\t\/\/ I have yet to see a case where a type declaration has more than one Specs.\n\t\t\t\t\ttypeSpec := src.Specs[0].(*ast.TypeSpec)\n\t\t\t\t\ttypeName := typeSpec.Name.String()\n\n\t\t\t\t\t\/\/ We can't guarantee that the type declaration was found before method\n\t\t\t\t\t\/\/ declarations, so the value may already exist in the map.\n\t\t\t\t\ttyp, ok := typeMap[typeName]\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\ttyp = &Name{}\n\t\t\t\t\t\ttypeMap[typeName] = typ\n\t\t\t\t\t}\n\t\t\t\t\ttyp.name = typeName\n\t\t\t\t\ttyp.path = pkg.Name + \".types.\" + typ.name\n\t\t\t\t\ttyp.color = dirColor\n\t\t\t\t\ttyp.filename = filename\n\t\t\t\t\ttyp.pos = int(typeSpec.Pos())\n\t\t\t\t\ttypes = append(types, typ)\n\t\t\t\t}\n\t\t\tcase *ast.FuncDecl:\n\t\t\t\tvar name Name\n\t\t\t\tname.name = src.Name.String()\n\t\t\t\tname.path = pkg.Name + \".funcs.\" + name.name\n\t\t\t\tname.color = dirColor\n\t\t\t\tname.filename = filename\n\t\t\t\tname.pos = int(src.Pos())\n\t\t\t\tif src.Recv == nil {\n\t\t\t\t\tfuncs = append(funcs, name)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\trecvTyp := src.Recv.List[0].Type\n\t\t\t\tif starExpr, ok := recvTyp.(*ast.StarExpr); ok {\n\t\t\t\t\trecvTyp = starExpr.X\n\t\t\t\t}\n\t\t\t\trecvTypeName := recvTyp.(*ast.Ident).String()\n\t\t\t\ttyp, ok := typeMap[recvTypeName]\n\t\t\t\tif !ok {\n\t\t\t\t\ttyp = &Name{}\n\t\t\t\t\ttypeMap[recvTypeName] = typ\n\t\t\t\t}\n\t\t\t\tname.path = pkg.Name + \".types.\" + recvTypeName + \".\" + name.name\n\t\t\t\ttyp.children = append(typ.children, name)\n\t\t\t}\n\t\t}\n\t}\n\tpkgNode.children = []gxui.TreeNode{\n\t\tgenericTreeNode{name: \"constants\", path: pkg.Name + \".constants\", color: dirColor, children: consts},\n\t\tgenericTreeNode{name: \"global vars\", path: pkg.Name + \".global vars\", color: dirColor, children: vars},\n\t\tgenericTreeNode{name: \"types\", path: pkg.Name + \".types\", color: dirColor, children: types},\n\t\tgenericTreeNode{name: \"funcs\", path: pkg.Name + \".funcs\", color: dirColor, children: funcs},\n\t}\n\treturn pkgNode\n}\n\nfunc valueNamesFrom(filename, parentName string, specs []ast.Spec) (names []gxui.TreeNode) {\n\tfor _, spec := range specs {\n\t\tvalSpec, ok := spec.(*ast.ValueSpec)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, name := range valSpec.Names {\n\t\t\tvar newName Name\n\t\t\tnewName.name = name.String()\n\t\t\tnewName.path = parentName + \".\" + newName.name\n\t\t\tnewName.color = dirColor\n\t\t\tnewName.filename = filename\n\t\t\tnewName.pos = int(name.Pos())\n\t\t\tnames = append(names, newName)\n\t\t}\n\t}\n\treturn\n}\n<|endoftext|>"} {"text":"package hardcode\n\nimport (\n\t\"bytes\"\n\t\"unicode\/utf8\"\n\n\t\"github.com\/valyala\/bytebufferpool\"\n)\n\nvar domainChars = func() (as asciiSet) {\n\tfor i := 'a'; i <= 'z'; i++ {\n\t\tas.add(byte(i))\n\t}\n\tfor i := 'A'; i <= 'Z'; i++ {\n\t\tas.add(byte(i))\n\t}\n\tfor i := '0'; i <= '9'; i++ {\n\t\tas.add(byte(i))\n\t}\n\tas.add(byte('-'))\n\tas.add(byte('_'))\n\treturn\n}()\n\nvar (\n\tuserapiStr = []byte(\"userapi\")\n\tvkuserStr = []byte(\"vkuser\")\n\tvkcdnStr = []byte(\"vk-cdn\")\n\tvkStr = []byte(\"vk\")\n\tcomStr = []byte(\"com\")\n\tnetStr = []byte(\"net\")\n\tmeStr = []byte(\"me\")\n\tvideoStr = []byte(\"video\")\n\taudioStr = []byte(\"audio\")\n\tliveStr = []byte(\"live\")\n\tescapedSlashStr = []byte(`\\\/`)\n\tescapedDoubleSlashStr = []byte(`\\\/\\\/`)\n\tdotStr = []byte(`.`)\n\tjsonHttpsStr = []byte(`\"https:`)\n\tdocPathStr = []byte(`doc`)\n\timagesPathStr = []byte(`images\\\/`)\n\timagesPath2Str = []byte(`\\\/images\\\/`)\n\tstickerPathStr = []byte(`sticker`)\n\tstickersPathEndingStr = []byte(`s_`)\n\tvideoHlsStr = []byte(`video_hls.php`)\n)\n\nconst (\n\tmaxDomainPartLen = 15\n\tescapedDoubleSlashLen = 4\n\tjsonHttpsLen = 7\n)\n\ntype HardcodedDomainReplaceConfig struct {\n\tPool bytebufferpool.Pool\n\n\t\/\/ Домен, который просто пропускает трафик через себя без обработки, обычно domain.com\\\/_\\\/\n\tSimpleReplace string\n\n\t\/\/ Домен для замены с обработкой, обычно domain.com\\\/@\n\tSmartReplace string\n}\n\ntype hardcodedDomainReplace struct {\n\tpool bytebufferpool.Pool\n\tsimple []byte\n\tsmart []byte\n}\n\ntype insertion struct {\n\toffset int\n\tcontent []byte\n}\n\n\/\/ Этот реплейс работает абсолютно так же, как вместе взятые следующие регулярки:\n\/\/ - \"https:\\\\\/\\\\\/[-_a-zA-Z0-9]{1,15}\\.(?:userapi\\.com|vk-cdn\\.net|vk\\.(?:me|com)|vkuser(?:live|video|audio)\\.(?:net|com))\\\\\/\n\/\/ -> \"https:\\\/\\\/proxy_domain\\\/_\\\/$1\\\/\n\/\/ - \"https:\\\/\\\/vk.com\\\/video_hls.php\n\/\/ -> \"https:\\\/\\\/proxy_domain\\\/@vk.com\\\/video_hls.php\n\/\/ - \"https:\\\\\/\\\\\/vk\\.com\\\\\/((?:\\\\\/)?images\\\\\/|sticker(:?\\\\\/|s_)|doc-?[0-9]+_)\n\/\/ -> \"https:\\\/\\\/proxy_domain\\\/_\\\/vk.com\\\/$1\nfunc NewHardcodedDomainReplace(config HardcodedDomainReplaceConfig) *hardcodedDomainReplace {\n\tv := &hardcodedDomainReplace{\n\t\tpool: config.Pool,\n\t\tsimple: []byte(config.SimpleReplace),\n\t\tsmart: []byte(config.SmartReplace),\n\t}\n\treturn v\n}\n\nfunc (v *hardcodedDomainReplace) Apply(input *bytebufferpool.ByteBuffer) *bytebufferpool.ByteBuffer {\n\tvar output *bytebufferpool.ByteBuffer\n\tvar host [][]byte\n\toffset := 0\n\tinputLen := len(input.B)\n\tvar insertions []insertion\n\tfor {\n\t\tindex := bytes.Index(input.B[offset:], escapedDoubleSlashStr)\n\t\tif index == -1 {\n\t\t\tbreak\n\t\t}\n\t\tmatch := offset + index\n\t\toffset += index + escapedDoubleSlashLen\n\t\tif offset+5 > inputLen {\n\t\t\tbreak\n\t\t}\n\n\t\t\/\/ Проверка на то что ссылка начинается с http и стоит в начале json строки\n\t\tif match < jsonHttpsLen || !bytes.Equal(input.B[match-jsonHttpsLen:match], jsonHttpsStr) {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Чтение домена\n\t\tdomainLength := bytes.Index(input.B[offset:offset+maxDomainPartLen*3], escapedSlashStr)\n\t\tif domainLength == -1 {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Проверка домена на допустимые символы\n\t\thost = bytes.SplitN(input.B[offset:offset+domainLength], dotStr, 3)\n\t\tfor i := len(host) - 1; i >= 0; i-- {\n\t\t\tif len(host[i]) > maxDomainPartLen || !testDomainPart(host[i]) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tins := v.simple\n\t\t\/\/ Проверка что домен можно проксировать\n\t\tif len(host) == 2 {\n\t\t\tif bytes.Equal(host[0], vkStr) && bytes.Equal(host[1], comStr) { \/\/ vk.com\n\t\t\t\t\/\/ Слишком короткий путь, гуляем\n\t\t\t\tif offset+domainLength+5 > inputLen || input.B[offset+domainLength] != '\\\\' {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tpath := input.B[offset+domainLength+2:]\n\n\t\t\t\tif bytes.HasPrefix(path, docPathStr) { \/\/ vk.com\/doc[-0-9]*\n\t\t\t\t\tc := path[len(docPathStr)]\n\t\t\t\t\tif c != '-' && !(c >= '0' && c <= '9') {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t} else if bytes.HasPrefix(path, imagesPathStr) || bytes.HasPrefix(path, imagesPath2Str) { \/\/ vk.com\/\/?images\/*\n\t\t\t\t\t\/\/ allow\n\t\t\t\t} else if bytes.HasPrefix(path, stickerPathStr) { \/\/ vk.com\/sticker*\n\t\t\t\t\tpath2 := path[len(stickerPathStr):]\n\t\t\t\t\tif !bytes.HasPrefix(path2, escapedSlashStr) && \/\/ vk.com\/sticker\/*\n\t\t\t\t\t\t!bytes.HasPrefix(path2, stickersPathEndingStr) { \/\/ vk.com\/stickers_\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t} else if bytes.HasPrefix(path, videoHlsStr) {\n\t\t\t\t\tins = v.smart\n\t\t\t\t} else {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t} else if len(host) == 3 {\n\t\t\tif bytes.Equal(host[1], userapiStr) { \/\/ *.userapi.com\n\t\t\t\tif !bytes.Equal(host[2], comStr) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t} else if bytes.Equal(host[1], vkcdnStr) { \/\/ *.vk-cdn.net\n\t\t\t\tif !bytes.Equal(host[2], netStr) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t} else if bytes.Equal(host[1], vkStr) { \/\/ *.vk.com\n\t\t\t\tif bytes.Equal(host[2], comStr) {\n\t\t\t\t\t\/\/ Домен m.vk.com не проксим\n\t\t\t\t\tif len(host[0]) == 1 && host[0][0] == 'm' {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t} else if !bytes.Equal(host[2], meStr) { \/\/ *.vk.me\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t} else if bytes.HasPrefix(host[1], vkuserStr) { \/\/ *.vkuser(audio|video|live).(net|com)\n\t\t\t\tif !bytes.Equal(host[2], comStr) && !bytes.Equal(host[2], netStr) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tr := host[1][len(vkuserStr):]\n\t\t\t\tif !bytes.Equal(r, videoStr) && !bytes.Equal(r, audioStr) && !bytes.Equal(r, liveStr) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t} else {\n\t\t\tcontinue\n\t\t}\n\t\tif insertions == nil {\n\t\t\t\/\/ Прикинем что в ответе на каждые 300 байт по одной ссылке\n\t\t\tinsertions = make([]insertion, 0, max(16, roundUpToPowerOfTwo(inputLen\/300)))\n\t\t}\n\t\tinsertions = append(insertions, insertion{\n\t\t\toffset: offset,\n\t\t\tcontent: ins,\n\t\t})\n\t}\n\tif insertions == nil {\n\t\treturn input\n\t}\n\n\tneededLength := inputLen\n\tfor _, ins := range insertions {\n\t\tneededLength += len(ins.content)\n\t}\n\n\toutput = v.pool.Get()\n\tif cap(output.B) < neededLength {\n\t\tv.pool.Put(output)\n\t\toutput = &bytebufferpool.ByteBuffer{}\n\t\toutput.B = make([]byte, 0, neededLength)\n\t}\n\n\tlastAppend := 0\n\tfor _, ins := range insertions {\n\t\toutput.B = append(append(output.B, input.B[lastAppend:ins.offset]...), ins.content...)\n\t\tlastAppend = ins.offset\n\t}\n\toutput.B = append(output.B, input.B[lastAppend:]...)\n\n\tv.pool.Put(input)\n\treturn output\n}\n\nfunc testDomainPart(part []byte) bool {\n\tfor i := len(part) - 1; i >= 0; i-- {\n\t\tif !domainChars.contains(part[i]) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc max(a, b int) int {\n\tif a > b {\n\t\treturn a\n\t} else {\n\t\treturn b\n\t}\n}\n\n\/\/ https:\/\/stackoverflow.com\/a\/466242\/6620659\nfunc roundUpToPowerOfTwo(i int) int {\n\ti--\n\ti |= i >> 1\n\ti |= i >> 2\n\ti |= i >> 4\n\ti |= i >> 8\n\ti |= i >> 16\n\treturn i + 1\n}\n\n\/\/ asciiSet is a 32-byte value, where each bit represents the presence of a\n\/\/ given ASCII character in the set. The 128-bits of the lower 16 bytes,\n\/\/ starting with the least-significant bit of the lowest word to the\n\/\/ most-significant bit of the highest word, map to the full range of all\n\/\/ 128 ASCII characters. The 128-bits of the upper 16 bytes will be zeroed,\n\/\/ ensuring that any non-ASCII character will be reported as not in the set.\ntype asciiSet [8]uint32\n\n\/\/ contains reports whether c is inside the set.\nfunc (as *asciiSet) add(c byte) bool {\n\tif c >= utf8.RuneSelf {\n\t\treturn false\n\t}\n\tas[c>>5] |= 1 << uint(c&31)\n\treturn true\n}\n\nfunc (as *asciiSet) contains(c byte) bool {\n\treturn (as[c>>5] & (1 << uint(c&31))) != 0\n}\nФикс выхода за границы массиваpackage hardcode\n\nimport (\n\t\"bytes\"\n\t\"unicode\/utf8\"\n\n\t\"github.com\/valyala\/bytebufferpool\"\n)\n\nvar domainChars = func() (as asciiSet) {\n\tfor i := 'a'; i <= 'z'; i++ {\n\t\tas.add(byte(i))\n\t}\n\tfor i := 'A'; i <= 'Z'; i++ {\n\t\tas.add(byte(i))\n\t}\n\tfor i := '0'; i <= '9'; i++ {\n\t\tas.add(byte(i))\n\t}\n\tas.add(byte('-'))\n\tas.add(byte('_'))\n\treturn\n}()\n\nvar (\n\tuserapiStr = []byte(\"userapi\")\n\tvkuserStr = []byte(\"vkuser\")\n\tvkcdnStr = []byte(\"vk-cdn\")\n\tvkStr = []byte(\"vk\")\n\tcomStr = []byte(\"com\")\n\tnetStr = []byte(\"net\")\n\tmeStr = []byte(\"me\")\n\tvideoStr = []byte(\"video\")\n\taudioStr = []byte(\"audio\")\n\tliveStr = []byte(\"live\")\n\tescapedSlashStr = []byte(`\\\/`)\n\tescapedDoubleSlashStr = []byte(`\\\/\\\/`)\n\tdotStr = []byte(`.`)\n\tjsonHttpsStr = []byte(`\"https:`)\n\tdocPathStr = []byte(`doc`)\n\timagesPathStr = []byte(`images\\\/`)\n\timagesPath2Str = []byte(`\\\/images\\\/`)\n\tstickerPathStr = []byte(`sticker`)\n\tstickersPathEndingStr = []byte(`s_`)\n\tvideoHlsStr = []byte(`video_hls.php`)\n)\n\nconst (\n\tmaxDomainPartLen = 15\n\tescapedDoubleSlashLen = 4\n\tjsonHttpsLen = 7\n)\n\ntype HardcodedDomainReplaceConfig struct {\n\tPool bytebufferpool.Pool\n\n\t\/\/ Домен, который просто пропускает трафик через себя без обработки, обычно domain.com\\\/_\\\/\n\tSimpleReplace string\n\n\t\/\/ Домен для замены с обработкой, обычно domain.com\\\/@\n\tSmartReplace string\n}\n\ntype hardcodedDomainReplace struct {\n\tpool bytebufferpool.Pool\n\tsimple []byte\n\tsmart []byte\n}\n\ntype insertion struct {\n\toffset int\n\tcontent []byte\n}\n\n\/\/ Этот реплейс работает абсолютно так же, как вместе взятые следующие регулярки:\n\/\/ - \"https:\\\\\/\\\\\/[-_a-zA-Z0-9]{1,15}\\.(?:userapi\\.com|vk-cdn\\.net|vk\\.(?:me|com)|vkuser(?:live|video|audio)\\.(?:net|com))\\\\\/\n\/\/ -> \"https:\\\/\\\/proxy_domain\\\/_\\\/$1\\\/\n\/\/ - \"https:\\\/\\\/vk.com\\\/video_hls.php\n\/\/ -> \"https:\\\/\\\/proxy_domain\\\/@vk.com\\\/video_hls.php\n\/\/ - \"https:\\\\\/\\\\\/vk\\.com\\\\\/((?:\\\\\/)?images\\\\\/|sticker(:?\\\\\/|s_)|doc-?[0-9]+_)\n\/\/ -> \"https:\\\/\\\/proxy_domain\\\/_\\\/vk.com\\\/$1\nfunc NewHardcodedDomainReplace(config HardcodedDomainReplaceConfig) *hardcodedDomainReplace {\n\tv := &hardcodedDomainReplace{\n\t\tpool: config.Pool,\n\t\tsimple: []byte(config.SimpleReplace),\n\t\tsmart: []byte(config.SmartReplace),\n\t}\n\treturn v\n}\n\nfunc (v *hardcodedDomainReplace) Apply(input *bytebufferpool.ByteBuffer) *bytebufferpool.ByteBuffer {\n\tvar output *bytebufferpool.ByteBuffer\n\tvar host [][]byte\n\toffset := 0\n\tinputLen := len(input.B)\n\tvar insertions []insertion\n\tfor {\n\t\tindex := bytes.Index(input.B[offset:], escapedDoubleSlashStr)\n\t\tif index == -1 {\n\t\t\tbreak\n\t\t}\n\t\tmatch := offset + index\n\t\toffset += index + escapedDoubleSlashLen\n\t\tif offset+5 > inputLen {\n\t\t\tbreak\n\t\t}\n\n\t\t\/\/ Проверка на то что ссылка начинается с http и стоит в начале json строки\n\t\tif match < jsonHttpsLen || !bytes.Equal(input.B[match-jsonHttpsLen:match], jsonHttpsStr) {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Чтение домена\n\t\tdomainLength := bytes.Index(input.B[offset:min(inputLen, offset+maxDomainPartLen*3)], escapedSlashStr)\n\t\tif domainLength == -1 {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Проверка домена на допустимые символы\n\t\thost = bytes.SplitN(input.B[offset:offset+domainLength], dotStr, 3)\n\t\tfor i := len(host) - 1; i >= 0; i-- {\n\t\t\tif len(host[i]) > maxDomainPartLen || !testDomainPart(host[i]) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tins := v.simple\n\t\t\/\/ Проверка что домен можно проксировать\n\t\tif len(host) == 2 {\n\t\t\tif bytes.Equal(host[0], vkStr) && bytes.Equal(host[1], comStr) { \/\/ vk.com\n\t\t\t\t\/\/ Слишком короткий путь, гуляем\n\t\t\t\tif offset+domainLength+5 > inputLen || input.B[offset+domainLength] != '\\\\' {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tpath := input.B[offset+domainLength+2:]\n\n\t\t\t\tif bytes.HasPrefix(path, docPathStr) { \/\/ vk.com\/doc[-0-9]*\n\t\t\t\t\tc := path[len(docPathStr)]\n\t\t\t\t\tif c != '-' && !(c >= '0' && c <= '9') {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t} else if bytes.HasPrefix(path, imagesPathStr) || bytes.HasPrefix(path, imagesPath2Str) { \/\/ vk.com\/\/?images\/*\n\t\t\t\t\t\/\/ allow\n\t\t\t\t} else if bytes.HasPrefix(path, stickerPathStr) { \/\/ vk.com\/sticker*\n\t\t\t\t\tpath2 := path[len(stickerPathStr):]\n\t\t\t\t\tif !bytes.HasPrefix(path2, escapedSlashStr) && \/\/ vk.com\/sticker\/*\n\t\t\t\t\t\t!bytes.HasPrefix(path2, stickersPathEndingStr) { \/\/ vk.com\/stickers_\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t} else if bytes.HasPrefix(path, videoHlsStr) {\n\t\t\t\t\tins = v.smart\n\t\t\t\t} else {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t} else if len(host) == 3 {\n\t\t\tif bytes.Equal(host[1], userapiStr) { \/\/ *.userapi.com\n\t\t\t\tif !bytes.Equal(host[2], comStr) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t} else if bytes.Equal(host[1], vkcdnStr) { \/\/ *.vk-cdn.net\n\t\t\t\tif !bytes.Equal(host[2], netStr) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t} else if bytes.Equal(host[1], vkStr) { \/\/ *.vk.com\n\t\t\t\tif bytes.Equal(host[2], comStr) {\n\t\t\t\t\t\/\/ Домен m.vk.com не проксим\n\t\t\t\t\tif len(host[0]) == 1 && host[0][0] == 'm' {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t} else if !bytes.Equal(host[2], meStr) { \/\/ *.vk.me\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t} else if bytes.HasPrefix(host[1], vkuserStr) { \/\/ *.vkuser(audio|video|live).(net|com)\n\t\t\t\tif !bytes.Equal(host[2], comStr) && !bytes.Equal(host[2], netStr) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tr := host[1][len(vkuserStr):]\n\t\t\t\tif !bytes.Equal(r, videoStr) && !bytes.Equal(r, audioStr) && !bytes.Equal(r, liveStr) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t} else {\n\t\t\tcontinue\n\t\t}\n\t\tif insertions == nil {\n\t\t\t\/\/ Прикинем что в ответе на каждые 300 байт по одной ссылке\n\t\t\tinsertions = make([]insertion, 0, max(16, roundUpToPowerOfTwo(inputLen\/300)))\n\t\t}\n\t\tinsertions = append(insertions, insertion{\n\t\t\toffset: offset,\n\t\t\tcontent: ins,\n\t\t})\n\t}\n\tif insertions == nil {\n\t\treturn input\n\t}\n\n\tneededLength := inputLen\n\tfor _, ins := range insertions {\n\t\tneededLength += len(ins.content)\n\t}\n\n\toutput = v.pool.Get()\n\tif cap(output.B) < neededLength {\n\t\tv.pool.Put(output)\n\t\toutput = &bytebufferpool.ByteBuffer{}\n\t\toutput.B = make([]byte, 0, neededLength)\n\t}\n\n\tlastAppend := 0\n\tfor _, ins := range insertions {\n\t\toutput.B = append(append(output.B, input.B[lastAppend:ins.offset]...), ins.content...)\n\t\tlastAppend = ins.offset\n\t}\n\toutput.B = append(output.B, input.B[lastAppend:]...)\n\n\tv.pool.Put(input)\n\treturn output\n}\n\nfunc testDomainPart(part []byte) bool {\n\tfor i := len(part) - 1; i >= 0; i-- {\n\t\tif !domainChars.contains(part[i]) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc max(a, b int) int {\n\tif a > b {\n\t\treturn a\n\t} else {\n\t\treturn b\n\t}\n}\n\nfunc min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t} else {\n\t\treturn b\n\t}\n}\n\n\/\/ https:\/\/stackoverflow.com\/a\/466242\/6620659\nfunc roundUpToPowerOfTwo(i int) int {\n\ti--\n\ti |= i >> 1\n\ti |= i >> 2\n\ti |= i >> 4\n\ti |= i >> 8\n\ti |= i >> 16\n\treturn i + 1\n}\n\n\/\/ asciiSet is a 32-byte value, where each bit represents the presence of a\n\/\/ given ASCII character in the set. The 128-bits of the lower 16 bytes,\n\/\/ starting with the least-significant bit of the lowest word to the\n\/\/ most-significant bit of the highest word, map to the full range of all\n\/\/ 128 ASCII characters. The 128-bits of the upper 16 bytes will be zeroed,\n\/\/ ensuring that any non-ASCII character will be reported as not in the set.\ntype asciiSet [8]uint32\n\n\/\/ contains reports whether c is inside the set.\nfunc (as *asciiSet) add(c byte) bool {\n\tif c >= utf8.RuneSelf {\n\t\treturn false\n\t}\n\tas[c>>5] |= 1 << uint(c&31)\n\treturn true\n}\n\nfunc (as *asciiSet) contains(c byte) bool {\n\treturn (as[c>>5] & (1 << uint(c&31))) != 0\n}\n<|endoftext|>"} {"text":"package gopherpods\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"html\/template\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"google.golang.org\/appengine\"\n\t\"google.golang.org\/appengine\/datastore\"\n\t\"google.golang.org\/appengine\/log\"\n\t\"google.golang.org\/appengine\/mail\"\n\t\"google.golang.org\/appengine\/memcache\"\n\t\"google.golang.org\/appengine\/urlfetch\"\n\n\t\"github.com\/gorilla\/feeds\"\n\t\"golang.org\/x\/net\/context\"\n)\n\nconst (\n\tyyyymmdd = \"2006-01-02\"\n\tdisplayDate = \"02 Jan 2006\"\n\trecaptchaURL = \"https:\/\/www.google.com\/recaptcha\/api\/siteverify\"\n\tcacheKey = \"podcasts\"\n\n\tfeedName = \"GopherPods\"\n\tfeedDescription = \"Podcasts about Go (golang)\"\n\tfeedURL = \"https:\/\/gopherpods.appspot.com\"\n)\n\nvar (\n\tpodcastsTmpl = template.Must(template.ParseFiles(\n\t\t\"static\/html\/base.html\",\n\t\t\"static\/html\/podcasts.html\",\n\t))\n\n\tsubmitTmpl = template.Must(template.ParseFiles(\n\t\t\"static\/html\/base.html\",\n\t\t\"static\/html\/submit.html\",\n\t))\n\n\tfailedTmpl = template.Must(template.ParseFiles(\n\t\t\"static\/html\/base.html\",\n\t\t\"static\/html\/failed.html\",\n\t))\n\n\tthanksTmpl = template.Must(template.ParseFiles(\n\t\t\"static\/html\/base.html\",\n\t\t\"static\/html\/thanks.html\",\n\t))\n\n\tsubmissionsTmpl = template.Must(template.ParseFiles(\n\t\t\"static\/html\/base.html\",\n\t\t\"static\/html\/submissions.html\",\n\t))\n\n\tsuccessTmpl = template.Must(template.ParseFiles(\n\t\t\"static\/html\/base.html\",\n\t\t\"static\/html\/success.html\",\n\t))\n\n\terrorTmpl = template.Must(template.ParseFiles(\n\t\t\"static\/html\/base.html\",\n\t\t\"static\/html\/error.html\",\n\t))\n)\n\nfunc serveErr(ctx context.Context, err error, w http.ResponseWriter) {\n\tlog.Errorf(ctx, \"%v\", err)\n\terrorTmpl.ExecuteTemplate(w, \"base\", nil)\n}\n\nfunc init() {\n\thttp.HandleFunc(\"\/\", podcastsHandler)\n\thttp.HandleFunc(\"\/submit\", submitHandler)\n\thttp.HandleFunc(\"\/submit\/add\", submitAddHandler)\n\thttp.HandleFunc(\"\/feed\", feedHandler)\n\thttp.HandleFunc(\"\/submissions\", submissionsHandler)\n\thttp.HandleFunc(\"\/submissions\/add\", submissionsAddHandler)\n\thttp.HandleFunc(\"\/submissions\/del\", submissionsDelHandler)\n\thttp.HandleFunc(\"\/tasks\/email\", emailHandler)\n}\n\ntype Podcast struct {\n\tID int64 `datastore:\",noindex\"`\n\tShow string `datastore:\",noindex\"`\n\tTitle string `datastore:\",noindex\"`\n\tDesc string `datastore:\",noindex\"`\n\tURL template.URL `datastore:\",noindex\"`\n\tMediaURL template.URL `datastore:\",noindex\"`\n\tRuntimeSec string `datastore:\",noindex\"`\n\tSize string `datastore:\",noindex\"`\n\tDate time.Time `datastore:\"\"`\n\tAdded time.Time `datastore:\"\"`\n}\n\nfunc (p *Podcast) DateFormatted() string {\n\treturn p.Date.Format(displayDate)\n}\n\ntype Submission struct {\n\tURL template.URL `datastore:\",noindex\"`\n\tSubmitted time.Time `datastore:\"\"`\n\tKey string `datastore:\"-\"`\n}\n\nfunc getPodcasts(ctx context.Context) ([]Podcast, error) {\n\tpodcasts := make([]Podcast, 0)\n\t_, err := memcache.Gob.Get(ctx, cacheKey, &podcasts)\n\tif err != nil && err != memcache.ErrCacheMiss {\n\t\tlog.Errorf(ctx, \"memcache get error %v\", err)\n\t}\n\n\tif err == nil {\n\t\treturn podcasts, err\n\t}\n\n\tif _, err := datastore.NewQuery(\"Podcast\").Order(\"-Date\").GetAll(ctx, &podcasts); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := memcache.Gob.Set(ctx, &memcache.Item{Key: cacheKey, Object: &podcasts}); err != nil {\n\t\tlog.Errorf(ctx, \"memcache set error %v\", err)\n\t}\n\n\treturn podcasts, nil\n}\n\nfunc podcastsHandler(w http.ResponseWriter, r *http.Request) {\n\tctx := appengine.NewContext(r)\n\tpodcasts, err := getPodcasts(ctx)\n\tif err != nil {\n\t\tserveErr(ctx, err, w)\n\t\treturn\n\t}\n\n\tvar tmplData = struct {\n\t\tPodcasts []Podcast\n\t}{\n\t\tpodcasts,\n\t}\n\n\tpodcastsTmpl.ExecuteTemplate(w, \"base\", tmplData)\n}\n\nfunc submitHandler(w http.ResponseWriter, r *http.Request) {\n\tsubmitTmpl.ExecuteTemplate(w, \"base\", nil)\n}\n\ntype recaptchaResponse struct {\n\tSuccess bool `json:\"success\"`\n\tErrorCode []string `json:\"error-codes\"`\n}\n\nfunc recaptchaCheck(ctx context.Context, response, ip string) (bool, error) {\n\tif appengine.IsDevAppServer() {\n\t\treturn true, nil\n\t}\n\n\tform := url.Values{}\n\tform.Add(\"secret\", os.Getenv(\"SECRET\"))\n\tform.Add(\"response\", response)\n\tform.Add(\"remoteip\", ip)\n\treq, err := http.NewRequest(\"POST\", recaptchaURL, strings.NewReader(form.Encode()))\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tcli := urlfetch.Client(ctx)\n\n\treq.Header.Add(\"Content-Type\", \"application\/x-www-form-urlencoded\")\n\tresp, err := cli.Do(req)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tvar recaptcha recaptchaResponse\n\tif err := json.NewDecoder(resp.Body).Decode(&recaptcha); err != nil {\n\t\treturn false, err\n\t}\n\n\tif !recaptcha.Success {\n\t\tlog.Warningf(ctx, \"%+v\", recaptcha)\n\t\treturn false, nil\n\t}\n\n\treturn true, nil\n}\n\nfunc submitAddHandler(w http.ResponseWriter, r *http.Request) {\n\tctx := appengine.NewContext(r)\n\tif err := r.ParseForm(); err != nil {\n\t\tserveErr(ctx, err, w)\n\t\treturn\n\t}\n\n\tsuccess, err := recaptchaCheck(ctx, r.FormValue(\"g-recaptcha-response\"), r.RemoteAddr)\n\tif err != nil {\n\t\tserveErr(ctx, err, w)\n\t\treturn\n\t}\n\n\tif !success {\n\t\tlog.Warningf(ctx, \"reCAPTCHA check failed\")\n\t\tfailedTmpl.ExecuteTemplate(w, \"base\", nil)\n\t\treturn\n\t}\n\n\tsub := Submission{\n\t\tURL: template.URL(strings.TrimSpace(r.FormValue(\"url\"))),\n\t\tSubmitted: time.Now(),\n\t}\n\n\tif _, err := datastore.Put(ctx, datastore.NewIncompleteKey(ctx, \"Submission\", nil), &sub); err != nil {\n\t\tserveErr(ctx, err, w)\n\t\treturn\n\t}\n\n\tthanksTmpl.ExecuteTemplate(w, \"base\", nil)\n}\n\nfunc feedHandler(w http.ResponseWriter, r *http.Request) {\n\tctx := appengine.NewContext(r)\n\tpodcasts, err := getPodcasts(ctx)\n\tif err != nil {\n\t\tserveErr(ctx, err, w)\n\t\treturn\n\t}\n\n\tfeed := &feeds.Feed{\n\t\tTitle: feedName,\n\t\tLink: &feeds.Link{Href: feedURL},\n\t\tDescription: feedDescription,\n\t\tUpdated: time.Now(),\n\t}\n\n\tfor _, pod := range podcasts {\n\t\tfeed.Add(&feeds.Item{\n\t\t\tTitle: pod.Show + \" - \" + pod.Title,\n\t\t\tDescription: pod.Desc,\n\t\t\tId: string(pod.URL),\n\t\t\tLink: &feeds.Link{\n\t\t\t\tHref: string(pod.MediaURL),\n\t\t\t\tLength: pod.Size,\n\t\t\t\tType: \"audio\/mpeg\",\n\t\t\t},\n\t\t\tCreated: pod.Date,\n\t\t})\n\t}\n\n\trss := &feeds.Rss{feed}\n\trssFeed := rss.RssFeed()\n\n\trssFeed.Image = &feeds.RssImage{\n\t\tTitle: feedName,\n\t\tLink: feedURL,\n\t\tUrl: \"https:\/\/gopherpods.appspot.com\/img\/gopher.png\",\n\t}\n\n\tfor i := 0; i < len(rssFeed.Items); i++ {\n\t\trssFeed.Items[i].Link = rssFeed.Items[i].Guid\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application\/xml\")\n\tif err := feeds.WriteXML(rssFeed, w); err != nil {\n\t\tserveErr(ctx, err, w)\n\t\treturn\n\t}\n}\n\nfunc submissionsHandler(w http.ResponseWriter, r *http.Request) {\n\tctx := appengine.NewContext(r)\n\tsubmissions := make([]Submission, 0)\n\tkeys, err := datastore.NewQuery(\"Submission\").Order(\"Submitted\").GetAll(ctx, &submissions)\n\tif err != nil {\n\t\tserveErr(ctx, err, w)\n\t\treturn\n\t}\n\n\tfor i := range submissions {\n\t\tsubmissions[i].Key = keys[i].Encode()\n\t}\n\n\tvar tmplData = struct {\n\t\tSubmissions []Submission\n\t}{\n\t\tSubmissions: submissions,\n\t}\n\n\tsubmissionsTmpl.ExecuteTemplate(w, \"base\", tmplData)\n}\n\nfunc submissionsAddHandler(w http.ResponseWriter, r *http.Request) {\n\tctx := appengine.NewContext(r)\n\tif err := r.ParseForm(); err != nil {\n\t\tserveErr(ctx, err, w)\n\t\treturn\n\t}\n\n\tID, _, err := datastore.AllocateIDs(ctx, \"Podcast\", nil, 1)\n\tif err != nil {\n\t\tserveErr(ctx, err, w)\n\t\treturn\n\t}\n\n\tdate, err := time.Parse(yyyymmdd, r.FormValue(\"date\"))\n\tif err != nil {\n\t\tserveErr(ctx, err, w)\n\t\treturn\n\t}\n\n\tpodcast := Podcast{\n\t\tID: ID,\n\t\tShow: r.FormValue(\"show\"),\n\t\tTitle: r.FormValue(\"title\"),\n\t\tDesc: r.FormValue(\"desc\"),\n\t\tURL: template.URL(r.FormValue(\"url\")),\n\t\tMediaURL: template.URL(r.FormValue(\"media_url\")),\n\t\tRuntimeSec: r.FormValue(\"runtime\"),\n\t\tSize: r.FormValue(\"size\"),\n\t\tDate: date,\n\t\tAdded: time.Now(),\n\t}\n\n\tif _, err := datastore.Put(ctx, datastore.NewKey(ctx, \"Podcast\", \"\", ID, nil), &podcast); err != nil {\n\t\tserveErr(ctx, err, w)\n\t\treturn\n\t}\n\n\tkey, err := datastore.DecodeKey(r.FormValue(\"key\"))\n\tif err != nil {\n\t\tserveErr(ctx, err, w)\n\t\treturn\n\t}\n\n\tif err := datastore.Delete(ctx, key); err != nil {\n\t\tserveErr(ctx, err, w)\n\t\treturn\n\t}\n\n\tif err := memcache.Delete(ctx, cacheKey); err != nil {\n\t\tlog.Errorf(ctx, \"memcache delete error %v\", err)\n\t}\n\n\tsuccessTmpl.ExecuteTemplate(w, \"base\", nil)\n}\n\nfunc submissionsDelHandler(w http.ResponseWriter, r *http.Request) {\n\tctx := appengine.NewContext(r)\n\tif err := r.ParseForm(); err != nil {\n\t\tserveErr(ctx, err, w)\n\t\treturn\n\t}\n\n\tkey, err := datastore.DecodeKey(r.FormValue(\"key\"))\n\tif err != nil {\n\t\tserveErr(ctx, err, w)\n\t\treturn\n\t}\n\n\tif err := datastore.Delete(ctx, key); err != nil {\n\t\tserveErr(ctx, err, w)\n\t\treturn\n\t}\n\n\tsuccessTmpl.ExecuteTemplate(w, \"base\", nil)\n}\n\nfunc emailHandler(w http.ResponseWriter, r *http.Request) {\n\tctx := appengine.NewContext(r)\n\tkeys, err := datastore.NewQuery(\"Submission\").KeysOnly().GetAll(ctx, nil)\n\tif err != nil {\n\t\tserveErr(ctx, err, w)\n\t\treturn\n\t}\n\n\tif len(keys) == 0 {\n\t\treturn\n\t}\n\n\tmsg := mail.Message{\n\t\tSubject: \"GopherPods\",\n\t\tSender: os.Getenv(\"EMAIL\"),\n\t\tBody: fmt.Sprintf(\"There are %d submissions\", len(keys)),\n\t}\n\n\tif err := mail.SendToAdmins(ctx, &msg); err != nil {\n\t\tserveErr(ctx, err, w)\n\t\treturn\n\t}\n}\nAdd handler to download all episodes as JSON.package gopherpods\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"html\/template\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"google.golang.org\/appengine\"\n\t\"google.golang.org\/appengine\/datastore\"\n\t\"google.golang.org\/appengine\/log\"\n\t\"google.golang.org\/appengine\/mail\"\n\t\"google.golang.org\/appengine\/memcache\"\n\t\"google.golang.org\/appengine\/urlfetch\"\n\n\t\"github.com\/gorilla\/feeds\"\n\t\"golang.org\/x\/net\/context\"\n)\n\nconst (\n\tyyyymmdd = \"2006-01-02\"\n\tdisplayDate = \"02 Jan 2006\"\n\trecaptchaURL = \"https:\/\/www.google.com\/recaptcha\/api\/siteverify\"\n\tcacheKey = \"podcasts\"\n\n\tfeedName = \"GopherPods\"\n\tfeedDescription = \"Podcasts about Go (golang)\"\n\tfeedURL = \"https:\/\/gopherpods.appspot.com\"\n)\n\nvar (\n\tpodcastsTmpl = template.Must(template.ParseFiles(\n\t\t\"static\/html\/base.html\",\n\t\t\"static\/html\/podcasts.html\",\n\t))\n\n\tsubmitTmpl = template.Must(template.ParseFiles(\n\t\t\"static\/html\/base.html\",\n\t\t\"static\/html\/submit.html\",\n\t))\n\n\tfailedTmpl = template.Must(template.ParseFiles(\n\t\t\"static\/html\/base.html\",\n\t\t\"static\/html\/failed.html\",\n\t))\n\n\tthanksTmpl = template.Must(template.ParseFiles(\n\t\t\"static\/html\/base.html\",\n\t\t\"static\/html\/thanks.html\",\n\t))\n\n\tsubmissionsTmpl = template.Must(template.ParseFiles(\n\t\t\"static\/html\/base.html\",\n\t\t\"static\/html\/submissions.html\",\n\t))\n\n\tsuccessTmpl = template.Must(template.ParseFiles(\n\t\t\"static\/html\/base.html\",\n\t\t\"static\/html\/success.html\",\n\t))\n\n\terrorTmpl = template.Must(template.ParseFiles(\n\t\t\"static\/html\/base.html\",\n\t\t\"static\/html\/error.html\",\n\t))\n)\n\nfunc serveErr(ctx context.Context, err error, w http.ResponseWriter) {\n\tlog.Errorf(ctx, \"%v\", err)\n\terrorTmpl.ExecuteTemplate(w, \"base\", nil)\n}\n\nfunc init() {\n\thttp.HandleFunc(\"\/\", podcastsHandler)\n\thttp.HandleFunc(\"\/submit\", submitHandler)\n\thttp.HandleFunc(\"\/submit\/add\", submitAddHandler)\n\thttp.HandleFunc(\"\/feed\", feedHandler)\n\thttp.HandleFunc(\"\/submissions\", submissionsHandler)\n\thttp.HandleFunc(\"\/submissions\/add\", submissionsAddHandler)\n\thttp.HandleFunc(\"\/submissions\/del\", submissionsDelHandler)\n\thttp.HandleFunc(\"\/tasks\/email\", emailHandler)\n\thttp.HandleFunc(\"\/dump\", jsonDumpHandler)\n}\n\ntype Podcast struct {\n\tID int64 `datastore:\",noindex\" json:\"-\"`\n\tShow string `datastore:\",noindex\" json:\"show\"`\n\tTitle string `datastore:\",noindex\" json:\"title\"`\n\tDesc string `datastore:\",noindex\" json:\"about\"`\n\tURL template.URL `datastore:\",noindex\" json:\"url\"`\n\tMediaURL template.URL `datastore:\",noindex\" json:\"-\"`\n\tRuntimeSec string `datastore:\",noindex\" json:\"-\"`\n\tSize string `datastore:\",noindex\" json:\"-\"`\n\tDate time.Time `datastore:\"\" json:\"date\"`\n\tAdded time.Time `datastore:\"\" json:\"added\"`\n}\n\nfunc (p *Podcast) DateFormatted() string {\n\treturn p.Date.Format(displayDate)\n}\n\ntype Submission struct {\n\tURL template.URL `datastore:\",noindex\"`\n\tSubmitted time.Time `datastore:\"\"`\n\tKey string `datastore:\"-\"`\n}\n\nfunc getPodcasts(ctx context.Context) ([]Podcast, error) {\n\tpodcasts := make([]Podcast, 0)\n\t_, err := memcache.Gob.Get(ctx, cacheKey, &podcasts)\n\tif err != nil && err != memcache.ErrCacheMiss {\n\t\tlog.Errorf(ctx, \"memcache get error %v\", err)\n\t}\n\n\tif err == nil {\n\t\treturn podcasts, err\n\t}\n\n\tif _, err := datastore.NewQuery(\"Podcast\").Order(\"-Date\").GetAll(ctx, &podcasts); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := memcache.Gob.Set(ctx, &memcache.Item{Key: cacheKey, Object: &podcasts}); err != nil {\n\t\tlog.Errorf(ctx, \"memcache set error %v\", err)\n\t}\n\n\treturn podcasts, nil\n}\n\nfunc jsonDumpHandler(w http.ResponseWriter, r *http.Request) {\n\tctx := appengine.NewContext(r)\n\tpods := make([]Podcast, 0)\n\tif _, err := datastore.NewQuery(\"Podcast\").Order(\"Date\").GetAll(ctx, &pods); err != nil {\n\t\tserveErr(ctx, err, w)\n\t\treturn\n\t}\n\tjson.NewEncoder(w).Encode(pods)\n}\n\nfunc podcastsHandler(w http.ResponseWriter, r *http.Request) {\n\tctx := appengine.NewContext(r)\n\tpodcasts, err := getPodcasts(ctx)\n\tif err != nil {\n\t\tserveErr(ctx, err, w)\n\t\treturn\n\t}\n\n\tvar tmplData = struct {\n\t\tPodcasts []Podcast\n\t}{\n\t\tpodcasts,\n\t}\n\n\tpodcastsTmpl.ExecuteTemplate(w, \"base\", tmplData)\n}\n\nfunc submitHandler(w http.ResponseWriter, r *http.Request) {\n\tsubmitTmpl.ExecuteTemplate(w, \"base\", nil)\n}\n\ntype recaptchaResponse struct {\n\tSuccess bool `json:\"success\"`\n\tErrorCode []string `json:\"error-codes\"`\n}\n\nfunc recaptchaCheck(ctx context.Context, response, ip string) (bool, error) {\n\tif appengine.IsDevAppServer() {\n\t\treturn true, nil\n\t}\n\n\tform := url.Values{}\n\tform.Add(\"secret\", os.Getenv(\"SECRET\"))\n\tform.Add(\"response\", response)\n\tform.Add(\"remoteip\", ip)\n\treq, err := http.NewRequest(\"POST\", recaptchaURL, strings.NewReader(form.Encode()))\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tcli := urlfetch.Client(ctx)\n\n\treq.Header.Add(\"Content-Type\", \"application\/x-www-form-urlencoded\")\n\tresp, err := cli.Do(req)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tvar recaptcha recaptchaResponse\n\tif err := json.NewDecoder(resp.Body).Decode(&recaptcha); err != nil {\n\t\treturn false, err\n\t}\n\n\tif !recaptcha.Success {\n\t\tlog.Warningf(ctx, \"%+v\", recaptcha)\n\t\treturn false, nil\n\t}\n\n\treturn true, nil\n}\n\nfunc submitAddHandler(w http.ResponseWriter, r *http.Request) {\n\tctx := appengine.NewContext(r)\n\tif err := r.ParseForm(); err != nil {\n\t\tserveErr(ctx, err, w)\n\t\treturn\n\t}\n\n\tsuccess, err := recaptchaCheck(ctx, r.FormValue(\"g-recaptcha-response\"), r.RemoteAddr)\n\tif err != nil {\n\t\tserveErr(ctx, err, w)\n\t\treturn\n\t}\n\n\tif !success {\n\t\tlog.Warningf(ctx, \"reCAPTCHA check failed\")\n\t\tfailedTmpl.ExecuteTemplate(w, \"base\", nil)\n\t\treturn\n\t}\n\n\tsub := Submission{\n\t\tURL: template.URL(strings.TrimSpace(r.FormValue(\"url\"))),\n\t\tSubmitted: time.Now(),\n\t}\n\n\tif _, err := datastore.Put(ctx, datastore.NewIncompleteKey(ctx, \"Submission\", nil), &sub); err != nil {\n\t\tserveErr(ctx, err, w)\n\t\treturn\n\t}\n\n\tthanksTmpl.ExecuteTemplate(w, \"base\", nil)\n}\n\nfunc feedHandler(w http.ResponseWriter, r *http.Request) {\n\tctx := appengine.NewContext(r)\n\tpodcasts, err := getPodcasts(ctx)\n\tif err != nil {\n\t\tserveErr(ctx, err, w)\n\t\treturn\n\t}\n\n\tfeed := &feeds.Feed{\n\t\tTitle: feedName,\n\t\tLink: &feeds.Link{Href: feedURL},\n\t\tDescription: feedDescription,\n\t\tUpdated: time.Now(),\n\t}\n\n\tfor _, pod := range podcasts {\n\t\tfeed.Add(&feeds.Item{\n\t\t\tTitle: pod.Show + \" - \" + pod.Title,\n\t\t\tDescription: pod.Desc,\n\t\t\tId: string(pod.URL),\n\t\t\tLink: &feeds.Link{\n\t\t\t\tHref: string(pod.MediaURL),\n\t\t\t\tLength: pod.Size,\n\t\t\t\tType: \"audio\/mpeg\",\n\t\t\t},\n\t\t\tCreated: pod.Date,\n\t\t})\n\t}\n\n\trss := &feeds.Rss{feed}\n\trssFeed := rss.RssFeed()\n\n\trssFeed.Image = &feeds.RssImage{\n\t\tTitle: feedName,\n\t\tLink: feedURL,\n\t\tUrl: \"https:\/\/gopherpods.appspot.com\/img\/gopher.png\",\n\t}\n\n\tfor i := 0; i < len(rssFeed.Items); i++ {\n\t\trssFeed.Items[i].Link = rssFeed.Items[i].Guid\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application\/xml\")\n\tif err := feeds.WriteXML(rssFeed, w); err != nil {\n\t\tserveErr(ctx, err, w)\n\t\treturn\n\t}\n}\n\nfunc submissionsHandler(w http.ResponseWriter, r *http.Request) {\n\tctx := appengine.NewContext(r)\n\tsubmissions := make([]Submission, 0)\n\tkeys, err := datastore.NewQuery(\"Submission\").Order(\"Submitted\").GetAll(ctx, &submissions)\n\tif err != nil {\n\t\tserveErr(ctx, err, w)\n\t\treturn\n\t}\n\n\tfor i := range submissions {\n\t\tsubmissions[i].Key = keys[i].Encode()\n\t}\n\n\tvar tmplData = struct {\n\t\tSubmissions []Submission\n\t}{\n\t\tSubmissions: submissions,\n\t}\n\n\tsubmissionsTmpl.ExecuteTemplate(w, \"base\", tmplData)\n}\n\nfunc submissionsAddHandler(w http.ResponseWriter, r *http.Request) {\n\tctx := appengine.NewContext(r)\n\tif err := r.ParseForm(); err != nil {\n\t\tserveErr(ctx, err, w)\n\t\treturn\n\t}\n\n\tID, _, err := datastore.AllocateIDs(ctx, \"Podcast\", nil, 1)\n\tif err != nil {\n\t\tserveErr(ctx, err, w)\n\t\treturn\n\t}\n\n\tdate, err := time.Parse(yyyymmdd, r.FormValue(\"date\"))\n\tif err != nil {\n\t\tserveErr(ctx, err, w)\n\t\treturn\n\t}\n\n\tpodcast := Podcast{\n\t\tID: ID,\n\t\tShow: r.FormValue(\"show\"),\n\t\tTitle: r.FormValue(\"title\"),\n\t\tDesc: r.FormValue(\"desc\"),\n\t\tURL: template.URL(r.FormValue(\"url\")),\n\t\tMediaURL: template.URL(r.FormValue(\"media_url\")),\n\t\tRuntimeSec: r.FormValue(\"runtime\"),\n\t\tSize: r.FormValue(\"size\"),\n\t\tDate: date,\n\t\tAdded: time.Now(),\n\t}\n\n\tif _, err := datastore.Put(ctx, datastore.NewKey(ctx, \"Podcast\", \"\", ID, nil), &podcast); err != nil {\n\t\tserveErr(ctx, err, w)\n\t\treturn\n\t}\n\n\tkey, err := datastore.DecodeKey(r.FormValue(\"key\"))\n\tif err != nil {\n\t\tserveErr(ctx, err, w)\n\t\treturn\n\t}\n\n\tif err := datastore.Delete(ctx, key); err != nil {\n\t\tserveErr(ctx, err, w)\n\t\treturn\n\t}\n\n\tif err := memcache.Delete(ctx, cacheKey); err != nil {\n\t\tlog.Errorf(ctx, \"memcache delete error %v\", err)\n\t}\n\n\tsuccessTmpl.ExecuteTemplate(w, \"base\", nil)\n}\n\nfunc submissionsDelHandler(w http.ResponseWriter, r *http.Request) {\n\tctx := appengine.NewContext(r)\n\tif err := r.ParseForm(); err != nil {\n\t\tserveErr(ctx, err, w)\n\t\treturn\n\t}\n\n\tkey, err := datastore.DecodeKey(r.FormValue(\"key\"))\n\tif err != nil {\n\t\tserveErr(ctx, err, w)\n\t\treturn\n\t}\n\n\tif err := datastore.Delete(ctx, key); err != nil {\n\t\tserveErr(ctx, err, w)\n\t\treturn\n\t}\n\n\tsuccessTmpl.ExecuteTemplate(w, \"base\", nil)\n}\n\nfunc emailHandler(w http.ResponseWriter, r *http.Request) {\n\tctx := appengine.NewContext(r)\n\tkeys, err := datastore.NewQuery(\"Submission\").KeysOnly().GetAll(ctx, nil)\n\tif err != nil {\n\t\tserveErr(ctx, err, w)\n\t\treturn\n\t}\n\n\tif len(keys) == 0 {\n\t\treturn\n\t}\n\n\tmsg := mail.Message{\n\t\tSubject: \"GopherPods\",\n\t\tSender: os.Getenv(\"EMAIL\"),\n\t\tBody: fmt.Sprintf(\"There are %d submissions\", len(keys)),\n\t}\n\n\tif err := mail.SendToAdmins(ctx, &msg); err != nil {\n\t\tserveErr(ctx, err, w)\n\t\treturn\n\t}\n}\n<|endoftext|>"} {"text":"\/\/ Copyright © 2016 The Things Network\n\/\/ Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\npackage router\n\nimport (\n\t. \"github.com\/TheThingsNetwork\/ttn\/core\"\n\t\"github.com\/TheThingsNetwork\/ttn\/core\/dutycycle\"\n\t\"github.com\/TheThingsNetwork\/ttn\/utils\/errors\"\n\t\"github.com\/TheThingsNetwork\/ttn\/utils\/stats\"\n\t\"github.com\/apex\/log\"\n)\n\ntype component struct {\n\tStorage\n\tManager dutycycle.DutyManager\n\tctx log.Interface\n}\n\n\/\/ New constructs a new router\nfunc New(db Storage, dm dutycycle.DutyManager, ctx log.Interface) Router {\n\treturn component{Storage: db, Manager: dm, ctx: ctx}\n}\n\n\/\/ Register implements the core.Router interface\nfunc (r component) Register(reg Registration, an AckNacker) (err error) {\n\tdefer ensureAckNack(an, nil, &err)\n\tstats.MarkMeter(\"router.registration.in\")\n\tr.ctx.Debug(\"Handling registration\")\n\n\trreg, ok := reg.(RRegistration)\n\tif !ok {\n\t\terr = errors.New(errors.Structural, \"Unexpected registration type\")\n\t\tr.ctx.WithError(err).Warn(\"Unable to register\")\n\t\treturn err\n\t}\n\n\treturn r.Store(rreg)\n}\n\n\/\/ HandleUp implements the core.Router interface\nfunc (r component) HandleUp(data []byte, an AckNacker, up Adapter) (err error) {\n\t\/\/ Make sure we don't forget the AckNacker\n\tvar ack Packet\n\tdefer ensureAckNack(an, &ack, &err)\n\n\t\/\/ Get some logs \/ analytics\n\tstats.MarkMeter(\"router.uplink.in\")\n\tr.ctx.Debug(\"Handling uplink packet\")\n\n\t\/\/ Extract the given packet\n\titf, _ := UnmarshalPacket(data)\n\tswitch itf.(type) {\n\tcase RPacket:\n\t\tack, err = r.handleDataUp(itf.(RPacket), up)\n\tcase SPacket:\n\t\terr = r.UpdateStats(itf.(SPacket))\n\tdefault:\n\t\tstats.MarkMeter(\"router.uplink.invalid\")\n\t\terr = errors.New(errors.Structural, \"Unreckognized packet type\")\n\t}\n\n\tif err != nil {\n\t\tr.ctx.WithError(err).Debug(\"Unable to process uplink\")\n\t}\n\treturn err\n}\n\n\/\/ handleDataUp handle an upcoming message which carries a data frame payload\nfunc (r component) handleDataUp(packet RPacket, up Adapter) (Packet, error) {\n\t\/\/ Lookup for an existing broker\n\tentries, err := r.Lookup(packet.DevEUI())\n\tif err != nil && err.(errors.Failure).Nature != errors.NotFound {\n\t\tr.ctx.Warn(\"Database lookup failed\")\n\t\treturn nil, errors.New(errors.Operational, err)\n\t}\n\tshouldBroadcast := err != nil\n\n\tmetadata := packet.Metadata()\n\tif metadata.Freq == nil {\n\t\tstats.MarkMeter(\"router.uplink.not_supported\")\n\t\treturn nil, errors.New(errors.Structural, \"Missing mandatory frequency in metadata\")\n\t}\n\n\t\/\/ Add Gateway location metadata\n\tgmeta, _ := r.LookupStats(packet.GatewayID())\n\tmetadata.Lati = gmeta.Lati\n\tmetadata.Long = gmeta.Long\n\tmetadata.Alti = gmeta.Alti\n\n\t\/\/ Add Gateway duty metadata\n\tcycles, err := r.Manager.Lookup(packet.GatewayID())\n\tif err != nil {\n\t\tr.ctx.WithError(err).Debug(\"Unable to get any metadata about duty-cycles\")\n\t\tcycles = make(dutycycle.Cycles)\n\t}\n\n\tsb1, err := dutycycle.GetSubBand(*metadata.Freq)\n\tif err != nil {\n\t\tstats.MarkMeter(\"router.uplink.not_supported\")\n\t\treturn nil, errors.New(errors.Structural, \"Unhandled uplink signal frequency\")\n\t}\n\n\trx1, rx2 := uint(dutycycle.StateFromDuty(cycles[sb1])), uint(dutycycle.StateFromDuty(cycles[dutycycle.EuropeG3]))\n\tmetadata.DutyRX1, metadata.DutyRX2 = &rx1, &rx2\n\n\tbpacket, err := NewBPacket(packet.Payload(), metadata)\n\tif err != nil {\n\t\tstats.MarkMeter(\"router.uplink.not_supported\")\n\t\tr.ctx.WithError(err).Warn(\"Unable to create router packet\")\n\t\treturn nil, errors.New(errors.Structural, err)\n\t}\n\n\t\/\/ Send packet to broker(s)\n\tvar response []byte\n\tif shouldBroadcast {\n\t\t\/\/ No Recipient available -> broadcast\n\t\tresponse, err = up.Send(bpacket)\n\t} else {\n\t\t\/\/ Recipients are available\n\t\tvar recipients []Recipient\n\t\tfor _, e := range entries {\n\t\t\t\/\/ Get the actual broker\n\t\t\trecipient, err := up.GetRecipient(e.Recipient)\n\t\t\tif err != nil {\n\t\t\t\tr.ctx.Warn(\"Unable to retrieve Recipient\")\n\t\t\t\treturn nil, errors.New(errors.Structural, err)\n\t\t\t}\n\t\t\trecipients = append(recipients, recipient)\n\t\t}\n\n\t\t\/\/ Send the packet\n\t\tresponse, err = up.Send(bpacket, recipients...)\n\t\tif err != nil && err.(errors.Failure).Nature == errors.NotFound {\n\t\t\t\/\/ Might be a collision with the dev addr, we better broadcast\n\t\t\tresponse, err = up.Send(bpacket)\n\t\t}\n\t\tstats.MarkMeter(\"router.uplink.out\")\n\t}\n\n\tif err != nil {\n\t\tswitch err.(errors.Failure).Nature {\n\t\tcase errors.NotFound:\n\t\t\tstats.MarkMeter(\"router.uplink.negative_broker_response\")\n\t\tdefault:\n\t\t\tstats.MarkMeter(\"router.uplink.bad_broker_response\")\n\t\t}\n\t\treturn nil, err\n\t}\n\n\treturn r.handleDataDown(response, packet.GatewayID())\n}\n\n\/\/ handleDataDown controls that data received from an uplink are okay.\n\/\/ It also updates metadata about the related gateway\nfunc (r component) handleDataDown(data []byte, gatewayID []byte) (Packet, error) {\n\tif data == nil {\n\t\treturn nil, nil\n\t}\n\n\titf, err := UnmarshalPacket(data)\n\tif err != nil {\n\t\tstats.MarkMeter(\"router.uplink.bad_broker_response\")\n\t\treturn nil, errors.New(errors.Operational, err)\n\t}\n\tswitch itf.(type) {\n\tcase RPacket:\n\t\t\/\/ Update downlink metadata for the related gateway\n\t\tmetadata := itf.(RPacket).Metadata()\n\t\tfreq := metadata.Freq\n\t\tdatr := metadata.Datr\n\t\tcodr := metadata.Codr\n\t\tsize := metadata.Size\n\n\t\tif freq == nil || datr == nil || codr == nil || size == nil {\n\t\t\tstats.MarkMeter(\"router.uplink.bad_broker_response\")\n\t\t\treturn nil, errors.New(errors.Operational, \"Missing mandatory metadata in response\")\n\t\t}\n\n\t\tif err := r.Manager.Update(gatewayID, *freq, *size, *datr, *codr); err != nil {\n\t\t\treturn nil, errors.New(errors.Operational, err)\n\t\t}\n\n\t\t\/\/ Finally, define the ack to be sent\n\t\treturn itf.(RPacket), nil\n\tdefault:\n\t\tstats.MarkMeter(\"router.uplink.bad_broker_response\")\n\t\treturn nil, errors.New(errors.Implementation, \"Unexpected packet type\")\n\t}\n}\n\n\/\/ ensureAckNack is used to make sure we Ack \/ Nack correctly in the HandleUp method.\n\/\/ The method will probably change or be moved outside the router itself.\nfunc ensureAckNack(an AckNacker, ack *Packet, err *error) {\n\tif err != nil && *err != nil {\n\t\tan.Nack(*err)\n\t} else {\n\t\tstats.MarkMeter(\"router.uplink.ok\")\n\t\tvar p Packet\n\t\tif ack != nil {\n\t\t\tp = *ack\n\t\t}\n\t\tan.Ack(p)\n\t}\n}\n[stats] Use distinct meters for stat and uplink\/\/ Copyright © 2016 The Things Network\n\/\/ Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\npackage router\n\nimport (\n\t. \"github.com\/TheThingsNetwork\/ttn\/core\"\n\t\"github.com\/TheThingsNetwork\/ttn\/core\/dutycycle\"\n\t\"github.com\/TheThingsNetwork\/ttn\/utils\/errors\"\n\t\"github.com\/TheThingsNetwork\/ttn\/utils\/stats\"\n\t\"github.com\/apex\/log\"\n)\n\ntype component struct {\n\tStorage\n\tManager dutycycle.DutyManager\n\tctx log.Interface\n}\n\n\/\/ New constructs a new router\nfunc New(db Storage, dm dutycycle.DutyManager, ctx log.Interface) Router {\n\treturn component{Storage: db, Manager: dm, ctx: ctx}\n}\n\n\/\/ Register implements the core.Router interface\nfunc (r component) Register(reg Registration, an AckNacker) (err error) {\n\tdefer ensureAckNack(an, nil, &err)\n\tstats.MarkMeter(\"router.registration.in\")\n\tr.ctx.Debug(\"Handling registration\")\n\n\trreg, ok := reg.(RRegistration)\n\tif !ok {\n\t\terr = errors.New(errors.Structural, \"Unexpected registration type\")\n\t\tr.ctx.WithError(err).Warn(\"Unable to register\")\n\t\treturn err\n\t}\n\n\treturn r.Store(rreg)\n}\n\n\/\/ HandleUp implements the core.Router interface\nfunc (r component) HandleUp(data []byte, an AckNacker, up Adapter) (err error) {\n\t\/\/ Make sure we don't forget the AckNacker\n\tvar ack Packet\n\tdefer ensureAckNack(an, &ack, &err)\n\n\t\/\/ Get some logs \/ analytics\n\tr.ctx.Debug(\"Handling uplink packet\")\n\n\t\/\/ Extract the given packet\n\titf, _ := UnmarshalPacket(data)\n\tswitch itf.(type) {\n\tcase RPacket:\n\t\tstats.MarkMeter(\"router.uplink.in\")\n\t\tack, err = r.handleDataUp(itf.(RPacket), up)\n\tcase SPacket:\n\t\tstats.MarkMeter(\"router.stat.in\")\n\t\terr = r.UpdateStats(itf.(SPacket))\n\tdefault:\n\t\tstats.MarkMeter(\"router.uplink.invalid\")\n\t\terr = errors.New(errors.Structural, \"Unreckognized packet type\")\n\t}\n\n\tif err != nil {\n\t\tr.ctx.WithError(err).Debug(\"Unable to process uplink\")\n\t}\n\treturn err\n}\n\n\/\/ handleDataUp handle an upcoming message which carries a data frame payload\nfunc (r component) handleDataUp(packet RPacket, up Adapter) (Packet, error) {\n\t\/\/ Lookup for an existing broker\n\tentries, err := r.Lookup(packet.DevEUI())\n\tif err != nil && err.(errors.Failure).Nature != errors.NotFound {\n\t\tr.ctx.Warn(\"Database lookup failed\")\n\t\treturn nil, errors.New(errors.Operational, err)\n\t}\n\tshouldBroadcast := err != nil\n\n\tmetadata := packet.Metadata()\n\tif metadata.Freq == nil {\n\t\tstats.MarkMeter(\"router.uplink.not_supported\")\n\t\treturn nil, errors.New(errors.Structural, \"Missing mandatory frequency in metadata\")\n\t}\n\n\t\/\/ Add Gateway location metadata\n\tgmeta, _ := r.LookupStats(packet.GatewayID())\n\tmetadata.Lati = gmeta.Lati\n\tmetadata.Long = gmeta.Long\n\tmetadata.Alti = gmeta.Alti\n\n\t\/\/ Add Gateway duty metadata\n\tcycles, err := r.Manager.Lookup(packet.GatewayID())\n\tif err != nil {\n\t\tr.ctx.WithError(err).Debug(\"Unable to get any metadata about duty-cycles\")\n\t\tcycles = make(dutycycle.Cycles)\n\t}\n\n\tsb1, err := dutycycle.GetSubBand(*metadata.Freq)\n\tif err != nil {\n\t\tstats.MarkMeter(\"router.uplink.not_supported\")\n\t\treturn nil, errors.New(errors.Structural, \"Unhandled uplink signal frequency\")\n\t}\n\n\trx1, rx2 := uint(dutycycle.StateFromDuty(cycles[sb1])), uint(dutycycle.StateFromDuty(cycles[dutycycle.EuropeG3]))\n\tmetadata.DutyRX1, metadata.DutyRX2 = &rx1, &rx2\n\n\tbpacket, err := NewBPacket(packet.Payload(), metadata)\n\tif err != nil {\n\t\tstats.MarkMeter(\"router.uplink.not_supported\")\n\t\tr.ctx.WithError(err).Warn(\"Unable to create router packet\")\n\t\treturn nil, errors.New(errors.Structural, err)\n\t}\n\n\t\/\/ Send packet to broker(s)\n\tvar response []byte\n\tif shouldBroadcast {\n\t\t\/\/ No Recipient available -> broadcast\n\t\tresponse, err = up.Send(bpacket)\n\t} else {\n\t\t\/\/ Recipients are available\n\t\tvar recipients []Recipient\n\t\tfor _, e := range entries {\n\t\t\t\/\/ Get the actual broker\n\t\t\trecipient, err := up.GetRecipient(e.Recipient)\n\t\t\tif err != nil {\n\t\t\t\tr.ctx.Warn(\"Unable to retrieve Recipient\")\n\t\t\t\treturn nil, errors.New(errors.Structural, err)\n\t\t\t}\n\t\t\trecipients = append(recipients, recipient)\n\t\t}\n\n\t\t\/\/ Send the packet\n\t\tresponse, err = up.Send(bpacket, recipients...)\n\t\tif err != nil && err.(errors.Failure).Nature == errors.NotFound {\n\t\t\t\/\/ Might be a collision with the dev addr, we better broadcast\n\t\t\tresponse, err = up.Send(bpacket)\n\t\t}\n\t\tstats.MarkMeter(\"router.uplink.out\")\n\t}\n\n\tif err != nil {\n\t\tswitch err.(errors.Failure).Nature {\n\t\tcase errors.NotFound:\n\t\t\tstats.MarkMeter(\"router.uplink.negative_broker_response\")\n\t\tdefault:\n\t\t\tstats.MarkMeter(\"router.uplink.bad_broker_response\")\n\t\t}\n\t\treturn nil, err\n\t}\n\n\treturn r.handleDataDown(response, packet.GatewayID())\n}\n\n\/\/ handleDataDown controls that data received from an uplink are okay.\n\/\/ It also updates metadata about the related gateway\nfunc (r component) handleDataDown(data []byte, gatewayID []byte) (Packet, error) {\n\tif data == nil {\n\t\treturn nil, nil\n\t}\n\n\titf, err := UnmarshalPacket(data)\n\tif err != nil {\n\t\tstats.MarkMeter(\"router.uplink.bad_broker_response\")\n\t\treturn nil, errors.New(errors.Operational, err)\n\t}\n\tswitch itf.(type) {\n\tcase RPacket:\n\t\t\/\/ Update downlink metadata for the related gateway\n\t\tmetadata := itf.(RPacket).Metadata()\n\t\tfreq := metadata.Freq\n\t\tdatr := metadata.Datr\n\t\tcodr := metadata.Codr\n\t\tsize := metadata.Size\n\n\t\tif freq == nil || datr == nil || codr == nil || size == nil {\n\t\t\tstats.MarkMeter(\"router.uplink.bad_broker_response\")\n\t\t\treturn nil, errors.New(errors.Operational, \"Missing mandatory metadata in response\")\n\t\t}\n\n\t\tif err := r.Manager.Update(gatewayID, *freq, *size, *datr, *codr); err != nil {\n\t\t\treturn nil, errors.New(errors.Operational, err)\n\t\t}\n\n\t\t\/\/ Finally, define the ack to be sent\n\t\treturn itf.(RPacket), nil\n\tdefault:\n\t\tstats.MarkMeter(\"router.uplink.bad_broker_response\")\n\t\treturn nil, errors.New(errors.Implementation, \"Unexpected packet type\")\n\t}\n}\n\n\/\/ ensureAckNack is used to make sure we Ack \/ Nack correctly in the HandleUp method.\n\/\/ The method will probably change or be moved outside the router itself.\nfunc ensureAckNack(an AckNacker, ack *Packet, err *error) {\n\tif err != nil && *err != nil {\n\t\tan.Nack(*err)\n\t} else {\n\t\tstats.MarkMeter(\"router.uplink.ok\")\n\t\tvar p Packet\n\t\tif ack != nil {\n\t\t\tp = *ack\n\t\t}\n\t\tan.Ack(p)\n\t}\n}\n<|endoftext|>"} {"text":"package dashboard\n\nimport (\n\t\"encoding\/json\"\n\t\"net\/http\"\n)\n\n\/\/ HandleHistory returns an object in JSON with the following members.\n\/\/\n\/\/ - \"Clock\": {number} is the current clock value (starting from 0).\n\/\/\n\/\/ - \"TotalHits\": {number} is the total number of hits in the past 24\n\/\/ hours.\n\/\/\n\/\/ - \"Directions\": {array} is the collection of directions. Each item is\n\/\/ an object with the following members:\n\/\/\n\/\/ - \"blocked-values\": {array} is the collection of blocked values.\n\/\/\n\/\/ - \"name\": {string} is the name of the direction.\nfunc (s *Server) HandleHistory(w http.ResponseWriter, r *http.Request) {\n\ttype HistoryData struct {\n\t\tClock int32\n\t\tTotalHits uint64\n\t\tDirections []interface{}\n\t}\n\n\tdata := HistoryData{\n\t\tClock: s.counter.Clock.GetTime(),\n\t\tTotalHits: s.counter.Count.Count(),\n\t\tDirections: make([]interface{}, 0, len(s.conf.Directions)),\n\t}\n\n\tfor iDirection := range s.conf.Directions {\n\t\tdirection := &s.conf.Directions[iDirection]\n\n\t\tdirData := map[string]interface{}{\n\t\t\t\"name\": direction.Name,\n\t\t\t\"blocked-values\": direction.BlockedValues(),\n\t\t}\n\n\t\tdata.Directions = append(data.Directions, dirData)\n\t}\n\n\tjson, _ := json.Marshal(data)\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\tw.Write(json)\n}\nRefreshing the dashboard invokes a CleanUp callpackage dashboard\n\nimport (\n\t\"encoding\/json\"\n\t\"net\/http\"\n)\n\n\/\/ HandleHistory returns an object in JSON with the following members.\n\/\/\n\/\/ - \"Clock\": {number} is the current clock value (starting from 0).\n\/\/\n\/\/ - \"TotalHits\": {number} is the total number of hits in the past 24\n\/\/ hours.\n\/\/\n\/\/ - \"Directions\": {array} is the collection of directions. Each item is\n\/\/ an object with the following members:\n\/\/\n\/\/ - \"blocked-values\": {array} is the collection of blocked values.\n\/\/\n\/\/ - \"name\": {string} is the name of the direction.\nfunc (s *Server) HandleHistory(w http.ResponseWriter, r *http.Request) {\n\ttype HistoryData struct {\n\t\tClock int32\n\t\tTotalHits uint64\n\t\tDirections []interface{}\n\t}\n\n\tdata := HistoryData{\n\t\tClock: s.counter.Clock.GetTime(),\n\t\tTotalHits: s.counter.Count.Count(),\n\t\tDirections: make([]interface{}, 0, len(s.conf.Directions)),\n\t}\n\n\tfor iDirection := range s.conf.Directions {\n\t\tdirection := &s.conf.Directions[iDirection]\n\t\tdirection.Store.CleanUp(data.Clock)\n\n\t\tdirData := map[string]interface{}{\n\t\t\t\"name\": direction.Name,\n\t\t\t\"blocked-values\": direction.BlockedValues(),\n\t\t}\n\n\t\tdata.Directions = append(data.Directions, dirData)\n\t}\n\n\tjson, _ := json.Marshal(data)\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\tw.Write(json)\n}\n<|endoftext|>"} {"text":"package echo\n\nimport (\n\t\"net\/http\"\n\t\"testing\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\n\/\/ TODO: Fix me\nfunc TestGroup(t *testing.T) {\n\tg := New().Group(\"\/group\")\n\th := func(Context) error { return nil }\n\tg.CONNECT(\"\/\", h)\n\tg.DELETE(\"\/\", h)\n\tg.GET(\"\/\", h)\n\tg.HEAD(\"\/\", h)\n\tg.OPTIONS(\"\/\", h)\n\tg.PATCH(\"\/\", h)\n\tg.POST(\"\/\", h)\n\tg.PUT(\"\/\", h)\n\tg.TRACE(\"\/\", h)\n\tg.Any(\"\/\", h)\n\tg.Match([]string{http.MethodGet, http.MethodPost}, \"\/\", h)\n\tg.Static(\"\/static\", \"\/tmp\")\n\tg.File(\"\/walle\", \"_fixture\/images\/\/walle.png\")\n}\n\nfunc TestGroupRouteMiddleware(t *testing.T) {\n\t\/\/ Ensure middleware slices are not re-used\n\te := New()\n\tg := e.Group(\"\/group\")\n\th := func(Context) error { return nil }\n\tm1 := func(next HandlerFunc) HandlerFunc {\n\t\treturn func(c Context) error {\n\t\t\treturn next(c)\n\t\t}\n\t}\n\tm2 := func(next HandlerFunc) HandlerFunc {\n\t\treturn func(c Context) error {\n\t\t\treturn next(c)\n\t\t}\n\t}\n\tm3 := func(next HandlerFunc) HandlerFunc {\n\t\treturn func(c Context) error {\n\t\t\treturn next(c)\n\t\t}\n\t}\n\tm4 := func(next HandlerFunc) HandlerFunc {\n\t\treturn func(c Context) error {\n\t\t\treturn c.NoContent(404)\n\t\t}\n\t}\n\tm5 := func(next HandlerFunc) HandlerFunc {\n\t\treturn func(c Context) error {\n\t\t\treturn c.NoContent(405)\n\t\t}\n\t}\n\tg.Use(m1, m2, m3)\n\tg.GET(\"\/404\", h, m4)\n\tg.GET(\"\/405\", h, m5)\n\n\tc, _ := request(http.MethodGet, \"\/group\/404\", e)\n\tassert.Equal(t, 404, c)\n\tc, _ = request(http.MethodGet, \"\/group\/405\", e)\n\tassert.Equal(t, 405, c)\n}\nAdd tests for group routing with middleware and match any routespackage echo\n\nimport (\n\t\"net\/http\"\n\t\"testing\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\n\/\/ TODO: Fix me\nfunc TestGroup(t *testing.T) {\n\tg := New().Group(\"\/group\")\n\th := func(Context) error { return nil }\n\tg.CONNECT(\"\/\", h)\n\tg.DELETE(\"\/\", h)\n\tg.GET(\"\/\", h)\n\tg.HEAD(\"\/\", h)\n\tg.OPTIONS(\"\/\", h)\n\tg.PATCH(\"\/\", h)\n\tg.POST(\"\/\", h)\n\tg.PUT(\"\/\", h)\n\tg.TRACE(\"\/\", h)\n\tg.Any(\"\/\", h)\n\tg.Match([]string{http.MethodGet, http.MethodPost}, \"\/\", h)\n\tg.Static(\"\/static\", \"\/tmp\")\n\tg.File(\"\/walle\", \"_fixture\/images\/\/walle.png\")\n}\n\nfunc TestGroupRouteMiddleware(t *testing.T) {\n\t\/\/ Ensure middleware slices are not re-used\n\te := New()\n\tg := e.Group(\"\/group\")\n\th := func(Context) error { return nil }\n\tm1 := func(next HandlerFunc) HandlerFunc {\n\t\treturn func(c Context) error {\n\t\t\treturn next(c)\n\t\t}\n\t}\n\tm2 := func(next HandlerFunc) HandlerFunc {\n\t\treturn func(c Context) error {\n\t\t\treturn next(c)\n\t\t}\n\t}\n\tm3 := func(next HandlerFunc) HandlerFunc {\n\t\treturn func(c Context) error {\n\t\t\treturn next(c)\n\t\t}\n\t}\n\tm4 := func(next HandlerFunc) HandlerFunc {\n\t\treturn func(c Context) error {\n\t\t\treturn c.NoContent(404)\n\t\t}\n\t}\n\tm5 := func(next HandlerFunc) HandlerFunc {\n\t\treturn func(c Context) error {\n\t\t\treturn c.NoContent(405)\n\t\t}\n\t}\n\tg.Use(m1, m2, m3)\n\tg.GET(\"\/404\", h, m4)\n\tg.GET(\"\/405\", h, m5)\n\n\tc, _ := request(http.MethodGet, \"\/group\/404\", e)\n\tassert.Equal(t, 404, c)\n\tc, _ = request(http.MethodGet, \"\/group\/405\", e)\n\tassert.Equal(t, 405, c)\n}\n\nfunc TestGroupRouteMiddlewareWithMatchAny(t *testing.T) {\n\t\/\/ Ensure middleware and match any routes do not conflict\n\te := New()\n\tg := e.Group(\"\/group\")\n\tm1 := func(next HandlerFunc) HandlerFunc {\n\t\treturn func(c Context) error {\n\t\t\treturn next(c)\n\t\t}\n\t}\n\tm2 := func(next HandlerFunc) HandlerFunc {\n\t\treturn func(c Context) error {\n\t\t\treturn c.String(http.StatusOK, c.Path())\n\t\t}\n\t}\n\th := func(c Context) error {\n\t\treturn c.String(http.StatusOK, c.Path())\n\t}\n\tg.Use(m1)\n\tg.GET(\"\/help\", h, m2)\n\tg.GET(\"\/*\", h, m2)\n\tg.GET(\"\", h, m2)\n\te.GET(\"*\", h, m2)\n\n\t_, m := request(http.MethodGet, \"\/group\/help\", e)\n\tassert.Equal(t, \"\/group\/help\", m)\n\t_, m = request(http.MethodGet, \"\/group\/help\/other\", e)\n\tassert.Equal(t, \"\/group\/*\", m)\n\t_, m = request(http.MethodGet, \"\/group\/404\", e)\n\tassert.Equal(t, \"\/group\/*\", m)\n\t_, m = request(http.MethodGet, \"\/group\", e)\n\tassert.Equal(t, \"\/group\", m)\n\t_, m = request(http.MethodGet, \"\/other\", e)\n\tassert.Equal(t, \"\/*\", m)\n\t_, m = request(http.MethodGet, \"\/\", e)\n\tassert.Equal(t, \"\/*\", m)\n\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"reflect\"\n\n\t\"github.com\/aacanakin\/qb\"\n)\n\nvar personTable = qb.Table(\n\t\"person\",\n\tqb.Column(\"id\", qb.Varchar().Size(36)),\n\tqb.Column(\"name\", qb.Varchar().NotNull()),\n\tqb.Column(\"email\", qb.Varchar()),\n\tqb.Column(\"created_at\", qb.Timestamp().NotNull()),\n\tqb.Column(\"updated_at\", qb.Timestamp()),\n\tqb.PrimaryKey(\"id\"),\n)\n\nvar personType = reflect.TypeOf(Person{})\n\n\/\/ StructType returns the reflect.Type of the struct\n\/\/ It is used for indexing mappers (and only that I guess, so\n\/\/ it could be replaced with a unique identifier).\nfunc (*Person) StructType() reflect.Type {\n\treturn personType\n}\n\n\/\/ PersonMapper is the Person mapper\ntype PersonMapper struct {\n\tstructType reflect.Type\n}\n\n\/\/ Name returns the mapper name\nfunc (*PersonMapper) Name() string {\n\treturn \"example\/person\"\n}\n\n\/\/ Table returns the mapper table\nfunc (*PersonMapper) Table() *qb.TableElem {\n\treturn &personTable\n}\n\n\/\/ StructType returns the reflect.Type of the mapped structure\nfunc (PersonMapper) StructType() reflect.Type {\n\treturn personType\n}\nCleanup unused attribute in PersonMapperpackage main\n\nimport (\n\t\"reflect\"\n\n\t\"github.com\/aacanakin\/qb\"\n)\n\nvar personTable = qb.Table(\n\t\"person\",\n\tqb.Column(\"id\", qb.Varchar().Size(36)),\n\tqb.Column(\"name\", qb.Varchar().NotNull()),\n\tqb.Column(\"email\", qb.Varchar()),\n\tqb.Column(\"created_at\", qb.Timestamp().NotNull()),\n\tqb.Column(\"updated_at\", qb.Timestamp()),\n\tqb.PrimaryKey(\"id\"),\n)\n\nvar personType = reflect.TypeOf(Person{})\n\n\/\/ StructType returns the reflect.Type of the struct\n\/\/ It is used for indexing mappers (and only that I guess, so\n\/\/ it could be replaced with a unique identifier).\nfunc (*Person) StructType() reflect.Type {\n\treturn personType\n}\n\n\/\/ PersonMapper is the Person mapper\ntype PersonMapper struct {\n}\n\n\/\/ Name returns the mapper name\nfunc (*PersonMapper) Name() string {\n\treturn \"example\/person\"\n}\n\n\/\/ Table returns the mapper table\nfunc (*PersonMapper) Table() *qb.TableElem {\n\treturn &personTable\n}\n\n\/\/ StructType returns the reflect.Type of the mapped structure\nfunc (PersonMapper) StructType() reflect.Type {\n\treturn personType\n}\n<|endoftext|>"} {"text":"package helix\n\nimport (\n\t\"net\/http\"\n\t\"strings\"\n\t\"time\"\n\n\thelixClient \"github.com\/nicklaw5\/helix\"\n\tlog \"github.com\/sirupsen\/logrus\"\n)\n\n\/\/ Client wrapper for helix\ntype Client struct {\n\tclientID string\n\tclientSecret string\n\tappAccessToken string\n\tclient *helixClient.Client\n\thttpClient *http.Client\n}\n\nvar (\n\tuserCacheByID map[string]*UserData\n\tuserCacheByUsername map[string]*UserData\n)\n\nfunc init() {\n\tuserCacheByID = map[string]*UserData{}\n\tuserCacheByUsername = map[string]*UserData{}\n}\n\n\/\/ NewClient Create helix client\nfunc NewClient(clientID string, clientSecret string) Client {\n\tclient, err := helixClient.NewClient(&helixClient.Options{\n\t\tClientID: clientID,\n\t\tClientSecret: clientSecret,\n\t})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tresp, err := client.GetAppAccessToken()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tlog.Infof(\"Requested access token, response: %d, expires in: %d\", resp.StatusCode, resp.Data.ExpiresIn)\n\tclient.SetAppAccessToken(resp.Data.AccessToken)\n\n\treturn Client{\n\t\tclientID: clientID,\n\t\tclientSecret: clientSecret,\n\t\tappAccessToken: clientSecret,\n\t\tclient: client,\n\t\thttpClient: &http.Client{},\n\t}\n}\n\ntype userResponse struct {\n\tData []UserData `json:\"data\"`\n}\n\n\/\/ UserData exported data from twitch\ntype UserData struct {\n\tID string `json:\"id\"`\n\tLogin string `json:\"login\"`\n\tDisplayName string `json:\"display_name\"`\n\tType string `json:\"type\"`\n\tBroadcasterType string `json:\"broadcaster_type\"`\n\tDescription string `json:\"description\"`\n\tProfileImageURL string `json:\"profile_image_url\"`\n\tOfflineImageURL string `json:\"offline_image_url\"`\n\tViewCount int `json:\"view_count\"`\n\tEmail string `json:\"email\"`\n}\n\n\/\/ StartRefreshTokenRoutine refresh our token\nfunc (c *Client) StartRefreshTokenRoutine() {\n\tticker := time.NewTicker(24 * time.Hour)\n\n\tfor range ticker.C {\n\t\tresp, err := c.client.GetAppAccessToken()\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\tcontinue\n\t\t}\n\t\tlog.Infof(\"Requested access token from routine, response: %d, expires in: %d\", resp.StatusCode, resp.Data.ExpiresIn)\n\n\t\tc.client.SetAppAccessToken(resp.Data.AccessToken)\n\t}\n}\n\n\/\/ GetUsersByUserIds receive userData for given ids\nfunc (c *Client) GetUsersByUserIds(userIDs []string) (map[string]UserData, error) {\n\tvar filteredUserIDs []string\n\n\tfor _, id := range userIDs {\n\t\tif _, ok := userCacheByID[id]; !ok {\n\t\t\tfilteredUserIDs = append(filteredUserIDs, id)\n\t\t}\n\t}\n\n\tif len(filteredUserIDs) > 0 {\n\t\tresp, err := c.client.GetUsers(&helixClient.UsersParams{\n\t\t\tIDs: filteredUserIDs,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn map[string]UserData{}, err\n\t\t}\n\n\t\tlog.Infof(\"%d GetUsersByUserIds %v\", resp.StatusCode, filteredUserIDs)\n\n\t\tfor _, user := range resp.Data.Users {\n\t\t\tdata := &UserData{\n\t\t\t\tID: user.ID,\n\t\t\t\tLogin: user.Login,\n\t\t\t\tDisplayName: user.Login,\n\t\t\t\tType: user.Type,\n\t\t\t\tBroadcasterType: user.BroadcasterType,\n\t\t\t\tDescription: user.Description,\n\t\t\t\tProfileImageURL: user.ProfileImageURL,\n\t\t\t\tOfflineImageURL: user.OfflineImageURL,\n\t\t\t\tViewCount: user.ViewCount,\n\t\t\t\tEmail: user.Email,\n\t\t\t}\n\t\t\tuserCacheByID[user.ID] = data\n\t\t\tuserCacheByUsername[user.Login] = data\n\t\t}\n\t}\n\n\tresult := make(map[string]UserData)\n\n\tfor _, id := range userIDs {\n\t\tif _, ok := userCacheByID[id]; !ok {\n\t\t\tlog.Warningf(\"Could not find userId, channel might be banned: %s\", id)\n\t\t\tcontinue\n\t\t}\n\t\tresult[id] = *userCacheByID[id]\n\t}\n\n\treturn result, nil\n}\n\n\/\/ GetUsersByUsernames fetches userdata from helix\nfunc (c *Client) GetUsersByUsernames(usernames []string) (map[string]UserData, error) {\n\tvar filteredUsernames []string\n\n\tfor _, username := range usernames {\n\t\tif _, ok := userCacheByUsername[strings.ToLower(username)]; !ok {\n\t\t\tfilteredUsernames = append(filteredUsernames, strings.ToLower(username))\n\t\t}\n\t}\n\n\tif len(filteredUsernames) > 0 {\n\t\tresp, err := c.client.GetUsers(&helixClient.UsersParams{\n\t\t\tLogins: filteredUsernames,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn map[string]UserData{}, err\n\t\t}\n\n\t\tlog.Infof(\"%d GetUsersByUsernames %v\", resp.StatusCode, filteredUsernames)\n\n\t\tfor _, user := range resp.Data.Users {\n\t\t\tdata := &UserData{\n\t\t\t\tID: user.ID,\n\t\t\t\tLogin: user.Login,\n\t\t\t\tDisplayName: user.Login,\n\t\t\t\tType: user.Type,\n\t\t\t\tBroadcasterType: user.BroadcasterType,\n\t\t\t\tDescription: user.Description,\n\t\t\t\tProfileImageURL: user.ProfileImageURL,\n\t\t\t\tOfflineImageURL: user.OfflineImageURL,\n\t\t\t\tViewCount: user.ViewCount,\n\t\t\t\tEmail: user.Email,\n\t\t\t}\n\t\t\tuserCacheByID[user.ID] = data\n\t\t\tuserCacheByUsername[user.Login] = data\n\t\t}\n\t}\n\n\tresult := make(map[string]UserData)\n\n\tfor _, username := range usernames {\n\t\tif _, ok := userCacheByUsername[username]; !ok {\n\t\t\tlog.Warningf(\"Could not find username, channel might be banned: %s\", username)\n\t\t\tcontinue\n\t\t}\n\t\tresult[strings.ToLower(username)] = *userCacheByUsername[strings.ToLower(username)]\n\t}\n\n\treturn result, nil\n}\nfix typopackage helix\n\nimport (\n\t\"net\/http\"\n\t\"strings\"\n\t\"time\"\n\n\thelixClient \"github.com\/nicklaw5\/helix\"\n\tlog \"github.com\/sirupsen\/logrus\"\n)\n\n\/\/ Client wrapper for helix\ntype Client struct {\n\tclientID string\n\tclientSecret string\n\tappAccessToken string\n\tclient *helixClient.Client\n\thttpClient *http.Client\n}\n\nvar (\n\tuserCacheByID map[string]*UserData\n\tuserCacheByUsername map[string]*UserData\n)\n\nfunc init() {\n\tuserCacheByID = map[string]*UserData{}\n\tuserCacheByUsername = map[string]*UserData{}\n}\n\n\/\/ NewClient Create helix client\nfunc NewClient(clientID string, clientSecret string) Client {\n\tclient, err := helixClient.NewClient(&helixClient.Options{\n\t\tClientID: clientID,\n\t\tClientSecret: clientSecret,\n\t})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tresp, err := client.GetAppAccessToken()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tlog.Infof(\"Requested access token, response: %d, expires in: %d\", resp.StatusCode, resp.Data.ExpiresIn)\n\tclient.SetAppAccessToken(resp.Data.AccessToken)\n\n\treturn Client{\n\t\tclientID: clientID,\n\t\tclientSecret: clientSecret,\n\t\tappAccessToken: resp.Data.AccessToken,\n\t\tclient: client,\n\t\thttpClient: &http.Client{},\n\t}\n}\n\ntype userResponse struct {\n\tData []UserData `json:\"data\"`\n}\n\n\/\/ UserData exported data from twitch\ntype UserData struct {\n\tID string `json:\"id\"`\n\tLogin string `json:\"login\"`\n\tDisplayName string `json:\"display_name\"`\n\tType string `json:\"type\"`\n\tBroadcasterType string `json:\"broadcaster_type\"`\n\tDescription string `json:\"description\"`\n\tProfileImageURL string `json:\"profile_image_url\"`\n\tOfflineImageURL string `json:\"offline_image_url\"`\n\tViewCount int `json:\"view_count\"`\n\tEmail string `json:\"email\"`\n}\n\n\/\/ StartRefreshTokenRoutine refresh our token\nfunc (c *Client) StartRefreshTokenRoutine() {\n\tticker := time.NewTicker(24 * time.Hour)\n\n\tfor range ticker.C {\n\t\tresp, err := c.client.GetAppAccessToken()\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\tcontinue\n\t\t}\n\t\tlog.Infof(\"Requested access token from routine, response: %d, expires in: %d\", resp.StatusCode, resp.Data.ExpiresIn)\n\n\t\tc.client.SetAppAccessToken(resp.Data.AccessToken)\n\t}\n}\n\n\/\/ GetUsersByUserIds receive userData for given ids\nfunc (c *Client) GetUsersByUserIds(userIDs []string) (map[string]UserData, error) {\n\tvar filteredUserIDs []string\n\n\tfor _, id := range userIDs {\n\t\tif _, ok := userCacheByID[id]; !ok {\n\t\t\tfilteredUserIDs = append(filteredUserIDs, id)\n\t\t}\n\t}\n\n\tif len(filteredUserIDs) > 0 {\n\t\tresp, err := c.client.GetUsers(&helixClient.UsersParams{\n\t\t\tIDs: filteredUserIDs,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn map[string]UserData{}, err\n\t\t}\n\n\t\tlog.Infof(\"%d GetUsersByUserIds %v\", resp.StatusCode, filteredUserIDs)\n\n\t\tfor _, user := range resp.Data.Users {\n\t\t\tdata := &UserData{\n\t\t\t\tID: user.ID,\n\t\t\t\tLogin: user.Login,\n\t\t\t\tDisplayName: user.Login,\n\t\t\t\tType: user.Type,\n\t\t\t\tBroadcasterType: user.BroadcasterType,\n\t\t\t\tDescription: user.Description,\n\t\t\t\tProfileImageURL: user.ProfileImageURL,\n\t\t\t\tOfflineImageURL: user.OfflineImageURL,\n\t\t\t\tViewCount: user.ViewCount,\n\t\t\t\tEmail: user.Email,\n\t\t\t}\n\t\t\tuserCacheByID[user.ID] = data\n\t\t\tuserCacheByUsername[user.Login] = data\n\t\t}\n\t}\n\n\tresult := make(map[string]UserData)\n\n\tfor _, id := range userIDs {\n\t\tif _, ok := userCacheByID[id]; !ok {\n\t\t\tlog.Warningf(\"Could not find userId, channel might be banned: %s\", id)\n\t\t\tcontinue\n\t\t}\n\t\tresult[id] = *userCacheByID[id]\n\t}\n\n\treturn result, nil\n}\n\n\/\/ GetUsersByUsernames fetches userdata from helix\nfunc (c *Client) GetUsersByUsernames(usernames []string) (map[string]UserData, error) {\n\tvar filteredUsernames []string\n\n\tfor _, username := range usernames {\n\t\tif _, ok := userCacheByUsername[strings.ToLower(username)]; !ok {\n\t\t\tfilteredUsernames = append(filteredUsernames, strings.ToLower(username))\n\t\t}\n\t}\n\n\tif len(filteredUsernames) > 0 {\n\t\tresp, err := c.client.GetUsers(&helixClient.UsersParams{\n\t\t\tLogins: filteredUsernames,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn map[string]UserData{}, err\n\t\t}\n\n\t\tlog.Infof(\"%d GetUsersByUsernames %v\", resp.StatusCode, filteredUsernames)\n\n\t\tfor _, user := range resp.Data.Users {\n\t\t\tdata := &UserData{\n\t\t\t\tID: user.ID,\n\t\t\t\tLogin: user.Login,\n\t\t\t\tDisplayName: user.Login,\n\t\t\t\tType: user.Type,\n\t\t\t\tBroadcasterType: user.BroadcasterType,\n\t\t\t\tDescription: user.Description,\n\t\t\t\tProfileImageURL: user.ProfileImageURL,\n\t\t\t\tOfflineImageURL: user.OfflineImageURL,\n\t\t\t\tViewCount: user.ViewCount,\n\t\t\t\tEmail: user.Email,\n\t\t\t}\n\t\t\tuserCacheByID[user.ID] = data\n\t\t\tuserCacheByUsername[user.Login] = data\n\t\t}\n\t}\n\n\tresult := make(map[string]UserData)\n\n\tfor _, username := range usernames {\n\t\tif _, ok := userCacheByUsername[username]; !ok {\n\t\t\tlog.Warningf(\"Could not find username, channel might be banned: %s\", username)\n\t\t\tcontinue\n\t\t}\n\t\tresult[strings.ToLower(username)] = *userCacheByUsername[strings.ToLower(username)]\n\t}\n\n\treturn result, nil\n}\n<|endoftext|>"} {"text":"\/*\n Copyright 2014 Outbrain Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\npackage logic\n\nimport (\n\t\"os\"\n\t\"os\/signal\"\n\t\"sync\/atomic\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com\/outbrain\/golib\/log\"\n\t\"github.com\/outbrain\/orchestrator\/go\/agent\"\n\t\"github.com\/outbrain\/orchestrator\/go\/config\"\n\t\"github.com\/outbrain\/orchestrator\/go\/inst\"\n\tometrics \"github.com\/outbrain\/orchestrator\/go\/metrics\"\n\t\"github.com\/outbrain\/orchestrator\/go\/process\"\n\t\"github.com\/pmylund\/go-cache\"\n\t\"github.com\/rcrowley\/go-metrics\"\n)\n\nconst (\n\tdiscoveryInstanceChannelCapacity = 5 \/\/ size here not critical as channel read by separate go routines.\n)\n\n\/\/ discoveryInstanceKeys is a channel of instanceKey-s that were requested for discovery.\n\/\/ It can be continuously updated as discovery process progresses.\nvar discoveryInstanceKeys = make(chan inst.InstanceKey, discoveryInstanceChannelCapacity)\n\nvar discoveriesCounter = metrics.NewCounter()\nvar failedDiscoveriesCounter = metrics.NewCounter()\nvar discoveryQueueLengthGauge = metrics.NewGauge()\nvar discoveryRecentCountGauge = metrics.NewGauge()\nvar isElectedGauge = metrics.NewGauge()\n\nvar isElectedNode int64 = 0\n\nvar recentDiscoveryOperationKeys *cache.Cache\n\nfunc init() {\n\tmetrics.Register(\"discoveries.attempt\", discoveriesCounter)\n\tmetrics.Register(\"discoveries.fail\", failedDiscoveriesCounter)\n\tmetrics.Register(\"discoveries.queue_length\", discoveryQueueLengthGauge)\n\tmetrics.Register(\"discoveries.recent_count\", discoveryRecentCountGauge)\n\tmetrics.Register(\"elect.is_elected\", isElectedGauge)\n\n\tometrics.OnGraphiteTick(func() { discoveryQueueLengthGauge.Update(int64(len(discoveryInstanceKeys))) })\n\tometrics.OnGraphiteTick(func() {\n\t\tif recentDiscoveryOperationKeys == nil {\n\t\t\treturn\n\t\t}\n\t\tdiscoveryRecentCountGauge.Update(int64(recentDiscoveryOperationKeys.ItemCount()))\n\t})\n\tometrics.OnGraphiteTick(func() { isElectedGauge.Update(int64(atomic.LoadInt64(&isElectedNode))) })\n}\n\n\/\/ acceptSignals registers for OS signals\nfunc acceptSignals() {\n\tc := make(chan os.Signal, 1)\n\n\tsignal.Notify(c, syscall.SIGHUP)\n\tgo func() {\n\t\tfor sig := range c {\n\t\t\tswitch sig {\n\t\t\tcase syscall.SIGHUP:\n\t\t\t\tlog.Debugf(\"Received SIGHUP. Reloading configuration\")\n\t\t\t\tconfig.Reload()\n\t\t\t\tinst.AuditOperation(\"reload-configuration\", nil, \"Triggered via SIGHUP\")\n\t\t\t}\n\t\t}\n\t}()\n}\n\n\/\/ handleDiscoveryRequests iterates the discoveryInstanceKeys channel\n\/\/ and calls upon instance discovery per entry. These requests will\n\/\/ be handled by separate go routines so concurrency should be high.\nfunc handleDiscoveryRequests() {\n\tfor instanceKey := range discoveryInstanceKeys {\n\t\t\/\/ Possibly this used to be the elected node, but has been demoted, while still\n\t\t\/\/ the queue is full.\n\t\t\/\/ Just don't process the queue when not elected.\n\t\tif atomic.LoadInt64(&isElectedNode) == 1 {\n\t\t\tgo discoverInstance(instanceKey)\n\t\t} else {\n\t\t\tlog.Debugf(\"Node apparently demoted. Skipping discovery of %+v. Remaining queue size: %+v\", instanceKey, len(discoveryInstanceKeys))\n\t\t}\n\t}\n}\n\n\/\/ discoverInstance will attempt to discover an instance (unless it is\n\/\/ already up to date) and will list down its master and slaves (if any)\n\/\/ for further discovery.\nfunc discoverInstance(instanceKey inst.InstanceKey) {\n\tstart := time.Now()\n\n\tinstanceKey.Formalize()\n\tif !instanceKey.IsValid() {\n\t\treturn\n\t}\n\n\tDiscoverStart(instanceKey)\n\tif existsInCacheError := recentDiscoveryOperationKeys.Add(instanceKey.DisplayString(), true, cache.DefaultExpiration); existsInCacheError != nil {\n\t\tDiscoverEnd(instanceKey)\n\t\t\/\/ Just recently attempted\n\t\treturn\n\t}\n\n\tinstance, found, err := inst.ReadInstance(&instanceKey)\n\n\tif found && instance.IsUpToDate && instance.IsLastCheckValid {\n\t\tDiscoverEnd(instanceKey)\n\t\t\/\/ we've already discovered this one. Skip!\n\t\treturn\n\t}\n\tdiscoveriesCounter.Inc(1)\n\t\/\/ First we've ever heard of this instance. Continue investigation:\n\tinstance, err = inst.ReadTopologyInstance(&instanceKey)\n\t\/\/ panic can occur (IO stuff). Therefore it may happen\n\t\/\/ that instance is nil. Check it.\n\tif instance == nil {\n\t\tDiscoverEnd(instanceKey)\n\t\tfailedDiscoveriesCounter.Inc(1)\n\t\tlog.Warningf(\"discoverInstance(%+v) instance is nil in %.3fs, error=%+v\", instanceKey, time.Since(start).Seconds(), err)\n\t\treturn\n\t}\n\n\tDiscoverEnd(instanceKey)\n\tlog.Debugf(\"Discovered host: %+v, master: %+v, version: %+v in %.3fs\", instance.Key, instance.MasterKey, instance.Version, time.Since(start).Seconds())\n\n\tif atomic.LoadInt64(&isElectedNode) == 0 {\n\t\t\/\/ Maybe this node was elected before, but isn't elected anymore.\n\t\t\/\/ If not elected, stop drilling up\/down the topology\n\t\treturn\n\t}\n\n\t\/\/ Investigate master and slaves asynchronously to ensure we\n\t\/\/ do not block processing other instances while adding these servers\n\t\/\/ to the queue.\n\n\t\/\/ Investigate slaves:\n\tfor _, slaveKey := range instance.SlaveHosts.GetInstanceKeys() {\n\t\tslaveKey := slaveKey\n\t\tif slaveKey.IsValid() {\n\t\t\tdiscoveryInstanceKeys <- slaveKey\n\t\t}\n\t}\n\t\/\/ Investigate master:\n\tif instance.MasterKey.IsValid() {\n\t\tdiscoveryInstanceKeys <- instance.MasterKey\n\t}\n}\n\n\/\/ ContinuousDiscovery starts an asynchronuous infinite discovery process where instances are\n\/\/ periodically investigated and their status captured, and long since unseen instances are\n\/\/ purged and forgotten.\nfunc ContinuousDiscovery() {\n\tif config.Config.DatabaselessMode__experimental {\n\t\tlog.Fatal(\"Cannot execute continuous mode in databaseless mode\")\n\t}\n\n\tlog.Infof(\"Starting continuous discovery\")\n\trecentDiscoveryOperationKeys = cache.New(time.Duration(config.Config.InstancePollSeconds)*time.Second, time.Second)\n\n\tinst.LoadHostnameResolveCache()\n\tgo handleDiscoveryRequests()\n\n\tdiscoveryTick := time.Tick(time.Duration(config.Config.GetDiscoveryPollSeconds()) * time.Second)\n\tinstancePollTick := time.Tick(time.Duration(config.Config.InstancePollSeconds) * time.Second)\n\tcaretakingTick := time.Tick(time.Minute)\n\trecoveryTick := time.Tick(time.Duration(config.Config.RecoveryPollSeconds) * time.Second)\n\tvar snapshotTopologiesTick <-chan time.Time\n\tif config.Config.SnapshotTopologiesIntervalHours > 0 {\n\t\tsnapshotTopologiesTick = time.Tick(time.Duration(config.Config.SnapshotTopologiesIntervalHours) * time.Hour)\n\t}\n\n\tgo ometrics.InitGraphiteMetrics()\n\tgo acceptSignals()\n\n\tif *config.RuntimeCLIFlags.GrabElection {\n\t\tprocess.GrabElection()\n\t}\n\tfor {\n\t\tselect {\n\t\tcase <-discoveryTick:\n\t\t\tgo func() {\n\t\t\t\twasAlreadyElected := atomic.LoadInt64(&isElectedNode)\n\t\t\t\tmyIsElectedNode, err := process.AttemptElection()\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errore(err)\n\t\t\t\t}\n\t\t\t\tif myIsElectedNode {\n\t\t\t\t\tatomic.StoreInt64(&isElectedNode, 1)\n\t\t\t\t} else {\n\t\t\t\t\tatomic.StoreInt64(&isElectedNode, 0)\n\t\t\t\t}\n\n\t\t\t\tif myIsElectedNode {\n\t\t\t\t\tinstanceKeys, err := inst.ReadOutdatedInstanceKeys()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Errore(err)\n\t\t\t\t\t}\n\n\t\t\t\t\tlog.Debugf(\"outdated keys: %+v\", instanceKeys)\n\t\t\t\t\tfor _, instanceKey := range instanceKeys {\n\t\t\t\t\t\tinstanceKey := instanceKey\n\n\t\t\t\t\t\tgo func() {\n\t\t\t\t\t\t\tif instanceKey.IsValid() {\n\t\t\t\t\t\t\t\tdiscoveryInstanceKeys <- instanceKey\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}()\n\t\t\t\t\t}\n\t\t\t\t\tif wasAlreadyElected == 0 {\n\t\t\t\t\t\t\/\/ Just turned to be leader!\n\t\t\t\t\t\tgo process.RegisterNode(\"\", \"\", false)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\thostname, token, _, err := process.ElectedNode()\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tlog.Debugf(\"Inactive node. Active node is: %v[%v]; polling\", hostname, token)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlog.Debugf(\"Inactive node. Unable to determine active node: %v; polling\", err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}()\n\t\tcase <-instancePollTick:\n\t\t\tgo func() {\n\t\t\t\t\/\/ This tick does NOT do instance poll (these are handled by the oversmapling discoveryTick)\n\t\t\t\t\/\/ But rather should invoke such routinely operations that need to be as (or roughly as) frequent\n\t\t\t\t\/\/ as instance poll\n\t\t\t\tif atomic.LoadInt64(&isElectedNode) == 1 {\n\t\t\t\t\tgo inst.UpdateInstanceRecentRelaylogHistory()\n\t\t\t\t\tgo inst.RecordInstanceCoordinatesHistory()\n\t\t\t\t}\n\t\t\t}()\n\t\tcase <-caretakingTick:\n\t\t\t\/\/ Various periodic internal maintenance tasks\n\t\t\tgo func() {\n\t\t\t\tif atomic.LoadInt64(&isElectedNode) == 1 {\n\t\t\t\t\tgo inst.RecordInstanceBinlogFileHistory()\n\t\t\t\t\tgo inst.ForgetLongUnseenInstances()\n\t\t\t\t\tgo inst.ForgetUnseenInstancesDifferentlyResolved()\n\t\t\t\t\tgo inst.ForgetExpiredHostnameResolves()\n\t\t\t\t\tgo inst.DeleteInvalidHostnameResolves()\n\t\t\t\t\tgo inst.ReviewUnseenInstances()\n\t\t\t\t\tgo inst.InjectUnseenMasters()\n\t\t\t\t\tgo inst.ResolveUnknownMasterHostnameResolves()\n\t\t\t\t\tgo inst.UpdateClusterAliases()\n\t\t\t\t\tgo inst.ExpireMaintenance()\n\t\t\t\t\tgo inst.ExpireDowntime()\n\t\t\t\t\tgo inst.ExpireCandidateInstances()\n\t\t\t\t\tgo inst.ExpireHostnameUnresolve()\n\t\t\t\t\tgo inst.ExpireClusterDomainName()\n\t\t\t\t\tgo inst.ExpireAudit()\n\t\t\t\t\tgo inst.ExpireMasterPositionEquivalence()\n\t\t\t\t\tgo inst.ExpirePoolInstances()\n\t\t\t\t\tgo inst.FlushNontrivialResolveCacheToDatabase()\n\t\t\t\t\tgo process.ExpireNodesHistory()\n\t\t\t\t\tgo process.ExpireAccessTokens()\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ Take this opportunity to refresh yourself\n\t\t\t\t\tgo inst.LoadHostnameResolveCache()\n\t\t\t\t}\n\t\t\t}()\n\t\tcase <-recoveryTick:\n\t\t\tgo func() {\n\t\t\t\tif atomic.LoadInt64(&isElectedNode) == 1 {\n\t\t\t\t\tgo ClearActiveFailureDetections()\n\t\t\t\t\tgo ClearActiveRecoveries()\n\t\t\t\t\tgo ExpireBlockedRecoveries()\n\t\t\t\t\tgo AcknowledgeCrashedRecoveries()\n\t\t\t\t\tgo inst.ExpireInstanceAnalysisChangelog()\n\t\t\t\t\tgo CheckAndRecover(nil, nil, false)\n\t\t\t\t}\n\t\t\t}()\n\t\tcase <-snapshotTopologiesTick:\n\t\t\tgo func() {\n\t\t\t\tgo inst.SnapshotTopologies()\n\t\t\t}()\n\t\t}\n\t}\n}\n\nfunc pollAgent(hostname string) error {\n\tpolledAgent, err := agent.GetAgent(hostname)\n\tagent.UpdateAgentLastChecked(hostname)\n\n\tif err != nil {\n\t\treturn log.Errore(err)\n\t}\n\n\terr = agent.UpdateAgentInfo(hostname, polledAgent)\n\tif err != nil {\n\t\treturn log.Errore(err)\n\t}\n\n\treturn nil\n}\n\n\/\/ ContinuousAgentsPoll starts an asynchronuous infinite process where agents are\n\/\/ periodically investigated and their status captured, and long since unseen agents are\n\/\/ purged and forgotten.\nfunc ContinuousAgentsPoll() {\n\tlog.Infof(\"Starting continuous agents poll\")\n\n\tgo discoverSeededAgents()\n\n\ttick := time.Tick(time.Duration(config.Config.GetDiscoveryPollSeconds()) * time.Second)\n\tcaretakingTick := time.Tick(time.Hour)\n\tfor range tick {\n\t\tagentsHosts, _ := agent.ReadOutdatedAgentsHosts()\n\t\tlog.Debugf(\"outdated agents hosts: %+v\", agentsHosts)\n\t\tfor _, hostname := range agentsHosts {\n\t\t\tgo pollAgent(hostname)\n\t\t}\n\t\t\/\/ See if we should also forget agents (lower frequency)\n\t\tselect {\n\t\tcase <-caretakingTick:\n\t\t\tagent.ForgetLongUnseenAgents()\n\t\t\tagent.FailStaleSeeds()\n\t\tdefault:\n\t\t}\n\t}\n}\n\nfunc discoverSeededAgents() {\n\tfor seededAgent := range agent.SeededAgents {\n\t\tinstanceKey := &inst.InstanceKey{Hostname: seededAgent.Hostname, Port: int(seededAgent.MySQLPort)}\n\t\tgo inst.ReadTopologyInstance(instanceKey)\n\t}\n}\nrecentDiscoveryOperationKeys acts as a mutex not a cache which expires\/*\n Copyright 2014 Outbrain Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\npackage logic\n\nimport (\n\t\"os\"\n\t\"os\/signal\"\n\t\"sync\/atomic\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com\/outbrain\/golib\/log\"\n\t\"github.com\/outbrain\/orchestrator\/go\/agent\"\n\t\"github.com\/outbrain\/orchestrator\/go\/config\"\n\t\"github.com\/outbrain\/orchestrator\/go\/inst\"\n\tometrics \"github.com\/outbrain\/orchestrator\/go\/metrics\"\n\t\"github.com\/outbrain\/orchestrator\/go\/process\"\n\t\"github.com\/pmylund\/go-cache\"\n\t\"github.com\/rcrowley\/go-metrics\"\n)\n\nconst (\n\tdiscoveryInstanceChannelCapacity = 5 \/\/ size here not critical as channel read by separate go routines.\n)\n\n\/\/ discoveryInstanceKeys is a channel of instanceKey-s that were requested for discovery.\n\/\/ It can be continuously updated as discovery process progresses.\nvar discoveryInstanceKeys = make(chan inst.InstanceKey, discoveryInstanceChannelCapacity)\n\nvar discoveriesCounter = metrics.NewCounter()\nvar failedDiscoveriesCounter = metrics.NewCounter()\nvar discoveryQueueLengthGauge = metrics.NewGauge()\nvar discoveryRecentCountGauge = metrics.NewGauge()\nvar isElectedGauge = metrics.NewGauge()\n\nvar isElectedNode int64 = 0\n\nvar recentDiscoveryOperationKeys *cache.Cache\n\nfunc init() {\n\tmetrics.Register(\"discoveries.attempt\", discoveriesCounter)\n\tmetrics.Register(\"discoveries.fail\", failedDiscoveriesCounter)\n\tmetrics.Register(\"discoveries.queue_length\", discoveryQueueLengthGauge)\n\tmetrics.Register(\"discoveries.recent_count\", discoveryRecentCountGauge)\n\tmetrics.Register(\"elect.is_elected\", isElectedGauge)\n\n\tometrics.OnGraphiteTick(func() { discoveryQueueLengthGauge.Update(int64(len(discoveryInstanceKeys))) })\n\tometrics.OnGraphiteTick(func() {\n\t\tif recentDiscoveryOperationKeys == nil {\n\t\t\treturn\n\t\t}\n\t\tdiscoveryRecentCountGauge.Update(int64(recentDiscoveryOperationKeys.ItemCount()))\n\t})\n\tometrics.OnGraphiteTick(func() { isElectedGauge.Update(int64(atomic.LoadInt64(&isElectedNode))) })\n}\n\n\/\/ acceptSignals registers for OS signals\nfunc acceptSignals() {\n\tc := make(chan os.Signal, 1)\n\n\tsignal.Notify(c, syscall.SIGHUP)\n\tgo func() {\n\t\tfor sig := range c {\n\t\t\tswitch sig {\n\t\t\tcase syscall.SIGHUP:\n\t\t\t\tlog.Debugf(\"Received SIGHUP. Reloading configuration\")\n\t\t\t\tconfig.Reload()\n\t\t\t\tinst.AuditOperation(\"reload-configuration\", nil, \"Triggered via SIGHUP\")\n\t\t\t}\n\t\t}\n\t}()\n}\n\n\/\/ handleDiscoveryRequests iterates the discoveryInstanceKeys channel\n\/\/ and calls upon instance discovery per entry. These requests will\n\/\/ be handled by separate go routines so concurrency should be high.\nfunc handleDiscoveryRequests() {\n\tfor instanceKey := range discoveryInstanceKeys {\n\t\t\/\/ Possibly this used to be the elected node, but has been demoted, while still\n\t\t\/\/ the queue is full.\n\t\t\/\/ Just don't process the queue when not elected.\n\t\tif atomic.LoadInt64(&isElectedNode) == 1 {\n\t\t\tgo discoverInstance(instanceKey)\n\t\t} else {\n\t\t\tlog.Debugf(\"Node apparently demoted. Skipping discovery of %+v. Remaining queue size: %+v\", instanceKey, len(discoveryInstanceKeys))\n\t\t}\n\t}\n}\n\n\/\/ discoverInstance will attempt to discover an instance (unless it is\n\/\/ already up to date) and will list down its master and slaves (if any)\n\/\/ for further discovery.\nfunc discoverInstance(instanceKey inst.InstanceKey) {\n\tstart := time.Now()\n\n\tinstanceKey.Formalize()\n\tif !instanceKey.IsValid() {\n\t\treturn\n\t}\n\n\tDiscoverStart(instanceKey)\n\tif existsInCacheError := recentDiscoveryOperationKeys.Add(instanceKey.DisplayString(), true, cache.DefaultExpiration); existsInCacheError != nil {\n\t\tDiscoverEnd(instanceKey)\n\t\t\/\/ Just recently attempted\n\t\treturn\n\t}\n\n\tinstance, found, err := inst.ReadInstance(&instanceKey)\n\n\tif found && instance.IsUpToDate && instance.IsLastCheckValid {\n\t\trecentDiscoveryOperationKeys.Delete(instanceKey.DisplayString())\n\t\tDiscoverEnd(instanceKey)\n\t\t\/\/ we've already discovered this one. Skip!\n\t\treturn\n\t}\n\tdiscoveriesCounter.Inc(1)\n\t\/\/ First we've ever heard of this instance. Continue investigation:\n\tinstance, err = inst.ReadTopologyInstance(&instanceKey)\n\t\/\/ panic can occur (IO stuff). Therefore it may happen\n\t\/\/ that instance is nil. Check it.\n\tif instance == nil {\n\t\trecentDiscoveryOperationKeys.Delete(instanceKey.DisplayString())\n\t\tDiscoverEnd(instanceKey)\n\t\tfailedDiscoveriesCounter.Inc(1)\n\t\tlog.Warningf(\"discoverInstance(%+v) instance is nil in %.3fs, error=%+v\", instanceKey, time.Since(start).Seconds(), err)\n\t\treturn\n\t}\n\n\trecentDiscoveryOperationKeys.Delete(instanceKey.DisplayString())\n\tDiscoverEnd(instanceKey)\n\tlog.Debugf(\"Discovered host: %+v, master: %+v, version: %+v in %.3fs\", instance.Key, instance.MasterKey, instance.Version, time.Since(start).Seconds())\n\n\tif atomic.LoadInt64(&isElectedNode) == 0 {\n\t\t\/\/ Maybe this node was elected before, but isn't elected anymore.\n\t\t\/\/ If not elected, stop drilling up\/down the topology\n\t\treturn\n\t}\n\n\t\/\/ Investigate master and slaves asynchronously to ensure we\n\t\/\/ do not block processing other instances while adding these servers\n\t\/\/ to the queue.\n\n\t\/\/ Investigate slaves:\n\tfor _, slaveKey := range instance.SlaveHosts.GetInstanceKeys() {\n\t\tslaveKey := slaveKey\n\t\tif slaveKey.IsValid() {\n\t\t\tdiscoveryInstanceKeys <- slaveKey\n\t\t}\n\t}\n\t\/\/ Investigate master:\n\tif instance.MasterKey.IsValid() {\n\t\tdiscoveryInstanceKeys <- instance.MasterKey\n\t}\n}\n\n\/\/ ContinuousDiscovery starts an asynchronuous infinite discovery process where instances are\n\/\/ periodically investigated and their status captured, and long since unseen instances are\n\/\/ purged and forgotten.\nfunc ContinuousDiscovery() {\n\tif config.Config.DatabaselessMode__experimental {\n\t\tlog.Fatal(\"Cannot execute continuous mode in databaseless mode\")\n\t}\n\n\tlog.Infof(\"Starting continuous discovery\")\n\trecentDiscoveryOperationKeys = cache.New(time.Duration(config.Config.InstancePollSeconds)*time.Second, time.Second)\n\n\tinst.LoadHostnameResolveCache()\n\tgo handleDiscoveryRequests()\n\n\tdiscoveryTick := time.Tick(time.Duration(config.Config.GetDiscoveryPollSeconds()) * time.Second)\n\tinstancePollTick := time.Tick(time.Duration(config.Config.InstancePollSeconds) * time.Second)\n\tcaretakingTick := time.Tick(time.Minute)\n\trecoveryTick := time.Tick(time.Duration(config.Config.RecoveryPollSeconds) * time.Second)\n\tvar snapshotTopologiesTick <-chan time.Time\n\tif config.Config.SnapshotTopologiesIntervalHours > 0 {\n\t\tsnapshotTopologiesTick = time.Tick(time.Duration(config.Config.SnapshotTopologiesIntervalHours) * time.Hour)\n\t}\n\n\tgo ometrics.InitGraphiteMetrics()\n\tgo acceptSignals()\n\n\tif *config.RuntimeCLIFlags.GrabElection {\n\t\tprocess.GrabElection()\n\t}\n\tfor {\n\t\tselect {\n\t\tcase <-discoveryTick:\n\t\t\tgo func() {\n\t\t\t\twasAlreadyElected := atomic.LoadInt64(&isElectedNode)\n\t\t\t\tmyIsElectedNode, err := process.AttemptElection()\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Errore(err)\n\t\t\t\t}\n\t\t\t\tif myIsElectedNode {\n\t\t\t\t\tatomic.StoreInt64(&isElectedNode, 1)\n\t\t\t\t} else {\n\t\t\t\t\tatomic.StoreInt64(&isElectedNode, 0)\n\t\t\t\t}\n\n\t\t\t\tif myIsElectedNode {\n\t\t\t\t\tinstanceKeys, err := inst.ReadOutdatedInstanceKeys()\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Errore(err)\n\t\t\t\t\t}\n\n\t\t\t\t\tlog.Debugf(\"outdated keys: %+v\", instanceKeys)\n\t\t\t\t\tfor _, instanceKey := range instanceKeys {\n\t\t\t\t\t\tinstanceKey := instanceKey\n\n\t\t\t\t\t\tgo func() {\n\t\t\t\t\t\t\tif instanceKey.IsValid() {\n\t\t\t\t\t\t\t\tdiscoveryInstanceKeys <- instanceKey\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}()\n\t\t\t\t\t}\n\t\t\t\t\tif wasAlreadyElected == 0 {\n\t\t\t\t\t\t\/\/ Just turned to be leader!\n\t\t\t\t\t\tgo process.RegisterNode(\"\", \"\", false)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\thostname, token, _, err := process.ElectedNode()\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tlog.Debugf(\"Inactive node. Active node is: %v[%v]; polling\", hostname, token)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlog.Debugf(\"Inactive node. Unable to determine active node: %v; polling\", err)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}()\n\t\tcase <-instancePollTick:\n\t\t\tgo func() {\n\t\t\t\t\/\/ This tick does NOT do instance poll (these are handled by the oversmapling discoveryTick)\n\t\t\t\t\/\/ But rather should invoke such routinely operations that need to be as (or roughly as) frequent\n\t\t\t\t\/\/ as instance poll\n\t\t\t\tif atomic.LoadInt64(&isElectedNode) == 1 {\n\t\t\t\t\tgo inst.UpdateInstanceRecentRelaylogHistory()\n\t\t\t\t\tgo inst.RecordInstanceCoordinatesHistory()\n\t\t\t\t}\n\t\t\t}()\n\t\tcase <-caretakingTick:\n\t\t\t\/\/ Various periodic internal maintenance tasks\n\t\t\tgo func() {\n\t\t\t\tif atomic.LoadInt64(&isElectedNode) == 1 {\n\t\t\t\t\tgo inst.RecordInstanceBinlogFileHistory()\n\t\t\t\t\tgo inst.ForgetLongUnseenInstances()\n\t\t\t\t\tgo inst.ForgetUnseenInstancesDifferentlyResolved()\n\t\t\t\t\tgo inst.ForgetExpiredHostnameResolves()\n\t\t\t\t\tgo inst.DeleteInvalidHostnameResolves()\n\t\t\t\t\tgo inst.ReviewUnseenInstances()\n\t\t\t\t\tgo inst.InjectUnseenMasters()\n\t\t\t\t\tgo inst.ResolveUnknownMasterHostnameResolves()\n\t\t\t\t\tgo inst.UpdateClusterAliases()\n\t\t\t\t\tgo inst.ExpireMaintenance()\n\t\t\t\t\tgo inst.ExpireDowntime()\n\t\t\t\t\tgo inst.ExpireCandidateInstances()\n\t\t\t\t\tgo inst.ExpireHostnameUnresolve()\n\t\t\t\t\tgo inst.ExpireClusterDomainName()\n\t\t\t\t\tgo inst.ExpireAudit()\n\t\t\t\t\tgo inst.ExpireMasterPositionEquivalence()\n\t\t\t\t\tgo inst.ExpirePoolInstances()\n\t\t\t\t\tgo inst.FlushNontrivialResolveCacheToDatabase()\n\t\t\t\t\tgo process.ExpireNodesHistory()\n\t\t\t\t\tgo process.ExpireAccessTokens()\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ Take this opportunity to refresh yourself\n\t\t\t\t\tgo inst.LoadHostnameResolveCache()\n\t\t\t\t}\n\t\t\t}()\n\t\tcase <-recoveryTick:\n\t\t\tgo func() {\n\t\t\t\tif atomic.LoadInt64(&isElectedNode) == 1 {\n\t\t\t\t\tgo ClearActiveFailureDetections()\n\t\t\t\t\tgo ClearActiveRecoveries()\n\t\t\t\t\tgo ExpireBlockedRecoveries()\n\t\t\t\t\tgo AcknowledgeCrashedRecoveries()\n\t\t\t\t\tgo inst.ExpireInstanceAnalysisChangelog()\n\t\t\t\t\tgo CheckAndRecover(nil, nil, false)\n\t\t\t\t}\n\t\t\t}()\n\t\tcase <-snapshotTopologiesTick:\n\t\t\tgo func() {\n\t\t\t\tgo inst.SnapshotTopologies()\n\t\t\t}()\n\t\t}\n\t}\n}\n\nfunc pollAgent(hostname string) error {\n\tpolledAgent, err := agent.GetAgent(hostname)\n\tagent.UpdateAgentLastChecked(hostname)\n\n\tif err != nil {\n\t\treturn log.Errore(err)\n\t}\n\n\terr = agent.UpdateAgentInfo(hostname, polledAgent)\n\tif err != nil {\n\t\treturn log.Errore(err)\n\t}\n\n\treturn nil\n}\n\n\/\/ ContinuousAgentsPoll starts an asynchronuous infinite process where agents are\n\/\/ periodically investigated and their status captured, and long since unseen agents are\n\/\/ purged and forgotten.\nfunc ContinuousAgentsPoll() {\n\tlog.Infof(\"Starting continuous agents poll\")\n\n\tgo discoverSeededAgents()\n\n\ttick := time.Tick(time.Duration(config.Config.GetDiscoveryPollSeconds()) * time.Second)\n\tcaretakingTick := time.Tick(time.Hour)\n\tfor range tick {\n\t\tagentsHosts, _ := agent.ReadOutdatedAgentsHosts()\n\t\tlog.Debugf(\"outdated agents hosts: %+v\", agentsHosts)\n\t\tfor _, hostname := range agentsHosts {\n\t\t\tgo pollAgent(hostname)\n\t\t}\n\t\t\/\/ See if we should also forget agents (lower frequency)\n\t\tselect {\n\t\tcase <-caretakingTick:\n\t\t\tagent.ForgetLongUnseenAgents()\n\t\t\tagent.FailStaleSeeds()\n\t\tdefault:\n\t\t}\n\t}\n}\n\nfunc discoverSeededAgents() {\n\tfor seededAgent := range agent.SeededAgents {\n\t\tinstanceKey := &inst.InstanceKey{Hostname: seededAgent.Hostname, Port: int(seededAgent.MySQLPort)}\n\t\tgo inst.ReadTopologyInstance(instanceKey)\n\t}\n}\n<|endoftext|>"} {"text":"package nfs\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"syscall\"\n\t\"time\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/pborman\/uuid\"\n\n\t\"github.com\/portworx\/kvdb\"\n\n\t\"github.com\/libopenstorage\/openstorage\/api\"\n\t\"github.com\/libopenstorage\/openstorage\/volume\"\n)\n\nconst (\n\tName = \"nfs\"\n\tType = volume.File\n\tNfsDBKey = \"OpenStorageNFSKey\"\n\tnfsMountPath = \"\/var\/lib\/openstorage\/nfs\/\"\n\tnfsBlockFile = \".blockdevice\"\n)\n\n\/\/ Implements the open storage volume interface.\ntype driver struct {\n\t*volume.DefaultEnumerator\n\tnfsServer string\n\tnfsPath string\n}\n\nfunc copyFile(source string, dest string) (err error) {\n\tsourcefile, err := os.Open(source)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer sourcefile.Close()\n\n\tdestfile, err := os.Create(dest)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer destfile.Close()\n\n\t_, err = io.Copy(destfile, sourcefile)\n\tif err == nil {\n\t\tsourceinfo, err := os.Stat(source)\n\t\tif err != nil {\n\t\t\terr = os.Chmod(dest, sourceinfo.Mode())\n\t\t}\n\n\t}\n\n\treturn\n}\n\nfunc copyDir(source string, dest string) (err error) {\n\t\/\/ get properties of source dir\n\tsourceinfo, err := os.Stat(source)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ create dest dir\n\n\terr = os.MkdirAll(dest, sourceinfo.Mode())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdirectory, _ := os.Open(source)\n\n\tobjects, err := directory.Readdir(-1)\n\n\tfor _, obj := range objects {\n\n\t\tsourcefilepointer := source + \"\/\" + obj.Name()\n\n\t\tdestinationfilepointer := dest + \"\/\" + obj.Name()\n\n\t\tif obj.IsDir() {\n\t\t\t\/\/ create sub-directories - recursively\n\t\t\terr = copyDir(sourcefilepointer, destinationfilepointer)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ perform copy\n\t\t\terr = copyFile(sourcefilepointer, destinationfilepointer)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t}\n\t\t}\n\n\t}\n\treturn\n}\n\nfunc Init(params volume.DriverParams) (volume.VolumeDriver, error) {\n\tpath, ok := params[\"path\"]\n\tif !ok {\n\t\treturn nil, errors.New(\"No NFS path provided\")\n\t}\n\n\tserver, ok := params[\"server\"]\n\tif !ok {\n\t\tlog.Printf(\"No NFS server provided, will attempt to bind mount %s\", path)\n\t} else {\n\t\tlog.Printf(\"NFS driver initializing with %s:%s \", server, path)\n\t}\n\n\tinst := &driver{\n\t\tDefaultEnumerator: volume.NewDefaultEnumerator(Name, kvdb.Instance()),\n\t\tnfsServer: server,\n\t\tnfsPath: path}\n\n\terr := os.MkdirAll(nfsMountPath, 0744)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ Mount the nfs server locally on a unique path.\n\tsyscall.Unmount(nfsMountPath, 0)\n\tif server != \"\" {\n\t\terr = syscall.Mount(\":\"+inst.nfsPath, nfsMountPath, \"nfs\", 0, \"nolock,addr=\"+inst.nfsServer)\n\t} else {\n\t\terr = syscall.Mount(inst.nfsPath, nfsMountPath, \"\", syscall.MS_BIND, \"\")\n\t}\n\tif err != nil {\n\t\tlog.Printf(\"Unable to mount %s:%s at %s (%+v)\", inst.nfsServer, inst.nfsPath, nfsMountPath, err)\n\t\treturn nil, err\n\t}\n\n\tvolumeInfo, err := inst.DefaultEnumerator.Enumerate(\n\t\tapi.VolumeLocator{},\n\t\tnil)\n\tif err == nil {\n\t\tfor _, info := range volumeInfo {\n\t\t\tif info.Status == \"\" {\n\t\t\t\tinfo.Status = api.Up\n\t\t\t\tinst.UpdateVol(&info)\n\t\t\t}\n\t\t}\n\t} else {\n\t\tlog.Println(\"Could not enumerate Volumes, \", err)\n\t}\n\n\tlog.Println(\"NFS initialized and driver mounted at: \", nfsMountPath)\n\treturn inst, nil\n}\n\nfunc (d *driver) String() string {\n\treturn Name\n}\n\nfunc (d *driver) Type() volume.DriverType {\n\treturn Type\n}\n\n\/\/ Status diagnostic information\nfunc (d *driver) Status() [][2]string {\n\treturn [][2]string{}\n}\n\nfunc (d *driver) Create(locator api.VolumeLocator, opt *api.CreateOptions, spec *api.VolumeSpec) (api.VolumeID, error) {\n\tvolumeID := uuid.New()\n\tvolumeID = strings.TrimSuffix(volumeID, \"\\n\")\n\n\t\/\/ Create a directory on the NFS server with this UUID.\n\terr := os.MkdirAll(nfsMountPath+volumeID, 0744)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn api.BadVolumeID, err\n\t}\n\n\tf, err := os.Create(nfsMountPath + volumeID + nfsBlockFile)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn api.BadVolumeID, err\n\t}\n\n\tdefer f.Close()\n\n\terr = f.Truncate(int64(spec.Size))\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn api.BadVolumeID, err\n\t}\n\n\tv := &api.Volume{\n\t\tID: api.VolumeID(volumeID),\n\t\tLocator: locator,\n\t\tCtime: time.Now(),\n\t\tSpec: spec,\n\t\tLastScan: time.Now(),\n\t\tFormat: \"nfs\",\n\t\tState: api.VolumeAvailable,\n\t\tStatus: api.Up,\n\t\tDevicePath: path.Join(nfsMountPath, string(volumeID), nfsBlockFile),\n\t}\n\n\terr = d.CreateVol(v)\n\tif err != nil {\n\t\treturn api.BadVolumeID, err\n\t}\n\n\terr = d.UpdateVol(v)\n\n\treturn v.ID, err\n}\n\nfunc (d *driver) Delete(volumeID api.VolumeID) error {\n\tv, err := d.GetVol(volumeID)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\n\t\/\/ Delete the simulated block volume\n\tos.Remove(v.DevicePath)\n\n\t\/\/ Delete the directory on the nfs server.\n\tos.RemoveAll(path.Join(nfsMountPath, string(volumeID)))\n\n\terr = d.DeleteVol(volumeID)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (d *driver) Mount(volumeID api.VolumeID, mountpath string) error {\n\tv, err := d.GetVol(volumeID)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\tsyscall.Unmount(mountpath, 0)\n\terr = syscall.Mount(path.Join(nfsMountPath, string(volumeID)), mountpath, string(v.Spec.Format), syscall.MS_BIND, \"\")\n\tif err != nil {\n\t\tlog.Printf(\"Cannot mount %s at %s because %+v\",\n\t\t\tpath.Join(nfsMountPath, string(volumeID)), mountpath, err)\n\t\treturn err\n\t}\n\n\tv.AttachPath = mountpath\n\terr = d.UpdateVol(v)\n\n\treturn err\n}\n\nfunc (d *driver) Unmount(volumeID api.VolumeID, mountpath string) error {\n\tv, err := d.GetVol(volumeID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif v.AttachPath == \"\" {\n\t\treturn fmt.Errorf(\"Device %v not mounted\", volumeID)\n\t}\n\terr = syscall.Unmount(v.AttachPath, 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\tv.AttachPath = \"\"\n\terr = d.UpdateVol(v)\n\treturn err\n}\n\nfunc (d *driver) Snapshot(volumeID api.VolumeID, readonly bool, locator api.VolumeLocator) (api.VolumeID, error) {\n\tvolIDs := make([]api.VolumeID, 1)\n\tvolIDs[0] = volumeID\n\tvols, err := d.Inspect(volIDs)\n\tif err != nil {\n\t\treturn api.BadVolumeID, nil\n\t}\n\n\tnewVolumeID, err := d.Create(locator, nil, vols[0].Spec)\n\tif err != nil {\n\t\treturn api.BadVolumeID, nil\n\t}\n\n\t\/\/ NFS does not support snapshots, so just copy the files.\n\terr = copyDir(nfsMountPath+string(volumeID), nfsMountPath+string(newVolumeID))\n\tif err != nil {\n\t\td.Delete(newVolumeID)\n\t\treturn api.BadVolumeID, nil\n\t}\n\n\treturn newVolumeID, nil\n}\n\nfunc (d *driver) Attach(volumeID api.VolumeID) (string, error) {\n\treturn path.Join(nfsMountPath, string(volumeID), nfsBlockFile), nil\n}\n\nfunc (d *driver) Format(volumeID api.VolumeID) error {\n\treturn nil\n}\n\nfunc (d *driver) Detach(volumeID api.VolumeID) error {\n\treturn nil\n}\n\nfunc (d *driver) Stats(volumeID api.VolumeID) (api.Stats, error) {\n\treturn api.Stats{}, volume.ErrNotSupported\n}\n\nfunc (d *driver) Alerts(volumeID api.VolumeID) (api.Alerts, error) {\n\treturn api.Alerts{}, volume.ErrNotSupported\n}\n\nfunc (d *driver) Shutdown() {\n\tlog.Printf(\"%s Shutting down\", Name)\n\tsyscall.Unmount(nfsMountPath, 0)\n}\n\nfunc init() {\n\t\/\/ Register ourselves as an openstorage volume driver.\n\tvolume.Register(Name, Init)\n}\nload nfs mounts on startup.package nfs\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\"\n\t\"strings\"\n\t\"syscall\"\n\t\"time\"\n\n\tlog \"github.com\/Sirupsen\/logrus\"\n\t\"github.com\/pborman\/uuid\"\n\n\t\"github.com\/portworx\/kvdb\"\n\n\t\"github.com\/libopenstorage\/openstorage\/api\"\n\t\"github.com\/libopenstorage\/openstorage\/pkg\/mount\"\n\t\"github.com\/libopenstorage\/openstorage\/volume\"\n)\n\nconst (\n\tName = \"nfs\"\n\tType = volume.File\n\tNfsDBKey = \"OpenStorageNFSKey\"\n\tnfsMountPath = \"\/var\/lib\/openstorage\/nfs\/\"\n\tnfsBlockFile = \".blockdevice\"\n)\n\n\/\/ Implements the open storage volume interface.\ntype driver struct {\n\t*volume.DefaultEnumerator\n\tnfsServer string\n\tnfsPath string\n\tmounter mount.Manager\n}\n\nfunc copyFile(source string, dest string) (err error) {\n\tsourcefile, err := os.Open(source)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer sourcefile.Close()\n\n\tdestfile, err := os.Create(dest)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer destfile.Close()\n\n\t_, err = io.Copy(destfile, sourcefile)\n\tif err == nil {\n\t\tsourceinfo, err := os.Stat(source)\n\t\tif err != nil {\n\t\t\terr = os.Chmod(dest, sourceinfo.Mode())\n\t\t}\n\n\t}\n\n\treturn\n}\n\nfunc copyDir(source string, dest string) (err error) {\n\t\/\/ get properties of source dir\n\tsourceinfo, err := os.Stat(source)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t\/\/ create dest dir\n\n\terr = os.MkdirAll(dest, sourceinfo.Mode())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdirectory, _ := os.Open(source)\n\n\tobjects, err := directory.Readdir(-1)\n\n\tfor _, obj := range objects {\n\n\t\tsourcefilepointer := source + \"\/\" + obj.Name()\n\n\t\tdestinationfilepointer := dest + \"\/\" + obj.Name()\n\n\t\tif obj.IsDir() {\n\t\t\t\/\/ create sub-directories - recursively\n\t\t\terr = copyDir(sourcefilepointer, destinationfilepointer)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ perform copy\n\t\t\terr = copyFile(sourcefilepointer, destinationfilepointer)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err)\n\t\t\t}\n\t\t}\n\n\t}\n\treturn\n}\n\nfunc Init(params volume.DriverParams) (volume.VolumeDriver, error) {\n\tpath, ok := params[\"path\"]\n\tif !ok {\n\t\treturn nil, errors.New(\"No NFS path provided\")\n\t}\n\n\tserver, ok := params[\"server\"]\n\tif !ok {\n\t\tlog.Printf(\"No NFS server provided, will attempt to bind mount %s\", path)\n\t} else {\n\t\tlog.Printf(\"NFS driver initializing with %s:%s \", server, path)\n\t}\n\n\t\/\/ Create a mount manager for this NFS server. Blank sever is OK.\n\tmounter, err := mount.New(mount.NFSMount, server)\n\tif err != nil {\n\t\tlog.Warnf(\"Failed to create mount manager for server: %v (%v)\", server, err)\n\t\treturn nil, err\n\t}\n\n\tinst := &driver{\n\t\tDefaultEnumerator: volume.NewDefaultEnumerator(Name, kvdb.Instance()),\n\t\tnfsServer: server,\n\t\tnfsPath: path,\n\t\tmounter: mounter,\n\t}\n\n\terr = os.MkdirAll(nfsMountPath, 0744)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsrc := inst.nfsPath\n\tif server != \"\" {\n\t\tsrc = \":\" + inst.nfsPath\n\t}\n\n\t\/\/ If src is already mounted at dest, leave it be.\n\tmountExists, err := mounter.Exists(src, nfsMountPath)\n\tif !mountExists {\n\t\t\/\/ Mount the nfs server locally on a unique path.\n\t\tsyscall.Unmount(nfsMountPath, 0)\n\t\tif server != \"\" {\n\t\t\terr = syscall.Mount(src, nfsMountPath, \"nfs\", 0, \"nolock,addr=\"+inst.nfsServer)\n\t\t} else {\n\t\t\terr = syscall.Mount(src, nfsMountPath, \"\", syscall.MS_BIND, \"\")\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Unable to mount %s:%s at %s (%+v)\", inst.nfsServer, inst.nfsPath, nfsMountPath, err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tvolumeInfo, err := inst.DefaultEnumerator.Enumerate(\n\t\tapi.VolumeLocator{},\n\t\tnil)\n\tif err == nil {\n\t\tfor _, info := range volumeInfo {\n\t\t\tif info.Status == \"\" {\n\t\t\t\tinfo.Status = api.Up\n\t\t\t\tinst.UpdateVol(&info)\n\t\t\t}\n\t\t}\n\t} else {\n\t\tlog.Println(\"Could not enumerate Volumes, \", err)\n\t}\n\n\tlog.Println(\"NFS initialized and driver mounted at: \", nfsMountPath)\n\treturn inst, nil\n}\n\nfunc (d *driver) String() string {\n\treturn Name\n}\n\nfunc (d *driver) Type() volume.DriverType {\n\treturn Type\n}\n\n\/\/ Status diagnostic information\nfunc (d *driver) Status() [][2]string {\n\treturn [][2]string{}\n}\n\nfunc (d *driver) Create(locator api.VolumeLocator, opt *api.CreateOptions, spec *api.VolumeSpec) (api.VolumeID, error) {\n\tvolumeID := uuid.New()\n\tvolumeID = strings.TrimSuffix(volumeID, \"\\n\")\n\n\t\/\/ Create a directory on the NFS server with this UUID.\n\terr := os.MkdirAll(nfsMountPath+volumeID, 0744)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn api.BadVolumeID, err\n\t}\n\n\tf, err := os.Create(nfsMountPath + volumeID + nfsBlockFile)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn api.BadVolumeID, err\n\t}\n\n\tdefer f.Close()\n\n\terr = f.Truncate(int64(spec.Size))\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn api.BadVolumeID, err\n\t}\n\n\tv := &api.Volume{\n\t\tID: api.VolumeID(volumeID),\n\t\tLocator: locator,\n\t\tCtime: time.Now(),\n\t\tSpec: spec,\n\t\tLastScan: time.Now(),\n\t\tFormat: \"nfs\",\n\t\tState: api.VolumeAvailable,\n\t\tStatus: api.Up,\n\t\tDevicePath: path.Join(nfsMountPath, string(volumeID), nfsBlockFile),\n\t}\n\n\terr = d.CreateVol(v)\n\tif err != nil {\n\t\treturn api.BadVolumeID, err\n\t}\n\n\terr = d.UpdateVol(v)\n\n\treturn v.ID, err\n}\n\nfunc (d *driver) Delete(volumeID api.VolumeID) error {\n\tv, err := d.GetVol(volumeID)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\n\t\/\/ Delete the simulated block volume\n\tos.Remove(v.DevicePath)\n\n\t\/\/ Delete the directory on the nfs server.\n\tos.RemoveAll(path.Join(nfsMountPath, string(volumeID)))\n\n\terr = d.DeleteVol(volumeID)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (d *driver) Mount(volumeID api.VolumeID, mountpath string) error {\n\tv, err := d.GetVol(volumeID)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\n\tsrcPath := path.Join(\":\", d.nfsPath, string(volumeID))\n\tmountExists, err := d.mounter.Exists(srcPath, mountpath)\n\tif !mountExists {\n\t\tsyscall.Unmount(mountpath, 0)\n\t\terr = syscall.Mount(path.Join(nfsMountPath, string(volumeID)), mountpath, string(v.Spec.Format), syscall.MS_BIND, \"\")\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Cannot mount %s at %s because %+v\",\n\t\t\t\tpath.Join(nfsMountPath, string(volumeID)), mountpath, err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\tv.AttachPath = mountpath\n\terr = d.UpdateVol(v)\n\n\treturn err\n}\n\nfunc (d *driver) Unmount(volumeID api.VolumeID, mountpath string) error {\n\tv, err := d.GetVol(volumeID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif v.AttachPath == \"\" {\n\t\treturn fmt.Errorf(\"Device %v not mounted\", volumeID)\n\t}\n\terr = syscall.Unmount(v.AttachPath, 0)\n\tif err != nil {\n\t\treturn err\n\t}\n\tv.AttachPath = \"\"\n\terr = d.UpdateVol(v)\n\treturn err\n}\n\nfunc (d *driver) Snapshot(volumeID api.VolumeID, readonly bool, locator api.VolumeLocator) (api.VolumeID, error) {\n\tvolIDs := make([]api.VolumeID, 1)\n\tvolIDs[0] = volumeID\n\tvols, err := d.Inspect(volIDs)\n\tif err != nil {\n\t\treturn api.BadVolumeID, nil\n\t}\n\n\tnewVolumeID, err := d.Create(locator, nil, vols[0].Spec)\n\tif err != nil {\n\t\treturn api.BadVolumeID, nil\n\t}\n\n\t\/\/ NFS does not support snapshots, so just copy the files.\n\terr = copyDir(nfsMountPath+string(volumeID), nfsMountPath+string(newVolumeID))\n\tif err != nil {\n\t\td.Delete(newVolumeID)\n\t\treturn api.BadVolumeID, nil\n\t}\n\n\treturn newVolumeID, nil\n}\n\nfunc (d *driver) Attach(volumeID api.VolumeID) (string, error) {\n\treturn path.Join(nfsMountPath, string(volumeID), nfsBlockFile), nil\n}\n\nfunc (d *driver) Format(volumeID api.VolumeID) error {\n\treturn nil\n}\n\nfunc (d *driver) Detach(volumeID api.VolumeID) error {\n\treturn nil\n}\n\nfunc (d *driver) Stats(volumeID api.VolumeID) (api.Stats, error) {\n\treturn api.Stats{}, volume.ErrNotSupported\n}\n\nfunc (d *driver) Alerts(volumeID api.VolumeID) (api.Alerts, error) {\n\treturn api.Alerts{}, volume.ErrNotSupported\n}\n\nfunc (d *driver) Shutdown() {\n\tlog.Printf(\"%s Shutting down\", Name)\n\tsyscall.Unmount(nfsMountPath, 0)\n}\n\nfunc init() {\n\t\/\/ Register ourselves as an openstorage volume driver.\n\tvolume.Register(Name, Init)\n}\n<|endoftext|>"} {"text":"\/\/ Based on aplay audio adaptor written by @colemanserious (https:\/\/github.com\/colemanserious)\npackage audio\n\nimport (\n\t\"errors\"\n\t\"github.com\/hybridgroup\/gobot\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n)\n\nvar _ gobot.Adaptor = (*AudioAdaptor)(nil)\n\ntype AudioAdaptor struct {\n\tname string\n}\n\nfunc NewAudioAdaptor(name string) *AudioAdaptor {\n\treturn &AudioAdaptor{\n\t\tname: name,\n\t}\n}\n\nfunc (a *AudioAdaptor) Name() string { return a.name }\n\nfunc (a *AudioAdaptor) Connect() []error { return nil }\n\nfunc (a *AudioAdaptor) Finalize() []error { return nil }\n\nfunc (a *AudioAdaptor) Sound(fileName string) []error {\n\n\tvar errorsList []error\n\tvar err error\n\n\tif fileName == \"\" {\n\t\tlog.Println(\"Require filename for MP3 file.\")\n\t\terrorsList = append(errorsList, errors.New(\"Requires filename for MP3 file.\"))\n\t\treturn errorsList\n\t}\n\n\t_, err = os.Open(fileName)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\terrorsList = append(errorsList, err)\n\t\treturn errorsList\n\t}\n\n\t\/\/ command to play a MP3 file\n\tcmd := exec.Command(\"mpg123\", fileName)\n\terr = cmd.Start()\n\n\tif err != nil {\n\t\tlog.Println(err)\n\t\terrorsList = append(errorsList, err)\n\t\treturn errorsList\n\t}\n\n\t\/\/ Need to return to fulfill function sig, even though returning an empty\n\treturn nil\n}\n[audio] Allows playback of both MP3 or WAV files, as long as the needed player (mpg123 or aplay) is installed\/\/ Based on aplay audio adaptor written by @colemanserious (https:\/\/github.com\/colemanserious)\npackage audio\n\nimport (\n\t\"errors\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\"\n\n\t\"github.com\/hybridgroup\/gobot\"\n)\n\nvar _ gobot.Adaptor = (*AudioAdaptor)(nil)\n\ntype AudioAdaptor struct {\n\tname string\n}\n\nfunc NewAudioAdaptor(name string) *AudioAdaptor {\n\treturn &AudioAdaptor{\n\t\tname: name,\n\t}\n}\n\nfunc (a *AudioAdaptor) Name() string { return a.name }\n\nfunc (a *AudioAdaptor) Connect() []error { return nil }\n\nfunc (a *AudioAdaptor) Finalize() []error { return nil }\n\nfunc (a *AudioAdaptor) Sound(fileName string) []error {\n\n\tvar errorsList []error\n\n\tif fileName == \"\" {\n\t\tlog.Println(\"Require filename for audio file.\")\n\t\terrorsList = append(errorsList, errors.New(\"Requires filename for audio file.\"))\n\t\treturn errorsList\n\t}\n\n\t_, err := os.Stat(fileName)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\terrorsList = append(errorsList, err)\n\t\treturn errorsList\n\t}\n\n\t\/\/ command to play audio file based on file type\n\tfileType := path.Ext(fileName)\n\tvar commandName string\n\tif fileType == \".mp3\" {\n\t\t\tcommandName = \"mpg123\"\n\t} else if fileType == \".wav\" {\n\t\t\tcommandName = \"aplay\"\n\t} else {\n\t\tlog.Println(\"Unknown filetype for audio file.\")\n\t\terrorsList = append(errorsList, errors.New(\"Unknown filetype for audio file.\"))\n\t\treturn errorsList\n\t}\n\n\tcmd := exec.Command(commandName, fileName)\n\terr = cmd.Start()\n\tif err != nil {\n\t\tlog.Println(err)\n\t\terrorsList = append(errorsList, err)\n\t\treturn errorsList\n\t}\n\n\t\/\/ Need to return to fulfill function sig, even though returning an empty\n\treturn nil\n}\n<|endoftext|>"} {"text":"package schemaversion\n\nimport (\n\t\"testing\"\n\n\t_ \"github.com\/Microsoft\/hcsshim\/functional\/manifest\"\n\t\"github.com\/Microsoft\/hcsshim\/internal\/schema2\"\n\t\"github.com\/Microsoft\/hcsshim\/osversion\"\n)\n\nfunc TestDetermineSchemaVersion(t *testing.T) {\n\tosv := osversion.Get()\n\n\tif osv.Build >= osversion.RS5 {\n\t\tif sv := DetermineSchemaVersion(nil); !IsV10(sv) { \/\/ TODO: Toggle this at some point so default is 2.0\n\t\t\tt.Fatalf(\"expected v1\")\n\t\t}\n\t\tif sv := DetermineSchemaVersion(SchemaV21()); !IsV21(sv) {\n\t\t\tt.Fatalf(\"expected requested v2\")\n\t\t}\n\t\tif sv := DetermineSchemaVersion(SchemaV10()); !IsV10(sv) {\n\t\t\tt.Fatalf(\"expected requested v1\")\n\t\t}\n\t\tif sv := DetermineSchemaVersion(&hcsschema.Version{}); !IsV10(sv) { \/\/ Logs a warning that 0.0 is ignored \/\/ TODO: Toggle this too\n\t\t\tt.Fatalf(\"expected requested v1\")\n\t\t}\n\n\t\tif err := IsSupported(SchemaV21()); err != nil {\n\t\t\tt.Fatalf(\"v2 expected to be supported\")\n\t\t}\n\t\tif err := IsSupported(SchemaV10()); err != nil {\n\t\t\tt.Fatalf(\"v1 expected to be supported\")\n\t\t}\n\n\t} else {\n\t\tif sv := DetermineSchemaVersion(nil); !IsV10(sv) {\n\t\t\tt.Fatalf(\"expected v1\")\n\t\t}\n\t\t\/\/ Pre RS5 will downgrade to v1 even if request v2\n\t\tif sv := DetermineSchemaVersion(SchemaV21()); !IsV10(sv) { \/\/ Logs a warning that 2.0 is ignored.\n\t\t\tt.Fatalf(\"expected requested v1\")\n\t\t}\n\t\tif sv := DetermineSchemaVersion(SchemaV10()); !IsV10(sv) {\n\t\t\tt.Fatalf(\"expected requested v1\")\n\t\t}\n\t\tif sv := DetermineSchemaVersion(&hcsschema.Version{}); !IsV10(sv) { \/\/ Log a warning that 0.0 is ignored\n\t\t\tt.Fatalf(\"expected requested v1\")\n\t\t}\n\n\t\tif err := IsSupported(SchemaV21()); err == nil {\n\t\t\tt.Fatalf(\"didn't expect v2 to be supported\")\n\t\t}\n\t\tif err := IsSupported(SchemaV10()); err != nil {\n\t\t\tt.Fatalf(\"v1 expected to be supported\")\n\t\t}\n\t}\n}\nFix schemaversion tests on RS5+package schemaversion\n\nimport (\n\t\"io\/ioutil\"\n\t\"testing\"\n\n\t_ \"github.com\/Microsoft\/hcsshim\/functional\/manifest\"\n\t\"github.com\/Microsoft\/hcsshim\/internal\/schema2\"\n\t\"github.com\/Microsoft\/hcsshim\/osversion\"\n\t\"github.com\/sirupsen\/logrus\"\n)\n\nfunc init() {\n\tlogrus.SetOutput(ioutil.Discard)\n}\n\nfunc TestDetermineSchemaVersion(t *testing.T) {\n\tosv := osversion.Get()\n\n\tif osv.Build >= osversion.RS5 {\n\t\tif sv := DetermineSchemaVersion(nil); !IsV21(sv) {\n\t\t\tt.Fatalf(\"expected v2\")\n\t\t}\n\t\tif sv := DetermineSchemaVersion(SchemaV21()); !IsV21(sv) {\n\t\t\tt.Fatalf(\"expected requested v2\")\n\t\t}\n\t\tif sv := DetermineSchemaVersion(SchemaV10()); !IsV10(sv) {\n\t\t\tt.Fatalf(\"expected requested v1\")\n\t\t}\n\t\tif sv := DetermineSchemaVersion(&hcsschema.Version{}); !IsV21(sv) {\n\t\t\tt.Fatalf(\"expected requested v2\")\n\t\t}\n\n\t\tif err := IsSupported(SchemaV21()); err != nil {\n\t\t\tt.Fatalf(\"v2 expected to be supported\")\n\t\t}\n\t\tif err := IsSupported(SchemaV10()); err != nil {\n\t\t\tt.Fatalf(\"v1 expected to be supported\")\n\t\t}\n\n\t} else {\n\t\tif sv := DetermineSchemaVersion(nil); !IsV10(sv) {\n\t\t\tt.Fatalf(\"expected v1\")\n\t\t}\n\t\t\/\/ Pre RS5 will downgrade to v1 even if request v2\n\t\tif sv := DetermineSchemaVersion(SchemaV21()); !IsV10(sv) {\n\t\t\tt.Fatalf(\"expected requested v1\")\n\t\t}\n\t\tif sv := DetermineSchemaVersion(SchemaV10()); !IsV10(sv) {\n\t\t\tt.Fatalf(\"expected requested v1\")\n\t\t}\n\t\tif sv := DetermineSchemaVersion(&hcsschema.Version{}); !IsV10(sv) {\n\t\t\tt.Fatalf(\"expected requested v1\")\n\t\t}\n\n\t\tif err := IsSupported(SchemaV21()); err == nil {\n\t\t\tt.Fatalf(\"didn't expect v2 to be supported\")\n\t\t}\n\t\tif err := IsSupported(SchemaV10()); err != nil {\n\t\t\tt.Fatalf(\"v1 expected to be supported\")\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2013 The Author - Unknown. 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.\npackage main\n\nimport (\n\t\"archive\/tar\"\n\t\"compress\/gzip\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"path\"\n)\n\nfunc main() {\n\ttargetFilePath := \"\/home\/unknown\/Applications\/Go\/src\/test.tar.gz\"\n\tsrcDirPath := \"test\"\n\tTarGz(srcDirPath, targetFilePath)\n\tfmt.Println(\"Finish!\")\n}\n\n\/\/ Gzip and tar from source directory to destination file\nfunc TarGz(srcDirPath string, destFilePath string) {\n\t\/\/ File writer\n\tfw, err := os.Create(destFilePath)\n\thandleError(err)\n\tdefer fw.Close()\n\n\t\/\/ Gzip writer\n\tgw := gzip.NewWriter(fw)\n\tdefer gw.Close()\n\n\t\/\/ Tar writer\n\ttw := tar.NewWriter(gw)\n\tdefer tw.Close()\n\n\t\/\/ handle source directory\n\tTarGzDir(srcDirPath, path.Base(srcDirPath), tw)\n}\n\n\/\/ Deal with directories\n\/\/ if find files, handle them with HandleFile\n\/\/ Every recurrence append the base path to the recPath\n\/\/ recPath is the path inside of tar.gz\nfunc TarGzDir(srcDirPath string, recPath string, tw *tar.Writer) {\n\t\/\/ Open source diretory\n\tdir, err := os.Open(srcDirPath)\n\thandleError(err)\n\tdefer dir.Close()\n\n\t\/\/ Get file info slice\n\tfis, err := dir.Readdir(0)\n\thandleError(err)\n\tfor _, fi := range fis {\n\t\t\/\/ Append path\n\t\tcurPath := srcDirPath + \"\/\" + fi.Name()\n\t\t\/\/ Check it is directory or file\n\t\tif fi.IsDir() {\n\t\t\t\/\/ Directory\n\t\t\t\/\/ (Directory won't add unitl all subfiles are added)\n\t\t\tfmt.Printf(\"Adding path...%s\\n\", curPath)\n\t\t\tTarGzDir(curPath, recPath+\"\/\"+fi.Name(), tw)\n\t\t} else {\n\t\t\t\/\/ File\n\t\t\tfmt.Printf(\"Adding file...%s\\n\", curPath)\n\t\t}\n\n\t\tTarGzFile(curPath, recPath+\"\/\"+fi.Name(), tw, fi)\n\t}\n}\n\n\/\/ Deal with files\nfunc TarGzFile(srcFile string, recPath string, tw *tar.Writer, fi os.FileInfo) {\n\tif fi.IsDir() {\n\t\t\/\/ Create tar header\n\t\thdr := new(tar.Header)\n\t\thdr.Name = recPath + \"\/\"\n\n\t\t\/\/ Write hander\n\t\terr := tw.WriteHeader(hdr)\n\t\thandleError(err)\n\t} else {\n\t\t\/\/ File reader\n\t\tfr, err := os.Open(srcFile)\n\t\thandleError(err)\n\t\tdefer fr.Close()\n\n\t\t\/\/ Create tar header\n\t\thdr := new(tar.Header)\n\t\thdr.Name = recPath\n\t\thdr.Size = fi.Size()\n\t\thdr.Mode = int64(fi.Mode())\n\t\thdr.ModTime = fi.ModTime()\n\n\t\t\/\/ Write hander\n\t\terr = tw.WriteHeader(hdr)\n\t\thandleError(err)\n\n\t\t\/\/ Write file data\n\t\t_, err = io.Copy(tw, fr)\n\t\thandleError(err)\n\t}\n}\n\nfunc handleError(e error) {\n\tif e != nil {\n\t\tlog.Fatal(e)\n\t}\n\n}\nbug fix\/\/ Copyright 2013 The Author - Unknown. 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.\npackage main\n\nimport (\n\t\"archive\/tar\"\n\t\"compress\/gzip\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"path\"\n)\n\nfunc main() {\n\ttargetFilePath := \"test.tar.gz\"\n\tsrcDirPath := \"test\"\n\tTarGz(srcDirPath, targetFilePath)\n\tfmt.Println(\"Finish!\")\n}\n\n\/\/ Gzip and tar from source directory to destination file\n\/\/ you need check file exist before you call this function\nfunc TarGz(srcDirPath string, destFilePath string) {\n\tfmt.Println(\"Cerating tar.gz...\")\n\tfw, err := os.Create(destFilePath)\n\thandleError(err)\n\tdefer fw.Close()\n\n\t\/\/ Gzip writer\n\tgw := gzip.NewWriter(fw)\n\tdefer gw.Close()\n\n\t\/\/ Tar writer\n\ttw := tar.NewWriter(gw)\n\tdefer tw.Close()\n\n\t\/\/ handle source directory\n\tTarGzDir(srcDirPath, path.Base(srcDirPath), tw)\n}\n\n\/\/ Deal with directories\n\/\/ if find files, handle them with HandleFile\n\/\/ Every recurrence append the base path to the recPath\n\/\/ recPath is the path inside of tar.gz\nfunc TarGzDir(srcDirPath string, recPath string, tw *tar.Writer) {\n\t\/\/ Open source diretory\n\tdir, err := os.Open(srcDirPath)\n\thandleError(err)\n\tdefer dir.Close()\n\n\t\/\/ Get file info slice\n\tfis, err := dir.Readdir(0)\n\thandleError(err)\n\tfor _, fi := range fis {\n\t\t\/\/ Append path\n\t\tcurPath := srcDirPath + \"\/\" + fi.Name()\n\t\t\/\/ Check it is directory or file\n\t\tif fi.IsDir() {\n\t\t\t\/\/ Directory\n\t\t\t\/\/ (Directory won't add unitl all subfiles are added)\n\t\t\tfmt.Printf(\"Adding path...%s\\n\", curPath)\n\t\t\tTarGzDir(curPath, recPath+\"\/\"+fi.Name(), tw)\n\t\t} else {\n\t\t\t\/\/ File\n\t\t\tfmt.Printf(\"Adding file...%s\\n\", curPath)\n\t\t}\n\n\t\tTarGzFile(curPath, recPath+\"\/\"+fi.Name(), tw, fi)\n\t}\n}\n\n\/\/ Deal with files\nfunc TarGzFile(srcFile string, recPath string, tw *tar.Writer, fi os.FileInfo) {\n\tif fi.IsDir() {\n\t\t\/\/ Create tar header\n\t\thdr := new(tar.Header)\n\t\thdr.Name = recPath + \"\/\"\n\n\t\t\/\/ Write hander\n\t\terr := tw.WriteHeader(hdr)\n\t\thandleError(err)\n\t} else {\n\t\t\/\/ File reader\n\t\tfr, err := os.Open(srcFile)\n\t\thandleError(err)\n\t\tdefer fr.Close()\n\n\t\t\/\/ Create tar header\n\t\thdr := new(tar.Header)\n\t\thdr.Name = recPath\n\t\thdr.Size = fi.Size()\n\t\thdr.Mode = int64(fi.Mode())\n\t\thdr.ModTime = fi.ModTime()\n\n\t\t\/\/ Write hander\n\t\terr = tw.WriteHeader(hdr)\n\t\thandleError(err)\n\n\t\t\/\/ Write file data\n\t\t_, err = io.Copy(tw, fr)\n\t\thandleError(err)\n\t}\n}\n\nfunc handleError(e error) {\n\tif e != nil {\n\t\tlog.Fatal(e)\n\t}\n\n}\n<|endoftext|>"} {"text":"package goku\n\nimport (\n\t\"encoding\/json\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/garyburd\/redigo\/redis\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"github.com\/stretchr\/testify\/require\"\n)\n\ntype TestJob struct {\n\tFoo int\n\tBar string\n}\n\nfunc (tj TestJob) Name() string {\n\treturn \"test_job\"\n}\n\nvar tjWasCalled bool\n\nfunc (tj TestJob) Execute() error {\n\ttjWasCalled = true\n\treturn nil\n}\n\nfunc TestBroker(t *testing.T) {\n\tassert := assert.New(t)\n\trequire := require.New(t)\n\n\thostport := \"127.0.0.1:6379\"\n\tqueueName := \"goku_test\"\n\n\tbroker, err := NewBroker(BrokerConfig{\n\t\tHostport: hostport,\n\t\tTimeout: time.Second,\n\t\tDefaultQueue: queueName,\n\t})\n\n\trequire.NoError(err)\n\n\tjob := TestJob{\n\t\tFoo: 4,\n\t\tBar: \"sup\",\n\t}\n\n\terr = broker.Run(job)\n\tassert.NoError(err)\n\n\tconn, err := redis.Dial(\"tcp\", hostport)\n\trequire.NoError(err)\n\n\tjsn, err := redis.Bytes(conn.Do(\"LPOP\", queueName))\n\tassert.NoError(err)\n\n\tvar m map[string]interface{}\n\tjson.Unmarshal(jsn, &m)\n\targs := m[\"A\"].(map[string]interface{})\n\n\tassert.Equal(m[\"N\"], job.Name())\n\tassert.Equal(args[\"Foo\"], float64(4))\n\tassert.Equal(args[\"Bar\"], \"sup\")\n}\n\nfunc TestWorker(t *testing.T) {\n\tassert := assert.New(t)\n\trequire := require.New(t)\n\n\tqueue := \"goku_test\"\n\thostport := \"127.0.0.1:6379\"\n\n\tconfig := WorkerConfig{\n\t\tNumWorkers: 1,\n\t\tQueues: []string{queue},\n\t\tHostport: hostport,\n\t\tTimeout: time.Second,\n\t}\n\n\topts := WorkerPoolOptions{\n\t\tFailure: nil,\n\t\tJobs: []Job{\n\t\t\tTestJob{},\n\t\t},\n\t}\n\n\t\/\/ start the worker\n\twp, err := NewWorkerPool(config, opts)\n\tassert.NoError(err)\n\twp.Start()\n\n\ttjWasCalled = false\n\n\t\/\/ schedule the job from the broker\n\tbroker, err := NewBroker(BrokerConfig{\n\t\tHostport: hostport,\n\t\tTimeout: time.Second,\n\t\tDefaultQueue: queue,\n\t})\n\n\trequire.NoError(err)\n\n\tjob := TestJob{\n\t\tFoo: 4,\n\t\tBar: \"sup\",\n\t}\n\n\terr = broker.Run(job)\n\tassert.NoError(err)\n\ttime.Sleep(time.Second) \/\/ give workers some time to pull the job out of the queue\n\twp.Stop()\n\n\tassert.True(tjWasCalled)\n}\nMore testspackage goku\n\nimport (\n\t\"encoding\/json\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/garyburd\/redigo\/redis\"\n\t\"github.com\/stretchr\/testify\/assert\"\n\t\"github.com\/stretchr\/testify\/require\"\n)\n\ntype TestJob struct {\n\tFoo int\n\tBar string\n}\n\nfunc (tj TestJob) Name() string {\n\treturn \"test_job\"\n}\n\nvar tjWasCalled bool\n\nfunc (tj TestJob) Execute() error {\n\ttjWasCalled = true\n\treturn nil\n}\n\nfunc TestBroker(t *testing.T) {\n\tassert := assert.New(t)\n\trequire := require.New(t)\n\n\thostport := \"127.0.0.1:6379\"\n\tqueueName := \"goku_test\"\n\n\tbroker, err := NewBroker(BrokerConfig{\n\t\tHostport: hostport,\n\t\tTimeout: time.Second,\n\t\tDefaultQueue: queueName,\n\t})\n\n\trequire.NoError(err)\n\n\tjob := TestJob{\n\t\tFoo: 4,\n\t\tBar: \"sup\",\n\t}\n\n\terr = broker.Run(job)\n\tassert.NoError(err)\n\n\tconn, err := redis.Dial(\"tcp\", hostport)\n\trequire.NoError(err)\n\n\tjsn, err := redis.Bytes(conn.Do(\"LPOP\", queueName))\n\tassert.NoError(err)\n\n\tvar m map[string]interface{}\n\tjson.Unmarshal(jsn, &m)\n\targs := m[\"A\"].(map[string]interface{})\n\n\tassert.Equal(m[\"N\"], job.Name())\n\tassert.Equal(args[\"Foo\"], float64(4))\n\tassert.Equal(args[\"Bar\"], \"sup\")\n}\n\nfunc TestWorker(t *testing.T) {\n\tassert := assert.New(t)\n\trequire := require.New(t)\n\n\tqueue := \"goku_test\"\n\thostport := \"127.0.0.1:6379\"\n\n\tconfig := WorkerConfig{\n\t\tNumWorkers: 1,\n\t\tQueues: []string{queue},\n\t\tHostport: hostport,\n\t\tTimeout: time.Second,\n\t}\n\n\topts := WorkerPoolOptions{\n\t\tFailure: nil,\n\t\tJobs: []Job{\n\t\t\tTestJob{},\n\t\t},\n\t}\n\n\t\/\/ start the worker\n\twp, err := NewWorkerPool(config, opts)\n\tassert.NoError(err)\n\twp.Start()\n\n\ttjWasCalled = false\n\n\t\/\/ schedule the job from the broker\n\tbroker, err := NewBroker(BrokerConfig{\n\t\tHostport: hostport,\n\t\tTimeout: time.Second,\n\t\tDefaultQueue: queue,\n\t})\n\n\trequire.NoError(err)\n\n\tjob := TestJob{\n\t\tFoo: 4,\n\t\tBar: \"sup\",\n\t}\n\n\terr = broker.Run(job)\n\tassert.NoError(err)\n\ttime.Sleep(time.Second) \/\/ give workers some time to pull the job out of the queue\n\twp.Stop()\n\n\tassert.True(tjWasCalled)\n}\n\nfunc TestBrokerBadConfig(t *testing.T) {\n\t_, err := NewBroker(BrokerConfig{})\n\tassert.Error(t, err)\n}\n\nfunc TestWorkerPoolBadConfig(t *testing.T) {\n\t_, err := NewWorkerPool(WorkerConfig{}, WorkerPoolOptions{})\n\tassert.Error(t, err)\n}\n\nfunc TestConfigureBadConfig(t *testing.T) {\n\terr := Configure(BrokerConfig{})\n\tassert.Error(t, err)\n}\n\nfunc TestConfigureGoodConfig(t *testing.T) {\n\thostport := \"127.0.0.1:6379\"\n\tqueueName := \"goku_test\"\n\terr := Configure(BrokerConfig{\n\t\tHostport: hostport,\n\t\tTimeout: time.Second,\n\t\tDefaultQueue: queueName,\n\t})\n\tassert.NoError(t, err)\n}\n<|endoftext|>"} {"text":"package main\n\n\/*\nConsider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5:\n2**2=4, 2**3=8, 2**4=16, 2**5=32\n3**2=9, 3**3=27, 3**4=81, 3**5=243 4**2=16, 4**3=64, 4**4=256, 4**5=1024\n5**2=25, 5**3=125, 5**4=625, 5**5=3125\nIf they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms:\n\n4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125\n\nHow many distinct terms are in the sequence generated by ab for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100?\n*\/\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/fenglyu\/projecteuler\/golang\/common\"\n)\n\nfunc main() {\n\t\/\/\tar := []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97}\n\n\tfor i := 2; i < 101; i++ {\n\t\tres := common.DivisorV3(i)\n\t\tif len(res) < 2 {\n\t\t\tcontinue\n\t\t}\n\n\t\tfmt.Println(\"num: \", i, res)\n\t}\n\n}\n\n\/*\n\n2**(2*2), 4 ** 2\n2**(2*2*2), 4 ** 4\n2**(2*2*2*2), 4**8, 16**2\n2**(2*2*2*2*2), 4**16, 16**8,\n2**(2*2*2*2*2*2), 4**32, 16**16,\n\n2**(3*2), 8**2\n2**(3*2*2), 8**4\n2**(3*2*2*2), 8**8, 64**4\n2**(3*2*2*2), 8**16, 64**8\n2**(3*2*2*2*2), 8**32, 64**16\n\n2**(3*3), 8**3\n2**(3*3*3), 8**9\n2**(3*3*3*3), 8**27\n\n2**(3*3*2), 8**6, 64**3\n2**(3*3*2*2), 8**12, 64**6\n\n2**(5*2), 32**2\n2**(5*2*2), 32**4\n2**(5*2*2*2), 32**4\n\n2**(5*3*2)), 32**6\n2**(5*3*2*2)), 32**12\n\n2**(5*5), 32**5\n\n2**(7*2), 4**7\n2**(7*2*2), 4**16, 16**7\n2**(7*2*2*2), 4**28, 16**14\n\n2**(9*2) 4**9\n2**(9*2*2) 4**18\n*\/\nupdatepackage main\n\n\/*\nConsider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5:\n2**2=4, 2**3=8, 2**4=16, 2**5=32\n3**2=9, 3**3=27, 3**4=81, 3**5=243 4**2=16, 4**3=64, 4**4=256, 4**5=1024\n5**2=25, 5**3=125, 5**4=625, 5**5=3125\nIf they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms:\n\n4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125\n\nHow many distinct terms are in the sequence generated by ab for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100?\n*\/\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/fenglyu\/projecteuler\/golang\/common\"\n)\n\nfunc main() {\n\t\/\/\tar := []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97}\n\n\tm := make(map[int][]int)\n\tfor i := 2; i < 101; i++ {\n\t\tres := common.DivisorV3(i)\n\t\tif len(res) < 2 {\n\t\t\tcontinue\n\t\t}\n\t\t\/\/\tfmt.Println(\"num: \", i, res)\n\t\tm[i] = res\n\t}\n\n\t\/\/\tfmt.Println(\"map: \", m)\n\tfor j := 2; j <= 10; j++ {\n\t\tfor k, v := range m {\n\n\t\t}\n\t}\n}\n\n\/*\n\n2**(2*2), 4 ** 2\n2**(2*2*2), 4 ** 4\n2**(2*2*2*2), 4**8, 16**2\n2**(2*2*2*2*2), 4**16, 16**8,\n2**(2*2*2*2*2*2), 4**32, 16**16,\n\n2**(3*2), 8**2\n2**(3*2*2), 8**4\n2**(3*2*2*2), 8**8, 64**4\n2**(3*2*2*2), 8**16, 64**8\n2**(3*2*2*2*2), 8**32, 64**16\n\n2**(3*3), 8**3\n2**(3*3*3), 8**9\n2**(3*3*3*3), 8**27\n\n2**(3*3*2), 8**6, 64**3\n2**(3*3*2*2), 8**12, 64**6\n\n2**(5*2), 32**2\n2**(5*2*2), 32**4\n2**(5*2*2*2), 32**4\n\n2**(5*3*2)), 32**6\n2**(5*3*2*2)), 32**12\n\n2**(5*5), 32**5\n\n2**(7*2), 4**7\n2**(7*2*2), 4**16, 16**7\n2**(7*2*2*2), 4**28, 16**14\n\n2**(9*2) 4**9\n2**(9*2*2) 4**18\n*\/\n<|endoftext|>"} {"text":"package golangsdk\n\nimport (\n\t\"crypto\/tls\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst (\n\tzincBaseURL = \"https:\/\/api.zinc.io\/v1\"\n)\n\ntype Retailer string\n\nconst (\n\tAmazon Retailer = \"amazon\"\n\tAmazonUK Retailer = \"amazon_uk\"\n\tAmazonCA Retailer = \"amazon_ca\"\n\tAmazonMX Retailer = \"amazon_mx\"\n\tWalmart Retailer = \"walmart\"\n\tAliexpress Retailer = \"aliexpress\"\n)\n\nvar DefaultProductOptions = ProductOptions{\n\tTimeout: time.Duration(time.Second * 90),\n}\n\ntype Zinc struct {\n\tClientToken string\n\tZincBaseURL string\n}\n\nfunc GetRetailer(retailer string) (Retailer, error) {\n\tswitch retailer {\n\tcase \"amazon\":\n\t\treturn Amazon, nil\n\tcase \"amazon_uk\":\n\t\treturn AmazonUK, nil\n\tcase \"amazon_ca\":\n\t\treturn AmazonCA, nil\n\tcase \"amazon_mx\":\n\t\treturn AmazonMX, nil\n\tcase \"walmart\":\n\t\treturn Walmart, nil\n\tcase \"aliexpress\":\n\t\treturn Aliexpress, nil\n\tdefault:\n\t\treturn Amazon, fmt.Errorf(\"Invalid retailer string\")\n\t}\n}\n\nfunc NewZinc(clientToken string) (*Zinc, error) {\n\tz := Zinc{\n\t\tClientToken: clientToken,\n\t\tZincBaseURL: zincBaseURL,\n\t}\n\treturn &z, nil\n}\n\ntype ProductOffersResponse struct {\n\tCode string `json:\"code\"`\n\tData ErrorDataResponse `json:\"data\"`\n\tStatus string `json:\"status\"`\n\tRetailer string `json:\"retailer\"`\n\tOffers []ProductOffer `json:\"offers\"`\n}\n\ntype ProductOffer struct {\n\tAvailable bool `json:\"available\"`\n\tAddon bool `json:\"addon\"`\n\tCondition string `json:\"condition\"`\n\tShippingOptions []ShippingOption `json:\"shipping_options\"`\n\tHandlingDays HandlingDays `json:\"handling_days\"`\n\tPrimeOnly bool `json:\"prime_only\"`\n\tMarketplaceFulfilled bool `json:\"marketplace_fulfilled\"`\n\tCurrency string `json:\"currency\"`\n\tSeller Seller `json:\"seller\"`\n\tBuyBoxWinner bool `json:\"buy_box_winner\"`\n\tInternational bool `json:\"international\"`\n\tOfferId string `json:\"offer_id\"`\n\tPrice int `json:\"price\"`\n}\n\ntype ShippingOption struct {\n\tPrice int `json:\"price\"`\n}\n\ntype HandlingDays struct {\n\tMax int `json:\"max\"`\n\tMin int `json:\"min\"`\n}\n\ntype Seller struct {\n\tNumRatings int `json:\"num_ratings\"`\n\tPercentPositive int `json:\"percent_positive\"`\n\tFirstParty bool `json:\"first_party\"`\n\tName string `json:\"name\"`\n\tId string `json:\"id\"`\n}\n\ntype ProductDetailsResponse struct {\n\tCode string `json:\"code\"`\n\tData ErrorDataResponse `json:\"data\"`\n\tStatus string `json:\"status\"`\n\tProductDescription string `json:\"product_description\"`\n\tPostDescription string `json:\"post_description\"`\n\tRetailer string `json:\"retailer\"`\n\tEpids []ExternalProductId `json:\"epids\"`\n\tProductDetails []string `json:\"product_details\"`\n\tTitle string `json:\"title\"`\n\tVariantSpecifics []VariantSpecific `json:\"variant_specifics\"`\n\tProductId json.Number `json:\"product_id\"`\n\tMainImage string `json:\"main_image\"`\n\tBrand string `json:\"brand\"`\n\tMPN string `json:\"mpn\"`\n\tImages []string `json:\"images\"`\n\tFeatureBullets []string `json:\"feature_bullets\"`\n}\n\ntype ExternalProductId struct {\n\tType string `json:\"type\"`\n\tValue string `json:\"value\"`\n}\n\ntype VariantSpecific struct {\n\tDimension string `json:\"dimension\"`\n\tValue string `json:\"value\"`\n}\n\ntype ErrorDataResponse struct {\n\tMessage string `json:\"message\"`\n}\n\ntype ProductOptions struct {\n\tMaxAge int `json:\"max_age\"`\n\tPriority int `json:\"priority\"`\n\tNewerThan time.Time `json:\"newer_than\"`\n\tTimeout time.Duration `json:\"timeout\"`\n}\n\ntype ZincError struct {\n\tErrorMessage string `json:\"error\"`\n\tData ErrorDataResponse `json:\"data\"`\n}\n\nfunc (z ZincError) Error() string {\n\treturn z.ErrorMessage\n}\n\nfunc SimpleError(errorStr string) ZincError {\n\treturn ZincError{ErrorMessage: errorStr}\n}\n\nfunc (z Zinc) GetProductInfo(productId string, retailer Retailer, options ProductOptions) (*ProductOffersResponse, *ProductDetailsResponse, error) {\n\toffersChan := make(chan *ProductOffersResponse, 1)\n\tdetailsChan := make(chan *ProductDetailsResponse, 1)\n\terrorsChan := make(chan error, 2)\n\n\tgo func() {\n\t\toffers, err := z.GetProductOffers(productId, retailer, options)\n\t\terrorsChan <- err\n\t\toffersChan <- offers\n\t}()\n\n\tgo func() {\n\t\tdetails, err := z.GetProductDetails(productId, retailer, options)\n\t\terrorsChan <- err\n\t\tdetailsChan <- details\n\t}()\n\n\toffers := <-offersChan\n\tdetails := <-detailsChan\n\tfor i := 0; i < 2; i++ {\n\t\terr := <-errorsChan\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\treturn offers, details, nil\n}\n\nfunc (z Zinc) GetProductOffers(productId string, retailer Retailer, options ProductOptions) (*ProductOffersResponse, error) {\n\tvalues := url.Values{}\n\tvalues.Set(\"retailer\", string(retailer))\n\tvalues.Set(\"version\", \"2\")\n\tif options.MaxAge != 0 {\n\t\tvalues.Set(\"max_age\", strconv.Itoa(options.MaxAge))\n\t}\n\tif !options.NewerThan.IsZero() {\n\t\tvalues.Set(\"newer_than\", strconv.FormatInt(options.NewerThan.Unix(), 10))\n\t}\n\trequestPath := fmt.Sprintf(\"%v\/products\/%v\/offers?%v\", z.ZincBaseURL, productId, values.Encode())\n\n\tvar resp ProductOffersResponse\n\tif err := z.SendGetRequest(requestPath, options.Timeout, &resp); err != nil {\n\t\treturn nil, SimpleError(err.Error())\n\t}\n\tif resp.Status == \"failed\" {\n\t\tmsg := fmt.Sprintf(\"Zinc API returned status 'failed' data=%+v\", resp.Data)\n\t\treturn &resp, ZincError{ErrorMessage: msg, Data: resp.Data}\n\t}\n\treturn &resp, nil\n}\n\nfunc (z Zinc) GetProductDetails(productId string, retailer Retailer, options ProductOptions) (*ProductDetailsResponse, error) {\n\tvalues := url.Values{}\n\tvalues.Set(\"retailer\", string(retailer))\n\tif options.MaxAge != 0 {\n\t\tvalues.Set(\"max_age\", strconv.Itoa(options.MaxAge))\n\t}\n\tif !options.NewerThan.IsZero() {\n\t\tvalues.Set(\"newer_than\", strconv.FormatInt(options.NewerThan.Unix(), 10))\n\t}\n\tif options.Priority != 0 {\n\t\tvalues.Set(\"priority\", strconv.Itoa(options.Priority))\n\t}\n\trequestPath := fmt.Sprintf(\"%v\/products\/%v?%v\", z.ZincBaseURL, productId, values.Encode())\n\n\tvar resp ProductDetailsResponse\n\tif err := z.SendGetRequest(requestPath, options.Timeout, &resp); err != nil {\n\t\treturn nil, SimpleError(err.Error())\n\t}\n\tif resp.Status == \"failed\" {\n\t\tmsg := fmt.Sprintf(\"Zinc API returned status 'failed' data=%+v\", resp.Data)\n\t\treturn &resp, ZincError{ErrorMessage: msg, Data: resp.Data}\n\t}\n\treturn &resp, nil\n}\n\nfunc cleanRespBody(respBody []byte) []byte {\n\tstr := string(respBody)\n\ti := strings.Index(str, \"HTTP\/1.1 200 OK\")\n\tif i == -1 {\n\t\treturn respBody\n\t}\n\treturn []byte(str[:i])\n}\n\nfunc (z Zinc) SendGetRequest(requestPath string, timeout time.Duration, resp interface{}) error {\n\thttpReq, err := http.NewRequest(\"GET\", requestPath, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\thttpReq.SetBasicAuth(z.ClientToken, \"\")\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\tclient := &http.Client{Transport: tr, Timeout: timeout}\n\thttpResp, err := client.Do(httpReq)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer httpResp.Body.Close()\n\trespBody, err := ioutil.ReadAll(httpResp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcleanedBody := cleanRespBody(respBody)\n\tif err := json.Unmarshal(cleanedBody, resp); err != nil {\n\t\tlog.Printf(\"[Golangsdk] Unable to unmarshal response request_path=%v body=%v\", requestPath, string(cleanedBody))\n\t\treturn SimpleError(err.Error())\n\t}\n\treturn nil\n}\nAdd order response to golangsdk.package golangsdk\n\nimport (\n\t\"crypto\/tls\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst (\n\tzincBaseURL = \"https:\/\/api.zinc.io\/v1\"\n)\n\ntype Retailer string\n\nconst (\n\tAmazon Retailer = \"amazon\"\n\tAmazonUK Retailer = \"amazon_uk\"\n\tAmazonCA Retailer = \"amazon_ca\"\n\tAmazonMX Retailer = \"amazon_mx\"\n\tWalmart Retailer = \"walmart\"\n\tAliexpress Retailer = \"aliexpress\"\n)\n\nvar DefaultProductOptions = ProductOptions{\n\tTimeout: time.Duration(time.Second * 90),\n}\n\ntype Zinc struct {\n\tClientToken string\n\tZincBaseURL string\n}\n\nfunc GetRetailer(retailer string) (Retailer, error) {\n\tswitch retailer {\n\tcase \"amazon\":\n\t\treturn Amazon, nil\n\tcase \"amazon_uk\":\n\t\treturn AmazonUK, nil\n\tcase \"amazon_ca\":\n\t\treturn AmazonCA, nil\n\tcase \"amazon_mx\":\n\t\treturn AmazonMX, nil\n\tcase \"walmart\":\n\t\treturn Walmart, nil\n\tcase \"aliexpress\":\n\t\treturn Aliexpress, nil\n\tdefault:\n\t\treturn Amazon, fmt.Errorf(\"Invalid retailer string\")\n\t}\n}\n\nfunc NewZinc(clientToken string) (*Zinc, error) {\n\tz := Zinc{\n\t\tClientToken: clientToken,\n\t\tZincBaseURL: zincBaseURL,\n\t}\n\treturn &z, nil\n}\n\ntype OrderResponse struct {\n\tType string `json:\"_type\"`\n\tCode string `json:\"code\"`\n\tData ErrorDataResponse `json:\"data\"`\n\tErrorMessage string `json:\"message\"`\n\tPriceComponents PriceComponents `json:\"price_components\"`\n\tMerchantOrderIds []MerchantOrderId `json:\"merchant_order_ids\"`\n\tTracking []Tracking `json:\"tracking\"`\n}\n\ntype PriceComponents struct {\n\tShipping int `json:\"shipping\"`\n\tSubtotal int `json:\"subtotal\"`\n\tTax int `json:\"tax\"`\n\tTotal int `json:\"total\"`\n}\n\ntype MerchantOrderId struct {\n\tMerchantOrderId string `json:\"merchant_order_id\"`\n\tMerchant string `json:\"merchant\"`\n\tAccount string `json:\"account\"`\n\tPlacedAt time.Time `json:\"placed_at\"`\n}\n\ntype Tracking struct {\n\tMerchantOrderId string `json:\"merchant_order_id\"`\n\tObtainedAt time.Time `json:\"obtained_at\"`\n\tCarrier string `json:\"carrier\"`\n\tTrackingNumber string `json:\"tracking_number\"`\n\tProductIds []string `json:\"product_ids\"`\n\tTrackingURL string `json:\"tracking_url\"`\n}\n\ntype ProductOffersResponse struct {\n\tCode string `json:\"code\"`\n\tData ErrorDataResponse `json:\"data\"`\n\tStatus string `json:\"status\"`\n\tRetailer string `json:\"retailer\"`\n\tOffers []ProductOffer `json:\"offers\"`\n}\n\ntype ProductOffer struct {\n\tAvailable bool `json:\"available\"`\n\tAddon bool `json:\"addon\"`\n\tCondition string `json:\"condition\"`\n\tShippingOptions []ShippingOption `json:\"shipping_options\"`\n\tHandlingDays HandlingDays `json:\"handling_days\"`\n\tPrimeOnly bool `json:\"prime_only\"`\n\tMarketplaceFulfilled bool `json:\"marketplace_fulfilled\"`\n\tCurrency string `json:\"currency\"`\n\tSeller Seller `json:\"seller\"`\n\tBuyBoxWinner bool `json:\"buy_box_winner\"`\n\tInternational bool `json:\"international\"`\n\tOfferId string `json:\"offer_id\"`\n\tPrice int `json:\"price\"`\n}\n\ntype ShippingOption struct {\n\tPrice int `json:\"price\"`\n}\n\ntype HandlingDays struct {\n\tMax int `json:\"max\"`\n\tMin int `json:\"min\"`\n}\n\ntype Seller struct {\n\tNumRatings int `json:\"num_ratings\"`\n\tPercentPositive int `json:\"percent_positive\"`\n\tFirstParty bool `json:\"first_party\"`\n\tName string `json:\"name\"`\n\tId string `json:\"id\"`\n}\n\ntype ProductDetailsResponse struct {\n\tCode string `json:\"code\"`\n\tData ErrorDataResponse `json:\"data\"`\n\tStatus string `json:\"status\"`\n\tProductDescription string `json:\"product_description\"`\n\tPostDescription string `json:\"post_description\"`\n\tRetailer string `json:\"retailer\"`\n\tEpids []ExternalProductId `json:\"epids\"`\n\tProductDetails []string `json:\"product_details\"`\n\tTitle string `json:\"title\"`\n\tVariantSpecifics []VariantSpecific `json:\"variant_specifics\"`\n\tProductId json.Number `json:\"product_id\"`\n\tMainImage string `json:\"main_image\"`\n\tBrand string `json:\"brand\"`\n\tMPN string `json:\"mpn\"`\n\tImages []string `json:\"images\"`\n\tFeatureBullets []string `json:\"feature_bullets\"`\n}\n\ntype ExternalProductId struct {\n\tType string `json:\"type\"`\n\tValue string `json:\"value\"`\n}\n\ntype VariantSpecific struct {\n\tDimension string `json:\"dimension\"`\n\tValue string `json:\"value\"`\n}\n\ntype ErrorDataResponse struct {\n\tMessage string `json:\"message\"`\n}\n\ntype ProductOptions struct {\n\tMaxAge int `json:\"max_age\"`\n\tPriority int `json:\"priority\"`\n\tNewerThan time.Time `json:\"newer_than\"`\n\tTimeout time.Duration `json:\"timeout\"`\n}\n\ntype ZincError struct {\n\tErrorMessage string `json:\"error\"`\n\tData ErrorDataResponse `json:\"data\"`\n}\n\nfunc (z ZincError) Error() string {\n\treturn z.ErrorMessage\n}\n\nfunc SimpleError(errorStr string) ZincError {\n\treturn ZincError{ErrorMessage: errorStr}\n}\n\nfunc (z Zinc) GetProductInfo(productId string, retailer Retailer, options ProductOptions) (*ProductOffersResponse, *ProductDetailsResponse, error) {\n\toffersChan := make(chan *ProductOffersResponse, 1)\n\tdetailsChan := make(chan *ProductDetailsResponse, 1)\n\terrorsChan := make(chan error, 2)\n\n\tgo func() {\n\t\toffers, err := z.GetProductOffers(productId, retailer, options)\n\t\terrorsChan <- err\n\t\toffersChan <- offers\n\t}()\n\n\tgo func() {\n\t\tdetails, err := z.GetProductDetails(productId, retailer, options)\n\t\terrorsChan <- err\n\t\tdetailsChan <- details\n\t}()\n\n\toffers := <-offersChan\n\tdetails := <-detailsChan\n\tfor i := 0; i < 2; i++ {\n\t\terr := <-errorsChan\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t}\n\treturn offers, details, nil\n}\n\nfunc (z Zinc) GetProductOffers(productId string, retailer Retailer, options ProductOptions) (*ProductOffersResponse, error) {\n\tvalues := url.Values{}\n\tvalues.Set(\"retailer\", string(retailer))\n\tvalues.Set(\"version\", \"2\")\n\tif options.MaxAge != 0 {\n\t\tvalues.Set(\"max_age\", strconv.Itoa(options.MaxAge))\n\t}\n\tif !options.NewerThan.IsZero() {\n\t\tvalues.Set(\"newer_than\", strconv.FormatInt(options.NewerThan.Unix(), 10))\n\t}\n\trequestPath := fmt.Sprintf(\"%v\/products\/%v\/offers?%v\", z.ZincBaseURL, productId, values.Encode())\n\n\tvar resp ProductOffersResponse\n\tif err := z.SendGetRequest(requestPath, options.Timeout, &resp); err != nil {\n\t\treturn nil, SimpleError(err.Error())\n\t}\n\tif resp.Status == \"failed\" {\n\t\tmsg := fmt.Sprintf(\"Zinc API returned status 'failed' data=%+v\", resp.Data)\n\t\treturn &resp, ZincError{ErrorMessage: msg, Data: resp.Data}\n\t}\n\treturn &resp, nil\n}\n\nfunc (z Zinc) GetProductDetails(productId string, retailer Retailer, options ProductOptions) (*ProductDetailsResponse, error) {\n\tvalues := url.Values{}\n\tvalues.Set(\"retailer\", string(retailer))\n\tif options.MaxAge != 0 {\n\t\tvalues.Set(\"max_age\", strconv.Itoa(options.MaxAge))\n\t}\n\tif !options.NewerThan.IsZero() {\n\t\tvalues.Set(\"newer_than\", strconv.FormatInt(options.NewerThan.Unix(), 10))\n\t}\n\tif options.Priority != 0 {\n\t\tvalues.Set(\"priority\", strconv.Itoa(options.Priority))\n\t}\n\trequestPath := fmt.Sprintf(\"%v\/products\/%v?%v\", z.ZincBaseURL, productId, values.Encode())\n\n\tvar resp ProductDetailsResponse\n\tif err := z.SendGetRequest(requestPath, options.Timeout, &resp); err != nil {\n\t\treturn nil, SimpleError(err.Error())\n\t}\n\tif resp.Status == \"failed\" {\n\t\tmsg := fmt.Sprintf(\"Zinc API returned status 'failed' data=%+v\", resp.Data)\n\t\treturn &resp, ZincError{ErrorMessage: msg, Data: resp.Data}\n\t}\n\treturn &resp, nil\n}\n\nfunc cleanRespBody(respBody []byte) []byte {\n\tstr := string(respBody)\n\ti := strings.Index(str, \"HTTP\/1.1 200 OK\")\n\tif i == -1 {\n\t\treturn respBody\n\t}\n\treturn []byte(str[:i])\n}\n\nfunc (z Zinc) SendGetRequest(requestPath string, timeout time.Duration, resp interface{}) error {\n\thttpReq, err := http.NewRequest(\"GET\", requestPath, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\thttpReq.SetBasicAuth(z.ClientToken, \"\")\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t}\n\tclient := &http.Client{Transport: tr, Timeout: timeout}\n\thttpResp, err := client.Do(httpReq)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer httpResp.Body.Close()\n\trespBody, err := ioutil.ReadAll(httpResp.Body)\n\tif err != nil {\n\t\treturn err\n\t}\n\tcleanedBody := cleanRespBody(respBody)\n\tif err := json.Unmarshal(cleanedBody, resp); err != nil {\n\t\tlog.Printf(\"[Golangsdk] Unable to unmarshal response request_path=%v body=%v\", requestPath, string(cleanedBody))\n\t\treturn SimpleError(err.Error())\n\t}\n\treturn nil\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n \"encoding\/json\"\n\t\"io\/ioutil\"\n \"os\"\n\t\"strings\"\n\t\"github.com\/adabei\/goldenbot\/greeter\"\n\t\"github.com\/adabei\/goldenbot\/rcon\"\n\t\"github.com\/adabei\/goldenbot\/tails\"\n\t\"github.com\/adabei\/goldenbot\/votes\"\n\t\"github.com\/adabei\/goldenbot\/advert\"\n)\n\ntype GoldenConfig struct {\n Address string\n RCONPassword string\n LogfilePath string\n SayPrefix string\n}\n\nfunc main() {\n fi, _ := os.Open(\"golden.cfg\")\n b, _ := ioutil.ReadAll(fi)\n var cfg GoldenConfig\n json.Unmarshal(b, &cfg)\n\trch := make(chan rcon.RCONRequest, 10)\n\trcon := rcon.NewRCON(cfg.Address, cfg.RCONPassword, rch)\n\tgreetings := greeter.NewGreeter(\"Greetings! Welcome to the server, %s.\", rch)\n\n\tvotekick := votes.NewVote(rch)\n advert := advert.NewAdvert(\"ads.txt\", 60000, rch)\n\tchain := daisy(greetings, votekick, advert)\n\tgo rcon.Relay()\n\n\tlogch := make(chan string)\n\tgo tails.Tail(cfg.LogfilePath, logch, false)\n\tfor {\n\t\tline := <-logch\n\t\t\/\/remove go\n\t\tfunc(ch chan string) { ch <- strings.TrimSpace(line) }(chain)\n\t}\n\tos.Exit(0)\n}\n\ntype Plugin interface {\n\tStart(prev, next chan string)\n}\n\n\/\/ Daisy sets up the daisy chain of plugins for message passing.\n\/\/ Returns a channel on which we can send in messages.\nfunc daisy(plugins ...Plugin) chan string {\n\tlast := make(chan string)\n\tprev := last\n\tnext := last\n\n\tfor _, p := range plugins {\n\t\tprev = make(chan string)\n\t\tgo p.Start(next, prev)\n\t\tnext = prev\n\t}\n\t\/\/ drain the last channel in the chain\n\tgo func(ch chan string) { <-last }(last)\n\treturn prev\n}\ncleans up goldenbot.gopackage main\n\nimport (\n \"encoding\/json\"\n \"flag\"\n\t\"io\/ioutil\"\n \"log\"\n \"os\"\n\t\"strings\"\n\t\"github.com\/adabei\/goldenbot\/greeter\"\n\t\"github.com\/adabei\/goldenbot\/rcon\"\n\t\"github.com\/adabei\/goldenbot\/tails\"\n\t\"github.com\/adabei\/goldenbot\/votes\"\n\t\"github.com\/adabei\/goldenbot\/advert\"\n)\n\ntype GoldenConfig struct {\n Address string\n RCONPassword string\n LogfilePath string\n SayPrefix string\n}\n\nfunc main() {\n \/\/ Parse command line flags\n configPath := *flag.String(\"config\", \"golden.cfg\", \"the config file to use\")\n flag.Parse()\n\n \/\/ Read config\n fi, err := os.Open(configPath)\n if err != nil {\n log.Fatal(\"Couldn't open config file: \", err)\n }\n\n b, err := ioutil.ReadAll(fi)\n if err != nil {\n log.Fatal(\"Couldn't read config file: \", err)\n }\n\n var cfg GoldenConfig\n json.Unmarshal(b, &cfg)\n\n \/\/ Setup RCON connection\n\trch := make(chan rcon.RCONRequest, 10)\n\trcon := rcon.NewRCON(cfg.Address, cfg.RCONPassword, rch)\n\t\n \/\/ Setup plugins\n greetings := greeter.NewGreeter(\"Greetings! Welcome to the server, %s.\", rch)\n\tvotekick := votes.NewVote(rch)\n advert := advert.NewAdvert(\"ads.txt\", 60000, rch)\n\t\n chain := daisy(greetings, votekick, advert)\n\tgo rcon.Relay()\n\n\tlogchan := make(chan string)\n\tgo tails.Tail(cfg.LogfilePath, logchan, false)\n\tfor {\n\t\tline := <-logch\n chain <- strings.TrimSpace(line)\n\t}\n}\n\ntype Plugin interface {\n\tStart(prev, next chan string)\n}\n\n\/\/ Daisy sets up the daisy chain of plugins for message passing.\n\/\/ Returns a channel on which we can send in messages.\nfunc daisy(plugins ...Plugin) chan string {\n\tlast := make(chan string)\n\tprev := last\n\tnext := last\n\n\tfor _, p := range plugins {\n\t\tprev = make(chan string)\n\t\tgo p.Start(next, prev)\n\t\tnext = prev\n\t}\n\t\/\/ drain the last channel in the chain\n\tgo func(ch chan string) { <-last }(last)\n\treturn prev\n}\n<|endoftext|>"} {"text":"\/\/ A simple database migrator for PostgreSQL.\n\npackage gomigrate\n\nimport (\n\t\"database\/sql\"\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"sort\"\n)\n\nconst (\n\tmigrationTableName = \"gomigrate\"\n)\n\nvar (\n\tupMigrationFile = regexp.MustCompile(`(\\d+)_(\\w+)_up\\.(\\w+)`)\n\tdownMigrationFile = regexp.MustCompile(`(\\d+)_(\\w+)_down\\.(\\w+)`)\n\tInvalidMigrationFile = errors.New(\"Invalid migration file\")\n\tInvalidMigrationPair = errors.New(\"Invalid pair of migration files\")\n\tInvalidMigrationsPath = errors.New(\"Invalid migrations path\")\n)\n\ntype Migrator struct {\n\tDB *sql.DB\n\tMigrationsPath string\n\tdbAdapter Migratable\n\tmigrations map[uint64]*Migration\n}\n\n\/\/ Returns true if the migration table already exists.\nfunc (m *Migrator) MigrationTableExists() (bool, error) {\n\trow := db.QueryRow(m.dbAdapter.SelectMigrationTableSql(), migrationTableName)\n\tvar tableName string\n\terr := row.Scan(&tableName)\n\tif err == sql.ErrNoRows {\n\t\tlog.Print(\"Migrations table not found\")\n\t\treturn false, nil\n\t}\n\tif err != nil {\n\t\tlog.Printf(\"Error checking for migration table: %v\", err)\n\t\treturn false, err\n\t}\n\tlog.Print(\"Migrations table found\")\n\treturn true, nil\n}\n\n\/\/ Creates the migrations table if it doesn't exist.\nfunc (m *Migrator) CreateMigrationsTable() error {\n\tlog.Print(\"Creating migrations table\")\n\n\t_, err := db.Query(m.dbAdapter.CreateMigrationTableSql())\n\tif err != nil {\n\t\tlog.Fatalf(\"Error creating migrations table: %v\", err)\n\t}\n\n\tlog.Printf(\"Created migrations table: %s\", migrationTableName)\n\n\treturn nil\n}\n\n\/\/ Returns a new migrator.\nfunc NewMigrator(db *sql.DB, adapter Migratable, migrationsPath string) (*Migrator, error) {\n\t\/\/ Normalize the migrations path.\n\tpath := []byte(migrationsPath)\n\tpathLength := len(path)\n\tif path[pathLength-1] != '\/' {\n\t\tpath = append(path, '\/')\n\t}\n\n\tlog.Printf(\"Migrations path: %s\", path)\n\n\tmigrator := Migrator{\n\t\tdb,\n\t\tstring(path),\n\t\tadapter,\n\t\tmake(map[uint64]*Migration),\n\t}\n\n\t\/\/ Create the migrations table if it doesn't exist.\n\ttableExists, err := migrator.MigrationTableExists()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !tableExists {\n\t\tif err := migrator.CreateMigrationsTable(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t\/\/ Get all metadata from the database.\n\tif err := migrator.fetchMigrations(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := migrator.getMigrationStatuses(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &migrator, nil\n}\n\n\/\/ Populates a migrator with a sorted list of migrations from the file system.\nfunc (m *Migrator) fetchMigrations() error {\n\tpathGlob := append([]byte(m.MigrationsPath), []byte(\"*\")...)\n\n\tlog.Printf(\"Migrations path glob: %s\", pathGlob)\n\n\tmatches, err := filepath.Glob(string(pathGlob))\n\tif err != nil {\n\t\tlog.Fatalf(\"Error while globbing migrations: %v\", err)\n\t}\n\n\tfor _, match := range matches {\n\t\tnum, migrationType, name, err := parseMigrationPath(match)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Invalid migration file found: %s\", match)\n\t\t\tcontinue\n\t\t}\n\n\t\tlog.Printf(\"Migration file found: %s\", match)\n\n\t\tmigration, ok := m.migrations[num]\n\t\tif !ok {\n\t\t\tmigration = &Migration{Id: num, Name: name, Status: Inactive}\n\t\t\tm.migrations[num] = migration\n\t\t}\n\t\tif migrationType == \"up\" {\n\t\t\tmigration.UpPath = match\n\t\t} else {\n\t\t\tmigration.DownPath = match\n\t\t}\n\t}\n\n\t\/\/ Validate each migration.\n\tfor _, migration := range m.migrations {\n\t\tif !migration.valid() {\n\t\t\tpath := migration.UpPath\n\t\t\tif path == \"\" {\n\t\t\t\tpath = migration.DownPath\n\t\t\t}\n\t\t\tlog.Printf(\"Invalid migration pair for path: %s\", path)\n\t\t\treturn InvalidMigrationPair\n\t\t}\n\t}\n\n\tlog.Printf(\"Migrations file pairs found: %v\", len(m.migrations))\n\n\treturn nil\n}\n\n\/\/ Queries the migration table to determine the status of each\n\/\/ migration.\nfunc (m *Migrator) getMigrationStatuses() error {\n\tfor _, migration := range m.migrations {\n\t\trows, err := m.DB.Query(m.dbAdapter.MigrationStatusSql(), migration.Name)\n\t\tif err != nil {\n\t\t\tlog.Printf(\n\t\t\t\t\"Error getting migration status for %s: %v\",\n\t\t\t\tmigration.Name,\n\t\t\t\terr,\n\t\t\t)\n\t\t\treturn err\n\t\t}\n\t\tfor rows.Next() {\n\t\t\tvar status int\n\t\t\terr := rows.Scan(&status)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error getting migration status: %v\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tmigration.Status = status\n\t\t\tlog.Printf(\n\t\t\t\t\"Migration %s found with status: %v\",\n\t\t\t\tmigration.Name,\n\t\t\t\tstatus,\n\t\t\t)\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ Returns a sorted list of migration ids for a given status.\nfunc (m *Migrator) Migrations(status int) []*Migration {\n\t\/\/ Sort all migration ids.\n\tids := make([]uint64, 0)\n\tfor id, _ := range m.migrations {\n\t\tids = append(ids, id)\n\t}\n\tsort.Sort(uint64slice(ids))\n\n\t\/\/ Find ids for the given status.\n\tmigrations := make([]*Migration, 0)\n\tfor _, id := range ids {\n\t\tmigration := m.migrations[id]\n\t\tif migration.Status == status {\n\t\t\tmigrations = append(migrations, migration)\n\t\t}\n\t}\n\treturn migrations\n}\n\n\/\/ Applies all inactive migrations.\nfunc (m *Migrator) Migrate() error {\n\tfor _, migration := range m.Migrations(Inactive) {\n\t\tlog.Printf(\"Applying migration: %s\", migration.Name)\n\n\t\tsql, err := ioutil.ReadFile(migration.UpPath)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error reading up migration: %s\", migration.Name)\n\t\t\treturn err\n\t\t}\n\t\ttransaction, err := m.DB.Begin()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error opening transaction: %v\", err)\n\t\t\treturn err\n\t\t}\n\t\t\/\/ Perform the migration.\n\t\tif _, err = transaction.Exec(string(sql)); err != nil {\n\t\t\tlog.Printf(\"Error executing migration: %v\", err)\n\t\t\tif rollbackErr := transaction.Rollback(); rollbackErr != nil {\n\t\t\t\tlog.Printf(\"Error rolling back transaction: %v\", rollbackErr)\n\t\t\t\treturn rollbackErr\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\t\/\/ Log the exception in the migrations table.\n\t\t_, err = transaction.Exec(\n\t\t\tm.dbAdapter.MigrationLogInsertSql(),\n\t\t\tmigration.Id,\n\t\t\tmigration.Name,\n\t\t\tActive,\n\t\t)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error logging migration: %v\", err)\n\t\t\tif rollbackErr := transaction.Rollback(); rollbackErr != nil {\n\t\t\t\tlog.Printf(\"Error rolling back transaction: %v\", rollbackErr)\n\t\t\t\treturn rollbackErr\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\tif err := transaction.Commit(); err != nil {\n\t\t\tlog.Printf(\"Error commiting transaction: %v\", err)\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Do this as the last step to ensure that the database has\n\t\t\/\/ been updated.\n\t\tmigration.Status = Active\n\t}\n\treturn nil\n}\n\nvar (\n\tNoActiveMigrations = errors.New(\"No active migrations to rollback\")\n)\n\n\/\/ Rolls back the last migration\nfunc (m *Migrator) Rollback() error {\n\tmigrations := m.Migrations(Active)\n\n\tif len(migrations) == 0 {\n\t\treturn NoActiveMigrations\n\t}\n\n\tlastMigration := migrations[len(migrations)-1]\n\n\tlog.Printf(\"Rolling back migration: %v\", lastMigration.Name)\n\n\tsql, err := ioutil.ReadFile(lastMigration.DownPath)\n\tif err != nil {\n\t\tlog.Printf(\"Error reading migration: %s\", lastMigration.DownPath)\n\t\treturn err\n\t}\n\ttransaction, err := m.DB.Begin()\n\tif err != nil {\n\t\tlog.Printf(\"Error creating transaction: %v\", err)\n\t\treturn err\n\t}\n\t_, err = transaction.Exec(string(sql))\n\tif err != nil {\n\t\ttransaction.Rollback()\n\t\tlog.Printf(\"Error rolling back transaction: %v\", err)\n\t\treturn err\n\t}\n\n\t\/\/ Change the status in the migrations table.\n\t_, err = transaction.Exec(\n\t\tm.dbAdapter.MigrationLogUpdateSql(),\n\t\tInactive,\n\t\tlastMigration.Id,\n\t)\n\tif err != nil {\n\t\tlog.Printf(\"Error logging rollback: %v\", err)\n\t\tif rollbackErr := transaction.Rollback(); rollbackErr != nil {\n\t\t\tlog.Printf(\"Error rolling back transaction: %v\", rollbackErr)\n\t\t\treturn rollbackErr\n\t\t}\n\t\treturn err\n\t}\n\n\terr = transaction.Commit()\n\tif err != nil {\n\t\tlog.Printf(\"Error commiting transaction: %v\", err)\n\t\treturn err\n\t}\n\tlastMigration.Status = Inactive\n\treturn nil\n}\nBug fix\/\/ A simple database migrator for PostgreSQL.\n\npackage gomigrate\n\nimport (\n\t\"database\/sql\"\n\t\"errors\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"sort\"\n)\n\nconst (\n\tmigrationTableName = \"gomigrate\"\n)\n\nvar (\n\tupMigrationFile = regexp.MustCompile(`(\\d+)_(\\w+)_up\\.(\\w+)`)\n\tdownMigrationFile = regexp.MustCompile(`(\\d+)_(\\w+)_down\\.(\\w+)`)\n\tInvalidMigrationFile = errors.New(\"Invalid migration file\")\n\tInvalidMigrationPair = errors.New(\"Invalid pair of migration files\")\n\tInvalidMigrationsPath = errors.New(\"Invalid migrations path\")\n)\n\ntype Migrator struct {\n\tDB *sql.DB\n\tMigrationsPath string\n\tdbAdapter Migratable\n\tmigrations map[uint64]*Migration\n}\n\n\/\/ Returns true if the migration table already exists.\nfunc (m *Migrator) MigrationTableExists() (bool, error) {\n\trow := m.DB.QueryRow(m.dbAdapter.SelectMigrationTableSql(), migrationTableName)\n\tvar tableName string\n\terr := row.Scan(&tableName)\n\tif err == sql.ErrNoRows {\n\t\tlog.Print(\"Migrations table not found\")\n\t\treturn false, nil\n\t}\n\tif err != nil {\n\t\tlog.Printf(\"Error checking for migration table: %v\", err)\n\t\treturn false, err\n\t}\n\tlog.Print(\"Migrations table found\")\n\treturn true, nil\n}\n\n\/\/ Creates the migrations table if it doesn't exist.\nfunc (m *Migrator) CreateMigrationsTable() error {\n\tlog.Print(\"Creating migrations table\")\n\n\t_, err := m.DB.Query(m.dbAdapter.CreateMigrationTableSql())\n\tif err != nil {\n\t\tlog.Fatalf(\"Error creating migrations table: %v\", err)\n\t}\n\n\tlog.Printf(\"Created migrations table: %s\", migrationTableName)\n\n\treturn nil\n}\n\n\/\/ Returns a new migrator.\nfunc NewMigrator(db *sql.DB, adapter Migratable, migrationsPath string) (*Migrator, error) {\n\t\/\/ Normalize the migrations path.\n\tpath := []byte(migrationsPath)\n\tpathLength := len(path)\n\tif path[pathLength-1] != '\/' {\n\t\tpath = append(path, '\/')\n\t}\n\n\tlog.Printf(\"Migrations path: %s\", path)\n\n\tmigrator := Migrator{\n\t\tdb,\n\t\tstring(path),\n\t\tadapter,\n\t\tmake(map[uint64]*Migration),\n\t}\n\n\t\/\/ Create the migrations table if it doesn't exist.\n\ttableExists, err := migrator.MigrationTableExists()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !tableExists {\n\t\tif err := migrator.CreateMigrationsTable(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t\/\/ Get all metadata from the database.\n\tif err := migrator.fetchMigrations(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := migrator.getMigrationStatuses(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &migrator, nil\n}\n\n\/\/ Populates a migrator with a sorted list of migrations from the file system.\nfunc (m *Migrator) fetchMigrations() error {\n\tpathGlob := append([]byte(m.MigrationsPath), []byte(\"*\")...)\n\n\tlog.Printf(\"Migrations path glob: %s\", pathGlob)\n\n\tmatches, err := filepath.Glob(string(pathGlob))\n\tif err != nil {\n\t\tlog.Fatalf(\"Error while globbing migrations: %v\", err)\n\t}\n\n\tfor _, match := range matches {\n\t\tnum, migrationType, name, err := parseMigrationPath(match)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Invalid migration file found: %s\", match)\n\t\t\tcontinue\n\t\t}\n\n\t\tlog.Printf(\"Migration file found: %s\", match)\n\n\t\tmigration, ok := m.migrations[num]\n\t\tif !ok {\n\t\t\tmigration = &Migration{Id: num, Name: name, Status: Inactive}\n\t\t\tm.migrations[num] = migration\n\t\t}\n\t\tif migrationType == \"up\" {\n\t\t\tmigration.UpPath = match\n\t\t} else {\n\t\t\tmigration.DownPath = match\n\t\t}\n\t}\n\n\t\/\/ Validate each migration.\n\tfor _, migration := range m.migrations {\n\t\tif !migration.valid() {\n\t\t\tpath := migration.UpPath\n\t\t\tif path == \"\" {\n\t\t\t\tpath = migration.DownPath\n\t\t\t}\n\t\t\tlog.Printf(\"Invalid migration pair for path: %s\", path)\n\t\t\treturn InvalidMigrationPair\n\t\t}\n\t}\n\n\tlog.Printf(\"Migrations file pairs found: %v\", len(m.migrations))\n\n\treturn nil\n}\n\n\/\/ Queries the migration table to determine the status of each\n\/\/ migration.\nfunc (m *Migrator) getMigrationStatuses() error {\n\tfor _, migration := range m.migrations {\n\t\trows, err := m.DB.Query(m.dbAdapter.MigrationStatusSql(), migration.Name)\n\t\tif err != nil {\n\t\t\tlog.Printf(\n\t\t\t\t\"Error getting migration status for %s: %v\",\n\t\t\t\tmigration.Name,\n\t\t\t\terr,\n\t\t\t)\n\t\t\treturn err\n\t\t}\n\t\tfor rows.Next() {\n\t\t\tvar status int\n\t\t\terr := rows.Scan(&status)\n\t\t\tif err != nil {\n\t\t\t\tlog.Printf(\"Error getting migration status: %v\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tmigration.Status = status\n\t\t\tlog.Printf(\n\t\t\t\t\"Migration %s found with status: %v\",\n\t\t\t\tmigration.Name,\n\t\t\t\tstatus,\n\t\t\t)\n\t\t}\n\t}\n\treturn nil\n}\n\n\/\/ Returns a sorted list of migration ids for a given status.\nfunc (m *Migrator) Migrations(status int) []*Migration {\n\t\/\/ Sort all migration ids.\n\tids := make([]uint64, 0)\n\tfor id, _ := range m.migrations {\n\t\tids = append(ids, id)\n\t}\n\tsort.Sort(uint64slice(ids))\n\n\t\/\/ Find ids for the given status.\n\tmigrations := make([]*Migration, 0)\n\tfor _, id := range ids {\n\t\tmigration := m.migrations[id]\n\t\tif migration.Status == status {\n\t\t\tmigrations = append(migrations, migration)\n\t\t}\n\t}\n\treturn migrations\n}\n\n\/\/ Applies all inactive migrations.\nfunc (m *Migrator) Migrate() error {\n\tfor _, migration := range m.Migrations(Inactive) {\n\t\tlog.Printf(\"Applying migration: %s\", migration.Name)\n\n\t\tsql, err := ioutil.ReadFile(migration.UpPath)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error reading up migration: %s\", migration.Name)\n\t\t\treturn err\n\t\t}\n\t\ttransaction, err := m.DB.Begin()\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error opening transaction: %v\", err)\n\t\t\treturn err\n\t\t}\n\t\t\/\/ Perform the migration.\n\t\tif _, err = transaction.Exec(string(sql)); err != nil {\n\t\t\tlog.Printf(\"Error executing migration: %v\", err)\n\t\t\tif rollbackErr := transaction.Rollback(); rollbackErr != nil {\n\t\t\t\tlog.Printf(\"Error rolling back transaction: %v\", rollbackErr)\n\t\t\t\treturn rollbackErr\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\t\/\/ Log the exception in the migrations table.\n\t\t_, err = transaction.Exec(\n\t\t\tm.dbAdapter.MigrationLogInsertSql(),\n\t\t\tmigration.Id,\n\t\t\tmigration.Name,\n\t\t\tActive,\n\t\t)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error logging migration: %v\", err)\n\t\t\tif rollbackErr := transaction.Rollback(); rollbackErr != nil {\n\t\t\t\tlog.Printf(\"Error rolling back transaction: %v\", rollbackErr)\n\t\t\t\treturn rollbackErr\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\tif err := transaction.Commit(); err != nil {\n\t\t\tlog.Printf(\"Error commiting transaction: %v\", err)\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ Do this as the last step to ensure that the database has\n\t\t\/\/ been updated.\n\t\tmigration.Status = Active\n\t}\n\treturn nil\n}\n\nvar (\n\tNoActiveMigrations = errors.New(\"No active migrations to rollback\")\n)\n\n\/\/ Rolls back the last migration\nfunc (m *Migrator) Rollback() error {\n\tmigrations := m.Migrations(Active)\n\n\tif len(migrations) == 0 {\n\t\treturn NoActiveMigrations\n\t}\n\n\tlastMigration := migrations[len(migrations)-1]\n\n\tlog.Printf(\"Rolling back migration: %v\", lastMigration.Name)\n\n\tsql, err := ioutil.ReadFile(lastMigration.DownPath)\n\tif err != nil {\n\t\tlog.Printf(\"Error reading migration: %s\", lastMigration.DownPath)\n\t\treturn err\n\t}\n\ttransaction, err := m.DB.Begin()\n\tif err != nil {\n\t\tlog.Printf(\"Error creating transaction: %v\", err)\n\t\treturn err\n\t}\n\t_, err = transaction.Exec(string(sql))\n\tif err != nil {\n\t\ttransaction.Rollback()\n\t\tlog.Printf(\"Error rolling back transaction: %v\", err)\n\t\treturn err\n\t}\n\n\t\/\/ Change the status in the migrations table.\n\t_, err = transaction.Exec(\n\t\tm.dbAdapter.MigrationLogUpdateSql(),\n\t\tInactive,\n\t\tlastMigration.Id,\n\t)\n\tif err != nil {\n\t\tlog.Printf(\"Error logging rollback: %v\", err)\n\t\tif rollbackErr := transaction.Rollback(); rollbackErr != nil {\n\t\t\tlog.Printf(\"Error rolling back transaction: %v\", rollbackErr)\n\t\t\treturn rollbackErr\n\t\t}\n\t\treturn err\n\t}\n\n\terr = transaction.Commit()\n\tif err != nil {\n\t\tlog.Printf(\"Error commiting transaction: %v\", err)\n\t\treturn err\n\t}\n\tlastMigration.Status = Inactive\n\treturn nil\n}\n<|endoftext|>"} {"text":"package config\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\"\n\t\"strings\"\n\n\t\"github.com\/EngineerBetter\/concourse-up\/iaas\"\n\t\"github.com\/asaskevich\/govalidator\"\n)\n\nconst terraformStateFileName = \"terraform.tfstate\"\nconst configFilePath = \"config.json\"\n\n\/\/ IClient is an interface for the config file client\ntype IClient interface {\n\tLoad() (Config, error)\n\tDeleteAll(config Config) error\n\tLoadOrCreate(deployArgs *DeployArgs) (Config, bool, bool, error)\n\tUpdate(Config) error\n\tStoreAsset(filename string, contents []byte) error\n\tHasAsset(filename string) (bool, error)\n\tLoadAsset(filename string) ([]byte, error)\n\tDeleteAsset(filename string) error\n}\n\n\/\/ Client is a client for loading the config file from S3\ntype Client struct {\n\tIaas iaas.Provider\n\tProject string\n\tNamespace string\n\tBucketName string\n\tBucketExists bool\n\tBucketError error\n\tConfig *Config\n}\n\n\/\/ New instantiates a new client\nfunc New(iaas iaas.Provider, project, namespace string) *Client {\n\tnamespace = determineNamespace(namespace, iaas.Region())\n\tbucketName, exists, err := determineBucketName(iaas, namespace, project)\n\n\tif !exists && err == nil {\n\t\terr = iaas.CreateBucket(bucketName)\n\t}\n\n\treturn &Client{\n\t\tiaas,\n\t\tproject,\n\t\tnamespace,\n\t\tbucketName,\n\t\texists,\n\t\terr,\n\t\t&Config{},\n\t}\n}\n\n\/\/ StoreAsset stores an associated configuration file\nfunc (client *Client) StoreAsset(filename string, contents []byte) error {\n\treturn client.Iaas.WriteFile(client.configBucket(),\n\t\tfilename,\n\t\tcontents,\n\t)\n}\n\n\/\/ LoadAsset loads an associated configuration file\nfunc (client *Client) LoadAsset(filename string) ([]byte, error) {\n\treturn client.Iaas.LoadFile(\n\t\tclient.configBucket(),\n\t\tfilename,\n\t)\n}\n\n\/\/ DeleteAsset deletes an associated configuration file\nfunc (client *Client) DeleteAsset(filename string) error {\n\treturn client.Iaas.DeleteFile(\n\t\tclient.configBucket(),\n\t\tfilename,\n\t)\n}\n\n\/\/ HasAsset returns true if an associated configuration file exists\nfunc (client *Client) HasAsset(filename string) (bool, error) {\n\treturn client.Iaas.HasFile(\n\t\tclient.configBucket(),\n\t\tfilename,\n\t)\n}\n\n\/\/ Update stores the conconcourse up config file to S3\nfunc (client *Client) Update(config Config) error {\n\tbytes, err := json.Marshal(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn client.Iaas.WriteFile(client.configBucket(), configFilePath, bytes)\n}\n\n\/\/ DeleteAll deletes the entire configuration bucket\nfunc (client *Client) DeleteAll(config Config) error {\n\treturn client.Iaas.DeleteVersionedBucket(config.ConfigBucket)\n}\n\n\/\/ Load loads an existing config file from S3\nfunc (client *Client) Load() (Config, error) {\n\tif client.BucketError != nil {\n\t\treturn Config{}, client.BucketError\n\t}\n\n\tconfigBytes, err := client.Iaas.LoadFile(\n\t\tclient.configBucket(),\n\t\tconfigFilePath,\n\t)\n\tif err != nil {\n\t\treturn Config{}, err\n\t}\n\n\tconf := Config{}\n\tif err := json.Unmarshal(configBytes, &conf); err != nil {\n\t\treturn Config{}, err\n\t}\n\n\treturn conf, nil\n}\n\n\/\/ LoadOrCreate loads an existing config file from S3, or creates a default if one doesn't already exist\nfunc (client *Client) LoadOrCreate(deployArgs *DeployArgs) (Config, bool, bool, error) {\n\n\tvar isDomainUpdated bool\n\n\tif client.BucketError != nil {\n\t\treturn Config{}, false, false, client.BucketError\n\t}\n\n\tconfig, err := generateDefaultConfig(\n\t\tclient.Project,\n\t\tdeployment(client.Project),\n\t\tclient.configBucket(),\n\t\tclient.Iaas.Region(),\n\t\tclient.Namespace,\n\t)\n\tif err != nil {\n\t\treturn Config{}, false, false, err\n\t}\n\n\tdefaultConfigBytes, err := json.Marshal(&config)\n\tif err != nil {\n\t\treturn Config{}, false, false, err\n\t}\n\n\tconfigBytes, newConfigCreated, err := client.Iaas.EnsureFileExists(\n\t\tclient.configBucket(),\n\t\tconfigFilePath,\n\t\tdefaultConfigBytes,\n\t)\n\tif err != nil {\n\t\treturn Config{}, newConfigCreated, false, err\n\t}\n\n\terr = json.Unmarshal(configBytes, &config)\n\tif err != nil {\n\t\treturn Config{}, newConfigCreated, false, err\n\t}\n\n\tallow, err := parseCIDRBlocks(deployArgs.AllowIPs)\n\tif err != nil {\n\t\treturn Config{}, newConfigCreated, false, err\n\t}\n\n\tconfig, err = updateAllowedIPs(config, allow)\n\tif err != nil {\n\t\treturn Config{}, newConfigCreated, false, err\n\t}\n\n\tif newConfigCreated {\n\t\tconfig.IAAS = deployArgs.IAAS\n\t}\n\n\tif deployArgs.ZoneIsSet {\n\t\tconfig.AvailabilityZone = deployArgs.Zone\n\t}\n\tif newConfigCreated || deployArgs.WorkerCountIsSet {\n\t\tconfig.ConcourseWorkerCount = deployArgs.WorkerCount\n\t}\n\tif newConfigCreated || deployArgs.WorkerSizeIsSet {\n\t\tconfig.ConcourseWorkerSize = deployArgs.WorkerSize\n\t}\n\tif newConfigCreated || deployArgs.WebSizeIsSet {\n\t\tconfig.ConcourseWebSize = deployArgs.WebSize\n\t}\n\tif newConfigCreated || deployArgs.DBSizeIsSet {\n\t\tconfig.RDSInstanceClass = DBSizes[deployArgs.DBSize]\n\t}\n\tif newConfigCreated || deployArgs.GithubAuthIsSet {\n\t\tconfig.GithubClientID = deployArgs.GithubAuthClientID\n\t\tconfig.GithubClientSecret = deployArgs.GithubAuthClientSecret\n\t\tconfig.GithubAuthIsSet = deployArgs.GithubAuthIsSet\n\t}\n\tif newConfigCreated || deployArgs.TagsIsSet {\n\t\tconfig.Tags = deployArgs.Tags\n\t}\n\tif newConfigCreated || deployArgs.SpotIsSet {\n\t\tconfig.Spot = deployArgs.Spot\n\t}\n\tif newConfigCreated || deployArgs.WorkerTypeIsSet {\n\t\tconfig.WorkerType = deployArgs.WorkerType\n\t}\n\n\tif newConfigCreated || deployArgs.DomainIsSet {\n\t\tif config.Domain != deployArgs.Domain {\n\t\t\tisDomainUpdated = true\n\t\t}\n\t\tconfig.Domain = deployArgs.Domain\n\t} else {\n\t\tif govalidator.IsIPv4(config.Domain) {\n\t\t\tconfig.Domain = \"\"\n\t\t}\n\t}\n\treturn config, newConfigCreated, isDomainUpdated, nil\n}\n\nfunc (client *Client) configBucket() string {\n\treturn client.BucketName\n}\n\nfunc deployment(project string) string {\n\treturn fmt.Sprintf(\"concourse-up-%s\", project)\n}\n\nfunc createBucketName(deployment, extension string) string {\n\treturn fmt.Sprintf(\"%s-%s-config\", deployment, extension)\n}\n\nfunc determineBucketName(iaas iaas.Provider, namespace, project string) (string, bool, error) {\n\tregionBucketName := createBucketName(deployment(project), iaas.Region())\n\tnamespaceBucketName := createBucketName(deployment(project), namespace)\n\n\tfoundRegionNamedBucket, err := iaas.BucketExists(regionBucketName)\n\tif err != nil {\n\t\treturn \"\", false, err\n\t}\n\tfoundNamespacedBucket, err := iaas.BucketExists(namespaceBucketName)\n\tif err != nil {\n\t\treturn \"\", false, err\n\t}\n\n\tfoundOne := foundRegionNamedBucket || foundNamespacedBucket\n\n\tswitch {\n\tcase !foundRegionNamedBucket && foundNamespacedBucket:\n\t\treturn namespaceBucketName, foundOne, nil\n\tcase foundRegionNamedBucket && !foundNamespacedBucket:\n\t\treturn regionBucketName, foundOne, nil\n\tdefault:\n\t\treturn namespaceBucketName, foundOne, nil\n\t}\n}\n\ntype cidrBlocks []*net.IPNet\n\nfunc parseCIDRBlocks(s string) (cidrBlocks, error) {\n\tvar x cidrBlocks\n\tfor _, ip := range strings.Split(s, \",\") {\n\t\tip = strings.TrimSpace(ip)\n\t\t_, ipNet, err := net.ParseCIDR(ip)\n\t\tif err != nil {\n\t\t\tipNet = &net.IPNet{\n\t\t\t\tIP: net.ParseIP(ip),\n\t\t\t\tMask: net.CIDRMask(32, 32),\n\t\t\t}\n\t\t}\n\t\tif ipNet.IP == nil {\n\t\t\treturn nil, fmt.Errorf(\"could not parse %q as an IP address or CIDR range\", ip)\n\t\t}\n\t\tx = append(x, ipNet)\n\t}\n\treturn x, nil\n}\n\nfunc (b cidrBlocks) String() (string, error) {\n\tvar buf bytes.Buffer\n\tfor i, ipNet := range b {\n\t\tif i > 0 {\n\t\t\t_, err := fmt.Fprintf(&buf, \", %q\", ipNet)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t} else {\n\t\t\t_, err := fmt.Fprintf(&buf, \"%q\", ipNet)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t}\n\t}\n\treturn buf.String(), nil\n}\n\nfunc determineNamespace(namespace, region string) string {\n\tif namespace == \"\" {\n\t\treturn region\n\t}\n\treturn namespace\n}\nerroneous zone arguments should be trapped while redeployingpackage config\n\nimport (\n\t\"bytes\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"net\"\n\t\"strings\"\n\n\t\"github.com\/EngineerBetter\/concourse-up\/iaas\"\n\t\"github.com\/asaskevich\/govalidator\"\n)\n\nconst terraformStateFileName = \"terraform.tfstate\"\nconst configFilePath = \"config.json\"\n\n\/\/ IClient is an interface for the config file client\ntype IClient interface {\n\tLoad() (Config, error)\n\tDeleteAll(config Config) error\n\tLoadOrCreate(deployArgs *DeployArgs) (Config, bool, bool, error)\n\tUpdate(Config) error\n\tStoreAsset(filename string, contents []byte) error\n\tHasAsset(filename string) (bool, error)\n\tLoadAsset(filename string) ([]byte, error)\n\tDeleteAsset(filename string) error\n}\n\n\/\/ Client is a client for loading the config file from S3\ntype Client struct {\n\tIaas iaas.Provider\n\tProject string\n\tNamespace string\n\tBucketName string\n\tBucketExists bool\n\tBucketError error\n\tConfig *Config\n}\n\n\/\/ New instantiates a new client\nfunc New(iaas iaas.Provider, project, namespace string) *Client {\n\tnamespace = determineNamespace(namespace, iaas.Region())\n\tbucketName, exists, err := determineBucketName(iaas, namespace, project)\n\n\tif !exists && err == nil {\n\t\terr = iaas.CreateBucket(bucketName)\n\t}\n\n\treturn &Client{\n\t\tiaas,\n\t\tproject,\n\t\tnamespace,\n\t\tbucketName,\n\t\texists,\n\t\terr,\n\t\t&Config{},\n\t}\n}\n\n\/\/ StoreAsset stores an associated configuration file\nfunc (client *Client) StoreAsset(filename string, contents []byte) error {\n\treturn client.Iaas.WriteFile(client.configBucket(),\n\t\tfilename,\n\t\tcontents,\n\t)\n}\n\n\/\/ LoadAsset loads an associated configuration file\nfunc (client *Client) LoadAsset(filename string) ([]byte, error) {\n\treturn client.Iaas.LoadFile(\n\t\tclient.configBucket(),\n\t\tfilename,\n\t)\n}\n\n\/\/ DeleteAsset deletes an associated configuration file\nfunc (client *Client) DeleteAsset(filename string) error {\n\treturn client.Iaas.DeleteFile(\n\t\tclient.configBucket(),\n\t\tfilename,\n\t)\n}\n\n\/\/ HasAsset returns true if an associated configuration file exists\nfunc (client *Client) HasAsset(filename string) (bool, error) {\n\treturn client.Iaas.HasFile(\n\t\tclient.configBucket(),\n\t\tfilename,\n\t)\n}\n\n\/\/ Update stores the conconcourse up config file to S3\nfunc (client *Client) Update(config Config) error {\n\tbytes, err := json.Marshal(config)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn client.Iaas.WriteFile(client.configBucket(), configFilePath, bytes)\n}\n\n\/\/ DeleteAll deletes the entire configuration bucket\nfunc (client *Client) DeleteAll(config Config) error {\n\treturn client.Iaas.DeleteVersionedBucket(config.ConfigBucket)\n}\n\n\/\/ Load loads an existing config file from S3\nfunc (client *Client) Load() (Config, error) {\n\tif client.BucketError != nil {\n\t\treturn Config{}, client.BucketError\n\t}\n\n\tconfigBytes, err := client.Iaas.LoadFile(\n\t\tclient.configBucket(),\n\t\tconfigFilePath,\n\t)\n\tif err != nil {\n\t\treturn Config{}, err\n\t}\n\n\tconf := Config{}\n\tif err := json.Unmarshal(configBytes, &conf); err != nil {\n\t\treturn Config{}, err\n\t}\n\n\treturn conf, nil\n}\n\n\/\/ LoadOrCreate loads an existing config file from S3, or creates a default if one doesn't already exist\nfunc (client *Client) LoadOrCreate(deployArgs *DeployArgs) (Config, bool, bool, error) {\n\n\tvar isDomainUpdated bool\n\n\tif client.BucketError != nil {\n\t\treturn Config{}, false, false, client.BucketError\n\t}\n\n\tconfig, err := generateDefaultConfig(\n\t\tclient.Project,\n\t\tdeployment(client.Project),\n\t\tclient.configBucket(),\n\t\tclient.Iaas.Region(),\n\t\tclient.Namespace,\n\t)\n\tif err != nil {\n\t\treturn Config{}, false, false, err\n\t}\n\n\tdefaultConfigBytes, err := json.Marshal(&config)\n\tif err != nil {\n\t\treturn Config{}, false, false, err\n\t}\n\n\tconfigBytes, newConfigCreated, err := client.Iaas.EnsureFileExists(\n\t\tclient.configBucket(),\n\t\tconfigFilePath,\n\t\tdefaultConfigBytes,\n\t)\n\tif err != nil {\n\t\treturn Config{}, newConfigCreated, false, err\n\t}\n\n\terr = json.Unmarshal(configBytes, &config)\n\tif err != nil {\n\t\treturn Config{}, newConfigCreated, false, err\n\t}\n\n\tallow, err := parseCIDRBlocks(deployArgs.AllowIPs)\n\tif err != nil {\n\t\treturn Config{}, newConfigCreated, false, err\n\t}\n\n\tconfig, err = updateAllowedIPs(config, allow)\n\tif err != nil {\n\t\treturn Config{}, newConfigCreated, false, err\n\t}\n\n\tif newConfigCreated {\n\t\tconfig.IAAS = deployArgs.IAAS\n\t}\n\n\tif deployArgs.ZoneIsSet {\n\t\t\/\/ This is a safeguard for a redeployment where zone does not belong to the region where the original deployment has happened\n\t\tif !newConfigCreated && !strings.Contains(deployArgs.Zone, config.AvailabilityZone) {\n\t\t\treturn Config{}, false, false, fmt.Errorf(\"Zone %s does not belong to region %s\", deployArgs.Zone, config.AvailabilityZone)\n\t\t}\n\t\tconfig.AvailabilityZone = deployArgs.Zone\n\t}\n\tif newConfigCreated || deployArgs.WorkerCountIsSet {\n\t\tconfig.ConcourseWorkerCount = deployArgs.WorkerCount\n\t}\n\tif newConfigCreated || deployArgs.WorkerSizeIsSet {\n\t\tconfig.ConcourseWorkerSize = deployArgs.WorkerSize\n\t}\n\tif newConfigCreated || deployArgs.WebSizeIsSet {\n\t\tconfig.ConcourseWebSize = deployArgs.WebSize\n\t}\n\tif newConfigCreated || deployArgs.DBSizeIsSet {\n\t\tconfig.RDSInstanceClass = DBSizes[deployArgs.DBSize]\n\t}\n\tif newConfigCreated || deployArgs.GithubAuthIsSet {\n\t\tconfig.GithubClientID = deployArgs.GithubAuthClientID\n\t\tconfig.GithubClientSecret = deployArgs.GithubAuthClientSecret\n\t\tconfig.GithubAuthIsSet = deployArgs.GithubAuthIsSet\n\t}\n\tif newConfigCreated || deployArgs.TagsIsSet {\n\t\tconfig.Tags = deployArgs.Tags\n\t}\n\tif newConfigCreated || deployArgs.SpotIsSet {\n\t\tconfig.Spot = deployArgs.Spot\n\t}\n\tif newConfigCreated || deployArgs.WorkerTypeIsSet {\n\t\tconfig.WorkerType = deployArgs.WorkerType\n\t}\n\n\tif newConfigCreated || deployArgs.DomainIsSet {\n\t\tif config.Domain != deployArgs.Domain {\n\t\t\tisDomainUpdated = true\n\t\t}\n\t\tconfig.Domain = deployArgs.Domain\n\t} else {\n\t\tif govalidator.IsIPv4(config.Domain) {\n\t\t\tconfig.Domain = \"\"\n\t\t}\n\t}\n\treturn config, newConfigCreated, isDomainUpdated, nil\n}\n\nfunc (client *Client) configBucket() string {\n\treturn client.BucketName\n}\n\nfunc deployment(project string) string {\n\treturn fmt.Sprintf(\"concourse-up-%s\", project)\n}\n\nfunc createBucketName(deployment, extension string) string {\n\treturn fmt.Sprintf(\"%s-%s-config\", deployment, extension)\n}\n\nfunc determineBucketName(iaas iaas.Provider, namespace, project string) (string, bool, error) {\n\tregionBucketName := createBucketName(deployment(project), iaas.Region())\n\tnamespaceBucketName := createBucketName(deployment(project), namespace)\n\n\tfoundRegionNamedBucket, err := iaas.BucketExists(regionBucketName)\n\tif err != nil {\n\t\treturn \"\", false, err\n\t}\n\tfoundNamespacedBucket, err := iaas.BucketExists(namespaceBucketName)\n\tif err != nil {\n\t\treturn \"\", false, err\n\t}\n\n\tfoundOne := foundRegionNamedBucket || foundNamespacedBucket\n\n\tswitch {\n\tcase !foundRegionNamedBucket && foundNamespacedBucket:\n\t\treturn namespaceBucketName, foundOne, nil\n\tcase foundRegionNamedBucket && !foundNamespacedBucket:\n\t\treturn regionBucketName, foundOne, nil\n\tdefault:\n\t\treturn namespaceBucketName, foundOne, nil\n\t}\n}\n\ntype cidrBlocks []*net.IPNet\n\nfunc parseCIDRBlocks(s string) (cidrBlocks, error) {\n\tvar x cidrBlocks\n\tfor _, ip := range strings.Split(s, \",\") {\n\t\tip = strings.TrimSpace(ip)\n\t\t_, ipNet, err := net.ParseCIDR(ip)\n\t\tif err != nil {\n\t\t\tipNet = &net.IPNet{\n\t\t\t\tIP: net.ParseIP(ip),\n\t\t\t\tMask: net.CIDRMask(32, 32),\n\t\t\t}\n\t\t}\n\t\tif ipNet.IP == nil {\n\t\t\treturn nil, fmt.Errorf(\"could not parse %q as an IP address or CIDR range\", ip)\n\t\t}\n\t\tx = append(x, ipNet)\n\t}\n\treturn x, nil\n}\n\nfunc (b cidrBlocks) String() (string, error) {\n\tvar buf bytes.Buffer\n\tfor i, ipNet := range b {\n\t\tif i > 0 {\n\t\t\t_, err := fmt.Fprintf(&buf, \", %q\", ipNet)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t} else {\n\t\t\t_, err := fmt.Fprintf(&buf, \"%q\", ipNet)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t}\n\t}\n\treturn buf.String(), nil\n}\n\nfunc determineNamespace(namespace, region string) string {\n\tif namespace == \"\" {\n\t\treturn region\n\t}\n\treturn namespace\n}\n<|endoftext|>"} {"text":"package config\n\nimport (\n\t\"flag\"\n\t\"github.com\/GeertJohan\/go.rice\"\n\t\"gopkg.in\/yaml.v2\"\n\t\"io\/ioutil\"\n\t\"os\"\n)\n\nvar configFileName = \".\/config.yml\"\n\nfunc init() {\n\tflag.StringVar(&configFileName, \"config\", \".\/config.yml\", \"Config File Location\")\n}\n\ntype Config struct {\n\tSite SiteConfig `yaml:\"site\"` \/\/ Site\/HTML Configuration\n\tDB DBConfig `yaml:\"db\"` \/\/ Database Configuration\n\tHostnameWhiteList []string `yaml:\"hosts\"` \/\/ List of valid hostnames, ignored if empty\n\tListenOn string `yaml:\"listen_on\"` \/\/ Address & Port to use\n\tMasterSecret string `yaml:\"secret\"` \/\/ Master Secret for keychain\n\tDisableSecurity bool `yaml:\"disable_security\"` \/\/ Disables various flags to ensure non-HTTPS requests work\n\tCaptcha CaptchaConfig `yaml:\"captcha\"`\n}\n\nconst (\n\tCaptchaRecaptcha = \"recaptcha\"\n\tCaptchaInternal = \"internal\"\n\tCaptchaHybrid = \"hybrid\"\n\tCaptchaDisabled = \"disabled\"\n)\n\ntype CaptchaConfig struct {\n\tMode string `yaml:\"mode\"` \/\/ Captcha Mode\n\tSettings map[string]string `yaml:\"settings,inline\"`\n}\n\ntype SiteConfig struct {\n\tTitle string `yaml:\"title\"` \/\/ Site Title\n\tDescription string `yaml:\"description\"` \/\/ Site Description\n\tPrimaryColor string `yaml:\"color\"` \/\/ Primary Color for Size\n}\n\ntype DBConfig struct {\n\tFile string `yaml:\"file\"`\n\tReadOnly bool `yaml:\"read_only\"`\n}\n\nfunc Load() (*Config, error) {\n\tvar config = &Config{\n\t\tSite: SiteConfig{\n\t\t\tTitle: \"NyxChan\",\n\t\t\tPrimaryColor: \"#78909c\",\n\t\t\tDescription: \"NyxChan Default Configuration\",\n\t\t},\n\t\tDB: DBConfig{\n\t\t\tFile: \":memory:\",\n\t\t\tReadOnly: false,\n\t\t},\n\t\tHostnameWhiteList: []string{},\n\t\tListenOn: \":8080\",\n\t\tMasterSecret: \"changeme\",\n\t\tDisableSecurity: false,\n\t\tCaptcha: CaptchaConfig{\n\t\t\tMode: CaptchaDisabled,\n\t\t},\n\t}\n\tif _, err := os.Stat(configFileName); os.IsNotExist(err) {\n\t\treturn config, nil\n\t}\n\tdat, err := ioutil.ReadFile(configFileName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = yaml.Unmarshal(dat, config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn config, nil\n}\n\nfunc (c Config) IsHostNameValid(hostname string) bool {\n\tif c.HostnameWhiteList == nil {\n\t\treturn true\n\t}\n\tif len(c.HostnameWhiteList) == 0 {\n\t\treturn true\n\t}\n\tfor _, v := range c.HostnameWhiteList {\n\t\tif v == hostname {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\nRemoved unused importpackage config\n\nimport (\n\t\"flag\"\n\t\"gopkg.in\/yaml.v2\"\n\t\"io\/ioutil\"\n\t\"os\"\n)\n\nvar configFileName = \".\/config.yml\"\n\nfunc init() {\n\tflag.StringVar(&configFileName, \"config\", \".\/config.yml\", \"Config File Location\")\n}\n\ntype Config struct {\n\tSite SiteConfig `yaml:\"site\"` \/\/ Site\/HTML Configuration\n\tDB DBConfig `yaml:\"db\"` \/\/ Database Configuration\n\tHostnameWhiteList []string `yaml:\"hosts\"` \/\/ List of valid hostnames, ignored if empty\n\tListenOn string `yaml:\"listen_on\"` \/\/ Address & Port to use\n\tMasterSecret string `yaml:\"secret\"` \/\/ Master Secret for keychain\n\tDisableSecurity bool `yaml:\"disable_security\"` \/\/ Disables various flags to ensure non-HTTPS requests work\n\tCaptcha CaptchaConfig `yaml:\"captcha\"`\n}\n\nconst (\n\tCaptchaRecaptcha = \"recaptcha\"\n\tCaptchaInternal = \"internal\"\n\tCaptchaHybrid = \"hybrid\"\n\tCaptchaDisabled = \"disabled\"\n)\n\ntype CaptchaConfig struct {\n\tMode string `yaml:\"mode\"` \/\/ Captcha Mode\n\tSettings map[string]string `yaml:\"settings,inline\"`\n}\n\ntype SiteConfig struct {\n\tTitle string `yaml:\"title\"` \/\/ Site Title\n\tDescription string `yaml:\"description\"` \/\/ Site Description\n\tPrimaryColor string `yaml:\"color\"` \/\/ Primary Color for Size\n}\n\ntype DBConfig struct {\n\tFile string `yaml:\"file\"`\n\tReadOnly bool `yaml:\"read_only\"`\n}\n\nfunc Load() (*Config, error) {\n\tvar config = &Config{\n\t\tSite: SiteConfig{\n\t\t\tTitle: \"NyxChan\",\n\t\t\tPrimaryColor: \"#78909c\",\n\t\t\tDescription: \"NyxChan Default Configuration\",\n\t\t},\n\t\tDB: DBConfig{\n\t\t\tFile: \":memory:\",\n\t\t\tReadOnly: false,\n\t\t},\n\t\tHostnameWhiteList: []string{},\n\t\tListenOn: \":8080\",\n\t\tMasterSecret: \"changeme\",\n\t\tDisableSecurity: false,\n\t\tCaptcha: CaptchaConfig{\n\t\t\tMode: CaptchaDisabled,\n\t\t},\n\t}\n\tif _, err := os.Stat(configFileName); os.IsNotExist(err) {\n\t\treturn config, nil\n\t}\n\tdat, err := ioutil.ReadFile(configFileName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = yaml.Unmarshal(dat, config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn config, nil\n}\n\nfunc (c Config) IsHostNameValid(hostname string) bool {\n\tif c.HostnameWhiteList == nil {\n\t\treturn true\n\t}\n\tif len(c.HostnameWhiteList) == 0 {\n\t\treturn true\n\t}\n\tfor _, v := range c.HostnameWhiteList {\n\t\tif v == hostname {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n<|endoftext|>"} {"text":"\/*\n\tconfig loads and understands the tegola config format.\n*\/\npackage config\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/BurntSushi\/toml\"\n\n\t\"github.com\/go-spatial\/tegola\"\n\t\"github.com\/go-spatial\/tegola\/config\/env\"\n\t\"github.com\/go-spatial\/tegola\/internal\/log\"\n)\n\n\/\/ Config represents a tegola config file.\ntype Config struct {\n\t\/\/ the tile buffer to use\n\tTileBuffer int64 `toml:\"tile_buffer\"`\n\t\/\/ LocationName is the file name or http server that the config was read from.\n\t\/\/ If this is an empty string, it means that the location was unknown. This is the case if\n\t\/\/ the Parse() function is used directly.\n\tLocationName string\n\tWebserver Webserver `toml:\"webserver\"`\n\tCache map[string]interface{} `toml:\"cache\"`\n\t\/\/ Map of providers.\n\tProviders []map[string]interface{}\n\tMaps []Map\n}\n\ntype Webserver struct {\n\tHostName env.String `toml:\"hostname\"`\n\tPort env.String `toml:\"port\"`\n\tCORSAllowedOrigin env.String `toml:\"cors_allowed_origin\"`\n}\n\n\/\/ A Map represents a map in the Tegola Config file.\ntype Map struct {\n\tName env.String `toml:\"name\"`\n\tAttribution env.String `toml:\"attribution\"`\n\tBounds []env.Float `toml:\"bounds\"`\n\tCenter [3]env.Float `toml:\"center\"`\n\tLayers []MapLayer `toml:\"layers\"`\n}\n\ntype MapLayer struct {\n\t\/\/ Name is optional. If it's not defined the name of the ProviderLayer will be used.\n\t\/\/ Name can also be used to group multiple ProviderLayers under the same namespace.\n\tName env.String `toml:\"name\"`\n\tProviderLayer env.String `toml:\"provider_layer\"`\n\tMinZoom *env.Uint `toml:\"min_zoom\"`\n\tMaxZoom *env.Uint `toml:\"max_zoom\"`\n\tDefaultTags interface{} `toml:\"default_tags\"`\n\t\/\/ DontSimplify indicates wheather feature simplification should be applied.\n\t\/\/ We use a negative in the name so the default is to simplify\n\tDontSimplify env.Bool `toml:\"dont_simplify\"`\n}\n\n\/\/ GetName helper to get the name we care about.\nfunc (ml MapLayer) GetName() (string, error) {\n\tif ml.Name != \"\" {\n\t\treturn ml.Name, nil\n\t}\n\t\/\/ split the provider layer (syntax is provider.layer)\n\tplParts := strings.Split(ml.ProviderLayer, \".\")\n\tif len(plParts) != 2 {\n\t\treturn \"\", ErrInvalidProviderLayerName{ProviderLayerName: ml.ProviderLayer}\n\t}\n\n\treturn plParts[1], nil\n}\n\n\/\/ checks the config for issues\nfunc (c *Config) Validate() error {\n\n\t\/\/ check for map layer name \/ zoom collisions\n\t\/\/ map of layers to providers\n\tmapLayers := map[string]map[string]MapLayer{}\n\tfor mapKey, m := range c.Maps {\n\t\tif _, ok := mapLayers[string(m.Name)]; !ok {\n\t\t\tmapLayers[string(m.Name)] = map[string]MapLayer{}\n\t\t}\n\n\t\tfor layerKey, l := range m.Layers {\n\t\t\tname, err := l.GetName()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t\/\/ MaxZoom default\n\t\t\tif l.MaxZoom == nil {\n\t\t\t\tph := env.Uint(tegola.MaxZ)\n\t\t\t\t\/\/ set in iterated value\n\t\t\t\tl.MaxZoom = &ph\n\t\t\t\t\/\/ set in underlying config struct\n\t\t\t\tc.Maps[mapKey].Layers[layerKey].MaxZoom = &ph\n\t\t\t}\n\t\t\t\/\/ MinZoom default\n\t\t\tif l.MinZoom == nil {\n\t\t\t\tph := env.Uint(0)\n\t\t\t\t\/\/ set in iterated value\n\t\t\t\tl.MinZoom = &ph\n\t\t\t\t\/\/ set in underlying config struct\n\t\t\t\tc.Maps[mapKey].Layers[layerKey].MinZoom = &ph\n\t\t\t}\n\n\t\t\t\/\/ check if we already have this layer\n\t\t\tif val, ok := mapLayers[string(m.Name)][name]; ok {\n\t\t\t\t\/\/ we have a hit. check for zoom range overlap\n\t\t\t\tif uint(*val.MinZoom) <= uint(*l.MaxZoom) && uint(*l.MinZoom) <= uint(*val.MaxZoom) {\n\t\t\t\t\treturn ErrOverlappingLayerZooms{\n\t\t\t\t\t\tProviderLayer1: string(val.ProviderLayer),\n\t\t\t\t\t\tProviderLayer2: string(l.ProviderLayer),\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ add the MapLayer to our map\n\t\t\tmapLayers[string(m.Name)][name] = l\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ Parse will parse the Tegola config file provided by the io.Reader.\nfunc Parse(reader io.Reader, location string) (conf Config, err error) {\n\t\/\/ decode conf file, don't care about the meta data.\n\t_, err = toml.DecodeReader(reader, &conf)\n\tconf.LocationName = location\n\n\treturn conf, err\n}\n\n\/\/ Load will load and parse the config file from the given location.\nfunc Load(location string) (conf Config, err error) {\n\tvar reader io.Reader\n\n\t\/\/ check for http prefix\n\tif strings.HasPrefix(location, \"http\") {\n\t\tlog.Infof(\"loading remote config (%v)\", location)\n\n\t\t\/\/ setup http client with a timeout\n\t\tvar httpClient = &http.Client{\n\t\t\tTimeout: time.Second * 10,\n\t\t}\n\n\t\t\/\/ make the http request\n\t\tres, err := httpClient.Get(location)\n\t\tif err != nil {\n\t\t\treturn conf, fmt.Errorf(\"error fetching remote config file (%v): %v \", location, err)\n\t\t}\n\n\t\t\/\/ set the reader to the response body\n\t\treader = res.Body\n\t} else {\n\t\tlog.Infof(\"loading local config (%v)\", location)\n\n\t\t\/\/ check the conf file exists\n\t\tif _, err := os.Stat(location); os.IsNotExist(err) {\n\t\t\treturn conf, fmt.Errorf(\"config file at location (%v) not found!\", location)\n\t\t}\n\t\t\/\/ open the confi file\n\t\treader, err = os.Open(location)\n\t\tif err != nil {\n\t\t\treturn conf, fmt.Errorf(\"error opening local config file (%v): %v \", location, err)\n\t\t}\n\t}\n\n\treturn Parse(reader, location)\n}\n\nfunc LoadAndValidate(filename string) (cfg Config, err error) {\n\tcfg, err = Load(filename)\n\tif err != nil {\n\t\treturn cfg, err\n\t}\n\t\/\/ validate our config\n\treturn cfg, cfg.Validate()\n}\nForgot to run test after merge conflict.\/*\n\tconfig loads and understands the tegola config format.\n*\/\npackage config\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net\/http\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/BurntSushi\/toml\"\n\n\t\"github.com\/go-spatial\/tegola\"\n\t\"github.com\/go-spatial\/tegola\/config\/env\"\n\t\"github.com\/go-spatial\/tegola\/internal\/log\"\n)\n\n\/\/ Config represents a tegola config file.\ntype Config struct {\n\t\/\/ the tile buffer to use\n\tTileBuffer int64 `toml:\"tile_buffer\"`\n\t\/\/ LocationName is the file name or http server that the config was read from.\n\t\/\/ If this is an empty string, it means that the location was unknown. This is the case if\n\t\/\/ the Parse() function is used directly.\n\tLocationName string\n\tWebserver Webserver `toml:\"webserver\"`\n\tCache map[string]interface{} `toml:\"cache\"`\n\t\/\/ Map of providers.\n\tProviders []map[string]interface{}\n\tMaps []Map\n}\n\ntype Webserver struct {\n\tHostName env.String `toml:\"hostname\"`\n\tPort env.String `toml:\"port\"`\n\tCORSAllowedOrigin env.String `toml:\"cors_allowed_origin\"`\n}\n\n\/\/ A Map represents a map in the Tegola Config file.\ntype Map struct {\n\tName env.String `toml:\"name\"`\n\tAttribution env.String `toml:\"attribution\"`\n\tBounds []env.Float `toml:\"bounds\"`\n\tCenter [3]env.Float `toml:\"center\"`\n\tLayers []MapLayer `toml:\"layers\"`\n}\n\ntype MapLayer struct {\n\t\/\/ Name is optional. If it's not defined the name of the ProviderLayer will be used.\n\t\/\/ Name can also be used to group multiple ProviderLayers under the same namespace.\n\tName env.String `toml:\"name\"`\n\tProviderLayer env.String `toml:\"provider_layer\"`\n\tMinZoom *env.Uint `toml:\"min_zoom\"`\n\tMaxZoom *env.Uint `toml:\"max_zoom\"`\n\tDefaultTags interface{} `toml:\"default_tags\"`\n\t\/\/ DontSimplify indicates wheather feature simplification should be applied.\n\t\/\/ We use a negative in the name so the default is to simplify\n\tDontSimplify env.Bool `toml:\"dont_simplify\"`\n}\n\n\/\/ GetName helper to get the name we care about.\nfunc (ml MapLayer) GetName() (string, error) {\n\tif ml.Name != \"\" {\n\t\treturn string(ml.Name), nil\n\t}\n\t\/\/ split the provider layer (syntax is provider.layer)\n\tplParts := strings.Split(string(ml.ProviderLayer), \".\")\n\tif len(plParts) != 2 {\n\t\treturn \"\", ErrInvalidProviderLayerName{ProviderLayerName: string(ml.ProviderLayer)}\n\t}\n\n\treturn plParts[1], nil\n}\n\n\/\/ checks the config for issues\nfunc (c *Config) Validate() error {\n\n\t\/\/ check for map layer name \/ zoom collisions\n\t\/\/ map of layers to providers\n\tmapLayers := map[string]map[string]MapLayer{}\n\tfor mapKey, m := range c.Maps {\n\t\tif _, ok := mapLayers[string(m.Name)]; !ok {\n\t\t\tmapLayers[string(m.Name)] = map[string]MapLayer{}\n\t\t}\n\n\t\tfor layerKey, l := range m.Layers {\n\t\t\tname, err := l.GetName()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\t\/\/ MaxZoom default\n\t\t\tif l.MaxZoom == nil {\n\t\t\t\tph := env.Uint(tegola.MaxZ)\n\t\t\t\t\/\/ set in iterated value\n\t\t\t\tl.MaxZoom = &ph\n\t\t\t\t\/\/ set in underlying config struct\n\t\t\t\tc.Maps[mapKey].Layers[layerKey].MaxZoom = &ph\n\t\t\t}\n\t\t\t\/\/ MinZoom default\n\t\t\tif l.MinZoom == nil {\n\t\t\t\tph := env.Uint(0)\n\t\t\t\t\/\/ set in iterated value\n\t\t\t\tl.MinZoom = &ph\n\t\t\t\t\/\/ set in underlying config struct\n\t\t\t\tc.Maps[mapKey].Layers[layerKey].MinZoom = &ph\n\t\t\t}\n\n\t\t\t\/\/ check if we already have this layer\n\t\t\tif val, ok := mapLayers[string(m.Name)][name]; ok {\n\t\t\t\t\/\/ we have a hit. check for zoom range overlap\n\t\t\t\tif uint(*val.MinZoom) <= uint(*l.MaxZoom) && uint(*l.MinZoom) <= uint(*val.MaxZoom) {\n\t\t\t\t\treturn ErrOverlappingLayerZooms{\n\t\t\t\t\t\tProviderLayer1: string(val.ProviderLayer),\n\t\t\t\t\t\tProviderLayer2: string(l.ProviderLayer),\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t\/\/ add the MapLayer to our map\n\t\t\tmapLayers[string(m.Name)][name] = l\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ Parse will parse the Tegola config file provided by the io.Reader.\nfunc Parse(reader io.Reader, location string) (conf Config, err error) {\n\t\/\/ decode conf file, don't care about the meta data.\n\t_, err = toml.DecodeReader(reader, &conf)\n\tconf.LocationName = location\n\n\treturn conf, err\n}\n\n\/\/ Load will load and parse the config file from the given location.\nfunc Load(location string) (conf Config, err error) {\n\tvar reader io.Reader\n\n\t\/\/ check for http prefix\n\tif strings.HasPrefix(location, \"http\") {\n\t\tlog.Infof(\"loading remote config (%v)\", location)\n\n\t\t\/\/ setup http client with a timeout\n\t\tvar httpClient = &http.Client{\n\t\t\tTimeout: time.Second * 10,\n\t\t}\n\n\t\t\/\/ make the http request\n\t\tres, err := httpClient.Get(location)\n\t\tif err != nil {\n\t\t\treturn conf, fmt.Errorf(\"error fetching remote config file (%v): %v \", location, err)\n\t\t}\n\n\t\t\/\/ set the reader to the response body\n\t\treader = res.Body\n\t} else {\n\t\tlog.Infof(\"loading local config (%v)\", location)\n\n\t\t\/\/ check the conf file exists\n\t\tif _, err := os.Stat(location); os.IsNotExist(err) {\n\t\t\treturn conf, fmt.Errorf(\"config file at location (%v) not found!\", location)\n\t\t}\n\t\t\/\/ open the confi file\n\t\treader, err = os.Open(location)\n\t\tif err != nil {\n\t\t\treturn conf, fmt.Errorf(\"error opening local config file (%v): %v \", location, err)\n\t\t}\n\t}\n\n\treturn Parse(reader, location)\n}\n\nfunc LoadAndValidate(filename string) (cfg Config, err error) {\n\tcfg, err = Load(filename)\n\tif err != nil {\n\t\treturn cfg, err\n\t}\n\t\/\/ validate our config\n\treturn cfg, cfg.Validate()\n}\n<|endoftext|>"} {"text":"package config\n\nimport (\n\t\"os\"\n\n\t\"github.com\/jinzhu\/configor\"\n\t\"github.com\/qor\/auth\/providers\/facebook\"\n\t\"github.com\/qor\/auth\/providers\/github\"\n\t\"github.com\/qor\/auth\/providers\/google\"\n\t\"github.com\/qor\/auth\/providers\/twitter\"\n\t\"github.com\/qor\/location\"\n\t\"github.com\/qor\/mailer\"\n\t\"github.com\/qor\/mailer\/logger\"\n\t\"github.com\/qor\/media\/oss\"\n\t\"github.com\/qor\/oss\/s3\"\n\t\"github.com\/qor\/redirect_back\"\n\t\"github.com\/qor\/session\/manager\"\n)\n\ntype SMTPConfig struct {\n\tHost string\n\tPort string\n\tUser string\n\tPassword string\n}\n\nvar Config = struct {\n\tPort uint `default:\"7000\" env:\"PORT\"`\n\tDB struct {\n\t\tName string `env:\"DBName\" default:\"qor_example\"`\n\t\tAdapter string `env:\"DBAdapter\" default:\"mysql\"`\n\t\tHost string `env:\"DBHost\" default:\"localhost\"`\n\t\tPort string `env:\"DBPort\" default:\"3306\"`\n\t\tUser string `env:\"DBUser\"`\n\t\tPassword string `env:\"DBPassword\"`\n\t}\n\tS3 struct {\n\t\tAccessKeyID string `env:\"AWS_ACCESS_KEY_ID\"`\n\t\tSecretAccessKey string `env:\"AWS_SECRET_ACCESS_KEY\"`\n\t\tRegion string `env:\"AWS_Region\"`\n\t\tS3Bucket string `env:\"AWS_Bucket\"`\n\t}\n\tSMTP SMTPConfig\n\tGithub github.Config\n\tGoogle google.Config\n\tFacebook facebook.Config\n\tTwitter twitter.Config\n\tGoogleAPIKey string `env:\"GoogleAPIKey\"`\n\tBaiduAPIKey string `env:\"BaiduAPIKey\"`\n}{}\n\nvar (\n\tRoot = os.Getenv(\"GOPATH\") + \"\/src\/github.com\/qor\/qor-example\"\n\tMailer *mailer.Mailer\n\tRedirectBack = redirect_back.New(&redirect_back.Config{\n\t\tSessionManager: manager.SessionManager,\n\t\tIgnoredPrefixes: []string{\"\/auth\"},\n\t})\n)\n\nfunc init() {\n\tif err := configor.Load(&Config, \"config\/database.yml\", \"config\/smtp.yml\", \"config\/application.yml\"); err != nil {\n\t\tpanic(err)\n\t}\n\n\tlocation.GoogleAPIKey = Config.GoogleAPIKey\n\tlocation.BaiduAPIKey = Config.BaiduAPIKey\n\n\tif Config.S3.AccessKeyID != \"\" {\n\t\toss.Storage = s3.New(&s3.Config{\n\t\t\tAccessID: Config.S3.AccessKeyID,\n\t\t\tAccessKey: Config.S3.SecretAccessKey,\n\t\t\tRegion: Config.S3.Region,\n\t\t\tBucket: Config.S3.S3Bucket,\n\t\t})\n\t}\n\n\t\/\/ dialer := gomail.NewDialer(Config.SMTP.Host, Config.SMTP.Port, Config.SMTP.User, Config.SMTP.Password)\n\t\/\/ sender, err := dialer.Dial()\n\n\t\/\/ Mailer = mailer.New(&mailer.Config{\n\t\/\/ \tSender: gomailer.New(&gomailer.Config{Sender: sender}),\n\t\/\/ })\n\tMailer = mailer.New(&mailer.Config{\n\t\tSender: logger.New(&logger.Config{}),\n\t})\n}\nAdd amazon pay configpackage config\n\nimport (\n\t\"os\"\n\n\t\"github.com\/jinzhu\/configor\"\n\t\"github.com\/qor\/auth\/providers\/facebook\"\n\t\"github.com\/qor\/auth\/providers\/github\"\n\t\"github.com\/qor\/auth\/providers\/google\"\n\t\"github.com\/qor\/auth\/providers\/twitter\"\n\t\"github.com\/qor\/location\"\n\t\"github.com\/qor\/mailer\"\n\t\"github.com\/qor\/mailer\/logger\"\n\t\"github.com\/qor\/media\/oss\"\n\t\"github.com\/qor\/oss\/s3\"\n\t\"github.com\/qor\/redirect_back\"\n\t\"github.com\/qor\/session\/manager\"\n)\n\ntype SMTPConfig struct {\n\tHost string\n\tPort string\n\tUser string\n\tPassword string\n}\n\nvar Config = struct {\n\tPort uint `default:\"7000\" env:\"PORT\"`\n\tDB struct {\n\t\tName string `env:\"DBName\" default:\"qor_example\"`\n\t\tAdapter string `env:\"DBAdapter\" default:\"mysql\"`\n\t\tHost string `env:\"DBHost\" default:\"localhost\"`\n\t\tPort string `env:\"DBPort\" default:\"3306\"`\n\t\tUser string `env:\"DBUser\"`\n\t\tPassword string `env:\"DBPassword\"`\n\t}\n\tS3 struct {\n\t\tAccessKeyID string `env:\"AWS_ACCESS_KEY_ID\"`\n\t\tSecretAccessKey string `env:\"AWS_SECRET_ACCESS_KEY\"`\n\t\tRegion string `env:\"AWS_Region\"`\n\t\tS3Bucket string `env:\"AWS_Bucket\"`\n\t}\n\tAmazonPay struct {\n\t\tMerchantID string `env:\"AmazonPayMerchantID\"`\n\t\tAccessKey string `env:\"AmazonPayAccessKey\"`\n\t\tSecretKey string `env:\"AmazonPaySecretKey\"`\n\t\tSandbox bool `env:\"AmazonPaySandbox\"`\n\t\tCurrencyCode string `env:\"AmazonPayCurrencyCode\"`\n\t}\n\tSMTP SMTPConfig\n\tGithub github.Config\n\tGoogle google.Config\n\tFacebook facebook.Config\n\tTwitter twitter.Config\n\tGoogleAPIKey string `env:\"GoogleAPIKey\"`\n\tBaiduAPIKey string `env:\"BaiduAPIKey\"`\n}{}\n\nvar (\n\tRoot = os.Getenv(\"GOPATH\") + \"\/src\/github.com\/qor\/qor-example\"\n\tMailer *mailer.Mailer\n\tRedirectBack = redirect_back.New(&redirect_back.Config{\n\t\tSessionManager: manager.SessionManager,\n\t\tIgnoredPrefixes: []string{\"\/auth\"},\n\t})\n)\n\nfunc init() {\n\tif err := configor.Load(&Config, \"config\/database.yml\", \"config\/smtp.yml\", \"config\/application.yml\"); err != nil {\n\t\tpanic(err)\n\t}\n\n\tlocation.GoogleAPIKey = Config.GoogleAPIKey\n\tlocation.BaiduAPIKey = Config.BaiduAPIKey\n\n\tif Config.S3.AccessKeyID != \"\" {\n\t\toss.Storage = s3.New(&s3.Config{\n\t\t\tAccessID: Config.S3.AccessKeyID,\n\t\t\tAccessKey: Config.S3.SecretAccessKey,\n\t\t\tRegion: Config.S3.Region,\n\t\t\tBucket: Config.S3.S3Bucket,\n\t\t})\n\t}\n\n\t\/\/ dialer := gomail.NewDialer(Config.SMTP.Host, Config.SMTP.Port, Config.SMTP.User, Config.SMTP.Password)\n\t\/\/ sender, err := dialer.Dial()\n\n\t\/\/ Mailer = mailer.New(&mailer.Config{\n\t\/\/ \tSender: gomailer.New(&gomailer.Config{Sender: sender}),\n\t\/\/ })\n\tMailer = mailer.New(&mailer.Config{\n\t\tSender: logger.New(&logger.Config{}),\n\t})\n}\n<|endoftext|>"} {"text":"package config\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/BurntSushi\/toml\"\n\t\"github.com\/mackerelio\/mackerel-agent\/logging\"\n\t\"github.com\/mackerelio\/mackerel-agent\/util\"\n)\n\nvar configLogger = logging.GetLogger(\"config\")\n\n\/\/ `apibase` and `agentName` are set from build flags\nvar apibase string\n\nfunc getApibase() string {\n\tif apibase != \"\" {\n\t\treturn apibase\n\t}\n\treturn \"https:\/\/mackerel.io\"\n}\n\nvar agentName string\n\nfunc getAgentName() string {\n\tif agentName != \"\" {\n\t\treturn agentName\n\t}\n\treturn \"mackerel-agent\"\n}\n\n\/\/ Config represents mackerel-agent's configuration file.\ntype Config struct {\n\tApibase string\n\tApikey string\n\tRoot string\n\tPidfile string\n\tConffile string\n\tRoles []string\n\tVerbose bool\n\tSilent bool\n\tDiagnostic bool `toml:\"diagnostic\"`\n\tConnection ConnectionConfig\n\tDisplayName string `toml:\"display_name\"`\n\tHostStatus HostStatus `toml:\"host_status\"`\n\tFilesystems Filesystems `toml:\"filesystems\"`\n\tHTTPProxy string `toml:\"http_proxy\"`\n\n\t\/\/ Corresponds to the set of [plugin..] sections\n\t\/\/ the key of the map is , which should be one of \"metrics\" or \"checks\".\n\tPlugin map[string]PluginConfigs\n\n\tInclude string\n\n\t\/\/ Cannot exist in configuration files\n\tHostIDStorage HostIDStorage\n\tMetricPlugins map[string]MetricPlugin\n\tCheckPlugins map[string]CheckPlugin\n}\n\n\/\/ PluginConfigs represents a set of [plugin..] sections in the configuration file\n\/\/ under a specific . The key of the map is , for example \"mysql\" of \"plugin.metrics.mysql\".\ntype PluginConfigs map[string]*PluginConfig\n\n\/\/ PluginConfig represents a section of [plugin.*].\n\/\/ `MaxCheckAttempts`, `NotificationInterval` and `CheckInterval` options are used with check monitoring plugins. Custom metrics plugins ignore these options.\n\/\/ `User` option is ignore in windows\ntype PluginConfig struct {\n\tCommandRaw interface{} `toml:\"command\"`\n\tCommand string\n\tCommandArgs []string\n\tUser string\n\tNotificationInterval *int32 `toml:\"notification_interval\"`\n\tCheckInterval *int32 `toml:\"check_interval\"`\n\tMaxCheckAttempts *int32 `toml:\"max_check_attempts\"`\n\tCustomIdentifier *string `toml:\"custom_identifier\"`\n}\n\n\/\/ MetricPlugin represents the configuration of a metric plugin\n\/\/ The `User` option is ignored in Windows\ntype MetricPlugin struct {\n\tCommand string\n\tCommandArgs []string\n\tUser string\n\tCustomIdentifier *string\n}\n\n\/\/ CheckPlugin represents the configuration of a check plugin\n\/\/ The `User` option is ignored in Windows\ntype CheckPlugin struct {\n\tCommand string\n\tCommandArgs []string\n\tUser string\n\tNotificationInterval *int32\n\tCheckInterval *int32\n\tMaxCheckAttempts *int32\n}\n\nfunc (pconf *PluginConfig) prepareCommand() error {\n\tconst errFmt = \"failed to prepare plugin command. A configuration value of `command` should be string or string slice, but %T\"\n\tv := pconf.CommandRaw\n\tswitch t := v.(type) {\n\tcase string:\n\t\tpconf.Command = t\n\tcase []interface{}:\n\t\tif len(t) > 0 {\n\t\t\tfor _, vv := range t {\n\t\t\t\tstr, ok := vv.(string)\n\t\t\t\tif !ok {\n\t\t\t\t\treturn fmt.Errorf(errFmt, v)\n\t\t\t\t}\n\t\t\t\tpconf.CommandArgs = append(pconf.CommandArgs, str)\n\t\t\t}\n\t\t} else {\n\t\t\treturn fmt.Errorf(errFmt, v)\n\t\t}\n\tcase []string:\n\t\tpconf.CommandArgs = t\n\tdefault:\n\t\treturn fmt.Errorf(errFmt, v)\n\t}\n\treturn nil\n}\n\n\/\/ Run the plugin\nfunc (pconf *PluginConfig) Run() (string, string, int, error) {\n\tif len(pconf.CommandArgs) > 0 {\n\t\treturn util.RunCommandArgs(pconf.CommandArgs, pconf.User)\n\t}\n\treturn util.RunCommand(pconf.Command, pconf.User)\n}\n\nconst postMetricsDequeueDelaySecondsMax = 59 \/\/ max delay seconds for dequeuing from buffer queue\nconst postMetricsRetryDelaySecondsMax = 3 * 60 \/\/ max delay seconds for retrying a request that caused errors\n\n\/\/ PostMetricsInterval XXX\nvar PostMetricsInterval = 1 * time.Minute\n\n\/\/ ConnectionConfig XXX\ntype ConnectionConfig struct {\n\tPostMetricsDequeueDelaySeconds int `toml:\"post_metrics_dequeue_delay_seconds\"` \/\/ delay for dequeuing from buffer queue\n\tPostMetricsRetryDelaySeconds int `toml:\"post_metrics_retry_delay_seconds\"` \/\/ delay for retrying a request that caused errors\n\tPostMetricsRetryMax int `toml:\"post_metrics_retry_max\"` \/\/ max numbers of retries for a request that causes errors\n\tPostMetricsBufferSize int `toml:\"post_metrics_buffer_size\"` \/\/ max numbers of requests stored in buffer queue.\n}\n\n\/\/ HostStatus configure host status on agent start\/stop\ntype HostStatus struct {\n\tOnStart string `toml:\"on_start\"`\n\tOnStop string `toml:\"on_stop\"`\n}\n\n\/\/ Filesystems configure filesystem related settings\ntype Filesystems struct {\n\tIgnore Regexpwrapper `toml:\"ignore\"`\n\tUseMountpoint bool `toml:\"use_mountpoint\"`\n}\n\n\/\/ Regexpwrapper is a wrapper type for marshalling string\ntype Regexpwrapper struct {\n\t*regexp.Regexp\n}\n\n\/\/ UnmarshalText for compiling regexp string while loading toml\nfunc (r *Regexpwrapper) UnmarshalText(text []byte) error {\n\tvar err error\n\tr.Regexp, err = regexp.Compile(string(text))\n\treturn err\n}\n\n\/\/ CheckNames return list of plugin.checks._name_\nfunc (conf *Config) CheckNames() []string {\n\tchecks := []string{}\n\tfor name := range conf.Plugin[\"checks\"] {\n\t\tchecks = append(checks, name)\n\t}\n\treturn checks\n}\n\n\/\/ LoadConfig XXX\nfunc LoadConfig(conffile string) (*Config, error) {\n\tconfig, err := loadConfigFile(conffile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ set default values if config does not have values\n\tif config.Apibase == \"\" {\n\t\tconfig.Apibase = DefaultConfig.Apibase\n\t}\n\tif config.Root == \"\" {\n\t\tconfig.Root = DefaultConfig.Root\n\t}\n\tif config.Pidfile == \"\" {\n\t\tconfig.Pidfile = DefaultConfig.Pidfile\n\t}\n\tif config.Verbose == false {\n\t\tconfig.Verbose = DefaultConfig.Verbose\n\t}\n\tif config.Diagnostic == false {\n\t\tconfig.Diagnostic = DefaultConfig.Diagnostic\n\t}\n\tif config.Connection.PostMetricsDequeueDelaySeconds == 0 {\n\t\tconfig.Connection.PostMetricsDequeueDelaySeconds = DefaultConfig.Connection.PostMetricsDequeueDelaySeconds\n\t}\n\tif config.Connection.PostMetricsDequeueDelaySeconds > postMetricsDequeueDelaySecondsMax {\n\t\tconfigLogger.Warningf(\"'post_metrics_dequese_delay_seconds' is set to %d (Maximum Value).\", postMetricsDequeueDelaySecondsMax)\n\t\tconfig.Connection.PostMetricsDequeueDelaySeconds = postMetricsDequeueDelaySecondsMax\n\t}\n\tif config.Connection.PostMetricsRetryDelaySeconds == 0 {\n\t\tconfig.Connection.PostMetricsRetryDelaySeconds = DefaultConfig.Connection.PostMetricsRetryDelaySeconds\n\t}\n\tif config.Connection.PostMetricsRetryDelaySeconds > postMetricsRetryDelaySecondsMax {\n\t\tconfigLogger.Warningf(\"'post_metrics_retry_delay_seconds' is set to %d (Maximum Value).\", postMetricsRetryDelaySecondsMax)\n\t\tconfig.Connection.PostMetricsRetryDelaySeconds = postMetricsRetryDelaySecondsMax\n\t}\n\tif config.Connection.PostMetricsRetryMax == 0 {\n\t\tconfig.Connection.PostMetricsRetryMax = DefaultConfig.Connection.PostMetricsRetryMax\n\t}\n\tif config.Connection.PostMetricsBufferSize == 0 {\n\t\tconfig.Connection.PostMetricsBufferSize = DefaultConfig.Connection.PostMetricsBufferSize\n\t}\n\n\treturn config, err\n}\n\nfunc loadConfigFile(file string) (*Config, error) {\n\tconfig := &Config{}\n\tif _, err := toml.DecodeFile(file, config); err != nil {\n\t\treturn config, err\n\t}\n\n\tif config.Include != \"\" {\n\t\tif err := includeConfigFile(config, config.Include); err != nil {\n\t\t\treturn config, err\n\t\t}\n\t}\n\tfor _, pconfs := range config.Plugin {\n\t\tfor _, pconf := range pconfs {\n\t\t\terr := pconf.prepareCommand()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\treturn config, nil\n}\n\nfunc includeConfigFile(config *Config, include string) error {\n\tfiles, err := filepath.Glob(include)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, file := range files {\n\t\t\/\/ Save current \"roles\" value and reset it\n\t\t\/\/ because toml.DecodeFile()-ing on a fulfilled struct\n\t\t\/\/ produces bizarre array values.\n\t\trolesSaved := config.Roles\n\t\tconfig.Roles = nil\n\n\t\t\/\/ Also, save plugin values for later merging\n\t\tpluginSaved := map[string]PluginConfigs{}\n\t\tfor kind, plugins := range config.Plugin {\n\t\t\tpluginSaved[kind] = plugins\n\t\t}\n\n\t\tmeta, err := toml.DecodeFile(file, &config)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"while loading included config file %s: %s\", file, err)\n\t\t}\n\n\t\t\/\/ If included config does not have \"roles\" key,\n\t\t\/\/ use the previous roles configuration value.\n\t\tif meta.IsDefined(\"roles\") == false {\n\t\t\tconfig.Roles = rolesSaved\n\t\t}\n\n\t\tfor kind, plugins := range config.Plugin {\n\t\t\tfor key, conf := range plugins {\n\t\t\t\tif pluginSaved[kind] == nil {\n\t\t\t\t\tpluginSaved[kind] = PluginConfigs{}\n\t\t\t\t}\n\t\t\t\tpluginSaved[kind][key] = conf\n\t\t\t}\n\t\t}\n\n\t\tconfig.Plugin = pluginSaved\n\t}\n\n\treturn nil\n}\n\nfunc (conf *Config) hostIDStorage() HostIDStorage {\n\tif conf.HostIDStorage == nil {\n\t\tconf.HostIDStorage = &FileSystemHostIDStorage{Root: conf.Root}\n\t}\n\treturn conf.HostIDStorage\n}\n\n\/\/ LoadHostID loads the previously saved host id.\nfunc (conf *Config) LoadHostID() (string, error) {\n\treturn conf.hostIDStorage().LoadHostID()\n}\n\n\/\/ SaveHostID saves the host id, which may be restored by LoadHostID.\nfunc (conf *Config) SaveHostID(id string) error {\n\treturn conf.hostIDStorage().SaveHostID(id)\n}\n\n\/\/ DeleteSavedHostID deletes the host id saved by SaveHostID.\nfunc (conf *Config) DeleteSavedHostID() error {\n\treturn conf.hostIDStorage().DeleteSavedHostID()\n}\n\n\/\/ HostIDStorage is an interface which maintains persistency\n\/\/ of the \"Host ID\" for the current host where the agent is running on.\n\/\/ The ID is always generated and given by Mackerel (mackerel.io).\ntype HostIDStorage interface {\n\tLoadHostID() (string, error)\n\tSaveHostID(id string) error\n\tDeleteSavedHostID() error\n}\n\n\/\/ FileSystemHostIDStorage is the default HostIDStorage\n\/\/ which saves\/loads the host id using an id file on the local filesystem.\n\/\/ The file will be located at \/var\/lib\/mackerel-agent\/id by default on linux.\ntype FileSystemHostIDStorage struct {\n\tRoot string\n}\n\nconst idFileName = \"id\"\n\n\/\/ HostIDFile is the location of the host id file.\nfunc (s FileSystemHostIDStorage) HostIDFile() string {\n\treturn filepath.Join(s.Root, idFileName)\n}\n\n\/\/ LoadHostID loads the current host ID from the mackerel-agent's id file.\nfunc (s FileSystemHostIDStorage) LoadHostID() (string, error) {\n\tcontent, err := ioutil.ReadFile(s.HostIDFile())\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn strings.TrimRight(string(content), \"\\r\\n\"), nil\n}\n\n\/\/ SaveHostID saves the host ID to the mackerel-agent's id file.\nfunc (s FileSystemHostIDStorage) SaveHostID(id string) error {\n\terr := os.MkdirAll(s.Root, 0755)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfile, err := os.Create(s.HostIDFile())\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\t_, err = file.Write([]byte(id))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ DeleteSavedHostID deletes the mackerel-agent's id file.\nfunc (s FileSystemHostIDStorage) DeleteSavedHostID() error {\n\treturn os.Remove(s.HostIDFile())\n}\ncreate MetricPlugins and CheckPluginspackage config\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/BurntSushi\/toml\"\n\t\"github.com\/mackerelio\/mackerel-agent\/logging\"\n\t\"github.com\/mackerelio\/mackerel-agent\/util\"\n)\n\nvar configLogger = logging.GetLogger(\"config\")\n\n\/\/ `apibase` and `agentName` are set from build flags\nvar apibase string\n\nfunc getApibase() string {\n\tif apibase != \"\" {\n\t\treturn apibase\n\t}\n\treturn \"https:\/\/mackerel.io\"\n}\n\nvar agentName string\n\nfunc getAgentName() string {\n\tif agentName != \"\" {\n\t\treturn agentName\n\t}\n\treturn \"mackerel-agent\"\n}\n\n\/\/ Config represents mackerel-agent's configuration file.\ntype Config struct {\n\tApibase string\n\tApikey string\n\tRoot string\n\tPidfile string\n\tConffile string\n\tRoles []string\n\tVerbose bool\n\tSilent bool\n\tDiagnostic bool `toml:\"diagnostic\"`\n\tConnection ConnectionConfig\n\tDisplayName string `toml:\"display_name\"`\n\tHostStatus HostStatus `toml:\"host_status\"`\n\tFilesystems Filesystems `toml:\"filesystems\"`\n\tHTTPProxy string `toml:\"http_proxy\"`\n\n\t\/\/ Corresponds to the set of [plugin..] sections\n\t\/\/ the key of the map is , which should be one of \"metrics\" or \"checks\".\n\tPlugin map[string]PluginConfigs\n\n\tInclude string\n\n\t\/\/ Cannot exist in configuration files\n\tHostIDStorage HostIDStorage\n\tMetricPlugins map[string]*MetricPlugin\n\tCheckPlugins map[string]*CheckPlugin\n}\n\n\/\/ PluginConfigs represents a set of [plugin..] sections in the configuration file\n\/\/ under a specific . The key of the map is , for example \"mysql\" of \"plugin.metrics.mysql\".\ntype PluginConfigs map[string]*PluginConfig\n\n\/\/ PluginConfig represents a section of [plugin.*].\n\/\/ `MaxCheckAttempts`, `NotificationInterval` and `CheckInterval` options are used with check monitoring plugins. Custom metrics plugins ignore these options.\n\/\/ `User` option is ignore in windows\ntype PluginConfig struct {\n\tCommandRaw interface{} `toml:\"command\"`\n\tCommand string\n\tCommandArgs []string\n\tUser string\n\tNotificationInterval *int32 `toml:\"notification_interval\"`\n\tCheckInterval *int32 `toml:\"check_interval\"`\n\tMaxCheckAttempts *int32 `toml:\"max_check_attempts\"`\n\tCustomIdentifier *string `toml:\"custom_identifier\"`\n}\n\nfunc makeMetricPlugin(pconf *PluginConfig) (*MetricPlugin, error) {\n\terr := pconf.prepareCommand()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &MetricPlugin{\n\t\tCommand: pconf.Command,\n\t\tCommandArgs: pconf.CommandArgs,\n\t\tUser: pconf.User,\n\t\tCustomIdentifier: pconf.CustomIdentifier,\n\t}, nil\n}\n\nfunc makeCheckPlugin(pconf *PluginConfig) (*CheckPlugin, error) {\n\terr := pconf.prepareCommand()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &CheckPlugin{\n\t\tCommand: pconf.Command,\n\t\tCommandArgs: pconf.CommandArgs,\n\t\tUser: pconf.User,\n\t\tNotificationInterval: pconf.NotificationInterval,\n\t\tCheckInterval: pconf.CheckInterval,\n\t\tMaxCheckAttempts: pconf.MaxCheckAttempts,\n\t}, nil\n}\n\n\/\/ MetricPlugin represents the configuration of a metric plugin\n\/\/ The `User` option is ignored in Windows\ntype MetricPlugin struct {\n\tCommand string\n\tCommandArgs []string\n\tUser string\n\tCustomIdentifier *string\n}\n\n\/\/ CheckPlugin represents the configuration of a check plugin\n\/\/ The `User` option is ignored in Windows\ntype CheckPlugin struct {\n\tCommand string\n\tCommandArgs []string\n\tUser string\n\tNotificationInterval *int32\n\tCheckInterval *int32\n\tMaxCheckAttempts *int32\n}\n\nfunc (pconf *PluginConfig) prepareCommand() error {\n\tconst errFmt = \"failed to prepare plugin command. A configuration value of `command` should be string or string slice, but %T\"\n\tv := pconf.CommandRaw\n\tswitch t := v.(type) {\n\tcase string:\n\t\tpconf.Command = t\n\tcase []interface{}:\n\t\tif len(t) > 0 {\n\t\t\tfor _, vv := range t {\n\t\t\t\tstr, ok := vv.(string)\n\t\t\t\tif !ok {\n\t\t\t\t\treturn fmt.Errorf(errFmt, v)\n\t\t\t\t}\n\t\t\t\tpconf.CommandArgs = append(pconf.CommandArgs, str)\n\t\t\t}\n\t\t} else {\n\t\t\treturn fmt.Errorf(errFmt, v)\n\t\t}\n\tcase []string:\n\t\tpconf.CommandArgs = t\n\tdefault:\n\t\treturn fmt.Errorf(errFmt, v)\n\t}\n\treturn nil\n}\n\n\/\/ Run the plugin\nfunc (pconf *PluginConfig) Run() (string, string, int, error) {\n\tif len(pconf.CommandArgs) > 0 {\n\t\treturn util.RunCommandArgs(pconf.CommandArgs, pconf.User)\n\t}\n\treturn util.RunCommand(pconf.Command, pconf.User)\n}\n\nconst postMetricsDequeueDelaySecondsMax = 59 \/\/ max delay seconds for dequeuing from buffer queue\nconst postMetricsRetryDelaySecondsMax = 3 * 60 \/\/ max delay seconds for retrying a request that caused errors\n\n\/\/ PostMetricsInterval XXX\nvar PostMetricsInterval = 1 * time.Minute\n\n\/\/ ConnectionConfig XXX\ntype ConnectionConfig struct {\n\tPostMetricsDequeueDelaySeconds int `toml:\"post_metrics_dequeue_delay_seconds\"` \/\/ delay for dequeuing from buffer queue\n\tPostMetricsRetryDelaySeconds int `toml:\"post_metrics_retry_delay_seconds\"` \/\/ delay for retrying a request that caused errors\n\tPostMetricsRetryMax int `toml:\"post_metrics_retry_max\"` \/\/ max numbers of retries for a request that causes errors\n\tPostMetricsBufferSize int `toml:\"post_metrics_buffer_size\"` \/\/ max numbers of requests stored in buffer queue.\n}\n\n\/\/ HostStatus configure host status on agent start\/stop\ntype HostStatus struct {\n\tOnStart string `toml:\"on_start\"`\n\tOnStop string `toml:\"on_stop\"`\n}\n\n\/\/ Filesystems configure filesystem related settings\ntype Filesystems struct {\n\tIgnore Regexpwrapper `toml:\"ignore\"`\n\tUseMountpoint bool `toml:\"use_mountpoint\"`\n}\n\n\/\/ Regexpwrapper is a wrapper type for marshalling string\ntype Regexpwrapper struct {\n\t*regexp.Regexp\n}\n\n\/\/ UnmarshalText for compiling regexp string while loading toml\nfunc (r *Regexpwrapper) UnmarshalText(text []byte) error {\n\tvar err error\n\tr.Regexp, err = regexp.Compile(string(text))\n\treturn err\n}\n\n\/\/ CheckNames return list of plugin.checks._name_\nfunc (conf *Config) CheckNames() []string {\n\tchecks := []string{}\n\tfor name := range conf.Plugin[\"checks\"] {\n\t\tchecks = append(checks, name)\n\t}\n\treturn checks\n}\n\n\/\/ LoadConfig XXX\nfunc LoadConfig(conffile string) (*Config, error) {\n\tconfig, err := loadConfigFile(conffile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t\/\/ set default values if config does not have values\n\tif config.Apibase == \"\" {\n\t\tconfig.Apibase = DefaultConfig.Apibase\n\t}\n\tif config.Root == \"\" {\n\t\tconfig.Root = DefaultConfig.Root\n\t}\n\tif config.Pidfile == \"\" {\n\t\tconfig.Pidfile = DefaultConfig.Pidfile\n\t}\n\tif config.Verbose == false {\n\t\tconfig.Verbose = DefaultConfig.Verbose\n\t}\n\tif config.Diagnostic == false {\n\t\tconfig.Diagnostic = DefaultConfig.Diagnostic\n\t}\n\tif config.Connection.PostMetricsDequeueDelaySeconds == 0 {\n\t\tconfig.Connection.PostMetricsDequeueDelaySeconds = DefaultConfig.Connection.PostMetricsDequeueDelaySeconds\n\t}\n\tif config.Connection.PostMetricsDequeueDelaySeconds > postMetricsDequeueDelaySecondsMax {\n\t\tconfigLogger.Warningf(\"'post_metrics_dequese_delay_seconds' is set to %d (Maximum Value).\", postMetricsDequeueDelaySecondsMax)\n\t\tconfig.Connection.PostMetricsDequeueDelaySeconds = postMetricsDequeueDelaySecondsMax\n\t}\n\tif config.Connection.PostMetricsRetryDelaySeconds == 0 {\n\t\tconfig.Connection.PostMetricsRetryDelaySeconds = DefaultConfig.Connection.PostMetricsRetryDelaySeconds\n\t}\n\tif config.Connection.PostMetricsRetryDelaySeconds > postMetricsRetryDelaySecondsMax {\n\t\tconfigLogger.Warningf(\"'post_metrics_retry_delay_seconds' is set to %d (Maximum Value).\", postMetricsRetryDelaySecondsMax)\n\t\tconfig.Connection.PostMetricsRetryDelaySeconds = postMetricsRetryDelaySecondsMax\n\t}\n\tif config.Connection.PostMetricsRetryMax == 0 {\n\t\tconfig.Connection.PostMetricsRetryMax = DefaultConfig.Connection.PostMetricsRetryMax\n\t}\n\tif config.Connection.PostMetricsBufferSize == 0 {\n\t\tconfig.Connection.PostMetricsBufferSize = DefaultConfig.Connection.PostMetricsBufferSize\n\t}\n\n\treturn config, err\n}\n\nfunc loadConfigFile(file string) (*Config, error) {\n\tconfig := &Config{}\n\tif _, err := toml.DecodeFile(file, config); err != nil {\n\t\treturn config, err\n\t}\n\n\tif config.Include != \"\" {\n\t\tif err := includeConfigFile(config, config.Include); err != nil {\n\t\t\treturn config, err\n\t\t}\n\t}\n\n\tconfig.MetricPlugins = make(map[string]*MetricPlugin)\n\tif pconfs, ok := config.Plugin[\"metrics\"]; ok {\n\t\tvar err error\n\t\tfor name, pconf := range pconfs {\n\t\t\tconfig.MetricPlugins[name], err = makeMetricPlugin(pconf)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\tconfig.CheckPlugins = make(map[string]*CheckPlugin)\n\tif pconfs, ok := config.Plugin[\"checks\"]; ok {\n\t\tvar err error\n\t\tfor name, pconf := range pconfs {\n\t\t\tconfig.CheckPlugins[name], err = makeCheckPlugin(pconf)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\treturn config, nil\n}\n\nfunc includeConfigFile(config *Config, include string) error {\n\tfiles, err := filepath.Glob(include)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, file := range files {\n\t\t\/\/ Save current \"roles\" value and reset it\n\t\t\/\/ because toml.DecodeFile()-ing on a fulfilled struct\n\t\t\/\/ produces bizarre array values.\n\t\trolesSaved := config.Roles\n\t\tconfig.Roles = nil\n\n\t\t\/\/ Also, save plugin values for later merging\n\t\tpluginSaved := map[string]PluginConfigs{}\n\t\tfor kind, plugins := range config.Plugin {\n\t\t\tpluginSaved[kind] = plugins\n\t\t}\n\n\t\tmeta, err := toml.DecodeFile(file, &config)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"while loading included config file %s: %s\", file, err)\n\t\t}\n\n\t\t\/\/ If included config does not have \"roles\" key,\n\t\t\/\/ use the previous roles configuration value.\n\t\tif meta.IsDefined(\"roles\") == false {\n\t\t\tconfig.Roles = rolesSaved\n\t\t}\n\n\t\tfor kind, plugins := range config.Plugin {\n\t\t\tfor key, conf := range plugins {\n\t\t\t\tif pluginSaved[kind] == nil {\n\t\t\t\t\tpluginSaved[kind] = PluginConfigs{}\n\t\t\t\t}\n\t\t\t\tpluginSaved[kind][key] = conf\n\t\t\t}\n\t\t}\n\n\t\tconfig.Plugin = pluginSaved\n\t}\n\n\treturn nil\n}\n\nfunc (conf *Config) hostIDStorage() HostIDStorage {\n\tif conf.HostIDStorage == nil {\n\t\tconf.HostIDStorage = &FileSystemHostIDStorage{Root: conf.Root}\n\t}\n\treturn conf.HostIDStorage\n}\n\n\/\/ LoadHostID loads the previously saved host id.\nfunc (conf *Config) LoadHostID() (string, error) {\n\treturn conf.hostIDStorage().LoadHostID()\n}\n\n\/\/ SaveHostID saves the host id, which may be restored by LoadHostID.\nfunc (conf *Config) SaveHostID(id string) error {\n\treturn conf.hostIDStorage().SaveHostID(id)\n}\n\n\/\/ DeleteSavedHostID deletes the host id saved by SaveHostID.\nfunc (conf *Config) DeleteSavedHostID() error {\n\treturn conf.hostIDStorage().DeleteSavedHostID()\n}\n\n\/\/ HostIDStorage is an interface which maintains persistency\n\/\/ of the \"Host ID\" for the current host where the agent is running on.\n\/\/ The ID is always generated and given by Mackerel (mackerel.io).\ntype HostIDStorage interface {\n\tLoadHostID() (string, error)\n\tSaveHostID(id string) error\n\tDeleteSavedHostID() error\n}\n\n\/\/ FileSystemHostIDStorage is the default HostIDStorage\n\/\/ which saves\/loads the host id using an id file on the local filesystem.\n\/\/ The file will be located at \/var\/lib\/mackerel-agent\/id by default on linux.\ntype FileSystemHostIDStorage struct {\n\tRoot string\n}\n\nconst idFileName = \"id\"\n\n\/\/ HostIDFile is the location of the host id file.\nfunc (s FileSystemHostIDStorage) HostIDFile() string {\n\treturn filepath.Join(s.Root, idFileName)\n}\n\n\/\/ LoadHostID loads the current host ID from the mackerel-agent's id file.\nfunc (s FileSystemHostIDStorage) LoadHostID() (string, error) {\n\tcontent, err := ioutil.ReadFile(s.HostIDFile())\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn strings.TrimRight(string(content), \"\\r\\n\"), nil\n}\n\n\/\/ SaveHostID saves the host ID to the mackerel-agent's id file.\nfunc (s FileSystemHostIDStorage) SaveHostID(id string) error {\n\terr := os.MkdirAll(s.Root, 0755)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfile, err := os.Create(s.HostIDFile())\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\t_, err = file.Write([]byte(id))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ DeleteSavedHostID deletes the mackerel-agent's id file.\nfunc (s FileSystemHostIDStorage) DeleteSavedHostID() error {\n\treturn os.Remove(s.HostIDFile())\n}\n<|endoftext|>"} {"text":"\/\/ Config is put into a different package to prevent cyclic imports in case\n\/\/ it is needed in several locations\n\npackage config\n\ntype Config struct {\n\tJmxproxybeat JmxproxybeatConfig\n}\n\ntype JmxproxybeatConfig struct {\n\tPeriod string `yaml:\"period\"`\n\tURLs []string `yaml:\"urls\"`\n\tAuthentication AuthenticationConfig `yaml:\"authentication\"`\n\tBeans []BeanConfig `yaml:\"beans\"`\n}\n\ntype AuthenticationConfig struct {\n\tUsername string\n\tPassword string\n}\n\ntype BeanConfig struct {\n\tName string `yaml:\"name\"`\n\tAttributes []Attribute `yaml:\"attributes\"`\n\tKeys []string `yaml:\"keys\"`\n}\n\ntype Attribute struct {\n\tName string `yaml:\"name\"`\n\tKeys []string `yaml:\"keys\"`\n}Cleanup code\/\/ Config is put into a different package to prevent cyclic imports in case\n\/\/ it is needed in several locations\n\npackage config\n\ntype Config struct {\n\tJmxproxybeat JmxproxybeatConfig\n}\n\ntype JmxproxybeatConfig struct {\n\tPeriod string `yaml:\"period\"`\n\tURLs []string `yaml:\"urls\"`\n\tAuthentication AuthenticationConfig `yaml:\"authentication\"`\n\tBeans []BeanConfig `yaml:\"beans\"`\n}\n\ntype AuthenticationConfig struct {\n\tUsername string\n\tPassword string\n}\n\ntype BeanConfig struct {\n\tName string `yaml:\"name\"`\n\tAttributes []Attribute `yaml:\"attributes\"`\n\tKeys []string `yaml:\"keys\"`\n}\n\ntype Attribute struct {\n\tName string `yaml:\"name\"`\n\tKeys []string `yaml:\"keys\"`\n}\n<|endoftext|>"} {"text":"\/\/ Defines the structure of our configuration file\npackage config\n\nimport (\n\t\"code.google.com\/p\/gcfg\"\n\t\"log\"\n\t\"path\"\n\t\"runtime\"\n)\n\ntype Config struct {\n\tServer struct {\n\t\tHost string\n\t\tPort int\n\t}\n\tDatabase struct {\n\t\tHost string\n\t\tPort int\n\t\tNetwork string\n\t}\n}\n\nfunc (self *Config) Load(name string) {\n\t_, filename, _, _ := runtime.Caller(1)\n\tconfigPath := path.Join(path.Dir(filename), name)\n\tif err := gcfg.ReadFileInto(self, configPath); err != nil {\n\t\tlog.Fatal(\"Error loading cfg:\", err)\n\t}\n}\n\ntype Entities struct {\n\tPlanets struct {\n\t\tRingOffset int\n\t\tPlanetRadius int\n\t\tPlanetCount int\n\t\tPlanetHashArgs int\n\t}\n\tSuns struct {\n\t\tRandomSpawnZoneRadius int\n\t\tSolarSystemRadius float64\n\t}\n}\n\nfunc (self *Entities) Load(name string) {\n\t_, filename, _, _ := runtime.Caller(1)\n\tconfigPath := path.Join(path.Dir(filename), name)\n\tif err := gcfg.ReadFileInto(self, configPath); err != nil {\n\t\tlog.Fatal(\"Error loading cfg:\", err)\n\t}\n}\nRemove config.Entities\/\/ Defines the structure of our configuration file\npackage config\n\nimport (\n\t\"code.google.com\/p\/gcfg\"\n\t\"log\"\n\t\"path\"\n\t\"runtime\"\n)\n\ntype Config struct {\n\tServer struct {\n\t\tHost string\n\t\tPort int\n\t}\n\tDatabase struct {\n\t\tHost string\n\t\tPort int\n\t\tNetwork string\n\t}\n}\n\nfunc (self *Config) Load(name string) {\n\t_, filename, _, _ := runtime.Caller(1)\n\tconfigPath := path.Join(path.Dir(filename), name)\n\tif err := gcfg.ReadFileInto(self, configPath); err != nil {\n\t\tlog.Fatal(\"Error loading cfg:\", err)\n\t}\n}\n<|endoftext|>"} {"text":"package config\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/reviewboard\/rb-gateway\/repositories\"\n)\n\nconst DefaultConfigPath = \"config.json\"\n\ntype repositoryData struct {\n\tName string `json:\"name\"`\n\tPath string `json:\"path\"`\n\tScm string `json:\"scm\"`\n}\n\ntype Config struct {\n\tHtpasswdPath string `json:\"htpasswdPath\"`\n\tPort uint16 `json:\"port\"`\n\tRepositoryData []repositoryData `json:\"repositories\"`\n\tSSLCertificate string `json:\"sslCertificate\"`\n\tSSLKey string `json:\"sslKey\"`\n\tTokenStorePath string `json:\"tokenStorePath\"`\n\tUseTLS bool `json:\"useTLS\"`\n\n\tRepositories map[string]repositories.Repository\n}\n\nfunc Load(path string) (*Config, error) {\n\tcontent, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar config Config\n\tif err = json.Unmarshal(content, &config); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar cfgDir string\n\tif cfgDir, err = filepath.Abs(path); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tcfgDir = filepath.Dir(cfgDir)\n\t}\n\n\tif err = validate(cfgDir, &config); err != nil {\n\t\treturn nil, err\n\t}\n\n\tconfig.Repositories = make(map[string]repositories.Repository)\n\n\tfor _, repo := range config.RepositoryData {\n\t\tswitch repo.Scm {\n\t\tcase \"git\":\n\t\t\tconfig.Repositories[repo.Name] = &repositories.GitRepository{\n\t\t\t\trepositories.RepositoryInfo{\n\t\t\t\t\tName: repo.Name,\n\t\t\t\t\tPath: repo.Path,\n\t\t\t\t},\n\t\t\t}\n\n\t\tdefault:\n\t\t\tlog.Printf(\"Unknown SCM '%s' while loading configuration '%s'; ignoring.\", repo.Scm, path)\n\t\t}\n\t}\n\n\treturn &config, nil\n}\n\nfunc validate(cfgDir string, config *Config) (err error) {\n\tmissingFields := []string{}\n\n\tif config.Port == 0 {\n\t\tlog.Printf(\"WARNING: Port missing, defaulting to 8888.\")\n\t\tconfig.Port = 8888\n\t}\n\n\tif len(config.RepositoryData) == 0 {\n\t\tmissingFields = append(missingFields, \"repositories\")\n\t}\n\n\tif config.UseTLS {\n\t\tif config.SSLCertificate == \"\" {\n\t\t\tmissingFields = append(missingFields, \"ssl_certificate\")\n\t\t} else {\n\t\t\tconfig.SSLCertificate = resolvePath(cfgDir, config.SSLCertificate)\n\t\t}\n\n\t\tif config.SSLKey == \"\" {\n\t\t\tmissingFields = append(missingFields, \"ssl_key\")\n\t\t} else {\n\t\t\tconfig.SSLKey = resolvePath(cfgDir, config.SSLKey)\n\t\t}\n\t}\n\n\tif config.TokenStorePath == \"\" {\n\t\tmissingFields = append(missingFields, \"tokenStorePath\")\n\t} else if config.TokenStorePath != \":memory:\" {\n\t\tconfig.TokenStorePath = resolvePath(cfgDir, config.TokenStorePath)\n\t}\n\n\tif config.HtpasswdPath == \"\" {\n\t\tmissingFields = append(missingFields, \"htpasswdPath\")\n\t} else {\n\t\tconfig.HtpasswdPath = resolvePath(cfgDir, config.HtpasswdPath)\n\t}\n\n\tif len(missingFields) != 0 {\n\t\terr = fmt.Errorf(\"Some required fields were missing from the configuration: %s.\", strings.Join(missingFields, \",\"))\n\t}\n\n\treturn\n}\n\n\/\/ Resolve a path so that . is treated as cfgDir\nfunc resolvePath(cfgDir string, path string) string {\n\tif !filepath.IsAbs(path) {\n\t\tpath = filepath.Join(cfgDir, path)\n\t}\n\treturn path\n}\nAdd defaults for Config.HtpasswdPath, Config.TokenStorePathpackage config\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"path\/filepath\"\n\t\"strings\"\n\n\t\"github.com\/reviewboard\/rb-gateway\/repositories\"\n)\n\nconst DefaultConfigPath = \"config.json\"\n\nconst (\n\tdefaultPort uint16 = 8888\n)\n\ntype repositoryData struct {\n\tName string `json:\"name\"`\n\tPath string `json:\"path\"`\n\tScm string `json:\"scm\"`\n}\n\ntype Config struct {\n\tHtpasswdPath string `json:\"htpasswdPath\"`\n\tPort uint16 `json:\"port\"`\n\tRepositoryData []repositoryData `json:\"repositories\"`\n\tSSLCertificate string `json:\"sslCertificate\"`\n\tSSLKey string `json:\"sslKey\"`\n\tTokenStorePath string `json:\"tokenStorePath\"`\n\tUseTLS bool `json:\"useTLS\"`\n\n\tRepositories map[string]repositories.Repository\n}\n\nfunc Load(path string) (*Config, error) {\n\tcontent, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar config Config\n\tif err = json.Unmarshal(content, &config); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar cfgDir string\n\tif cfgDir, err = filepath.Abs(path); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tcfgDir = filepath.Dir(cfgDir)\n\t}\n\n\tif err = validate(cfgDir, &config); err != nil {\n\t\treturn nil, err\n\t}\n\n\tconfig.Repositories = make(map[string]repositories.Repository)\n\n\tfor _, repo := range config.RepositoryData {\n\t\tswitch repo.Scm {\n\t\tcase \"git\":\n\t\t\tconfig.Repositories[repo.Name] = &repositories.GitRepository{\n\t\t\t\trepositories.RepositoryInfo{\n\t\t\t\t\tName: repo.Name,\n\t\t\t\t\tPath: repo.Path,\n\t\t\t\t},\n\t\t\t}\n\n\t\tdefault:\n\t\t\tlog.Printf(\"Unknown SCM '%s' while loading configuration '%s'; ignoring.\", repo.Scm, path)\n\t\t}\n\t}\n\n\treturn &config, nil\n}\n\nfunc validate(cfgDir string, config *Config) (err error) {\n\tmissingFields := []string{}\n\n\tif config.Port == 0 {\n\t\tlog.Printf(\"WARNING: Port missing from config, defaulting to %d.\", defaultPort)\n\t\tconfig.Port = defaultPort\n\t}\n\n\tif len(config.RepositoryData) == 0 {\n\t\tmissingFields = append(missingFields, \"repositories\")\n\t}\n\n\tif config.UseTLS {\n\t\tif config.SSLCertificate == \"\" {\n\t\t\tmissingFields = append(missingFields, \"ssl_certificate\")\n\t\t} else {\n\t\t\tconfig.SSLCertificate = resolvePath(cfgDir, config.SSLCertificate)\n\t\t}\n\n\t\tif config.SSLKey == \"\" {\n\t\t\tmissingFields = append(missingFields, \"ssl_key\")\n\t\t} else {\n\t\t\tconfig.SSLKey = resolvePath(cfgDir, config.SSLKey)\n\t\t}\n\t}\n\n\toptionalPathFields := []struct {\n\t\tfield *string\n\t\tname string\n\t\tdefaultValue string\n\t}{\n\t\t{&config.TokenStorePath, \"tokenStorePath\", \"tokens.dat\"},\n\t\t{&config.HtpasswdPath, \"htpasswdPath\", \"htpasswd\"},\n\t}\n\n\tfor _, fieldInfo := range optionalPathFields {\n\t\tif *fieldInfo.field == \"\" {\n\t\t\tlog.Printf(`Warning: %s missing from config, defaulting to \"%v\".`, fieldInfo.name, fieldInfo.defaultValue)\n\t\t\t*fieldInfo.field = fieldInfo.defaultValue\n\t\t}\n\t}\n\n\tif config.TokenStorePath != \":memory:\" {\n\t\tconfig.TokenStorePath = resolvePath(cfgDir, config.TokenStorePath)\n\t}\n\n\tconfig.HtpasswdPath = resolvePath(cfgDir, config.HtpasswdPath)\n\n\tif len(missingFields) != 0 {\n\t\terr = fmt.Errorf(\"Some required fields were missing from the configuration: %s.\", strings.Join(missingFields, \",\"))\n\t}\n\n\treturn\n}\n\n\/\/ Resolve a path so that . is treated as cfgDir\nfunc resolvePath(cfgDir string, path string) string {\n\tif !filepath.IsAbs(path) {\n\t\tpath = filepath.Join(cfgDir, path)\n\t}\n\treturn path\n}\n<|endoftext|>"} {"text":"package config\n\nimport (\n\t\"gopkg.in\/yaml.v2\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/user\"\n\t\"path\"\n)\n\nconst DefaultConfigFileName = \".graven.yaml\"\n\ntype Config struct {\n\tconfigFileName string\n\tdata map[string]interface{}\n}\n\nfunc NewConfig() Config {\n\tconfig := Config{}\n\tconfig.data = map[string]interface{}{}\n\tconfig.configFileName = DefaultConfigFileName\n\treturn config\n}\n\nfunc (c Config) Set(name string, value interface{}) {\n\tc.data[name] = value\n}\n\nfunc (c Config) Get(name string) interface{} {\n\treturn c.data[name]\n}\n\nfunc (c Config) GetString(name string) string {\n\tif v, ok := c.data[name]; ok {\n\t\treturn v.(string)\n\t}\n\treturn \"\"\n}\n\nfunc (c Config) GetMap(name string) map[string]interface{} {\n\tif v, ok := c.data[name]; ok {\n\t\treturn v.(map[string]interface{})\n\t}\n\treturn map[string]interface{}{}\n}\n\nfunc (c Config) GetMaps(name string) []map[string]interface{} {\n\tif v, ok := c.data[name]; ok {\n\t\treturn v.([]map[string]interface{})\n\t}\n\treturn []map[string]interface{}{}\n}\n\nfunc (c Config) Read() error {\n\tusr, err := user.Current()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfile, err := os.Open(path.Join(usr.HomeDir, c.configFileName))\n\tif err != nil {\n\t\treturn err\n\t}\n\tbytes, err := ioutil.ReadAll(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = yaml.Unmarshal(bytes, c)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (c Config) Write() error {\n\tusr, err := user.Current()\n\tif err != nil {\n\t\treturn err\n\t}\n\tbytes, err := yaml.Marshal(c)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(path.Join(usr.HomeDir, c.configFileName), bytes, 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\nfixing loginpackage config\n\nimport (\n\t\"gopkg.in\/yaml.v2\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"os\/user\"\n\t\"path\"\n)\n\nconst DefaultConfigFileName = \".graven.yaml\"\n\ntype Config struct {\n\tconfigFileName string\n\tdata map[string]interface{}\n}\n\nfunc NewConfig() Config {\n\tconfig := Config{}\n\tconfig.data = map[string]interface{}{}\n\tconfig.configFileName = DefaultConfigFileName\n\treturn config\n}\n\nfunc (c Config) Set(name string, value interface{}) {\n\tc.data[name] = value\n}\n\nfunc (c Config) Get(name string) interface{} {\n\treturn c.data[name]\n}\n\nfunc (c Config) GetString(name string) string {\n\tif v, ok := c.data[name]; ok {\n\t\treturn v.(string)\n\t}\n\treturn \"\"\n}\n\nfunc (c Config) GetMap(name string) map[string]interface{} {\n\tif v, ok := c.data[name]; ok {\n\t\treturn v.(map[string]interface{})\n\t}\n\treturn map[string]interface{}{}\n}\n\nfunc (c Config) GetMaps(name string) []map[string]interface{} {\n\tif v, ok := c.data[name]; ok {\n\t\treturn v.([]map[string]interface{})\n\t}\n\treturn []map[string]interface{}{}\n}\n\nfunc (c Config) Read() error {\n\tusr, err := user.Current()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfile, err := os.Open(path.Join(usr.HomeDir, c.configFileName))\n\tif err != nil {\n\t\treturn err\n\t}\n\tbytes, err := ioutil.ReadAll(file)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = yaml.Unmarshal(bytes, c)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (c Config) Write() error {\n\tusr, err := user.Current()\n\tif err != nil {\n\t\treturn err\n\t}\n\tbytes, err := yaml.Marshal(c.data)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(path.Join(usr.HomeDir, c.configFileName), bytes, 0600)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n<|endoftext|>"} {"text":"package release\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com\/goreleaser\/goreleaser\/context\"\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\nfunc TestDescribeBody(t *testing.T) {\n\tvar assert = assert.New(t)\n\tvar changelog = \"\\nfeature1: description\\nfeature2: other description\"\n\tvar ctx = &context.Context{\n\t\tReleaseNotes: changelog,\n\t}\n\tout, err := describeBody(ctx)\n\tassert.NoError(err)\n\tassert.Contains(out.String(), changelog)\n\tassert.Contains(out.String(), \"Automated with @goreleaser\")\n\tassert.Contains(out.String(), \"Built with go version go1.8\")\n}\n\nfunc TestGoVersionFails(t *testing.T) {\n\tvar assert = assert.New(t)\n\tvar path = os.Getenv(\"PATH\")\n\tdefer func() {\n\t\tassert.NoError(os.Setenv(\"PATH\", path))\n\t}()\n\tassert.NoError(os.Setenv(\"PATH\", \"\"))\n\tvar ctx = &context.Context{\n\t\tReleaseNotes: \"changelog\",\n\t}\n\t_, err := describeBody(ctx)\n\tassert.Error(err)\n}\nfixed unit testpackage release\n\nimport (\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com\/goreleaser\/goreleaser\/context\"\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\nfunc TestDescribeBody(t *testing.T) {\n\tvar assert = assert.New(t)\n\tvar changelog = \"\\nfeature1: description\\nfeature2: other description\"\n\tvar ctx = &context.Context{\n\t\tReleaseNotes: changelog,\n\t}\n\tout, err := describeBody(ctx)\n\tassert.NoError(err)\n\tassert.Contains(out.String(), changelog)\n\tassert.Contains(out.String(), \"Automated with [GoReleaser]\")\n\tassert.Contains(out.String(), \"Built with go version go1.8\")\n}\n\nfunc TestGoVersionFails(t *testing.T) {\n\tvar assert = assert.New(t)\n\tvar path = os.Getenv(\"PATH\")\n\tdefer func() {\n\t\tassert.NoError(os.Setenv(\"PATH\", path))\n\t}()\n\tassert.NoError(os.Setenv(\"PATH\", \"\"))\n\tvar ctx = &context.Context{\n\t\tReleaseNotes: \"changelog\",\n\t}\n\t_, err := describeBody(ctx)\n\tassert.Error(err)\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2017 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 gps\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com\/golang\/dep\/internal\/fs\"\n\t\"github.com\/pkg\/errors\"\n)\n\n\/\/ PruneOptions represents the pruning options used to write the dependecy tree.\ntype PruneOptions uint8\n\nconst (\n\t\/\/ PruneNestedVendorDirs indicates if nested vendor directories should be pruned.\n\tPruneNestedVendorDirs PruneOptions = 1 << iota\n\t\/\/ PruneUnusedPackages indicates if unused Go packages should be pruned.\n\tPruneUnusedPackages\n\t\/\/ PruneNonGoFiles indicates if non-Go files should be pruned.\n\t\/\/ Files matching licenseFilePrefixes and legalFileSubstrings are kept in\n\t\/\/ an attempt to comply with legal requirements.\n\tPruneNonGoFiles\n\t\/\/ PruneGoTestFiles indicates if Go test files should be pruned.\n\tPruneGoTestFiles\n)\n\n\/\/ PruneOptionSet represents trinary distinctions for each of the types of\n\/\/ prune rules (as expressed via PruneOptions): nested vendor directories,\n\/\/ unused packages, non-go files, and go test files.\n\/\/\n\/\/ The three-way distinction is between \"none\", \"true\", and \"false\", represented\n\/\/ by uint8 values of 0, 1, and 2, respectively.\n\/\/\n\/\/ This trinary distinction is necessary in order to record, with full fidelity,\n\/\/ a cascading tree of pruning values, as expressed in CascadingPruneOptions; a\n\/\/ simple boolean cannot delineate between \"false\" and \"none\".\ntype PruneOptionSet struct {\n\tNestedVendor uint8\n\tUnusedPackages uint8\n\tNonGoFiles uint8\n\tGoTests uint8\n}\n\n\/\/ CascadingPruneOptions is a set of rules for pruning a dependency tree.\n\/\/\n\/\/ The DefaultOptions are the global default pruning rules, expressed as a\n\/\/ single PruneOptions bitfield. These global rules will cascade down to\n\/\/ individual project rules, unless superseded.\ntype CascadingPruneOptions struct {\n\tDefaultOptions PruneOptions\n\tPerProjectOptions map[ProjectRoot]PruneOptionSet\n}\n\n\/\/ PruneOptionsFor returns the PruneOptions bits for the given project,\n\/\/ indicating which pruning rules should be applied to the project's code.\n\/\/\n\/\/ It computes the cascade from default to project-specific options (if any) on\n\/\/ the fly.\nfunc (o CascadingPruneOptions) PruneOptionsFor(pr ProjectRoot) PruneOptions {\n\tpo, has := o.PerProjectOptions[pr]\n\tif !has {\n\t\treturn o.DefaultOptions\n\t}\n\n\tops := o.DefaultOptions\n\tif po.NestedVendor != 0 {\n\t\tif po.NestedVendor == 1 {\n\t\t\tops |= PruneNestedVendorDirs\n\t\t} else {\n\t\t\tops &^= PruneNestedVendorDirs\n\t\t}\n\t}\n\n\tif po.UnusedPackages != 0 {\n\t\tif po.UnusedPackages == 1 {\n\t\t\tops |= PruneUnusedPackages\n\t\t} else {\n\t\t\tops &^= PruneUnusedPackages\n\t\t}\n\t}\n\n\tif po.NonGoFiles != 0 {\n\t\tif po.NonGoFiles == 1 {\n\t\t\tops |= PruneNonGoFiles\n\t\t} else {\n\t\t\tops &^= PruneNonGoFiles\n\t\t}\n\t}\n\n\tif po.GoTests != 0 {\n\t\tif po.GoTests == 1 {\n\t\t\tops |= PruneGoTestFiles\n\t\t} else {\n\t\t\tops &^= PruneGoTestFiles\n\t\t}\n\t}\n\n\treturn ops\n}\n\nfunc defaultCascadingPruneOptions() CascadingPruneOptions {\n\treturn CascadingPruneOptions{\n\t\tDefaultOptions: PruneNestedVendorDirs,\n\t\tPerProjectOptions: map[ProjectRoot]PruneOptionSet{},\n\t}\n}\n\nvar (\n\t\/\/ licenseFilePrefixes is a list of name prefixes for license files.\n\tlicenseFilePrefixes = []string{\n\t\t\"license\",\n\t\t\"licence\",\n\t\t\"copying\",\n\t\t\"unlicense\",\n\t\t\"copyright\",\n\t\t\"copyleft\",\n\t}\n\t\/\/ legalFileSubstrings contains substrings that are likey part of a legal\n\t\/\/ declaration file.\n\tlegalFileSubstrings = []string{\n\t\t\"authors\",\n\t\t\"contributors\",\n\t\t\"legal\",\n\t\t\"notice\",\n\t\t\"disclaimer\",\n\t\t\"patent\",\n\t\t\"third-party\",\n\t\t\"thirdparty\",\n\t}\n)\n\n\/\/ PruneProject remove excess files according to the options passed, from\n\/\/ the lp directory in baseDir.\nfunc PruneProject(baseDir string, lp LockedProject, options PruneOptions, logger *log.Logger) error {\n\tfsState, err := deriveFilesystemState(baseDir)\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"could not derive filesystem state\")\n\t}\n\n\tif (options & PruneNestedVendorDirs) != 0 {\n\t\tif err := pruneVendorDirs(fsState); err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed to prune nested vendor directories\")\n\t\t}\n\t}\n\n\tif (options & PruneUnusedPackages) != 0 {\n\t\tif _, err := pruneUnusedPackages(lp, fsState); err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to prune unused packages\")\n\t\t}\n\t}\n\n\tif (options & PruneNonGoFiles) != 0 {\n\t\tif err := pruneNonGoFiles(fsState); err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to prune non-Go files\")\n\t\t}\n\t}\n\n\tif (options & PruneGoTestFiles) != 0 {\n\t\tif err := pruneGoTestFiles(fsState); err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to prune Go test files\")\n\t\t}\n\t}\n\n\tif err := deleteEmptyDirs(fsState); err != nil {\n\t\treturn errors.Wrap(err, \"could not delete empty dirs\")\n\t}\n\n\treturn nil\n}\n\n\/\/ pruneVendorDirs deletes all nested vendor directories within baseDir.\nfunc pruneVendorDirs(fsState filesystemState) error {\n\tfor _, dir := range fsState.dirs {\n\t\tif filepath.Base(dir) == \"vendor\" {\n\t\t\terr := os.RemoveAll(filepath.Join(fsState.root, dir))\n\t\t\tif err != nil && !os.IsNotExist(err) {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, link := range fsState.links {\n\t\tif filepath.Base(link.path) == \"vendor\" {\n\t\t\terr := os.Remove(filepath.Join(fsState.root, link.path))\n\t\t\tif err != nil && !os.IsNotExist(err) {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ pruneUnusedPackages deletes unimported packages found in fsState.\n\/\/ Determining whether packages are imported or not is based on the passed LockedProject.\nfunc pruneUnusedPackages(lp LockedProject, fsState filesystemState) (map[string]interface{}, error) {\n\tunusedPackages := calculateUnusedPackages(lp, fsState)\n\ttoDelete := collectUnusedPackagesFiles(fsState, unusedPackages)\n\n\tfor _, path := range toDelete {\n\t\tif err := os.Remove(path); err != nil && !os.IsNotExist(err) {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn unusedPackages, nil\n}\n\n\/\/ calculateUnusedPackages generates a list of unused packages in lp.\nfunc calculateUnusedPackages(lp LockedProject, fsState filesystemState) map[string]interface{} {\n\tunused := make(map[string]interface{})\n\timported := make(map[string]interface{})\n\n\tfor _, pkg := range lp.Packages() {\n\t\timported[pkg] = nil\n\t}\n\n\t\/\/ Add the root package if it's not imported.\n\tif _, ok := imported[\".\"]; !ok {\n\t\tunused[\".\"] = nil\n\t}\n\n\tfor _, dirPath := range fsState.dirs {\n\t\tpkg := filepath.ToSlash(dirPath)\n\n\t\tif _, ok := imported[pkg]; !ok {\n\t\t\tunused[pkg] = nil\n\t\t}\n\t}\n\n\treturn unused\n}\n\n\/\/ collectUnusedPackagesFiles returns a slice of all files in the unused\n\/\/ packages based on fsState.\nfunc collectUnusedPackagesFiles(fsState filesystemState, unusedPackages map[string]interface{}) []string {\n\t\/\/ TODO(ibrasho): is this useful?\n\tfiles := make([]string, 0, len(unusedPackages))\n\n\tfor _, path := range fsState.files {\n\t\t\/\/ Keep perserved files.\n\t\tif isPreservedFile(filepath.Base(path)) {\n\t\t\tcontinue\n\t\t}\n\n\t\tpkg := filepath.ToSlash(filepath.Dir(path))\n\n\t\tif _, ok := unusedPackages[pkg]; ok {\n\t\t\tfiles = append(files, filepath.Join(fsState.root, path))\n\t\t}\n\t}\n\n\treturn files\n}\n\nfunc isSourceFile(path string) bool {\n\text := fileExt(path)\n\n\t\/\/ Refer to: https:\/\/github.com\/golang\/go\/blob\/release-branch.go1.9\/src\/go\/build\/build.go#L750\n\tswitch ext {\n\tcase \".go\":\n\t\treturn true\n\tcase \".c\":\n\t\treturn true\n\tcase \".cc\", \".cpp\", \".cxx\":\n\t\treturn true\n\tcase \".m\":\n\t\treturn true\n\tcase \".h\", \".hh\", \".hpp\", \".hxx\":\n\t\treturn true\n\tcase \".f\", \".F\", \".for\", \".f90\":\n\t\treturn true\n\tcase \".s\":\n\t\treturn true\n\tcase \".S\":\n\t\treturn true\n\tcase \".swig\":\n\t\treturn true\n\tcase \".swigcxx\":\n\t\treturn true\n\tcase \".syso\":\n\t\treturn true\n\t}\n\treturn false\n}\n\n\/\/ pruneNonGoFiles delete all non-Go files existing in fsState.\n\/\/\n\/\/ Files matching licenseFilePrefixes and legalFileSubstrings are not pruned.\nfunc pruneNonGoFiles(fsState filesystemState) error {\n\ttoDelete := make([]string, 0, len(fsState.files)\/4)\n\n\tfor _, path := range fsState.files {\n\t\tif isSourceFile(path) {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Ignore perserved files.\n\t\tif isPreservedFile(filepath.Base(path)) {\n\t\t\tcontinue\n\t\t}\n\n\t\ttoDelete = append(toDelete, filepath.Join(fsState.root, path))\n\t}\n\n\tfor _, path := range toDelete {\n\t\tif err := os.Remove(path); err != nil && !os.IsNotExist(err) {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ isPreservedFile checks if the file name indicates that the file should be\n\/\/ preserved based on licenseFilePrefixes or legalFileSubstrings.\nfunc isPreservedFile(name string) bool {\n\tname = strings.ToLower(name)\n\n\tfor _, prefix := range licenseFilePrefixes {\n\t\tif strings.HasPrefix(name, prefix) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\tfor _, substring := range legalFileSubstrings {\n\t\tif strings.Contains(name, substring) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\n\/\/ pruneGoTestFiles deletes all Go test files (*_test.go) in fsState.\nfunc pruneGoTestFiles(fsState filesystemState) error {\n\ttoDelete := make([]string, 0, len(fsState.files)\/2)\n\n\tfor _, path := range fsState.files {\n\t\tif strings.HasSuffix(path, \"_test.go\") {\n\t\t\ttoDelete = append(toDelete, filepath.Join(fsState.root, path))\n\t\t}\n\t}\n\n\tfor _, path := range toDelete {\n\t\tif err := os.Remove(path); err != nil && !os.IsNotExist(err) {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc deleteEmptyDirs(fsState filesystemState) error {\n\tsort.Sort(sort.Reverse(sort.StringSlice(fsState.dirs)))\n\n\tfor _, dir := range fsState.dirs {\n\t\tpath := filepath.Join(fsState.root, dir)\n\n\t\tnotEmpty, err := fs.IsNonEmptyDir(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif !notEmpty {\n\t\t\tif err := os.Remove(path); err != nil && !os.IsNotExist(err) {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc fileExt(name string) string {\n\ti := strings.LastIndex(name, \".\")\n\tif i < 0 {\n\t\treturn \"\"\n\t}\n\treturn name[i:]\n}\nprune: Fix handling of \"legal\" source files\/\/ Copyright 2017 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 gps\n\nimport (\n\t\"log\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com\/golang\/dep\/internal\/fs\"\n\t\"github.com\/pkg\/errors\"\n)\n\n\/\/ PruneOptions represents the pruning options used to write the dependecy tree.\ntype PruneOptions uint8\n\nconst (\n\t\/\/ PruneNestedVendorDirs indicates if nested vendor directories should be pruned.\n\tPruneNestedVendorDirs PruneOptions = 1 << iota\n\t\/\/ PruneUnusedPackages indicates if unused Go packages should be pruned.\n\tPruneUnusedPackages\n\t\/\/ PruneNonGoFiles indicates if non-Go files should be pruned.\n\t\/\/ Files matching licenseFilePrefixes and legalFileSubstrings are kept in\n\t\/\/ an attempt to comply with legal requirements.\n\tPruneNonGoFiles\n\t\/\/ PruneGoTestFiles indicates if Go test files should be pruned.\n\tPruneGoTestFiles\n)\n\n\/\/ PruneOptionSet represents trinary distinctions for each of the types of\n\/\/ prune rules (as expressed via PruneOptions): nested vendor directories,\n\/\/ unused packages, non-go files, and go test files.\n\/\/\n\/\/ The three-way distinction is between \"none\", \"true\", and \"false\", represented\n\/\/ by uint8 values of 0, 1, and 2, respectively.\n\/\/\n\/\/ This trinary distinction is necessary in order to record, with full fidelity,\n\/\/ a cascading tree of pruning values, as expressed in CascadingPruneOptions; a\n\/\/ simple boolean cannot delineate between \"false\" and \"none\".\ntype PruneOptionSet struct {\n\tNestedVendor uint8\n\tUnusedPackages uint8\n\tNonGoFiles uint8\n\tGoTests uint8\n}\n\n\/\/ CascadingPruneOptions is a set of rules for pruning a dependency tree.\n\/\/\n\/\/ The DefaultOptions are the global default pruning rules, expressed as a\n\/\/ single PruneOptions bitfield. These global rules will cascade down to\n\/\/ individual project rules, unless superseded.\ntype CascadingPruneOptions struct {\n\tDefaultOptions PruneOptions\n\tPerProjectOptions map[ProjectRoot]PruneOptionSet\n}\n\n\/\/ PruneOptionsFor returns the PruneOptions bits for the given project,\n\/\/ indicating which pruning rules should be applied to the project's code.\n\/\/\n\/\/ It computes the cascade from default to project-specific options (if any) on\n\/\/ the fly.\nfunc (o CascadingPruneOptions) PruneOptionsFor(pr ProjectRoot) PruneOptions {\n\tpo, has := o.PerProjectOptions[pr]\n\tif !has {\n\t\treturn o.DefaultOptions\n\t}\n\n\tops := o.DefaultOptions\n\tif po.NestedVendor != 0 {\n\t\tif po.NestedVendor == 1 {\n\t\t\tops |= PruneNestedVendorDirs\n\t\t} else {\n\t\t\tops &^= PruneNestedVendorDirs\n\t\t}\n\t}\n\n\tif po.UnusedPackages != 0 {\n\t\tif po.UnusedPackages == 1 {\n\t\t\tops |= PruneUnusedPackages\n\t\t} else {\n\t\t\tops &^= PruneUnusedPackages\n\t\t}\n\t}\n\n\tif po.NonGoFiles != 0 {\n\t\tif po.NonGoFiles == 1 {\n\t\t\tops |= PruneNonGoFiles\n\t\t} else {\n\t\t\tops &^= PruneNonGoFiles\n\t\t}\n\t}\n\n\tif po.GoTests != 0 {\n\t\tif po.GoTests == 1 {\n\t\t\tops |= PruneGoTestFiles\n\t\t} else {\n\t\t\tops &^= PruneGoTestFiles\n\t\t}\n\t}\n\n\treturn ops\n}\n\nfunc defaultCascadingPruneOptions() CascadingPruneOptions {\n\treturn CascadingPruneOptions{\n\t\tDefaultOptions: PruneNestedVendorDirs,\n\t\tPerProjectOptions: map[ProjectRoot]PruneOptionSet{},\n\t}\n}\n\nvar (\n\t\/\/ licenseFilePrefixes is a list of name prefixes for license files.\n\tlicenseFilePrefixes = []string{\n\t\t\"license\",\n\t\t\"licence\",\n\t\t\"copying\",\n\t\t\"unlicense\",\n\t\t\"copyright\",\n\t\t\"copyleft\",\n\t}\n\t\/\/ legalFileSubstrings contains substrings that are likey part of a legal\n\t\/\/ declaration file.\n\tlegalFileSubstrings = []string{\n\t\t\"authors\",\n\t\t\"contributors\",\n\t\t\"legal\",\n\t\t\"notice\",\n\t\t\"disclaimer\",\n\t\t\"patent\",\n\t\t\"third-party\",\n\t\t\"thirdparty\",\n\t}\n)\n\n\/\/ PruneProject remove excess files according to the options passed, from\n\/\/ the lp directory in baseDir.\nfunc PruneProject(baseDir string, lp LockedProject, options PruneOptions, logger *log.Logger) error {\n\tfsState, err := deriveFilesystemState(baseDir)\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"could not derive filesystem state\")\n\t}\n\n\tif (options & PruneNestedVendorDirs) != 0 {\n\t\tif err := pruneVendorDirs(fsState); err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed to prune nested vendor directories\")\n\t\t}\n\t}\n\n\tif (options & PruneUnusedPackages) != 0 {\n\t\tif _, err := pruneUnusedPackages(lp, fsState); err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to prune unused packages\")\n\t\t}\n\t}\n\n\tif (options & PruneNonGoFiles) != 0 {\n\t\tif err := pruneNonGoFiles(fsState); err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to prune non-Go files\")\n\t\t}\n\t}\n\n\tif (options & PruneGoTestFiles) != 0 {\n\t\tif err := pruneGoTestFiles(fsState); err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to prune Go test files\")\n\t\t}\n\t}\n\n\tif err := deleteEmptyDirs(fsState); err != nil {\n\t\treturn errors.Wrap(err, \"could not delete empty dirs\")\n\t}\n\n\treturn nil\n}\n\n\/\/ pruneVendorDirs deletes all nested vendor directories within baseDir.\nfunc pruneVendorDirs(fsState filesystemState) error {\n\tfor _, dir := range fsState.dirs {\n\t\tif filepath.Base(dir) == \"vendor\" {\n\t\t\terr := os.RemoveAll(filepath.Join(fsState.root, dir))\n\t\t\tif err != nil && !os.IsNotExist(err) {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, link := range fsState.links {\n\t\tif filepath.Base(link.path) == \"vendor\" {\n\t\t\terr := os.Remove(filepath.Join(fsState.root, link.path))\n\t\t\tif err != nil && !os.IsNotExist(err) {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ pruneUnusedPackages deletes unimported packages found in fsState.\n\/\/ Determining whether packages are imported or not is based on the passed LockedProject.\nfunc pruneUnusedPackages(lp LockedProject, fsState filesystemState) (map[string]interface{}, error) {\n\tunusedPackages := calculateUnusedPackages(lp, fsState)\n\ttoDelete := collectUnusedPackagesFiles(fsState, unusedPackages)\n\n\tfor _, path := range toDelete {\n\t\tif err := os.Remove(path); err != nil && !os.IsNotExist(err) {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn unusedPackages, nil\n}\n\n\/\/ calculateUnusedPackages generates a list of unused packages in lp.\nfunc calculateUnusedPackages(lp LockedProject, fsState filesystemState) map[string]interface{} {\n\tunused := make(map[string]interface{})\n\timported := make(map[string]interface{})\n\n\tfor _, pkg := range lp.Packages() {\n\t\timported[pkg] = nil\n\t}\n\n\t\/\/ Add the root package if it's not imported.\n\tif _, ok := imported[\".\"]; !ok {\n\t\tunused[\".\"] = nil\n\t}\n\n\tfor _, dirPath := range fsState.dirs {\n\t\tpkg := filepath.ToSlash(dirPath)\n\n\t\tif _, ok := imported[pkg]; !ok {\n\t\t\tunused[pkg] = nil\n\t\t}\n\t}\n\n\treturn unused\n}\n\n\/\/ collectUnusedPackagesFiles returns a slice of all files in the unused\n\/\/ packages based on fsState.\nfunc collectUnusedPackagesFiles(fsState filesystemState, unusedPackages map[string]interface{}) []string {\n\t\/\/ TODO(ibrasho): is this useful?\n\tfiles := make([]string, 0, len(unusedPackages))\n\n\tfor _, path := range fsState.files {\n\t\t\/\/ Keep perserved files.\n\t\tif isPreservedFile(filepath.Base(path)) {\n\t\t\tcontinue\n\t\t}\n\n\t\tpkg := filepath.ToSlash(filepath.Dir(path))\n\n\t\tif _, ok := unusedPackages[pkg]; ok {\n\t\t\tfiles = append(files, filepath.Join(fsState.root, path))\n\t\t}\n\t}\n\n\treturn files\n}\n\nfunc isSourceFile(path string) bool {\n\text := fileExt(path)\n\n\t\/\/ Refer to: https:\/\/github.com\/golang\/go\/blob\/release-branch.go1.9\/src\/go\/build\/build.go#L750\n\tswitch ext {\n\tcase \".go\":\n\t\treturn true\n\tcase \".c\":\n\t\treturn true\n\tcase \".cc\", \".cpp\", \".cxx\":\n\t\treturn true\n\tcase \".m\":\n\t\treturn true\n\tcase \".h\", \".hh\", \".hpp\", \".hxx\":\n\t\treturn true\n\tcase \".f\", \".F\", \".for\", \".f90\":\n\t\treturn true\n\tcase \".s\":\n\t\treturn true\n\tcase \".S\":\n\t\treturn true\n\tcase \".swig\":\n\t\treturn true\n\tcase \".swigcxx\":\n\t\treturn true\n\tcase \".syso\":\n\t\treturn true\n\t}\n\treturn false\n}\n\n\/\/ pruneNonGoFiles delete all non-Go files existing in fsState.\n\/\/\n\/\/ Files matching licenseFilePrefixes and legalFileSubstrings are not pruned.\nfunc pruneNonGoFiles(fsState filesystemState) error {\n\ttoDelete := make([]string, 0, len(fsState.files)\/4)\n\n\tfor _, path := range fsState.files {\n\t\tif isSourceFile(path) {\n\t\t\tcontinue\n\t\t}\n\n\t\t\/\/ Ignore perserved files.\n\t\tif isPreservedFile(filepath.Base(path)) {\n\t\t\tcontinue\n\t\t}\n\n\t\ttoDelete = append(toDelete, filepath.Join(fsState.root, path))\n\t}\n\n\tfor _, path := range toDelete {\n\t\tif err := os.Remove(path); err != nil && !os.IsNotExist(err) {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ isPreservedFile checks if the file name indicates that the file should be\n\/\/ preserved based on licenseFilePrefixes or legalFileSubstrings.\n\/\/ This applies only to non-source files.\nfunc isPreservedFile(name string) bool {\n\tif isSourceFile(name) {\n\t\treturn false\n\t}\n\n\tname = strings.ToLower(name)\n\n\tfor _, prefix := range licenseFilePrefixes {\n\t\tif strings.HasPrefix(name, prefix) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\tfor _, substring := range legalFileSubstrings {\n\t\tif strings.Contains(name, substring) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\n\/\/ pruneGoTestFiles deletes all Go test files (*_test.go) in fsState.\nfunc pruneGoTestFiles(fsState filesystemState) error {\n\ttoDelete := make([]string, 0, len(fsState.files)\/2)\n\n\tfor _, path := range fsState.files {\n\t\tif strings.HasSuffix(path, \"_test.go\") {\n\t\t\ttoDelete = append(toDelete, filepath.Join(fsState.root, path))\n\t\t}\n\t}\n\n\tfor _, path := range toDelete {\n\t\tif err := os.Remove(path); err != nil && !os.IsNotExist(err) {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc deleteEmptyDirs(fsState filesystemState) error {\n\tsort.Sort(sort.Reverse(sort.StringSlice(fsState.dirs)))\n\n\tfor _, dir := range fsState.dirs {\n\t\tpath := filepath.Join(fsState.root, dir)\n\n\t\tnotEmpty, err := fs.IsNonEmptyDir(path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif !notEmpty {\n\t\t\tif err := os.Remove(path); err != nil && !os.IsNotExist(err) {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc fileExt(name string) string {\n\ti := strings.LastIndex(name, \".\")\n\tif i < 0 {\n\t\treturn \"\"\n\t}\n\treturn name[i:]\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2019 Istio Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Package annotations makes it possible to track use of resource annotations within a procress\n\/\/ in order to generate documentation for these uses.\npackage annotations\n\nimport (\n\t\"sort\"\n\t\"sync\"\n\n\t\"istio.io\/istio\/pkg\/log\"\n)\n\n\/\/ Annotation describes a single resource annotation\ntype Annotation struct {\n\t\/\/ The name of the annotation.\n\tName string\n\n\t\/\/ Description of the annotation.\n\tDescription string\n\n\t\/\/ Hide the existence of this annotation when outputting usage information.\n\tHidden bool\n\n\t\/\/ Mark this annotation as deprecated when generating usage information.\n\tDeprecated bool\n}\n\nvar allAnnotations = make(map[string]Annotation)\nvar mutex sync.Mutex\n\n\/\/ Returns a description of this process' annotations, sorted by name.\nfunc Descriptions() []Annotation {\n\tmutex.Lock()\n\tsorted := make([]Annotation, 0, len(allAnnotations))\n\tfor _, v := range allAnnotations {\n\t\tsorted = append(sorted, v)\n\t}\n\tmutex.Unlock()\n\n\tsort.Slice(sorted, func(i, j int) bool {\n\t\treturn sorted[i].Name < sorted[j].Name\n\t})\n\n\treturn sorted\n}\n\n\/\/ Register registers a new annotation.\nfunc Register(name string, description string) Annotation {\n\ta := Annotation{Name: name, Description: description}\n\tRegisterFull(a)\n\n\t\/\/ get what's actually been registered\n\tmutex.Lock()\n\tresult := allAnnotations[name]\n\tmutex.Unlock()\n\n\treturn result\n}\n\n\/\/ RegisterFull registers a new annotation.\nfunc RegisterFull(a Annotation) {\n\tmutex.Lock()\n\n\tif old, ok := allAnnotations[a.Name]; ok {\n\t\tif a.Description != \"\" {\n\t\t\tallAnnotations[a.Name] = a \/\/ last one with a description wins if the same annotation name is registered multiple times\n\t\t}\n\n\t\tif old.Description != a.Description || old.Deprecated != a.Deprecated || old.Hidden != a.Hidden {\n\t\t\tlog.Warnf(\"The annotation %s was registered multiple times using different metadata: %v, %v\", a.Name, old, a)\n\t\t}\n\t} else {\n\t\tallAnnotations[a.Name] = a\n\t}\n\n\tmutex.Unlock()\n}\nUpdate import path of log package.\/\/ Copyright 2019 Istio Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Package annotations makes it possible to track use of resource annotations within a procress\n\/\/ in order to generate documentation for these uses.\npackage annotations\n\nimport (\n\t\"sort\"\n\t\"sync\"\n\n\t\"istio.io\/common\/pkg\/log\"\n)\n\n\/\/ Annotation describes a single resource annotation\ntype Annotation struct {\n\t\/\/ The name of the annotation.\n\tName string\n\n\t\/\/ Description of the annotation.\n\tDescription string\n\n\t\/\/ Hide the existence of this annotation when outputting usage information.\n\tHidden bool\n\n\t\/\/ Mark this annotation as deprecated when generating usage information.\n\tDeprecated bool\n}\n\nvar allAnnotations = make(map[string]Annotation)\nvar mutex sync.Mutex\n\n\/\/ Returns a description of this process' annotations, sorted by name.\nfunc Descriptions() []Annotation {\n\tmutex.Lock()\n\tsorted := make([]Annotation, 0, len(allAnnotations))\n\tfor _, v := range allAnnotations {\n\t\tsorted = append(sorted, v)\n\t}\n\tmutex.Unlock()\n\n\tsort.Slice(sorted, func(i, j int) bool {\n\t\treturn sorted[i].Name < sorted[j].Name\n\t})\n\n\treturn sorted\n}\n\n\/\/ Register registers a new annotation.\nfunc Register(name string, description string) Annotation {\n\ta := Annotation{Name: name, Description: description}\n\tRegisterFull(a)\n\n\t\/\/ get what's actually been registered\n\tmutex.Lock()\n\tresult := allAnnotations[name]\n\tmutex.Unlock()\n\n\treturn result\n}\n\n\/\/ RegisterFull registers a new annotation.\nfunc RegisterFull(a Annotation) {\n\tmutex.Lock()\n\n\tif old, ok := allAnnotations[a.Name]; ok {\n\t\tif a.Description != \"\" {\n\t\t\tallAnnotations[a.Name] = a \/\/ last one with a description wins if the same annotation name is registered multiple times\n\t\t}\n\n\t\tif old.Description != a.Description || old.Deprecated != a.Deprecated || old.Hidden != a.Hidden {\n\t\t\tlog.Warnf(\"The annotation %s was registered multiple times using different metadata: %v, %v\", a.Name, old, a)\n\t\t}\n\t} else {\n\t\tallAnnotations[a.Name] = a\n\t}\n\n\tmutex.Unlock()\n}\n<|endoftext|>"} {"text":"package api\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"k8s.io\/kubernetes\/pkg\/api\"\n\t\"k8s.io\/kubernetes\/pkg\/api\/validation\"\n\t\"k8s.io\/kubernetes\/pkg\/runtime\"\n\t\"k8s.io\/kubernetes\/pkg\/util\/fielderrors\"\n)\n\nfunc TestCompatibility_v1_Pod(t *testing.T) {\n\t\/\/ Test \"spec.host\" -> \"spec.nodeName\"\n\texpectedHost := \"my-host\"\n\t\/\/ Test \"spec.serviceAccount\" -> \"spec.serviceAccountName\"\n\texpectedServiceAccount := \"my-service-account\"\n\t\/\/ Test \"tcp\" protocol gets converted to \"TCP\" and validated\n\toriginalProtocol := \"tcp\"\n\texpectedProtocol := \"TCP\"\n\n\tinput := []byte(fmt.Sprintf(`\n{\n\t\"kind\":\"Pod\",\n\t\"apiVersion\":\"v1\",\n\t\"metadata\":{\"name\":\"my-pod-name\", \"namespace\":\"my-pod-namespace\"},\n\t\"spec\": {\n\t\t\"host\":\"%s\",\n\t\t\"serviceAccount\":\"%s\",\n\t\t\"containers\":[{\n\t\t\t\"name\":\"my-container-name\",\n\t\t\t\"image\":\"my-container-image\",\n\t\t\t\"ports\":[{\"containerPort\":1,\"protocol\":\"%s\"}]\n\t\t}]\n\t}\n}\n`, expectedHost, expectedServiceAccount, originalProtocol))\n\n\tt.Log(\"Testing 1.0.0 v1 migration added in PR #3592\")\n\ttestCompatibility(\n\t\tt, \"v1\", input,\n\t\tfunc(obj runtime.Object) fielderrors.ValidationErrorList {\n\t\t\treturn validation.ValidatePod(obj.(*api.Pod))\n\t\t},\n\t\tmap[string]string{\n\t\t\t\"spec.host\": expectedHost,\n\t\t\t\"spec.nodeName\": expectedHost,\n\n\t\t\t\"spec.serviceAccount\": expectedServiceAccount,\n\t\t\t\"spec.serviceAccountName\": expectedServiceAccount,\n\n\t\t\t\"spec.containers[0].ports[0].protocol\": expectedProtocol,\n\t\t},\n\t)\n}\n\nfunc TestCompatibility_v1_Service(t *testing.T) {\n\t\/\/ Test \"spec.portalIP\" -> \"spec.clusterIP\"\n\texpectedIP := \"1.2.3.4\"\n\t\/\/ Test \"tcp\" protocol gets converted to \"TCP\" and validated\n\toriginalProtocol := \"tcp\"\n\texpectedProtocol := \"TCP\"\n\n\tinput := []byte(fmt.Sprintf(`\n{\n\t\"kind\":\"Service\",\n\t\"apiVersion\":\"v1\",\n\t\"metadata\":{\"name\":\"my-service-name\", \"namespace\":\"my-service-namespace\"},\n\t\"spec\": {\n\t\t\"portalIP\":\"%s\",\n\t\t\"ports\":[{\"port\":1,\"protocol\":\"%s\"}]\n\t}\n}\n`, expectedIP, originalProtocol))\n\n\tt.Log(\"Testing 1.0.0 v1 migration added in PR #3592\")\n\ttestCompatibility(\n\t\tt, \"v1\", input,\n\t\tfunc(obj runtime.Object) fielderrors.ValidationErrorList {\n\t\t\treturn validation.ValidateService(obj.(*api.Service))\n\t\t},\n\t\tmap[string]string{\n\t\t\t\"spec.portalIP\": expectedIP,\n\t\t\t\"spec.clusterIP\": expectedIP,\n\t\t\t\"spec.ports[0].protocol\": expectedProtocol,\n\t\t},\n\t)\n}\n\nfunc TestCompatibility_v1_Endpoints(t *testing.T) {\n\t\/\/ Test \"tcp\" protocol gets converted to \"TCP\" and validated\n\toriginalProtocol := \"tcp\"\n\texpectedProtocol := \"TCP\"\n\n\tinput := []byte(fmt.Sprintf(`\n{\n\t\"kind\":\"Endpoints\",\n\t\"apiVersion\":\"v1\",\n\t\"metadata\":{\"name\":\"my-endpoints-name\", \"namespace\":\"my-endpoints-namespace\"},\n\t\"subsets\": [{\n\t\t\"addresses\":[{\"ip\":\"1.2.3.4\"}],\n\t\t\"ports\": [{\"port\":1,\"targetPort\":1,\"protocol\":\"%s\"}]\n\t}]\n}\n`, originalProtocol))\n\n\tt.Log(\"Testing 1.0.0 v1 migration added in PR #3592\")\n\ttestCompatibility(\n\t\tt, \"v1\", input,\n\t\tfunc(obj runtime.Object) fielderrors.ValidationErrorList {\n\t\t\treturn validation.ValidateEndpoints(obj.(*api.Endpoints))\n\t\t},\n\t\tmap[string]string{\n\t\t\t\"subsets[0].ports[0].protocol\": expectedProtocol,\n\t\t},\n\t)\n}\n\nfunc testCompatibility(\n\tt *testing.T,\n\tversion string,\n\tinput []byte,\n\tvalidator func(obj runtime.Object) fielderrors.ValidationErrorList,\n\tserialized map[string]string,\n) {\n\n\t\/\/ Decode\n\tcodec := runtime.CodecFor(api.Scheme, version)\n\tobj, err := codec.Decode(input)\n\tif err != nil {\n\t\tt.Fatalf(\"Unexpected error: %v\", err)\n\t}\n\n\t\/\/ Validate\n\terrs := validator(obj)\n\tif len(errs) != 0 {\n\t\tt.Fatalf(\"Unexpected errors: %v\", errs)\n\t}\n\n\t\/\/ Encode\n\toutput, err := codec.Encode(obj)\n\tif err != nil {\n\t\tt.Fatalf(\"Unexpected error: %v\", err)\n\t}\n\n\t\/\/ Validate old and new fields are encoded\n\tgeneric := map[string]interface{}{}\n\tif err := json.Unmarshal(output, &generic); err != nil {\n\t\tt.Fatalf(\"Unexpected error: %v\", err)\n\t}\n\tfor k, expectedValue := range serialized {\n\t\tkeys := strings.Split(k, \".\")\n\t\tif actualValue, ok, err := getJSONValue(generic, keys...); err != nil || !ok {\n\t\t\tt.Errorf(\"Unexpected error for %s: %v\", k, err)\n\t\t} else if !reflect.DeepEqual(expectedValue, actualValue) {\n\t\t\tt.Errorf(\"Expected %v, got %v\", expectedValue, actualValue)\n\t\t}\n\t}\n}\n\nfunc getJSONValue(data map[string]interface{}, keys ...string) (interface{}, bool, error) {\n\t\/\/ No keys, current value is it\n\tif len(keys) == 0 {\n\t\treturn data, true, nil\n\t}\n\n\t\/\/ Get the key (and optional index)\n\tkey := keys[0]\n\tindex := -1\n\tif matches := regexp.MustCompile(`^(.*)\\[(\\d+)\\]$`).FindStringSubmatch(key); len(matches) > 0 {\n\t\tkey = matches[1]\n\t\tindex, _ = strconv.Atoi(matches[2])\n\t}\n\n\t\/\/ Look up the value\n\tvalue, ok := data[key]\n\tif !ok {\n\t\treturn nil, false, fmt.Errorf(\"No key %s found\", key)\n\t}\n\n\t\/\/ Get the indexed value if an index is specified\n\tif index >= 0 {\n\t\tvalueSlice, ok := value.([]interface{})\n\t\tif !ok {\n\t\t\treturn nil, false, fmt.Errorf(\"Key %s did not hold a slice\", key)\n\t\t}\n\t\tif index >= len(valueSlice) {\n\t\t\treturn nil, false, fmt.Errorf(\"Index %d out of bounds for slice at key: %v\", index, key)\n\t\t}\n\t\tvalue = valueSlice[index]\n\t}\n\n\tif len(keys) == 1 {\n\t\treturn value, true, nil\n\t}\n\n\tchildData, ok := value.(map[string]interface{})\n\tif !ok {\n\t\treturn nil, false, fmt.Errorf(\"Key %s did not hold a map\", keys[0])\n\t}\n\treturn getJSONValue(childData, keys[1:]...)\n}\nCompatibility test for Volume Sourcepackage api\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"k8s.io\/kubernetes\/pkg\/api\"\n\t\"k8s.io\/kubernetes\/pkg\/api\/validation\"\n\t\"k8s.io\/kubernetes\/pkg\/runtime\"\n\t\"k8s.io\/kubernetes\/pkg\/util\/fielderrors\"\n)\n\nfunc TestCompatibility_v1_Pod(t *testing.T) {\n\t\/\/ Test \"spec.host\" -> \"spec.nodeName\"\n\texpectedHost := \"my-host\"\n\t\/\/ Test \"spec.serviceAccount\" -> \"spec.serviceAccountName\"\n\texpectedServiceAccount := \"my-service-account\"\n\t\/\/ Test \"tcp\" protocol gets converted to \"TCP\" and validated\n\toriginalProtocol := \"tcp\"\n\texpectedProtocol := \"TCP\"\n\n\tinput := []byte(fmt.Sprintf(`\n{\n\t\"kind\":\"Pod\",\n\t\"apiVersion\":\"v1\",\n\t\"metadata\":{\"name\":\"my-pod-name\", \"namespace\":\"my-pod-namespace\"},\n\t\"spec\": {\n\t\t\"host\":\"%s\",\n\t\t\"serviceAccount\":\"%s\",\n\t\t\"containers\":[{\n\t\t\t\"name\":\"my-container-name\",\n\t\t\t\"image\":\"my-container-image\",\n\t\t\t\"ports\":[{\"containerPort\":1,\"protocol\":\"%s\"}]\n\t\t}]\n\t}\n}\n`, expectedHost, expectedServiceAccount, originalProtocol))\n\n\tt.Log(\"Testing 1.0.0 v1 migration added in PR #3592\")\n\ttestCompatibility(\n\t\tt, \"v1\", input,\n\t\tfunc(obj runtime.Object) fielderrors.ValidationErrorList {\n\t\t\treturn validation.ValidatePod(obj.(*api.Pod))\n\t\t},\n\t\tmap[string]string{\n\t\t\t\"spec.host\": expectedHost,\n\t\t\t\"spec.nodeName\": expectedHost,\n\n\t\t\t\"spec.serviceAccount\": expectedServiceAccount,\n\t\t\t\"spec.serviceAccountName\": expectedServiceAccount,\n\n\t\t\t\"spec.containers[0].ports[0].protocol\": expectedProtocol,\n\t\t},\n\t)\n}\n\n\/\/ TestCompatibility_v1_VolumeSource tests that the metadata field in volume\n\/\/ sources gets properly round-tripped\nfunc TestCompatibility_v1_VolumeSource(t *testing.T) {\n\t\/\/ Test volume source compatibility\n\tpath := \"test\/volume\/source\/compat\"\n\n\tmetadata := []byte(fmt.Sprintf(`\n{\n\t\"kind\":\"Pod\",\n\t\"apiVersion\":\"v1\",\n\t\"metadata\":{\"name\":\"my-pod-name\", \"namespace\":\"my-pod-namespace\"},\n\t\"spec\": {\n\t\t\"containers\":[{\n\t\t\t\"name\":\"my-container-name\",\n\t\t\t\"image\":\"my-container-image\",\n\t\t\t\"ports\":[{\"containerPort\":1,\"protocol\":\"TCP\"}]\n\t\t}],\n\t\t\"volumes\":[{\n\t\t\t\"name\":\"a-metadata-volume\",\n\t\t\t\"metadata\":{\"items\":[{\"name\":\"%s\",\"fieldRef\":{\"apiVersion\":\"v1\",\"fieldPath\":\"metadata.name\"}}]}\n\t\t}]\n\t}\n}\n`, path))\n\n\tdownward := []byte(fmt.Sprintf(`\n{\n\t\"kind\":\"Pod\",\n\t\"apiVersion\":\"v1\",\n\t\"metadata\":{\"name\":\"my-pod-name\", \"namespace\":\"my-pod-namespace\"},\n\t\"spec\": {\n\t\t\"containers\":[{\n\t\t\t\"name\":\"my-container-name\",\n\t\t\t\"image\":\"my-container-image\",\n\t\t\t\"ports\":[{\"containerPort\":1,\"protocol\":\"TCP\"}]\n\t\t}],\n\t\t\"volumes\":[{\n\t\t\t\"name\":\"a-downwardapi-volume\",\n\t\t\t\"downwardAPI\":{\"items\":[{\"path\":\"%s\",\"fieldRef\":{\"apiVersion\":\"v1\",\"fieldPath\":\"metadata.name\"}}]}\n\t\t}]\n\t}\n}\n`, path))\n\n\tt.Log(\"Testing 1.0.6 v1 migration added in PR #4663\")\n\ttestCompatibility(\n\t\tt, \"v1\", metadata,\n\t\tfunc(obj runtime.Object) fielderrors.ValidationErrorList {\n\t\t\treturn validation.ValidatePod(obj.(*api.Pod))\n\t\t},\n\t\tmap[string]string{\n\t\t\t\"spec.volumes[0].metadata.items[0].name\": path,\n\t\t\t\"spec.volumes[0].downwardAPI.items[0].path\": path,\n\t\t},\n\t)\n\ttestCompatibility(\n\t\tt, \"v1\", downward,\n\t\tfunc(obj runtime.Object) fielderrors.ValidationErrorList {\n\t\t\treturn validation.ValidatePod(obj.(*api.Pod))\n\t\t},\n\t\tmap[string]string{\n\t\t\t\"spec.volumes[0].metadata.items[0].name\": path,\n\t\t\t\"spec.volumes[0].downwardAPI.items[0].path\": path,\n\t\t},\n\t)\n}\n\nfunc TestCompatibility_v1_Service(t *testing.T) {\n\t\/\/ Test \"spec.portalIP\" -> \"spec.clusterIP\"\n\texpectedIP := \"1.2.3.4\"\n\t\/\/ Test \"tcp\" protocol gets converted to \"TCP\" and validated\n\toriginalProtocol := \"tcp\"\n\texpectedProtocol := \"TCP\"\n\n\tinput := []byte(fmt.Sprintf(`\n{\n\t\"kind\":\"Service\",\n\t\"apiVersion\":\"v1\",\n\t\"metadata\":{\"name\":\"my-service-name\", \"namespace\":\"my-service-namespace\"},\n\t\"spec\": {\n\t\t\"portalIP\":\"%s\",\n\t\t\"ports\":[{\"port\":1,\"protocol\":\"%s\"}]\n\t}\n}\n`, expectedIP, originalProtocol))\n\n\tt.Log(\"Testing 1.0.0 v1 migration added in PR #3592\")\n\ttestCompatibility(\n\t\tt, \"v1\", input,\n\t\tfunc(obj runtime.Object) fielderrors.ValidationErrorList {\n\t\t\treturn validation.ValidateService(obj.(*api.Service))\n\t\t},\n\t\tmap[string]string{\n\t\t\t\"spec.portalIP\": expectedIP,\n\t\t\t\"spec.clusterIP\": expectedIP,\n\t\t\t\"spec.ports[0].protocol\": expectedProtocol,\n\t\t},\n\t)\n}\n\nfunc TestCompatibility_v1_Endpoints(t *testing.T) {\n\t\/\/ Test \"tcp\" protocol gets converted to \"TCP\" and validated\n\toriginalProtocol := \"tcp\"\n\texpectedProtocol := \"TCP\"\n\n\tinput := []byte(fmt.Sprintf(`\n{\n\t\"kind\":\"Endpoints\",\n\t\"apiVersion\":\"v1\",\n\t\"metadata\":{\"name\":\"my-endpoints-name\", \"namespace\":\"my-endpoints-namespace\"},\n\t\"subsets\": [{\n\t\t\"addresses\":[{\"ip\":\"1.2.3.4\"}],\n\t\t\"ports\": [{\"port\":1,\"targetPort\":1,\"protocol\":\"%s\"}]\n\t}]\n}\n`, originalProtocol))\n\n\tt.Log(\"Testing 1.0.0 v1 migration added in PR #3592\")\n\ttestCompatibility(\n\t\tt, \"v1\", input,\n\t\tfunc(obj runtime.Object) fielderrors.ValidationErrorList {\n\t\t\treturn validation.ValidateEndpoints(obj.(*api.Endpoints))\n\t\t},\n\t\tmap[string]string{\n\t\t\t\"subsets[0].ports[0].protocol\": expectedProtocol,\n\t\t},\n\t)\n}\n\nfunc testCompatibility(\n\tt *testing.T,\n\tversion string,\n\tinput []byte,\n\tvalidator func(obj runtime.Object) fielderrors.ValidationErrorList,\n\tserialized map[string]string,\n) {\n\n\t\/\/ Decode\n\tcodec := runtime.CodecFor(api.Scheme, version)\n\tobj, err := codec.Decode(input)\n\tif err != nil {\n\t\tt.Fatalf(\"Unexpected error: %v\", err)\n\t}\n\n\t\/\/ Validate\n\terrs := validator(obj)\n\tif len(errs) != 0 {\n\t\tt.Fatalf(\"Unexpected errors: %v\", errs)\n\t}\n\n\t\/\/ Encode\n\toutput, err := codec.Encode(obj)\n\tif err != nil {\n\t\tt.Fatalf(\"Unexpected error: %v\", err)\n\t}\n\n\t\/\/ Validate old and new fields are encoded\n\tgeneric := map[string]interface{}{}\n\tif err := json.Unmarshal(output, &generic); err != nil {\n\t\tt.Fatalf(\"Unexpected error: %v\", err)\n\t}\n\tfor k, expectedValue := range serialized {\n\t\tkeys := strings.Split(k, \".\")\n\t\tif actualValue, ok, err := getJSONValue(generic, keys...); err != nil || !ok {\n\t\t\tt.Errorf(\"Unexpected error for %s: %v\", k, err)\n\t\t} else if !reflect.DeepEqual(expectedValue, actualValue) {\n\t\t\tt.Errorf(\"Expected %v, got %v\", expectedValue, actualValue)\n\t\t}\n\t}\n}\n\nfunc getJSONValue(data map[string]interface{}, keys ...string) (interface{}, bool, error) {\n\t\/\/ No keys, current value is it\n\tif len(keys) == 0 {\n\t\treturn data, true, nil\n\t}\n\n\t\/\/ Get the key (and optional index)\n\tkey := keys[0]\n\tindex := -1\n\tif matches := regexp.MustCompile(`^(.*)\\[(\\d+)\\]$`).FindStringSubmatch(key); len(matches) > 0 {\n\t\tkey = matches[1]\n\t\tindex, _ = strconv.Atoi(matches[2])\n\t}\n\n\t\/\/ Look up the value\n\tvalue, ok := data[key]\n\tif !ok {\n\t\treturn nil, false, fmt.Errorf(\"No key %s found\", key)\n\t}\n\n\t\/\/ Get the indexed value if an index is specified\n\tif index >= 0 {\n\t\tvalueSlice, ok := value.([]interface{})\n\t\tif !ok {\n\t\t\treturn nil, false, fmt.Errorf(\"Key %s did not hold a slice\", key)\n\t\t}\n\t\tif index >= len(valueSlice) {\n\t\t\treturn nil, false, fmt.Errorf(\"Index %d out of bounds for slice at key: %v\", index, key)\n\t\t}\n\t\tvalue = valueSlice[index]\n\t}\n\n\tif len(keys) == 1 {\n\t\treturn value, true, nil\n\t}\n\n\tchildData, ok := value.(map[string]interface{})\n\tif !ok {\n\t\treturn nil, false, fmt.Errorf(\"Key %s did not hold a map\", keys[0])\n\t}\n\treturn getJSONValue(childData, keys[1:]...)\n}\n<|endoftext|>"} {"text":"\/*\nCopyright 2017 the Velero contributors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage restore\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n\t\"time\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/spf13\/pflag\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/client-go\/tools\/cache\"\n\n\tapi \"github.com\/vmware-tanzu\/velero\/pkg\/apis\/velero\/v1\"\n\t\"github.com\/vmware-tanzu\/velero\/pkg\/client\"\n\t\"github.com\/vmware-tanzu\/velero\/pkg\/cmd\"\n\t\"github.com\/vmware-tanzu\/velero\/pkg\/cmd\/util\/flag\"\n\t\"github.com\/vmware-tanzu\/velero\/pkg\/cmd\/util\/output\"\n\tveleroclient \"github.com\/vmware-tanzu\/velero\/pkg\/generated\/clientset\/versioned\"\n\tv1 \"github.com\/vmware-tanzu\/velero\/pkg\/generated\/informers\/externalversions\/velero\/v1\"\n\t\"github.com\/vmware-tanzu\/velero\/pkg\/util\/boolptr\"\n)\n\nfunc NewCreateCommand(f client.Factory, use string) *cobra.Command {\n\to := NewCreateOptions()\n\n\tc := &cobra.Command{\n\t\tUse: use + \" [RESTORE_NAME] [--from-backup BACKUP_NAME | --from-schedule SCHEDULE_NAME]\",\n\t\tShort: \"Create a restore\",\n\t\tExample: ` # create a restore named \"restore-1\" from backup \"backup-1\"\n velero restore create restore-1 --from-backup backup-1\n\n # create a restore with a default name (\"backup-1-\") from backup \"backup-1\"\n velero restore create --from-backup backup-1\n \n # create a restore from the latest successful backup triggered by schedule \"schedule-1\"\n velero restore create --from-schedule schedule-1\n\n # create a restore from the latest successful OR partially-failed backup triggered by schedule \"schedule-1\"\n velero restore create --from-schedule schedule-1 --allow-partially-failed\n\n # create a restore for only persistentvolumeclaims and persistentvolumes within a backup\n velero restore create --from-backup backup-2 --include-resources persistentvolumeclaims,persistentvolumes\n `,\n\t\tArgs: cobra.MaximumNArgs(1),\n\t\tRun: func(c *cobra.Command, args []string) {\n\t\t\tcmd.CheckError(o.Complete(args, f))\n\t\t\tcmd.CheckError(o.Validate(c, args, f))\n\t\t\tcmd.CheckError(o.Run(c, f))\n\t\t},\n\t}\n\n\to.BindFlags(c.Flags())\n\toutput.BindFlags(c.Flags())\n\toutput.ClearOutputFlagDefault(c)\n\n\treturn c\n}\n\ntype CreateOptions struct {\n\tBackupName string\n\tScheduleName string\n\tRestoreName string\n\tRestoreVolumes flag.OptionalBool\n\tLabels flag.Map\n\tIncludeNamespaces flag.StringArray\n\tExcludeNamespaces flag.StringArray\n\tIncludeResources flag.StringArray\n\tExcludeResources flag.StringArray\n\tNamespaceMappings flag.Map\n\tSelector flag.LabelSelector\n\tIncludeClusterResources flag.OptionalBool\n\tWait bool\n\tAllowPartiallyFailed flag.OptionalBool\n\n\tclient veleroclient.Interface\n}\n\nfunc NewCreateOptions() *CreateOptions {\n\treturn &CreateOptions{\n\t\tLabels: flag.NewMap(),\n\t\tIncludeNamespaces: flag.NewStringArray(\"*\"),\n\t\tNamespaceMappings: flag.NewMap().WithEntryDelimiter(\",\").WithKeyValueDelimiter(\":\"),\n\t\tRestoreVolumes: flag.NewOptionalBool(nil),\n\t\tIncludeClusterResources: flag.NewOptionalBool(nil),\n\t}\n}\n\nfunc (o *CreateOptions) BindFlags(flags *pflag.FlagSet) {\n\tflags.StringVar(&o.BackupName, \"from-backup\", \"\", \"backup to restore from\")\n\tflags.StringVar(&o.ScheduleName, \"from-schedule\", \"\", \"schedule to restore from\")\n\tflags.Var(&o.IncludeNamespaces, \"include-namespaces\", \"namespaces to include in the restore (use '*' for all namespaces)\")\n\tflags.Var(&o.ExcludeNamespaces, \"exclude-namespaces\", \"namespaces to exclude from the restore\")\n\tflags.Var(&o.NamespaceMappings, \"namespace-mappings\", \"namespace mappings from name in the backup to desired restored name in the form src1:dst1,src2:dst2,...\")\n\tflags.Var(&o.Labels, \"labels\", \"labels to apply to the restore\")\n\tflags.Var(&o.IncludeResources, \"include-resources\", \"resources to include in the restore, formatted as resource.group, such as storageclasses.storage.k8s.io (use '*' for all resources)\")\n\tflags.Var(&o.ExcludeResources, \"exclude-resources\", \"resources to exclude from the restore, formatted as resource.group, such as storageclasses.storage.k8s.io\")\n\tflags.VarP(&o.Selector, \"selector\", \"l\", \"only restore resources matching this label selector\")\n\tf := flags.VarPF(&o.RestoreVolumes, \"restore-volumes\", \"\", \"whether to restore volumes from snapshots\")\n\t\/\/ this allows the user to just specify \"--restore-volumes\" as shorthand for \"--restore-volumes=true\"\n\t\/\/ like a normal bool flag\n\tf.NoOptDefVal = \"true\"\n\n\tf = flags.VarPF(&o.IncludeClusterResources, \"include-cluster-resources\", \"\", \"include cluster-scoped resources in the restore\")\n\tf.NoOptDefVal = \"true\"\n\n\tf = flags.VarPF(&o.AllowPartiallyFailed, \"allow-partially-failed\", \"\", \"if using --from-schedule, whether to consider PartiallyFailed backups when looking for the most recent one. This flag has no effect if not using --from-schedule.\")\n\tf.NoOptDefVal = \"true\"\n\n\tflags.BoolVarP(&o.Wait, \"wait\", \"w\", o.Wait, \"wait for the operation to complete\")\n}\n\nfunc (o *CreateOptions) Complete(args []string, f client.Factory) error {\n\tif len(args) == 1 {\n\t\to.RestoreName = args[0]\n\t} else {\n\t\tsourceName := o.BackupName\n\t\tif o.ScheduleName != \"\" {\n\t\t\tsourceName = o.ScheduleName\n\t\t}\n\n\t\to.RestoreName = fmt.Sprintf(\"%s-%s\", sourceName, time.Now().Format(\"20060102150405\"))\n\t}\n\n\tclient, err := f.Client()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.client = client\n\n\treturn nil\n}\n\nfunc (o *CreateOptions) Validate(c *cobra.Command, args []string, f client.Factory) error {\n\tif o.BackupName != \"\" && o.ScheduleName != \"\" {\n\t\treturn errors.New(\"either a backup or schedule must be specified, but not both\")\n\t}\n\n\tif o.BackupName == \"\" && o.ScheduleName == \"\" {\n\t\treturn errors.New(\"either a backup or schedule must be specified, but not both\")\n\t}\n\n\tif err := output.ValidateFlags(c); err != nil {\n\t\treturn err\n\t}\n\n\tif o.client == nil {\n\t\t\/\/ This should never happen\n\t\treturn errors.New(\"Velero client is not set; unable to proceed\")\n\t}\n\n\tswitch {\n\tcase o.BackupName != \"\":\n\t\tif _, err := o.client.VeleroV1().Backups(f.Namespace()).Get(o.BackupName, metav1.GetOptions{}); err != nil {\n\t\t\treturn err\n\t\t}\n\tcase o.ScheduleName != \"\":\n\t\tif _, err := o.client.VeleroV1().Schedules(f.Namespace()).Get(o.ScheduleName, metav1.GetOptions{}); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ mostRecentBackup returns the backup with the most recent start timestamp that has a phase that's\n\/\/ in the provided list of allowed phases.\nfunc mostRecentBackup(backups []api.Backup, allowedPhases ...api.BackupPhase) *api.Backup {\n\t\/\/ sort the backups in descending order of start time (i.e. most recent to least recent)\n\tsort.Slice(backups, func(i, j int) bool {\n\t\t\/\/ Use .After() because we want descending sort.\n\n\t\tvar iStartTime, jStartTime time.Time\n\t\tif backups[i].Status.StartTimestamp != nil {\n\t\t\tiStartTime = backups[i].Status.StartTimestamp.Time\n\t\t}\n\t\tif backups[j].Status.StartTimestamp != nil {\n\t\t\tjStartTime = backups[j].Status.StartTimestamp.Time\n\t\t}\n\t\treturn iStartTime.After(jStartTime)\n\t})\n\n\t\/\/ create a map of the allowed phases for easy lookup below\n\tphases := map[api.BackupPhase]struct{}{}\n\tfor _, phase := range allowedPhases {\n\t\tphases[phase] = struct{}{}\n\t}\n\n\tvar res *api.Backup\n\tfor i, backup := range backups {\n\t\t\/\/ if the backup's phase is one of the allowable ones, record\n\t\t\/\/ the backup and break the loop so we can return it\n\t\tif _, ok := phases[backup.Status.Phase]; ok {\n\t\t\tres = &backups[i]\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn res\n}\n\nfunc (o *CreateOptions) Run(c *cobra.Command, f client.Factory) error {\n\tif o.client == nil {\n\t\t\/\/ This should never happen\n\t\treturn errors.New(\"Velero client is not set; unable to proceed\")\n\t}\n\n\t\/\/ if --allow-partially-failed was specified, look up the most recent Completed or\n\t\/\/ PartiallyFailed backup for the provided schedule, and use that specific backup\n\t\/\/ to restore from.\n\tif o.ScheduleName != \"\" && boolptr.IsSetToTrue(o.AllowPartiallyFailed.Value) {\n\t\tbackups, err := o.client.VeleroV1().Backups(f.Namespace()).List(metav1.ListOptions{LabelSelector: fmt.Sprintf(\"%s=%s\", api.ScheduleNameLabel, o.ScheduleName)})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ if we find a Completed or PartiallyFailed backup for the schedule, restore specifically from that backup. If we don't\n\t\t\/\/ find one, proceed as-is -- the Velero server will handle validation.\n\t\tif backup := mostRecentBackup(backups.Items, api.BackupPhaseCompleted, api.BackupPhasePartiallyFailed); backup != nil {\n\t\t\t\/\/ TODO(sk): this is kind of a hack -- we should revisit this and probably\n\t\t\t\/\/ move this logic to the server side or otherwise solve this problem.\n\t\t\to.BackupName = backup.Name\n\t\t\to.ScheduleName = \"\"\n\t\t}\n\t}\n\n\trestore := &api.Restore{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tNamespace: f.Namespace(),\n\t\t\tName: o.RestoreName,\n\t\t\tLabels: o.Labels.Data(),\n\t\t},\n\t\tSpec: api.RestoreSpec{\n\t\t\tBackupName: o.BackupName,\n\t\t\tScheduleName: o.ScheduleName,\n\t\t\tIncludedNamespaces: o.IncludeNamespaces,\n\t\t\tExcludedNamespaces: o.ExcludeNamespaces,\n\t\t\tIncludedResources: o.IncludeResources,\n\t\t\tExcludedResources: o.ExcludeResources,\n\t\t\tNamespaceMapping: o.NamespaceMappings.Data(),\n\t\t\tLabelSelector: o.Selector.LabelSelector,\n\t\t\tRestorePVs: o.RestoreVolumes.Value,\n\t\t\tIncludeClusterResources: o.IncludeClusterResources.Value,\n\t\t},\n\t}\n\n\tif printed, err := output.PrintWithFormat(c, restore); printed || err != nil {\n\t\treturn err\n\t}\n\n\tvar restoreInformer cache.SharedIndexInformer\n\tvar updates chan *api.Restore\n\tif o.Wait {\n\t\tstop := make(chan struct{})\n\t\tdefer close(stop)\n\n\t\tupdates = make(chan *api.Restore)\n\n\t\trestoreInformer = v1.NewRestoreInformer(o.client, f.Namespace(), 0, nil)\n\n\t\trestoreInformer.AddEventHandler(\n\t\t\tcache.FilteringResourceEventHandler{\n\t\t\t\tFilterFunc: func(obj interface{}) bool {\n\t\t\t\t\trestore, ok := obj.(*api.Restore)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t\treturn restore.Name == o.RestoreName\n\t\t\t\t},\n\t\t\t\tHandler: cache.ResourceEventHandlerFuncs{\n\t\t\t\t\tUpdateFunc: func(_, obj interface{}) {\n\t\t\t\t\t\trestore, ok := obj.(*api.Restore)\n\t\t\t\t\t\tif !ok {\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\tupdates <- restore\n\t\t\t\t\t},\n\t\t\t\t\tDeleteFunc: func(obj interface{}) {\n\t\t\t\t\t\trestore, ok := obj.(*api.Restore)\n\t\t\t\t\t\tif !ok {\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\tupdates <- restore\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t)\n\t\tgo restoreInformer.Run(stop)\n\t}\n\n\trestore, err := o.client.VeleroV1().Restores(restore.Namespace).Create(restore)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"Restore request %q submitted successfully.\\n\", restore.Name)\n\tif o.Wait {\n\t\tfmt.Println(\"Waiting for restore to complete. You may safely press ctrl-c to stop waiting - your restore will continue in the background.\")\n\t\tticker := time.NewTicker(time.Second)\n\t\tdefer ticker.Stop()\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ticker.C:\n\t\t\t\tfmt.Print(\".\")\n\t\t\tcase restore, ok := <-updates:\n\t\t\t\tif !ok {\n\t\t\t\t\tfmt.Println(\"\\nError waiting: unable to watch restores.\")\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\tif restore.Status.Phase != api.RestorePhaseNew && restore.Status.Phase != api.RestorePhaseInProgress {\n\t\t\t\t\tfmt.Printf(\"\\nRestore completed with status: %s. You may check for more information using the commands `velero restore describe %s` and `velero restore logs %s`.\\n\", restore.Status.Phase, restore.Name, restore.Name)\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Not waiting\n\n\tfmt.Printf(\"Run `velero restore describe %s` or `velero restore logs %s` for more details.\\n\", restore.Name, restore.Name)\n\n\treturn nil\n}\nremove schedule validation\/*\nCopyright 2017 the Velero contributors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage restore\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n\t\"time\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/spf13\/cobra\"\n\t\"github.com\/spf13\/pflag\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/client-go\/tools\/cache\"\n\n\tapi \"github.com\/vmware-tanzu\/velero\/pkg\/apis\/velero\/v1\"\n\t\"github.com\/vmware-tanzu\/velero\/pkg\/client\"\n\t\"github.com\/vmware-tanzu\/velero\/pkg\/cmd\"\n\t\"github.com\/vmware-tanzu\/velero\/pkg\/cmd\/util\/flag\"\n\t\"github.com\/vmware-tanzu\/velero\/pkg\/cmd\/util\/output\"\n\tveleroclient \"github.com\/vmware-tanzu\/velero\/pkg\/generated\/clientset\/versioned\"\n\tv1 \"github.com\/vmware-tanzu\/velero\/pkg\/generated\/informers\/externalversions\/velero\/v1\"\n\t\"github.com\/vmware-tanzu\/velero\/pkg\/util\/boolptr\"\n)\n\nfunc NewCreateCommand(f client.Factory, use string) *cobra.Command {\n\to := NewCreateOptions()\n\n\tc := &cobra.Command{\n\t\tUse: use + \" [RESTORE_NAME] [--from-backup BACKUP_NAME | --from-schedule SCHEDULE_NAME]\",\n\t\tShort: \"Create a restore\",\n\t\tExample: ` # create a restore named \"restore-1\" from backup \"backup-1\"\n velero restore create restore-1 --from-backup backup-1\n\n # create a restore with a default name (\"backup-1-\") from backup \"backup-1\"\n velero restore create --from-backup backup-1\n \n # create a restore from the latest successful backup triggered by schedule \"schedule-1\"\n velero restore create --from-schedule schedule-1\n\n # create a restore from the latest successful OR partially-failed backup triggered by schedule \"schedule-1\"\n velero restore create --from-schedule schedule-1 --allow-partially-failed\n\n # create a restore for only persistentvolumeclaims and persistentvolumes within a backup\n velero restore create --from-backup backup-2 --include-resources persistentvolumeclaims,persistentvolumes\n `,\n\t\tArgs: cobra.MaximumNArgs(1),\n\t\tRun: func(c *cobra.Command, args []string) {\n\t\t\tcmd.CheckError(o.Complete(args, f))\n\t\t\tcmd.CheckError(o.Validate(c, args, f))\n\t\t\tcmd.CheckError(o.Run(c, f))\n\t\t},\n\t}\n\n\to.BindFlags(c.Flags())\n\toutput.BindFlags(c.Flags())\n\toutput.ClearOutputFlagDefault(c)\n\n\treturn c\n}\n\ntype CreateOptions struct {\n\tBackupName string\n\tScheduleName string\n\tRestoreName string\n\tRestoreVolumes flag.OptionalBool\n\tLabels flag.Map\n\tIncludeNamespaces flag.StringArray\n\tExcludeNamespaces flag.StringArray\n\tIncludeResources flag.StringArray\n\tExcludeResources flag.StringArray\n\tNamespaceMappings flag.Map\n\tSelector flag.LabelSelector\n\tIncludeClusterResources flag.OptionalBool\n\tWait bool\n\tAllowPartiallyFailed flag.OptionalBool\n\n\tclient veleroclient.Interface\n}\n\nfunc NewCreateOptions() *CreateOptions {\n\treturn &CreateOptions{\n\t\tLabels: flag.NewMap(),\n\t\tIncludeNamespaces: flag.NewStringArray(\"*\"),\n\t\tNamespaceMappings: flag.NewMap().WithEntryDelimiter(\",\").WithKeyValueDelimiter(\":\"),\n\t\tRestoreVolumes: flag.NewOptionalBool(nil),\n\t\tIncludeClusterResources: flag.NewOptionalBool(nil),\n\t}\n}\n\nfunc (o *CreateOptions) BindFlags(flags *pflag.FlagSet) {\n\tflags.StringVar(&o.BackupName, \"from-backup\", \"\", \"backup to restore from\")\n\tflags.StringVar(&o.ScheduleName, \"from-schedule\", \"\", \"schedule to restore from\")\n\tflags.Var(&o.IncludeNamespaces, \"include-namespaces\", \"namespaces to include in the restore (use '*' for all namespaces)\")\n\tflags.Var(&o.ExcludeNamespaces, \"exclude-namespaces\", \"namespaces to exclude from the restore\")\n\tflags.Var(&o.NamespaceMappings, \"namespace-mappings\", \"namespace mappings from name in the backup to desired restored name in the form src1:dst1,src2:dst2,...\")\n\tflags.Var(&o.Labels, \"labels\", \"labels to apply to the restore\")\n\tflags.Var(&o.IncludeResources, \"include-resources\", \"resources to include in the restore, formatted as resource.group, such as storageclasses.storage.k8s.io (use '*' for all resources)\")\n\tflags.Var(&o.ExcludeResources, \"exclude-resources\", \"resources to exclude from the restore, formatted as resource.group, such as storageclasses.storage.k8s.io\")\n\tflags.VarP(&o.Selector, \"selector\", \"l\", \"only restore resources matching this label selector\")\n\tf := flags.VarPF(&o.RestoreVolumes, \"restore-volumes\", \"\", \"whether to restore volumes from snapshots\")\n\t\/\/ this allows the user to just specify \"--restore-volumes\" as shorthand for \"--restore-volumes=true\"\n\t\/\/ like a normal bool flag\n\tf.NoOptDefVal = \"true\"\n\n\tf = flags.VarPF(&o.IncludeClusterResources, \"include-cluster-resources\", \"\", \"include cluster-scoped resources in the restore\")\n\tf.NoOptDefVal = \"true\"\n\n\tf = flags.VarPF(&o.AllowPartiallyFailed, \"allow-partially-failed\", \"\", \"if using --from-schedule, whether to consider PartiallyFailed backups when looking for the most recent one. This flag has no effect if not using --from-schedule.\")\n\tf.NoOptDefVal = \"true\"\n\n\tflags.BoolVarP(&o.Wait, \"wait\", \"w\", o.Wait, \"wait for the operation to complete\")\n}\n\nfunc (o *CreateOptions) Complete(args []string, f client.Factory) error {\n\tif len(args) == 1 {\n\t\to.RestoreName = args[0]\n\t} else {\n\t\tsourceName := o.BackupName\n\t\tif o.ScheduleName != \"\" {\n\t\t\tsourceName = o.ScheduleName\n\t\t}\n\n\t\to.RestoreName = fmt.Sprintf(\"%s-%s\", sourceName, time.Now().Format(\"20060102150405\"))\n\t}\n\n\tclient, err := f.Client()\n\tif err != nil {\n\t\treturn err\n\t}\n\to.client = client\n\n\treturn nil\n}\n\nfunc (o *CreateOptions) Validate(c *cobra.Command, args []string, f client.Factory) error {\n\tif o.BackupName != \"\" && o.ScheduleName != \"\" {\n\t\treturn errors.New(\"either a backup or schedule must be specified, but not both\")\n\t}\n\n\tif o.BackupName == \"\" && o.ScheduleName == \"\" {\n\t\treturn errors.New(\"either a backup or schedule must be specified, but not both\")\n\t}\n\n\tif err := output.ValidateFlags(c); err != nil {\n\t\treturn err\n\t}\n\n\tif o.client == nil {\n\t\t\/\/ This should never happen\n\t\treturn errors.New(\"Velero client is not set; unable to proceed\")\n\t}\n\n\tif o.BackupName != \"\" {\n\t\tif _, err := o.client.VeleroV1().Backups(f.Namespace()).Get(o.BackupName, metav1.GetOptions{}); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n\/\/ mostRecentBackup returns the backup with the most recent start timestamp that has a phase that's\n\/\/ in the provided list of allowed phases.\nfunc mostRecentBackup(backups []api.Backup, allowedPhases ...api.BackupPhase) *api.Backup {\n\t\/\/ sort the backups in descending order of start time (i.e. most recent to least recent)\n\tsort.Slice(backups, func(i, j int) bool {\n\t\t\/\/ Use .After() because we want descending sort.\n\n\t\tvar iStartTime, jStartTime time.Time\n\t\tif backups[i].Status.StartTimestamp != nil {\n\t\t\tiStartTime = backups[i].Status.StartTimestamp.Time\n\t\t}\n\t\tif backups[j].Status.StartTimestamp != nil {\n\t\t\tjStartTime = backups[j].Status.StartTimestamp.Time\n\t\t}\n\t\treturn iStartTime.After(jStartTime)\n\t})\n\n\t\/\/ create a map of the allowed phases for easy lookup below\n\tphases := map[api.BackupPhase]struct{}{}\n\tfor _, phase := range allowedPhases {\n\t\tphases[phase] = struct{}{}\n\t}\n\n\tvar res *api.Backup\n\tfor i, backup := range backups {\n\t\t\/\/ if the backup's phase is one of the allowable ones, record\n\t\t\/\/ the backup and break the loop so we can return it\n\t\tif _, ok := phases[backup.Status.Phase]; ok {\n\t\t\tres = &backups[i]\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn res\n}\n\nfunc (o *CreateOptions) Run(c *cobra.Command, f client.Factory) error {\n\tif o.client == nil {\n\t\t\/\/ This should never happen\n\t\treturn errors.New(\"Velero client is not set; unable to proceed\")\n\t}\n\n\t\/\/ if --allow-partially-failed was specified, look up the most recent Completed or\n\t\/\/ PartiallyFailed backup for the provided schedule, and use that specific backup\n\t\/\/ to restore from.\n\tif o.ScheduleName != \"\" && boolptr.IsSetToTrue(o.AllowPartiallyFailed.Value) {\n\t\tbackups, err := o.client.VeleroV1().Backups(f.Namespace()).List(metav1.ListOptions{LabelSelector: fmt.Sprintf(\"%s=%s\", api.ScheduleNameLabel, o.ScheduleName)})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t\/\/ if we find a Completed or PartiallyFailed backup for the schedule, restore specifically from that backup. If we don't\n\t\t\/\/ find one, proceed as-is -- the Velero server will handle validation.\n\t\tif backup := mostRecentBackup(backups.Items, api.BackupPhaseCompleted, api.BackupPhasePartiallyFailed); backup != nil {\n\t\t\t\/\/ TODO(sk): this is kind of a hack -- we should revisit this and probably\n\t\t\t\/\/ move this logic to the server side or otherwise solve this problem.\n\t\t\to.BackupName = backup.Name\n\t\t\to.ScheduleName = \"\"\n\t\t}\n\t}\n\n\trestore := &api.Restore{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tNamespace: f.Namespace(),\n\t\t\tName: o.RestoreName,\n\t\t\tLabels: o.Labels.Data(),\n\t\t},\n\t\tSpec: api.RestoreSpec{\n\t\t\tBackupName: o.BackupName,\n\t\t\tScheduleName: o.ScheduleName,\n\t\t\tIncludedNamespaces: o.IncludeNamespaces,\n\t\t\tExcludedNamespaces: o.ExcludeNamespaces,\n\t\t\tIncludedResources: o.IncludeResources,\n\t\t\tExcludedResources: o.ExcludeResources,\n\t\t\tNamespaceMapping: o.NamespaceMappings.Data(),\n\t\t\tLabelSelector: o.Selector.LabelSelector,\n\t\t\tRestorePVs: o.RestoreVolumes.Value,\n\t\t\tIncludeClusterResources: o.IncludeClusterResources.Value,\n\t\t},\n\t}\n\n\tif printed, err := output.PrintWithFormat(c, restore); printed || err != nil {\n\t\treturn err\n\t}\n\n\tvar restoreInformer cache.SharedIndexInformer\n\tvar updates chan *api.Restore\n\tif o.Wait {\n\t\tstop := make(chan struct{})\n\t\tdefer close(stop)\n\n\t\tupdates = make(chan *api.Restore)\n\n\t\trestoreInformer = v1.NewRestoreInformer(o.client, f.Namespace(), 0, nil)\n\n\t\trestoreInformer.AddEventHandler(\n\t\t\tcache.FilteringResourceEventHandler{\n\t\t\t\tFilterFunc: func(obj interface{}) bool {\n\t\t\t\t\trestore, ok := obj.(*api.Restore)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t\treturn restore.Name == o.RestoreName\n\t\t\t\t},\n\t\t\t\tHandler: cache.ResourceEventHandlerFuncs{\n\t\t\t\t\tUpdateFunc: func(_, obj interface{}) {\n\t\t\t\t\t\trestore, ok := obj.(*api.Restore)\n\t\t\t\t\t\tif !ok {\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\tupdates <- restore\n\t\t\t\t\t},\n\t\t\t\t\tDeleteFunc: func(obj interface{}) {\n\t\t\t\t\t\trestore, ok := obj.(*api.Restore)\n\t\t\t\t\t\tif !ok {\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\tupdates <- restore\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t)\n\t\tgo restoreInformer.Run(stop)\n\t}\n\n\trestore, err := o.client.VeleroV1().Restores(restore.Namespace).Create(restore)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"Restore request %q submitted successfully.\\n\", restore.Name)\n\tif o.Wait {\n\t\tfmt.Println(\"Waiting for restore to complete. You may safely press ctrl-c to stop waiting - your restore will continue in the background.\")\n\t\tticker := time.NewTicker(time.Second)\n\t\tdefer ticker.Stop()\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ticker.C:\n\t\t\t\tfmt.Print(\".\")\n\t\t\tcase restore, ok := <-updates:\n\t\t\t\tif !ok {\n\t\t\t\t\tfmt.Println(\"\\nError waiting: unable to watch restores.\")\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\n\t\t\t\tif restore.Status.Phase != api.RestorePhaseNew && restore.Status.Phase != api.RestorePhaseInProgress {\n\t\t\t\t\tfmt.Printf(\"\\nRestore completed with status: %s. You may check for more information using the commands `velero restore describe %s` and `velero restore logs %s`.\\n\", restore.Status.Phase, restore.Name, restore.Name)\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Not waiting\n\n\tfmt.Printf(\"Run `velero restore describe %s` or `velero restore logs %s` for more details.\\n\", restore.Name, restore.Name)\n\n\treturn nil\n}\n<|endoftext|>"} {"text":"\/*\nCopyright 2020 The Rook Authors. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n\thttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage osd\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"time\"\n\n\tkerrors \"k8s.io\/apimachinery\/pkg\/api\/errors\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/rook\/rook\/pkg\/clusterd\"\n\t\"github.com\/rook\/rook\/pkg\/daemon\/ceph\/client\"\n\t\"github.com\/rook\/rook\/pkg\/operator\/ceph\/cluster\/osd\"\n\t\"github.com\/rook\/rook\/pkg\/operator\/k8sutil\"\n)\n\n\/\/ RemoveOSDs purges a list of OSDs from the cluster\nfunc RemoveOSDs(context *clusterd.Context, clusterInfo *client.ClusterInfo, osdsToRemove []string, preservePVC, forceOSDRemoval bool) error {\n\t\/\/ Generate the ceph config for running ceph commands similar to the operator\n\tif err := client.WriteCephConfig(context, clusterInfo); err != nil {\n\t\treturn errors.Wrap(err, \"failed to write the ceph config\")\n\t}\n\n\tosdDump, err := client.GetOSDDump(context, clusterInfo)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to get osd dump\")\n\t}\n\n\tfor _, osdIDStr := range osdsToRemove {\n\t\tosdID, err := strconv.Atoi(osdIDStr)\n\t\tif err != nil {\n\t\t\tlogger.Errorf(\"invalid OSD ID: %s. %v\", osdIDStr, err)\n\t\t\tcontinue\n\t\t}\n\t\tlogger.Infof(\"validating status of osd.%d\", osdID)\n\t\tstatus, _, err := osdDump.StatusByID(int64(osdID))\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed to get osd status for osd %d\", osdID)\n\t\t}\n\t\tconst upStatus int64 = 1\n\t\tif status == upStatus {\n\t\t\tlogger.Infof(\"osd.%d is healthy. It cannot be removed unless it is 'down'\", osdID)\n\t\t\tcontinue\n\t\t} else {\n\t\t\tlogger.Infof(\"osd.%d is marked 'DOWN'\", osdID)\n\t\t}\n\n\t\t\/\/ Check we can remove the OSD\n\t\t\/\/ Loop forever until the osd is safe-to-destroy\n\t\tfor {\n\t\t\tisSafeToDestroy, err := client.OsdSafeToDestroy(context, clusterInfo, osdID)\n\t\t\tif err != nil {\n\t\t\t\t\/\/ If we want to force remove the OSD and there was an error let's break outside of\n\t\t\t\t\/\/ the loop and proceed with the OSD removal\n\t\t\t\tif forceOSDRemoval {\n\t\t\t\t\tlogger.Errorf(\"failed to check if osd %d is safe to destroy, but force removal is enabled so proceeding with removal. %v\", osdID, err)\n\t\t\t\t\tbreak\n\t\t\t\t} else {\n\t\t\t\t\tlogger.Errorf(\"failed to check if osd %d is safe to destroy, retrying in 1m. %v\", osdID, err)\n\t\t\t\t\ttime.Sleep(1 * time.Minute)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ If no error and the OSD is safe to destroy, we can proceed with the OSD removal\n\t\t\tif isSafeToDestroy {\n\t\t\t\tlogger.Infof(\"osd.%d is safe to destroy, proceeding\", osdID)\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\t\/\/ If we arrive here and forceOSDRemoval is true, we should proceed with the OSD removal\n\t\t\t\tif forceOSDRemoval {\n\t\t\t\t\tlogger.Infof(\"osd.%d is NOT be ok to destroy but force removal is enabled so proceeding with removal\", osdID)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\t\/\/ Else we wait until the OSD can be removed\n\t\t\t\tlogger.Warningf(\"osd.%d is NOT be ok to destroy, retrying in 1m until success\", osdID)\n\t\t\t\ttime.Sleep(1 * time.Minute)\n\t\t\t}\n\t\t}\n\n\t\tremoveOSD(context, clusterInfo, osdID, preservePVC)\n\t}\n\n\treturn nil\n}\n\nfunc removeOSD(clusterdContext *clusterd.Context, clusterInfo *client.ClusterInfo, osdID int, preservePVC bool) {\n\t\/\/ Get the host where the OSD is found\n\thostName, err := client.GetCrushHostName(clusterdContext, clusterInfo, osdID)\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to get the host where osd.%d is running. %v\", osdID, err)\n\t}\n\n\t\/\/ Mark the OSD as out.\n\tlogger.Infof(\"marking osd.%d out\", osdID)\n\targs := []string{\"osd\", \"out\", fmt.Sprintf(\"osd.%d\", osdID)}\n\t_, err = client.NewCephCommand(clusterdContext, clusterInfo, args).Run()\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to exclude osd.%d out of the crush map. %v\", osdID, err)\n\t}\n\n\t\/\/ Remove the OSD deployment\n\tdeploymentName := fmt.Sprintf(\"rook-ceph-osd-%d\", osdID)\n\tdeployment, err := clusterdContext.Clientset.AppsV1().Deployments(clusterInfo.Namespace).Get(clusterInfo.Context, deploymentName, metav1.GetOptions{})\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to fetch the deployment %q. %v\", deploymentName, err)\n\t} else {\n\t\tlogger.Infof(\"removing the OSD deployment %q\", deploymentName)\n\t\tif err := k8sutil.DeleteDeployment(clusterInfo.Context, clusterdContext.Clientset, clusterInfo.Namespace, deploymentName); err != nil {\n\t\t\tif err != nil {\n\t\t\t\t\/\/ Continue purging the OSD even if the deployment fails to be deleted\n\t\t\t\tlogger.Errorf(\"failed to delete deployment for OSD %d. %v\", osdID, err)\n\t\t\t}\n\t\t}\n\t\tif pvcName, ok := deployment.GetLabels()[osd.OSDOverPVCLabelKey]; ok {\n\t\t\tremoveOSDPrepareJob(clusterdContext, clusterInfo, pvcName)\n\t\t\tremovePVCs(clusterdContext, clusterInfo, pvcName, preservePVC)\n\t\t} else {\n\t\t\tlogger.Infof(\"did not find a pvc name to remove for osd %q\", deploymentName)\n\t\t}\n\t}\n\n\t\/\/ purge the osd\n\tlogger.Infof(\"purging osd.%d\", osdID)\n\tpurgeOSDArgs := []string{\"osd\", \"purge\", fmt.Sprintf(\"osd.%d\", osdID), \"--force\", \"--yes-i-really-mean-it\"}\n\t_, err = client.NewCephCommand(clusterdContext, clusterInfo, purgeOSDArgs).Run()\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to purge osd.%d. %v\", osdID, err)\n\t}\n\n\t\/\/ Attempting to remove the parent host. Errors can be ignored if there are other OSDs on the same host\n\tlogger.Infof(\"attempting to remove host %q from crush map if not in use\", osdID)\n\thostArgs := []string{\"osd\", \"crush\", \"rm\", hostName}\n\t_, err = client.NewCephCommand(clusterdContext, clusterInfo, hostArgs).Run()\n\tif err != nil {\n\t\tlogger.Infof(\"failed to remove CRUSH host %q. %v\", hostName, err)\n\t}\n\n\t\/\/ call archiveCrash to silence crash warning in ceph health if any\n\tarchiveCrash(clusterdContext, clusterInfo, osdID)\n\n\tlogger.Infof(\"completed removal of OSD %d\", osdID)\n}\n\nfunc removeOSDPrepareJob(clusterdContext *clusterd.Context, clusterInfo *client.ClusterInfo, pvcName string) {\n\tlabelSelector := fmt.Sprintf(\"%s=%s\", osd.OSDOverPVCLabelKey, pvcName)\n\tprepareJobList, err := clusterdContext.Clientset.BatchV1().Jobs(clusterInfo.Namespace).List(clusterInfo.Context, metav1.ListOptions{LabelSelector: labelSelector})\n\tif err != nil && !kerrors.IsNotFound(err) {\n\t\tlogger.Errorf(\"failed to list osd prepare jobs with pvc %q. %v \", pvcName, err)\n\t}\n\t\/\/ Remove osd prepare job\n\tfor _, prepareJob := range prepareJobList.Items {\n\t\tlogger.Infof(\"removing the osd prepare job %q\", prepareJob.GetName())\n\t\tif err := k8sutil.DeleteBatchJob(clusterInfo.Context, clusterdContext.Clientset, clusterInfo.Namespace, prepareJob.GetName(), false); err != nil {\n\t\t\tif err != nil {\n\t\t\t\t\/\/ Continue with the cleanup even if the job fails to be deleted\n\t\t\t\tlogger.Errorf(\"failed to delete prepare job for osd %q. %v\", prepareJob.GetName(), err)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc removePVCs(clusterdContext *clusterd.Context, clusterInfo *client.ClusterInfo, dataPVCName string, preservePVC bool) {\n\tdataPVC, err := clusterdContext.Clientset.CoreV1().PersistentVolumeClaims(clusterInfo.Namespace).Get(clusterInfo.Context, dataPVCName, metav1.GetOptions{})\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to get pvc for OSD %q. %v\", dataPVCName, err)\n\t\treturn\n\t}\n\tlabels := dataPVC.GetLabels()\n\tdeviceSet := labels[osd.CephDeviceSetLabelKey]\n\tsetIndex := labels[osd.CephSetIndexLabelKey]\n\n\tlabelSelector := fmt.Sprintf(\"%s=%s,%s=%s\", osd.CephDeviceSetLabelKey, deviceSet, osd.CephSetIndexLabelKey, setIndex)\n\tlistOptions := metav1.ListOptions{LabelSelector: labelSelector}\n\tpvcs, err := clusterdContext.Clientset.CoreV1().PersistentVolumeClaims(clusterInfo.Namespace).List(clusterInfo.Context, listOptions)\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to get pvcs for OSD %q. %v\", dataPVCName, err)\n\t\treturn\n\t}\n\n\t\/\/ Delete each of the data, wal, and db PVCs that belonged to the OSD\n\tfor i, pvc := range pvcs.Items {\n\t\tif preservePVC {\n\t\t\t\/\/ Detach the OSD PVC from Rook. We will continue OSD deletion even if failed to remove PVC label\n\t\t\tlogger.Infof(\"detach the OSD PVC %q from Rook\", pvc.Name)\n\t\t\tdelete(labels, osd.CephDeviceSetPVCIDLabelKey)\n\t\t\tpvc.SetLabels(labels)\n\t\t\tif _, err := clusterdContext.Clientset.CoreV1().PersistentVolumeClaims(clusterInfo.Namespace).Update(clusterInfo.Context, &pvcs.Items[i], metav1.UpdateOptions{}); err != nil {\n\t\t\t\tlogger.Errorf(\"failed to remove label %q from pvc for OSD %q. %v\", osd.CephDeviceSetPVCIDLabelKey, pvc.Name, err)\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ Remove the OSD PVC\n\t\t\tlogger.Infof(\"removing the OSD PVC %q\", pvc.Name)\n\t\t\tif err := clusterdContext.Clientset.CoreV1().PersistentVolumeClaims(clusterInfo.Namespace).Delete(clusterInfo.Context, pvc.Name, metav1.DeleteOptions{}); err != nil {\n\t\t\t\tif err != nil {\n\t\t\t\t\t\/\/ Continue deleting the OSD PVC even if PVC deletion fails\n\t\t\t\t\tlogger.Errorf(\"failed to delete pvc %q for OSD. %v\", pvc.Name, err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc archiveCrash(clusterdContext *clusterd.Context, clusterInfo *client.ClusterInfo, osdID int) {\n\t\/\/ The ceph health warning should be silenced by archiving the crash\n\tcrash, err := client.GetCrash(clusterdContext, clusterInfo)\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to list ceph crash. %v\", err)\n\t\treturn\n\t}\n\tif crash != nil {\n\t\tlogger.Info(\"no ceph crash to silence\")\n\t\treturn\n\t}\n\n\tvar crashID string\n\tfor _, c := range crash {\n\t\tif c.Entity == fmt.Sprintf(\"osd.%d\", osdID) {\n\t\t\tcrashID = c.ID\n\t\t\tbreak\n\t\t}\n\t}\n\n\terr = client.ArchiveCrash(clusterdContext, clusterInfo, crashID)\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to archive the crash %q. %v\", crashID, err)\n\t}\n}\nosd: osdSafeToDestroy check should be after osd out\/*\nCopyright 2020 The Rook Authors. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n\thttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage osd\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"time\"\n\n\tkerrors \"k8s.io\/apimachinery\/pkg\/api\/errors\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/rook\/rook\/pkg\/clusterd\"\n\t\"github.com\/rook\/rook\/pkg\/daemon\/ceph\/client\"\n\t\"github.com\/rook\/rook\/pkg\/operator\/ceph\/cluster\/osd\"\n\t\"github.com\/rook\/rook\/pkg\/operator\/k8sutil\"\n)\n\n\/\/ RemoveOSDs purges a list of OSDs from the cluster\nfunc RemoveOSDs(context *clusterd.Context, clusterInfo *client.ClusterInfo, osdsToRemove []string, preservePVC, forceOSDRemoval bool) error {\n\t\/\/ Generate the ceph config for running ceph commands similar to the operator\n\tif err := client.WriteCephConfig(context, clusterInfo); err != nil {\n\t\treturn errors.Wrap(err, \"failed to write the ceph config\")\n\t}\n\n\tosdDump, err := client.GetOSDDump(context, clusterInfo)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to get osd dump\")\n\t}\n\n\tfor _, osdIDStr := range osdsToRemove {\n\t\tosdID, err := strconv.Atoi(osdIDStr)\n\t\tif err != nil {\n\t\t\tlogger.Errorf(\"invalid OSD ID: %s. %v\", osdIDStr, err)\n\t\t\tcontinue\n\t\t}\n\t\tlogger.Infof(\"validating status of osd.%d\", osdID)\n\t\tstatus, _, err := osdDump.StatusByID(int64(osdID))\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed to get osd status for osd %d\", osdID)\n\t\t}\n\t\tconst upStatus int64 = 1\n\t\tif status == upStatus {\n\t\t\tlogger.Infof(\"osd.%d is healthy. It cannot be removed unless it is 'down'\", osdID)\n\t\t\tcontinue\n\t\t} else {\n\t\t\tlogger.Infof(\"osd.%d is marked 'DOWN'\", osdID)\n\t\t}\n\n\t\tremoveOSD(context, clusterInfo, osdID, preservePVC, forceOSDRemoval)\n\t}\n\n\treturn nil\n}\n\nfunc removeOSD(clusterdContext *clusterd.Context, clusterInfo *client.ClusterInfo, osdID int, preservePVC, forceOSDRemoval bool) {\n\t\/\/ Get the host where the OSD is found\n\thostName, err := client.GetCrushHostName(clusterdContext, clusterInfo, osdID)\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to get the host where osd.%d is running. %v\", osdID, err)\n\t}\n\n\t\/\/ Mark the OSD as out.\n\tlogger.Infof(\"marking osd.%d out\", osdID)\n\targs := []string{\"osd\", \"out\", fmt.Sprintf(\"osd.%d\", osdID)}\n\t_, err = client.NewCephCommand(clusterdContext, clusterInfo, args).Run()\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to exclude osd.%d out of the crush map. %v\", osdID, err)\n\t}\n\n\t\/\/ Check we can remove the OSD\n\t\/\/ Loop forever until the osd is safe-to-destroy\n\tfor {\n\t\tisSafeToDestroy, err := client.OsdSafeToDestroy(clusterdContext, clusterInfo, osdID)\n\t\tif err != nil {\n\t\t\t\/\/ If we want to force remove the OSD and there was an error let's break outside of\n\t\t\t\/\/ the loop and proceed with the OSD removal\n\t\t\tif forceOSDRemoval {\n\t\t\t\tlogger.Errorf(\"failed to check if osd %d is safe to destroy, but force removal is enabled so proceeding with removal. %v\", osdID, err)\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\tlogger.Errorf(\"failed to check if osd %d is safe to destroy, retrying in 1m. %v\", osdID, err)\n\t\t\t\ttime.Sleep(1 * time.Minute)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\t\/\/ If no error and the OSD is safe to destroy, we can proceed with the OSD removal\n\t\tif isSafeToDestroy {\n\t\t\tlogger.Infof(\"osd.%d is safe to destroy, proceeding\", osdID)\n\t\t\tbreak\n\t\t} else {\n\t\t\t\/\/ If we arrive here and forceOSDRemoval is true, we should proceed with the OSD removal\n\t\t\tif forceOSDRemoval {\n\t\t\t\tlogger.Infof(\"osd.%d is NOT be ok to destroy but force removal is enabled so proceeding with removal\", osdID)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t\/\/ Else we wait until the OSD can be removed\n\t\t\tlogger.Warningf(\"osd.%d is NOT be ok to destroy, retrying in 1m until success\", osdID)\n\t\t\ttime.Sleep(1 * time.Minute)\n\t\t}\n\t}\n\n\t\/\/ Remove the OSD deployment\n\tdeploymentName := fmt.Sprintf(\"rook-ceph-osd-%d\", osdID)\n\tdeployment, err := clusterdContext.Clientset.AppsV1().Deployments(clusterInfo.Namespace).Get(clusterInfo.Context, deploymentName, metav1.GetOptions{})\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to fetch the deployment %q. %v\", deploymentName, err)\n\t} else {\n\t\tlogger.Infof(\"removing the OSD deployment %q\", deploymentName)\n\t\tif err := k8sutil.DeleteDeployment(clusterInfo.Context, clusterdContext.Clientset, clusterInfo.Namespace, deploymentName); err != nil {\n\t\t\tif err != nil {\n\t\t\t\t\/\/ Continue purging the OSD even if the deployment fails to be deleted\n\t\t\t\tlogger.Errorf(\"failed to delete deployment for OSD %d. %v\", osdID, err)\n\t\t\t}\n\t\t}\n\t\tif pvcName, ok := deployment.GetLabels()[osd.OSDOverPVCLabelKey]; ok {\n\t\t\tremoveOSDPrepareJob(clusterdContext, clusterInfo, pvcName)\n\t\t\tremovePVCs(clusterdContext, clusterInfo, pvcName, preservePVC)\n\t\t} else {\n\t\t\tlogger.Infof(\"did not find a pvc name to remove for osd %q\", deploymentName)\n\t\t}\n\t}\n\n\t\/\/ purge the osd\n\tlogger.Infof(\"purging osd.%d\", osdID)\n\tpurgeOSDArgs := []string{\"osd\", \"purge\", fmt.Sprintf(\"osd.%d\", osdID), \"--force\", \"--yes-i-really-mean-it\"}\n\t_, err = client.NewCephCommand(clusterdContext, clusterInfo, purgeOSDArgs).Run()\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to purge osd.%d. %v\", osdID, err)\n\t}\n\n\t\/\/ Attempting to remove the parent host. Errors can be ignored if there are other OSDs on the same host\n\tlogger.Infof(\"attempting to remove host %q from crush map if not in use\", osdID)\n\thostArgs := []string{\"osd\", \"crush\", \"rm\", hostName}\n\t_, err = client.NewCephCommand(clusterdContext, clusterInfo, hostArgs).Run()\n\tif err != nil {\n\t\tlogger.Infof(\"failed to remove CRUSH host %q. %v\", hostName, err)\n\t}\n\n\t\/\/ call archiveCrash to silence crash warning in ceph health if any\n\tarchiveCrash(clusterdContext, clusterInfo, osdID)\n\n\tlogger.Infof(\"completed removal of OSD %d\", osdID)\n}\n\nfunc removeOSDPrepareJob(clusterdContext *clusterd.Context, clusterInfo *client.ClusterInfo, pvcName string) {\n\tlabelSelector := fmt.Sprintf(\"%s=%s\", osd.OSDOverPVCLabelKey, pvcName)\n\tprepareJobList, err := clusterdContext.Clientset.BatchV1().Jobs(clusterInfo.Namespace).List(clusterInfo.Context, metav1.ListOptions{LabelSelector: labelSelector})\n\tif err != nil && !kerrors.IsNotFound(err) {\n\t\tlogger.Errorf(\"failed to list osd prepare jobs with pvc %q. %v \", pvcName, err)\n\t}\n\t\/\/ Remove osd prepare job\n\tfor _, prepareJob := range prepareJobList.Items {\n\t\tlogger.Infof(\"removing the osd prepare job %q\", prepareJob.GetName())\n\t\tif err := k8sutil.DeleteBatchJob(clusterInfo.Context, clusterdContext.Clientset, clusterInfo.Namespace, prepareJob.GetName(), false); err != nil {\n\t\t\tif err != nil {\n\t\t\t\t\/\/ Continue with the cleanup even if the job fails to be deleted\n\t\t\t\tlogger.Errorf(\"failed to delete prepare job for osd %q. %v\", prepareJob.GetName(), err)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc removePVCs(clusterdContext *clusterd.Context, clusterInfo *client.ClusterInfo, dataPVCName string, preservePVC bool) {\n\tdataPVC, err := clusterdContext.Clientset.CoreV1().PersistentVolumeClaims(clusterInfo.Namespace).Get(clusterInfo.Context, dataPVCName, metav1.GetOptions{})\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to get pvc for OSD %q. %v\", dataPVCName, err)\n\t\treturn\n\t}\n\tlabels := dataPVC.GetLabels()\n\tdeviceSet := labels[osd.CephDeviceSetLabelKey]\n\tsetIndex := labels[osd.CephSetIndexLabelKey]\n\n\tlabelSelector := fmt.Sprintf(\"%s=%s,%s=%s\", osd.CephDeviceSetLabelKey, deviceSet, osd.CephSetIndexLabelKey, setIndex)\n\tlistOptions := metav1.ListOptions{LabelSelector: labelSelector}\n\tpvcs, err := clusterdContext.Clientset.CoreV1().PersistentVolumeClaims(clusterInfo.Namespace).List(clusterInfo.Context, listOptions)\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to get pvcs for OSD %q. %v\", dataPVCName, err)\n\t\treturn\n\t}\n\n\t\/\/ Delete each of the data, wal, and db PVCs that belonged to the OSD\n\tfor i, pvc := range pvcs.Items {\n\t\tif preservePVC {\n\t\t\t\/\/ Detach the OSD PVC from Rook. We will continue OSD deletion even if failed to remove PVC label\n\t\t\tlogger.Infof(\"detach the OSD PVC %q from Rook\", pvc.Name)\n\t\t\tdelete(labels, osd.CephDeviceSetPVCIDLabelKey)\n\t\t\tpvc.SetLabels(labels)\n\t\t\tif _, err := clusterdContext.Clientset.CoreV1().PersistentVolumeClaims(clusterInfo.Namespace).Update(clusterInfo.Context, &pvcs.Items[i], metav1.UpdateOptions{}); err != nil {\n\t\t\t\tlogger.Errorf(\"failed to remove label %q from pvc for OSD %q. %v\", osd.CephDeviceSetPVCIDLabelKey, pvc.Name, err)\n\t\t\t}\n\t\t} else {\n\t\t\t\/\/ Remove the OSD PVC\n\t\t\tlogger.Infof(\"removing the OSD PVC %q\", pvc.Name)\n\t\t\tif err := clusterdContext.Clientset.CoreV1().PersistentVolumeClaims(clusterInfo.Namespace).Delete(clusterInfo.Context, pvc.Name, metav1.DeleteOptions{}); err != nil {\n\t\t\t\tif err != nil {\n\t\t\t\t\t\/\/ Continue deleting the OSD PVC even if PVC deletion fails\n\t\t\t\t\tlogger.Errorf(\"failed to delete pvc %q for OSD. %v\", pvc.Name, err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc archiveCrash(clusterdContext *clusterd.Context, clusterInfo *client.ClusterInfo, osdID int) {\n\t\/\/ The ceph health warning should be silenced by archiving the crash\n\tcrash, err := client.GetCrash(clusterdContext, clusterInfo)\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to list ceph crash. %v\", err)\n\t\treturn\n\t}\n\tif crash != nil {\n\t\tlogger.Info(\"no ceph crash to silence\")\n\t\treturn\n\t}\n\n\tvar crashID string\n\tfor _, c := range crash {\n\t\tif c.Entity == fmt.Sprintf(\"osd.%d\", osdID) {\n\t\t\tcrashID = c.ID\n\t\t\tbreak\n\t\t}\n\t}\n\n\terr = client.ArchiveCrash(clusterdContext, clusterInfo, crashID)\n\tif err != nil {\n\t\tlogger.Errorf(\"failed to archive the crash %q. %v\", crashID, err)\n\t}\n}\n<|endoftext|>"} {"text":"package binary\n\n\/\/ BigEndian big endian.\nvar BigEndian bigEndian\n\ntype bigEndian struct{}\n\nfunc (bigEndian) Int8(b []byte) int8 { return int8(b[0]) }\n\nfunc (bigEndian) PutInt8(b []byte, v int8) {\n\tb[0] = byte(v)\n}\n\nfunc (bigEndian) Int16(b []byte) int16 { return int16(b[1]) | int16(b[0])<<8 }\n\nfunc (bigEndian) PutInt16(b []byte, v int16) {\n\tb[0] = byte(v >> 8)\n\tb[1] = byte(v)\n}\n\nfunc (bigEndian) Int32(b []byte) int32 {\n\treturn int32(b[3]) | int32(b[2])<<8 | int32(b[1])<<16 | int32(b[0])<<24\n}\n\nfunc (bigEndian) PutInt32(b []byte, v int32) {\n\tb[0] = byte(v >> 24)\n\tb[1] = byte(v >> 16)\n\tb[2] = byte(v >> 8)\n\tb[3] = byte(v)\n}\nreduce bound check (#362)package binary\n\n\/\/ BigEndian big endian.\nvar BigEndian bigEndian\n\ntype bigEndian struct{}\n\nfunc (bigEndian) Int8(b []byte) int8 { return int8(b[0]) }\n\nfunc (bigEndian) PutInt8(b []byte, v int8) {\n\tb[0] = byte(v)\n}\n\nfunc (bigEndian) Int16(b []byte) int16 { return int16(b[1]) | int16(b[0])<<8 }\n\nfunc (bigEndian) PutInt16(b []byte, v int16) {\n\t_ = b[1]\n\tb[0] = byte(v >> 8)\n\tb[1] = byte(v)\n}\n\nfunc (bigEndian) Int32(b []byte) int32 {\n\treturn int32(b[3]) | int32(b[2])<<8 | int32(b[1])<<16 | int32(b[0])<<24\n}\n\nfunc (bigEndian) PutInt32(b []byte, v int32) {\n\t_ = b[3]\n\tb[0] = byte(v >> 24)\n\tb[1] = byte(v >> 16)\n\tb[2] = byte(v >> 8)\n\tb[3] = byte(v)\n}\n<|endoftext|>"} {"text":"package ingester\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/grafana\/loki\/pkg\/logproto\"\n\t\"github.com\/stretchr\/testify\/require\"\n\t\"github.com\/weaveworks\/common\/user\"\n\t\"golang.org\/x\/net\/context\"\n\t\"google.golang.org\/grpc\"\n\n\t\"github.com\/cortexproject\/cortex\/pkg\/chunk\"\n\t\"github.com\/cortexproject\/cortex\/pkg\/ring\"\n\t\"github.com\/cortexproject\/cortex\/pkg\/util\/flagext\"\n)\n\nfunc TestIngester(t *testing.T) {\n\tvar ingesterConfig Config\n\tflagext.DefaultValues(&ingesterConfig)\n\tingesterConfig.LifecyclerConfig.RingConfig.Mock = ring.NewInMemoryKVClient()\n\tingesterConfig.LifecyclerConfig.NumTokens = 1\n\tingesterConfig.LifecyclerConfig.ListenPort = func(i int) *int { return &i }(0)\n\tingesterConfig.LifecyclerConfig.Addr = \"localhost\"\n\tingesterConfig.LifecyclerConfig.ID = \"localhost\"\n\n\tstore := &mockStore{\n\t\tchunks: map[string][]chunk.Chunk{},\n\t}\n\n\ti, err := New(ingesterConfig, store)\n\trequire.NoError(t, err)\n\tdefer i.Shutdown()\n\n\treq := logproto.PushRequest{\n\t\tStreams: []*logproto.Stream{\n\t\t\t{\n\t\t\t\tLabels: `{foo=\"bar\",bar=\"baz1\"}`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tLabels: `{foo=\"bar\",bar=\"baz2\"}`,\n\t\t\t},\n\t\t},\n\t}\n\tfor i := 0; i < 10; i++ {\n\t\treq.Streams[0].Entries = append(req.Streams[0].Entries, logproto.Entry{\n\t\t\tTimestamp: time.Unix(0, 0),\n\t\t\tLine: fmt.Sprintf(\"line %d\", i),\n\t\t})\n\t\treq.Streams[1].Entries = append(req.Streams[0].Entries, logproto.Entry{\n\t\t\tTimestamp: time.Unix(0, 0),\n\t\t\tLine: fmt.Sprintf(\"line %d\", i),\n\t\t})\n\t}\n\n\tctx := user.InjectOrgID(context.Background(), \"test\")\n\t_, err = i.Push(ctx, &req)\n\trequire.NoError(t, err)\n\n\tfmt.Println(\"hehe\")\n\n\tresult := mockQuerierServer{\n\t\tctx: ctx,\n\t}\n\terr = i.Query(&logproto.QueryRequest{\n\t\tQuery: `{foo=\"bar\"}`,\n\t\tLimit: 100,\n\t\tStart: time.Unix(0, 0),\n\t\tEnd: time.Unix(1, 0),\n\t}, &result)\n\trequire.NoError(t, err)\n\n\trequire.Len(t, result.resps, 1)\n\trequire.Len(t, result.resps[0].Streams, 2)\n\trequire.Equal(t, `{foo=\"bar\", bar=\"baz1\"}`, result.resps[0].Streams[0].Labels)\n\trequire.Equal(t, `{foo=\"bar\", bar=\"baz2\"}`, result.resps[0].Streams[1].Labels)\n}\n\ntype mockStore struct {\n\tmtx sync.Mutex\n\tchunks map[string][]chunk.Chunk\n}\n\nfunc (s *mockStore) Put(ctx context.Context, chunks []chunk.Chunk) error {\n\ts.mtx.Lock()\n\tdefer s.mtx.Unlock()\n\n\tuserid, err := user.ExtractOrgID(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.chunks[userid] = append(s.chunks[userid], chunks...)\n\treturn nil\n}\n\ntype mockQuerierServer struct {\n\tctx context.Context\n\tresps []*logproto.QueryResponse\n\tgrpc.ServerStream\n}\n\nfunc (m *mockQuerierServer) Send(resp *logproto.QueryResponse) error {\n\tm.resps = append(m.resps, resp)\n\treturn nil\n}\n\nfunc (m *mockQuerierServer) Context() context.Context {\n\treturn m.ctx\n}\nfixed one bug which was probably unrelated to the test failure and broke out the test to avoid some non-deterministic behaviors in querying the ingesterpackage ingester\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/grafana\/loki\/pkg\/logproto\"\n\t\"github.com\/stretchr\/testify\/require\"\n\t\"github.com\/weaveworks\/common\/user\"\n\t\"golang.org\/x\/net\/context\"\n\t\"google.golang.org\/grpc\"\n\n\t\"github.com\/cortexproject\/cortex\/pkg\/chunk\"\n\t\"github.com\/cortexproject\/cortex\/pkg\/ring\"\n\t\"github.com\/cortexproject\/cortex\/pkg\/util\/flagext\"\n)\n\nfunc TestIngester(t *testing.T) {\n\tvar ingesterConfig Config\n\tflagext.DefaultValues(&ingesterConfig)\n\tingesterConfig.LifecyclerConfig.RingConfig.Mock = ring.NewInMemoryKVClient()\n\tingesterConfig.LifecyclerConfig.NumTokens = 1\n\tingesterConfig.LifecyclerConfig.ListenPort = func(i int) *int { return &i }(0)\n\tingesterConfig.LifecyclerConfig.Addr = \"localhost\"\n\tingesterConfig.LifecyclerConfig.ID = \"localhost\"\n\n\tstore := &mockStore{\n\t\tchunks: map[string][]chunk.Chunk{},\n\t}\n\n\ti, err := New(ingesterConfig, store)\n\trequire.NoError(t, err)\n\tdefer i.Shutdown()\n\n\treq := logproto.PushRequest{\n\t\tStreams: []*logproto.Stream{\n\t\t\t{\n\t\t\t\tLabels: `{foo=\"bar\",bar=\"baz1\"}`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tLabels: `{foo=\"bar\",bar=\"baz2\"}`,\n\t\t\t},\n\t\t},\n\t}\n\tfor i := 0; i < 10; i++ {\n\t\treq.Streams[0].Entries = append(req.Streams[0].Entries, logproto.Entry{\n\t\t\tTimestamp: time.Unix(0, 0),\n\t\t\tLine: fmt.Sprintf(\"line %d\", i),\n\t\t})\n\t\treq.Streams[1].Entries = append(req.Streams[1].Entries, logproto.Entry{\n\t\t\tTimestamp: time.Unix(0, 0),\n\t\t\tLine: fmt.Sprintf(\"line %d\", i),\n\t\t})\n\t}\n\n\tctx := user.InjectOrgID(context.Background(), \"test\")\n\t_, err = i.Push(ctx, &req)\n\trequire.NoError(t, err)\n\n\tfmt.Println(\"hehe\")\n\n\tresult := mockQuerierServer{\n\t\tctx: ctx,\n\t}\n\terr = i.Query(&logproto.QueryRequest{\n\t\tQuery: `{foo=\"bar\"}`,\n\t\tLimit: 100,\n\t\tStart: time.Unix(0, 0),\n\t\tEnd: time.Unix(1, 0),\n\t}, &result)\n\trequire.NoError(t, err)\n\trequire.Len(t, result.resps, 1)\n\trequire.Len(t, result.resps[0].Streams, 2)\n\n\tresult = mockQuerierServer{\n\t\tctx: ctx,\n\t}\n\terr = i.Query(&logproto.QueryRequest{\n\t\tQuery: `{foo=\"bar\",bar=\"baz1\"}`,\n\t\tLimit: 100,\n\t\tStart: time.Unix(0, 0),\n\t\tEnd: time.Unix(1, 0),\n\t}, &result)\n\trequire.NoError(t, err)\n\trequire.Len(t, result.resps, 1)\n\trequire.Len(t, result.resps[0].Streams, 1)\n\trequire.Equal(t, `{foo=\"bar\", bar=\"baz1\"}`, result.resps[0].Streams[0].Labels)\n\n\tresult = mockQuerierServer{\n\t\tctx: ctx,\n\t}\n\terr = i.Query(&logproto.QueryRequest{\n\t\tQuery: `{foo=\"bar\",bar=\"baz2\"}`,\n\t\tLimit: 100,\n\t\tStart: time.Unix(0, 0),\n\t\tEnd: time.Unix(1, 0),\n\t}, &result)\n\trequire.NoError(t, err)\n\trequire.Len(t, result.resps, 1)\n\trequire.Len(t, result.resps[0].Streams, 1)\n\trequire.Equal(t, `{foo=\"bar\", bar=\"baz2\"}`, result.resps[0].Streams[0].Labels)\n}\n\ntype mockStore struct {\n\tmtx sync.Mutex\n\tchunks map[string][]chunk.Chunk\n}\n\nfunc (s *mockStore) Put(ctx context.Context, chunks []chunk.Chunk) error {\n\ts.mtx.Lock()\n\tdefer s.mtx.Unlock()\n\n\tuserid, err := user.ExtractOrgID(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts.chunks[userid] = append(s.chunks[userid], chunks...)\n\treturn nil\n}\n\ntype mockQuerierServer struct {\n\tctx context.Context\n\tresps []*logproto.QueryResponse\n\tgrpc.ServerStream\n}\n\nfunc (m *mockQuerierServer) Send(resp *logproto.QueryResponse) error {\n\tm.resps = append(m.resps, resp)\n\treturn nil\n}\n\nfunc (m *mockQuerierServer) Context() context.Context {\n\treturn m.ctx\n}\n<|endoftext|>"} {"text":"package config\n\nimport (\n\t\"crypto\/rand\"\n\t\"database\/sql\"\n\t\"encoding\/hex\"\n\t\"fmt\"\n\n\t\"golang.org\/x\/crypto\/bcrypt\"\n)\n\n\/\/ Config represents a config set\ntype Config map[string]string\n\n\/\/ NewConfig creates a new config set\nfunc NewConfig() Config {\n\treturn Config(make(map[string]string))\n}\n\nconst (\n\t\/\/ ConfigNameSystemPassword is the name for the system password configuration setting\n\tConfigNameSystemPassword = \"SystemPassword\"\n\t\/\/ ConfigSystemPasswordBcryptCost is the cost for bcrypting the system password\n\tConfigSystemPasswordBcryptCost = 12\n)\n\nconst (\n\t\/\/ DefaultPasswordBytes is the default password length in bytes\n\tDefaultPasswordBytes = 32\n)\n\ntype entrySetter func(Config) error\n\n\/\/ SetPassword returns a setter for a cleartext system password\nfunc SetPassword(pw []byte) entrySetter {\n\treturn entrySetter(func(c Config) error {\n\t\tenc, err := bcrypt.GenerateFromPassword(pw, ConfigSystemPasswordBcryptCost)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tc[ConfigNameSystemPassword] = string(enc)\n\t\treturn nil\n\t})\n}\n\n\/\/ DefaultPassword represents a default password generation and setting\ntype DefaultPassword string\n\n\/\/ Generate generates a random password\nfunc (d *DefaultPassword) Generate() error {\n\tpw := make([]byte, DefaultPasswordBytes)\n\t_, err := rand.Read(pw)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*d = DefaultPassword(hex.EncodeToString(pw))\n\treturn nil\n}\n\n\/\/ Entry returns a setter, which can be used with the Set() function for setting\n\/\/ the default system password\nfunc (d DefaultPassword) Entry() entrySetter {\n\treturn SetPassword([]byte(d))\n}\n\n\/\/ DefaultPasswordSetter sets a default password\nvar DefaultPasswordSetter = entrySetter(func(c Config) error {\n\tpw := make([]byte, DefaultPasswordBytes)\n\t_, err := rand.Read(pw)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc[ConfigNameSystemPassword] = hex.EncodeToString(pw)\n\treturn nil\n})\n\n\/\/ Set sets passed configuration settings\nfunc Set(db *sql.DB, settings ...entrySetter) error {\n\tvar err error\n\t\/\/ empty config\n\tcfg := NewConfig()\n\tfor _, set := range settings {\n\t\terr = set(cfg)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif len(cfg) == 0 {\n\t\treturn nil\n\t}\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error on begin tx: %v\", err)\n\t}\n\terr = InsertConfigTx(tx, cfg)\n\tif err != nil {\n\t\ttxErr := tx.Rollback()\n\t\tif txErr != nil {\n\t\t\treturn fmt.Errorf(\"error on rollback tx: %v\", err)\n\t\t}\n\t\treturn fmt.Errorf(\"error on saving config: %v\", err)\n\t}\n\terr = tx.Commit()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error on commit tx: %v\", err)\n\t}\n\treturn nil\n}\nlower default bcrypt costpackage config\n\nimport (\n\t\"crypto\/rand\"\n\t\"database\/sql\"\n\t\"encoding\/hex\"\n\t\"fmt\"\n\n\t\"golang.org\/x\/crypto\/bcrypt\"\n)\n\n\/\/ Config represents a config set\ntype Config map[string]string\n\n\/\/ NewConfig creates a new config set\nfunc NewConfig() Config {\n\treturn Config(make(map[string]string))\n}\n\nconst (\n\t\/\/ ConfigNameSystemPassword is the name for the system password configuration setting\n\tConfigNameSystemPassword = \"SystemPassword\"\n\t\/\/ ConfigSystemPasswordBcryptCost is the cost for bcrypting the system password\n\tConfigSystemPasswordBcryptCost = 10\n)\n\nconst (\n\t\/\/ DefaultPasswordBytes is the default password length in bytes\n\tDefaultPasswordBytes = 32\n)\n\ntype entrySetter func(Config) error\n\n\/\/ SetPassword returns a setter for a cleartext system password\nfunc SetPassword(pw []byte) entrySetter {\n\treturn entrySetter(func(c Config) error {\n\t\tenc, err := bcrypt.GenerateFromPassword(pw, ConfigSystemPasswordBcryptCost)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tc[ConfigNameSystemPassword] = string(enc)\n\t\treturn nil\n\t})\n}\n\n\/\/ DefaultPassword represents a default password generation and setting\ntype DefaultPassword string\n\n\/\/ Generate generates a random password\nfunc (d *DefaultPassword) Generate() error {\n\tpw := make([]byte, DefaultPasswordBytes)\n\t_, err := rand.Read(pw)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*d = DefaultPassword(hex.EncodeToString(pw))\n\treturn nil\n}\n\n\/\/ Entry returns a setter, which can be used with the Set() function for setting\n\/\/ the default system password\nfunc (d DefaultPassword) Entry() entrySetter {\n\treturn SetPassword([]byte(d))\n}\n\n\/\/ DefaultPasswordSetter sets a default password\nvar DefaultPasswordSetter = entrySetter(func(c Config) error {\n\tpw := make([]byte, DefaultPasswordBytes)\n\t_, err := rand.Read(pw)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc[ConfigNameSystemPassword] = hex.EncodeToString(pw)\n\treturn nil\n})\n\n\/\/ Set sets passed configuration settings\nfunc Set(db *sql.DB, settings ...entrySetter) error {\n\tvar err error\n\t\/\/ empty config\n\tcfg := NewConfig()\n\tfor _, set := range settings {\n\t\terr = set(cfg)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tif len(cfg) == 0 {\n\t\treturn nil\n\t}\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error on begin tx: %v\", err)\n\t}\n\terr = InsertConfigTx(tx, cfg)\n\tif err != nil {\n\t\ttxErr := tx.Rollback()\n\t\tif txErr != nil {\n\t\t\treturn fmt.Errorf(\"error on rollback tx: %v\", err)\n\t\t}\n\t\treturn fmt.Errorf(\"error on saving config: %v\", err)\n\t}\n\terr = tx.Commit()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error on commit tx: %v\", err)\n\t}\n\treturn nil\n}\n<|endoftext|>"} {"text":"\/\/+build linux\n\npackage audio\n\nimport (\n\t\"github.com\/oakmound\/alsa-go\"\n\t\"github.com\/pkg\/errors\"\n)\n\ntype alsaAudio struct {\n\t*Encoding\n\t*alsa.Handle\n}\n\nfunc (aa *alsaAudio) Play() <-chan error {\n\tch := make(chan error)\n\tgo func() {\n\t\t\/\/ Todo: loop? library does not export loop\n\t\t_, err := aa.Handle.Write(aa.Encoding.Data)\n\t\tch <- err\n\t}()\n\treturn ch\n}\n\nfunc (aa *alsaAudio) Stop() error {\n\t\/\/ Todo: don't just pause man, actually stop\n\t\/\/ library we are using does not export stop\n\treturn aa.Pause()\n}\n\nfunc (aa *alsaAudio) Filter(fs ...Filter) (Audio, error) {\n\tvar a Audio = aa\n\tvar err, consErr error\n\tfor _, f := range fs {\n\t\ta, err = f.Apply(a)\n\t\tif err != nil {\n\t\t\tif consErr == nil {\n\t\t\t\tconsErr = err\n\t\t\t} else {\n\t\t\t\tconsErr = errors.New(err.Error() + \":\" + consErr.Error())\n\t\t\t}\n\t\t}\n\t}\n\treturn aa, consErr\n}\n\n\/\/ MustFilter acts like Filter, but ignores errors (it does not panic,\n\/\/ as filter errors are expected to be non-fatal)\nfunc (aa *alsaAudio) MustFilter(fs ...Filter) Audio {\n\ta, _ := aa.Filter(fs...)\n\treturn a\n}\n\nfunc EncodeBytes(enc Encoding) (Audio, error) {\n\thandle := alsa.New()\n\terr := handle.Open(\"default\", alsa.StreamTypePlayback, alsa.ModeBlock)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\thandle.SampleFormat = alsaFormat(enc.Bits)\n\thandle.SampleRate = int(enc.SampleRate)\n\thandle.Channels = int(enc.Channels)\n\terr = handle.ApplyHwParams()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &alsaAudio{\n\t\t&enc,\n\t\thandle,\n\t}, nil\n}\n\nfunc alsaFormat(bits uint16) alsa.SampleFormat {\n\tswitch bits {\n\tcase 8:\n\t\treturn alsa.SampleFormatS8\n\tcase 16:\n\t\treturn alsa.SampleFormatS16LE\n\t}\n\treturn alsa.SampleFormatUnknown\n}\nTrying out a new alsa library with no cgo\/\/+build linux\n\npackage audio\n\nimport (\n\t\"sync\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/yobert\/alsa\"\n)\n\ntype alsaAudio struct {\n\t*Encoding\n\t*alsa.Device\n\tbytesPerPeriod int\n\tperiod int\n\tplayProgress int\n\tplaying bool\n\tplayMutex sync.Mutex\n}\n\nfunc (aa *alsaAudio) Play() <-chan error {\n\tch := make(chan error)\n\t\/\/ If currently playing, restart\n\taa.playMutex.Lock()\n\tif aa.playing {\n\t\taa.playProgress = 0\n\t\taa.playMutex.Unlock()\n\t\treturn\n\t}\n\taa.playMutex.Unlock()\n\tgo func() {\n\t\tfor {\n\t\t\tvar data []byte\n\t\t\tif len(aa.Encoding.Data)-aa.playProgress >= aa.period {\n\t\t\t\tdata = aa.Encoding.Data[aa.playProgress:]\n\t\t\t\tif aa.Loop {\n\t\t\t\t\tdelta := aa.period - (len(aa.Encoding.Data)-aa.playProgress)\n\t\t\t\t\tdata = append(data, aa.Encoding.Data[:delta)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tdata = aa.Encoding.Data[aa.playProgress : aa.playProgress+aa.period]\n\t\t\t}\n\t\t\terr := aa.Device.Write(data, aa.period)\n\t\t\tif err != nil {\n\t\t\t\tch <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t\t\/\/ Consider: its racy, but we could remove this lock and risk\n\t\t\t\/\/ skipping the first period of the audio on concurrent play requests\n\t\t\taa.playMutex.Lock()\n\t\t\taa.playProgress += aa.period\n\t\t\tif aa.playProgress > len(aa.Encoding.Data) {\n\t\t\t\tif aa.Loop {\n\t\t\t\t\taa.playProgress %= len(aa.Encoding.Data)\n\t\t\t\t} else {\n\t\t\t\t\taa.playMutex.Unlock()\n\t\t\t\t\treturn \n\t\t\t\t}\n\t\t\t}\n\t\t\taa.playMutex.Unlock()\n\t\t}\n\t}()\n\treturn ch\n}\n\nfunc (aa *alsaAudio) Stop() error {\n\t\/\/ Todo: don't just pause man, actually stop\n\t\/\/ library we are using does not export stop\n\treturn aa.Pause()\n}\n\nfunc (aa *alsaAudio) Filter(fs ...Filter) (Audio, error) {\n\tvar a Audio = aa\n\tvar err, consErr error\n\tfor _, f := range fs {\n\t\ta, err = f.Apply(a)\n\t\tif err != nil {\n\t\t\tif consErr == nil {\n\t\t\t\tconsErr = err\n\t\t\t} else {\n\t\t\t\tconsErr = errors.New(err.Error() + \":\" + consErr.Error())\n\t\t\t}\n\t\t}\n\t}\n\treturn aa, consErr\n}\n\n\/\/ MustFilter acts like Filter, but ignores errors (it does not panic,\n\/\/ as filter errors are expected to be non-fatal)\nfunc (aa *alsaAudio) MustFilter(fs ...Filter) Audio {\n\ta, _ := aa.Filter(fs...)\n\treturn a\n}\n\nfunc EncodeBytes(enc Encoding) (Audio, error) {\n\thandle, err := openDevice()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/err := handle.Open(\"default\", alsa.StreamTypePlayback, alsa.ModeBlock)\n\t\/\/if err != nil {\n\t\/\/\treturn nil, err\n\t\/\/}\n\t\/\/ Todo: annotate these errors with more info\n\tformat, err := alsaFormat(enc.Bits)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, err := handle.NegotiateFormat(format)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, err := handle.NegotiateRate(int(enc.SampleRate))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, err := handle.NegotiateChannels(int(enc.Channels))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t\/\/ Default value at recommendation of library\n\tperiod, err := handle.NegotiatePeriodSize(2048)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, err := handle.NegotiateBufferSize(4096)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = handle.Prepare()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &alsaAudio{\n\t\tEncoding: &enc,\n\t\tDevice: handle,\n\t\tperiod: period,\n\t\tbytesPerPeriod: period * (enc.Bits \/ 8),\n\t}, nil\n}\n\nfunc openDevice() (*alsa.Device, error) {\n\tcards, err := alsa.OpenCards()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor i, c := range cards {\n\t\tdvcs, err := c.Devices()\n\t\tif err != nil {\n\t\t\talsa.CloseCards([]*alsa.Card{c})\n\t\t\tcontinue\n\t\t}\n\t\tfor j, d := range dvcs {\n\t\t\tif d.Type != alsa.PCM || !d.Play {\n\t\t\t\td.Close()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t\/\/ We've a found a device we can hypothetically use\n\t\t\t\/\/ Close all other cards and devices\n\t\t\tfor h := j + 1; h < len(dvcs); h++ {\n\t\t\t\tdvcs[h].Close()\n\t\t\t}\n\t\t\talsa.CloseCards(cards[i+1:])\n\t\t\treturn d, d.Open()\n\t\t}\n\t\talsa.CloseCards([]*alsa.Card{c})\n\t}\n}\n\nfunc alsaFormat(bits uint16) (alsa.FormatType, error) {\n\tswitch bits {\n\tcase 8:\n\t\treturn alsa.S8, nil\n\tcase 16:\n\t\treturn alsa.S16_LE, nil\n\t}\n\treturn 0, errors.New(\"Undefined alsa format for encoding bits\")\n}\n<|endoftext|>"} {"text":"\/*\nCopyright 2012 Google Inc.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage schema\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"math\/rand\"\n\t\"sort\"\n\t\"sync\"\n\t\"testing\"\n\n\t\"camlistore.org\/pkg\/blobserver\/stats\"\n\t\"camlistore.org\/pkg\/test\"\n)\n\nfunc TestWriteFileMap(t *testing.T) {\n\tm := NewFileMap(\"test-file\")\n\tr := &randReader{seed: 123, length: 5 << 20}\n\tsr := new(stats.Receiver)\n\tvar buf bytes.Buffer\n\tbr, err := WriteFileMap(sr, m, io.TeeReader(r, &buf))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tt.Logf(\"Got root file %v; %d blobs, %d bytes\", br, sr.NumBlobs(), sr.SumBlobSize())\n\tsizes := sr.Sizes()\n\tt.Logf(\"Sizes are %v\", sizes)\n\n\t\/\/ TODO(bradfitz): these are fragile tests and mostly just a placeholder.\n\t\/\/ Real tests to add:\n\t\/\/ -- no \"bytes\" schema with a single \"blobref\"\n\t\/\/ -- more seeds (including some that tickle the above)\n\t\/\/ -- file reader reading back the root gets the same sha1 content back\n\t\/\/ (will require keeping the full data in our stats receiver, not\n\t\/\/ just the size)\n\t\/\/ -- well-balanced tree\n\t\/\/ -- nothing too big, nothing too small.\n\tif g, w := br.String(), \"sha1-95a5d2686b239e36dff3aeb5a45ed18153121835\"; g != w {\n\t\tt.Errorf(\"root blobref = %v; want %v\", g, w)\n\t}\n\tif g, w := sr.NumBlobs(), 88; g != w {\n\t\tt.Errorf(\"num blobs = %v; want %v\", g, w)\n\t}\n\tif g, w := sr.SumBlobSize(), int64(5252655); g != w {\n\t\tt.Errorf(\"sum blob size = %v; want %v\", g, w)\n\t}\n\tif g, w := sizes[len(sizes)-1], 262144; g != w {\n\t\tt.Errorf(\"biggest blob is %d; want %d\", g, w)\n\t}\n}\n\nfunc TestWriteThenRead(t *testing.T) {\n\tm := NewFileMap(\"test-file\")\n\tconst size = 5 << 20\n\tr := &randReader{seed: 123, length: size}\n\tsto := new(test.Fetcher)\n\tvar buf bytes.Buffer\n\tbr, err := WriteFileMap(sto, m, io.TeeReader(r, &buf))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tvar got bytes.Buffer\n\tfr, err := NewFileReader(sto, br)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tn, err := io.Copy(&got, fr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif n != size {\n\t\tt.Errorf(\"read back %d bytes; want %d\", n, size)\n\t}\n\tif !bytes.Equal(buf.Bytes(), got.Bytes()) {\n\t\tt.Error(\"bytes differ\")\n\t}\n\n\tvar offc chan int64\n\tvar offs []int\n\n\tgetOffsets := func() error {\n\t\toffs = offs[:0]\n\t\toffc = make(chan int64)\n\t\tgo func() {\n\t\t\tfor off := range offc {\n\t\t\t\toffs = append(offs, int(off))\n\t\t\t}\n\t\t}()\n\t\treturn fr.GetChunkOffsets(offc)\n\t}\n\n\tif err := getOffsets(); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tsort.Ints(offs)\n\twantOffs := \"[0 262144 358150 433428 525437 602690 675039 748088 816210 898743 980993 1053410 1120438 1188662 1265192 1332541 1398316 1463899 1530446 1596700 1668839 1738909 1817065 1891025 1961646 2031127 2099232 2170640 2238692 2304743 2374317 2440449 2514327 2582670 2653257 2753975 2827518 2905783 2975426 3053820 3134057 3204879 3271019 3346750 3421351 3487420 3557939 3624006 3701093 3768863 3842013 3918267 4001933 4069157 4139132 4208109 4281390 4348801 4422695 4490535 4568111 4642769 4709005 4785526 4866313 4933575 5005564 5071633 5152695 5227716]\"\n\tgotOffs := fmt.Sprintf(\"%v\", offs)\n\tif wantOffs != gotOffs {\n\t\tt.Errorf(\"Got chunk offsets %v; want %v\", gotOffs, wantOffs)\n\t}\n\n\t\/\/ Now force a fetch failure on one of the filereader schema chunks, to\n\t\/\/ force a failure of GetChunkOffsets\n\terrFetch := errors.New(\"fake fetch error\")\n\tvar fetches struct {\n\t\tsync.Mutex\n\t\tn int\n\t}\n\tsto.FetchErr = func() error {\n\t\tfetches.Lock()\n\t\tdefer fetches.Unlock()\n\t\tfetches.n++\n\t\tif fetches.n == 1 {\n\t\t\treturn nil\n\t\t}\n\t\treturn errFetch\n\t}\n\n\tfr, err = NewFileReader(sto, br)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := getOffsets(); fmt.Sprint(err) != \"schema\/filereader: fetching file schema blob: fake fetch error\" {\n\t\tt.Errorf(\"expected second call of GetChunkOffsets to return wrapped errFetch; got %v\", err)\n\t}\n}\n\ntype randReader struct {\n\tseed int64\n\tlength int\n\trnd *rand.Rand \/\/ lazy init\n\tremain int \/\/ lazy init\n}\n\nfunc (r *randReader) Read(p []byte) (n int, err error) {\n\tif r.rnd == nil {\n\t\tr.rnd = rand.New(rand.NewSource(r.seed))\n\t\tr.remain = r.length\n\t}\n\tif r.remain == 0 {\n\t\treturn 0, io.EOF\n\t}\n\tif len(p) > r.remain {\n\t\tp = p[:r.remain]\n\t}\n\tfor i := range p {\n\t\tp[i] = byte(r.rnd.Intn(256))\n\t}\n\tr.remain -= len(p)\n\treturn len(p), nil\n}\nschema: fix test I broken when removing GetChunkOffsets\/*\nCopyright 2012 Google Inc.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage schema\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"math\/rand\"\n\t\"sort\"\n\t\"sync\"\n\t\"testing\"\n\n\t\"camlistore.org\/pkg\/blob\"\n\t\"camlistore.org\/pkg\/blobserver\/stats\"\n\t\"camlistore.org\/pkg\/test\"\n)\n\nfunc TestWriteFileMap(t *testing.T) {\n\tm := NewFileMap(\"test-file\")\n\tr := &randReader{seed: 123, length: 5 << 20}\n\tsr := new(stats.Receiver)\n\tvar buf bytes.Buffer\n\tbr, err := WriteFileMap(sr, m, io.TeeReader(r, &buf))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tt.Logf(\"Got root file %v; %d blobs, %d bytes\", br, sr.NumBlobs(), sr.SumBlobSize())\n\tsizes := sr.Sizes()\n\tt.Logf(\"Sizes are %v\", sizes)\n\n\t\/\/ TODO(bradfitz): these are fragile tests and mostly just a placeholder.\n\t\/\/ Real tests to add:\n\t\/\/ -- no \"bytes\" schema with a single \"blobref\"\n\t\/\/ -- more seeds (including some that tickle the above)\n\t\/\/ -- file reader reading back the root gets the same sha1 content back\n\t\/\/ (will require keeping the full data in our stats receiver, not\n\t\/\/ just the size)\n\t\/\/ -- well-balanced tree\n\t\/\/ -- nothing too big, nothing too small.\n\tif g, w := br.String(), \"sha1-95a5d2686b239e36dff3aeb5a45ed18153121835\"; g != w {\n\t\tt.Errorf(\"root blobref = %v; want %v\", g, w)\n\t}\n\tif g, w := sr.NumBlobs(), 88; g != w {\n\t\tt.Errorf(\"num blobs = %v; want %v\", g, w)\n\t}\n\tif g, w := sr.SumBlobSize(), int64(5252655); g != w {\n\t\tt.Errorf(\"sum blob size = %v; want %v\", g, w)\n\t}\n\tif g, w := sizes[len(sizes)-1], 262144; g != w {\n\t\tt.Errorf(\"biggest blob is %d; want %d\", g, w)\n\t}\n}\n\nfunc TestWriteThenRead(t *testing.T) {\n\tm := NewFileMap(\"test-file\")\n\tconst size = 5 << 20\n\tr := &randReader{seed: 123, length: size}\n\tsto := new(test.Fetcher)\n\tvar buf bytes.Buffer\n\tbr, err := WriteFileMap(sto, m, io.TeeReader(r, &buf))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tvar got bytes.Buffer\n\tfr, err := NewFileReader(sto, br)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tn, err := io.Copy(&got, fr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif n != size {\n\t\tt.Errorf(\"read back %d bytes; want %d\", n, size)\n\t}\n\tif !bytes.Equal(buf.Bytes(), got.Bytes()) {\n\t\tt.Error(\"bytes differ\")\n\t}\n\n\tvar offs []int\n\n\tgetOffsets := func() error {\n\t\toffs = offs[:0]\n\t\tvar off int\n\t\treturn fr.ForeachChunk(func(schemaRef blob.Ref, p BytesPart) error {\n\t\t\toffs = append(offs, off)\n\t\t\toff += int(p.Size)\n\t\t\treturn err\n\t\t})\n\t}\n\n\tif err := getOffsets(); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tsort.Ints(offs)\n\twantOffs := \"[0 262144 358150 433428 525437 602690 675039 748088 816210 898743 980993 1053410 1120438 1188662 1265192 1332541 1398316 1463899 1530446 1596700 1668839 1738909 1817065 1891025 1961646 2031127 2099232 2170640 2238692 2304743 2374317 2440449 2514327 2582670 2653257 2753975 2827518 2905783 2975426 3053820 3134057 3204879 3271019 3346750 3421351 3487420 3557939 3624006 3701093 3768863 3842013 3918267 4001933 4069157 4139132 4208109 4281390 4348801 4422695 4490535 4568111 4642769 4709005 4785526 4866313 4933575 5005564 5071633 5152695 5227716]\"\n\tgotOffs := fmt.Sprintf(\"%v\", offs)\n\tif wantOffs != gotOffs {\n\t\tt.Errorf(\"Got chunk offsets %v; want %v\", gotOffs, wantOffs)\n\t}\n\n\t\/\/ Now force a fetch failure on one of the filereader schema chunks, to\n\t\/\/ force a failure of GetChunkOffsets\n\terrFetch := errors.New(\"fake fetch error\")\n\tvar fetches struct {\n\t\tsync.Mutex\n\t\tn int\n\t}\n\tsto.FetchErr = func() error {\n\t\tfetches.Lock()\n\t\tdefer fetches.Unlock()\n\t\tfetches.n++\n\t\tif fetches.n == 1 {\n\t\t\treturn nil\n\t\t}\n\t\treturn errFetch\n\t}\n\n\tfr, err = NewFileReader(sto, br)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := getOffsets(); fmt.Sprint(err) != \"schema\/filereader: fetching file schema blob: fake fetch error\" {\n\t\tt.Errorf(\"expected second call of GetChunkOffsets to return wrapped errFetch; got %v\", err)\n\t}\n}\n\ntype randReader struct {\n\tseed int64\n\tlength int\n\trnd *rand.Rand \/\/ lazy init\n\tremain int \/\/ lazy init\n}\n\nfunc (r *randReader) Read(p []byte) (n int, err error) {\n\tif r.rnd == nil {\n\t\tr.rnd = rand.New(rand.NewSource(r.seed))\n\t\tr.remain = r.length\n\t}\n\tif r.remain == 0 {\n\t\treturn 0, io.EOF\n\t}\n\tif len(p) > r.remain {\n\t\tp = p[:r.remain]\n\t}\n\tfor i := range p {\n\t\tp[i] = byte(r.rnd.Intn(256))\n\t}\n\tr.remain -= len(p)\n\treturn len(p), nil\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (C) 2016 Nippon Telegraph and Telephone 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\n\/\/ implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/go:build openbsd\n\/\/ +build openbsd\n\npackage server\n\nimport (\n\t\"encoding\/binary\"\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n\t\"syscall\"\n\t\"unsafe\"\n)\n\nconst (\n\tPF_KEY_V2 = 2\n\n\tSADB_X_SATYPE_TCPSIGNATURE = 8\n\n\tSADB_EXT_SA = 1\n\tSADB_EXT_ADDRESS_SRC = 5\n\tSADB_EXT_ADDRESS_DST = 6\n\tSADB_EXT_KEY_AUTH = 8\n\tSADB_EXT_SPIRANGE = 16\n\n\tSADB_GETSPI = 1\n\tSADB_UPDATE = 2\n\tSADB_DELETE = 4\n\n\tSADB_X_EALG_AES = 12\n\n\tSADB_SASTATE_MATURE = 1\n)\n\ntype sadbMsg struct {\n\tsadbMsgVersion uint8\n\tsadbMsgType uint8\n\tsadbMsgErrno uint8\n\tsadbMsgSatype uint8\n\tsadbMsgLen uint16\n\tsadbMsgReserved uint16\n\tsadbMsgSeq uint32\n\tsadbMsgPid uint32\n}\n\nfunc (s *sadbMsg) DecodeFromBytes(data []byte) error {\n\tif len(data) < SADB_MSG_SIZE {\n\t\treturn fmt.Errorf(\"too short for sadbMsg %d\", len(data))\n\t}\n\ts.sadbMsgVersion = data[0]\n\ts.sadbMsgType = data[1]\n\ts.sadbMsgErrno = data[2]\n\ts.sadbMsgSatype = data[3]\n\ts.sadbMsgLen = binary.LittleEndian.Uint16(data[4:6])\n\ts.sadbMsgSeq = binary.LittleEndian.Uint32(data[8:12])\n\ts.sadbMsgPid = binary.LittleEndian.Uint32(data[12:16])\n\treturn nil\n}\n\ntype sadbSpirange struct {\n\tsadbSpirangeLen uint16\n\tsadbSpirangeExttype uint16\n\tsadbSpirangeMin uint32\n\tsadbSpirangeMax uint32\n\tsadbSpirangeReserved uint32\n}\n\ntype sadbAddress struct {\n\tsadbAddressLen uint16\n\tsadbAddressExttype uint16\n\tsadbAddressReserved uint32\n}\n\ntype sadbExt struct {\n\tsadbExtLen uint16\n\tsadbExtType uint16\n}\n\ntype sadbSa struct {\n\tsadbSaLen uint16\n\tsadbSaExttype uint16\n\tsadbSaSpi uint32\n\tsadbSaReplay uint8\n\tsadbSaState uint8\n\tsadbSaAuth uint8\n\tsadbSaEncrypt uint8\n\tsadbSaFlags uint32\n}\n\ntype sadbKey struct {\n\tsadbKeyLen uint16\n\tsadbKeyExttype uint16\n\tsadbKeyBits uint16\n\tsadbKeyReserved uint16\n}\n\nconst (\n\tSADB_MSG_SIZE = int(unsafe.Sizeof(sadbMsg{}))\n\tSADB_SPIRANGE_SIZE = int(unsafe.Sizeof(sadbSpirange{}))\n\tSADB_ADDRESS_SIZE = int(unsafe.Sizeof(sadbAddress{}))\n\tSADB_SA_SIZE = int(unsafe.Sizeof(sadbSa{}))\n\tSADB_KEY_SIZE = int(unsafe.Sizeof(sadbKey{}))\n)\n\ntype sockaddrIn struct {\n\tssLen uint8\n\tssFamily uint8\n\tssPort uint16\n\tssAddr uint32\n\tpad [8]byte\n}\n\nfunc newSockaddrIn(addr string) sockaddrIn {\n\tif len(addr) == 0 {\n\t\treturn sockaddrIn{\n\t\t\tssLen: 16,\n\t\t}\n\t}\n\tv := net.ParseIP(addr).To4()\n\treturn sockaddrIn{\n\t\tssAddr: uint32(v[3])<<24 | uint32(v[2])<<16 | uint32(v[1])<<8 | uint32(v[0]),\n\t\tssLen: 16,\n\t\tssFamily: syscall.AF_INET,\n\t}\n}\n\nfunc roundUp(v int) int {\n\tif v%8 != 0 {\n\t\tv += 8 - v%8\n\t}\n\treturn v\n}\n\nfunc b(p unsafe.Pointer, length int) []byte {\n\tbuf := make([]byte, length)\n\tfor i := 0; i < length; i++ {\n\t\tbuf[i] = *(*byte)(p)\n\t\tp = unsafe.Pointer(uintptr(p) + 1)\n\t}\n\treturn buf\n}\n\nvar seq uint32\nvar fd int\n\nvar spiInMap map[string]uint32 = map[string]uint32{}\nvar spiOutMap map[string]uint32 = map[string]uint32{}\n\nfunc pfkeyReply() (spi uint32, err error) {\n\tbuf := make([]byte, SADB_MSG_SIZE)\n\tif count, _, _, _, _ := syscall.Recvmsg(fd, buf, nil, syscall.MSG_PEEK); count != len(buf) {\n\t\treturn spi, fmt.Errorf(\"incomplete sadb msg %d %d\", len(buf), count)\n\t}\n\th := sadbMsg{}\n\th.DecodeFromBytes(buf)\n\tif h.sadbMsgErrno != 0 {\n\t\treturn spi, fmt.Errorf(\"sadb msg reply error %d\", h.sadbMsgErrno)\n\t}\n\n\tif h.sadbMsgSeq != seq {\n\t\treturn spi, fmt.Errorf(\"sadb msg sequence doesn't match %d %d\", h.sadbMsgSeq, seq)\n\t}\n\n\tif h.sadbMsgPid != uint32(os.Getpid()) {\n\t\treturn spi, fmt.Errorf(\"sadb msg pid doesn't match %d %d\", h.sadbMsgPid, os.Getpid())\n\t}\n\n\tbuf = make([]byte, int(8*h.sadbMsgLen))\n\tif count, _, _, _, _ := syscall.Recvmsg(fd, buf, nil, 0); count != len(buf) {\n\t\treturn spi, fmt.Errorf(\"incomplete sadb msg body %d %d\", len(buf), count)\n\t}\n\n\tbuf = buf[SADB_MSG_SIZE:]\n\n\tfor len(buf) >= 4 {\n\t\tl := binary.LittleEndian.Uint16(buf[0:2]) * 8\n\t\tt := binary.LittleEndian.Uint16(buf[2:4])\n\t\tif t == SADB_EXT_SA {\n\t\t\treturn binary.LittleEndian.Uint32(buf[4:8]), nil\n\t\t}\n\n\t\tif len(buf) <= int(l) {\n\t\t\tbreak\n\t\t}\n\t\tbuf = buf[l:]\n\t}\n\treturn spi, err\n}\n\nfunc sendSadbMsg(msg *sadbMsg, body []byte) (err error) {\n\tif fd == 0 {\n\t\tfd, err = syscall.Socket(syscall.AF_KEY, syscall.SOCK_RAW, PF_KEY_V2)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tseq++\n\tmsg.sadbMsgSeq = seq\n\tmsg.sadbMsgLen = uint16((len(body) + SADB_MSG_SIZE) \/ 8)\n\n\tbuf := append(b(unsafe.Pointer(msg), SADB_MSG_SIZE), body...)\n\n\tr, err := syscall.Write(fd, buf)\n\tif r != len(buf) {\n\t\treturn fmt.Errorf(\"short write %d %d\", r, len(buf))\n\t}\n\treturn err\n}\n\nfunc rfkeyRequest(msgType uint8, src, dst string, spi uint32, key string) error {\n\th := sadbMsg{\n\t\tsadbMsgVersion: PF_KEY_V2,\n\t\tsadbMsgType: msgType,\n\t\tsadbMsgSatype: SADB_X_SATYPE_TCPSIGNATURE,\n\t\tsadbMsgPid: uint32(os.Getpid()),\n\t}\n\n\tssrc := newSockaddrIn(src)\n\tsa_src := sadbAddress{\n\t\tsadbAddressExttype: SADB_EXT_ADDRESS_SRC,\n\t\tsadbAddressLen: uint16(SADB_ADDRESS_SIZE+roundUp(int(ssrc.ssLen))) \/ 8,\n\t}\n\n\tsdst := newSockaddrIn(dst)\n\tsa_dst := sadbAddress{\n\t\tsadbAddressExttype: SADB_EXT_ADDRESS_DST,\n\t\tsadbAddressLen: uint16(SADB_ADDRESS_SIZE+roundUp(int(sdst.ssLen))) \/ 8,\n\t}\n\n\tbuf := make([]byte, 0)\n\tswitch msgType {\n\tcase SADB_UPDATE, SADB_DELETE:\n\t\tsa := sadbSa{\n\t\t\tsadbSaLen: uint16(SADB_SA_SIZE \/ 8),\n\t\t\tsadbSaExttype: SADB_EXT_SA,\n\t\t\tsadbSaSpi: spi,\n\t\t\tsadbSaState: SADB_SASTATE_MATURE,\n\t\t\tsadbSaEncrypt: SADB_X_EALG_AES,\n\t\t}\n\t\tbuf = append(buf, b(unsafe.Pointer(&sa), SADB_SA_SIZE)...)\n\tcase SADB_GETSPI:\n\t\tspirange := sadbSpirange{\n\t\t\tsadbSpirangeLen: uint16(SADB_SPIRANGE_SIZE) \/ 8,\n\t\t\tsadbSpirangeExttype: SADB_EXT_SPIRANGE,\n\t\t\tsadbSpirangeMin: 0x100,\n\t\t\tsadbSpirangeMax: 0xffffffff,\n\t\t}\n\t\tbuf = append(buf, b(unsafe.Pointer(&spirange), SADB_SPIRANGE_SIZE)...)\n\t}\n\n\tbuf = append(buf, b(unsafe.Pointer(&sa_dst), SADB_ADDRESS_SIZE)...)\n\tbuf = append(buf, b(unsafe.Pointer(&sdst), roundUp(int(sdst.ssLen)))...)\n\tbuf = append(buf, b(unsafe.Pointer(&sa_src), SADB_ADDRESS_SIZE)...)\n\tbuf = append(buf, b(unsafe.Pointer(&ssrc), roundUp(int(ssrc.ssLen)))...)\n\n\tswitch msgType {\n\tcase SADB_UPDATE:\n\t\tkeylen := roundUp(len(key))\n\t\tsa_akey := sadbKey{\n\t\t\tsadbKeyLen: uint16((SADB_KEY_SIZE + keylen) \/ 8),\n\t\t\tsadbKeyExttype: SADB_EXT_KEY_AUTH,\n\t\t\tsadbKeyBits: uint16(len(key) * 8),\n\t\t}\n\t\tk := []byte(key)\n\t\tif pad := keylen - len(k); pad != 0 {\n\t\t\tk = append(k, make([]byte, pad)...)\n\t\t}\n\t\tbuf = append(buf, b(unsafe.Pointer(&sa_akey), SADB_KEY_SIZE)...)\n\t\tbuf = append(buf, k...)\n\t}\n\n\treturn sendSadbMsg(&h, buf)\n}\n\nfunc saAdd(address, key string) error {\n\tf := func(src, dst string) error {\n\t\tif err := rfkeyRequest(SADB_GETSPI, src, dst, 0, \"\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tspi, err := pfkeyReply()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif src == \"\" {\n\t\t\tspiOutMap[address] = spi\n\t\t} else {\n\t\t\tspiInMap[address] = spi\n\t\t}\n\n\t\tif err := rfkeyRequest(SADB_UPDATE, src, dst, spi, key); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = pfkeyReply()\n\t\treturn err\n\t}\n\n\tif err := f(address, \"\"); err != nil {\n\t\treturn err\n\t}\n\n\treturn f(\"\", address)\n}\n\nfunc saDelete(address string) error {\n\tif spi, y := spiInMap[address]; y {\n\t\tif err := rfkeyRequest(SADB_DELETE, address, \"\", spi, \"\"); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to delete md5 for incoming: %s\", err)\n\t\t}\n\t} else {\n\t\treturn fmt.Errorf(\"can't find spi for md5 for incoming: %s\", err)\n\t}\n\n\tif spi, y := spiOutMap[address]; y {\n\t\tif err := rfkeyRequest(SADB_DELETE, \"\", address, spi, \"\"); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to delete md5 for outgoing: %s\", err)\n\t\t}\n\t} else {\n\t\treturn fmt.Errorf(\"can't find spi for md5 for outgoing: %s\", err)\n\t}\n\treturn nil\n}\n\nconst (\n\ttcpMD5SIG = 0x4 \/\/ TCP MD5 Signature (RFC2385)\n\tipv6MinHopCount = 73 \/\/ Generalized TTL Security Mechanism (RFC5082)\n)\n\nfunc setsockoptTcpMD5Sig(sc syscall.RawConn, address string, key string) error {\n\tif err := setsockOptInt(sc, syscall.IPPROTO_TCP, tcpMD5SIG, 1); err != nil {\n\t\treturn err\n\t}\n\tif len(key) > 0 {\n\t\treturn saAdd(address, key)\n\t}\n\treturn saDelete(address)\n}\n\nfunc setTCPMD5SigSockopt(l *net.TCPListener, address string, key string) error {\n\tsc, err := l.SyscallConn()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn setsockoptTcpMD5Sig(sc, address, key)\n}\n\nfunc setTCPTTLSockopt(conn *net.TCPConn, ttl int) error {\n\tfamily := extractFamilyFromTCPConn(conn)\n\tsc, err := conn.SyscallConn()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn setsockoptIpTtl(sc, family, ttl)\n}\n\nfunc setTCPMinTTLSockopt(conn *net.TCPConn, ttl int) error {\n\tfamily := extractFamilyFromTCPConn(conn)\n\tsc, err := conn.SyscallConn()\n\tif err != nil {\n\t\treturn err\n\t}\n\tlevel := syscall.IPPROTO_IP\n\tname := syscall.IP_MINTTL\n\tif family == syscall.AF_INET6 {\n\t\tlevel = syscall.IPPROTO_IPV6\n\t\tname = ipv6MinHopCount\n\t}\n\treturn setsockOptInt(sc, level, name, ttl)\n}\n\nfunc setBindToDevSockopt(sc syscall.RawConn, device string) error {\n\treturn fmt.Errorf(\"binding connection to a device is not supported\")\n}\n\nfunc dialerControl(logger log.Logger, network, address string, c syscall.RawConn, ttl, minTtl uint8, password string, bindInterface string) error {\n\tif password != \"\" {\n\t\tlogger.Warn(\"setting md5 for active connection is not supported\",\n\t\t\t\"Topic\", \"Peer\",\n\t\t\t\"Key\", address)\n\t}\n\tif ttl != 0 {\n\t\tlogger.Warn(\"setting ttl for active connection is not supported\",\n\t\t\t\"Topic\", \"Peer\",\n\t\t\t\"Key\", address)\n\t}\n\tif minTtl != 0 {\n\t\tlogger.Warn(\"setting min ttl for active connection is not supported\",\n\t\t\t\"Topic\", \"Peer\",\n\t\t\t\"Key\", address)\n\t}\n\treturn nil\n}\nfix openbsd build\/\/ Copyright (C) 2016 Nippon Telegraph and Telephone 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\n\/\/ implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/go:build openbsd\n\/\/ +build openbsd\n\npackage server\n\nimport (\n\t\"encoding\/binary\"\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n\t\"syscall\"\n\t\"unsafe\"\n\n\t\"github.com\/osrg\/gobgp\/v3\/pkg\/log\"\n)\n\nconst (\n\tPF_KEY_V2 = 2\n\n\tSADB_X_SATYPE_TCPSIGNATURE = 8\n\n\tSADB_EXT_SA = 1\n\tSADB_EXT_ADDRESS_SRC = 5\n\tSADB_EXT_ADDRESS_DST = 6\n\tSADB_EXT_KEY_AUTH = 8\n\tSADB_EXT_SPIRANGE = 16\n\n\tSADB_GETSPI = 1\n\tSADB_UPDATE = 2\n\tSADB_DELETE = 4\n\n\tSADB_X_EALG_AES = 12\n\n\tSADB_SASTATE_MATURE = 1\n)\n\ntype sadbMsg struct {\n\tsadbMsgVersion uint8\n\tsadbMsgType uint8\n\tsadbMsgErrno uint8\n\tsadbMsgSatype uint8\n\tsadbMsgLen uint16\n\tsadbMsgReserved uint16\n\tsadbMsgSeq uint32\n\tsadbMsgPid uint32\n}\n\nfunc (s *sadbMsg) DecodeFromBytes(data []byte) error {\n\tif len(data) < SADB_MSG_SIZE {\n\t\treturn fmt.Errorf(\"too short for sadbMsg %d\", len(data))\n\t}\n\ts.sadbMsgVersion = data[0]\n\ts.sadbMsgType = data[1]\n\ts.sadbMsgErrno = data[2]\n\ts.sadbMsgSatype = data[3]\n\ts.sadbMsgLen = binary.LittleEndian.Uint16(data[4:6])\n\ts.sadbMsgSeq = binary.LittleEndian.Uint32(data[8:12])\n\ts.sadbMsgPid = binary.LittleEndian.Uint32(data[12:16])\n\treturn nil\n}\n\ntype sadbSpirange struct {\n\tsadbSpirangeLen uint16\n\tsadbSpirangeExttype uint16\n\tsadbSpirangeMin uint32\n\tsadbSpirangeMax uint32\n\tsadbSpirangeReserved uint32\n}\n\ntype sadbAddress struct {\n\tsadbAddressLen uint16\n\tsadbAddressExttype uint16\n\tsadbAddressReserved uint32\n}\n\ntype sadbExt struct {\n\tsadbExtLen uint16\n\tsadbExtType uint16\n}\n\ntype sadbSa struct {\n\tsadbSaLen uint16\n\tsadbSaExttype uint16\n\tsadbSaSpi uint32\n\tsadbSaReplay uint8\n\tsadbSaState uint8\n\tsadbSaAuth uint8\n\tsadbSaEncrypt uint8\n\tsadbSaFlags uint32\n}\n\ntype sadbKey struct {\n\tsadbKeyLen uint16\n\tsadbKeyExttype uint16\n\tsadbKeyBits uint16\n\tsadbKeyReserved uint16\n}\n\nconst (\n\tSADB_MSG_SIZE = int(unsafe.Sizeof(sadbMsg{}))\n\tSADB_SPIRANGE_SIZE = int(unsafe.Sizeof(sadbSpirange{}))\n\tSADB_ADDRESS_SIZE = int(unsafe.Sizeof(sadbAddress{}))\n\tSADB_SA_SIZE = int(unsafe.Sizeof(sadbSa{}))\n\tSADB_KEY_SIZE = int(unsafe.Sizeof(sadbKey{}))\n)\n\ntype sockaddrIn struct {\n\tssLen uint8\n\tssFamily uint8\n\tssPort uint16\n\tssAddr uint32\n\tpad [8]byte\n}\n\nfunc newSockaddrIn(addr string) sockaddrIn {\n\tif len(addr) == 0 {\n\t\treturn sockaddrIn{\n\t\t\tssLen: 16,\n\t\t}\n\t}\n\tv := net.ParseIP(addr).To4()\n\treturn sockaddrIn{\n\t\tssAddr: uint32(v[3])<<24 | uint32(v[2])<<16 | uint32(v[1])<<8 | uint32(v[0]),\n\t\tssLen: 16,\n\t\tssFamily: syscall.AF_INET,\n\t}\n}\n\nfunc roundUp(v int) int {\n\tif v%8 != 0 {\n\t\tv += 8 - v%8\n\t}\n\treturn v\n}\n\nfunc b(p unsafe.Pointer, length int) []byte {\n\tbuf := make([]byte, length)\n\tfor i := 0; i < length; i++ {\n\t\tbuf[i] = *(*byte)(p)\n\t\tp = unsafe.Pointer(uintptr(p) + 1)\n\t}\n\treturn buf\n}\n\nvar seq uint32\nvar fd int\n\nvar spiInMap map[string]uint32 = map[string]uint32{}\nvar spiOutMap map[string]uint32 = map[string]uint32{}\n\nfunc pfkeyReply() (spi uint32, err error) {\n\tbuf := make([]byte, SADB_MSG_SIZE)\n\tif count, _, _, _, _ := syscall.Recvmsg(fd, buf, nil, syscall.MSG_PEEK); count != len(buf) {\n\t\treturn spi, fmt.Errorf(\"incomplete sadb msg %d %d\", len(buf), count)\n\t}\n\th := sadbMsg{}\n\th.DecodeFromBytes(buf)\n\tif h.sadbMsgErrno != 0 {\n\t\treturn spi, fmt.Errorf(\"sadb msg reply error %d\", h.sadbMsgErrno)\n\t}\n\n\tif h.sadbMsgSeq != seq {\n\t\treturn spi, fmt.Errorf(\"sadb msg sequence doesn't match %d %d\", h.sadbMsgSeq, seq)\n\t}\n\n\tif h.sadbMsgPid != uint32(os.Getpid()) {\n\t\treturn spi, fmt.Errorf(\"sadb msg pid doesn't match %d %d\", h.sadbMsgPid, os.Getpid())\n\t}\n\n\tbuf = make([]byte, int(8*h.sadbMsgLen))\n\tif count, _, _, _, _ := syscall.Recvmsg(fd, buf, nil, 0); count != len(buf) {\n\t\treturn spi, fmt.Errorf(\"incomplete sadb msg body %d %d\", len(buf), count)\n\t}\n\n\tbuf = buf[SADB_MSG_SIZE:]\n\n\tfor len(buf) >= 4 {\n\t\tl := binary.LittleEndian.Uint16(buf[0:2]) * 8\n\t\tt := binary.LittleEndian.Uint16(buf[2:4])\n\t\tif t == SADB_EXT_SA {\n\t\t\treturn binary.LittleEndian.Uint32(buf[4:8]), nil\n\t\t}\n\n\t\tif len(buf) <= int(l) {\n\t\t\tbreak\n\t\t}\n\t\tbuf = buf[l:]\n\t}\n\treturn spi, err\n}\n\nfunc sendSadbMsg(msg *sadbMsg, body []byte) (err error) {\n\tif fd == 0 {\n\t\tfd, err = syscall.Socket(syscall.AF_KEY, syscall.SOCK_RAW, PF_KEY_V2)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tseq++\n\tmsg.sadbMsgSeq = seq\n\tmsg.sadbMsgLen = uint16((len(body) + SADB_MSG_SIZE) \/ 8)\n\n\tbuf := append(b(unsafe.Pointer(msg), SADB_MSG_SIZE), body...)\n\n\tr, err := syscall.Write(fd, buf)\n\tif r != len(buf) {\n\t\treturn fmt.Errorf(\"short write %d %d\", r, len(buf))\n\t}\n\treturn err\n}\n\nfunc rfkeyRequest(msgType uint8, src, dst string, spi uint32, key string) error {\n\th := sadbMsg{\n\t\tsadbMsgVersion: PF_KEY_V2,\n\t\tsadbMsgType: msgType,\n\t\tsadbMsgSatype: SADB_X_SATYPE_TCPSIGNATURE,\n\t\tsadbMsgPid: uint32(os.Getpid()),\n\t}\n\n\tssrc := newSockaddrIn(src)\n\tsa_src := sadbAddress{\n\t\tsadbAddressExttype: SADB_EXT_ADDRESS_SRC,\n\t\tsadbAddressLen: uint16(SADB_ADDRESS_SIZE+roundUp(int(ssrc.ssLen))) \/ 8,\n\t}\n\n\tsdst := newSockaddrIn(dst)\n\tsa_dst := sadbAddress{\n\t\tsadbAddressExttype: SADB_EXT_ADDRESS_DST,\n\t\tsadbAddressLen: uint16(SADB_ADDRESS_SIZE+roundUp(int(sdst.ssLen))) \/ 8,\n\t}\n\n\tbuf := make([]byte, 0)\n\tswitch msgType {\n\tcase SADB_UPDATE, SADB_DELETE:\n\t\tsa := sadbSa{\n\t\t\tsadbSaLen: uint16(SADB_SA_SIZE \/ 8),\n\t\t\tsadbSaExttype: SADB_EXT_SA,\n\t\t\tsadbSaSpi: spi,\n\t\t\tsadbSaState: SADB_SASTATE_MATURE,\n\t\t\tsadbSaEncrypt: SADB_X_EALG_AES,\n\t\t}\n\t\tbuf = append(buf, b(unsafe.Pointer(&sa), SADB_SA_SIZE)...)\n\tcase SADB_GETSPI:\n\t\tspirange := sadbSpirange{\n\t\t\tsadbSpirangeLen: uint16(SADB_SPIRANGE_SIZE) \/ 8,\n\t\t\tsadbSpirangeExttype: SADB_EXT_SPIRANGE,\n\t\t\tsadbSpirangeMin: 0x100,\n\t\t\tsadbSpirangeMax: 0xffffffff,\n\t\t}\n\t\tbuf = append(buf, b(unsafe.Pointer(&spirange), SADB_SPIRANGE_SIZE)...)\n\t}\n\n\tbuf = append(buf, b(unsafe.Pointer(&sa_dst), SADB_ADDRESS_SIZE)...)\n\tbuf = append(buf, b(unsafe.Pointer(&sdst), roundUp(int(sdst.ssLen)))...)\n\tbuf = append(buf, b(unsafe.Pointer(&sa_src), SADB_ADDRESS_SIZE)...)\n\tbuf = append(buf, b(unsafe.Pointer(&ssrc), roundUp(int(ssrc.ssLen)))...)\n\n\tswitch msgType {\n\tcase SADB_UPDATE:\n\t\tkeylen := roundUp(len(key))\n\t\tsa_akey := sadbKey{\n\t\t\tsadbKeyLen: uint16((SADB_KEY_SIZE + keylen) \/ 8),\n\t\t\tsadbKeyExttype: SADB_EXT_KEY_AUTH,\n\t\t\tsadbKeyBits: uint16(len(key) * 8),\n\t\t}\n\t\tk := []byte(key)\n\t\tif pad := keylen - len(k); pad != 0 {\n\t\t\tk = append(k, make([]byte, pad)...)\n\t\t}\n\t\tbuf = append(buf, b(unsafe.Pointer(&sa_akey), SADB_KEY_SIZE)...)\n\t\tbuf = append(buf, k...)\n\t}\n\n\treturn sendSadbMsg(&h, buf)\n}\n\nfunc saAdd(address, key string) error {\n\tf := func(src, dst string) error {\n\t\tif err := rfkeyRequest(SADB_GETSPI, src, dst, 0, \"\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tspi, err := pfkeyReply()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif src == \"\" {\n\t\t\tspiOutMap[address] = spi\n\t\t} else {\n\t\t\tspiInMap[address] = spi\n\t\t}\n\n\t\tif err := rfkeyRequest(SADB_UPDATE, src, dst, spi, key); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = pfkeyReply()\n\t\treturn err\n\t}\n\n\tif err := f(address, \"\"); err != nil {\n\t\treturn err\n\t}\n\n\treturn f(\"\", address)\n}\n\nfunc saDelete(address string) error {\n\tif spi, y := spiInMap[address]; y {\n\t\tif err := rfkeyRequest(SADB_DELETE, address, \"\", spi, \"\"); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to delete md5 for incoming: %s\", err)\n\t\t}\n\t} else {\n\t\treturn fmt.Errorf(\"can't find spi for md5 for incoming\")\n\t}\n\n\tif spi, y := spiOutMap[address]; y {\n\t\tif err := rfkeyRequest(SADB_DELETE, \"\", address, spi, \"\"); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to delete md5 for outgoing: %s\", err)\n\t\t}\n\t} else {\n\t\treturn fmt.Errorf(\"can't find spi for md5 for outgoing\")\n\t}\n\treturn nil\n}\n\nconst (\n\ttcpMD5SIG = 0x4 \/\/ TCP MD5 Signature (RFC2385)\n\tipv6MinHopCount = 73 \/\/ Generalized TTL Security Mechanism (RFC5082)\n)\n\nfunc setsockoptTcpMD5Sig(sc syscall.RawConn, address string, key string) error {\n\tif err := setsockOptInt(sc, syscall.IPPROTO_TCP, tcpMD5SIG, 1); err != nil {\n\t\treturn err\n\t}\n\tif len(key) > 0 {\n\t\treturn saAdd(address, key)\n\t}\n\treturn saDelete(address)\n}\n\nfunc setTCPMD5SigSockopt(l *net.TCPListener, address string, key string) error {\n\tsc, err := l.SyscallConn()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn setsockoptTcpMD5Sig(sc, address, key)\n}\n\nfunc setTCPTTLSockopt(conn *net.TCPConn, ttl int) error {\n\tfamily := extractFamilyFromTCPConn(conn)\n\tsc, err := conn.SyscallConn()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn setsockoptIpTtl(sc, family, ttl)\n}\n\nfunc setTCPMinTTLSockopt(conn *net.TCPConn, ttl int) error {\n\tfamily := extractFamilyFromTCPConn(conn)\n\tsc, err := conn.SyscallConn()\n\tif err != nil {\n\t\treturn err\n\t}\n\tlevel := syscall.IPPROTO_IP\n\tname := syscall.IP_MINTTL\n\tif family == syscall.AF_INET6 {\n\t\tlevel = syscall.IPPROTO_IPV6\n\t\tname = ipv6MinHopCount\n\t}\n\treturn setsockOptInt(sc, level, name, ttl)\n}\n\nfunc setBindToDevSockopt(sc syscall.RawConn, device string) error {\n\treturn fmt.Errorf(\"binding connection to a device is not supported\")\n}\n\nfunc dialerControl(logger log.Logger, network, address string, c syscall.RawConn, ttl, minTtl uint8, password string, bindInterface string) error {\n\tif password != \"\" {\n\t\tlogger.Warn(\"setting md5 for active connection is not supported\",\n\t\t\tlog.Fields{\n\t\t\t\t\"Topic\": \"Peer\",\n\t\t\t\t\"Key\": address})\n\t}\n\tif ttl != 0 {\n\t\tlogger.Warn(\"setting ttl for active connection is not supported\",\n\t\t\tlog.Fields{\n\t\t\t\t\"Topic\": \"Peer\",\n\t\t\t\t\"Key\": address})\n\t}\n\tif minTtl != 0 {\n\t\tlogger.Warn(\"setting min ttl for active connection is not supported\",\n\t\t\tlog.Fields{\n\t\t\t\t\"Topic\": \"Peer\",\n\t\t\t\t\"Key\": address})\n\t}\n\treturn nil\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2015 Volker Dobler. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ latency.go contains checks against response time latency.\n\npackage ht\n\nimport (\n\t\"bufio\"\n\t\"encoding\/csv\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"math\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/vdobler\/ht\/cookiejar\"\n)\n\nfunc init() {\n\tRegisterCheck(&Latency{})\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Latency\n\n\/\/ Latency provides checks against percentils of the response time latency.\ntype Latency struct {\n\t\/\/ N is the number if request to measure. It should be much larger\n\t\/\/ than Concurrent. Default is 50.\n\tN int `json:\",omitempty\"`\n\n\t\/\/ Concurrent is the number of concurrent requests in flight.\n\t\/\/ Defaults to 2.\n\tConcurrent int `json:\",omitempty\"`\n\n\t\/\/ Limits is a string of the following form:\n\t\/\/ \"50% ≤ 150ms; 80% ≤ 200ms; 95% ≤ 250ms; 0.9995 ≤ 0.9s\"\n\t\/\/ The limits above would require the median of the response\n\t\/\/ times to be <= 150 ms and would allow only 1 request in 2000 to\n\t\/\/ exced 900ms.\n\t\/\/ Note that it must be the ≤ sign (U+2264), a plain < or a <=\n\t\/\/ is not recognized.\n\tLimits string `json:\",omitempty\"`\n\n\t\/\/ IndividualSessions tries to run the concurrent requests in\n\t\/\/ individual sessions: A new one for each of the Concurrent many\n\t\/\/ requests (not N many sessions).\n\t\/\/ This is done by using a fresh cookiejar so it won't work if the\n\t\/\/ request requires prior login.\n\tIndividualSessions bool `json:\",omitempty\"`\n\n\t\/\/ If SkipChecks is true no checks are performed i.e. only the\n\t\/\/ requests are executed.\n\tSkipChecks bool `json:\",omitempty\"`\n\n\t\/\/ DumpTo is the filename where the latencies are reported.\n\t\/\/ The special values \"stdout\" and \"stderr\" are recognized.\n\tDumpTo string `json:\",omitempty\"`\n\n\tlimits []latLimit\n}\n\ntype latLimit struct {\n\tq float64\n\tmax time.Duration\n}\n\n\/\/ Execute implements Check's Execute method.\nfunc (L *Latency) Execute(t *Test) error {\n\tvar dumper io.Writer\n\tswitch L.DumpTo {\n\tcase \"\":\n\t\tdumper = ioutil.Discard\n\tcase \"stdout\":\n\t\tdumper = os.Stdout\n\tcase \"stderr\":\n\t\tdumper = os.Stderr\n\tdefault:\n\t\tfile, err := os.OpenFile(L.DumpTo, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer file.Close()\n\t\tbuffile := bufio.NewWriter(file)\n\t\tdefer buffile.Flush()\n\t\tdumper = buffile\n\t}\n\tcsvWriter := csv.NewWriter(dumper)\n\tdefer csvWriter.Flush()\n\n\tconc := L.Concurrent\n\n\t\/\/ Provide a set of Test instances to be executed.\n\ttests := []*Test{}\n\tfor i := 0; i < conc; i++ {\n\t\tcpy, err := Merge(t)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcpy.Name = fmt.Sprintf(\"Latency-Test %d\", i+1)\n\t\tchecks := []Check{}\n\t\tfor _, c := range t.Checks {\n\t\t\tif _, lt := c.(*Latency); L.SkipChecks || lt {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tchecks = append(checks, c)\n\t\t}\n\t\tcpy.Checks = checks\n\t\tcpy.Execution.Verbosity = 0\n\n\t\tif t.Jar != nil {\n\t\t\tif L.IndividualSessions {\n\t\t\t\tcpy.Jar, _ = cookiejar.New(nil)\n\t\t\t} else {\n\t\t\t\tcpy.Jar = t.Jar\n\t\t\t}\n\t\t}\n\t\ttests = append(tests, cpy)\n\t}\n\n\tresults := make(chan latencyResult, 2*conc)\n\n\t\/\/ Synchronous warmup phase is much simpler.\n\twg := &sync.WaitGroup{}\n\tstarted := time.Now()\n\tprewarmed := 0\n\tfor prewarm := 0; prewarm < 2; prewarm++ {\n\t\tfor i := 0; i < conc; i++ {\n\t\t\tprewarmed++\n\t\t\twg.Add(1)\n\t\t\tgo func(ex *Test) {\n\t\t\t\tex.Run()\n\t\t\t\twg.Done()\n\t\t\t}(tests[i])\n\t\t}\n\t\twg.Wait()\n\t}\n\toffset := time.Since(started) \/ time.Duration(prewarmed*conc)\n\n\t\/\/ Conc requests generation workers execute their own test instance\n\t\/\/ until the channel running is closed.\n\tdone := make(chan bool)\n\twg2 := &sync.WaitGroup{}\n\twg2.Add(1) \/\/ Add one sentinel value.\n\tfor i := 0; i < conc; i++ {\n\t\tgo func(ex *Test, id int) {\n\t\t\tfor {\n\t\t\t\twg2.Add(1)\n\t\t\t\tex.Run()\n\t\t\t\tresults <- latencyResult{\n\t\t\t\t\tstatus: ex.Result.Status,\n\t\t\t\t\tstarted: ex.Result.Started,\n\t\t\t\t\tduration: ex.Response.Duration,\n\t\t\t\t\texecBy: id,\n\t\t\t\t}\n\t\t\t\twg2.Done()\n\t\t\t\tselect {\n\t\t\t\tcase <-done:\n\t\t\t\t\treturn\n\t\t\t\tdefault:\n\t\t\t\t}\n\t\t\t}\n\t\t}(tests[i], i)\n\t\ttime.Sleep(offset)\n\t}\n\n\t\/\/ Collect results into data and signal end via done.\n\tdata := make([]latencyResult, 2*L.N)\n\tcounters := make([]int, Bogus)\n\tseen := uint64(0) \/\/ Bitmap of testinstances who returned.\n\tall := (uint64(1) << uint(conc)) - 1\n\tmeasureFrom := 0\n\tn := 0\n\tstarted = time.Now()\n\tfor n < len(data) {\n\t\tdata[n] = <-results\n\t\tif seen == all {\n\t\t\tif measureFrom == 0 {\n\t\t\t\tmeasureFrom = n\n\t\t\t}\n\t\t\tcounters[data[n].status]++\n\t\t} else {\n\t\t\tseen |= 1 << uint(data[n].execBy)\n\t\t}\n\t\tn++\n\n\t\t\/\/ TODO: Make limits configurable?\n\t\tif counters[Pass] == L.N ||\n\t\t\tcounters[Fail] > L.N\/5 ||\n\t\t\tcounters[Error] > L.N\/20 ||\n\t\t\ttime.Since(started) > 3*time.Minute {\n\t\t\tbreak\n\t\t}\n\t}\n\tclose(done)\n\tdata = data[:n]\n\n\t\/\/ Drain rest; wait till requests currently in flight die.\n\twg2.Done() \/\/ Done with sentinel value.\n\twg2.Wait()\n\n\tcompleted := false\n\tif counters[Pass] == L.N {\n\t\tcompleted = true\n\t}\n\tfor _, r := range data {\n\t\tcsvWriter.Write([]string{\n\t\t\tt.Name,\n\t\t\tstrconv.Itoa(L.Concurrent),\n\t\t\tr.started.Format(time.RFC3339Nano),\n\t\t\tr.status.String(),\n\t\t\t(r.duration \/ time.Millisecond).String(),\n\t\t\tfmt.Sprintf(\"%t\", completed),\n\t\t})\n\t}\n\n\tlatencies := []int{}\n\tfor i, r := range data {\n\t\tif i < measureFrom || r.status != Pass {\n\t\t\tcontinue\n\t\t}\n\t\tlatencies = append(latencies, int(r.duration)\/int(time.Millisecond))\n\t}\n\tsort.Ints(latencies)\n\n\terrs := ErrorList{}\n\tfor _, lim := range L.limits {\n\t\tlat := time.Millisecond * time.Duration(quantile(latencies, lim.q))\n\t\tt.infof(\"Latency quantil (conc=%d) %0.2f%% ≤ %d ms\",\n\t\t\tconc, lim.q*100, lat\/time.Millisecond)\n\t\tif lat > lim.max {\n\t\t\terrs = append(errs, fmt.Errorf(\"%.2f%% = %s > limit %s\",\n\t\t\t\t100*lim.q, lat, lim.max))\n\t\t}\n\t}\n\n\tif !completed {\n\t\terrs = append(errs, fmt.Errorf(\"Got only %d PASS but %d FAIL and %d ERROR\",\n\t\t\tcounters[Pass], counters[Fail], counters[Error]))\n\t}\n\n\treturn errs.AsError()\n}\n\ntype latencyResult struct {\n\tstatus Status\n\tstarted time.Time\n\tduration time.Duration\n\texecBy int\n}\n\n\/\/ https:\/\/en.wikipedia.org\/wiki\/Quantile formula R-8\nfunc quantile(x []int, p float64) float64 {\n\tif len(x) == 0 {\n\t\treturn 0\n\t}\n\tN := float64(len(x))\n\tif p < 2.0\/(3.0*(N+1.0\/3.0)) {\n\t\treturn float64(x[0])\n\t}\n\tif p >= (N-1.0\/3.0)\/(N+1.0\/3.0) {\n\t\treturn float64(x[len(x)-1])\n\t}\n\n\th := (N+1.0\/3.0)*p + 1.0\/3.0\n\tfh := math.Floor(h)\n\txl := x[int(fh)-1]\n\txr := x[int(fh)]\n\n\treturn float64(xl) + (h-fh)*float64(xr-xl)\n}\n\n\/\/ Prepare implements Check's Prepare method.\nfunc (L *Latency) Prepare(*Test) error {\n\tif L.N == 0 {\n\t\tL.N = 50\n\t}\n\tif L.Concurrent == 0 {\n\t\tL.Concurrent = 2\n\t} else if L.Concurrent > 64 {\n\t\treturn fmt.Errorf(\"concurrency %d > allowed max of 64\", L.Concurrent)\n\t}\n\n\tif L.Limits == \"\" {\n\t\tL.Limits = \"75% ≤ 500\"\n\t}\n\n\tif err := L.parseLimit(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nvar _ Preparable = &Latency{}\n\nfunc (L *Latency) parseLimit() error {\n\tparts := strings.Split(strings.Trim(L.Limits, \"; \"), \";\")\n\tfor i := range parts {\n\t\ts := strings.TrimSpace(parts[i])\n\t\tq, t, err := parseQantileLimit(s)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tL.limits = append(L.limits, latLimit{q: q, max: t})\n\t}\n\n\treturn nil\n}\n\nfunc parseQantileLimit(s string) (float64, time.Duration, error) {\n\tparts := strings.SplitN(s, \"≤\", 2)\n\tif len(parts) != 2 {\n\t\treturn 0, 0, fmt.Errorf(\"Latency: missing '≤' in %q\", s)\n\t}\n\n\tq := strings.TrimSpace(strings.TrimRight(parts[0], \" %\"))\n\tquantile, err := strconv.ParseFloat(q, 64)\n\tif err != nil {\n\t\treturn 0, 0, err\n\t}\n\tif strings.Contains(parts[0], \"%\") {\n\t\tquantile \/= 100\n\t}\n\tif quantile < 0 || quantile > 1 {\n\t\treturn 0, 0, fmt.Errorf(\"Latency: quantile %.3f out of range [0,1]\", quantile)\n\t}\n\n\tb := strings.TrimSpace(strings.TrimLeft(parts[1], \"=\"))\n\n\tm, err := time.ParseDuration(b)\n\tif err != nil {\n\t\treturn 0, 0, err\n\t}\n\tif m <= 0 || m > 300*time.Second {\n\t\treturn 0, 0, fmt.Errorf(\"Latency: limit %s out of range (0,300s]\", m)\n\t}\n\n\treturn quantile, m, nil\n}\n\n\/*\n\nFor Conc==4 and RT_orig == 12 ==> offset==3\n\n 1 +---------+ +---------+ +---------+ +---------+ +---------+\n 2 +---------+ +---------+ +---------+ +---------+ +---------+\n 3 +---------+ +---------+ +---------+ +---------+ +---------+\n 4 +---------+ +---------+ +---------+ +---------+ +---------+\n | | | |\n -+--+- -+-----------+-\n offset RT_orig\n\n*\/\nht: fix reporting of latency data\/\/ Copyright 2015 Volker Dobler. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ latency.go contains checks against response time latency.\n\npackage ht\n\nimport (\n\t\"bufio\"\n\t\"encoding\/csv\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"math\"\n\t\"os\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/vdobler\/ht\/cookiejar\"\n)\n\nfunc init() {\n\tRegisterCheck(&Latency{})\n}\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Latency\n\n\/\/ Latency provides checks against percentils of the response time latency.\ntype Latency struct {\n\t\/\/ N is the number if request to measure. It should be much larger\n\t\/\/ than Concurrent. Default is 50.\n\tN int `json:\",omitempty\"`\n\n\t\/\/ Concurrent is the number of concurrent requests in flight.\n\t\/\/ Defaults to 2.\n\tConcurrent int `json:\",omitempty\"`\n\n\t\/\/ Limits is a string of the following form:\n\t\/\/ \"50% ≤ 150ms; 80% ≤ 200ms; 95% ≤ 250ms; 0.9995 ≤ 0.9s\"\n\t\/\/ The limits above would require the median of the response\n\t\/\/ times to be <= 150 ms and would allow only 1 request in 2000 to\n\t\/\/ exced 900ms.\n\t\/\/ Note that it must be the ≤ sign (U+2264), a plain < or a <=\n\t\/\/ is not recognized.\n\tLimits string `json:\",omitempty\"`\n\n\t\/\/ IndividualSessions tries to run the concurrent requests in\n\t\/\/ individual sessions: A new one for each of the Concurrent many\n\t\/\/ requests (not N many sessions).\n\t\/\/ This is done by using a fresh cookiejar so it won't work if the\n\t\/\/ request requires prior login.\n\tIndividualSessions bool `json:\",omitempty\"`\n\n\t\/\/ If SkipChecks is true no checks are performed i.e. only the\n\t\/\/ requests are executed.\n\tSkipChecks bool `json:\",omitempty\"`\n\n\t\/\/ DumpTo is the filename where the latencies are reported.\n\t\/\/ The special values \"stdout\" and \"stderr\" are recognized.\n\tDumpTo string `json:\",omitempty\"`\n\n\tlimits []latLimit\n}\n\ntype latLimit struct {\n\tq float64\n\tmax time.Duration\n}\n\n\/\/ Execute implements Check's Execute method.\nfunc (L *Latency) Execute(t *Test) error {\n\tvar dumper io.Writer\n\tswitch L.DumpTo {\n\tcase \"\":\n\t\tdumper = ioutil.Discard\n\tcase \"stdout\":\n\t\tdumper = os.Stdout\n\tcase \"stderr\":\n\t\tdumper = os.Stderr\n\tdefault:\n\t\tfile, err := os.OpenFile(L.DumpTo, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer file.Close()\n\t\tbuffile := bufio.NewWriter(file)\n\t\tdefer buffile.Flush()\n\t\tdumper = buffile\n\t}\n\tcsvWriter := csv.NewWriter(dumper)\n\tdefer csvWriter.Flush()\n\n\tconc := L.Concurrent\n\n\t\/\/ Provide a set of Test instances to be executed.\n\ttests := []*Test{}\n\tfor i := 0; i < conc; i++ {\n\t\tcpy, err := Merge(t)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcpy.Name = fmt.Sprintf(\"Latency-Test %d\", i+1)\n\t\tchecks := []Check{}\n\t\tfor _, c := range t.Checks {\n\t\t\tif _, lt := c.(*Latency); L.SkipChecks || lt {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tchecks = append(checks, c)\n\t\t}\n\t\tcpy.Checks = checks\n\t\tcpy.Execution.Verbosity = 0\n\n\t\tif t.Jar != nil {\n\t\t\tif L.IndividualSessions {\n\t\t\t\tcpy.Jar, _ = cookiejar.New(nil)\n\t\t\t} else {\n\t\t\t\tcpy.Jar = t.Jar\n\t\t\t}\n\t\t}\n\t\ttests = append(tests, cpy)\n\t}\n\n\tresults := make(chan latencyResult, 2*conc)\n\n\t\/\/ Synchronous warmup phase is much simpler.\n\twg := &sync.WaitGroup{}\n\tstarted := time.Now()\n\tprewarmed := 0\n\tfor prewarm := 0; prewarm < 2; prewarm++ {\n\t\tfor i := 0; i < conc; i++ {\n\t\t\tprewarmed++\n\t\t\twg.Add(1)\n\t\t\tgo func(ex *Test) {\n\t\t\t\tex.Run()\n\t\t\t\twg.Done()\n\t\t\t}(tests[i])\n\t\t}\n\t\twg.Wait()\n\t}\n\toffset := time.Since(started) \/ time.Duration(prewarmed*conc)\n\n\t\/\/ Conc requests generation workers execute their own test instance\n\t\/\/ until the channel running is closed.\n\tdone := make(chan bool)\n\twg2 := &sync.WaitGroup{}\n\twg2.Add(1) \/\/ Add one sentinel value.\n\tfor i := 0; i < conc; i++ {\n\t\tgo func(ex *Test, id int) {\n\t\t\tfor {\n\t\t\t\twg2.Add(1)\n\t\t\t\tex.Run()\n\t\t\t\tresults <- latencyResult{\n\t\t\t\t\tstatus: ex.Result.Status,\n\t\t\t\t\tstarted: ex.Result.Started,\n\t\t\t\t\tduration: ex.Response.Duration,\n\t\t\t\t\texecBy: id,\n\t\t\t\t}\n\t\t\t\twg2.Done()\n\t\t\t\tselect {\n\t\t\t\tcase <-done:\n\t\t\t\t\treturn\n\t\t\t\tdefault:\n\t\t\t\t}\n\t\t\t}\n\t\t}(tests[i], i)\n\t\ttime.Sleep(offset)\n\t}\n\n\t\/\/ Collect results into data and signal end via done.\n\tdata := make([]latencyResult, 2*L.N)\n\tcounters := make([]int, Bogus)\n\tseen := uint64(0) \/\/ Bitmap of testinstances who returned.\n\tall := (uint64(1) << uint(conc)) - 1\n\tmeasureFrom := 0\n\tn := 0\n\tstarted = time.Now()\n\tfor n < len(data) {\n\t\tdata[n] = <-results\n\t\tif seen == all {\n\t\t\tif measureFrom == 0 {\n\t\t\t\tmeasureFrom = n\n\t\t\t}\n\t\t\tcounters[data[n].status]++\n\t\t} else {\n\t\t\tseen |= 1 << uint(data[n].execBy)\n\t\t}\n\t\tn++\n\n\t\t\/\/ TODO: Make limits configurable?\n\t\tif counters[Pass] == L.N ||\n\t\t\tcounters[Fail] > L.N\/5 ||\n\t\t\tcounters[Error] > L.N\/20 ||\n\t\t\ttime.Since(started) > 3*time.Minute {\n\t\t\tbreak\n\t\t}\n\t}\n\tclose(done)\n\tdata = data[:n]\n\n\t\/\/ Drain rest; wait till requests currently in flight die.\n\twg2.Done() \/\/ Done with sentinel value.\n\twg2.Wait()\n\n\tcompleted := false\n\tif counters[Pass] == L.N {\n\t\tcompleted = true\n\t}\n\tZ := 1 * time.Microsecond\n\tfor _, r := range data {\n\t\td := Z * ((r.duration + Z\/2) \/ Z) \/\/ cut off nanosecond (=noise) part\n\t\tcsvWriter.Write([]string{\n\t\t\tt.Name,\n\t\t\tstrconv.Itoa(L.Concurrent),\n\t\t\tr.started.Format(time.RFC3339Nano),\n\t\t\tr.status.String(),\n\t\t\td.String(),\n\t\t\tfmt.Sprintf(\"%t\", completed),\n\t\t})\n\t}\n\n\tlatencies := []int{}\n\tfor i, r := range data {\n\t\tif i < measureFrom || r.status != Pass {\n\t\t\tcontinue\n\t\t}\n\t\tlatencies = append(latencies, int(r.duration)\/int(time.Millisecond))\n\t}\n\tsort.Ints(latencies)\n\n\terrs := ErrorList{}\n\tfor _, lim := range L.limits {\n\t\tlat := time.Millisecond * time.Duration(quantile(latencies, lim.q))\n\t\tt.infof(\"Latency quantil (conc=%d) %0.2f%% ≤ %d ms\",\n\t\t\tconc, lim.q*100, lat\/time.Millisecond)\n\t\tif lat > lim.max {\n\t\t\terrs = append(errs, fmt.Errorf(\"%.2f%% = %s > limit %s\",\n\t\t\t\t100*lim.q, lat, lim.max))\n\t\t}\n\t}\n\n\tif !completed {\n\t\terrs = append(errs, fmt.Errorf(\"Got only %d PASS but %d FAIL and %d ERROR\",\n\t\t\tcounters[Pass], counters[Fail], counters[Error]))\n\t}\n\n\treturn errs.AsError()\n}\n\ntype latencyResult struct {\n\tstatus Status\n\tstarted time.Time\n\tduration time.Duration\n\texecBy int\n}\n\n\/\/ https:\/\/en.wikipedia.org\/wiki\/Quantile formula R-8\nfunc quantile(x []int, p float64) float64 {\n\tif len(x) == 0 {\n\t\treturn 0\n\t}\n\tN := float64(len(x))\n\tif p < 2.0\/(3.0*(N+1.0\/3.0)) {\n\t\treturn float64(x[0])\n\t}\n\tif p >= (N-1.0\/3.0)\/(N+1.0\/3.0) {\n\t\treturn float64(x[len(x)-1])\n\t}\n\n\th := (N+1.0\/3.0)*p + 1.0\/3.0\n\tfh := math.Floor(h)\n\txl := x[int(fh)-1]\n\txr := x[int(fh)]\n\n\treturn float64(xl) + (h-fh)*float64(xr-xl)\n}\n\n\/\/ Prepare implements Check's Prepare method.\nfunc (L *Latency) Prepare(*Test) error {\n\tif L.N == 0 {\n\t\tL.N = 50\n\t}\n\tif L.Concurrent == 0 {\n\t\tL.Concurrent = 2\n\t} else if L.Concurrent > 64 {\n\t\treturn fmt.Errorf(\"concurrency %d > allowed max of 64\", L.Concurrent)\n\t}\n\n\tif L.Limits == \"\" {\n\t\tL.Limits = \"75% ≤ 500\"\n\t}\n\n\tif err := L.parseLimit(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nvar _ Preparable = &Latency{}\n\nfunc (L *Latency) parseLimit() error {\n\tparts := strings.Split(strings.Trim(L.Limits, \"; \"), \";\")\n\tfor i := range parts {\n\t\ts := strings.TrimSpace(parts[i])\n\t\tq, t, err := parseQantileLimit(s)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tL.limits = append(L.limits, latLimit{q: q, max: t})\n\t}\n\n\treturn nil\n}\n\nfunc parseQantileLimit(s string) (float64, time.Duration, error) {\n\tparts := strings.SplitN(s, \"≤\", 2)\n\tif len(parts) != 2 {\n\t\treturn 0, 0, fmt.Errorf(\"Latency: missing '≤' in %q\", s)\n\t}\n\n\tq := strings.TrimSpace(strings.TrimRight(parts[0], \" %\"))\n\tquantile, err := strconv.ParseFloat(q, 64)\n\tif err != nil {\n\t\treturn 0, 0, err\n\t}\n\tif strings.Contains(parts[0], \"%\") {\n\t\tquantile \/= 100\n\t}\n\tif quantile < 0 || quantile > 1 {\n\t\treturn 0, 0, fmt.Errorf(\"Latency: quantile %.3f out of range [0,1]\", quantile)\n\t}\n\n\tb := strings.TrimSpace(strings.TrimLeft(parts[1], \"=\"))\n\n\tm, err := time.ParseDuration(b)\n\tif err != nil {\n\t\treturn 0, 0, err\n\t}\n\tif m <= 0 || m > 300*time.Second {\n\t\treturn 0, 0, fmt.Errorf(\"Latency: limit %s out of range (0,300s]\", m)\n\t}\n\n\treturn quantile, m, nil\n}\n\n\/*\n\nFor Conc==4 and RT_orig == 12 ==> offset==3\n\n 1 +---------+ +---------+ +---------+ +---------+ +---------+\n 2 +---------+ +---------+ +---------+ +---------+ +---------+\n 3 +---------+ +---------+ +---------+ +---------+ +---------+\n 4 +---------+ +---------+ +---------+ +---------+ +---------+\n | | | |\n -+--+- -+-----------+-\n offset RT_orig\n\n*\/\n<|endoftext|>"} {"text":"\/*\nCopyright 2018 The Skaffold Authors\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage deploy\n\nimport (\n\t\"context\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"time\"\n\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/build\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/constants\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/kubernetes\"\n\tkubectx \"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/kubernetes\/context\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/sirupsen\/logrus\"\n\t\"k8s.io\/apimachinery\/pkg\/api\/meta\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/runtime\/schema\"\n\t\"k8s.io\/apimachinery\/pkg\/types\"\n\tpatch \"k8s.io\/apimachinery\/pkg\/util\/strategicpatch\"\n\n\t\"k8s.io\/client-go\/discovery\"\n\t\"k8s.io\/client-go\/dynamic\"\n)\n\n\/\/ Labeller can give key\/value labels to set on deployed resources.\ntype Labeller interface {\n\tLabels() map[string]string\n}\n\ntype withLabels struct {\n\tDeployer\n\n\tlabellers []Labeller\n}\n\n\/\/ WithLabels creates a deployer that sets labels on deployed resources.\nfunc WithLabels(d Deployer, labellers ...Labeller) Deployer {\n\treturn &withLabels{\n\t\tDeployer: d,\n\t\tlabellers: labellers,\n\t}\n}\n\nfunc (w *withLabels) Deploy(ctx context.Context, out io.Writer, artifacts []build.Artifact) ([]Artifact, error) {\n\tdRes, err := w.Deployer.Deploy(ctx, out, artifacts)\n\n\tlabelDeployResults(merge(w.labellers...), dRes)\n\n\treturn dRes, err\n}\n\n\/\/ merge merges the labels from multiple sources.\nfunc merge(sources ...Labeller) map[string]string {\n\tmerged := make(map[string]string)\n\n\tfor _, src := range sources {\n\t\tif src != nil {\n\t\t\tfor k, v := range src.Labels() {\n\t\t\t\tmerged[k] = v\n\t\t\t}\n\t\t}\n\t}\n\n\treturn merged\n}\n\n\/\/ retry 3 times to give the object time to propagate to the API server\nconst (\n\ttries = 3\n\tsleeptime = 300 * time.Millisecond\n)\n\nfunc labelDeployResults(labels map[string]string, results []Artifact) {\n\t\/\/ use the kubectl client to update all k8s objects with a skaffold watermark\n\tdynClient, err := kubernetes.DynamicClient()\n\tif err != nil {\n\t\tlogrus.Warnf(\"error retrieving kubernetes client: %s\", err.Error())\n\t\treturn\n\t}\n\n\tclient, err := kubernetes.GetClientset()\n\tif err != nil {\n\t\tlogrus.Warnf(\"error retrieving kubernetes client: %s\", err.Error())\n\t\treturn\n\t}\n\n\tfor _, res := range results {\n\t\terr = nil\n\t\tfor i := 0; i < tries; i++ {\n\t\t\tif err = updateRuntimeObject(dynClient, client.Discovery(), labels, res); err == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttime.Sleep(sleeptime)\n\t\t}\n\t\tif err != nil {\n\t\t\tlogrus.Warnf(\"error adding label to runtime object: %s\", err.Error())\n\t\t}\n\t}\n}\n\nfunc addLabels(labels map[string]string, accessor metav1.Object) {\n\tfor k, v := range constants.Labels.DefaultLabels {\n\t\tlabels[k] = v\n\t}\n\n\tobjLabels := accessor.GetLabels()\n\tif objLabels == nil {\n\t\tobjLabels = make(map[string]string)\n\t}\n\n\tfor key, value := range labels {\n\t\tobjLabels[key] = value\n\t}\n\taccessor.SetLabels(objLabels)\n}\n\nfunc updateRuntimeObject(client dynamic.Interface, disco discovery.DiscoveryInterface, labels map[string]string, res Artifact) error {\n\toriginalJSON, _ := json.Marshal(*res.Obj)\n\tmodifiedObj := (*res.Obj).DeepCopyObject()\n\taccessor, err := meta.Accessor(modifiedObj)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"getting metadata accessor\")\n\t}\n\tname := accessor.GetName()\n\tnamespace := accessor.GetNamespace()\n\taddLabels(labels, accessor)\n\n\tmodifiedJSON, _ := json.Marshal(modifiedObj)\n\tp, _ := patch.CreateTwoWayMergePatch(originalJSON, modifiedJSON, modifiedObj)\n\tgvr, err := groupVersionResource(disco, modifiedObj.GetObjectKind().GroupVersionKind())\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"getting group version resource from obj\")\n\t}\n\tns, err := resolveNamespace(namespace)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"resolving namespace\")\n\t}\n\tif _, err := client.Resource(gvr).Namespace(ns).Patch(name, types.StrategicMergePatchType, p); err != nil {\n\t\treturn errors.Wrapf(err, \"patching resource %s\/%s\", namespace, name)\n\t}\n\n\treturn err\n}\n\nfunc resolveNamespace(ns string) (string, error) {\n\tif ns != \"\" {\n\t\treturn ns, nil\n\t}\n\tcfg, err := kubectx.CurrentConfig()\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"getting kubeconfig\")\n\t}\n\n\tcurrent, present := cfg.Contexts[cfg.CurrentContext]\n\tif present {\n\t\treturn current.Namespace, nil\n\t}\n\treturn \"default\", nil\n}\n\nfunc groupVersionResource(disco discovery.DiscoveryInterface, gvk schema.GroupVersionKind) (schema.GroupVersionResource, error) {\n\tresources, err := disco.ServerResourcesForGroupVersion(gvk.GroupVersion().String())\n\tif err != nil {\n\t\treturn schema.GroupVersionResource{}, errors.Wrap(err, \"getting server resources for group version\")\n\t}\n\n\tfor _, r := range resources.APIResources {\n\t\tif r.Kind == gvk.Kind {\n\t\t\treturn schema.GroupVersionResource{\n\t\t\t\tGroup: gvk.Group,\n\t\t\t\tVersion: gvk.Version,\n\t\t\t\tResource: r.Name,\n\t\t\t}, nil\n\t\t}\n\t}\n\n\treturn schema.GroupVersionResource{}, fmt.Errorf(\"Could not find resource for %s\", gvk.String())\n}\nreview feedback\/*\nCopyright 2018 The Skaffold Authors\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage deploy\n\nimport (\n\t\"context\"\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"time\"\n\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/build\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/constants\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/kubernetes\"\n\tkubectx \"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/kubernetes\/context\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/sirupsen\/logrus\"\n\t\"k8s.io\/apimachinery\/pkg\/api\/meta\"\n\tmetav1 \"k8s.io\/apimachinery\/pkg\/apis\/meta\/v1\"\n\t\"k8s.io\/apimachinery\/pkg\/runtime\/schema\"\n\t\"k8s.io\/apimachinery\/pkg\/types\"\n\tpatch \"k8s.io\/apimachinery\/pkg\/util\/strategicpatch\"\n\n\t\"k8s.io\/client-go\/discovery\"\n\t\"k8s.io\/client-go\/dynamic\"\n)\n\n\/\/ Labeller can give key\/value labels to set on deployed resources.\ntype Labeller interface {\n\tLabels() map[string]string\n}\n\ntype withLabels struct {\n\tDeployer\n\n\tlabellers []Labeller\n}\n\n\/\/ WithLabels creates a deployer that sets labels on deployed resources.\nfunc WithLabels(d Deployer, labellers ...Labeller) Deployer {\n\treturn &withLabels{\n\t\tDeployer: d,\n\t\tlabellers: labellers,\n\t}\n}\n\nfunc (w *withLabels) Deploy(ctx context.Context, out io.Writer, artifacts []build.Artifact) ([]Artifact, error) {\n\tdRes, err := w.Deployer.Deploy(ctx, out, artifacts)\n\n\tlabelDeployResults(merge(w.labellers...), dRes)\n\n\treturn dRes, err\n}\n\n\/\/ merge merges the labels from multiple sources.\nfunc merge(sources ...Labeller) map[string]string {\n\tmerged := make(map[string]string)\n\n\tfor _, src := range sources {\n\t\tif src != nil {\n\t\t\tfor k, v := range src.Labels() {\n\t\t\t\tmerged[k] = v\n\t\t\t}\n\t\t}\n\t}\n\n\treturn merged\n}\n\n\/\/ retry 3 times to give the object time to propagate to the API server\nconst (\n\ttries = 3\n\tsleeptime = 300 * time.Millisecond\n)\n\nfunc labelDeployResults(labels map[string]string, results []Artifact) {\n\t\/\/ use the kubectl client to update all k8s objects with a skaffold watermark\n\tdynClient, err := kubernetes.DynamicClient()\n\tif err != nil {\n\t\tlogrus.Warnf(\"error retrieving kubernetes client: %s\", err.Error())\n\t\treturn\n\t}\n\n\tclient, err := kubernetes.GetClientset()\n\tif err != nil {\n\t\tlogrus.Warnf(\"error retrieving kubernetes client: %s\", err.Error())\n\t\treturn\n\t}\n\n\tfor _, res := range results {\n\t\terr = nil\n\t\tfor i := 0; i < tries; i++ {\n\t\t\tif err = updateRuntimeObject(dynClient, client.Discovery(), labels, res); err == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttime.Sleep(sleeptime)\n\t\t}\n\t\tif err != nil {\n\t\t\tlogrus.Warnf(\"error adding label to runtime object: %s\", err.Error())\n\t\t}\n\t}\n}\n\nfunc addLabels(labels map[string]string, accessor metav1.Object) {\n\tfor k, v := range constants.Labels.DefaultLabels {\n\t\tlabels[k] = v\n\t}\n\n\tobjLabels := accessor.GetLabels()\n\tif objLabels == nil {\n\t\tobjLabels = make(map[string]string)\n\t}\n\n\tfor key, value := range labels {\n\t\tobjLabels[key] = value\n\t}\n\taccessor.SetLabels(objLabels)\n}\n\nfunc updateRuntimeObject(client dynamic.Interface, disco discovery.DiscoveryInterface, labels map[string]string, res Artifact) error {\n\toriginalJSON, _ := json.Marshal(*res.Obj)\n\tmodifiedObj := (*res.Obj).DeepCopyObject()\n\taccessor, err := meta.Accessor(modifiedObj)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"getting metadata accessor\")\n\t}\n\tname := accessor.GetName()\n\tnamespace := accessor.GetNamespace()\n\taddLabels(labels, accessor)\n\n\tmodifiedJSON, _ := json.Marshal(modifiedObj)\n\tp, _ := patch.CreateTwoWayMergePatch(originalJSON, modifiedJSON, modifiedObj)\n\tgvr, err := groupVersionResource(disco, modifiedObj.GetObjectKind().GroupVersionKind())\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"getting group version resource from obj\")\n\t}\n\tns, err := resolveNamespace(namespace)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"resolving namespace\")\n\t}\n\tif _, err := client.Resource(gvr).Namespace(ns).Patch(name, types.StrategicMergePatchType, p); err != nil {\n\t\treturn errors.Wrapf(err, \"patching resource %s\/%s\", namespace, name)\n\t}\n\n\treturn nil\n}\n\nfunc resolveNamespace(ns string) (string, error) {\n\tif ns != \"\" {\n\t\treturn ns, nil\n\t}\n\tcfg, err := kubectx.CurrentConfig()\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"getting kubeconfig\")\n\t}\n\n\tcurrent, present := cfg.Contexts[cfg.CurrentContext]\n\tif present {\n\t\treturn current.Namespace, nil\n\t}\n\treturn \"default\", nil\n}\n\nfunc groupVersionResource(disco discovery.DiscoveryInterface, gvk schema.GroupVersionKind) (schema.GroupVersionResource, error) {\n\tresources, err := disco.ServerResourcesForGroupVersion(gvk.GroupVersion().String())\n\tif err != nil {\n\t\treturn schema.GroupVersionResource{}, errors.Wrap(err, \"getting server resources for group version\")\n\t}\n\n\tfor _, r := range resources.APIResources {\n\t\tif r.Kind == gvk.Kind {\n\t\t\treturn schema.GroupVersionResource{\n\t\t\t\tGroup: gvk.Group,\n\t\t\t\tVersion: gvk.Version,\n\t\t\t\tResource: r.Name,\n\t\t\t}, nil\n\t\t}\n\t}\n\n\treturn schema.GroupVersionResource{}, fmt.Errorf(\"Could not find resource for %s\", gvk.String())\n}\n<|endoftext|>"} {"text":"\/*\nCopyright 2018 The Skaffold Authors\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage runner\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/bazel\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/build\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/build\/gcb\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/build\/kaniko\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/build\/local\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/build\/tag\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/color\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/config\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/deploy\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/docker\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/jib\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/kubernetes\"\n\tkubectx \"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/kubernetes\/context\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/schema\/latest\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/test\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/watch\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/sirupsen\/logrus\"\n)\n\n\/\/ ErrorConfigurationChanged is a special error that's returned when the skaffold configuration was changed.\nvar ErrorConfigurationChanged = errors.New(\"configuration changed\")\n\n\/\/ SkaffoldRunner is responsible for running the skaffold build and deploy pipeline.\ntype SkaffoldRunner struct {\n\tbuild.Builder\n\tdeploy.Deployer\n\ttest.Tester\n\ttag.Tagger\n\n\topts *config.SkaffoldOptions\n\twatchFactory watch.Factory\n\tbuilds []build.Artifact\n}\n\n\/\/ NewForConfig returns a new SkaffoldRunner for a SkaffoldConfig\nfunc NewForConfig(opts *config.SkaffoldOptions, cfg *latest.SkaffoldConfig) (*SkaffoldRunner, error) {\n\tkubeContext, err := kubectx.CurrentContext()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"getting current cluster context\")\n\t}\n\tlogrus.Infof(\"Using kubectl context: %s\", kubeContext)\n\n\ttagger, err := getTagger(cfg.Build.TagPolicy, opts.CustomTag)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"parsing skaffold tag config\")\n\t}\n\n\tbuilder, err := getBuilder(&cfg.Build, kubeContext)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"parsing skaffold build config\")\n\t}\n\n\ttester, err := getTester(&cfg.Test)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"parsing skaffold test config\")\n\t}\n\n\tdeployer, err := getDeployer(&cfg.Deploy, kubeContext, opts.Namespace)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"parsing skaffold deploy config\")\n\t}\n\n\tdeployer = deploy.WithLabels(deployer, opts, builder, deployer, tagger)\n\tbuilder, tester, deployer = WithTimings(builder, tester, deployer)\n\tif opts.Notification {\n\t\tdeployer = WithNotification(deployer)\n\t}\n\n\treturn &SkaffoldRunner{\n\t\tBuilder: builder,\n\t\tTester: tester,\n\t\tDeployer: deployer,\n\t\tTagger: tagger,\n\t\topts: opts,\n\t\twatchFactory: watch.NewWatcher,\n\t}, nil\n}\n\nfunc getBuilder(cfg *latest.BuildConfig, kubeContext string) (build.Builder, error) {\n\tswitch {\n\tcase cfg.LocalBuild != nil:\n\t\tlogrus.Debugf(\"Using builder: local\")\n\t\treturn local.NewBuilder(cfg.LocalBuild, kubeContext)\n\n\tcase cfg.GoogleCloudBuild != nil:\n\t\tlogrus.Debugf(\"Using builder: google cloud\")\n\t\treturn gcb.NewBuilder(cfg.GoogleCloudBuild), nil\n\n\tcase cfg.KanikoBuild != nil:\n\t\tlogrus.Debugf(\"Using builder: kaniko\")\n\t\treturn kaniko.NewBuilder(cfg.KanikoBuild), nil\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unknown builder for config %+v\", cfg)\n\t}\n}\n\nfunc getTester(cfg *[]latest.TestCase) (test.Tester, error) {\n\treturn test.NewTester(cfg)\n}\n\nfunc getDeployer(cfg *latest.DeployConfig, kubeContext string, namespace string) (deploy.Deployer, error) {\n\tdeployers := []deploy.Deployer{}\n\n\t\/\/ HelmDeploy first, in case there are resources in Kubectl that depend on these...\n\tif cfg.HelmDeploy != nil {\n\t\tdeployers = append(deployers, deploy.NewHelmDeployer(cfg.HelmDeploy, kubeContext, namespace))\n\t}\n\n\tif cfg.KubectlDeploy != nil {\n\t\t\/\/ TODO(dgageot): this should be the folder containing skaffold.yaml. Should also be moved elsewhere.\n\t\tcwd, err := os.Getwd()\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"finding current directory\")\n\t\t}\n\t\tdeployers = append(deployers, deploy.NewKubectlDeployer(cwd, cfg.KubectlDeploy, kubeContext, namespace))\n\t}\n\n\tif cfg.KustomizeDeploy != nil {\n\t\tdeployers = append(deployers, deploy.NewKustomizeDeployer(cfg.KustomizeDeploy, kubeContext, namespace))\n\t}\n\n\tif len(deployers) == 0 {\n\t\treturn nil, fmt.Errorf(\"Unknown deployer for config %+v\", cfg)\n\t}\n\n\tif len(deployers) == 1 {\n\t\treturn deployers[0], nil\n\t}\n\n\treturn deploy.NewMultiDeployer(deployers), nil\n}\n\nfunc getTagger(t latest.TagPolicy, customTag string) (tag.Tagger, error) {\n\tswitch {\n\tcase customTag != \"\":\n\t\treturn &tag.CustomTag{\n\t\t\tTag: customTag,\n\t\t}, nil\n\n\tcase t.EnvTemplateTagger != nil:\n\t\treturn tag.NewEnvTemplateTagger(t.EnvTemplateTagger.Template)\n\n\tcase t.ShaTagger != nil:\n\t\treturn &tag.ChecksumTagger{}, nil\n\n\tcase t.GitTagger != nil:\n\t\treturn &tag.GitCommit{}, nil\n\n\tcase t.DateTimeTagger != nil:\n\t\treturn tag.NewDateTimeTagger(t.DateTimeTagger.Format, t.DateTimeTagger.TimeZone), nil\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unknown tagger for strategy %+v\", t)\n\t}\n}\n\n\/\/ Run builds artifacts, runs tests on built artifacts, and then deploys them.\nfunc (r *SkaffoldRunner) Run(ctx context.Context, out io.Writer, artifacts []*latest.Artifact) error {\n\tbRes, err := r.Build(ctx, out, r.Tagger, artifacts)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"build step\")\n\t}\n\n\tif err = r.Test(out, bRes); err != nil {\n\t\treturn errors.Wrap(err, \"test step\")\n\t}\n\n\t_, err = r.Deploy(ctx, out, bRes)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"deploy step\")\n\t}\n\n\treturn r.TailLogs(ctx, out, artifacts, bRes)\n}\n\n\/\/ TailLogs prints the logs for deployed artifacts.\nfunc (r *SkaffoldRunner) TailLogs(ctx context.Context, out io.Writer, artifacts []*latest.Artifact, bRes []build.Artifact) error {\n\tif !r.opts.Tail {\n\t\treturn nil\n\t}\n\n\timageList := kubernetes.NewImageList()\n\tfor _, b := range bRes {\n\t\timageList.Add(b.Tag)\n\t}\n\n\tcolorPicker := kubernetes.NewColorPicker(artifacts)\n\tlogger := kubernetes.NewLogAggregator(out, imageList, colorPicker)\n\tif err := logger.Start(ctx); err != nil {\n\t\treturn errors.Wrap(err, \"starting logger\")\n\t}\n\n\t<-ctx.Done()\n\treturn nil\n}\n\n\/\/ Dev watches for changes and runs the skaffold build and deploy\n\/\/ pipeline until interrrupted by the user.\nfunc (r *SkaffoldRunner) Dev(ctx context.Context, out io.Writer, artifacts []*latest.Artifact) ([]build.Artifact, error) {\n\timageList := kubernetes.NewImageList()\n\tcolorPicker := kubernetes.NewColorPicker(artifacts)\n\tlogger := kubernetes.NewLogAggregator(out, imageList, colorPicker)\n\tportForwarder := kubernetes.NewPortForwarder(out, imageList)\n\n\t\/\/ Create watcher and register artifacts to build current state of files.\n\tchanged := changes{}\n\tonChange := func() error {\n\t\thasError := true\n\n\t\tlogger.Mute()\n\t\tdefer func() {\n\t\t\tchanged.reset()\n\t\t\tcolor.Default.Fprintln(out, \"Watching for changes...\")\n\t\t\tif !hasError {\n\t\t\t\tlogger.Unmute()\n\t\t\t}\n\t\t}()\n\n\t\tswitch {\n\t\tcase changed.needsReload:\n\t\t\tlogger.Stop()\n\t\t\treturn ErrorConfigurationChanged\n\t\tcase len(changed.dirtyArtifacts) > 0:\n\t\t\tbRes, err := r.Build(ctx, out, r.Tagger, changed.dirtyArtifacts)\n\t\t\tif err != nil {\n\t\t\t\tlogrus.Warnln(\"Skipping Deploy due to build error:\", err)\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tr.updateBuiltImages(imageList, bRes)\n\t\t\tif err := r.Test(out, bRes); err != nil {\n\t\t\t\tlogrus.Warnln(\"Skipping Deploy due to failed tests:\", err)\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tif _, err = r.Deploy(ctx, out, r.builds); err != nil {\n\t\t\t\tlogrus.Warnln(\"Skipping Deploy due to error:\", err)\n\t\t\t\treturn nil\n\t\t\t}\n\t\tcase changed.needsRedeploy:\n\t\t\tif err := r.Test(out, r.builds); err != nil {\n\t\t\t\tlogrus.Warnln(\"Skipping Deploy due to failed tests:\", err)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif _, err := r.Deploy(ctx, out, r.builds); err != nil {\n\t\t\t\tlogrus.Warnln(\"Skipping Deploy due to error:\", err)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\n\t\thasError = false\n\t\treturn nil\n\t}\n\n\twatcher := r.watchFactory()\n\n\t\/\/ Watch artifacts\n\tfor i := range artifacts {\n\t\tartifact := artifacts[i]\n\n\t\tif !r.shouldWatch(artifact) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := watcher.Register(\n\t\t\tfunc() ([]string, error) { return dependenciesForArtifact(artifact) },\n\t\t\tfunc(watch.Events) { changed.Add(artifact) },\n\t\t); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"watching files for artifact %s\", artifact.ImageName)\n\t\t}\n\t}\n\n\t\/\/ Watch test configuration\n\tif err := watcher.Register(\n\t\tfunc() ([]string, error) { return r.TestDependencies(), nil },\n\t\tfunc(watch.Events) { changed.needsRedeploy = true },\n\t); err != nil {\n\t\treturn nil, errors.Wrap(err, \"watching test files\")\n\t}\n\n\t\/\/ Watch deployment configuration\n\tif err := watcher.Register(\n\t\tfunc() ([]string, error) { return r.Dependencies() },\n\t\tfunc(watch.Events) { changed.needsRedeploy = true },\n\t); err != nil {\n\t\treturn nil, errors.Wrap(err, \"watching files for deployer\")\n\t}\n\n\t\/\/ Watch Skaffold configuration\n\tif err := watcher.Register(\n\t\tfunc() ([]string, error) { return []string{r.opts.ConfigurationFile}, nil },\n\t\tfunc(watch.Events) { changed.needsReload = true },\n\t); err != nil {\n\t\treturn nil, errors.Wrapf(err, \"watching skaffold configuration %s\", r.opts.ConfigurationFile)\n\t}\n\n\t\/\/ First run\n\tbRes, err := r.Build(ctx, out, r.Tagger, artifacts)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"exiting dev mode because the first build failed\")\n\t}\n\n\tr.updateBuiltImages(imageList, bRes)\n\tif err := r.Test(out, bRes); err != nil {\n\t\treturn nil, errors.Wrap(err, \"exiting dev mode because the first test run failed\")\n\t}\n\n\t_, err = r.Deploy(ctx, out, r.builds)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"exiting dev mode because the first deploy failed\")\n\t}\n\n\t\/\/ Start logs\n\tif r.opts.TailDev {\n\t\tif err := logger.Start(ctx); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"starting logger\")\n\t\t}\n\t}\n\n\tif r.opts.PortForward {\n\t\tif err := portForwarder.Start(ctx); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"starting port-forwarder\")\n\t\t}\n\t}\n\n\tpollInterval := time.Duration(r.opts.WatchPollInterval) * time.Millisecond\n\treturn nil, watcher.Run(ctx, pollInterval, onChange)\n}\n\nfunc (r *SkaffoldRunner) shouldWatch(artifact *latest.Artifact) bool {\n\tif len(r.opts.Watch) == 0 {\n\t\treturn true\n\t}\n\n\tfor _, watchExpression := range r.opts.Watch {\n\t\tif strings.Contains(artifact.ImageName, watchExpression) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc (r *SkaffoldRunner) updateBuiltImages(images *kubernetes.ImageList, bRes []build.Artifact) {\n\t\/\/ Update which images are logged.\n\tfor _, build := range bRes {\n\t\timages.Add(build.Tag)\n\t}\n\n\t\/\/ Make sure all artifacts are redeployed. Not only those that were just rebuilt.\n\tr.builds = mergeWithPreviousBuilds(bRes, r.builds)\n}\n\nfunc mergeWithPreviousBuilds(builds, previous []build.Artifact) []build.Artifact {\n\tupdatedBuilds := map[string]bool{}\n\tfor _, build := range builds {\n\t\tupdatedBuilds[build.ImageName] = true\n\t}\n\n\tvar merged []build.Artifact\n\tmerged = append(merged, builds...)\n\n\tfor _, b := range previous {\n\t\tif !updatedBuilds[b.ImageName] {\n\t\t\tmerged = append(merged, b)\n\t\t}\n\t}\n\n\treturn merged\n}\n\nfunc dependenciesForArtifact(a *latest.Artifact) ([]string, error) {\n\tvar (\n\t\tpaths []string\n\t\terr error\n\t)\n\n\tswitch {\n\tcase a.DockerArtifact != nil:\n\t\tpaths, err = docker.GetDependencies(a.Workspace, a.DockerArtifact)\n\n\tcase a.BazelArtifact != nil:\n\t\tpaths, err = bazel.GetDependencies(a.Workspace, a.BazelArtifact)\n\n\tcase a.JibMavenArtifact != nil:\n\t\tpaths, err = jib.GetDependenciesMaven(a.Workspace, a.JibMavenArtifact)\n\n\tcase a.JibGradleArtifact != nil:\n\t\tpaths, err = jib.GetDependenciesGradle(a.Workspace, a.JibGradleArtifact)\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"undefined artifact type: %+v\", a.ArtifactType)\n\t}\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar p []string\n\tfor _, path := range paths {\n\t\tif !filepath.IsAbs(path) {\n\t\t\tpath = filepath.Join(a.Workspace, path)\n\t\t}\n\t\tp = append(p, path)\n\n\t\tlogrus.Info(\"watching: \" + filepath.Join(a.Workspace, path))\n\t}\n\treturn p, nil\n}\nRemoves debug message.\/*\nCopyright 2018 The Skaffold Authors\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage runner\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/bazel\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/build\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/build\/gcb\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/build\/kaniko\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/build\/local\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/build\/tag\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/color\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/config\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/deploy\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/docker\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/jib\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/kubernetes\"\n\tkubectx \"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/kubernetes\/context\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/schema\/latest\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/test\"\n\t\"github.com\/GoogleContainerTools\/skaffold\/pkg\/skaffold\/watch\"\n\n\t\"github.com\/pkg\/errors\"\n\t\"github.com\/sirupsen\/logrus\"\n)\n\n\/\/ ErrorConfigurationChanged is a special error that's returned when the skaffold configuration was changed.\nvar ErrorConfigurationChanged = errors.New(\"configuration changed\")\n\n\/\/ SkaffoldRunner is responsible for running the skaffold build and deploy pipeline.\ntype SkaffoldRunner struct {\n\tbuild.Builder\n\tdeploy.Deployer\n\ttest.Tester\n\ttag.Tagger\n\n\topts *config.SkaffoldOptions\n\twatchFactory watch.Factory\n\tbuilds []build.Artifact\n}\n\n\/\/ NewForConfig returns a new SkaffoldRunner for a SkaffoldConfig\nfunc NewForConfig(opts *config.SkaffoldOptions, cfg *latest.SkaffoldConfig) (*SkaffoldRunner, error) {\n\tkubeContext, err := kubectx.CurrentContext()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"getting current cluster context\")\n\t}\n\tlogrus.Infof(\"Using kubectl context: %s\", kubeContext)\n\n\ttagger, err := getTagger(cfg.Build.TagPolicy, opts.CustomTag)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"parsing skaffold tag config\")\n\t}\n\n\tbuilder, err := getBuilder(&cfg.Build, kubeContext)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"parsing skaffold build config\")\n\t}\n\n\ttester, err := getTester(&cfg.Test)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"parsing skaffold test config\")\n\t}\n\n\tdeployer, err := getDeployer(&cfg.Deploy, kubeContext, opts.Namespace)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"parsing skaffold deploy config\")\n\t}\n\n\tdeployer = deploy.WithLabels(deployer, opts, builder, deployer, tagger)\n\tbuilder, tester, deployer = WithTimings(builder, tester, deployer)\n\tif opts.Notification {\n\t\tdeployer = WithNotification(deployer)\n\t}\n\n\treturn &SkaffoldRunner{\n\t\tBuilder: builder,\n\t\tTester: tester,\n\t\tDeployer: deployer,\n\t\tTagger: tagger,\n\t\topts: opts,\n\t\twatchFactory: watch.NewWatcher,\n\t}, nil\n}\n\nfunc getBuilder(cfg *latest.BuildConfig, kubeContext string) (build.Builder, error) {\n\tswitch {\n\tcase cfg.LocalBuild != nil:\n\t\tlogrus.Debugf(\"Using builder: local\")\n\t\treturn local.NewBuilder(cfg.LocalBuild, kubeContext)\n\n\tcase cfg.GoogleCloudBuild != nil:\n\t\tlogrus.Debugf(\"Using builder: google cloud\")\n\t\treturn gcb.NewBuilder(cfg.GoogleCloudBuild), nil\n\n\tcase cfg.KanikoBuild != nil:\n\t\tlogrus.Debugf(\"Using builder: kaniko\")\n\t\treturn kaniko.NewBuilder(cfg.KanikoBuild), nil\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unknown builder for config %+v\", cfg)\n\t}\n}\n\nfunc getTester(cfg *[]latest.TestCase) (test.Tester, error) {\n\treturn test.NewTester(cfg)\n}\n\nfunc getDeployer(cfg *latest.DeployConfig, kubeContext string, namespace string) (deploy.Deployer, error) {\n\tdeployers := []deploy.Deployer{}\n\n\t\/\/ HelmDeploy first, in case there are resources in Kubectl that depend on these...\n\tif cfg.HelmDeploy != nil {\n\t\tdeployers = append(deployers, deploy.NewHelmDeployer(cfg.HelmDeploy, kubeContext, namespace))\n\t}\n\n\tif cfg.KubectlDeploy != nil {\n\t\t\/\/ TODO(dgageot): this should be the folder containing skaffold.yaml. Should also be moved elsewhere.\n\t\tcwd, err := os.Getwd()\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"finding current directory\")\n\t\t}\n\t\tdeployers = append(deployers, deploy.NewKubectlDeployer(cwd, cfg.KubectlDeploy, kubeContext, namespace))\n\t}\n\n\tif cfg.KustomizeDeploy != nil {\n\t\tdeployers = append(deployers, deploy.NewKustomizeDeployer(cfg.KustomizeDeploy, kubeContext, namespace))\n\t}\n\n\tif len(deployers) == 0 {\n\t\treturn nil, fmt.Errorf(\"Unknown deployer for config %+v\", cfg)\n\t}\n\n\tif len(deployers) == 1 {\n\t\treturn deployers[0], nil\n\t}\n\n\treturn deploy.NewMultiDeployer(deployers), nil\n}\n\nfunc getTagger(t latest.TagPolicy, customTag string) (tag.Tagger, error) {\n\tswitch {\n\tcase customTag != \"\":\n\t\treturn &tag.CustomTag{\n\t\t\tTag: customTag,\n\t\t}, nil\n\n\tcase t.EnvTemplateTagger != nil:\n\t\treturn tag.NewEnvTemplateTagger(t.EnvTemplateTagger.Template)\n\n\tcase t.ShaTagger != nil:\n\t\treturn &tag.ChecksumTagger{}, nil\n\n\tcase t.GitTagger != nil:\n\t\treturn &tag.GitCommit{}, nil\n\n\tcase t.DateTimeTagger != nil:\n\t\treturn tag.NewDateTimeTagger(t.DateTimeTagger.Format, t.DateTimeTagger.TimeZone), nil\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unknown tagger for strategy %+v\", t)\n\t}\n}\n\n\/\/ Run builds artifacts, runs tests on built artifacts, and then deploys them.\nfunc (r *SkaffoldRunner) Run(ctx context.Context, out io.Writer, artifacts []*latest.Artifact) error {\n\tbRes, err := r.Build(ctx, out, r.Tagger, artifacts)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"build step\")\n\t}\n\n\tif err = r.Test(out, bRes); err != nil {\n\t\treturn errors.Wrap(err, \"test step\")\n\t}\n\n\t_, err = r.Deploy(ctx, out, bRes)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"deploy step\")\n\t}\n\n\treturn r.TailLogs(ctx, out, artifacts, bRes)\n}\n\n\/\/ TailLogs prints the logs for deployed artifacts.\nfunc (r *SkaffoldRunner) TailLogs(ctx context.Context, out io.Writer, artifacts []*latest.Artifact, bRes []build.Artifact) error {\n\tif !r.opts.Tail {\n\t\treturn nil\n\t}\n\n\timageList := kubernetes.NewImageList()\n\tfor _, b := range bRes {\n\t\timageList.Add(b.Tag)\n\t}\n\n\tcolorPicker := kubernetes.NewColorPicker(artifacts)\n\tlogger := kubernetes.NewLogAggregator(out, imageList, colorPicker)\n\tif err := logger.Start(ctx); err != nil {\n\t\treturn errors.Wrap(err, \"starting logger\")\n\t}\n\n\t<-ctx.Done()\n\treturn nil\n}\n\n\/\/ Dev watches for changes and runs the skaffold build and deploy\n\/\/ pipeline until interrrupted by the user.\nfunc (r *SkaffoldRunner) Dev(ctx context.Context, out io.Writer, artifacts []*latest.Artifact) ([]build.Artifact, error) {\n\timageList := kubernetes.NewImageList()\n\tcolorPicker := kubernetes.NewColorPicker(artifacts)\n\tlogger := kubernetes.NewLogAggregator(out, imageList, colorPicker)\n\tportForwarder := kubernetes.NewPortForwarder(out, imageList)\n\n\t\/\/ Create watcher and register artifacts to build current state of files.\n\tchanged := changes{}\n\tonChange := func() error {\n\t\thasError := true\n\n\t\tlogger.Mute()\n\t\tdefer func() {\n\t\t\tchanged.reset()\n\t\t\tcolor.Default.Fprintln(out, \"Watching for changes...\")\n\t\t\tif !hasError {\n\t\t\t\tlogger.Unmute()\n\t\t\t}\n\t\t}()\n\n\t\tswitch {\n\t\tcase changed.needsReload:\n\t\t\tlogger.Stop()\n\t\t\treturn ErrorConfigurationChanged\n\t\tcase len(changed.dirtyArtifacts) > 0:\n\t\t\tbRes, err := r.Build(ctx, out, r.Tagger, changed.dirtyArtifacts)\n\t\t\tif err != nil {\n\t\t\t\tlogrus.Warnln(\"Skipping Deploy due to build error:\", err)\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tr.updateBuiltImages(imageList, bRes)\n\t\t\tif err := r.Test(out, bRes); err != nil {\n\t\t\t\tlogrus.Warnln(\"Skipping Deploy due to failed tests:\", err)\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tif _, err = r.Deploy(ctx, out, r.builds); err != nil {\n\t\t\t\tlogrus.Warnln(\"Skipping Deploy due to error:\", err)\n\t\t\t\treturn nil\n\t\t\t}\n\t\tcase changed.needsRedeploy:\n\t\t\tif err := r.Test(out, r.builds); err != nil {\n\t\t\t\tlogrus.Warnln(\"Skipping Deploy due to failed tests:\", err)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tif _, err := r.Deploy(ctx, out, r.builds); err != nil {\n\t\t\t\tlogrus.Warnln(\"Skipping Deploy due to error:\", err)\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\n\t\thasError = false\n\t\treturn nil\n\t}\n\n\twatcher := r.watchFactory()\n\n\t\/\/ Watch artifacts\n\tfor i := range artifacts {\n\t\tartifact := artifacts[i]\n\n\t\tif !r.shouldWatch(artifact) {\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := watcher.Register(\n\t\t\tfunc() ([]string, error) { return dependenciesForArtifact(artifact) },\n\t\t\tfunc(watch.Events) { changed.Add(artifact) },\n\t\t); err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"watching files for artifact %s\", artifact.ImageName)\n\t\t}\n\t}\n\n\t\/\/ Watch test configuration\n\tif err := watcher.Register(\n\t\tfunc() ([]string, error) { return r.TestDependencies(), nil },\n\t\tfunc(watch.Events) { changed.needsRedeploy = true },\n\t); err != nil {\n\t\treturn nil, errors.Wrap(err, \"watching test files\")\n\t}\n\n\t\/\/ Watch deployment configuration\n\tif err := watcher.Register(\n\t\tfunc() ([]string, error) { return r.Dependencies() },\n\t\tfunc(watch.Events) { changed.needsRedeploy = true },\n\t); err != nil {\n\t\treturn nil, errors.Wrap(err, \"watching files for deployer\")\n\t}\n\n\t\/\/ Watch Skaffold configuration\n\tif err := watcher.Register(\n\t\tfunc() ([]string, error) { return []string{r.opts.ConfigurationFile}, nil },\n\t\tfunc(watch.Events) { changed.needsReload = true },\n\t); err != nil {\n\t\treturn nil, errors.Wrapf(err, \"watching skaffold configuration %s\", r.opts.ConfigurationFile)\n\t}\n\n\t\/\/ First run\n\tbRes, err := r.Build(ctx, out, r.Tagger, artifacts)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"exiting dev mode because the first build failed\")\n\t}\n\n\tr.updateBuiltImages(imageList, bRes)\n\tif err := r.Test(out, bRes); err != nil {\n\t\treturn nil, errors.Wrap(err, \"exiting dev mode because the first test run failed\")\n\t}\n\n\t_, err = r.Deploy(ctx, out, r.builds)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"exiting dev mode because the first deploy failed\")\n\t}\n\n\t\/\/ Start logs\n\tif r.opts.TailDev {\n\t\tif err := logger.Start(ctx); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"starting logger\")\n\t\t}\n\t}\n\n\tif r.opts.PortForward {\n\t\tif err := portForwarder.Start(ctx); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"starting port-forwarder\")\n\t\t}\n\t}\n\n\tpollInterval := time.Duration(r.opts.WatchPollInterval) * time.Millisecond\n\treturn nil, watcher.Run(ctx, pollInterval, onChange)\n}\n\nfunc (r *SkaffoldRunner) shouldWatch(artifact *latest.Artifact) bool {\n\tif len(r.opts.Watch) == 0 {\n\t\treturn true\n\t}\n\n\tfor _, watchExpression := range r.opts.Watch {\n\t\tif strings.Contains(artifact.ImageName, watchExpression) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc (r *SkaffoldRunner) updateBuiltImages(images *kubernetes.ImageList, bRes []build.Artifact) {\n\t\/\/ Update which images are logged.\n\tfor _, build := range bRes {\n\t\timages.Add(build.Tag)\n\t}\n\n\t\/\/ Make sure all artifacts are redeployed. Not only those that were just rebuilt.\n\tr.builds = mergeWithPreviousBuilds(bRes, r.builds)\n}\n\nfunc mergeWithPreviousBuilds(builds, previous []build.Artifact) []build.Artifact {\n\tupdatedBuilds := map[string]bool{}\n\tfor _, build := range builds {\n\t\tupdatedBuilds[build.ImageName] = true\n\t}\n\n\tvar merged []build.Artifact\n\tmerged = append(merged, builds...)\n\n\tfor _, b := range previous {\n\t\tif !updatedBuilds[b.ImageName] {\n\t\t\tmerged = append(merged, b)\n\t\t}\n\t}\n\n\treturn merged\n}\n\nfunc dependenciesForArtifact(a *latest.Artifact) ([]string, error) {\n\tvar (\n\t\tpaths []string\n\t\terr error\n\t)\n\n\tswitch {\n\tcase a.DockerArtifact != nil:\n\t\tpaths, err = docker.GetDependencies(a.Workspace, a.DockerArtifact)\n\n\tcase a.BazelArtifact != nil:\n\t\tpaths, err = bazel.GetDependencies(a.Workspace, a.BazelArtifact)\n\n\tcase a.JibMavenArtifact != nil:\n\t\tpaths, err = jib.GetDependenciesMaven(a.Workspace, a.JibMavenArtifact)\n\n\tcase a.JibGradleArtifact != nil:\n\t\tpaths, err = jib.GetDependenciesGradle(a.Workspace, a.JibGradleArtifact)\n\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"undefined artifact type: %+v\", a.ArtifactType)\n\t}\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar p []string\n\tfor _, path := range paths {\n\t\tif !filepath.IsAbs(path) {\n\t\t\tpath = filepath.Join(a.Workspace, path)\n\t\t}\n\t\tp = append(p, path)\n\t}\n\treturn p, nil\n}\n<|endoftext|>"} {"text":"\/*\nCopyright 2014 The Perkeep Authors\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n\/*\nPackage dockertest contains helper functions for setting up and tearing down docker containers to aid in testing.\n*\/\npackage dockertest \/\/ import \"perkeep.org\/pkg\/test\/dockertest\"\n\nimport (\n\t\"bytes\"\n\t\"compress\/gzip\"\n\t\"database\/sql\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"perkeep.org\/internal\/netutil\"\n)\n\n\/\/ Debug when set, prevents any container from being removed.\nvar Debug bool\n\n\/\/\/ runLongTest checks all the conditions for running a docker container\n\/\/ based on image.\nfunc runLongTest(t *testing.T, image string) {\n\tif testing.Short() {\n\t\tt.Skip(\"skipping in short mode\")\n\t}\n\tif !haveDocker() {\n\t\tt.Skip(\"skipping test; 'docker' command not found\")\n\t}\n\tif ok, err := haveImage(image); !ok || err != nil {\n\t\tif err != nil {\n\t\t\tt.Skipf(\"Error running docker to check for %s: %v\", image, err)\n\t\t}\n\t\tlog.Printf(\"Pulling docker image %s ...\", image)\n\t\tif strings.HasPrefix(image, \"camlistore\/\") {\n\t\t\tif err := loadCamliHubImage(image); err != nil {\n\t\t\t\tt.Skipf(\"Error pulling %s: %v\", image, err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tif err := Pull(image); err != nil {\n\t\t\tt.Skipf(\"Error pulling %s: %v\", image, err)\n\t\t}\n\t}\n}\n\n\/\/ loadCamliHubImage fetches a docker image saved as a .tar.gz in the\n\/\/ camlistore-docker bucket, and loads it in docker.\nfunc loadCamliHubImage(image string) error {\n\tif !strings.HasPrefix(image, \"camlistore\/\") {\n\t\treturn fmt.Errorf(\"not an image hosted on camlistore-docker\")\n\t}\n\timgURL := camliHub + strings.TrimPrefix(image, \"camlistore\/\") + \".tar.gz\"\n\tresp, err := http.Get(imgURL)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error fetching image %s: %v\", image, err)\n\t}\n\tdefer resp.Body.Close()\n\n\tdockerLoad := exec.Command(\"docker\", \"load\")\n\tdockerLoad.Stderr = os.Stderr\n\ttar, err := dockerLoad.StdinPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\terrc1 := make(chan error)\n\terrc2 := make(chan error)\n\tgo func() {\n\t\tdefer tar.Close()\n\t\tzr, err := gzip.NewReader(resp.Body)\n\t\tif err != nil {\n\t\t\terrc1 <- fmt.Errorf(\"gzip reader error for image %s: %v\", image, err)\n\t\t\treturn\n\t\t}\n\t\tdefer zr.Close()\n\t\tif _, err = io.Copy(tar, zr); err != nil {\n\t\t\terrc1 <- fmt.Errorf(\"error gunzipping image %s: %v\", image, err)\n\t\t\treturn\n\t\t}\n\t\terrc1 <- nil\n\t}()\n\tgo func() {\n\t\tif err := dockerLoad.Run(); err != nil {\n\t\t\terrc2 <- fmt.Errorf(\"error running docker load %v: %v\", image, err)\n\t\t\treturn\n\t\t}\n\t\terrc2 <- nil\n\t}()\n\tselect {\n\tcase err := <-errc1:\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn <-errc2\n\tcase err := <-errc2:\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn <-errc1\n\t}\n\treturn nil\n}\n\n\/\/ haveDocker returns whether the \"docker\" command was found.\nfunc haveDocker() bool {\n\t_, err := exec.LookPath(\"docker\")\n\treturn err == nil\n}\n\nfunc haveImage(name string) (ok bool, err error) {\n\tout, err := exec.Command(\"docker\", \"images\", \"--no-trunc\").Output()\n\tif err != nil {\n\t\treturn\n\t}\n\treturn bytes.Contains(out, []byte(name)), nil\n}\n\nfunc run(args ...string) (containerID string, err error) {\n\tcmd := exec.Command(\"docker\", append([]string{\"run\"}, args...)...)\n\tvar stdout, stderr bytes.Buffer\n\tcmd.Stdout, cmd.Stderr = &stdout, &stderr\n\tif err = cmd.Run(); err != nil {\n\t\terr = fmt.Errorf(\"%v%v\", stderr.String(), err)\n\t\treturn\n\t}\n\tcontainerID = strings.TrimSpace(stdout.String())\n\tif containerID == \"\" {\n\t\treturn \"\", errors.New(\"unexpected empty output from `docker run`\")\n\t}\n\treturn\n}\n\nfunc KillContainer(container string) error {\n\treturn exec.Command(\"docker\", \"kill\", container).Run()\n}\n\n\/\/ Pull retrieves the docker image with 'docker pull'.\nfunc Pull(image string) error {\n\tvar stdout, stderr bytes.Buffer\n\tcmd := exec.Command(\"docker\", \"pull\", image)\n\tcmd.Stdout = &stdout\n\tcmd.Stderr = &stderr\n\terr := cmd.Run()\n\tout := stdout.String()\n\t\/\/ TODO(mpl): if it turns out docker respects conventions and the\n\t\/\/ \"Authentication is required\" message does come from stderr, then quit\n\t\/\/ checking stdout.\n\tif err != nil || stderr.Len() != 0 || strings.Contains(out, \"Authentication is required\") {\n\t\treturn fmt.Errorf(\"docker pull failed: stdout: %s, stderr: %s, err: %v\", out, stderr.String(), err)\n\t}\n\treturn nil\n}\n\n\/\/ IP returns the IP address of the container.\nfunc IP(containerID string) (string, error) {\n\tout, err := exec.Command(\"docker\", \"inspect\", containerID).Output()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\ttype networkSettings struct {\n\t\tIPAddress string\n\t}\n\ttype container struct {\n\t\tNetworkSettings networkSettings\n\t}\n\tvar c []container\n\tif err := json.NewDecoder(bytes.NewReader(out)).Decode(&c); err != nil {\n\t\treturn \"\", err\n\t}\n\tif len(c) == 0 {\n\t\treturn \"\", errors.New(\"no output from docker inspect\")\n\t}\n\tif ip := c[0].NetworkSettings.IPAddress; ip != \"\" {\n\t\treturn ip, nil\n\t}\n\treturn \"\", errors.New(\"could not find an IP. Not running?\")\n}\n\ntype ContainerID string\n\nfunc (c ContainerID) IP() (string, error) {\n\treturn IP(string(c))\n}\n\nfunc (c ContainerID) Kill() error {\n\tif string(c) == \"\" {\n\t\treturn nil\n\t}\n\treturn KillContainer(string(c))\n}\n\n\/\/ Remove runs \"docker rm\" on the container\nfunc (c ContainerID) Remove() error {\n\tif Debug {\n\t\treturn nil\n\t}\n\tif string(c) == \"\" {\n\t\treturn nil\n\t}\n\treturn exec.Command(\"docker\", \"rm\", \"-v\", string(c)).Run()\n}\n\n\/\/ KillRemove calls Kill on the container, and then Remove if there was\n\/\/ no error. It logs any error to t.\nfunc (c ContainerID) KillRemove(t *testing.T) {\n\tif err := c.Kill(); err != nil {\n\t\tt.Log(err)\n\t\treturn\n\t}\n\tif err := c.Remove(); err != nil {\n\t\tt.Log(err)\n\t}\n}\n\n\/\/ lookup retrieves the ip address of the container, and tries to reach\n\/\/ before timeout the tcp address at this ip and given port.\nfunc (c ContainerID) lookup(port int, timeout time.Duration) (ip string, err error) {\n\tip, err = c.IP()\n\tif err != nil {\n\t\terr = fmt.Errorf(\"error getting IP: %v\", err)\n\t\treturn\n\t}\n\taddr := fmt.Sprintf(\"%s:%d\", ip, port)\n\terr = netutil.AwaitReachable(addr, timeout)\n\treturn\n}\n\n\/\/ setupContainer sets up a container, using the start function to run the given image.\n\/\/ It also looks up the IP address of the container, and tests this address with the given\n\/\/ port and timeout. It returns the container ID and its IP address, or makes the test\n\/\/ fail on error.\nfunc setupContainer(t *testing.T, image string, port int, timeout time.Duration,\n\tstart func() (string, error)) (c ContainerID, ip string) {\n\trunLongTest(t, image)\n\n\tcontainerID, err := start()\n\tif err != nil {\n\t\tt.Fatalf(\"docker run: %v\", err)\n\t}\n\tc = ContainerID(containerID)\n\tip, err = c.lookup(port, timeout)\n\tif err != nil {\n\t\tc.KillRemove(t)\n\t\tt.Skipf(\"Skipping test for container %v: %v\", c, err)\n\t}\n\treturn\n}\n\nconst (\n\tmongoImage = \"mpl7\/mongo\"\n\tmysqlImage = \"mysql\"\n\tMySQLUsername = \"root\"\n\tMySQLPassword = \"root\"\n\tpostgresImage = \"nornagon\/postgres\"\n\tPostgresUsername = \"docker\" \/\/ set up by the dockerfile of postgresImage\n\tPostgresPassword = \"docker\" \/\/ set up by the dockerfile of postgresImage\n\tcamliHub = \"https:\/\/storage.googleapis.com\/camlistore-docker\/\"\n\tfakeS3Image = \"camlistore\/fakes3\"\n)\n\nfunc SetupFakeS3Container(t *testing.T) (c ContainerID, ip string) {\n\treturn setupContainer(t, fakeS3Image, 4567, 10*time.Second, func() (string, error) {\n\t\treturn run(\"-d\", fakeS3Image)\n\t})\n}\n\n\/\/ SetupMongoContainer sets up a real MongoDB instance for testing purposes,\n\/\/ using a Docker container. It returns the container ID and its IP address,\n\/\/ or makes the test fail on error.\n\/\/ Currently using https:\/\/index.docker.io\/u\/robinvdvleuten\/mongo\/\nfunc SetupMongoContainer(t *testing.T) (c ContainerID, ip string) {\n\treturn setupContainer(t, mongoImage, 27017, 10*time.Second, func() (string, error) {\n\t\treturn run(\"-d\", mongoImage, \"--nojournal\")\n\t})\n}\n\n\/\/ SetupMySQLContainer sets up a real MySQL instance for testing purposes,\n\/\/ using a Docker container. It returns the container ID and its IP address,\n\/\/ or makes the test fail on error.\n\/\/ Currently using https:\/\/hub.docker.com\/_\/mysql\/\nfunc SetupMySQLContainer(t *testing.T, dbname string) (c ContainerID, ip string) {\n\treturn setupContainer(t, mysqlImage, 3306, 20*time.Second, func() (string, error) {\n\t\treturn run(\"-d\", \"-e\", \"MYSQL_ROOT_PASSWORD=\"+MySQLPassword, \"-e\", \"MYSQL_DATABASE=\"+dbname, mysqlImage)\n\t})\n}\n\n\/\/ SetupPostgreSQLContainer sets up a real PostgreSQL instance for testing purposes,\n\/\/ using a Docker container. It returns the container ID and its IP address,\n\/\/ or makes the test fail on error.\n\/\/ Currently using https:\/\/index.docker.io\/u\/nornagon\/postgres\nfunc SetupPostgreSQLContainer(t *testing.T, dbname string) (c ContainerID, ip string) {\n\tc, ip = setupContainer(t, postgresImage, 5432, 15*time.Second, func() (string, error) {\n\t\treturn run(\"-d\", postgresImage)\n\t})\n\tcleanupAndDie := func(err error) {\n\t\tc.KillRemove(t)\n\t\tt.Fatal(err)\n\t}\n\trootdb, err := sql.Open(\"postgres\",\n\t\tfmt.Sprintf(\"user=%s password=%s host=%s dbname=postgres sslmode=disable\", PostgresUsername, PostgresPassword, ip))\n\tif err != nil {\n\t\tcleanupAndDie(fmt.Errorf(\"Could not open postgres rootdb: %v\", err))\n\t}\n\tif _, err := sqlExecRetry(rootdb,\n\t\t\"CREATE DATABASE \"+dbname+\" LC_COLLATE = 'C' TEMPLATE = template0\",\n\t\t50); err != nil {\n\t\tcleanupAndDie(fmt.Errorf(\"Could not create database %v: %v\", dbname, err))\n\t}\n\treturn\n}\n\n\/\/ sqlExecRetry keeps calling http:\/\/golang.org\/pkg\/database\/sql\/#DB.Exec on db\n\/\/ with stmt until it succeeds or until it has been tried maxTry times.\n\/\/ It sleeps in between tries, twice longer after each new try, starting with\n\/\/ 100 milliseconds.\nfunc sqlExecRetry(db *sql.DB, stmt string, maxTry int) (sql.Result, error) {\n\tif maxTry <= 0 {\n\t\treturn nil, errors.New(\"did not try at all\")\n\t}\n\tinterval := 100 * time.Millisecond\n\ttry := 0\n\tvar err error\n\tvar result sql.Result\n\tfor {\n\t\tresult, err = db.Exec(stmt)\n\t\tif err == nil {\n\t\t\treturn result, nil\n\t\t}\n\t\ttry++\n\t\tif try == maxTry {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(interval)\n\t\tinterval *= 2\n\t}\n\treturn result, fmt.Errorf(\"failed %v times: %v\", try, err)\n}\npkg\/test\/docker: force the MySQL version to 5\/*\nCopyright 2014 The Perkeep Authors\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\n\/*\nPackage dockertest contains helper functions for setting up and tearing down docker containers to aid in testing.\n*\/\npackage dockertest \/\/ import \"perkeep.org\/pkg\/test\/dockertest\"\n\nimport (\n\t\"bytes\"\n\t\"compress\/gzip\"\n\t\"database\/sql\"\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"perkeep.org\/internal\/netutil\"\n)\n\n\/\/ Debug when set, prevents any container from being removed.\nvar Debug bool\n\n\/\/\/ runLongTest checks all the conditions for running a docker container\n\/\/ based on image.\nfunc runLongTest(t *testing.T, image string) {\n\tif testing.Short() {\n\t\tt.Skip(\"skipping in short mode\")\n\t}\n\tif !haveDocker() {\n\t\tt.Skip(\"skipping test; 'docker' command not found\")\n\t}\n\tif ok, err := haveImage(image); !ok || err != nil {\n\t\tif err != nil {\n\t\t\tt.Skipf(\"Error running docker to check for %s: %v\", image, err)\n\t\t}\n\t\tlog.Printf(\"Pulling docker image %s ...\", image)\n\t\tif strings.HasPrefix(image, \"camlistore\/\") {\n\t\t\tif err := loadCamliHubImage(image); err != nil {\n\t\t\t\tt.Skipf(\"Error pulling %s: %v\", image, err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tif err := Pull(image); err != nil {\n\t\t\tt.Skipf(\"Error pulling %s: %v\", image, err)\n\t\t}\n\t}\n}\n\n\/\/ loadCamliHubImage fetches a docker image saved as a .tar.gz in the\n\/\/ camlistore-docker bucket, and loads it in docker.\nfunc loadCamliHubImage(image string) error {\n\tif !strings.HasPrefix(image, \"camlistore\/\") {\n\t\treturn fmt.Errorf(\"not an image hosted on camlistore-docker\")\n\t}\n\timgURL := camliHub + strings.TrimPrefix(image, \"camlistore\/\") + \".tar.gz\"\n\tresp, err := http.Get(imgURL)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error fetching image %s: %v\", image, err)\n\t}\n\tdefer resp.Body.Close()\n\n\tdockerLoad := exec.Command(\"docker\", \"load\")\n\tdockerLoad.Stderr = os.Stderr\n\ttar, err := dockerLoad.StdinPipe()\n\tif err != nil {\n\t\treturn err\n\t}\n\terrc1 := make(chan error)\n\terrc2 := make(chan error)\n\tgo func() {\n\t\tdefer tar.Close()\n\t\tzr, err := gzip.NewReader(resp.Body)\n\t\tif err != nil {\n\t\t\terrc1 <- fmt.Errorf(\"gzip reader error for image %s: %v\", image, err)\n\t\t\treturn\n\t\t}\n\t\tdefer zr.Close()\n\t\tif _, err = io.Copy(tar, zr); err != nil {\n\t\t\terrc1 <- fmt.Errorf(\"error gunzipping image %s: %v\", image, err)\n\t\t\treturn\n\t\t}\n\t\terrc1 <- nil\n\t}()\n\tgo func() {\n\t\tif err := dockerLoad.Run(); err != nil {\n\t\t\terrc2 <- fmt.Errorf(\"error running docker load %v: %v\", image, err)\n\t\t\treturn\n\t\t}\n\t\terrc2 <- nil\n\t}()\n\tselect {\n\tcase err := <-errc1:\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn <-errc2\n\tcase err := <-errc2:\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn <-errc1\n\t}\n\treturn nil\n}\n\n\/\/ haveDocker returns whether the \"docker\" command was found.\nfunc haveDocker() bool {\n\t_, err := exec.LookPath(\"docker\")\n\treturn err == nil\n}\n\nfunc haveImage(name string) (ok bool, err error) {\n\tout, err := exec.Command(\"docker\", \"images\", \"--no-trunc\").Output()\n\tif err != nil {\n\t\treturn\n\t}\n\treturn bytes.Contains(out, []byte(name)), nil\n}\n\nfunc run(args ...string) (containerID string, err error) {\n\tcmd := exec.Command(\"docker\", append([]string{\"run\"}, args...)...)\n\tvar stdout, stderr bytes.Buffer\n\tcmd.Stdout, cmd.Stderr = &stdout, &stderr\n\tif err = cmd.Run(); err != nil {\n\t\terr = fmt.Errorf(\"%v%v\", stderr.String(), err)\n\t\treturn\n\t}\n\tcontainerID = strings.TrimSpace(stdout.String())\n\tif containerID == \"\" {\n\t\treturn \"\", errors.New(\"unexpected empty output from `docker run`\")\n\t}\n\treturn\n}\n\nfunc KillContainer(container string) error {\n\treturn exec.Command(\"docker\", \"kill\", container).Run()\n}\n\n\/\/ Pull retrieves the docker image with 'docker pull'.\nfunc Pull(image string) error {\n\tvar stdout, stderr bytes.Buffer\n\tcmd := exec.Command(\"docker\", \"pull\", image)\n\tcmd.Stdout = &stdout\n\tcmd.Stderr = &stderr\n\terr := cmd.Run()\n\tout := stdout.String()\n\t\/\/ TODO(mpl): if it turns out docker respects conventions and the\n\t\/\/ \"Authentication is required\" message does come from stderr, then quit\n\t\/\/ checking stdout.\n\tif err != nil || stderr.Len() != 0 || strings.Contains(out, \"Authentication is required\") {\n\t\treturn fmt.Errorf(\"docker pull failed: stdout: %s, stderr: %s, err: %v\", out, stderr.String(), err)\n\t}\n\treturn nil\n}\n\n\/\/ IP returns the IP address of the container.\nfunc IP(containerID string) (string, error) {\n\tout, err := exec.Command(\"docker\", \"inspect\", containerID).Output()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\ttype networkSettings struct {\n\t\tIPAddress string\n\t}\n\ttype container struct {\n\t\tNetworkSettings networkSettings\n\t}\n\tvar c []container\n\tif err := json.NewDecoder(bytes.NewReader(out)).Decode(&c); err != nil {\n\t\treturn \"\", err\n\t}\n\tif len(c) == 0 {\n\t\treturn \"\", errors.New(\"no output from docker inspect\")\n\t}\n\tif ip := c[0].NetworkSettings.IPAddress; ip != \"\" {\n\t\treturn ip, nil\n\t}\n\treturn \"\", errors.New(\"could not find an IP. Not running?\")\n}\n\ntype ContainerID string\n\nfunc (c ContainerID) IP() (string, error) {\n\treturn IP(string(c))\n}\n\nfunc (c ContainerID) Kill() error {\n\tif string(c) == \"\" {\n\t\treturn nil\n\t}\n\treturn KillContainer(string(c))\n}\n\n\/\/ Remove runs \"docker rm\" on the container\nfunc (c ContainerID) Remove() error {\n\tif Debug {\n\t\treturn nil\n\t}\n\tif string(c) == \"\" {\n\t\treturn nil\n\t}\n\treturn exec.Command(\"docker\", \"rm\", \"-v\", string(c)).Run()\n}\n\n\/\/ KillRemove calls Kill on the container, and then Remove if there was\n\/\/ no error. It logs any error to t.\nfunc (c ContainerID) KillRemove(t *testing.T) {\n\tif err := c.Kill(); err != nil {\n\t\tt.Log(err)\n\t\treturn\n\t}\n\tif err := c.Remove(); err != nil {\n\t\tt.Log(err)\n\t}\n}\n\n\/\/ lookup retrieves the ip address of the container, and tries to reach\n\/\/ before timeout the tcp address at this ip and given port.\nfunc (c ContainerID) lookup(port int, timeout time.Duration) (ip string, err error) {\n\tip, err = c.IP()\n\tif err != nil {\n\t\terr = fmt.Errorf(\"error getting IP: %v\", err)\n\t\treturn\n\t}\n\taddr := fmt.Sprintf(\"%s:%d\", ip, port)\n\terr = netutil.AwaitReachable(addr, timeout)\n\treturn\n}\n\n\/\/ setupContainer sets up a container, using the start function to run the given image.\n\/\/ It also looks up the IP address of the container, and tests this address with the given\n\/\/ port and timeout. It returns the container ID and its IP address, or makes the test\n\/\/ fail on error.\nfunc setupContainer(t *testing.T, image string, port int, timeout time.Duration,\n\tstart func() (string, error)) (c ContainerID, ip string) {\n\trunLongTest(t, image)\n\n\tcontainerID, err := start()\n\tif err != nil {\n\t\tt.Fatalf(\"docker run: %v\", err)\n\t}\n\tc = ContainerID(containerID)\n\tip, err = c.lookup(port, timeout)\n\tif err != nil {\n\t\tc.KillRemove(t)\n\t\tt.Skipf(\"Skipping test for container %v: %v\", c, err)\n\t}\n\treturn\n}\n\nconst (\n\tmongoImage = \"mpl7\/mongo\"\n\tmysqlImage = \"mysql:5\"\n\tMySQLUsername = \"root\"\n\tMySQLPassword = \"root\"\n\tpostgresImage = \"nornagon\/postgres\"\n\tPostgresUsername = \"docker\" \/\/ set up by the dockerfile of postgresImage\n\tPostgresPassword = \"docker\" \/\/ set up by the dockerfile of postgresImage\n\tcamliHub = \"https:\/\/storage.googleapis.com\/camlistore-docker\/\"\n\tfakeS3Image = \"camlistore\/fakes3\"\n)\n\nfunc SetupFakeS3Container(t *testing.T) (c ContainerID, ip string) {\n\treturn setupContainer(t, fakeS3Image, 4567, 10*time.Second, func() (string, error) {\n\t\treturn run(\"-d\", fakeS3Image)\n\t})\n}\n\n\/\/ SetupMongoContainer sets up a real MongoDB instance for testing purposes,\n\/\/ using a Docker container. It returns the container ID and its IP address,\n\/\/ or makes the test fail on error.\n\/\/ Currently using https:\/\/index.docker.io\/u\/robinvdvleuten\/mongo\/\nfunc SetupMongoContainer(t *testing.T) (c ContainerID, ip string) {\n\treturn setupContainer(t, mongoImage, 27017, 10*time.Second, func() (string, error) {\n\t\treturn run(\"-d\", mongoImage, \"--nojournal\")\n\t})\n}\n\n\/\/ SetupMySQLContainer sets up a real MySQL instance for testing purposes,\n\/\/ using a Docker container. It returns the container ID and its IP address,\n\/\/ or makes the test fail on error.\n\/\/ Currently using https:\/\/hub.docker.com\/_\/mysql\/\nfunc SetupMySQLContainer(t *testing.T, dbname string) (c ContainerID, ip string) {\n\treturn setupContainer(t, mysqlImage, 3306, 20*time.Second, func() (string, error) {\n\t\treturn run(\"-d\", \"-e\", \"MYSQL_ROOT_PASSWORD=\"+MySQLPassword, \"-e\", \"MYSQL_DATABASE=\"+dbname, mysqlImage)\n\t})\n}\n\n\/\/ SetupPostgreSQLContainer sets up a real PostgreSQL instance for testing purposes,\n\/\/ using a Docker container. It returns the container ID and its IP address,\n\/\/ or makes the test fail on error.\n\/\/ Currently using https:\/\/index.docker.io\/u\/nornagon\/postgres\nfunc SetupPostgreSQLContainer(t *testing.T, dbname string) (c ContainerID, ip string) {\n\tc, ip = setupContainer(t, postgresImage, 5432, 15*time.Second, func() (string, error) {\n\t\treturn run(\"-d\", postgresImage)\n\t})\n\tcleanupAndDie := func(err error) {\n\t\tc.KillRemove(t)\n\t\tt.Fatal(err)\n\t}\n\trootdb, err := sql.Open(\"postgres\",\n\t\tfmt.Sprintf(\"user=%s password=%s host=%s dbname=postgres sslmode=disable\", PostgresUsername, PostgresPassword, ip))\n\tif err != nil {\n\t\tcleanupAndDie(fmt.Errorf(\"Could not open postgres rootdb: %v\", err))\n\t}\n\tif _, err := sqlExecRetry(rootdb,\n\t\t\"CREATE DATABASE \"+dbname+\" LC_COLLATE = 'C' TEMPLATE = template0\",\n\t\t50); err != nil {\n\t\tcleanupAndDie(fmt.Errorf(\"Could not create database %v: %v\", dbname, err))\n\t}\n\treturn\n}\n\n\/\/ sqlExecRetry keeps calling http:\/\/golang.org\/pkg\/database\/sql\/#DB.Exec on db\n\/\/ with stmt until it succeeds or until it has been tried maxTry times.\n\/\/ It sleeps in between tries, twice longer after each new try, starting with\n\/\/ 100 milliseconds.\nfunc sqlExecRetry(db *sql.DB, stmt string, maxTry int) (sql.Result, error) {\n\tif maxTry <= 0 {\n\t\treturn nil, errors.New(\"did not try at all\")\n\t}\n\tinterval := 100 * time.Millisecond\n\ttry := 0\n\tvar err error\n\tvar result sql.Result\n\tfor {\n\t\tresult, err = db.Exec(stmt)\n\t\tif err == nil {\n\t\t\treturn result, nil\n\t\t}\n\t\ttry++\n\t\tif try == maxTry {\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(interval)\n\t\tinterval *= 2\n\t}\n\treturn result, fmt.Errorf(\"failed %v times: %v\", try, err)\n}\n<|endoftext|>"} {"text":"\/*\nCopyright 2014 Google Inc. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage tools\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/coreos\/go-etcd\/etcd\"\n)\n\ntype EtcdResponseWithError struct {\n\tR *etcd.Response\n\tE error\n}\n\n\/\/ TestLogger is a type passed to Test functions to support formatted test logs.\ntype TestLogger interface {\n\tErrorf(format string, args ...interface{})\n\tLogf(format string, args ...interface{})\n}\n\ntype FakeEtcdClient struct {\n\twatchCompletedChan chan bool\n\n\tData map[string]EtcdResponseWithError\n\tDeletedKeys []string\n\tErr error\n\tt TestLogger\n\tIx int\n\n\t\/\/ Will become valid after Watch is called; tester may write to it. Tester may\n\t\/\/ also read from it to verify that it's closed after injecting an error.\n\tWatchResponse chan *etcd.Response\n\t\/\/ Write to this to prematurely stop a Watch that is running in a goroutine.\n\tWatchInjectError chan<- error\n\tWatchStop chan<- bool\n}\n\nfunc MakeFakeEtcdClient(t TestLogger) *FakeEtcdClient {\n\tret := &FakeEtcdClient{\n\t\tt: t,\n\t\tData: map[string]EtcdResponseWithError{},\n\t}\n\t\/\/ There are three publicly accessible channels in FakeEtcdClient:\n\t\/\/ - WatchResponse\n\t\/\/ - WatchInjectError\n\t\/\/ - WatchStop\n\t\/\/ They are only available when Watch() is called. If users of\n\t\/\/ FakeEtcdClient want to use any of these channels, they have to call\n\t\/\/ WaitForWatchCompletion before any operation on these channels.\n\t\/\/ Internally, FakeEtcdClient use watchCompletedChan to indicate if the\n\t\/\/ Watch() method has been called. WaitForWatchCompletion() will wait\n\t\/\/ on this channel. WaitForWatchCompletion() will return only when\n\t\/\/ WatchResponse, WatchInjectError and WatchStop are ready to read\/write.\n\tret.watchCompletedChan = make(chan bool)\n\treturn ret\n}\n\nfunc (f *FakeEtcdClient) AddChild(key, data string, ttl uint64) (*etcd.Response, error) {\n\tf.Ix = f.Ix + 1\n\treturn f.Set(fmt.Sprintf(\"%s\/%d\", key, f.Ix), data, ttl)\n}\n\nfunc (f *FakeEtcdClient) Get(key string, sort, recursive bool) (*etcd.Response, error) {\n\tresult := f.Data[key]\n\tif result.R == nil {\n\t\tf.t.Errorf(\"Unexpected get for %s\", key)\n\t\treturn &etcd.Response{}, EtcdErrorNotFound\n\t}\n\tf.t.Logf(\"returning %v: %v %#v\", key, result.R, result.E)\n\treturn result.R, result.E\n}\n\nfunc (f *FakeEtcdClient) Set(key, value string, ttl uint64) (*etcd.Response, error) {\n\tresult := EtcdResponseWithError{\n\t\tR: &etcd.Response{\n\t\t\tNode: &etcd.Node{\n\t\t\t\tValue: value,\n\t\t\t},\n\t\t},\n\t}\n\tf.Data[key] = result\n\treturn result.R, f.Err\n}\n\nfunc (f *FakeEtcdClient) CompareAndSwap(key, value string, ttl uint64, prevValue string, prevIndex uint64) (*etcd.Response, error) {\n\t\/\/ TODO: Maybe actually implement compare and swap here?\n\treturn f.Set(key, value, ttl)\n}\n\nfunc (f *FakeEtcdClient) Create(key, value string, ttl uint64) (*etcd.Response, error) {\n\treturn f.Set(key, value, ttl)\n}\nfunc (f *FakeEtcdClient) Delete(key string, recursive bool) (*etcd.Response, error) {\n\tf.Data[key] = EtcdResponseWithError{\n\t\tR: &etcd.Response{\n\t\t\tNode: nil,\n\t\t},\n\t\tE: EtcdErrorNotFound,\n\t}\n\n\tf.DeletedKeys = append(f.DeletedKeys, key)\n\treturn &etcd.Response{}, f.Err\n}\n\nfunc (f *FakeEtcdClient) WaitForWatchCompletion() {\n\t<-f.watchCompletedChan\n}\n\nfunc (f *FakeEtcdClient) Watch(prefix string, waitIndex uint64, recursive bool, receiver chan *etcd.Response, stop chan bool) (*etcd.Response, error) {\n\tf.WatchResponse = receiver\n\tf.WatchStop = stop\n\tinjectedError := make(chan error)\n\n\tdefer close(injectedError)\n\tf.WatchInjectError = injectedError\n\n\tif receiver == nil {\n\t\treturn f.Get(prefix, false, recursive)\n\t}\n\n\tf.watchCompletedChan <- true\n\tselect {\n\tcase <-stop:\n\t\treturn nil, etcd.ErrWatchStoppedByUser\n\tcase err := <-injectedError:\n\t\t\/\/ Emulate etcd's behavior.\n\t\tclose(receiver)\n\t\treturn nil, err\n\t}\n\t\/\/ Never get here.\n\treturn nil, nil\n}\nFakeEtcdClient: Maintain change index\/*\nCopyright 2014 Google Inc. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*\/\n\npackage tools\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/coreos\/go-etcd\/etcd\"\n)\n\ntype EtcdResponseWithError struct {\n\tR *etcd.Response\n\tE error\n}\n\n\/\/ TestLogger is a type passed to Test functions to support formatted test logs.\ntype TestLogger interface {\n\tErrorf(format string, args ...interface{})\n\tLogf(format string, args ...interface{})\n}\n\ntype FakeEtcdClient struct {\n\twatchCompletedChan chan bool\n\n\tData map[string]EtcdResponseWithError\n\tDeletedKeys []string\n\tErr error\n\tt TestLogger\n\tIx int\n\tChangeIndex uint64\n\n\t\/\/ Will become valid after Watch is called; tester may write to it. Tester may\n\t\/\/ also read from it to verify that it's closed after injecting an error.\n\tWatchResponse chan *etcd.Response\n\t\/\/ Write to this to prematurely stop a Watch that is running in a goroutine.\n\tWatchInjectError chan<- error\n\tWatchStop chan<- bool\n}\n\nfunc MakeFakeEtcdClient(t TestLogger) *FakeEtcdClient {\n\tret := &FakeEtcdClient{\n\t\tt: t,\n\t\tData: map[string]EtcdResponseWithError{},\n\t}\n\t\/\/ There are three publicly accessible channels in FakeEtcdClient:\n\t\/\/ - WatchResponse\n\t\/\/ - WatchInjectError\n\t\/\/ - WatchStop\n\t\/\/ They are only available when Watch() is called. If users of\n\t\/\/ FakeEtcdClient want to use any of these channels, they have to call\n\t\/\/ WaitForWatchCompletion before any operation on these channels.\n\t\/\/ Internally, FakeEtcdClient use watchCompletedChan to indicate if the\n\t\/\/ Watch() method has been called. WaitForWatchCompletion() will wait\n\t\/\/ on this channel. WaitForWatchCompletion() will return only when\n\t\/\/ WatchResponse, WatchInjectError and WatchStop are ready to read\/write.\n\tret.watchCompletedChan = make(chan bool)\n\treturn ret\n}\n\nfunc (f *FakeEtcdClient) generateIndex() uint64 {\n\tf.ChangeIndex++\n\treturn f.ChangeIndex\n}\n\nfunc (f *FakeEtcdClient) AddChild(key, data string, ttl uint64) (*etcd.Response, error) {\n\tf.Ix = f.Ix + 1\n\treturn f.Set(fmt.Sprintf(\"%s\/%d\", key, f.Ix), data, ttl)\n}\n\nfunc (f *FakeEtcdClient) Get(key string, sort, recursive bool) (*etcd.Response, error) {\n\tresult := f.Data[key]\n\tif result.R == nil {\n\t\tf.t.Errorf(\"Unexpected get for %s\", key)\n\t\treturn &etcd.Response{}, EtcdErrorNotFound\n\t}\n\tf.t.Logf(\"returning %v: %v %#v\", key, result.R, result.E)\n\treturn result.R, result.E\n}\n\nfunc (f *FakeEtcdClient) Set(key, value string, ttl uint64) (*etcd.Response, error) {\n\ti := f.generateIndex()\n\n\tif prevResult, ok := f.Data[key]; ok && prevResult.R != nil && prevResult.R.Node != nil {\n\t\tcreatedIndex := prevResult.R.Node.CreatedIndex\n\t\tresult := EtcdResponseWithError{\n\t\t\tR: &etcd.Response{\n\t\t\t\tNode: &etcd.Node{\n\t\t\t\t\tValue: value,\n\t\t\t\t\tCreatedIndex: createdIndex,\n\t\t\t\t\tModifiedIndex: i,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\tf.Data[key] = result\n\t\treturn result.R, f.Err\n\t}\n\n\tresult := EtcdResponseWithError{\n\t\tR: &etcd.Response{\n\t\t\tNode: &etcd.Node{\n\t\t\t\tValue: value,\n\t\t\t\tCreatedIndex: i,\n\t\t\t\tModifiedIndex: i,\n\t\t\t},\n\t\t},\n\t}\n\tf.Data[key] = result\n\treturn result.R, f.Err\n}\n\nfunc (f *FakeEtcdClient) CompareAndSwap(key, value string, ttl uint64, prevValue string, prevIndex uint64) (*etcd.Response, error) {\n\t\/\/ TODO: Maybe actually implement compare and swap here?\n\treturn f.Set(key, value, ttl)\n}\n\nfunc (f *FakeEtcdClient) Create(key, value string, ttl uint64) (*etcd.Response, error) {\n\treturn f.Set(key, value, ttl)\n}\nfunc (f *FakeEtcdClient) Delete(key string, recursive bool) (*etcd.Response, error) {\n\tf.Data[key] = EtcdResponseWithError{\n\t\tR: &etcd.Response{\n\t\t\tNode: nil,\n\t\t},\n\t\tE: EtcdErrorNotFound,\n\t}\n\n\tf.DeletedKeys = append(f.DeletedKeys, key)\n\treturn &etcd.Response{}, f.Err\n}\n\nfunc (f *FakeEtcdClient) WaitForWatchCompletion() {\n\t<-f.watchCompletedChan\n}\n\nfunc (f *FakeEtcdClient) Watch(prefix string, waitIndex uint64, recursive bool, receiver chan *etcd.Response, stop chan bool) (*etcd.Response, error) {\n\tf.WatchResponse = receiver\n\tf.WatchStop = stop\n\tinjectedError := make(chan error)\n\n\tdefer close(injectedError)\n\tf.WatchInjectError = injectedError\n\n\tif receiver == nil {\n\t\treturn f.Get(prefix, false, recursive)\n\t}\n\n\tf.watchCompletedChan <- true\n\tselect {\n\tcase <-stop:\n\t\treturn nil, etcd.ErrWatchStoppedByUser\n\tcase err := <-injectedError:\n\t\t\/\/ Emulate etcd's behavior.\n\t\tclose(receiver)\n\t\treturn nil, err\n\t}\n\t\/\/ Never get here.\n\treturn nil, nil\n}\n<|endoftext|>"} {"text":"package hal\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ Evt is a generic container for events processed by the bot.\n\/\/ Event sources are responsible for copying the appropriate data into\n\/\/ the Evt fields. Routing and most plugins will not work if the body\n\/\/ isn't copied, at a minimum.\n\/\/ The original event should usually be attached to the Original\ntype Evt struct {\n\tBody string `json:\"body\"` \/\/ body of the event, regardless of source\n\tChannel string `json:\"channel\"` \/\/ the channel where the event originated\n\tFrom string `json:\"from\"` \/\/ the username that created the event\n\tTime time.Time `json:\"time\"` \/\/ timestamp of the event\n\tBroker Broker `json:\"broker\"` \/\/ the broker origin of the event\n\tIsGeneric bool `json:\"is_generic\"` \/\/ true if evt should be published to GenericBroker\n\tOriginal interface{} \/\/ the original message container (e.g. slack.MessageEvent)\n\tinstance *Instance \/\/ used by the broker to provide plugin instance metadata\n}\n\n\/\/ Clone() returns a copy of the event with the same broker\/channel\/from\n\/\/ and a current timestamp. Body and Original will be empty.\nfunc (e *Evt) Clone() Evt {\n\tout := Evt{\n\t\tChannel: e.Channel,\n\t\tFrom: e.From,\n\t\tTime: time.Now(),\n\t\tBroker: e.Broker,\n\t\tIsGeneric: e.IsGeneric,\n\t}\n\n\treturn out\n}\n\n\/\/ Reply is a helper that crafts a new event from the provided string\n\/\/ and initiates the reply on the broker attached to the event.\nfunc (e *Evt) Reply(msg string) {\n\tout := e.Clone()\n\tout.Body = msg\n\te.Broker.Send(out)\n}\n\n\/\/ Replyf is the same as Reply but allows for string formatting using\n\/\/ fmt.Sprintf()\nfunc (e *Evt) Replyf(msg string, a ...interface{}) {\n\te.Reply(fmt.Sprintf(msg, a...))\n}\n\n\/\/ fetch union of all matching settings from the database\n\/\/ for user, broker, channel, and plugin\n\/\/ Plugins can use the Prefs methods to filter from there.\nfunc (e *Evt) FindPrefs() Prefs {\n\tbroker := e.Broker.Name()\n\tplugin := e.instance.Plugin.Name\n\treturn FindPrefs(e.From, broker, e.Channel, plugin, \"\")\n}\n\n\/\/ gets the plugin instance's preferences\nfunc (e *Evt) InstanceSettings() []Pref {\n\tbroker := e.Broker.Name()\n\tplugin := e.instance.Plugin.Name\n\n\tout := make([]Pref, 0)\n\n\tfor _, stg := range e.instance.Plugin.Settings {\n\t\t\/\/ ignore channel-specific settings for other channels\n\t\tif stg.Channel != \"\" && stg.Channel != e.Channel {\n\t\t\tcontinue\n\t\t}\n\n\t\tpref := GetPref(\"\", broker, e.Channel, plugin, stg.Key, stg.Default)\n\t\tout = append(out, pref)\n\t}\n\n\treturn out\n}\n\n\/\/ NewPref creates a new pref struct with user, channel, broker, and plugin\n\/\/ set using metadata from the event.\nfunc (e *Evt) NewPref() Pref {\n\treturn Pref{\n\t\tUser: e.From,\n\t\tChannel: e.Channel,\n\t\tBroker: e.Broker.Name(),\n\t\tPlugin: e.instance.Plugin.Name,\n\t}\n}\n\n\/\/ BodyAsArgv does minimal parsing of the event body, returning an argv-like\n\/\/ array of strings with quoted strings intact (but with quotes removed).\n\/\/ The goal is shell-like, and is not a full implementation.\n\/\/ Leading\/trailing whitespace is removed.\n\/\/ Escaping quotes, etc. is not supported.\nfunc (e *Evt) BodyAsArgv() []string {\n\t\/\/ use a simple RE rather than pulling in a package to do this\n\tre := regexp.MustCompile(`'[^']*'|\"[^\"]*\"|\\S+`)\n\tbody := strings.TrimSpace(e.Body)\n\targv := re.FindAllString(body, -1)\n\n\t\/\/ remove the outer quotes from quoted strings\n\tfor i, val := range argv {\n\t\tif strings.HasPrefix(val, `'`) && strings.HasSuffix(val, `'`) {\n\t\t\ttmp := strings.TrimPrefix(val, `'`)\n\t\t\targv[i] = strings.TrimSuffix(tmp, `'`)\n\t\t} else if strings.HasPrefix(val, `\"`) && strings.HasSuffix(val, `\"`) {\n\t\t\ttmp := strings.TrimPrefix(val, `\"`)\n\t\t\targv[i] = strings.TrimSuffix(tmp, `\"`)\n\t\t}\n\t}\n\n\treturn argv\n}\n\nfunc (e *Evt) String() string {\n\treturn fmt.Sprintf(\"%s\/%s@%s: %s\", e.From, e.Channel, e.Time.String(), e.Body)\n}\nadd a BrokerName methodpackage hal\n\nimport (\n\t\"fmt\"\n\t\"regexp\"\n\t\"strings\"\n\t\"time\"\n)\n\n\/\/ Evt is a generic container for events processed by the bot.\n\/\/ Event sources are responsible for copying the appropriate data into\n\/\/ the Evt fields. Routing and most plugins will not work if the body\n\/\/ isn't copied, at a minimum.\n\/\/ The original event should usually be attached to the Original\ntype Evt struct {\n\tBody string `json:\"body\"` \/\/ body of the event, regardless of source\n\tChannel string `json:\"channel\"` \/\/ the channel where the event originated\n\tFrom string `json:\"from\"` \/\/ the username that created the event\n\tTime time.Time `json:\"time\"` \/\/ timestamp of the event\n\tBroker Broker `json:\"broker\"` \/\/ the broker origin of the event\n\tIsGeneric bool `json:\"is_generic\"` \/\/ true if evt should be published to GenericBroker\n\tOriginal interface{} \/\/ the original message container (e.g. slack.MessageEvent)\n\tinstance *Instance \/\/ used by the broker to provide plugin instance metadata\n}\n\n\/\/ Clone() returns a copy of the event with the same broker\/channel\/from\n\/\/ and a current timestamp. Body and Original will be empty.\nfunc (e *Evt) Clone() Evt {\n\tout := Evt{\n\t\tChannel: e.Channel,\n\t\tFrom: e.From,\n\t\tTime: time.Now(),\n\t\tBroker: e.Broker,\n\t\tIsGeneric: e.IsGeneric,\n\t}\n\n\treturn out\n}\n\n\/\/ Reply is a helper that crafts a new event from the provided string\n\/\/ and initiates the reply on the broker attached to the event.\nfunc (e *Evt) Reply(msg string) {\n\tout := e.Clone()\n\tout.Body = msg\n\te.Broker.Send(out)\n}\n\n\/\/ Replyf is the same as Reply but allows for string formatting using\n\/\/ fmt.Sprintf()\nfunc (e *Evt) Replyf(msg string, a ...interface{}) {\n\te.Reply(fmt.Sprintf(msg, a...))\n}\n\n\/\/ BrokerName returns the text name of the broker.\nfunc (e *Evt) BrokerName() string {\n\treturn e.Broker.Name\n}\n\n\/\/ fetch union of all matching settings from the database\n\/\/ for user, broker, channel, and plugin\n\/\/ Plugins can use the Prefs methods to filter from there.\nfunc (e *Evt) FindPrefs() Prefs {\n\tbroker := e.Broker.Name()\n\tplugin := e.instance.Plugin.Name\n\treturn FindPrefs(e.From, broker, e.Channel, plugin, \"\")\n}\n\n\/\/ gets the plugin instance's preferences\nfunc (e *Evt) InstanceSettings() []Pref {\n\tbroker := e.Broker.Name()\n\tplugin := e.instance.Plugin.Name\n\n\tout := make([]Pref, 0)\n\n\tfor _, stg := range e.instance.Plugin.Settings {\n\t\t\/\/ ignore channel-specific settings for other channels\n\t\tif stg.Channel != \"\" && stg.Channel != e.Channel {\n\t\t\tcontinue\n\t\t}\n\n\t\tpref := GetPref(\"\", broker, e.Channel, plugin, stg.Key, stg.Default)\n\t\tout = append(out, pref)\n\t}\n\n\treturn out\n}\n\n\/\/ NewPref creates a new pref struct with user, channel, broker, and plugin\n\/\/ set using metadata from the event.\nfunc (e *Evt) NewPref() Pref {\n\treturn Pref{\n\t\tUser: e.From,\n\t\tChannel: e.Channel,\n\t\tBroker: e.Broker.Name(),\n\t\tPlugin: e.instance.Plugin.Name,\n\t}\n}\n\n\/\/ BodyAsArgv does minimal parsing of the event body, returning an argv-like\n\/\/ array of strings with quoted strings intact (but with quotes removed).\n\/\/ The goal is shell-like, and is not a full implementation.\n\/\/ Leading\/trailing whitespace is removed.\n\/\/ Escaping quotes, etc. is not supported.\nfunc (e *Evt) BodyAsArgv() []string {\n\t\/\/ use a simple RE rather than pulling in a package to do this\n\tre := regexp.MustCompile(`'[^']*'|\"[^\"]*\"|\\S+`)\n\tbody := strings.TrimSpace(e.Body)\n\targv := re.FindAllString(body, -1)\n\n\t\/\/ remove the outer quotes from quoted strings\n\tfor i, val := range argv {\n\t\tif strings.HasPrefix(val, `'`) && strings.HasSuffix(val, `'`) {\n\t\t\ttmp := strings.TrimPrefix(val, `'`)\n\t\t\targv[i] = strings.TrimSuffix(tmp, `'`)\n\t\t} else if strings.HasPrefix(val, `\"`) && strings.HasSuffix(val, `\"`) {\n\t\t\ttmp := strings.TrimPrefix(val, `\"`)\n\t\t\targv[i] = strings.TrimSuffix(tmp, `\"`)\n\t\t}\n\t}\n\n\treturn argv\n}\n\nfunc (e *Evt) String() string {\n\treturn fmt.Sprintf(\"%s\/%s@%s: %s\", e.From, e.Channel, e.Time.String(), e.Body)\n}\n<|endoftext|>"} {"text":"package http\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"sync\"\n\n\t\"github.com\/mcuadros\/dockership\/config\"\n\n\t\"code.google.com\/p\/goauth2\/oauth\"\n\t\"github.com\/golang\/oauth2\"\n\t\"github.com\/google\/go-github\/github\"\n\t\"github.com\/gorilla\/sessions\"\n)\n\nconst (\n\tCODE_REDIRECT = 302\n\tKEY_TOKEN = \"oauth2_token\"\n)\n\ntype User struct {\n\tFullname string\n\tAvatar string\n}\n\ntype OAuth struct {\n\tPathLogin string \/\/ Path to handle OAuth 2.0 logins.\n\tPathLogout string \/\/ Path to handle OAuth 2.0 logouts.\n\tPathCallback string \/\/ Path to handle callback from OAuth 2.0 backend\n\tPathError string \/\/ Path to handle error cases.\n\tOAuthFlow *oauth2.Flow\n\tConfig *config.Config\n\tusers map[string]*User\n\tstore sessions.Store\n\tsync.Mutex\n}\n\nfunc NewOAuth(config *config.Config) *OAuth {\n\tauthUrl := \"https:\/\/github.com\/login\/oauth\/authorize\"\n\ttokenUrl := \"https:\/\/github.com\/login\/oauth\/access_token\"\n\n\tflow, err := oauth2.New(\n\t\toauth2.Client(config.HTTP.GithubID, config.HTTP.GithubSecret),\n\t\toauth2.RedirectURL(config.HTTP.GithubRedirectURL),\n\t\toauth2.Scope(\"read:org\"),\n\t\toauth2.Endpoint(authUrl, tokenUrl),\n\t)\n\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"oauth2: %s\", err))\n\t}\n\n\treturn &OAuth{\n\t\tPathLogin: \"\/login\",\n\t\tPathLogout: \"\/logout\",\n\t\tPathCallback: \"\/oauth2callback\",\n\t\tPathError: \"\/oauth2error\",\n\t\tOAuthFlow: flow,\n\t\tConfig: config,\n\t\tusers: make(map[string]*User, 0),\n\t\tstore: sessions.NewCookieStore([]byte(\"cookie-key\")),\n\t}\n}\n\nfunc (o *OAuth) Handler(w http.ResponseWriter, r *http.Request) bool {\n\tif r.Method == \"GET\" {\n\t\tswitch r.URL.Path {\n\t\tcase o.PathLogin:\n\t\t\to.HandleLogin(w, r)\n\t\t\treturn false\n\t\tcase o.PathLogout:\n\t\t\to.HandleLogout(w, r)\n\t\t\treturn false\n\t\tcase o.PathCallback:\n\t\t\to.HandleCallback(w, r)\n\t\t\treturn false\n\t\t}\n\t}\n\n\ttoken := o.getToken(r)\n\tfailed := true\n\tif token != nil && !token.Expired() {\n\t\tif _, err := o.getValidUser(token); err == nil {\n\t\t\tfailed = false\n\t\t} else {\n\t\t\tw.Write([]byte(err.Error()))\n\t\t\treturn false\n\t\t}\n\n\t}\n\n\tif failed {\n\t\tnext := url.QueryEscape(r.URL.RequestURI())\n\t\thttp.Redirect(w, r, o.PathLogin+\"?next=\"+next, CODE_REDIRECT)\n\t\treturn false\n\t}\n\n\treturn true\n}\n\nfunc (o *OAuth) HandleCallback(w http.ResponseWriter, r *http.Request) {\n\tnext := extractPath(r.URL.Query().Get(\"state\"))\n\tcode := r.URL.Query().Get(\"code\")\n\n\tt, err := o.OAuthFlow.NewTransportFromCode(code)\n\tif err != nil {\n\t\t\/\/ Pass the error message, or allow dev to provide its own\n\t\t\/\/ error handler.\n\t\thttp.Redirect(w, r, o.PathError, CODE_REDIRECT)\n\t\treturn\n\t}\n\n\to.setToken(w, r, t.Token())\n\thttp.Redirect(w, r, next, CODE_REDIRECT)\n}\n\nfunc (o *OAuth) HandleLogin(w http.ResponseWriter, r *http.Request) {\n\tnext := extractPath(r.URL.Query().Get(\"next\"))\n\tif o.getToken(r) == nil {\n\t\t\/\/ User is not logged in.\n\t\tif next == \"\" {\n\t\t\tnext = \"\/\"\n\t\t}\n\t\thttp.Redirect(w, r, o.OAuthFlow.AuthCodeURL(next, \"\", \"\"), CODE_REDIRECT)\n\t\treturn\n\t}\n\n\t\/\/ No need to login, redirect to the next page.\n\thttp.Redirect(w, r, next, CODE_REDIRECT)\n}\n\nfunc (o *OAuth) HandleLogout(w http.ResponseWriter, r *http.Request) {\n\tnext := extractPath(r.URL.Query().Get(\"next\"))\n\t\/\/s.Delete(KEY_TOKEN)\n\thttp.Redirect(w, r, next, CODE_REDIRECT)\n}\n\nfunc (s *OAuth) getToken(r *http.Request) *oauth2.Token {\n\tsession, _ := s.store.Get(r, KEY_TOKEN)\n\tif raw, ok := session.Values[\"token\"]; !ok {\n\t\treturn nil\n\t} else {\n\t\tvar tk oauth2.Token\n\t\tjson.Unmarshal(raw.([]byte), &tk)\n\n\t\treturn &tk\n\t}\n}\n\nfunc (s *OAuth) setToken(w http.ResponseWriter, r *http.Request, t *oauth2.Token) {\n\tsession, _ := s.store.Get(r, KEY_TOKEN)\n\tval, _ := json.Marshal(t)\n\tsession.Values[\"token\"] = val\n\tsession.Save(r, w)\n}\n\nfunc (o *OAuth) getValidUser(token *oauth2.Token) (*User, error) {\n\to.Lock()\n\tuser, ok := o.users[token.AccessToken]\n\to.Unlock()\n\n\tif ok {\n\t\treturn user, nil\n\t}\n\n\tt := &oauth.Transport{\n\t\tToken: &oauth.Token{AccessToken: token.AccessToken},\n\t}\n\n\tc := github.NewClient(t.Client())\n\tguser, _, err := c.Users.Get(\"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := o.isValidUser(c, guser); err != nil {\n\t\treturn nil, err\n\t}\n\n\tuser = &User{}\n\tif guser != nil && guser.Name != nil {\n\t\tuser.Fullname = *guser.Name\n\t} else if guser.Login != nil {\n\t\tuser.Fullname = *guser.Login\n\t}\n\n\tif guser != nil && guser.AvatarURL != nil {\n\t\tuser.Avatar = *guser.AvatarURL\n\t}\n\n\to.Lock()\n\to.users[token.AccessToken] = user\n\to.Unlock()\n\n\treturn user, nil\n}\n\nfunc (o *OAuth) isValidUser(c *github.Client, u *github.User) error {\n\tif err := o.validateGithubOrganization(c, u); err != nil {\n\t\treturn err\n\t}\n\n\tif err := o.validateGithubUser(c, u); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (o *OAuth) validateGithubOrganization(c *github.Client, u *github.User) error {\n\torg := o.Config.HTTP.GithubOrganization\n\tif org == \"\" {\n\t\treturn nil\n\t}\n\n\tm, _, err := c.Organizations.IsMember(org, *u.Login)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !m {\n\t\treturn errors.New(fmt.Sprintf(\n\t\t\t\"User %q should be member of %q\", *u.Login, org,\n\t\t))\n\t}\n\n\treturn nil\n}\n\nfunc (o *OAuth) validateGithubUser(c *github.Client, u *github.User) error {\n\tif len(o.Config.HTTP.GithubUsers) == 0 {\n\t\treturn nil\n\t}\n\n\tfor _, user := range o.Config.HTTP.GithubUsers {\n\t\tif user == *u.Login {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn errors.New(fmt.Sprintf(\n\t\t\"User %q not allowed, not in the access list.\", *u.Login,\n\t))\n}\n\nfunc extractPath(next string) string {\n\tn, err := url.Parse(next)\n\tif err != nil {\n\t\treturn \"\/\"\n\t}\n\treturn n.Path\n}\nhttp: small ouath fixespackage http\n\nimport (\n\t\"encoding\/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"sync\"\n\n\t\"github.com\/mcuadros\/dockership\/config\"\n\n\t\"code.google.com\/p\/goauth2\/oauth\"\n\t\"github.com\/golang\/oauth2\"\n\t\"github.com\/google\/go-github\/github\"\n\t\"github.com\/gorilla\/sessions\"\n)\n\nconst (\n\tCODE_REDIRECT = 302\n\tKEY_TOKEN = \"oauth2_token\"\n)\n\ntype User struct {\n\tFullname string\n\tAvatar string\n}\n\ntype OAuth struct {\n\tPathLogin string \/\/ Path to handle OAuth 2.0 logins.\n\tPathLogout string \/\/ Path to handle OAuth 2.0 logouts.\n\tPathCallback string \/\/ Path to handle callback from OAuth 2.0 backend\n\tPathError string \/\/ Path to handle error cases.\n\tOAuthOptions *oauth2.Options\n\tConfig *config.Config\n\tusers map[string]*User\n\tstore sessions.Store\n\tsync.Mutex\n}\n\nfunc NewOAuth(config *config.Config) *OAuth {\n\tauthUrl := \"https:\/\/github.com\/login\/oauth\/authorize\"\n\ttokenUrl := \"https:\/\/github.com\/login\/oauth\/access_token\"\n\n\toptions, err := oauth2.New(\n\t\toauth2.Client(config.HTTP.GithubID, config.HTTP.GithubSecret),\n\t\toauth2.RedirectURL(config.HTTP.GithubRedirectURL),\n\t\toauth2.Scope(\"read:org\"),\n\t\toauth2.Endpoint(authUrl, tokenUrl),\n\t)\n\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"oauth2: %s\", err))\n\t}\n\n\treturn &OAuth{\n\t\tPathLogin: \"\/login\",\n\t\tPathLogout: \"\/logout\",\n\t\tPathCallback: \"\/oauth2callback\",\n\t\tPathError: \"\/oauth2error\",\n\t\tOAuthOptions: options,\n\t\tConfig: config,\n\t\tusers: make(map[string]*User, 0),\n\t\tstore: sessions.NewCookieStore([]byte(\"cookie-key\")),\n\t}\n}\n\nfunc (o *OAuth) Handler(w http.ResponseWriter, r *http.Request) bool {\n\tif r.Method == \"GET\" {\n\t\tswitch r.URL.Path {\n\t\tcase o.PathLogin:\n\t\t\to.HandleLogin(w, r)\n\t\t\treturn false\n\t\tcase o.PathLogout:\n\t\t\to.HandleLogout(w, r)\n\t\t\treturn false\n\t\tcase o.PathCallback:\n\t\t\to.HandleCallback(w, r)\n\t\t\treturn false\n\t\t}\n\t}\n\n\ttoken := o.getToken(r)\n\tfailed := true\n\tif token != nil && !token.Expired() {\n\t\tif _, err := o.getValidUser(token); err == nil {\n\t\t\tfailed = false\n\t\t} else {\n\t\t\tw.Write([]byte(err.Error()))\n\t\t\treturn false\n\t\t}\n\n\t}\n\n\tif failed {\n\t\tnext := url.QueryEscape(r.URL.RequestURI())\n\t\thttp.Redirect(w, r, o.PathLogin+\"?next=\"+next, CODE_REDIRECT)\n\t\treturn false\n\t}\n\n\treturn true\n}\n\nfunc (o *OAuth) HandleCallback(w http.ResponseWriter, r *http.Request) {\n\tnext := extractPath(r.URL.Query().Get(\"state\"))\n\tcode := r.URL.Query().Get(\"code\")\n\n\tt, err := o.OAuthOptions.NewTransportFromCode(code)\n\tif err != nil {\n\t\t\/\/ Pass the error message, or allow dev to provide its own\n\t\t\/\/ error handler.\n\t\thttp.Redirect(w, r, o.PathError, CODE_REDIRECT)\n\t\treturn\n\t}\n\n\to.setToken(w, r, t.Token())\n\thttp.Redirect(w, r, next, CODE_REDIRECT)\n}\n\nfunc (o *OAuth) HandleLogin(w http.ResponseWriter, r *http.Request) {\n\tnext := extractPath(r.URL.Query().Get(\"next\"))\n\tif o.getToken(r) == nil {\n\t\t\/\/ User is not logged in.\n\t\tif next == \"\" {\n\t\t\tnext = \"\/\"\n\t\t}\n\t\thttp.Redirect(w, r, o.OAuthOptions.AuthCodeURL(next, \"\", \"\"), CODE_REDIRECT)\n\t\treturn\n\t}\n\n\t\/\/ No need to login, redirect to the next page.\n\thttp.Redirect(w, r, next, CODE_REDIRECT)\n}\n\nfunc (o *OAuth) HandleLogout(w http.ResponseWriter, r *http.Request) {\n\tnext := extractPath(r.URL.Query().Get(\"next\"))\n\t\/\/s.Delete(KEY_TOKEN)\n\thttp.Redirect(w, r, next, CODE_REDIRECT)\n}\n\nfunc (s *OAuth) getToken(r *http.Request) *oauth2.Token {\n\tsession, _ := s.store.Get(r, KEY_TOKEN)\n\tif raw, ok := session.Values[\"token\"]; !ok {\n\t\treturn nil\n\t} else {\n\t\tvar tk oauth2.Token\n\t\tjson.Unmarshal(raw.([]byte), &tk)\n\n\t\treturn &tk\n\t}\n}\n\nfunc (s *OAuth) setToken(w http.ResponseWriter, r *http.Request, t *oauth2.Token) {\n\tsession, _ := s.store.Get(r, KEY_TOKEN)\n\tval, _ := json.Marshal(t)\n\tsession.Values[\"token\"] = val\n\tsession.Save(r, w)\n}\n\nfunc (o *OAuth) getValidUser(token *oauth2.Token) (*User, error) {\n\to.Lock()\n\tuser, ok := o.users[token.AccessToken]\n\to.Unlock()\n\n\tif ok {\n\t\treturn user, nil\n\t}\n\n\tt := &oauth.Transport{\n\t\tToken: &oauth.Token{AccessToken: token.AccessToken},\n\t}\n\n\tc := github.NewClient(t.Client())\n\tguser, _, err := c.Users.Get(\"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err := o.isValidUser(c, guser); err != nil {\n\t\treturn nil, err\n\t}\n\n\tuser = &User{}\n\tif guser != nil && guser.Name != nil {\n\t\tuser.Fullname = *guser.Name\n\t} else if guser.Login != nil {\n\t\tuser.Fullname = *guser.Login\n\t}\n\n\tif guser != nil && guser.AvatarURL != nil {\n\t\tuser.Avatar = *guser.AvatarURL\n\t}\n\n\to.Lock()\n\to.users[token.AccessToken] = user\n\to.Unlock()\n\n\treturn user, nil\n}\n\nfunc (o *OAuth) isValidUser(c *github.Client, u *github.User) error {\n\tif err := o.validateGithubOrganization(c, u); err != nil {\n\t\treturn err\n\t}\n\n\tif err := o.validateGithubUser(c, u); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (o *OAuth) validateGithubOrganization(c *github.Client, u *github.User) error {\n\torg := o.Config.HTTP.GithubOrganization\n\tif org == \"\" {\n\t\treturn nil\n\t}\n\n\tm, _, err := c.Organizations.IsMember(org, *u.Login)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !m {\n\t\treturn errors.New(fmt.Sprintf(\n\t\t\t\"User %q should be member of %q\", *u.Login, org,\n\t\t))\n\t}\n\n\treturn nil\n}\n\nfunc (o *OAuth) validateGithubUser(c *github.Client, u *github.User) error {\n\tif len(o.Config.HTTP.GithubUsers) == 0 {\n\t\treturn nil\n\t}\n\n\tfor _, user := range o.Config.HTTP.GithubUsers {\n\t\tif user == *u.Login {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn errors.New(fmt.Sprintf(\n\t\t\"User %q not allowed, not in the access list.\", *u.Login,\n\t))\n}\n\nfunc extractPath(next string) string {\n\tn, err := url.Parse(next)\n\tif err != nil {\n\t\treturn \"\/\"\n\t}\n\treturn n.Path\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com\/spf13\/cobra\"\n\n\t\"github.com\/restic\/restic\/internal\/backend\"\n\t\"github.com\/restic\/restic\/internal\/debug\"\n\t\"github.com\/restic\/restic\/internal\/errors\"\n\t\"github.com\/restic\/restic\/internal\/repository\"\n\t\"github.com\/restic\/restic\/internal\/restic\"\n\t\"github.com\/restic\/restic\/internal\/walker\"\n)\n\nvar cmdRewrite = &cobra.Command{\n\tUse: \"rewrite [flags] [all|snapshotID ...]\",\n\tShort: \"Rewrite existing snapshots\",\n\tLong: `\nThe \"rewrite\" command excludes files from existing snapshots.\n\nBy default 'rewrite' will create new snapshots that will contains same data as\nthe source snapshots but without excluded files. All metadata (time, host, tags)\nwill be preserved. The special tag 'rewrite' will be added to new snapshots to\ndistinguish it from the source (unless --inplace is used).\n\nIf --inplace option is used, old snapshot will be removed from repository.\n\nSnapshots to rewrite are specified using --host, --tag, --path or by providing\na list of snapshot ids. Alternatively it's possible to use special snapshot id 'all'\nthat will match all snapshots.\n\nPlease note, that this command only creates new snapshots. In order to delete\ndata from the repository use 'prune' command.\n\nEXIT STATUS\n===========\n\nExit status is 0 if the command was successful, and non-zero if there was any error.\n`,\n\tDisableAutoGenTag: true,\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\treturn runRewrite(cmd.Context(), rewriteOptions, globalOptions, args)\n\t},\n}\n\n\/\/ RewriteOptions collects all options for the rewrite command.\ntype RewriteOptions struct {\n\tHosts []string\n\tPaths []string\n\tTags restic.TagLists\n\tInplace bool\n\tDryRun bool\n\n\t\/\/ Exclude options\n\tExcludes []string\n\tInsensitiveExcludes []string\n\tExcludeFiles []string\n}\n\nvar rewriteOptions RewriteOptions\n\nfunc init() {\n\tcmdRoot.AddCommand(cmdRewrite)\n\n\tf := cmdRewrite.Flags()\n\tf.StringArrayVarP(&rewriteOptions.Hosts, \"host\", \"H\", nil, \"only consider snapshots for this `host`, when no snapshot ID is given (can be specified multiple times)\")\n\tf.Var(&rewriteOptions.Tags, \"tag\", \"only consider snapshots which include this `taglist`, when no snapshot-ID is given\")\n\tf.StringArrayVar(&rewriteOptions.Paths, \"path\", nil, \"only consider snapshots which include this (absolute) `path`, when no snapshot-ID is given\")\n\tf.BoolVarP(&rewriteOptions.Inplace, \"inplace\", \"\", false, \"replace existing snapshots\")\n\tf.BoolVarP(&rewriteOptions.DryRun, \"dry-run\", \"n\", false, \"do not do anything, just print what would be done\")\n\n\t\/\/ Excludes\n\tf.StringArrayVarP(&rewriteOptions.Excludes, \"exclude\", \"e\", nil, \"exclude a `pattern` (can be specified multiple times)\")\n\tf.StringArrayVar(&rewriteOptions.InsensitiveExcludes, \"iexclude\", nil, \"same as --exclude `pattern` but ignores the casing of filenames\")\n\tf.StringArrayVar(&rewriteOptions.ExcludeFiles, \"exclude-file\", nil, \"read exclude patterns from a `file` (can be specified multiple times)\")\n}\n\nfunc collectRejectFuncsForRewrite(opts RewriteOptions) (fs []RejectByNameFunc, err error) {\n\t\/\/TODO: merge with cmd_backup\n\n\t\/\/ add patterns from file\n\tif len(opts.ExcludeFiles) > 0 {\n\t\texcludes, err := readExcludePatternsFromFiles(opts.ExcludeFiles)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\topts.Excludes = append(opts.Excludes, excludes...)\n\t}\n\n\tif len(opts.InsensitiveExcludes) > 0 {\n\t\tfs = append(fs, rejectByInsensitivePattern(opts.InsensitiveExcludes))\n\t}\n\n\tif len(opts.Excludes) > 0 {\n\t\tfs = append(fs, rejectByPattern(opts.Excludes))\n\t}\n\n\treturn fs, nil\n}\n\nfunc rewriteSnapshot(ctx context.Context, repo *repository.Repository, sn *restic.Snapshot, opts RewriteOptions, gopts GlobalOptions) (bool, error) {\n\tif sn.Tree == nil {\n\t\treturn false, errors.Errorf(\"snapshot %v has nil tree\", sn.ID().Str())\n\t}\n\n\trejectByNameFuncs, err := collectRejectFuncsForRewrite(opts)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tcheckExclude := func(nodepath string) bool {\n\t\tfor _, reject := range rejectByNameFuncs {\n\t\t\tif reject(nodepath) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\n\tfilteredTree, err := walker.FilterTree(ctx, repo, \"\/\", *sn.Tree, &walker.TreeFilterVisitor{\n\t\tCheckExclude: checkExclude,\n\t\tPrintExclude: func(path string) { Verbosef(fmt.Sprintf(\"excluding %s\\n\", path)) },\n\t})\n\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tif filteredTree == *sn.Tree {\n\t\tdebug.Log(\"Snapshot %v not modified\", sn)\n\t\treturn false, nil\n\t}\n\n\tdebug.Log(\"Snapshot %v modified\", sn)\n\tif opts.DryRun {\n\t\tPrintf(\"Would modify snapshot: %s\\n\", sn.String())\n\t\treturn true, nil\n\t}\n\n\terr = repo.Flush(ctx)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\t\/\/ Retain the original snapshot id over all tag changes.\n\tif sn.Original == nil {\n\t\tsn.Original = sn.ID()\n\t}\n\t*sn.Tree = filteredTree\n\n\tif !opts.Inplace {\n\t\tsn.AddTags([]string{\"rewrite\"})\n\t}\n\n\t\/\/ Save the new snapshot.\n\tid, err := restic.SaveSnapshot(ctx, repo, sn)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tif opts.Inplace {\n\t\th := restic.Handle{Type: restic.SnapshotFile, Name: sn.ID().String()}\n\t\tif err = repo.Backend().Remove(ctx, h); err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tdebug.Log(\"old snapshot %v removed\", sn.ID())\n\t}\n\tPrintf(\"new snapshot saved as %v\\n\", id)\n\treturn true, nil\n}\n\nfunc runRewrite(ctx context.Context, opts RewriteOptions, gopts GlobalOptions, args []string) error {\n\n\tif len(opts.Hosts) == 0 && len(opts.Tags) == 0 && len(opts.Paths) == 0 && len(args) == 0 {\n\t\treturn errors.Fatal(\"no snapshots provided\")\n\t}\n\n\tif len(opts.ExcludeFiles) == 0 && len(opts.Excludes) == 0 && len(opts.InsensitiveExcludes) == 0 {\n\t\treturn errors.Fatal(\"Nothing to do: no excludes provided\")\n\t}\n\n\tif len(args) == 1 && args[0] == \"all\" {\n\t\targs = []string{}\n\t}\n\n\trepo, err := OpenRepository(ctx, gopts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !opts.DryRun {\n\t\tVerbosef(\"create exclusive lock for repository\\n\")\n\t\tvar lock *restic.Lock\n\t\tlock, ctx, err = lockRepoExclusive(ctx, repo)\n\t\tdefer unlockRepo(lock)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\trepo.SetDryRun()\n\t}\n\n\tsnapshotLister, err := backend.MemorizeList(ctx, repo.Backend(), restic.SnapshotFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = repo.LoadIndex(ctx); err != nil {\n\t\treturn err\n\t}\n\n\tchangedCount := 0\n\tfor sn := range FindFilteredSnapshots(ctx, snapshotLister, repo, opts.Hosts, opts.Tags, opts.Paths, args) {\n\t\tVerbosef(\"Checking snapshot %s\\n\", sn.String())\n\t\tchanged, err := rewriteSnapshot(ctx, repo, sn, opts, gopts)\n\t\tif err != nil {\n\t\t\tWarnf(\"unable to rewrite snapshot ID %q, ignoring: %v\\n\", sn.ID(), err)\n\t\t\tcontinue\n\t\t}\n\t\tif changed {\n\t\t\tchangedCount++\n\t\t}\n\t}\n\n\tif changedCount == 0 {\n\t\tVerbosef(\"no snapshots modified\\n\")\n\t} else {\n\t\tif !opts.DryRun {\n\t\t\tVerbosef(\"modified %v snapshots\\n\", changedCount)\n\t\t} else {\n\t\t\tVerbosef(\"dry run. would modify %v snapshots\\n\", changedCount)\n\t\t}\n\t}\n\n\treturn nil\n}\nrewrite: filter all snapshots if none are specifiedpackage main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com\/spf13\/cobra\"\n\n\t\"github.com\/restic\/restic\/internal\/backend\"\n\t\"github.com\/restic\/restic\/internal\/debug\"\n\t\"github.com\/restic\/restic\/internal\/errors\"\n\t\"github.com\/restic\/restic\/internal\/repository\"\n\t\"github.com\/restic\/restic\/internal\/restic\"\n\t\"github.com\/restic\/restic\/internal\/walker\"\n)\n\nvar cmdRewrite = &cobra.Command{\n\tUse: \"rewrite [flags] [snapshotID ...]\",\n\tShort: \"Rewrite existing snapshots\",\n\tLong: `\nThe \"rewrite\" command excludes files from existing snapshots.\n\nBy default 'rewrite' will create new snapshots that will contains same data as\nthe source snapshots but without excluded files. All metadata (time, host, tags)\nwill be preserved. The special tag 'rewrite' will be added to new snapshots to\ndistinguish it from the source (unless --inplace is used).\n\nIf --inplace option is used, old snapshot will be removed from repository.\n\nSnapshots to rewrite are specified using --host, --tag, --path or by providing\na list of snapshot ids. Not specifying a snapshot id will rewrite all snapshots.\n\nPlease note, that this command only creates new snapshots. In order to delete\ndata from the repository use 'prune' command.\n\nEXIT STATUS\n===========\n\nExit status is 0 if the command was successful, and non-zero if there was any error.\n`,\n\tDisableAutoGenTag: true,\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\treturn runRewrite(cmd.Context(), rewriteOptions, globalOptions, args)\n\t},\n}\n\n\/\/ RewriteOptions collects all options for the rewrite command.\ntype RewriteOptions struct {\n\tHosts []string\n\tPaths []string\n\tTags restic.TagLists\n\tInplace bool\n\tDryRun bool\n\n\t\/\/ Exclude options\n\tExcludes []string\n\tInsensitiveExcludes []string\n\tExcludeFiles []string\n}\n\nvar rewriteOptions RewriteOptions\n\nfunc init() {\n\tcmdRoot.AddCommand(cmdRewrite)\n\n\tf := cmdRewrite.Flags()\n\tf.StringArrayVarP(&rewriteOptions.Hosts, \"host\", \"H\", nil, \"only consider snapshots for this `host`, when no snapshot ID is given (can be specified multiple times)\")\n\tf.Var(&rewriteOptions.Tags, \"tag\", \"only consider snapshots which include this `taglist`, when no snapshot-ID is given\")\n\tf.StringArrayVar(&rewriteOptions.Paths, \"path\", nil, \"only consider snapshots which include this (absolute) `path`, when no snapshot-ID is given\")\n\tf.BoolVarP(&rewriteOptions.Inplace, \"inplace\", \"\", false, \"replace existing snapshots\")\n\tf.BoolVarP(&rewriteOptions.DryRun, \"dry-run\", \"n\", false, \"do not do anything, just print what would be done\")\n\n\t\/\/ Excludes\n\tf.StringArrayVarP(&rewriteOptions.Excludes, \"exclude\", \"e\", nil, \"exclude a `pattern` (can be specified multiple times)\")\n\tf.StringArrayVar(&rewriteOptions.InsensitiveExcludes, \"iexclude\", nil, \"same as --exclude `pattern` but ignores the casing of filenames\")\n\tf.StringArrayVar(&rewriteOptions.ExcludeFiles, \"exclude-file\", nil, \"read exclude patterns from a `file` (can be specified multiple times)\")\n}\n\nfunc collectRejectFuncsForRewrite(opts RewriteOptions) (fs []RejectByNameFunc, err error) {\n\t\/\/TODO: merge with cmd_backup\n\n\t\/\/ add patterns from file\n\tif len(opts.ExcludeFiles) > 0 {\n\t\texcludes, err := readExcludePatternsFromFiles(opts.ExcludeFiles)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\topts.Excludes = append(opts.Excludes, excludes...)\n\t}\n\n\tif len(opts.InsensitiveExcludes) > 0 {\n\t\tfs = append(fs, rejectByInsensitivePattern(opts.InsensitiveExcludes))\n\t}\n\n\tif len(opts.Excludes) > 0 {\n\t\tfs = append(fs, rejectByPattern(opts.Excludes))\n\t}\n\n\treturn fs, nil\n}\n\nfunc rewriteSnapshot(ctx context.Context, repo *repository.Repository, sn *restic.Snapshot, opts RewriteOptions, gopts GlobalOptions) (bool, error) {\n\tif sn.Tree == nil {\n\t\treturn false, errors.Errorf(\"snapshot %v has nil tree\", sn.ID().Str())\n\t}\n\n\trejectByNameFuncs, err := collectRejectFuncsForRewrite(opts)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tcheckExclude := func(nodepath string) bool {\n\t\tfor _, reject := range rejectByNameFuncs {\n\t\t\tif reject(nodepath) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\n\tfilteredTree, err := walker.FilterTree(ctx, repo, \"\/\", *sn.Tree, &walker.TreeFilterVisitor{\n\t\tCheckExclude: checkExclude,\n\t\tPrintExclude: func(path string) { Verbosef(fmt.Sprintf(\"excluding %s\\n\", path)) },\n\t})\n\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tif filteredTree == *sn.Tree {\n\t\tdebug.Log(\"Snapshot %v not modified\", sn)\n\t\treturn false, nil\n\t}\n\n\tdebug.Log(\"Snapshot %v modified\", sn)\n\tif opts.DryRun {\n\t\tPrintf(\"Would modify snapshot: %s\\n\", sn.String())\n\t\treturn true, nil\n\t}\n\n\terr = repo.Flush(ctx)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\t\/\/ Retain the original snapshot id over all tag changes.\n\tif sn.Original == nil {\n\t\tsn.Original = sn.ID()\n\t}\n\t*sn.Tree = filteredTree\n\n\tif !opts.Inplace {\n\t\tsn.AddTags([]string{\"rewrite\"})\n\t}\n\n\t\/\/ Save the new snapshot.\n\tid, err := restic.SaveSnapshot(ctx, repo, sn)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tif opts.Inplace {\n\t\th := restic.Handle{Type: restic.SnapshotFile, Name: sn.ID().String()}\n\t\tif err = repo.Backend().Remove(ctx, h); err != nil {\n\t\t\treturn false, err\n\t\t}\n\n\t\tdebug.Log(\"old snapshot %v removed\", sn.ID())\n\t}\n\tPrintf(\"new snapshot saved as %v\\n\", id)\n\treturn true, nil\n}\n\nfunc runRewrite(ctx context.Context, opts RewriteOptions, gopts GlobalOptions, args []string) error {\n\n\tif len(opts.ExcludeFiles) == 0 && len(opts.Excludes) == 0 && len(opts.InsensitiveExcludes) == 0 {\n\t\treturn errors.Fatal(\"Nothing to do: no excludes provided\")\n\t}\n\n\trepo, err := OpenRepository(ctx, gopts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !opts.DryRun {\n\t\tVerbosef(\"create exclusive lock for repository\\n\")\n\t\tvar lock *restic.Lock\n\t\tlock, ctx, err = lockRepoExclusive(ctx, repo)\n\t\tdefer unlockRepo(lock)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\trepo.SetDryRun()\n\t}\n\n\tsnapshotLister, err := backend.MemorizeList(ctx, repo.Backend(), restic.SnapshotFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = repo.LoadIndex(ctx); err != nil {\n\t\treturn err\n\t}\n\n\tchangedCount := 0\n\tfor sn := range FindFilteredSnapshots(ctx, snapshotLister, repo, opts.Hosts, opts.Tags, opts.Paths, args) {\n\t\tVerbosef(\"Checking snapshot %s\\n\", sn.String())\n\t\tchanged, err := rewriteSnapshot(ctx, repo, sn, opts, gopts)\n\t\tif err != nil {\n\t\t\tWarnf(\"unable to rewrite snapshot ID %q, ignoring: %v\\n\", sn.ID(), err)\n\t\t\tcontinue\n\t\t}\n\t\tif changed {\n\t\t\tchangedCount++\n\t\t}\n\t}\n\n\tif changedCount == 0 {\n\t\tVerbosef(\"no snapshots modified\\n\")\n\t} else {\n\t\tif !opts.DryRun {\n\t\t\tVerbosef(\"modified %v snapshots\\n\", changedCount)\n\t\t} else {\n\t\t\tVerbosef(\"dry run. would modify %v snapshots\\n\", changedCount)\n\t\t}\n\t}\n\n\treturn nil\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2017 the u-root Authors. All rights reserved\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ dhclient sets up DHCP.\n\/\/\n\/\/ Synopsis:\n\/\/ dhclient [OPTIONS...]\n\/\/\n\/\/ Options:\n\/\/ -timeout: lease timeout in seconds\n\/\/ -renewals: number of DHCP renewals before exiting\n\/\/ -verbose: verbose output\npackage main\n\nimport (\n\t\"crypto\/rand\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"regexp\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/u-root\/dhcp4\"\n\t\"github.com\/u-root\/dhcp4\/dhcp4client\"\n\t\"github.com\/u-root\/u-root\/pkg\/dhclient\"\n\t\"github.com\/u-root\/u-root\/pkg\/dhcp6client\"\n\t\"github.com\/vishvananda\/netlink\"\n)\n\nconst (\n\t\/\/ slop is the slop in our lease time.\n\tslop = 10 * time.Second\n\tlinkUpAttempt = 30 * time.Second\n)\n\nvar (\n\tifName = \"^e.*\"\n\tleasetimeout = flag.Int(\"timeout\", 15, \"Lease timeout in seconds\")\n\tretry = flag.Int(\"retry\", 5, \"Max number of attempts for DHCP clients to send requests. -1 means infinity\")\n\trenewals = flag.Int(\"renewals\", 0, \"Number of DHCP renewals before exiting. -1 means infinity\")\n\trenewalTimeout = flag.Int(\"renewal timeout\", 3600, \"How long to wait before renewing in seconds\")\n\tverbose = flag.Bool(\"verbose\", false, \"Verbose output\")\n\tipv4 = flag.Bool(\"ipv4\", true, \"use IPV4\")\n\tipv6 = flag.Bool(\"ipv6\", true, \"use IPV6\")\n\ttest = flag.Bool(\"test\", false, \"Test mode\")\n\tdebug = func(string, ...interface{}) {}\n)\n\nfunc ifup(ifname string) (netlink.Link, error) {\n\tdebug(\"Try bringing up %v\", ifname)\n\tstart := time.Now()\n\tfor time.Since(start) < linkUpAttempt {\n\t\t\/\/ Note that it may seem odd to keep trying the\n\t\t\/\/ LinkByName operation, by consider that a hotplug\n\t\t\/\/ device such as USB ethernet can just vanish.\n\t\tiface, err := netlink.LinkByName(ifname)\n\t\tdebug(\"LinkByName(%v) returns (%v, %v)\", ifname, iface, err)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"cannot get interface by name %v: %v\", ifname, err)\n\t\t}\n\n\t\tif iface.Attrs().OperState == netlink.OperUp {\n\t\t\tdebug(\"Link %v is up\", ifname)\n\t\t\treturn iface, nil\n\t\t}\n\n\t\tif err := netlink.LinkSetUp(iface); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"%v: %v can't make it up: %v\", ifname, iface, err)\n\t\t}\n\t\ttime.Sleep(1 * time.Second)\n\t}\n\treturn nil, fmt.Errorf(\"Link %v still down after %d seconds\", ifname, linkUpAttempt)\n}\n\nfunc dhclient4(iface netlink.Link, timeout time.Duration, retry int, numRenewals int) error {\n\tclient, err := dhcp4client.New(iface,\n\t\tdhcp4client.WithTimeout(timeout),\n\t\tdhcp4client.WithRetry(retry))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor i := 0; numRenewals < 0 || i <= numRenewals; i++ {\n\t\tvar packet *dhcp4.Packet\n\t\tvar err error\n\t\tif i == 0 {\n\t\t\tpacket, err = client.Request()\n\t\t} else {\n\t\t\ttime.Sleep(time.Duration(*renewalTimeout) * time.Second)\n\t\t\tpacket, err = client.Renew(packet)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := dhclient.Configure4(iface, packet); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc dhclient6(iface netlink.Link, timeout time.Duration, retry int, numRenewals int) error {\n\tclient, err := dhcp6client.New(iface,\n\t\tdhcp6client.WithTimeout(timeout),\n\t\tdhcp6client.WithRetry(retry))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor i := 0; numRenewals < 0 || i <= numRenewals; i++ {\n\t\tif i != 0 {\n\t\t\ttime.Sleep(time.Duration(*renewalTimeout) * time.Second)\n\t\t}\n\t\tiana, packet, err := client.RapidSolicit()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := dhclient.Configure6(iface, packet, iana); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc main() {\n\tflag.Parse()\n\tif *verbose {\n\t\tdebug = log.Printf\n\t}\n\n\t\/\/ if we boot quickly enough, the random number generator\n\t\/\/ may not be ready, and the dhcp package panics in that case.\n\t\/\/ Worse, \/dev\/urandom, which the Go package falls back to,\n\t\/\/ might not be there. Still worse, the Go package is \"sticky\"\n\t\/\/ in that once it decides to use \/dev\/urandom, it won't go back,\n\t\/\/ even if the system call would subsequently work.\n\t\/\/ You're screwed. Exit.\n\t\/\/ Wouldn't it be nice if we could just do the blocking system\n\t\/\/ call? But that comes with its own giant set of headaches.\n\t\/\/ Maybe we'll end up in a loop, sleeping, and just running\n\t\/\/ ourselves.\n\tif n, err := rand.Read([]byte{0}); err != nil || n != 1 {\n\t\tlog.Fatalf(\"We're sorry, the random number generator is not up. Please file a ticket\")\n\t}\n\n\tif len(flag.Args()) > 1 {\n\t\tlog.Fatalf(\"only one re\")\n\t}\n\n\tif len(flag.Args()) > 0 {\n\t\tifName = flag.Args()[0]\n\t}\n\n\tifRE := regexp.MustCompilePOSIX(ifName)\n\n\tifnames, err := netlink.LinkList()\n\tif err != nil {\n\t\tlog.Fatalf(\"Can't get list of link names: %v\", err)\n\t}\n\n\ttimeout := time.Duration(*leasetimeout) * time.Second\n\t\/\/ if timeout is < slop, it's too short.\n\tif timeout < slop {\n\t\ttimeout = 2 * slop\n\t\tlog.Printf(\"increased lease timeout to %s\", timeout)\n\t}\n\n\tvar wg sync.WaitGroup\n\tdone := make(chan error)\n\tfor _, i := range ifnames {\n\t\tif !ifRE.MatchString(i.Attrs().Name) {\n\t\t\tcontinue\n\t\t}\n\t\twg.Add(1)\n\t\tgo func(ifname string) {\n\t\t\tdefer wg.Done()\n\t\t\tiface, err := dhclient.IfUp(ifname)\n\t\t\tif err != nil {\n\t\t\t\tdone <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif *ipv4 {\n\t\t\t\twg.Add(1)\n\t\t\t\tgo func() {\n\t\t\t\t\tdefer wg.Done()\n\t\t\t\t\tdone <- dhclient4(iface, timeout, *retry, *renewals)\n\t\t\t\t}()\n\t\t\t}\n\t\t\tif *ipv6 {\n\t\t\t\twg.Add(1)\n\t\t\t\tgo func() {\n\t\t\t\t\tdefer wg.Done()\n\t\t\t\t\tdone <- dhclient6(iface, timeout, *retry, *renewals)\n\t\t\t\t}()\n\t\t\t}\n\t\t\tdebug(\"Done dhclient for %v\", ifname)\n\t\t}(i.Attrs().Name)\n\t}\n\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(done)\n\t}()\n\t\/\/ Wait for all goroutines to finish.\n\tvar nif int\n\tfor err := range done {\n\t\tdebug(\"err from done %v\", err)\n\t\tif err != nil {\n\t\t\tlog.Print(err)\n\t\t}\n\t\tnif++\n\t}\n\n\tif nif == 0 {\n\t\tlog.Fatalf(\"No interfaces match %v\\n\", ifName)\n\t}\n\tfmt.Printf(\"%d dhclient attempts were sent\", nif)\n}\ndhclient: printf formatting changes\/\/ Copyright 2017 the u-root Authors. All rights reserved\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ dhclient sets up DHCP.\n\/\/\n\/\/ Synopsis:\n\/\/ dhclient [OPTIONS...]\n\/\/\n\/\/ Options:\n\/\/ -timeout: lease timeout in seconds\n\/\/ -renewals: number of DHCP renewals before exiting\n\/\/ -verbose: verbose output\npackage main\n\nimport (\n\t\"crypto\/rand\"\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"regexp\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/u-root\/dhcp4\"\n\t\"github.com\/u-root\/dhcp4\/dhcp4client\"\n\t\"github.com\/u-root\/u-root\/pkg\/dhclient\"\n\t\"github.com\/u-root\/u-root\/pkg\/dhcp6client\"\n\t\"github.com\/vishvananda\/netlink\"\n)\n\nconst (\n\t\/\/ slop is the slop in our lease time.\n\tslop = 10 * time.Second\n\tlinkUpAttempt = 30 * time.Second\n)\n\nvar (\n\tifName = \"^e.*\"\n\tleasetimeout = flag.Int(\"timeout\", 15, \"Lease timeout in seconds\")\n\tretry = flag.Int(\"retry\", 5, \"Max number of attempts for DHCP clients to send requests. -1 means infinity\")\n\trenewals = flag.Int(\"renewals\", 0, \"Number of DHCP renewals before exiting. -1 means infinity\")\n\trenewalTimeout = flag.Int(\"renewal timeout\", 3600, \"How long to wait before renewing in seconds\")\n\tverbose = flag.Bool(\"verbose\", false, \"Verbose output\")\n\tipv4 = flag.Bool(\"ipv4\", true, \"use IPV4\")\n\tipv6 = flag.Bool(\"ipv6\", true, \"use IPV6\")\n\ttest = flag.Bool(\"test\", false, \"Test mode\")\n\tdebug = func(string, ...interface{}) {}\n)\n\nfunc ifup(ifname string) (netlink.Link, error) {\n\tdebug(\"Try bringing up %v\", ifname)\n\tstart := time.Now()\n\tfor time.Since(start) < linkUpAttempt {\n\t\t\/\/ Note that it may seem odd to keep trying the\n\t\t\/\/ LinkByName operation, by consider that a hotplug\n\t\t\/\/ device such as USB ethernet can just vanish.\n\t\tiface, err := netlink.LinkByName(ifname)\n\t\tdebug(\"LinkByName(%v) returns (%v, %v)\", ifname, iface, err)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"cannot get interface by name %v: %v\", ifname, err)\n\t\t}\n\n\t\tif iface.Attrs().OperState == netlink.OperUp {\n\t\t\tdebug(\"Link %v is up\", ifname)\n\t\t\treturn iface, nil\n\t\t}\n\n\t\tif err := netlink.LinkSetUp(iface); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"%v: %v can't make it up: %v\", ifname, iface, err)\n\t\t}\n\t\ttime.Sleep(1 * time.Second)\n\t}\n\treturn nil, fmt.Errorf(\"Link %v still down after %s\", ifname, linkUpAttempt)\n}\n\nfunc dhclient4(iface netlink.Link, timeout time.Duration, retry int, numRenewals int) error {\n\tclient, err := dhcp4client.New(iface,\n\t\tdhcp4client.WithTimeout(timeout),\n\t\tdhcp4client.WithRetry(retry))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor i := 0; numRenewals < 0 || i <= numRenewals; i++ {\n\t\tvar packet *dhcp4.Packet\n\t\tvar err error\n\t\tif i == 0 {\n\t\t\tpacket, err = client.Request()\n\t\t} else {\n\t\t\ttime.Sleep(time.Duration(*renewalTimeout) * time.Second)\n\t\t\tpacket, err = client.Renew(packet)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := dhclient.Configure4(iface, packet); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc dhclient6(iface netlink.Link, timeout time.Duration, retry int, numRenewals int) error {\n\tclient, err := dhcp6client.New(iface,\n\t\tdhcp6client.WithTimeout(timeout),\n\t\tdhcp6client.WithRetry(retry))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor i := 0; numRenewals < 0 || i <= numRenewals; i++ {\n\t\tif i != 0 {\n\t\t\ttime.Sleep(time.Duration(*renewalTimeout) * time.Second)\n\t\t}\n\t\tiana, packet, err := client.RapidSolicit()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := dhclient.Configure6(iface, packet, iana); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc main() {\n\tflag.Parse()\n\tif *verbose {\n\t\tdebug = log.Printf\n\t}\n\n\t\/\/ if we boot quickly enough, the random number generator\n\t\/\/ may not be ready, and the dhcp package panics in that case.\n\t\/\/ Worse, \/dev\/urandom, which the Go package falls back to,\n\t\/\/ might not be there. Still worse, the Go package is \"sticky\"\n\t\/\/ in that once it decides to use \/dev\/urandom, it won't go back,\n\t\/\/ even if the system call would subsequently work.\n\t\/\/ You're screwed. Exit.\n\t\/\/ Wouldn't it be nice if we could just do the blocking system\n\t\/\/ call? But that comes with its own giant set of headaches.\n\t\/\/ Maybe we'll end up in a loop, sleeping, and just running\n\t\/\/ ourselves.\n\tif n, err := rand.Read([]byte{0}); err != nil || n != 1 {\n\t\tlog.Fatalf(\"We're sorry, the random number generator is not up. Please file a ticket\")\n\t}\n\n\tif len(flag.Args()) > 1 {\n\t\tlog.Fatalf(\"only one re\")\n\t}\n\n\tif len(flag.Args()) > 0 {\n\t\tifName = flag.Args()[0]\n\t}\n\n\tifRE := regexp.MustCompilePOSIX(ifName)\n\n\tifnames, err := netlink.LinkList()\n\tif err != nil {\n\t\tlog.Fatalf(\"Can't get list of link names: %v\", err)\n\t}\n\n\ttimeout := time.Duration(*leasetimeout) * time.Second\n\t\/\/ if timeout is < slop, it's too short.\n\tif timeout < slop {\n\t\ttimeout = 2 * slop\n\t\tlog.Printf(\"increased lease timeout to %s\", timeout)\n\t}\n\n\tvar wg sync.WaitGroup\n\tdone := make(chan error)\n\tfor _, i := range ifnames {\n\t\tif !ifRE.MatchString(i.Attrs().Name) {\n\t\t\tcontinue\n\t\t}\n\t\twg.Add(1)\n\t\tgo func(ifname string) {\n\t\t\tdefer wg.Done()\n\t\t\tiface, err := dhclient.IfUp(ifname)\n\t\t\tif err != nil {\n\t\t\t\tdone <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif *ipv4 {\n\t\t\t\twg.Add(1)\n\t\t\t\tgo func() {\n\t\t\t\t\tdefer wg.Done()\n\t\t\t\t\tdone <- dhclient4(iface, timeout, *retry, *renewals)\n\t\t\t\t}()\n\t\t\t}\n\t\t\tif *ipv6 {\n\t\t\t\twg.Add(1)\n\t\t\t\tgo func() {\n\t\t\t\t\tdefer wg.Done()\n\t\t\t\t\tdone <- dhclient6(iface, timeout, *retry, *renewals)\n\t\t\t\t}()\n\t\t\t}\n\t\t\tdebug(\"Done dhclient for %v\", ifname)\n\t\t}(i.Attrs().Name)\n\t}\n\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(done)\n\t}()\n\t\/\/ Wait for all goroutines to finish.\n\tvar nif int\n\tfor err := range done {\n\t\tdebug(\"err from done %v\", err)\n\t\tif err != nil {\n\t\t\tlog.Print(err)\n\t\t}\n\t\tnif++\n\t}\n\n\tif nif == 0 {\n\t\tlog.Fatalf(\"No interfaces match %v\\n\", ifName)\n\t}\n\tfmt.Printf(\"%d dhclient attempts were sent\\n\", nif)\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"github.com\/urfave\/cli\"\n)\n\nfunc main() {\n\tapp := cli.NewApp()\n\tapp.Name = \"heartbeat\"\n\tapp.Usage = \"Produce a periodic heartbeat message\"\n\tapp.Version = \"0.1.0\"\n\n\tapp.Flags = []cli.Flag{\n\t\tcli.BoolTFlag{\n\t\t\tName: \"verbose\",\n\t\t\tUsage: \"Print verbose output\",\n\t\t},\n\t}\n\n\t\/\/cfg := &Config{ Verbose: false}\n\n\tapp.Commands = []cli.Command{\n\t\t{\n\t\t\tName: \"version\",\n\t\t\tAliases: []string{\"v\"},\n\t\t\tUsage: \"Print the version and exit\",\n\t\t\tAction: func(c *cli.Context) error {\n\t\t\t\tfmt.Printf(\"heartbeat version %s\\n\", app.Version)\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t}\n\n\tapp.Run(os.Args)\n}\nCreate a simple program to publish a heartbeat message once per second.package main\n\nimport (\n\t\"fmt\"\n\t\"github.com\/urfave\/cli\"\n\t\"os\"\n\t\"time\"\n)\n\nfunc main() {\n\tapp := cli.NewApp()\n\tapp.Name = \"heartbeat\"\n\tapp.Usage = \"Produce a periodic heartbeat message\"\n\tapp.Version = \"0.1.0\"\n\n\tapp.Flags = []cli.Flag{\n\t\tcli.BoolTFlag{\n\t\t\tName: \"verbose\",\n\t\t\tUsage: \"Print verbose output\",\n\t\t},\n\t}\n\n\tapp.Commands = []cli.Command{\n\t\t{\n\t\t\tName: \"version\",\n\t\t\tAliases: []string{\"v\"},\n\t\t\tUsage: \"Print the version and exit\",\n\t\t\tAction: func(c *cli.Context) error {\n\t\t\t\tfmt.Printf(\"heartbeat version %s\\n\", app.Version)\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"run\",\n\t\t\tUsage: \"Run the program\",\n\t\t\tAction: RunPeriodically,\n\t\t},\n\t}\n\n\tapp.Run(os.Args)\n}\n\nfunc RunPeriodically(c *cli.Context) error {\n\tvar period time.Duration = 1 * time.Second\n\n\tfmt.Printf(\"Running %s periodically\\n\", c.App.Name)\n\tfor {\n\t\tgo func() {\n\t\t\tPrintHeartbeat()\n\t\t}()\n\n\t\ttime.Sleep(period)\n\t}\n\n\treturn nil\n}\n\nfunc PrintHeartbeat() {\n\tnow := time.Now().UTC()\n\tfmt.Printf(\"%v Every heartbeat bears your name\\n\", now.Format(time.RFC3339))\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"bufio\"\n\t\"io\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/seletskiy\/hierr\"\n\t\"github.com\/theairkit\/runcmd\"\n)\n\nconst (\n\theartbeatPing = \"PING\"\n)\n\nfunc heartbeat(\n\tperiod time.Duration,\n\tnode *distributedLockNode,\n\tcanceler *sync.Cond,\n) {\n\tabort := make(chan struct{}, 0)\n\n\tgo func() {\n\t\tcanceler.L.Lock()\n\t\tcanceler.Wait()\n\t\tcanceler.L.Unlock()\n\n\t\tabort <- struct{}{}\n\t}()\n\n\tfinish := func(code int) {\n\t\tcanceler.L.Lock()\n\t\tcanceler.Broadcast()\n\t\tcanceler.L.Unlock()\n\n\t\t<-abort\n\n\t\tif remote, ok := node.runner.(*runcmd.Remote); ok {\n\t\t\ttracef(\"%s closing connection\", node.String())\n\t\t\terr := remote.CloseConnection()\n\t\t\tif err != nil {\n\t\t\t\twarningf(\n\t\t\t\t\t\"%s\",\n\t\t\t\t\thierr.Errorf(\n\t\t\t\t\t\terr,\n\t\t\t\t\t\t\"%s error while closing connection\",\n\t\t\t\t\t\tnode.String(),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\texit(code)\n\t}\n\n\tticker := time.Tick(period)\n\n\tfor {\n\t\t_, err := io.WriteString(node.connection.stdin, heartbeatPing+\"\\n\")\n\t\tif err != nil {\n\t\t\tlogger.Error(\n\t\t\t\thierr.Errorf(\n\t\t\t\t\terr,\n\t\t\t\t\t`%s can't send heartbeat`,\n\t\t\t\t\tnode.String(),\n\t\t\t\t).Error(),\n\t\t\t)\n\n\t\t\tfinish(2)\n\t\t}\n\n\t\tselect {\n\t\tcase <-abort:\n\t\t\treturn\n\n\t\tcase <-ticker:\n\t\t\t\/\/ pass\n\t\t}\n\n\t\tping, err := bufio.NewReader(node.connection.stdout).ReadString('\\n')\n\t\tif err != nil {\n\t\t\tlogger.Error(\n\t\t\t\thierr.Errorf(\n\t\t\t\t\terr,\n\t\t\t\t\t`%s can't receive heartbeat`,\n\t\t\t\t\tnode.String(),\n\t\t\t\t),\n\t\t\t)\n\n\t\t\tfinish(2)\n\t\t}\n\n\t\tif strings.TrimSpace(ping) != heartbeatPing {\n\t\t\tlogger.Errorf(\n\t\t\t\t`%s received unexpected heartbeat ping: '%s'`,\n\t\t\t\tnode.String(),\n\t\t\t\tping,\n\t\t\t)\n\n\t\t\tfinish(2)\n\t\t}\n\n\t\ttracef(`%s heartbeat`, node.String())\n\t}\n}\nadd comments for the heartbeat functionpackage main\n\nimport (\n\t\"bufio\"\n\t\"io\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/seletskiy\/hierr\"\n\t\"github.com\/theairkit\/runcmd\"\n)\n\nconst (\n\theartbeatPing = \"PING\"\n)\n\n\/\/ heartbeat runs infinite process of sending test messages to the connected\n\/\/ node. All heartbeats to all nodes are connected to each other, so if one\n\/\/ heartbeat routine exits, all heartbeat routines will exit, because in that\n\/\/ case orgalorg can't guarantee global lock.\nfunc heartbeat(\n\tperiod time.Duration,\n\tnode *distributedLockNode,\n\tcanceler *sync.Cond,\n) {\n\tabort := make(chan struct{}, 0)\n\n\t\/\/ Internal go-routine for listening abort broadcast and finishing current\n\t\/\/ heartbeat process.\n\tgo func() {\n\t\tcanceler.L.Lock()\n\t\tcanceler.Wait()\n\t\tcanceler.L.Unlock()\n\n\t\tabort <- struct{}{}\n\t}()\n\n\t\/\/ Finish finishes current go-routine and send abort broadcast to all\n\t\/\/ connected go-routines.\n\tfinish := func(code int) {\n\t\tcanceler.L.Lock()\n\t\tcanceler.Broadcast()\n\t\tcanceler.L.Unlock()\n\n\t\t<-abort\n\n\t\tif remote, ok := node.runner.(*runcmd.Remote); ok {\n\t\t\ttracef(\"%s closing connection\", node.String())\n\t\t\terr := remote.CloseConnection()\n\t\t\tif err != nil {\n\t\t\t\twarningf(\n\t\t\t\t\t\"%s\",\n\t\t\t\t\thierr.Errorf(\n\t\t\t\t\t\terr,\n\t\t\t\t\t\t\"%s error while closing connection\",\n\t\t\t\t\t\tnode.String(),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\texit(code)\n\t}\n\n\tticker := time.Tick(period)\n\n\t\/\/ Infinite loop of heartbeating. It will send heartbeat message, wait\n\t\/\/ fraction of send timeout time and try to receive heartbeat response.\n\t\/\/ If no response received, heartbeat process aborts.\n\tfor {\n\t\t_, err := io.WriteString(node.connection.stdin, heartbeatPing+\"\\n\")\n\t\tif err != nil {\n\t\t\tlogger.Error(\n\t\t\t\thierr.Errorf(\n\t\t\t\t\terr,\n\t\t\t\t\t`%s can't send heartbeat`,\n\t\t\t\t\tnode.String(),\n\t\t\t\t).Error(),\n\t\t\t)\n\n\t\t\tfinish(2)\n\t\t}\n\n\t\tselect {\n\t\tcase <-abort:\n\t\t\treturn\n\n\t\tcase <-ticker:\n\t\t\t\/\/ pass\n\t\t}\n\n\t\tping, err := bufio.NewReader(node.connection.stdout).ReadString('\\n')\n\t\tif err != nil {\n\t\t\tlogger.Error(\n\t\t\t\thierr.Errorf(\n\t\t\t\t\terr,\n\t\t\t\t\t`%s can't receive heartbeat`,\n\t\t\t\t\tnode.String(),\n\t\t\t\t),\n\t\t\t)\n\n\t\t\tfinish(2)\n\t\t}\n\n\t\tif strings.TrimSpace(ping) != heartbeatPing {\n\t\t\tlogger.Errorf(\n\t\t\t\t`%s received unexpected heartbeat ping: '%s'`,\n\t\t\t\tnode.String(),\n\t\t\t\tping,\n\t\t\t)\n\n\t\t\tfinish(2)\n\t\t}\n\n\t\ttracef(`%s heartbeat`, node.String())\n\t}\n}\n<|endoftext|>"} {"text":"package gearcmd\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"container\/ring\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/Clever\/baseworker-go\"\n\t\"github.com\/Clever\/gearcmd\/argsparser\"\n\t\"gopkg.in\/Clever\/kayvee-go.v2\"\n)\n\n\/\/ TaskConfig defines the configuration for the task.\ntype TaskConfig struct {\n\tFunctionName, FunctionCmd string\n\tWarningLines int\n\tParseArgs bool\n\tCmdTimeout time.Duration\n\tRetryCount int\n}\n\n\/\/ Process runs the Gearman job by running the configured task.\n\/\/ We need to implement the Task interface so we return (byte[], error)\n\/\/ though the byte[] is always nil.\nfunc (conf TaskConfig) Process(job baseworker.Job) ([]byte, error) {\n\t\/\/ This wraps the actual processing to do some logging\n\tlog.Println(kayvee.FormatLog(\"gearcmd\", kayvee.Info, \"START\",\n\t\tmap[string]interface{}{\"function\": conf.FunctionName, \"job_id\": getJobId(job), \"job_data\": string(job.Data())}))\n\n\tfor {\n\t\tstart := time.Now()\n\t\terr := conf.doProcess(job)\n\t\tend := time.Now()\n\t\tdata := map[string]interface{}{\n\t\t\t\"function\": conf.FunctionName,\n\t\t\t\"job_id\": getJobId(job),\n\t\t\t\"job_data\": string(job.Data()),\n\t\t\t\"type\": \"gauge\",\n\t\t}\n\t\t\/\/ Return if the job was successful.\n\t\tif err == nil {\n\t\t\tdata[\"value\"] = 1\n\t\t\tdata[\"success\"] = true\n\t\t\tlog.Println(kayvee.FormatLog(\"gearcmd\", kayvee.Info, \"END\", data))\n\t\t\t\/\/ Hopefully none of our jobs last long enough for a uint64...\n\t\t\tlog.Printf(kayvee.FormatLog(\"gearcmd\", kayvee.Info, \"duration\",\n\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\"value\": uint64(end.Sub(start).Seconds() * 1000),\n\t\t\t\t\t\"type\": \"gauge\",\n\t\t\t\t\t\"function\": conf.FunctionName,\n\t\t\t\t},\n\t\t\t))\n\t\t\treturn nil, nil\n\t\t}\n\t\tdata[\"error_message\"] = err.Error()\n\t\tdata[\"value\"] = 0\n\t\tdata[\"success\"] = false\n\t\t\/\/ Return if the job has no more retries.\n\t\tif conf.RetryCount <= 0 {\n\t\t\tlog.Println(kayvee.FormatLog(\"gearcmd\", kayvee.Error, \"END\", data))\n\t\t\treturn nil, err\n\t\t}\n\t\tconf.RetryCount--\n\t\tlog.Println(kayvee.FormatLog(\"gearcmd\", kayvee.Error, \"RETRY\", data))\n\t}\n}\n\n\/\/ getJobId returns the jobId from the job handle\nfunc getJobId(job baseworker.Job) string {\n\tsplits := strings.Split(job.Handle(), \":\")\n\treturn splits[len(splits)-1]\n}\n\nfunc (conf TaskConfig) doProcess(job baseworker.Job) error {\n\n\tdefer func() {\n\t\t\/\/ If we panicked then set the panic message as a warning. Gearman-go will\n\t\t\/\/ handle marking this job as failed.\n\t\tif r := recover(); r != nil {\n\t\t\terr := r.(error)\n\t\t\tjob.SendWarning([]byte(err.Error()))\n\t\t}\n\t}()\n\tvar args []string\n\tvar err error\n\tif conf.ParseArgs {\n\t\targs, err = argsparser.ParseArgs(string(job.Data()))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\targs = []string{string(job.Data())}\n\n\t}\n\tcmd := exec.Command(conf.FunctionCmd, args...)\n\n\t\/\/ Write the stdout and stderr of the process to both this process' stdout and stderr\n\t\/\/ and also write it to a byte buffer so that we can return it with the Gearman job\n\t\/\/ data as necessary.\n\tvar stderrbuf bytes.Buffer\n\tcmd.Stderr = io.MultiWriter(os.Stderr, &stderrbuf)\n\tdefer sendStderrWarnings(&stderrbuf, job, conf.WarningLines)\n\n\tstdoutReader, stdoutWriter := io.Pipe()\n\tcmd.Stdout = io.MultiWriter(os.Stdout, stdoutWriter)\n\n\tdone := make(chan error)\n\tgo func() {\n\t\tdefer close(done)\n\n\t\tfinishedProcessingStdout := make(chan error)\n\t\tgo func() {\n\t\t\tfinishedProcessingStdout <- streamToGearman(stdoutReader, job)\n\t\t}()\n\n\t\t\/\/ Save the cmdErr. We want to process stdout and stderr before we return it\n\t\tcmdErr := cmd.Run()\n\t\tstdoutWriter.Close()\n\n\t\tstdoutErr := <-finishedProcessingStdout\n\t\tif cmdErr != nil {\n\t\t\tdone <- cmdErr\n\t\t} else if stdoutErr != nil {\n\t\t\tdone <- stdoutErr\n\t\t}\n\t}()\n\t\/\/ No timeout\n\tif conf.CmdTimeout == 0 {\n\t\t\/\/ Will be nil if the channel was closed without any errors\n\t\treturn <-done\n\t}\n\tselect {\n\tcase err := <-done:\n\t\t\/\/ Will be nil if the channel was closed without any errors\n\t\treturn err\n\tcase <-time.After(conf.CmdTimeout):\n\t\tif err := cmd.Process.Kill(); err != nil {\n\t\t\treturn fmt.Errorf(\"process timeout after %s. error: %s\", conf.CmdTimeout.String(), err.Error())\n\t\t}\n\t\treturn fmt.Errorf(\"process timed out after %s\", conf.CmdTimeout.String())\n\t}\n}\n\n\/\/ This function streams the reader to the Gearman job (through job.SendData())\nfunc streamToGearman(reader io.Reader, job baseworker.Job) error {\n\tbuffer := make([]byte, 1024)\n\tfor {\n\t\tn, err := reader.Read(buffer)\n\t\t\/\/ Process the data before processing the error (as per the io.Reader docs)\n\t\tif n > 0 {\n\t\t\tjob.SendData(buffer[:n])\n\t\t}\n\t\tif err == io.EOF {\n\t\t\treturn nil\n\t\t} else if err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n}\n\n\/\/ sendStderrWarnings sends the last X lines in the stderr output and to the job's warnings\n\/\/ field\nfunc sendStderrWarnings(buffer io.Reader, job baseworker.Job, warningLines int) error {\n\tscanner := bufio.NewScanner(buffer)\n\t\/\/ Create a circular buffer for the last X lines\n\tlastStderrLines := ring.New(warningLines)\n\tfor scanner.Scan() {\n\t\tlastStderrLines = lastStderrLines.Next()\n\t\tlastStderrLines.Value = scanner.Bytes()\n\t}\n\t\/\/ Walk forward through the buffer to get all the last X entries. Note that we call next first\n\t\/\/ so that we start at the oldest entry.\n\tfor i := 0; i < lastStderrLines.Len(); i++ {\n\t\tif lastStderrLines = lastStderrLines.Next(); lastStderrLines.Value != nil {\n\t\t\tjob.SendWarning(append(lastStderrLines.Value.([]byte), byte('\\n')))\n\t\t}\n\t}\n\treturn scanner.Err()\n}\nAdded log line of type counter. Will be used for alerting.package gearcmd\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"container\/ring\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com\/Clever\/baseworker-go\"\n\t\"github.com\/Clever\/gearcmd\/argsparser\"\n\t\"gopkg.in\/Clever\/kayvee-go.v2\"\n)\n\n\/\/ TaskConfig defines the configuration for the task.\ntype TaskConfig struct {\n\tFunctionName, FunctionCmd string\n\tWarningLines int\n\tParseArgs bool\n\tCmdTimeout time.Duration\n\tRetryCount int\n}\n\n\/\/ Process runs the Gearman job by running the configured task.\n\/\/ We need to implement the Task interface so we return (byte[], error)\n\/\/ though the byte[] is always nil.\nfunc (conf TaskConfig) Process(job baseworker.Job) ([]byte, error) {\n\t\/\/ This wraps the actual processing to do some logging\n\tlog.Println(kayvee.FormatLog(\"gearcmd\", kayvee.Info, \"START\",\n\t\tmap[string]interface{}{\"function\": conf.FunctionName, \"job_id\": getJobId(job), \"job_data\": string(job.Data())}))\n\n\tfor {\n\t\tstart := time.Now()\n\t\terr := conf.doProcess(job)\n\t\tend := time.Now()\n\t\tdata := map[string]interface{}{\n\t\t\t\"function\": conf.FunctionName,\n\t\t\t\"job_id\": getJobId(job),\n\t\t\t\"job_data\": string(job.Data()),\n\t\t\t\"type\": \"gauge\",\n\t\t}\n\n\t\tvar status string\n\t\tif err == nil {\n\t\t\tstatus = \"success\"\n\t\t} else {\n\t\t\tstatus = \"failure\"\n\t\t}\n\t\tlog.Println(kayvee.FormatLog(\"gearcmd\", kayvee.Info, status, map[string]interface{}{\n\t\t\t\"type\": \"counter\",\n\t\t\t\"function\": conf.FunctionName,\n\t\t}))\n\n\t\t\/\/ Return if the job was successful.\n\t\tif err == nil {\n\t\t\tdata[\"value\"] = 1\n\t\t\tdata[\"success\"] = true\n\t\t\tlog.Println(kayvee.FormatLog(\"gearcmd\", kayvee.Info, \"END\", data))\n\t\t\t\/\/ Hopefully none of our jobs last long enough for a uint64...\n\t\t\tlog.Printf(kayvee.FormatLog(\"gearcmd\", kayvee.Info, \"duration\",\n\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\"value\": uint64(end.Sub(start).Seconds() * 1000),\n\t\t\t\t\t\"type\": \"gauge\",\n\t\t\t\t\t\"function\": conf.FunctionName,\n\t\t\t\t},\n\t\t\t))\n\t\t\treturn nil, nil\n\t\t}\n\t\tdata[\"error_message\"] = err.Error()\n\t\tdata[\"value\"] = 0\n\t\tdata[\"success\"] = false\n\t\t\/\/ Return if the job has no more retries.\n\t\tif conf.RetryCount <= 0 {\n\t\t\tlog.Println(kayvee.FormatLog(\"gearcmd\", kayvee.Error, \"END\", data))\n\t\t\treturn nil, err\n\t\t}\n\t\tconf.RetryCount--\n\t\tlog.Println(kayvee.FormatLog(\"gearcmd\", kayvee.Error, \"RETRY\", data))\n\t}\n}\n\n\/\/ getJobId returns the jobId from the job handle\nfunc getJobId(job baseworker.Job) string {\n\tsplits := strings.Split(job.Handle(), \":\")\n\treturn splits[len(splits)-1]\n}\n\nfunc (conf TaskConfig) doProcess(job baseworker.Job) error {\n\n\tdefer func() {\n\t\t\/\/ If we panicked then set the panic message as a warning. Gearman-go will\n\t\t\/\/ handle marking this job as failed.\n\t\tif r := recover(); r != nil {\n\t\t\terr := r.(error)\n\t\t\tjob.SendWarning([]byte(err.Error()))\n\t\t}\n\t}()\n\tvar args []string\n\tvar err error\n\tif conf.ParseArgs {\n\t\targs, err = argsparser.ParseArgs(string(job.Data()))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\targs = []string{string(job.Data())}\n\n\t}\n\tcmd := exec.Command(conf.FunctionCmd, args...)\n\n\t\/\/ Write the stdout and stderr of the process to both this process' stdout and stderr\n\t\/\/ and also write it to a byte buffer so that we can return it with the Gearman job\n\t\/\/ data as necessary.\n\tvar stderrbuf bytes.Buffer\n\tcmd.Stderr = io.MultiWriter(os.Stderr, &stderrbuf)\n\tdefer sendStderrWarnings(&stderrbuf, job, conf.WarningLines)\n\n\tstdoutReader, stdoutWriter := io.Pipe()\n\tcmd.Stdout = io.MultiWriter(os.Stdout, stdoutWriter)\n\n\tdone := make(chan error)\n\tgo func() {\n\t\tdefer close(done)\n\n\t\tfinishedProcessingStdout := make(chan error)\n\t\tgo func() {\n\t\t\tfinishedProcessingStdout <- streamToGearman(stdoutReader, job)\n\t\t}()\n\n\t\t\/\/ Save the cmdErr. We want to process stdout and stderr before we return it\n\t\tcmdErr := cmd.Run()\n\t\tstdoutWriter.Close()\n\n\t\tstdoutErr := <-finishedProcessingStdout\n\t\tif cmdErr != nil {\n\t\t\tdone <- cmdErr\n\t\t} else if stdoutErr != nil {\n\t\t\tdone <- stdoutErr\n\t\t}\n\t}()\n\t\/\/ No timeout\n\tif conf.CmdTimeout == 0 {\n\t\t\/\/ Will be nil if the channel was closed without any errors\n\t\treturn <-done\n\t}\n\tselect {\n\tcase err := <-done:\n\t\t\/\/ Will be nil if the channel was closed without any errors\n\t\treturn err\n\tcase <-time.After(conf.CmdTimeout):\n\t\tif err := cmd.Process.Kill(); err != nil {\n\t\t\treturn fmt.Errorf(\"process timeout after %s. error: %s\", conf.CmdTimeout.String(), err.Error())\n\t\t}\n\t\treturn fmt.Errorf(\"process timed out after %s\", conf.CmdTimeout.String())\n\t}\n}\n\n\/\/ This function streams the reader to the Gearman job (through job.SendData())\nfunc streamToGearman(reader io.Reader, job baseworker.Job) error {\n\tbuffer := make([]byte, 1024)\n\tfor {\n\t\tn, err := reader.Read(buffer)\n\t\t\/\/ Process the data before processing the error (as per the io.Reader docs)\n\t\tif n > 0 {\n\t\t\tjob.SendData(buffer[:n])\n\t\t}\n\t\tif err == io.EOF {\n\t\t\treturn nil\n\t\t} else if err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n}\n\n\/\/ sendStderrWarnings sends the last X lines in the stderr output and to the job's warnings\n\/\/ field\nfunc sendStderrWarnings(buffer io.Reader, job baseworker.Job, warningLines int) error {\n\tscanner := bufio.NewScanner(buffer)\n\t\/\/ Create a circular buffer for the last X lines\n\tlastStderrLines := ring.New(warningLines)\n\tfor scanner.Scan() {\n\t\tlastStderrLines = lastStderrLines.Next()\n\t\tlastStderrLines.Value = scanner.Bytes()\n\t}\n\t\/\/ Walk forward through the buffer to get all the last X entries. Note that we call next first\n\t\/\/ so that we start at the oldest entry.\n\tfor i := 0; i < lastStderrLines.Len(); i++ {\n\t\tif lastStderrLines = lastStderrLines.Next(); lastStderrLines.Value != nil {\n\t\t\tjob.SendWarning(append(lastStderrLines.Value.([]byte), byte('\\n')))\n\t\t}\n\t}\n\treturn scanner.Err()\n}\n<|endoftext|>"} {"text":"package emitter\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\t\"gopkg.in\/vmihailenco\/msgpack.v1\"\n\t\"github.com\/garyburd\/redigo\/redis\"\n)\n\nconst (\n\tevent = 2\n\tbinaryEvent = 5\n\tredisPoolMaxIdle = 80\n\tredisPoolMaxActive = 12000 \/\/ max number of connections\n)\n\ntype EmitterOptions struct {\n\tHost string\n\tPassword string\n\tKey string\n}\n\ntype Emitter struct {\n\t_opts EmitterOptions\n\t_key string\n\t_flags map[string]string\n\t_rooms map[string]bool\n\t_pool *redis.Pool\n}\n\nfunc New(opts EmitterOptions) Emitter {\n\temitter := Emitter{_opts:opts}\n\n\tinitRedisConnPool(&emitter, opts)\n\n\tif opts.Key != \"\" {\n\t\temitter._key = fmt.Sprintf(\"%s#emitter\", opts.Key)\n\t}else {\n\t\temitter._key = \"socket.io#emitter\"\n\t}\n\n\temitter._rooms = make(map[string]bool)\n\temitter._flags = make(map[string]string)\n\n\treturn emitter\n}\n\nfunc (emitter Emitter) In(room string) Emitter {\n\tif _, ok := emitter._rooms[room]; ok == false {\n\t\temitter._rooms[room] = true\n\t}\n\treturn emitter\n}\n\nfunc (emitter Emitter) To(room string) Emitter {\n\treturn emitter.In(room)\n}\n\nfunc (emitter Emitter) Of(nsp string) Emitter {\n\temitter._flags[\"nsp\"] = nsp\n\treturn emitter\n}\n\nfunc (emitter Emitter) Emit(args ...interface{}) bool {\n\tpacket := make(map[string]interface{})\n\textras := make(map[string]interface{})\n\n\tif ok := emitter.hasBin(args); ok {\n\t\tpacket[\"type\"] = binaryEvent\n\t}else {\n\t\tpacket[\"type\"] = event\n\t}\n\n\tpacket[\"data\"] = args\n\n\tif value, ok := emitter._flags[\"nsp\"]; ok {\n\t\tpacket[\"nsp\"] = value\n\t\tdelete(emitter._flags, \"nsp\")\n\t}else {\n\t\tpacket[\"nsp\"] = \"\/\"\n\t}\n\n\n\tif ok := len(emitter._rooms); ok > 0 {\n\t\t\/\/TODO:Cast??\n\t\textras[\"rooms\"] = getKeys(emitter._rooms)\n\t}else {\n\t\textras[\"rooms\"] = make([]string, 0, 0)\n\t}\n\n\tif ok := len(emitter._flags); ok > 0 {\n\t\textras[\"flags\"] = emitter._flags\n\t}else {\n\t\textras[\"flags\"] = make(map[string]string)\n\t}\n\n\t\/\/TODO: Gorotunes\n\t\/\/Pack & Publish\n\tb, err := msgpack.Marshal([]interface{}{packet, extras})\n\tif err != nil {\n\t\tpanic(err)\n\t}else {\n\t\tpublish(emitter, emitter._key, b)\n\t}\n\n\temitter._rooms = make(map[string]bool)\n\temitter._flags = make(map[string]string)\n\n\treturn true\n}\n\n\nfunc (emitter Emitter) hasBin(args ...interface{}) bool {\n\t\/\/NOT implemented yet!\n\treturn true\n}\n\nfunc initRedisConnPool(emitter *Emitter , opts EmitterOptions) () {\n\tif opts.Host == \"\" {\n\t\tpanic(\"Missing redis `host`\")\n\t}\n\n\temitter._pool = newPool(opts)\n}\n\nfunc newPool(opts EmitterOptions) *redis.Pool {\n\treturn &redis.Pool{\n\t\tMaxIdle: redisPoolMaxIdle,\n\t\tMaxActive: redisPoolMaxActive,\n\t\tDial: func() (redis.Conn, error) {\n\t\t\tc, err := redis.Dial(\"tcp\", opts.Host)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tif opts.Password != \"\" {\n\t\t\t\tif _, err := c.Do(\"AUTH\", opts.Password); err != nil {\n\t\t\t\t\tc.Close()\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\treturn c, err\n\t\t\t}\n\n\t\t\treturn c, err\n\t\t},\n\t\tTestOnBorrow: func(c redis.Conn, t time.Time) error {\n\t\t\t_, err := c.Do(\"PING\")\n\t\t\treturn err\n\t\t},\n\t}\n\n}\n\n\nfunc publish(emitter Emitter, channel string, value interface{}) {\n\tc := emitter._pool.Get()\n\tdefer c.Close()\n\tc.Do(\"PUBLISH\", channel, value)\n\n}\n\nfunc getKeys(m map[string]bool) []string {\n\tkeys := make([]string, 0, len(m))\n\n\tfor key := range m {\n\t\tkeys = append(keys, key)\n\t}\n\n\treturn keys\n}\n\n\nfunc dump(emitter Emitter, args ...interface{}) {\n\tfmt.Println(\"Emit params : \", args)\n\tfmt.Println(\"Emitter key: \", emitter._key)\n\tfmt.Println(\"Emitter flags: \", emitter._flags)\n\tfmt.Println(\"Emitter rooms: \", emitter._rooms)\n}fix typopackage emitter\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\t\"gopkg.in\/vmihailenco\/msgpack.v1\"\n\t\"github.com\/garyburd\/redigo\/redis\"\n)\n\nconst (\n\tevent = 2\n\tbinaryEvent = 5\n\tredisPoolMaxIdle = 80\n\tredisPoolMaxActive = 12000 \/\/ max number of connections\n)\n\ntype EmitterOptions struct {\n\tHost string\n\tPassword string\n\tKey string\n}\n\ntype Emitter struct {\n\t_opts EmitterOptions\n\t_key string\n\t_flags map[string]string\n\t_rooms map[string]bool\n\t_pool *redis.Pool\n}\n\nfunc New(opts EmitterOptions) Emitter {\n\temitter := Emitter{_opts:opts}\n\n\tinitRedisConnPool(&emitter, opts)\n\n\tif opts.Key != \"\" {\n\t\temitter._key = fmt.Sprintf(\"%s#emitter\", opts.Key)\n\t}else {\n\t\temitter._key = \"socket.io#emitter\"\n\t}\n\n\temitter._rooms = make(map[string]bool)\n\temitter._flags = make(map[string]string)\n\n\treturn emitter\n}\n\nfunc (emitter Emitter) In(room string) Emitter {\n\tif _, ok := emitter._rooms[room]; ok == false {\n\t\temitter._rooms[room] = true\n\t}\n\treturn emitter\n}\n\nfunc (emitter Emitter) To(room string) Emitter {\n\treturn emitter.In(room)\n}\n\nfunc (emitter Emitter) Of(nsp string) Emitter {\n\temitter._flags[\"nsp\"] = nsp\n\treturn emitter\n}\n\nfunc (emitter Emitter) Emit(args ...interface{}) bool {\n\tpacket := make(map[string]interface{})\n\textras := make(map[string]interface{})\n\n\tif ok := emitter.hasBin(args); ok {\n\t\tpacket[\"type\"] = binaryEvent\n\t}else {\n\t\tpacket[\"type\"] = event\n\t}\n\n\tpacket[\"data\"] = args\n\n\tif value, ok := emitter._flags[\"nsp\"]; ok {\n\t\tpacket[\"nsp\"] = value\n\t\tdelete(emitter._flags, \"nsp\")\n\t}else {\n\t\tpacket[\"nsp\"] = \"\/\"\n\t}\n\n\n\tif ok := len(emitter._rooms); ok > 0 {\n\t\t\/\/TODO:Cast??\n\t\textras[\"rooms\"] = getKeys(emitter._rooms)\n\t}else {\n\t\textras[\"rooms\"] = make([]string, 0, 0)\n\t}\n\n\tif ok := len(emitter._flags); ok > 0 {\n\t\textras[\"flags\"] = emitter._flags\n\t}else {\n\t\textras[\"flags\"] = make(map[string]string)\n\t}\n\n\t\/\/TODO: Goroutines\n\t\/\/Pack & Publish\n\tb, err := msgpack.Marshal([]interface{}{packet, extras})\n\tif err != nil {\n\t\tpanic(err)\n\t}else {\n\t\tpublish(emitter, emitter._key, b)\n\t}\n\n\temitter._rooms = make(map[string]bool)\n\temitter._flags = make(map[string]string)\n\n\treturn true\n}\n\n\nfunc (emitter Emitter) hasBin(args ...interface{}) bool {\n\t\/\/NOT implemented yet!\n\treturn true\n}\n\nfunc initRedisConnPool(emitter *Emitter , opts EmitterOptions) () {\n\tif opts.Host == \"\" {\n\t\tpanic(\"Missing redis `host`\")\n\t}\n\n\temitter._pool = newPool(opts)\n}\n\nfunc newPool(opts EmitterOptions) *redis.Pool {\n\treturn &redis.Pool{\n\t\tMaxIdle: redisPoolMaxIdle,\n\t\tMaxActive: redisPoolMaxActive,\n\t\tDial: func() (redis.Conn, error) {\n\t\t\tc, err := redis.Dial(\"tcp\", opts.Host)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tif opts.Password != \"\" {\n\t\t\t\tif _, err := c.Do(\"AUTH\", opts.Password); err != nil {\n\t\t\t\t\tc.Close()\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\treturn c, err\n\t\t\t}\n\n\t\t\treturn c, err\n\t\t},\n\t\tTestOnBorrow: func(c redis.Conn, t time.Time) error {\n\t\t\t_, err := c.Do(\"PING\")\n\t\t\treturn err\n\t\t},\n\t}\n\n}\n\n\nfunc publish(emitter Emitter, channel string, value interface{}) {\n\tc := emitter._pool.Get()\n\tdefer c.Close()\n\tc.Do(\"PUBLISH\", channel, value)\n\n}\n\nfunc getKeys(m map[string]bool) []string {\n\tkeys := make([]string, 0, len(m))\n\n\tfor key := range m {\n\t\tkeys = append(keys, key)\n\t}\n\n\treturn keys\n}\n\n\nfunc dump(emitter Emitter, args ...interface{}) {\n\tfmt.Println(\"Emit params : \", args)\n\tfmt.Println(\"Emitter key: \", emitter._key)\n\tfmt.Println(\"Emitter flags: \", emitter._flags)\n\tfmt.Println(\"Emitter rooms: \", emitter._rooms)\n}\n<|endoftext|>"} {"text":"package apexovernsq\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com\/avct\/apexovernsq\/protobuf\"\n\n\talog \"github.com\/apex\/log\"\n\t\"github.com\/apex\/log\/handlers\/memory\"\n\tnsq \"github.com\/nsqio\/go-nsq\"\n)\n\ntype entryList []*alog.Entry\n\n\/\/ simulateMessageFromNSQ packs an Apex Log Entry into an NSQ Message\n\/\/ and pushes it through the NSQApexLogHandler. The NSQApexLogHandler\n\/\/ will use the Apex Log memory handler to return the Apex Log Entry\n\/\/ that would be logged.\nfunc simulateMessageFromNSQ(sourceEntry *alog.Entry, filter *[]string) (*alog.Entry, error) {\n\tvar handler *NSQApexLogHandler\n\tmarshalledEntry, err := protobuf.Marshal(sourceEntry)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Couldn't marshal log entry: %s\", err.Error())\n\t}\n\n\tmsg := nsq.NewMessage(nsq.MessageID{'a', 'b', 'c'}, []byte(marshalledEntry))\n\n\tinnerHandler := memory.New()\n\tif filter == nil {\n\t\thandler = NewNSQApexLogHandler(innerHandler, protobuf.Unmarshal)\n\t} else {\n\t\tfilterHandler := NewApexLogServiceFilterHandler(innerHandler, filter)\n\t\thandler = NewNSQApexLogHandler(filterHandler, protobuf.Unmarshal)\n\t}\n\n\thandler.HandleMessage(msg)\n\treturn innerHandler.Entries[0], nil\n}\n\n\/\/ simulateMessagesFromNSQ packs an entryList into a series of NSQ Messages and pushes them through the NSQApexLogHandler. The NSQApexLogHandler will use the Apex Log memory handler to return an entryList that would be logged locally.\nfunc simulateMessagesFromNSQ(sourceEntries *entryList, filter *[]string) (*entryList, error) {\n\tvar marshalledEntry []byte\n\tvar err error\n\tvar msg *nsq.Message\n\tvar handler nsq.Handler\n\n\tinnerHandler := memory.New()\n\tif filter == nil {\n\t\thandler = NewNSQApexLogHandler(innerHandler, protobuf.Unmarshal)\n\t} else {\n\t\tfilterHandler := NewApexLogServiceFilterHandler(innerHandler, filter)\n\t\thandler = NewNSQApexLogHandler(filterHandler, protobuf.Unmarshal)\n\t}\n\n\tfor _, sourceEntry := range *sourceEntries {\n\t\tmarshalledEntry, err = protobuf.Marshal(sourceEntry)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Couldn't marshal log entry: %s\", err.Error())\n\t\t}\n\n\t\tmsg = nsq.NewMessage(nsq.MessageID{'a', 'b', 'c'}, marshalledEntry)\n\t\thandler.HandleMessage(msg)\n\t}\n\tresult := innerHandler.Entries[:]\n\treturn (*entryList)(&result), nil\n\n}\n\n\/\/ simulateEntry returns a finalised Entry from the memory handler as\n\/\/ it would appear in normal logging.\nfunc simulateEntry(logger alog.Interface, fields alog.Fielder, msg string) *alog.Entry {\n\tmemoryHandler := memory.New()\n\talog.SetHandler(memoryHandler)\n\tif fields == nil {\n\t\tlogger.Info(msg)\n\t} else {\n\t\tlogger.WithFields(fields).Info(msg)\n\t}\n\treturn memoryHandler.Entries[0]\n}\n\n\/\/ simulateEntries makes a stipulated number of finalised Apex Log\n\/\/ Entry instances and stores them in a provided store (a pointer to\n\/\/ an entryList), starting from a given offset. ⚠ Danger Will\n\/\/ Robinson, here be side-effects. The provided offset and store will\n\/\/ both be mutated. ⚠\nfunc simulateEntries(ctx alog.Interface, count int, offset *int, store *entryList) {\n\tvar m int\n\tfor m = 0; m < count; m++ {\n\t\tentry := simulateEntry(ctx, nil, fmt.Sprintf(\"%d\", *offset))\n\t\t(*store)[*offset] = entry\n\t\t*offset++\n\t}\n}\n\nfunc TestHandleMessage(t *testing.T) {\n\tlogger := alog.Log\n\tsourceEntry := simulateEntry(logger, alog.Fields{\n\t\t\"flavour\": \"pistachio\",\n\t\t\"scoops\": \"2\",\n\t}, \"it's ice cream time!\")\n\n\tentry, err := simulateMessageFromNSQ(sourceEntry, nil)\n\tif err != nil {\n\t\tt.Fatalf(\"%s\", err.Error())\n\t}\n\tif entry.Message != sourceEntry.Message {\n\t\tt.Errorf(\"Expected %q, got %q\", sourceEntry.Message, entry.Message)\n\t}\n\tif entry.Level != sourceEntry.Level {\n\t\tt.Errorf(\"Expected %s, got %s\", sourceEntry.Level, entry.Level)\n\t}\n\tif entry.Timestamp != sourceEntry.Timestamp {\n\t\tt.Errorf(\"Expected %q, got %q\", sourceEntry.Timestamp, entry.Timestamp)\n\t}\n\texpectedFieldCount := len(sourceEntry.Fields)\n\tactualFieldCount := len(entry.Fields)\n\tif expectedFieldCount != actualFieldCount {\n\t\tt.Errorf(\"Expected %d fields, but got %d fields\", expectedFieldCount, actualFieldCount)\n\t}\n\tfor fieldName, value := range sourceEntry.Fields {\n\t\trecieved := entry.Fields.Get(fieldName)\n\t\tif recieved != value {\n\t\t\tt.Errorf(\"Expected %s=%q, got %s=%q\", fieldName, value, fieldName, recieved)\n\t\t}\n\t}\n}\n\nfunc TestFilterMessagesByService(t *testing.T) {\n\tvar ctx alog.Interface\n\tvar entries *entryList\n\tvar err error\n\tvar generatedMessages int\n\tvar resultEntryCount int\n\tvar sourceEntries entryList\n\tvar totalMessages int\n\n\tvar thisProcessFilter = &[]string{processName()}\n\tvar otherProcessFilter = &[]string{\"other\"}\n\tvar unknownProcessFilter = &[]string{\"unknown\"}\n\tvar multiServiceFilter = &[]string{processName(), \"other\"}\n\n\tvar caseTable = []struct {\n\t\tserviceMessages int\n\t\totherServiceMessages int\n\t\tnonServiceMessages int\n\t\tresultEntryCount int\n\t\tfilter *[]string\n\t\tmessages []string\n\t}{\n\t\t{1, 1, 1, 3, nil, []string{\"0\", \"1\", \"2\"}}, \/\/ Default case, no filtering\n\t\t{1, 1, 1, 1, thisProcessFilter, []string{\"0\"}}, \/\/ Whitelist service messages\n\t\t{1, 1, 1, 1, otherProcessFilter, []string{\"1\"}}, \/\/ Whitelist other service messages\n\t\t{1, 1, 1, 0, unknownProcessFilter, []string{}}, \/\/ Whitelist service that isn't present\n\t\t{1, 1, 1, 2, multiServiceFilter, []string{\"0\", \"1\"}}, \/\/ Whitelist both this service and \"other\" service\n\n\t}\n\n\tfor caseNum, testCase := range caseTable {\n\t\ttotalMessages = testCase.serviceMessages + testCase.nonServiceMessages + testCase.otherServiceMessages\n\t\tgeneratedMessages = 0\n\t\tsourceEntries = make([]*alog.Entry, totalMessages)\n\n\t\t\/\/ Generate service messages\n\t\tctx = NewApexLogServiceContext()\n\t\tsimulateEntries(ctx, testCase.serviceMessages, &generatedMessages, &sourceEntries)\n\t\t\/\/ Generate other service messages\n\t\tctx = ctx.WithFields(alog.Fields{\"service\": \"other\"})\n\t\tsimulateEntries(ctx, testCase.otherServiceMessages, &generatedMessages, &sourceEntries)\n\n\t\t\/\/ Generate non-service messages\n\t\tctx = alog.Log\n\t\tsimulateEntries(ctx, testCase.nonServiceMessages, &generatedMessages, &sourceEntries)\n\n\t\tentries, err = simulateMessagesFromNSQ(&sourceEntries, testCase.filter)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Error in message simulation: %s\", err.Error())\n\t\t}\n\t\tif entries == nil && testCase.resultEntryCount > 0 {\n\t\t\tt.Errorf(\"Expected %d entries from test case %d but got nil. Message counts: service %d, other-service %d, non-service %d. Filter: %+v.\", testCase.resultEntryCount, caseNum, testCase.serviceMessages, testCase.otherServiceMessages, testCase.nonServiceMessages, testCase.filter)\n\t\t\tcontinue\n\t\t}\n\t\tresultEntryCount = len(*entries)\n\t\tif resultEntryCount != testCase.resultEntryCount {\n\t\t\tt.Errorf(\"[Case %d] Expected %d entries, but got %d. Message counts: service %d, other-service %d, non-service %d. Filter: %+v.\", caseNum+1, testCase.resultEntryCount, resultEntryCount, testCase.serviceMessages, testCase.otherServiceMessages, testCase.nonServiceMessages, testCase.filter)\n\t\t\tcontinue\n\t\t}\n\n\t\tfor idx, entry := range *entries {\n\t\t\ttestMessage := testCase.messages[idx]\n\t\t\tif entry.Message != testMessage {\n\t\t\t\tt.Errorf(\"[Case %d] Expected Entry[%d] to have message %q, but got %q\", caseNum, idx, testMessage, entry.Message)\n\t\t\t}\n\t\t}\n\t}\n}\nUse time.Time.Equal instead of = operator when comparing timestampspackage apexovernsq\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com\/avct\/apexovernsq\/protobuf\"\n\n\talog \"github.com\/apex\/log\"\n\t\"github.com\/apex\/log\/handlers\/memory\"\n\tnsq \"github.com\/nsqio\/go-nsq\"\n)\n\ntype entryList []*alog.Entry\n\n\/\/ simulateMessageFromNSQ packs an Apex Log Entry into an NSQ Message\n\/\/ and pushes it through the NSQApexLogHandler. The NSQApexLogHandler\n\/\/ will use the Apex Log memory handler to return the Apex Log Entry\n\/\/ that would be logged.\nfunc simulateMessageFromNSQ(sourceEntry *alog.Entry, filter *[]string) (*alog.Entry, error) {\n\tvar handler *NSQApexLogHandler\n\tmarshalledEntry, err := protobuf.Marshal(sourceEntry)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Couldn't marshal log entry: %s\", err.Error())\n\t}\n\n\tmsg := nsq.NewMessage(nsq.MessageID{'a', 'b', 'c'}, []byte(marshalledEntry))\n\n\tinnerHandler := memory.New()\n\tif filter == nil {\n\t\thandler = NewNSQApexLogHandler(innerHandler, protobuf.Unmarshal)\n\t} else {\n\t\tfilterHandler := NewApexLogServiceFilterHandler(innerHandler, filter)\n\t\thandler = NewNSQApexLogHandler(filterHandler, protobuf.Unmarshal)\n\t}\n\n\thandler.HandleMessage(msg)\n\treturn innerHandler.Entries[0], nil\n}\n\n\/\/ simulateMessagesFromNSQ packs an entryList into a series of NSQ Messages and pushes them through the NSQApexLogHandler. The NSQApexLogHandler will use the Apex Log memory handler to return an entryList that would be logged locally.\nfunc simulateMessagesFromNSQ(sourceEntries *entryList, filter *[]string) (*entryList, error) {\n\tvar marshalledEntry []byte\n\tvar err error\n\tvar msg *nsq.Message\n\tvar handler nsq.Handler\n\n\tinnerHandler := memory.New()\n\tif filter == nil {\n\t\thandler = NewNSQApexLogHandler(innerHandler, protobuf.Unmarshal)\n\t} else {\n\t\tfilterHandler := NewApexLogServiceFilterHandler(innerHandler, filter)\n\t\thandler = NewNSQApexLogHandler(filterHandler, protobuf.Unmarshal)\n\t}\n\n\tfor _, sourceEntry := range *sourceEntries {\n\t\tmarshalledEntry, err = protobuf.Marshal(sourceEntry)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Couldn't marshal log entry: %s\", err.Error())\n\t\t}\n\n\t\tmsg = nsq.NewMessage(nsq.MessageID{'a', 'b', 'c'}, marshalledEntry)\n\t\thandler.HandleMessage(msg)\n\t}\n\tresult := innerHandler.Entries[:]\n\treturn (*entryList)(&result), nil\n\n}\n\n\/\/ simulateEntry returns a finalised Entry from the memory handler as\n\/\/ it would appear in normal logging.\nfunc simulateEntry(logger alog.Interface, fields alog.Fielder, msg string) *alog.Entry {\n\tmemoryHandler := memory.New()\n\talog.SetHandler(memoryHandler)\n\tif fields == nil {\n\t\tlogger.Info(msg)\n\t} else {\n\t\tlogger.WithFields(fields).Info(msg)\n\t}\n\treturn memoryHandler.Entries[0]\n}\n\n\/\/ simulateEntries makes a stipulated number of finalised Apex Log\n\/\/ Entry instances and stores them in a provided store (a pointer to\n\/\/ an entryList), starting from a given offset. ⚠ Danger Will\n\/\/ Robinson, here be side-effects. The provided offset and store will\n\/\/ both be mutated. ⚠\nfunc simulateEntries(ctx alog.Interface, count int, offset *int, store *entryList) {\n\tvar m int\n\tfor m = 0; m < count; m++ {\n\t\tentry := simulateEntry(ctx, nil, fmt.Sprintf(\"%d\", *offset))\n\t\t(*store)[*offset] = entry\n\t\t*offset++\n\t}\n}\n\nfunc TestHandleMessage(t *testing.T) {\n\tlogger := alog.Log\n\tsourceEntry := simulateEntry(logger, alog.Fields{\n\t\t\"flavour\": \"pistachio\",\n\t\t\"scoops\": \"2\",\n\t}, \"it's ice cream time!\")\n\n\tentry, err := simulateMessageFromNSQ(sourceEntry, nil)\n\tif err != nil {\n\t\tt.Fatalf(\"%s\", err.Error())\n\t}\n\tif entry.Message != sourceEntry.Message {\n\t\tt.Errorf(\"Expected %q, got %q\", sourceEntry.Message, entry.Message)\n\t}\n\tif entry.Level != sourceEntry.Level {\n\t\tt.Errorf(\"Expected %s, got %s\", sourceEntry.Level, entry.Level)\n\t}\n\tif !entry.Timestamp.Equal(sourceEntry.Timestamp) {\n\t\tt.Errorf(\"Expected %q, got %q\", sourceEntry.Timestamp, entry.Timestamp)\n\t}\n\texpectedFieldCount := len(sourceEntry.Fields)\n\tactualFieldCount := len(entry.Fields)\n\tif expectedFieldCount != actualFieldCount {\n\t\tt.Errorf(\"Expected %d fields, but got %d fields\", expectedFieldCount, actualFieldCount)\n\t}\n\tfor fieldName, value := range sourceEntry.Fields {\n\t\trecieved := entry.Fields.Get(fieldName)\n\t\tif recieved != value {\n\t\t\tt.Errorf(\"Expected %s=%q, got %s=%q\", fieldName, value, fieldName, recieved)\n\t\t}\n\t}\n}\n\nfunc TestFilterMessagesByService(t *testing.T) {\n\tvar ctx alog.Interface\n\tvar entries *entryList\n\tvar err error\n\tvar generatedMessages int\n\tvar resultEntryCount int\n\tvar sourceEntries entryList\n\tvar totalMessages int\n\n\tvar thisProcessFilter = &[]string{processName()}\n\tvar otherProcessFilter = &[]string{\"other\"}\n\tvar unknownProcessFilter = &[]string{\"unknown\"}\n\tvar multiServiceFilter = &[]string{processName(), \"other\"}\n\n\tvar caseTable = []struct {\n\t\tserviceMessages int\n\t\totherServiceMessages int\n\t\tnonServiceMessages int\n\t\tresultEntryCount int\n\t\tfilter *[]string\n\t\tmessages []string\n\t}{\n\t\t{1, 1, 1, 3, nil, []string{\"0\", \"1\", \"2\"}}, \/\/ Default case, no filtering\n\t\t{1, 1, 1, 1, thisProcessFilter, []string{\"0\"}}, \/\/ Whitelist service messages\n\t\t{1, 1, 1, 1, otherProcessFilter, []string{\"1\"}}, \/\/ Whitelist other service messages\n\t\t{1, 1, 1, 0, unknownProcessFilter, []string{}}, \/\/ Whitelist service that isn't present\n\t\t{1, 1, 1, 2, multiServiceFilter, []string{\"0\", \"1\"}}, \/\/ Whitelist both this service and \"other\" service\n\n\t}\n\n\tfor caseNum, testCase := range caseTable {\n\t\ttotalMessages = testCase.serviceMessages + testCase.nonServiceMessages + testCase.otherServiceMessages\n\t\tgeneratedMessages = 0\n\t\tsourceEntries = make([]*alog.Entry, totalMessages)\n\n\t\t\/\/ Generate service messages\n\t\tctx = NewApexLogServiceContext()\n\t\tsimulateEntries(ctx, testCase.serviceMessages, &generatedMessages, &sourceEntries)\n\t\t\/\/ Generate other service messages\n\t\tctx = ctx.WithFields(alog.Fields{\"service\": \"other\"})\n\t\tsimulateEntries(ctx, testCase.otherServiceMessages, &generatedMessages, &sourceEntries)\n\n\t\t\/\/ Generate non-service messages\n\t\tctx = alog.Log\n\t\tsimulateEntries(ctx, testCase.nonServiceMessages, &generatedMessages, &sourceEntries)\n\n\t\tentries, err = simulateMessagesFromNSQ(&sourceEntries, testCase.filter)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Error in message simulation: %s\", err.Error())\n\t\t}\n\t\tif entries == nil && testCase.resultEntryCount > 0 {\n\t\t\tt.Errorf(\"Expected %d entries from test case %d but got nil. Message counts: service %d, other-service %d, non-service %d. Filter: %+v.\", testCase.resultEntryCount, caseNum, testCase.serviceMessages, testCase.otherServiceMessages, testCase.nonServiceMessages, testCase.filter)\n\t\t\tcontinue\n\t\t}\n\t\tresultEntryCount = len(*entries)\n\t\tif resultEntryCount != testCase.resultEntryCount {\n\t\t\tt.Errorf(\"[Case %d] Expected %d entries, but got %d. Message counts: service %d, other-service %d, non-service %d. Filter: %+v.\", caseNum+1, testCase.resultEntryCount, resultEntryCount, testCase.serviceMessages, testCase.otherServiceMessages, testCase.nonServiceMessages, testCase.filter)\n\t\t\tcontinue\n\t\t}\n\n\t\tfor idx, entry := range *entries {\n\t\t\ttestMessage := testCase.messages[idx]\n\t\t\tif entry.Message != testMessage {\n\t\t\t\tt.Errorf(\"[Case %d] Expected Entry[%d] to have message %q, but got %q\", caseNum, idx, testMessage, entry.Message)\n\t\t\t}\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"package container\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n\n\t\"github.com\/zenoss\/glog\"\n\t\"github.com\/zenoss\/serviced\/node\"\n\t\"github.com\/zenoss\/serviced\/validation\"\n)\n\nconst defaultSubnet string = \"10.3\" \/\/ \/16 subnet for virtual addresses\n\ntype vif struct {\n\tname string\n\tip string\n\thostname string\n\ttcpPorts map[string]string\n\tudpPorts map[string]string\n}\n\n\/\/ VIFRegistry holds state regarding virtual interfaces. It is meant to be\n\/\/ created in the proxy to manage vifs in the running service container.\ntype VIFRegistry struct {\n\tsubnet string\n\tvifs map[string]*vif\n}\n\n\/\/ NewVIFRegistry initializes a new VIFRegistry.\nfunc NewVIFRegistry() *VIFRegistry {\n\treturn &VIFRegistry{subnet: defaultSubnet, vifs: make(map[string]*vif)}\n}\n\n\/\/ SetSubnet sets the subnet used for virtual addresses\nfunc (reg *VIFRegistry) SetSubnet(subnet string) error {\n\tif err := validation.IsSubnet16(subnet); err != nil {\n\t\treturn err\n\t}\n\treg.subnet = subnet\n\tglog.Infof(\"vif subnet is: %s\", reg.subnet)\n\treturn nil\n}\n\nfunc (reg *VIFRegistry) nextIP() (string, error) {\n\tn := len(reg.vifs) + 2\n\tif n > (255 * 255) {\n\t\treturn \"\", fmt.Errorf(\"unable to allocate IPs for %d interfaces\", n)\n\t}\n\to3 := (n \/ 255)\n\to4 := (n - (o3 * 255))\n\t\/\/ ZEN-11478: made the subnet configurable\n\treturn fmt.Sprintf(\"%s.%d.%d\", reg.subnet, o3, o4), nil\n}\n\n\/\/ RegisterVirtualAddress takes care of the entire virtual address setup. It\n\/\/ creates a virtual interface if one does not yet exist, allocates an IP\n\/\/ address, assigns it to the virtual interface, adds an entry to \/etc\/hosts,\n\/\/ and sets up the iptables rule to redirect traffic to the specified port.\nfunc (reg *VIFRegistry) RegisterVirtualAddress(address, toport, protocol string) error {\n\tglog.Infof(\"RegisterVirtualAddress address:%s toport:%s protocol:%s\", address, toport, protocol)\n\tvar (\n\t\thost, port string\n\t\tviface *vif\n\t\terr error\n\t\tok bool\n\t\tportmap *map[string]string\n\t)\n\tif host, port, err = net.SplitHostPort(address); err != nil {\n\t\treturn err\n\t}\n\tif viface, ok = reg.vifs[host]; !ok {\n\t\t\/\/ vif doesn't exist yet\n\t\tip, err := reg.nextIP()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tviface = &vif{\n\t\t\thostname: host,\n\t\t\tip: ip,\n\t\t\tname: \"eth0:\" + host,\n\t\t\ttcpPorts: make(map[string]string),\n\t\t\tudpPorts: make(map[string]string),\n\t\t}\n\t\tif err = viface.createCommand(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treg.vifs[host] = viface\n\t}\n\tswitch strings.ToLower(protocol) {\n\tcase \"tcp\":\n\t\tportmap = &viface.tcpPorts\n\tcase \"udp\":\n\t\tportmap = &viface.udpPorts\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid protocol: %s\", protocol)\n\t}\n\n\tglog.Infof(\"portmap: %+v\", *portmap)\n\tif _, ok := (*portmap)[toport]; !ok {\n\t\t\/\/ dest isn't there, let's DO IT!!!!!\n\t\tif err := viface.redirectCommand(port, toport, protocol); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t(*portmap)[toport] = port\n\t}\n\treturn nil\n}\n\nfunc (viface *vif) createCommand() error {\n\tcommand := []string{\n\t\t\"ip\", \"link\", \"add\", \"link\", \"eth0\",\n\t\t\"name\", viface.name,\n\t\t\"type\", \"veth\",\n\t\t\"peer\", \"name\", viface.name + \"-peer\",\n\t}\n\tc := exec.Command(command[0], command[1:]...)\n\tc.Stdout = os.Stdout\n\tc.Stderr = os.Stdout\n\n\tif err := c.Run(); err != nil {\n\t\tglog.Errorf(\"Adding virtual interface failed: %+v\", err)\n\t\treturn err\n\t}\n\tcommand = []string{\n\t\t\"ip\", \"addr\", \"add\", viface.ip + \"\/16\", \"dev\", viface.name,\n\t}\n\tc = exec.Command(command[0], command[1:]...)\n\tc.Stdout = os.Stdout\n\tc.Stderr = os.Stdout\n\tif err := c.Run(); err != nil {\n\t\tglog.Errorf(\"Adding IP to virtual interface failed: %+v\", err)\n\t\treturn err\n\t}\n\tcommand = []string{\n\t\t\"ip\", \"link\", \"set\", viface.name, \"up\",\n\t}\n\tc = exec.Command(command[0], command[1:]...)\n\tc.Stdout = os.Stdout\n\tc.Stderr = os.Stdout\n\tif err := c.Run(); err != nil {\n\t\tglog.Errorf(\"Bringing interface %s up failed: %+v\", viface.name, err)\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (viface *vif) redirectCommand(from, to, protocol string) error {\n\tfor _, chain := range []string{\"OUTPUT\", \"PREROUTING\"} {\n\t\tcommand := []string{\n\t\t\t\"iptables\",\n\t\t\t\"-t\", \"nat\",\n\t\t\t\"-A\", chain,\n\t\t\t\"-d\", viface.ip,\n\t\t\t\"-p\", protocol,\n\t\t\t\"--dport\", from,\n\t\t\t\"-j\", \"REDIRECT\",\n\t\t\t\"--to-ports\", to,\n\t\t}\n\t\tc := exec.Command(command[0], command[1:]...)\n\n\t\tc.Stdout = os.Stdout\n\t\tc.Stderr = os.Stdout\n\t\tif err := c.Run(); err != nil {\n\t\t\tglog.Errorf(\"Unable to set up redirect %s:%s->:%s\", viface.hostname, from, to)\n\t\t\treturn err\n\t\t}\n\t}\n\n\tglog.Infof(\"AddToEtcHosts(%s, %s)\", viface.hostname, viface.ip)\n\terr := node.AddToEtcHosts(viface.hostname, viface.ip)\n\tif err != nil {\n\t\tglog.Errorf(\"Unable to add %s to \/etc\/hosts\", viface.hostname)\n\t\treturn err\n\t}\n\treturn nil\n}\nlock when calling vif.RegisterVirtualAddress()package container\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com\/zenoss\/glog\"\n\t\"github.com\/zenoss\/serviced\/node\"\n\t\"github.com\/zenoss\/serviced\/validation\"\n)\n\nconst defaultSubnet string = \"10.3\" \/\/ \/16 subnet for virtual addresses\n\ntype vif struct {\n\tname string\n\tip string\n\thostname string\n\ttcpPorts map[string]string\n\tudpPorts map[string]string\n}\n\n\/\/ VIFRegistry holds state regarding virtual interfaces. It is meant to be\n\/\/ created in the proxy to manage vifs in the running service container.\ntype VIFRegistry struct {\n\tsync.RWMutex\n\tsubnet string\n\tvifs map[string]*vif\n}\n\n\/\/ NewVIFRegistry initializes a new VIFRegistry.\nfunc NewVIFRegistry() *VIFRegistry {\n\treturn &VIFRegistry{subnet: defaultSubnet, vifs: make(map[string]*vif)}\n}\n\n\/\/ SetSubnet sets the subnet used for virtual addresses\nfunc (reg *VIFRegistry) SetSubnet(subnet string) error {\n\tif err := validation.IsSubnet16(subnet); err != nil {\n\t\treturn err\n\t}\n\treg.subnet = subnet\n\tglog.Infof(\"vif subnet is: %s\", reg.subnet)\n\treturn nil\n}\n\nfunc (reg *VIFRegistry) nextIP() (string, error) {\n\tn := len(reg.vifs) + 2\n\tif n > (255 * 255) {\n\t\treturn \"\", fmt.Errorf(\"unable to allocate IPs for %d interfaces\", n)\n\t}\n\to3 := (n \/ 255)\n\to4 := (n - (o3 * 255))\n\t\/\/ ZEN-11478: made the subnet configurable\n\treturn fmt.Sprintf(\"%s.%d.%d\", reg.subnet, o3, o4), nil\n}\n\n\/\/ RegisterVirtualAddress takes care of the entire virtual address setup. It\n\/\/ creates a virtual interface if one does not yet exist, allocates an IP\n\/\/ address, assigns it to the virtual interface, adds an entry to \/etc\/hosts,\n\/\/ and sets up the iptables rule to redirect traffic to the specified port.\nfunc (reg *VIFRegistry) RegisterVirtualAddress(address, toport, protocol string) error {\n\tglog.Infof(\"RegisterVirtualAddress address:%s toport:%s protocol:%s locking...\", address, toport, protocol)\n\treg.Lock()\n\tdefer reg.Unlock()\n\tglog.Infof(\"RegisterVirtualAddress address:%s toport:%s protocol:%s locked\", address, toport, protocol)\n\n\tvar (\n\t\thost, port string\n\t\tviface *vif\n\t\terr error\n\t\tok bool\n\t\tportmap *map[string]string\n\t)\n\tif host, port, err = net.SplitHostPort(address); err != nil {\n\t\treturn err\n\t}\n\tif viface, ok = reg.vifs[host]; !ok {\n\t\t\/\/ vif doesn't exist yet\n\t\tip, err := reg.nextIP()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tviface = &vif{\n\t\t\thostname: host,\n\t\t\tip: ip,\n\t\t\tname: \"eth0:\" + host,\n\t\t\ttcpPorts: make(map[string]string),\n\t\t\tudpPorts: make(map[string]string),\n\t\t}\n\t\tif err = viface.createCommand(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\treg.vifs[host] = viface\n\t}\n\tswitch strings.ToLower(protocol) {\n\tcase \"tcp\":\n\t\tportmap = &viface.tcpPorts\n\tcase \"udp\":\n\t\tportmap = &viface.udpPorts\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid protocol: %s\", protocol)\n\t}\n\n\tglog.Infof(\"RegisterVirtualAddress portmap: %+v\", *portmap)\n\tif _, ok := (*portmap)[toport]; !ok {\n\t\t\/\/ dest isn't there, let's DO IT!!!!!\n\t\tif err := viface.redirectCommand(port, toport, protocol); err != nil {\n\t\t\treturn err\n\t\t}\n\t\t(*portmap)[toport] = port\n\t}\n\treturn nil\n}\n\nfunc (viface *vif) createCommand() error {\n\tcommand := []string{\n\t\t\"ip\", \"link\", \"add\", \"link\", \"eth0\",\n\t\t\"name\", viface.name,\n\t\t\"type\", \"veth\",\n\t\t\"peer\", \"name\", viface.name + \"-peer\",\n\t}\n\tc := exec.Command(command[0], command[1:]...)\n\tc.Stdout = os.Stdout\n\tc.Stderr = os.Stdout\n\n\tif err := c.Run(); err != nil {\n\t\tglog.Errorf(\"Adding virtual interface failed: %+v\", err)\n\t\treturn err\n\t}\n\tcommand = []string{\n\t\t\"ip\", \"addr\", \"add\", viface.ip + \"\/16\", \"dev\", viface.name,\n\t}\n\tc = exec.Command(command[0], command[1:]...)\n\tc.Stdout = os.Stdout\n\tc.Stderr = os.Stdout\n\tif err := c.Run(); err != nil {\n\t\tglog.Errorf(\"Adding IP to virtual interface failed: %+v\", err)\n\t\treturn err\n\t}\n\tcommand = []string{\n\t\t\"ip\", \"link\", \"set\", viface.name, \"up\",\n\t}\n\tc = exec.Command(command[0], command[1:]...)\n\tc.Stdout = os.Stdout\n\tc.Stderr = os.Stdout\n\tif err := c.Run(); err != nil {\n\t\tglog.Errorf(\"Bringing interface %s up failed: %+v\", viface.name, err)\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (viface *vif) redirectCommand(from, to, protocol string) error {\n\tglog.Infof(\"Trying to set up redirect %s:%s->:%s %s\", viface.hostname, from, to, protocol)\n\tfor _, chain := range []string{\"OUTPUT\", \"PREROUTING\"} {\n\t\tcommand := []string{\n\t\t\t\"iptables\",\n\t\t\t\"-t\", \"nat\",\n\t\t\t\"-A\", chain,\n\t\t\t\"-d\", viface.ip,\n\t\t\t\"-p\", protocol,\n\t\t\t\"--dport\", from,\n\t\t\t\"-j\", \"REDIRECT\",\n\t\t\t\"--to-ports\", to,\n\t\t}\n\t\tc := exec.Command(command[0], command[1:]...)\n\n\t\tc.Stdout = os.Stdout\n\t\tc.Stderr = os.Stdout\n\t\tif err := c.Run(); err != nil {\n\t\t\tglog.Errorf(\"Unable to set up redirect %s:%s->:%s %s command:%+v\", viface.hostname, from, to, protocol, command)\n\t\t\treturn err\n\t\t}\n\t}\n\n\tglog.Infof(\"AddToEtcHosts(%s, %s)\", viface.hostname, viface.ip)\n\terr := node.AddToEtcHosts(viface.hostname, viface.ip)\n\tif err != nil {\n\t\tglog.Errorf(\"Unable to add %s %s to \/etc\/hosts\", viface.ip, viface.hostname)\n\t\treturn err\n\t}\n\treturn nil\n}\n<|endoftext|>"} {"text":"package lazycache\n\/\/ A generic cache that favors returning stale data\n\/\/ than blocking a caller\n\nimport (\n \"sync\"\n \"time\"\n)\n\ntype Fetcher func(id string) (interface{}, error)\n\ntype Item struct {\n object interface{}\n expires time.Time\n}\n\ntype LazyCache struct {\n fetcher Fetcher\n ttl time.Duration\n lock sync.RWMutex\n items map[string]*Item\n}\n\nfunc New(fetcher Fetcher, ttl time.Duration, size int) *LazyCache {\n return &LazyCache{\n ttl: ttl,\n fetcher: fetcher,\n items: make(map[string]*Item, size),\n }\n}\n\nfunc (cache *LazyCache) Get(id string) (interface{}, bool) {\n cache.lock.RLock()\n item, exists := cache.items[id]\n cache.lock.RUnlock()\n if exists == false {\n return cache.Fetch(id, item)\n }\n if time.Now().After(item.expires) {\n if item.object == nil {\n return cache.Fetch(id, item)\n } else {\n go cache.Fetch(id, item)\n }\n }\n return item.object, true\n}\n\nfunc (cache *LazyCache) Set(id string, object interface{}) {\n cache.lock.Lock()\n defer cache.lock.Unlock()\n cache.items[id] = &Item{expires: time.Now().Add(cache.ttl), object: object}\n}\n\nfunc (cache *LazyCache) Fetch(id string, current *Item) (interface{}, bool) {\n object, err := cache.fetcher(id)\n if err != nil { return nil, false }\n \n if current == nil {\n if object == nil { return nil, false }\n cache.Set(id, object)\n return object, true\n }\n\n cache.lock.Lock()\n defer cache.lock.Unlock()\n if object == nil {\n delete(cache.items, id)\n } else {\n current.expires = time.Now().Add(cache.ttl)\n current.object = object\n }\n return object, object != nil\n}\nshoul set missespackage lazycache\n\/\/ A generic cache that favors returning stale data\n\/\/ than blocking a caller\n\nimport (\n \"sync\"\n \"time\"\n)\n\ntype Fetcher func(id string) (interface{}, error)\n\ntype Item struct {\n object interface{}\n expires time.Time\n}\n\ntype LazyCache struct {\n fetcher Fetcher\n ttl time.Duration\n lock sync.RWMutex\n items map[string]*Item\n}\n\nfunc New(fetcher Fetcher, ttl time.Duration, size int) *LazyCache {\n return &LazyCache{\n ttl: ttl,\n fetcher: fetcher,\n items: make(map[string]*Item, size),\n }\n}\n\nfunc (cache *LazyCache) Get(id string) (interface{}, bool) {\n cache.lock.RLock()\n item, exists := cache.items[id]\n cache.lock.RUnlock()\n if exists == false {\n return cache.Fetch(id, item)\n }\n if time.Now().After(item.expires) {\n if item.object == nil {\n return cache.Fetch(id, item)\n } else {\n go cache.Fetch(id, item)\n }\n }\n return item.object, true\n}\n\nfunc (cache *LazyCache) Set(id string, object interface{}) {\n cache.lock.Lock()\n defer cache.lock.Unlock()\n cache.items[id] = &Item{expires: time.Now().Add(cache.ttl), object: object}\n}\n\nfunc (cache *LazyCache) Fetch(id string, current *Item) (interface{}, bool) {\n object, err := cache.fetcher(id)\n if err != nil { return nil, false }\n \n if current == nil {\n cache.Set(id, object)\n return object, object != nil\n }\n\n cache.lock.Lock()\n defer cache.lock.Unlock()\n if object == nil {\n delete(cache.items, id)\n } else {\n current.expires = time.Now().Add(cache.ttl)\n current.object = object\n }\n return object, object != 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 os\n\nimport (\n\t\"io\"\n\t\"runtime\"\n\t\"sync\"\n\t\"syscall\"\n\t\"unicode\/utf16\"\n)\n\n\/\/ File represents an open file descriptor.\ntype File struct {\n\t*file\n}\n\n\/\/ file is the real representation of *File.\n\/\/ The extra level of indirection ensures that no clients of os\n\/\/ can overwrite this data, which could cause the finalizer\n\/\/ to close the wrong file descriptor.\ntype file struct {\n\tfd syscall.Handle\n\tname string\n\tdirinfo *dirInfo \/\/ nil unless directory being read\n\tnepipe int \/\/ number of consecutive EPIPE in Write\n\tl sync.Mutex \/\/ used to implement windows pread\/pwrite\n}\n\n\/\/ Fd returns the Windows handle referencing the open file.\nfunc (file *File) Fd() syscall.Handle {\n\tif file == nil {\n\t\treturn syscall.InvalidHandle\n\t}\n\treturn file.fd\n}\n\n\/\/ NewFile returns a new File with the given file descriptor and name.\nfunc NewFile(fd syscall.Handle, name string) *File {\n\tif fd < 0 {\n\t\treturn nil\n\t}\n\tf := &File{&file{fd: fd, name: name}}\n\truntime.SetFinalizer(f.file, (*file).close)\n\treturn f\n}\n\n\/\/ Auxiliary information if the File describes a directory\ntype dirInfo struct {\n\tdata syscall.Win32finddata\n\tneeddata bool\n}\n\nconst DevNull = \"NUL\"\n\nfunc (file *File) isdir() bool { return file != nil && file.dirinfo != nil }\n\nfunc openFile(name string, flag int, perm uint32) (file *File, err error) {\n\tr, e := syscall.Open(name, flag|syscall.O_CLOEXEC, perm)\n\tif e != nil {\n\t\treturn nil, &PathError{\"open\", name, e}\n\t}\n\n\t\/\/ There's a race here with fork\/exec, which we are\n\t\/\/ content to live with. See ..\/syscall\/exec.go\n\tif syscall.O_CLOEXEC == 0 { \/\/ O_CLOEXEC not supported\n\t\tsyscall.CloseOnExec(r)\n\t}\n\n\treturn NewFile(r, name), nil\n}\n\nfunc openDir(name string) (file *File, err error) {\n\td := new(dirInfo)\n\tr, e := syscall.FindFirstFile(syscall.StringToUTF16Ptr(name+`\\*`), &d.data)\n\tif e != nil {\n\t\treturn nil, &PathError{\"open\", name, e}\n\t}\n\tf := NewFile(r, name)\n\tf.dirinfo = d\n\treturn f, nil\n}\n\n\/\/ OpenFile is the generalized open call; most users will use Open\n\/\/ or Create instead. It opens the named file with specified flag\n\/\/ (O_RDONLY etc.) and perm, (0666 etc.) if applicable. If successful,\n\/\/ methods on the returned File can be used for I\/O.\n\/\/ It returns the File and an error, if any.\nfunc OpenFile(name string, flag int, perm uint32) (file *File, err error) {\n\t\/\/ TODO(brainman): not sure about my logic of assuming it is dir first, then fall back to file\n\tr, e := openDir(name)\n\tif e == nil {\n\t\tif flag&O_WRONLY != 0 || flag&O_RDWR != 0 {\n\t\t\tr.Close()\n\t\t\treturn nil, &PathError{\"open\", name, EISDIR}\n\t\t}\n\t\treturn r, nil\n\t}\n\tr, e = openFile(name, flag, perm)\n\tif e == nil {\n\t\treturn r, nil\n\t}\n\treturn nil, e\n}\n\n\/\/ Close closes the File, rendering it unusable for I\/O.\n\/\/ It returns an error, if any.\nfunc (file *File) Close() error {\n\treturn file.file.close()\n}\n\nfunc (file *file) close() error {\n\tif file == nil || file.fd < 0 {\n\t\treturn EINVAL\n\t}\n\tvar e error\n\tif file.isdir() {\n\t\te = syscall.FindClose(syscall.Handle(file.fd))\n\t} else {\n\t\te = syscall.CloseHandle(syscall.Handle(file.fd))\n\t}\n\tvar err error\n\tif e != nil {\n\t\terr = &PathError{\"close\", file.name, e}\n\t}\n\tfile.fd = syscall.InvalidHandle \/\/ so it can't be closed again\n\n\t\/\/ no need for a finalizer anymore\n\truntime.SetFinalizer(file, nil)\n\treturn err\n}\n\n\/\/ Readdir reads the contents of the directory associated with file and\n\/\/ returns an array of up to n FileInfo structures, as would be returned\n\/\/ by Lstat, in directory order. Subsequent calls on the same file will yield\n\/\/ further FileInfos.\n\/\/\n\/\/ If n > 0, Readdir returns at most n FileInfo structures. In this case, if\n\/\/ Readdir returns an empty slice, it will return a non-nil error\n\/\/ explaining why. At the end of a directory, the error is io.EOF.\n\/\/\n\/\/ If n <= 0, Readdir returns all the FileInfo from the directory in\n\/\/ a single slice. In this case, if Readdir succeeds (reads all\n\/\/ the way to the end of the directory), it returns the slice and a\n\/\/ nil error. If it encounters an error before the end of the\n\/\/ directory, Readdir returns the FileInfo read until that point\n\/\/ and a non-nil error.\nfunc (file *File) Readdir(n int) (fi []FileInfo, err error) {\n\tif file == nil || file.fd < 0 {\n\t\treturn nil, EINVAL\n\t}\n\tif !file.isdir() {\n\t\treturn nil, &PathError{\"Readdir\", file.name, ENOTDIR}\n\t}\n\twantAll := n <= 0\n\tsize := n\n\tif wantAll {\n\t\tn = -1\n\t\tsize = 100\n\t}\n\tfi = make([]FileInfo, 0, size) \/\/ Empty with room to grow.\n\td := &file.dirinfo.data\n\tfor n != 0 {\n\t\tif file.dirinfo.needdata {\n\t\t\te := syscall.FindNextFile(syscall.Handle(file.fd), d)\n\t\t\tif e != nil {\n\t\t\t\tif e == syscall.ERROR_NO_MORE_FILES {\n\t\t\t\t\tbreak\n\t\t\t\t} else {\n\t\t\t\t\terr = &PathError{\"FindNextFile\", file.name, e}\n\t\t\t\t\tif !wantAll {\n\t\t\t\t\t\tfi = nil\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tvar f FileInfo\n\t\tsetFileInfo(&f, string(syscall.UTF16ToString(d.FileName[0:])), d.FileAttributes, d.FileSizeHigh, d.FileSizeLow, d.CreationTime, d.LastAccessTime, d.LastWriteTime)\n\t\tfile.dirinfo.needdata = true\n\t\tif f.Name == \".\" || f.Name == \"..\" { \/\/ Useless names\n\t\t\tcontinue\n\t\t}\n\t\tn--\n\t\tfi = append(fi, f)\n\t}\n\tif !wantAll && len(fi) == 0 {\n\t\treturn fi, io.EOF\n\t}\n\treturn fi, nil\n}\n\n\/\/ read reads up to len(b) bytes from the File.\n\/\/ It returns the number of bytes read and an error, if any.\nfunc (f *File) read(b []byte) (n int, err error) {\n\tf.l.Lock()\n\tdefer f.l.Unlock()\n\treturn syscall.Read(f.fd, b)\n}\n\n\/\/ pread reads len(b) bytes from the File starting at byte offset off.\n\/\/ It returns the number of bytes read and the error, if any.\n\/\/ EOF is signaled by a zero count with err set to 0.\nfunc (f *File) pread(b []byte, off int64) (n int, err error) {\n\tf.l.Lock()\n\tdefer f.l.Unlock()\n\tcuroffset, e := syscall.Seek(f.fd, 0, 1)\n\tif e != nil {\n\t\treturn 0, e\n\t}\n\tdefer syscall.Seek(f.fd, curoffset, 0)\n\to := syscall.Overlapped{\n\t\tOffsetHigh: uint32(off >> 32),\n\t\tOffset: uint32(off),\n\t}\n\tvar done uint32\n\te = syscall.ReadFile(syscall.Handle(f.fd), b, &done, &o)\n\tif e != nil {\n\t\treturn 0, e\n\t}\n\treturn int(done), nil\n}\n\n\/\/ write writes len(b) bytes to the File.\n\/\/ It returns the number of bytes written and an error, if any.\nfunc (f *File) write(b []byte) (n int, err error) {\n\tf.l.Lock()\n\tdefer f.l.Unlock()\n\treturn syscall.Write(f.fd, b)\n}\n\n\/\/ pwrite writes len(b) bytes to the File starting at byte offset off.\n\/\/ It returns the number of bytes written and an error, if any.\nfunc (f *File) pwrite(b []byte, off int64) (n int, err error) {\n\tf.l.Lock()\n\tdefer f.l.Unlock()\n\tcuroffset, e := syscall.Seek(f.fd, 0, 1)\n\tif e != nil {\n\t\treturn 0, e\n\t}\n\tdefer syscall.Seek(f.fd, curoffset, 0)\n\to := syscall.Overlapped{\n\t\tOffsetHigh: uint32(off >> 32),\n\t\tOffset: uint32(off),\n\t}\n\tvar done uint32\n\te = syscall.WriteFile(syscall.Handle(f.fd), b, &done, &o)\n\tif e != nil {\n\t\treturn 0, e\n\t}\n\treturn int(done), nil\n}\n\n\/\/ seek sets the offset for the next Read or Write on file to offset, interpreted\n\/\/ according to whence: 0 means relative to the origin of the file, 1 means\n\/\/ relative to the current offset, and 2 means relative to the end.\n\/\/ It returns the new offset and an error, if any.\nfunc (f *File) seek(offset int64, whence int) (ret int64, err error) {\n\tf.l.Lock()\n\tdefer f.l.Unlock()\n\treturn syscall.Seek(f.fd, offset, whence)\n}\n\n\/\/ Truncate changes the size of the named file.\n\/\/ If the file is a symbolic link, it changes the size of the link's target.\nfunc Truncate(name string, size int64) error {\n\tf, e := OpenFile(name, O_WRONLY|O_CREATE, 0666)\n\tif e != nil {\n\t\treturn e\n\t}\n\tdefer f.Close()\n\te1 := f.Truncate(size)\n\tif e1 != nil {\n\t\treturn e1\n\t}\n\treturn nil\n}\n\n\/\/ Pipe returns a connected pair of Files; reads from r return bytes written to w.\n\/\/ It returns the files and an error, if any.\nfunc Pipe() (r *File, w *File, err error) {\n\tvar p [2]syscall.Handle\n\n\t\/\/ See ..\/syscall\/exec.go for description of lock.\n\tsyscall.ForkLock.RLock()\n\te := syscall.Pipe(p[0:])\n\tif e != nil {\n\t\tsyscall.ForkLock.RUnlock()\n\t\treturn nil, nil, NewSyscallError(\"pipe\", e)\n\t}\n\tsyscall.CloseOnExec(p[0])\n\tsyscall.CloseOnExec(p[1])\n\tsyscall.ForkLock.RUnlock()\n\n\treturn NewFile(p[0], \"|0\"), NewFile(p[1], \"|1\"), nil\n}\n\n\/\/ TempDir returns the default directory to use for temporary files.\nfunc TempDir() string {\n\tconst pathSep = '\\\\'\n\tdirw := make([]uint16, syscall.MAX_PATH)\n\tn, _ := syscall.GetTempPath(uint32(len(dirw)), &dirw[0])\n\tif n > uint32(len(dirw)) {\n\t\tdirw = make([]uint16, n)\n\t\tn, _ = syscall.GetTempPath(uint32(len(dirw)), &dirw[0])\n\t\tif n > uint32(len(dirw)) {\n\t\t\tn = 0\n\t\t}\n\t}\n\tif n > 0 && dirw[n-1] == pathSep {\n\t\tn--\n\t}\n\treturn string(utf16.Decode(dirw[0:n]))\n}\nos: fix windows build\/\/ 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 os\n\nimport (\n\t\"io\"\n\t\"runtime\"\n\t\"sync\"\n\t\"syscall\"\n\t\"unicode\/utf16\"\n)\n\n\/\/ File represents an open file descriptor.\ntype File struct {\n\t*file\n}\n\n\/\/ file is the real representation of *File.\n\/\/ The extra level of indirection ensures that no clients of os\n\/\/ can overwrite this data, which could cause the finalizer\n\/\/ to close the wrong file descriptor.\ntype file struct {\n\tfd syscall.Handle\n\tname string\n\tdirinfo *dirInfo \/\/ nil unless directory being read\n\tnepipe int \/\/ number of consecutive EPIPE in Write\n\tl sync.Mutex \/\/ used to implement windows pread\/pwrite\n}\n\n\/\/ Fd returns the Windows handle referencing the open file.\nfunc (file *File) Fd() syscall.Handle {\n\tif file == nil {\n\t\treturn syscall.InvalidHandle\n\t}\n\treturn file.fd\n}\n\n\/\/ NewFile returns a new File with the given file descriptor and name.\nfunc NewFile(fd syscall.Handle, name string) *File {\n\tif fd < 0 {\n\t\treturn nil\n\t}\n\tf := &File{&file{fd: fd, name: name}}\n\truntime.SetFinalizer(f.file, (*file).close)\n\treturn f\n}\n\n\/\/ Auxiliary information if the File describes a directory\ntype dirInfo struct {\n\tdata syscall.Win32finddata\n\tneeddata bool\n}\n\nconst DevNull = \"NUL\"\n\nfunc (file *file) isdir() bool { return file != nil && file.dirinfo != nil }\n\nfunc openFile(name string, flag int, perm uint32) (file *File, err error) {\n\tr, e := syscall.Open(name, flag|syscall.O_CLOEXEC, perm)\n\tif e != nil {\n\t\treturn nil, &PathError{\"open\", name, e}\n\t}\n\n\t\/\/ There's a race here with fork\/exec, which we are\n\t\/\/ content to live with. See ..\/syscall\/exec.go\n\tif syscall.O_CLOEXEC == 0 { \/\/ O_CLOEXEC not supported\n\t\tsyscall.CloseOnExec(r)\n\t}\n\n\treturn NewFile(r, name), nil\n}\n\nfunc openDir(name string) (file *File, err error) {\n\td := new(dirInfo)\n\tr, e := syscall.FindFirstFile(syscall.StringToUTF16Ptr(name+`\\*`), &d.data)\n\tif e != nil {\n\t\treturn nil, &PathError{\"open\", name, e}\n\t}\n\tf := NewFile(r, name)\n\tf.dirinfo = d\n\treturn f, nil\n}\n\n\/\/ OpenFile is the generalized open call; most users will use Open\n\/\/ or Create instead. It opens the named file with specified flag\n\/\/ (O_RDONLY etc.) and perm, (0666 etc.) if applicable. If successful,\n\/\/ methods on the returned File can be used for I\/O.\n\/\/ It returns the File and an error, if any.\nfunc OpenFile(name string, flag int, perm uint32) (file *File, err error) {\n\t\/\/ TODO(brainman): not sure about my logic of assuming it is dir first, then fall back to file\n\tr, e := openDir(name)\n\tif e == nil {\n\t\tif flag&O_WRONLY != 0 || flag&O_RDWR != 0 {\n\t\t\tr.Close()\n\t\t\treturn nil, &PathError{\"open\", name, EISDIR}\n\t\t}\n\t\treturn r, nil\n\t}\n\tr, e = openFile(name, flag, perm)\n\tif e == nil {\n\t\treturn r, nil\n\t}\n\treturn nil, e\n}\n\n\/\/ Close closes the File, rendering it unusable for I\/O.\n\/\/ It returns an error, if any.\nfunc (file *File) Close() error {\n\treturn file.file.close()\n}\n\nfunc (file *file) close() error {\n\tif file == nil || file.fd < 0 {\n\t\treturn EINVAL\n\t}\n\tvar e error\n\tif file.isdir() {\n\t\te = syscall.FindClose(syscall.Handle(file.fd))\n\t} else {\n\t\te = syscall.CloseHandle(syscall.Handle(file.fd))\n\t}\n\tvar err error\n\tif e != nil {\n\t\terr = &PathError{\"close\", file.name, e}\n\t}\n\tfile.fd = syscall.InvalidHandle \/\/ so it can't be closed again\n\n\t\/\/ no need for a finalizer anymore\n\truntime.SetFinalizer(file, nil)\n\treturn err\n}\n\n\/\/ Readdir reads the contents of the directory associated with file and\n\/\/ returns an array of up to n FileInfo structures, as would be returned\n\/\/ by Lstat, in directory order. Subsequent calls on the same file will yield\n\/\/ further FileInfos.\n\/\/\n\/\/ If n > 0, Readdir returns at most n FileInfo structures. In this case, if\n\/\/ Readdir returns an empty slice, it will return a non-nil error\n\/\/ explaining why. At the end of a directory, the error is io.EOF.\n\/\/\n\/\/ If n <= 0, Readdir returns all the FileInfo from the directory in\n\/\/ a single slice. In this case, if Readdir succeeds (reads all\n\/\/ the way to the end of the directory), it returns the slice and a\n\/\/ nil error. If it encounters an error before the end of the\n\/\/ directory, Readdir returns the FileInfo read until that point\n\/\/ and a non-nil error.\nfunc (file *File) Readdir(n int) (fi []FileInfo, err error) {\n\tif file == nil || file.fd < 0 {\n\t\treturn nil, EINVAL\n\t}\n\tif !file.isdir() {\n\t\treturn nil, &PathError{\"Readdir\", file.name, ENOTDIR}\n\t}\n\twantAll := n <= 0\n\tsize := n\n\tif wantAll {\n\t\tn = -1\n\t\tsize = 100\n\t}\n\tfi = make([]FileInfo, 0, size) \/\/ Empty with room to grow.\n\td := &file.dirinfo.data\n\tfor n != 0 {\n\t\tif file.dirinfo.needdata {\n\t\t\te := syscall.FindNextFile(syscall.Handle(file.fd), d)\n\t\t\tif e != nil {\n\t\t\t\tif e == syscall.ERROR_NO_MORE_FILES {\n\t\t\t\t\tbreak\n\t\t\t\t} else {\n\t\t\t\t\terr = &PathError{\"FindNextFile\", file.name, e}\n\t\t\t\t\tif !wantAll {\n\t\t\t\t\t\tfi = nil\n\t\t\t\t\t}\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tvar f FileInfo\n\t\tsetFileInfo(&f, string(syscall.UTF16ToString(d.FileName[0:])), d.FileAttributes, d.FileSizeHigh, d.FileSizeLow, d.CreationTime, d.LastAccessTime, d.LastWriteTime)\n\t\tfile.dirinfo.needdata = true\n\t\tif f.Name == \".\" || f.Name == \"..\" { \/\/ Useless names\n\t\t\tcontinue\n\t\t}\n\t\tn--\n\t\tfi = append(fi, f)\n\t}\n\tif !wantAll && len(fi) == 0 {\n\t\treturn fi, io.EOF\n\t}\n\treturn fi, nil\n}\n\n\/\/ read reads up to len(b) bytes from the File.\n\/\/ It returns the number of bytes read and an error, if any.\nfunc (f *File) read(b []byte) (n int, err error) {\n\tf.l.Lock()\n\tdefer f.l.Unlock()\n\treturn syscall.Read(f.fd, b)\n}\n\n\/\/ pread reads len(b) bytes from the File starting at byte offset off.\n\/\/ It returns the number of bytes read and the error, if any.\n\/\/ EOF is signaled by a zero count with err set to 0.\nfunc (f *File) pread(b []byte, off int64) (n int, err error) {\n\tf.l.Lock()\n\tdefer f.l.Unlock()\n\tcuroffset, e := syscall.Seek(f.fd, 0, 1)\n\tif e != nil {\n\t\treturn 0, e\n\t}\n\tdefer syscall.Seek(f.fd, curoffset, 0)\n\to := syscall.Overlapped{\n\t\tOffsetHigh: uint32(off >> 32),\n\t\tOffset: uint32(off),\n\t}\n\tvar done uint32\n\te = syscall.ReadFile(syscall.Handle(f.fd), b, &done, &o)\n\tif e != nil {\n\t\treturn 0, e\n\t}\n\treturn int(done), nil\n}\n\n\/\/ write writes len(b) bytes to the File.\n\/\/ It returns the number of bytes written and an error, if any.\nfunc (f *File) write(b []byte) (n int, err error) {\n\tf.l.Lock()\n\tdefer f.l.Unlock()\n\treturn syscall.Write(f.fd, b)\n}\n\n\/\/ pwrite writes len(b) bytes to the File starting at byte offset off.\n\/\/ It returns the number of bytes written and an error, if any.\nfunc (f *File) pwrite(b []byte, off int64) (n int, err error) {\n\tf.l.Lock()\n\tdefer f.l.Unlock()\n\tcuroffset, e := syscall.Seek(f.fd, 0, 1)\n\tif e != nil {\n\t\treturn 0, e\n\t}\n\tdefer syscall.Seek(f.fd, curoffset, 0)\n\to := syscall.Overlapped{\n\t\tOffsetHigh: uint32(off >> 32),\n\t\tOffset: uint32(off),\n\t}\n\tvar done uint32\n\te = syscall.WriteFile(syscall.Handle(f.fd), b, &done, &o)\n\tif e != nil {\n\t\treturn 0, e\n\t}\n\treturn int(done), nil\n}\n\n\/\/ seek sets the offset for the next Read or Write on file to offset, interpreted\n\/\/ according to whence: 0 means relative to the origin of the file, 1 means\n\/\/ relative to the current offset, and 2 means relative to the end.\n\/\/ It returns the new offset and an error, if any.\nfunc (f *File) seek(offset int64, whence int) (ret int64, err error) {\n\tf.l.Lock()\n\tdefer f.l.Unlock()\n\treturn syscall.Seek(f.fd, offset, whence)\n}\n\n\/\/ Truncate changes the size of the named file.\n\/\/ If the file is a symbolic link, it changes the size of the link's target.\nfunc Truncate(name string, size int64) error {\n\tf, e := OpenFile(name, O_WRONLY|O_CREATE, 0666)\n\tif e != nil {\n\t\treturn e\n\t}\n\tdefer f.Close()\n\te1 := f.Truncate(size)\n\tif e1 != nil {\n\t\treturn e1\n\t}\n\treturn nil\n}\n\n\/\/ Pipe returns a connected pair of Files; reads from r return bytes written to w.\n\/\/ It returns the files and an error, if any.\nfunc Pipe() (r *File, w *File, err error) {\n\tvar p [2]syscall.Handle\n\n\t\/\/ See ..\/syscall\/exec.go for description of lock.\n\tsyscall.ForkLock.RLock()\n\te := syscall.Pipe(p[0:])\n\tif e != nil {\n\t\tsyscall.ForkLock.RUnlock()\n\t\treturn nil, nil, NewSyscallError(\"pipe\", e)\n\t}\n\tsyscall.CloseOnExec(p[0])\n\tsyscall.CloseOnExec(p[1])\n\tsyscall.ForkLock.RUnlock()\n\n\treturn NewFile(p[0], \"|0\"), NewFile(p[1], \"|1\"), nil\n}\n\n\/\/ TempDir returns the default directory to use for temporary files.\nfunc TempDir() string {\n\tconst pathSep = '\\\\'\n\tdirw := make([]uint16, syscall.MAX_PATH)\n\tn, _ := syscall.GetTempPath(uint32(len(dirw)), &dirw[0])\n\tif n > uint32(len(dirw)) {\n\t\tdirw = make([]uint16, n)\n\t\tn, _ = syscall.GetTempPath(uint32(len(dirw)), &dirw[0])\n\t\tif n > uint32(len(dirw)) {\n\t\t\tn = 0\n\t\t}\n\t}\n\tif n > 0 && dirw[n-1] == pathSep {\n\t\tn--\n\t}\n\treturn string(utf16.Decode(dirw[0:n]))\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2017 Uber Technologies, Inc.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\npackage http_test\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\tnethttp \"net\/http\"\n\t\"os\"\n\n\t\"go.uber.org\/yarpc\"\n\t\"go.uber.org\/yarpc\/internal\/iopool\"\n\t\"go.uber.org\/yarpc\/transport\/http\"\n)\n\nfunc ExampleInbound() {\n\ttransport := http.NewTransport()\n\tinbound := transport.NewInbound(\":8888\")\n\n\tdispatcher := yarpc.NewDispatcher(yarpc.Config{\n\t\tName: \"myservice\",\n\t\tInbounds: yarpc.Inbounds{inbound},\n\t})\n\tif err := dispatcher.Start(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer dispatcher.Stop()\n}\n\nfunc ExampleMux() {\n\t\/\/ import nethttp \"net\/http\"\n\n\t\/\/ We set up a ServeMux which provides a \/health endpoint.\n\tmux := nethttp.NewServeMux()\n\tmux.HandleFunc(\"\/health\", func(w nethttp.ResponseWriter, _ *nethttp.Request) {\n\t\tif _, err := fmt.Fprintln(w, \"hello from \/health\"); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t})\n\n\t\/\/ This inbound will serve the YARPC service on the path \/yarpc. The\n\t\/\/ \/health endpoint on the Mux will be left alone.\n\ttransport := http.NewTransport()\n\tinbound := transport.NewInbound(\":8888\", http.Mux(\"\/yarpc\", mux))\n\n\t\/\/ Fire up a dispatcher with the new inbound.\n\tdispatcher := yarpc.NewDispatcher(yarpc.Config{\n\t\tName: \"server\",\n\t\tInbounds: yarpc.Inbounds{inbound},\n\t})\n\tif err := dispatcher.Start(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer dispatcher.Stop()\n\n\t\/\/ Make a request to the \/health endpoint.\n\tres, err := nethttp.Get(\"http:\/\/127.0.0.1:8888\/health\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer res.Body.Close()\n\n\tif _, err := iopool.Copy(os.Stdout, res.Body); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t\/\/ Output: hello from \/health\n}\n\nfunc ExampleInterceptor() {\n\t\/\/ import nethttp \"net\/http\"\n\n\t\/\/ We create an interceptor which executes an override http.Handler if\n\t\/\/ the HTTP request is not a well-formed YARPC request.\n\toverride := func(overrideHandler nethttp.Handler) http.InboundOption {\n\t\treturn http.Interceptor(func(transportHandler nethttp.Handler) nethttp.Handler {\n\t\t\treturn nethttp.HandlerFunc(func(w nethttp.ResponseWriter, r *nethttp.Request) {\n\t\t\t\tif r.Header.Get(\"RPC-Encoding\") == \"\" {\n\t\t\t\t\toverrideHandler.ServeHTTP(w, r)\n\t\t\t\t} else {\n\t\t\t\t\ttransportHandler.ServeHTTP(w, r)\n\t\t\t\t}\n\t\t\t})\n\t\t})\n\t}\n\n\t\/\/ This handler will be executed for non-YARPC HTTP requests.\n\thandler := nethttp.HandlerFunc(func(w nethttp.ResponseWriter, req *nethttp.Request) {\n\t\tio.WriteString(w, \"hello, world!\")\n\t})\n\n\t\/\/ We create the inbound, attaching the override interceptor.\n\ttransport := http.NewTransport()\n\tinbound := transport.NewInbound(\":8889\", override(handler))\n\n\t\/\/ Fire up a dispatcher with the new inbound.\n\tdispatcher := yarpc.NewDispatcher(yarpc.Config{\n\t\tName: \"server\",\n\t\tInbounds: yarpc.Inbounds{inbound},\n\t})\n\tif err := dispatcher.Start(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer dispatcher.Stop()\n\n\t\/\/ Make a non-YARPC request to the \/ endpoint.\n\tres, err := nethttp.Get(\"http:\/\/127.0.0.1:8889\/\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer res.Body.Close()\n\n\tif _, err := iopool.Copy(os.Stdout, res.Body); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t\/\/ Output: hello, world!\n}\nSimplify http.Interceptor example (#1337)\/\/ Copyright (c) 2017 Uber Technologies, Inc.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\npackage http_test\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\tnethttp \"net\/http\"\n\t\"os\"\n\n\t\"go.uber.org\/yarpc\"\n\t\"go.uber.org\/yarpc\/transport\/http\"\n)\n\nfunc ExampleInbound() {\n\ttransport := http.NewTransport()\n\tinbound := transport.NewInbound(\":8888\")\n\n\tdispatcher := yarpc.NewDispatcher(yarpc.Config{\n\t\tName: \"myservice\",\n\t\tInbounds: yarpc.Inbounds{inbound},\n\t})\n\tif err := dispatcher.Start(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer dispatcher.Stop()\n}\n\nfunc ExampleMux() {\n\t\/\/ import nethttp \"net\/http\"\n\n\t\/\/ We set up a ServeMux which provides a \/health endpoint.\n\tmux := nethttp.NewServeMux()\n\tmux.HandleFunc(\"\/health\", func(w nethttp.ResponseWriter, _ *nethttp.Request) {\n\t\tif _, err := fmt.Fprintln(w, \"hello from \/health\"); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t})\n\n\t\/\/ This inbound will serve the YARPC service on the path \/yarpc. The\n\t\/\/ \/health endpoint on the Mux will be left alone.\n\ttransport := http.NewTransport()\n\tinbound := transport.NewInbound(\":8888\", http.Mux(\"\/yarpc\", mux))\n\n\t\/\/ Fire up a dispatcher with the new inbound.\n\tdispatcher := yarpc.NewDispatcher(yarpc.Config{\n\t\tName: \"server\",\n\t\tInbounds: yarpc.Inbounds{inbound},\n\t})\n\tif err := dispatcher.Start(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer dispatcher.Stop()\n\n\t\/\/ Make a request to the \/health endpoint.\n\tres, err := nethttp.Get(\"http:\/\/127.0.0.1:8888\/health\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer res.Body.Close()\n\n\tif _, err := io.Copy(os.Stdout, res.Body); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t\/\/ Output: hello from \/health\n}\n\nfunc ExampleInterceptor() {\n\t\/\/ import nethttp \"net\/http\"\n\n\t\/\/ Given a fallback http.Handler\n\tfallback := nethttp.HandlerFunc(func(w nethttp.ResponseWriter, r *nethttp.Request) {\n\t\tio.WriteString(w, \"hello, world!\")\n\t})\n\n\t\/\/ Create an interceptor that falls back to a handler when the HTTP request is\n\t\/\/ missing the RPC-Encoding header.\n\tintercept := func(transportHandler nethttp.Handler) nethttp.Handler {\n\t\treturn nethttp.HandlerFunc(func(w nethttp.ResponseWriter, r *nethttp.Request) {\n\t\t\tif r.Header.Get(http.EncodingHeader) == \"\" {\n\t\t\t\t\/\/ Not a YARPC request, use fallback handler.\n\t\t\t\tfallback.ServeHTTP(w, r)\n\t\t\t} else {\n\t\t\t\ttransportHandler.ServeHTTP(w, r)\n\t\t\t}\n\t\t})\n\t}\n\n\t\/\/ Create a new inbound, attaching the interceptor\n\ttransport := http.NewTransport()\n\tinbound := transport.NewInbound(\":8889\", http.Interceptor(intercept))\n\n\t\/\/ Fire up a dispatcher with the new inbound.\n\tdispatcher := yarpc.NewDispatcher(yarpc.Config{\n\t\tName: \"server\",\n\t\tInbounds: yarpc.Inbounds{inbound},\n\t})\n\tif err := dispatcher.Start(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer dispatcher.Stop()\n\n\t\/\/ Make a non-YARPC request to the \/ endpoint.\n\tres, err := nethttp.Get(\"http:\/\/127.0.0.1:8889\/\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer res.Body.Close()\n\n\tif _, err := io.Copy(os.Stdout, res.Body); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t\/\/ Output: hello, world!\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2017 gf Author(https:\/\/github.com\/gogf\/gf). All Rights Reserved.\n\/\/\n\/\/ This Source Code Form is subject to the terms of the MIT License.\n\/\/ If a copy of the MIT was not distributed with this file,\n\/\/ You can obtain one at https:\/\/github.com\/gogf\/gf.\n\npackage gdb\n\nimport (\n\t\"fmt\"\n\t\"github.com\/gogf\/gf\/container\/gset\"\n\t\"github.com\/gogf\/gf\/text\/gstr\"\n)\n\n\/\/ Filter marks filtering the fields which does not exist in the fields of the operated table.\n\/\/ Note that this function supports only single table operations.\nfunc (m *Model) Filter() *Model {\n\tif gstr.Contains(m.tables, \" \") {\n\t\tpanic(\"function Filter supports only single table operations\")\n\t}\n\tmodel := m.getModel()\n\tmodel.filter = true\n\treturn model\n}\n\n\/\/ Fields sets the operation fields of the model, multiple fields joined using char ','.\nfunc (m *Model) Fields(fields string) *Model {\n\tmodel := m.getModel()\n\tmodel.fields = fields\n\treturn model\n}\n\n\/\/ FieldsEx sets the excluded operation fields of the model, multiple fields joined using char ','.\n\/\/ Note that this function supports only single table operations.\nfunc (m *Model) FieldsEx(fields string) *Model {\n\tif gstr.Contains(m.tables, \" \") {\n\t\tpanic(\"function FieldsEx supports only single table operations\")\n\t}\n\ttableFields, err := m.db.TableFields(m.tables)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif len(tableFields) == 0 {\n\t\tpanic(fmt.Sprintf(`empty table fields for table \"%s\"`, m.tables))\n\t}\n\tmodel := m.getModel()\n\tmodel.fieldsEx = fields\n\tfieldsExSet := gset.NewStrSetFrom(gstr.SplitAndTrim(fields, \",\"))\n\tfieldsArray := make([]string, len(tableFields))\n\tfor k, v := range tableFields {\n\t\tfieldsArray[v.Index] = k\n\t}\n\tmodel.fields = \"\"\n\tfor _, k := range fieldsArray {\n\t\tif fieldsExSet.Contains(k) {\n\t\t\tcontinue\n\t\t}\n\t\tif len(model.fields) > 0 {\n\t\t\tmodel.fields += \",\"\n\t\t}\n\t\tmodel.fields += k\n\t}\n\tmodel.fields = model.db.QuoteString(model.fields)\n\treturn model\n}\n\n\/\/ FieldsStr retrieves and returns all fields from the table, joined with char ','.\n\/\/ The optional parameter specifies the prefix for each field, eg: FieldsStr(\"u.\").\nfunc (m *Model) FieldsStr(prefix ...string) string {\n\tprefixStr := \"\"\n\tif len(prefix) > 0 {\n\t\tprefixStr = prefix[0]\n\t}\n\ttableFields, err := m.db.TableFields(m.tables)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif len(tableFields) == 0 {\n\t\tpanic(fmt.Sprintf(`empty table fields for table \"%s\"`, m.tables))\n\t}\n\tfieldsArray := make([]string, len(tableFields))\n\tfor k, v := range tableFields {\n\t\tfieldsArray[v.Index] = k\n\t}\n\tnewFields := \"\"\n\tfor _, k := range fieldsArray {\n\t\tif len(newFields) > 0 {\n\t\t\tnewFields += \",\"\n\t\t}\n\t\tnewFields += prefixStr + k\n\t}\n\tnewFields = m.db.QuoteString(newFields)\n\treturn newFields\n}\n\n\/\/ FieldsExStr retrieves and returns fields which are not in parameter from the table,\n\/\/ joined with char ','.\n\/\/ The parameter specifies the fields that are excluded.\n\/\/ The optional parameter specifies the prefix for each field, eg: FieldsExStr(\"id\", \"u.\").\nfunc (m *Model) FieldsExStr(fields string, prefix ...string) string {\n\tprefixStr := \"\"\n\tif len(prefix) > 0 {\n\t\tprefixStr = prefix[0]\n\t}\n\ttableFields, err := m.db.TableFields(m.tables)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif len(tableFields) == 0 {\n\t\tpanic(fmt.Sprintf(`empty table fields for table \"%s\"`, m.tables))\n\t}\n\tfieldsExSet := gset.NewStrSetFrom(gstr.SplitAndTrim(fields, \",\"))\n\tfieldsArray := make([]string, len(tableFields))\n\tfor k, v := range tableFields {\n\t\tfieldsArray[v.Index] = k\n\t}\n\tnewFields := \"\"\n\tfor _, k := range fieldsArray {\n\t\tif fieldsExSet.Contains(k) {\n\t\t\tcontinue\n\t\t}\n\t\tif len(newFields) > 0 {\n\t\t\tnewFields += \",\"\n\t\t}\n\t\tnewFields += prefixStr + k\n\t}\n\tnewFields = m.db.QuoteString(newFields)\n\treturn newFields\n}\nadd table field method\/\/ Copyright 2017 gf Author(https:\/\/github.com\/gogf\/gf). All Rights Reserved.\n\/\/\n\/\/ This Source Code Form is subject to the terms of the MIT License.\n\/\/ If a copy of the MIT was not distributed with this file,\n\/\/ You can obtain one at https:\/\/github.com\/gogf\/gf.\n\npackage gdb\n\nimport (\n\t\"fmt\"\n\t\"github.com\/gogf\/gf\/container\/gset\"\n\t\"github.com\/gogf\/gf\/text\/gstr\"\n)\n\n\/\/ Filter marks filtering the fields which does not exist in the fields of the operated table.\n\/\/ Note that this function supports only single table operations.\nfunc (m *Model) Filter() *Model {\n\tif gstr.Contains(m.tables, \" \") {\n\t\tpanic(\"function Filter supports only single table operations\")\n\t}\n\tmodel := m.getModel()\n\tmodel.filter = true\n\treturn model\n}\n\n\/\/ Fields sets the operation fields of the model, multiple fields joined using char ','.\nfunc (m *Model) Fields(fields string) *Model {\n\tmodel := m.getModel()\n\tmodel.fields = fields\n\treturn model\n}\n\n\/\/ FieldsEx sets the excluded operation fields of the model, multiple fields joined using char ','.\n\/\/ Note that this function supports only single table operations.\nfunc (m *Model) FieldsEx(fields string) *Model {\n\tif gstr.Contains(m.tables, \" \") {\n\t\tpanic(\"function FieldsEx supports only single table operations\")\n\t}\n\ttableFields, err := m.db.TableFields(m.tables)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif len(tableFields) == 0 {\n\t\tpanic(fmt.Sprintf(`empty table fields for table \"%s\"`, m.tables))\n\t}\n\tmodel := m.getModel()\n\tmodel.fieldsEx = fields\n\tfieldsExSet := gset.NewStrSetFrom(gstr.SplitAndTrim(fields, \",\"))\n\tfieldsArray := make([]string, len(tableFields))\n\tfor k, v := range tableFields {\n\t\tfieldsArray[v.Index] = k\n\t}\n\tmodel.fields = \"\"\n\tfor _, k := range fieldsArray {\n\t\tif fieldsExSet.Contains(k) {\n\t\t\tcontinue\n\t\t}\n\t\tif len(model.fields) > 0 {\n\t\t\tmodel.fields += \",\"\n\t\t}\n\t\tmodel.fields += k\n\t}\n\tmodel.fields = model.db.QuoteString(model.fields)\n\treturn model\n}\n\n\/\/ FieldsStr retrieves and returns all fields from the table, joined with char ','.\n\/\/ The optional parameter specifies the prefix for each field, eg: FieldsStr(\"u.\").\nfunc (m *Model) FieldsStr(prefix ...string) string {\n\tprefixStr := \"\"\n\tif len(prefix) > 0 {\n\t\tprefixStr = prefix[0]\n\t}\n\ttableFields, err := m.db.TableFields(m.tables)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif len(tableFields) == 0 {\n\t\tpanic(fmt.Sprintf(`empty table fields for table \"%s\"`, m.tables))\n\t}\n\tfieldsArray := make([]string, len(tableFields))\n\tfor k, v := range tableFields {\n\t\tfieldsArray[v.Index] = k\n\t}\n\tnewFields := \"\"\n\tfor _, k := range fieldsArray {\n\t\tif len(newFields) > 0 {\n\t\t\tnewFields += \",\"\n\t\t}\n\t\tnewFields += prefixStr + k\n\t}\n\tnewFields = m.db.QuoteString(newFields)\n\treturn newFields\n}\n\n\/\/ FieldsExStr retrieves and returns fields which are not in parameter from the table,\n\/\/ joined with char ','.\n\/\/ The parameter specifies the fields that are excluded.\n\/\/ The optional parameter specifies the prefix for each field, eg: FieldsExStr(\"id\", \"u.\").\nfunc (m *Model) FieldsExStr(fields string, prefix ...string) string {\n\tprefixStr := \"\"\n\tif len(prefix) > 0 {\n\t\tprefixStr = prefix[0]\n\t}\n\ttableFields, err := m.db.TableFields(m.tables)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif len(tableFields) == 0 {\n\t\tpanic(fmt.Sprintf(`empty table fields for table \"%s\"`, m.tables))\n\t}\n\tfieldsExSet := gset.NewStrSetFrom(gstr.SplitAndTrim(fields, \",\"))\n\tfieldsArray := make([]string, len(tableFields))\n\tfor k, v := range tableFields {\n\t\tfieldsArray[v.Index] = k\n\t}\n\tnewFields := \"\"\n\tfor _, k := range fieldsArray {\n\t\tif fieldsExSet.Contains(k) {\n\t\t\tcontinue\n\t\t}\n\t\tif len(newFields) > 0 {\n\t\t\tnewFields += \",\"\n\t\t}\n\t\tnewFields += prefixStr + k\n\t}\n\tnewFields = m.db.QuoteString(newFields)\n\treturn newFields\n}\n\n\/\/ HasField determine whether the field exists in the table.\nfunc (m *Model) HasField(field string) bool {\n\ttableFields, err := m.db.TableFields(m.tables)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif len(tableFields) == 0 {\n\t\tpanic(fmt.Sprintf(`empty table fields for table \"%s\"`, m.tables))\n\t}\n\tfieldsArray := make([]string, len(tableFields))\n\tfor k, v := range tableFields {\n\t\tfieldsArray[v.Index] = k\n\t}\n\tfor _, f := range fieldsArray {\n\t\tif f == field {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}<|endoftext|>"} {"text":"package template\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"strings\"\n\t\"sync\"\n\t\"testing\"\n\n\tr \"github.com\/hashicorp\/terraform\/helper\/resource\"\n\t\"github.com\/hashicorp\/terraform\/terraform\"\n)\n\nvar testProviders = map[string]terraform.ResourceProvider{\n\t\"template\": Provider(),\n}\n\nfunc TestTemplateRendering(t *testing.T) {\n\tvar cases = []struct {\n\t\tvars string\n\t\ttemplate string\n\t\twant string\n\t}{\n\t\t{`{}`, `ABC`, `ABC`},\n\t\t{`{a=\"foo\"}`, `$${a}`, `foo`},\n\t\t{`{a=\"hello\"}`, `$${replace(a, \"ello\", \"i\")}`, `hi`},\n\t\t{`{}`, `${1+2+3}`, `6`},\n\t}\n\n\tfor _, tt := range cases {\n\t\tr.UnitTest(t, r.TestCase{\n\t\t\tProviders: testProviders,\n\t\t\tSteps: []r.TestStep{\n\t\t\t\tr.TestStep{\n\t\t\t\t\tConfig: testTemplateConfig(tt.template, tt.vars),\n\t\t\t\t\tCheck: func(s *terraform.State) error {\n\t\t\t\t\t\tgot := s.RootModule().Outputs[\"rendered\"]\n\t\t\t\t\t\tif tt.want != got.Value {\n\t\t\t\t\t\t\treturn fmt.Errorf(\"template:\\n%s\\nvars:\\n%s\\ngot:\\n%s\\nwant:\\n%s\\n\", tt.template, tt.vars, got, tt.want)\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t})\n\t}\n}\n\nfunc TestValidateTemplateAttribute(t *testing.T) {\n\tfile, err := ioutil.TempFile(\"\", \"testtemplate\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tfile.WriteString(\"Hello world.\")\n\tfile.Close()\n\tdefer os.Remove(file.Name())\n\n\tws, es := validateTemplateAttribute(file.Name(), \"test\")\n\n\tif len(es) != 0 {\n\t\tt.Fatalf(\"Unexpected errors: %#v\", es)\n\t}\n\n\tif len(ws) != 1 {\n\t\tt.Fatalf(\"Expected 1 warning, got %d\", len(ws))\n\t}\n\n\tif !strings.Contains(ws[0], \"Specifying a path directly is deprecated\") {\n\t\tt.Fatalf(\"Expected warning about path, got: %s\", ws[0])\n\t}\n}\n\nfunc TestValidateVarsAttribute(t *testing.T) {\n\tcases := map[string]struct {\n\t\tVars map[string]interface{}\n\t\tExpectErr string\n\t}{\n\t\t\"lists are invalid\": {\n\t\t\tmap[string]interface{}{\n\t\t\t\t\"list\": []interface{}{},\n\t\t\t},\n\t\t\t`vars: cannot contain non-primitives`,\n\t\t},\n\t\t\"maps are invalid\": {\n\t\t\tmap[string]interface{}{\n\t\t\t\t\"map\": map[string]interface{}{},\n\t\t\t},\n\t\t\t`vars: cannot contain non-primitives`,\n\t\t},\n\t\t\"strings, integers, floats, and bools are AOK\": {\n\t\t\tmap[string]interface{}{\n\t\t\t\t\"string\": \"foo\",\n\t\t\t\t\"int\": 1,\n\t\t\t\t\"bool\": true,\n\t\t\t\t\"float\": float64(1.0),\n\t\t\t},\n\t\t\t``,\n\t\t},\n\t}\n\n\tfor tn, tc := range cases {\n\t\t_, es := validateVarsAttribute(tc.Vars, \"vars\")\n\t\tif len(es) > 0 {\n\t\t\tif tc.ExpectErr == \"\" {\n\t\t\t\tt.Fatalf(\"%s: expected no err, got: %#v\", tn, es)\n\t\t\t}\n\t\t\tif !strings.Contains(es[0].Error(), tc.ExpectErr) {\n\t\t\t\tt.Fatalf(\"%s: expected\\n%s\\nto contain\\n%s\", tn, es[0], tc.ExpectErr)\n\t\t\t}\n\t\t} else if tc.ExpectErr != \"\" {\n\t\t\tt.Fatalf(\"%s: expected err containing %q, got none!\", tn, tc.ExpectErr)\n\t\t}\n\t}\n}\n\n\/\/ This test covers a panic due to config.Func formerly being a\n\/\/ shared map, causing multiple template_file resources to try and\n\/\/ accessing it parallel during their lang.Eval() runs.\n\/\/\n\/\/ Before fix, test fails under `go test -race`\nfunc TestTemplateSharedMemoryRace(t *testing.T) {\n\tvar wg sync.WaitGroup\n\tfor i := 0; i < 100; i++ {\n\t\tgo func(wg sync.WaitGroup, t *testing.T, i int) {\n\t\t\twg.Add(1)\n\t\t\tout, err := execute(\"don't panic!\", map[string]interface{}{})\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"err: %s\", err)\n\t\t\t}\n\t\t\tif out != \"don't panic!\" {\n\t\t\t\tt.Fatalf(\"bad output: %s\", out)\n\t\t\t}\n\t\t\twg.Done()\n\t\t}(wg, t, i)\n\t}\n\twg.Wait()\n}\n\nfunc testTemplateConfig(template, vars string) string {\n\treturn fmt.Sprintf(`\n\t\tdata \"template_file\" \"t0\" {\n\t\t\ttemplate = \"%s\"\n\t\t\tvars = %s\n\t\t}\n\t\toutput \"rendered\" {\n\t\t\t\tvalue = \"${data.template_file.t0.rendered}\"\n\t\t}`, template, vars)\n}\nfix make issues (supersedes #7868) (#7876)package template\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"strings\"\n\t\"sync\"\n\t\"testing\"\n\n\tr \"github.com\/hashicorp\/terraform\/helper\/resource\"\n\t\"github.com\/hashicorp\/terraform\/terraform\"\n)\n\nvar testProviders = map[string]terraform.ResourceProvider{\n\t\"template\": Provider(),\n}\n\nfunc TestTemplateRendering(t *testing.T) {\n\tvar cases = []struct {\n\t\tvars string\n\t\ttemplate string\n\t\twant string\n\t}{\n\t\t{`{}`, `ABC`, `ABC`},\n\t\t{`{a=\"foo\"}`, `$${a}`, `foo`},\n\t\t{`{a=\"hello\"}`, `$${replace(a, \"ello\", \"i\")}`, `hi`},\n\t\t{`{}`, `${1+2+3}`, `6`},\n\t}\n\n\tfor _, tt := range cases {\n\t\tr.UnitTest(t, r.TestCase{\n\t\t\tProviders: testProviders,\n\t\t\tSteps: []r.TestStep{\n\t\t\t\tr.TestStep{\n\t\t\t\t\tConfig: testTemplateConfig(tt.template, tt.vars),\n\t\t\t\t\tCheck: func(s *terraform.State) error {\n\t\t\t\t\t\tgot := s.RootModule().Outputs[\"rendered\"]\n\t\t\t\t\t\tif tt.want != got.Value {\n\t\t\t\t\t\t\treturn fmt.Errorf(\"template:\\n%s\\nvars:\\n%s\\ngot:\\n%s\\nwant:\\n%s\\n\", tt.template, tt.vars, got, tt.want)\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t})\n\t}\n}\n\nfunc TestValidateTemplateAttribute(t *testing.T) {\n\tfile, err := ioutil.TempFile(\"\", \"testtemplate\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tfile.WriteString(\"Hello world.\")\n\tfile.Close()\n\tdefer os.Remove(file.Name())\n\n\tws, es := validateTemplateAttribute(file.Name(), \"test\")\n\n\tif len(es) != 0 {\n\t\tt.Fatalf(\"Unexpected errors: %#v\", es)\n\t}\n\n\tif len(ws) != 1 {\n\t\tt.Fatalf(\"Expected 1 warning, got %d\", len(ws))\n\t}\n\n\tif !strings.Contains(ws[0], \"Specifying a path directly is deprecated\") {\n\t\tt.Fatalf(\"Expected warning about path, got: %s\", ws[0])\n\t}\n}\n\nfunc TestValidateVarsAttribute(t *testing.T) {\n\tcases := map[string]struct {\n\t\tVars map[string]interface{}\n\t\tExpectErr string\n\t}{\n\t\t\"lists are invalid\": {\n\t\t\tmap[string]interface{}{\n\t\t\t\t\"list\": []interface{}{},\n\t\t\t},\n\t\t\t`vars: cannot contain non-primitives`,\n\t\t},\n\t\t\"maps are invalid\": {\n\t\t\tmap[string]interface{}{\n\t\t\t\t\"map\": map[string]interface{}{},\n\t\t\t},\n\t\t\t`vars: cannot contain non-primitives`,\n\t\t},\n\t\t\"strings, integers, floats, and bools are AOK\": {\n\t\t\tmap[string]interface{}{\n\t\t\t\t\"string\": \"foo\",\n\t\t\t\t\"int\": 1,\n\t\t\t\t\"bool\": true,\n\t\t\t\t\"float\": float64(1.0),\n\t\t\t},\n\t\t\t``,\n\t\t},\n\t}\n\n\tfor tn, tc := range cases {\n\t\t_, es := validateVarsAttribute(tc.Vars, \"vars\")\n\t\tif len(es) > 0 {\n\t\t\tif tc.ExpectErr == \"\" {\n\t\t\t\tt.Fatalf(\"%s: expected no err, got: %#v\", tn, es)\n\t\t\t}\n\t\t\tif !strings.Contains(es[0].Error(), tc.ExpectErr) {\n\t\t\t\tt.Fatalf(\"%s: expected\\n%s\\nto contain\\n%s\", tn, es[0], tc.ExpectErr)\n\t\t\t}\n\t\t} else if tc.ExpectErr != \"\" {\n\t\t\tt.Fatalf(\"%s: expected err containing %q, got none!\", tn, tc.ExpectErr)\n\t\t}\n\t}\n}\n\n\/\/ This test covers a panic due to config.Func formerly being a\n\/\/ shared map, causing multiple template_file resources to try and\n\/\/ accessing it parallel during their lang.Eval() runs.\n\/\/\n\/\/ Before fix, test fails under `go test -race`\nfunc TestTemplateSharedMemoryRace(t *testing.T) {\n\tvar wg sync.WaitGroup\n\tfor i := 0; i < 100; i++ {\n\t\tgo func(wg *sync.WaitGroup, t *testing.T, i int) {\n\t\t\twg.Add(1)\n\t\t\tout, err := execute(\"don't panic!\", map[string]interface{}{})\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"err: %s\", err)\n\t\t\t}\n\t\t\tif out != \"don't panic!\" {\n\t\t\t\tt.Fatalf(\"bad output: %s\", out)\n\t\t\t}\n\t\t\twg.Done()\n\t\t}(&wg, t, i)\n\t}\n\twg.Wait()\n}\n\nfunc testTemplateConfig(template, vars string) string {\n\treturn fmt.Sprintf(`\n\t\tdata \"template_file\" \"t0\" {\n\t\t\ttemplate = \"%s\"\n\t\t\tvars = %s\n\t\t}\n\t\toutput \"rendered\" {\n\t\t\t\tvalue = \"${data.template_file.t0.rendered}\"\n\t\t}`, template, vars)\n}\n<|endoftext|>"} {"text":"\/\/ Package sp provides tools for buildin an SP such as serving metadata,\n\/\/ authenticating an assertion and building assertions for IdPs.\npackage saml\n\nimport (\n\t\"bytes\"\n\t\"compress\/flate\"\n\t\"encoding\/base64\"\n\t\"encoding\/xml\"\n\t\"fmt\"\n\t\"net\/url\"\n\t\"strings\"\n\n\t\"github.com\/goware\/saml\/xmlsec\"\n\t\"github.com\/pkg\/errors\"\n)\n\n\/\/ AuthnRequestURL creates SAML 2.0 AuthnRequest redirect URL,\n\/\/ aka SP-initiated login (SP->IdP).\n\/\/ The data is passed in the ?SAMLRequest query parameter and\n\/\/ the value is base64 encoded and deflate-compressed \n\/\/ XML element. The final redirect destination that will be invoked\n\/\/ on successful login is passed using ?RelayState query parameter.\nfunc (sp *ServiceProvider) AuthnRequestURL(relayState string) (string, error) {\n\tdestination, err := sp.GetIdPAuthResource()\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"failed to get IdP destination\")\n\t}\n\n\tauthnRequest, err := sp.NewAuthnRequest(destination)\n\tif err != nil {\n\t\treturn \"\", errors.Wrapf(err, \"failed to make auth request to %v\", destination)\n\t}\n\n\tbuf, err := xml.MarshalIndent(authnRequest, \"\", \"\\t\")\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"Failed to marshal auth request\")\n\t}\n\n\tflateBuf := bytes.NewBuffer(nil)\n\tflateWriter, err := flate.NewWriter(flateBuf, flate.DefaultCompression)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"failed to create flate writer\")\n\t}\n\n\t_, err = flateWriter.Write(buf)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"failed to write to flate writer\")\n\t}\n\tflateWriter.Close()\n\tmessage := base64.StdEncoding.EncodeToString(flateBuf.Bytes())\n\n\tredirectURL := destination + fmt.Sprintf(`?RelayState=%s&SAMLRequest=%s`, url.QueryEscape(relayState), url.QueryEscape(message))\n\n\treturn redirectURL, nil\n}\n\n\/\/ MetadataXML returns SAML 2.0 Service Provider metadata XML.\nfunc (sp *ServiceProvider) MetadataXML() ([]byte, error) {\n\tmetadata, err := sp.Metadata()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not build nor serve metadata XML\")\n\t}\n\n\tout, err := xml.MarshalIndent(metadata, \"\", \"\\t\")\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not format metadata\")\n\t}\n\n\treturn out, nil\n}\n\nfunc (sp *ServiceProvider) possibleResponseIDs() []string {\n\tresponseIDs := []string{}\n\tif sp.AllowIdpInitiated {\n\t\tresponseIDs = append(responseIDs, \"\")\n\t}\n\treturn responseIDs\n}\n\nfunc (sp *ServiceProvider) verifySignature(plaintextMessage []byte) error {\n\tidpCertFile, err := sp.GetIdPCertFile()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = xmlsec.Verify(plaintextMessage, idpCertFile, &xmlsec.ValidationOptions{\n\t\tDTDFile: sp.DTDFile,\n\t})\n\tif err == nil {\n\t\t\/\/ No error, this message is OK\n\t\treturn nil\n\t}\n\n\t\/\/ We got an error...\n\tif !IsSecurityException(err, &sp.SecurityOpts) {\n\t\t\/\/ ...but it was not a security exception, so we ignore it and accept\n\t\t\/\/ the verification.\n\t\treturn nil\n\t}\n\n\treturn err\n}\n\nfunc (sp *ServiceProvider) parseSAMLResponse(samlResponse string) (*Response, error) {\n\tsamlResponseXML, err := base64.StdEncoding.DecodeString(samlResponse)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to base64-decode SAML response\")\n\t}\n\n\tvar res Response\n\terr = xml.Unmarshal(samlResponseXML, &res)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to unmarshal XML document: %s\", string(samlResponseXML))\n\t}\n\n\treturn &res, nil\n}\n\nfunc (sp *ServiceProvider) AssertResponse(samlResponse string) (*Assertion, error) {\n\tnow := Now()\n\n\tres, err := sp.parseSAMLResponse(samlResponse)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to parse SAML response\")\n\t}\n\n\t\/\/ TODO: Do we really need to check the IdP metadata here?\n\tif _, err := sp.GetIdPMetadata(); err != nil {\n\t\treturn nil, errors.Wrap(err, \"unable to retrieve IdP metadata\")\n\t}\n\n\t\/\/ Validate message.\n\n\tif res.Destination != sp.AcsURL {\n\t\t\/\/ Note: OneLogin triggers this error when the Recipient field\n\t\t\/\/ is left blank (or when not set to the correct ACS endpoint)\n\t\t\/\/ in the OneLogin SAML configuration page. OneLogin returns\n\t\t\/\/ Destination=\"{recipient}\" in the SAML reponse in this case.\n\t\treturn nil, errors.Errorf(\"Wrong ACS destination, expected %q, got %q\", sp.AcsURL, res.Destination)\n\t}\n\n\tif sp.IdPMetadata.EntityID != \"\" {\n\t\tif res.Issuer == nil {\n\t\t\treturn nil, errors.New(`Issuer does not match expected entity ID: Missing \"Issuer\" node`)\n\t\t}\n\t\tif res.Issuer.Value != sp.IdPMetadata.EntityID {\n\t\t\treturn nil, errors.Errorf(\"Issuer does not match expected entity ID: expected %q, got %q\", sp.IdPMetadata.EntityID, res.Issuer.Value)\n\t\t}\n\t}\n\n\tif res.Status.StatusCode.Value != \"urn:oasis:names:tc:SAML:2.0:status:Success\" {\n\t\treturn nil, errors.Errorf(\"Unexpected status code: %v\", res.Status.StatusCode.Value)\n\t}\n\n\texpectedResponse := false\n\tresponseIDs := sp.possibleResponseIDs()\n\tfor i := range responseIDs {\n\t\tif responseIDs[i] == res.InResponseTo {\n\t\t\texpectedResponse = true\n\t\t}\n\t}\n\tif len(responseIDs) == 1 && responseIDs[0] == \"\" {\n\t\texpectedResponse = true\n\t}\n\tif !expectedResponse && len(responseIDs) > 0 {\n\t\treturn nil, errors.Errorf(\"Expecting a proper InResponseTo value, got %#v\", responseIDs)\n\t}\n\n\t\/\/ Try getting the IdP's cert file before using it.\n\tif _, err := sp.GetIdPCertFile(); err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to get private key\")\n\t}\n\n\t\/\/ Validate signatures\n\n\tif res.Signature != nil {\n\t\terr := validateSignedNode(res.Signature, res.ID)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to validate Response + Signature\")\n\t\t}\n\t}\n\n\tif res.Assertion != nil && res.Assertion.Signature != nil {\n\t\terr := validateSignedNode(res.Assertion.Signature, res.Assertion.ID)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to validate Assertion + Signature\")\n\t\t}\n\t}\n\n\t\/\/ Validating message.\n\tsignatureOK := false\n\n\tif res.Signature != nil || (res.Assertion != nil && res.Assertion.Signature != nil) {\n\t\terr := sp.verifySignature([]byte(samlResponse))\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"Unable to verify message signature\")\n\t\t} else {\n\t\t\tsignatureOK = true\n\t\t}\n\t}\n\n\t\/\/ Retrieve assertion\n\tvar assertion *Assertion\n\n\tif res.EncryptedAssertion != nil {\n\t\tkeyFile, err := sp.PrivkeyFile()\n\t\tif err != nil {\n\t\t\treturn nil, errors.Errorf(\"Failed to get private key: %v\", err)\n\t\t}\n\n\t\tplainTextAssertion, err := xmlsec.Decrypt(res.EncryptedAssertion.EncryptedData, keyFile)\n\t\tif err != nil {\n\t\t\tif IsSecurityException(err, &sp.SecurityOpts) {\n\t\t\t\treturn nil, errors.Wrap(err, \"Unable to decrypt message\")\n\t\t\t}\n\t\t}\n\n\t\tassertion = &Assertion{}\n\t\tif err := xml.Unmarshal(plainTextAssertion, assertion); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"Unable to parse assertion\")\n\t\t}\n\n\t\tif assertion.Signature != nil {\n\t\t\terr := validateSignedNode(assertion.Signature, assertion.ID)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Wrap(err, \"failed to validate Assertion + Signature\")\n\t\t\t}\n\n\t\t\terr = sp.verifySignature(plainTextAssertion)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Wrapf(err, \"Unable to verify assertion signature\")\n\t\t\t} else {\n\t\t\t\tsignatureOK = true\n\t\t\t}\n\t\t}\n\t} else {\n\t\tassertion = res.Assertion\n\t}\n\tif assertion == nil {\n\t\treturn nil, errors.New(\"Missing assertion\")\n\t}\n\n\t\/\/ Did we receive a signature?\n\tif !signatureOK {\n\t\treturn nil, errors.New(\"Unable to validate signature: node not found\")\n\t}\n\n\t\/\/ Validate assertion.\n\tswitch {\n\tcase sp.IdPMetadata.EntityID == \"\":\n\t\t\/\/ Skip issuer validation\n\tcase res.Issuer == nil:\n\t\treturn nil, errors.New(`Assertion issuer does not match expected entity ID: missing Assertion > Issuer`)\n\tcase assertion.Issuer.Value != sp.IdPMetadata.EntityID:\n\t\treturn nil, errors.Errorf(\"Assertion issuer does not match expected entity ID: Expected %q, got %q\", sp.IdPMetadata.EntityID, assertion.Issuer.Value)\n\t}\n\n\t\/\/ Validate recipient\n\t{\n\t\tvar err error\n\t\tswitch {\n\t\tcase assertion.Subject == nil:\n\t\t\terr = errors.New(`missing Assertion > Subject`)\n\t\tcase assertion.Subject.SubjectConfirmation == nil:\n\t\t\terr = errors.New(`missing Assertion > Subject > SubjectConfirmation`)\n\t\tcase assertion.Subject.SubjectConfirmation.SubjectConfirmationData.Recipient != sp.AcsURL:\n\t\t\terr = errors.Errorf(\"unexpected assertion recipient, expected %q, got %q\", sp.AcsURL, assertion.Subject.SubjectConfirmation.SubjectConfirmationData.Recipient)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"invalid assertion recipient\")\n\t\t}\n\t}\n\n\t\/\/ Make sure we have Conditions\n\tif assertion.Conditions == nil {\n\t\treturn nil, errors.New(`missing Assertion > Conditions`)\n\t}\n\n\t\/\/ The NotBefore and NotOnOrAfter attributes specify time limits on the\n\t\/\/ validity of the assertion within the context of its profile(s) of use.\n\t\/\/ They do not guarantee that the statements in the assertion will be\n\t\/\/ correct or accurate throughout the validity period. The NotBefore\n\t\/\/ attribute specifies the time instant at which the validity interval\n\t\/\/ begins. The NotOnOrAfter attribute specifies the time instant at which\n\t\/\/ the validity interval has ended. If the value for either NotBefore or\n\t\/\/ NotOnOrAfter is omitted, then it is considered unspecified.\n\t{\n\t\tvalidFrom := assertion.Conditions.NotBefore\n\t\tif !validFrom.IsZero() && validFrom.After(now.Add(ClockDriftTolerance)) {\n\t\t\treturn nil, errors.Errorf(\"Assertion conditions are not valid yet, got %v, current time is %v\", validFrom, now)\n\t\t}\n\t}\n\n\t{\n\t\tvalidUntil := assertion.Conditions.NotOnOrAfter\n\t\tif !validUntil.IsZero() && validUntil.Before(now.Add(-ClockDriftTolerance)) {\n\t\t\treturn nil, errors.Errorf(\"Assertion conditions already expired, got %v current time is %v, extra time is %v\", validUntil, now, now.Add(-ClockDriftTolerance))\n\t\t}\n\t}\n\n\t\/\/ A time instant at which the subject can no longer be confirmed. The time\n\t\/\/ value is encoded in UTC, as described in Section 1.3.3.\n\t\/\/\n\t\/\/ Note that the time period specified by the optional NotBefore and\n\t\/\/ NotOnOrAfter attributes, if present, SHOULD fall within the overall\n\t\/\/ assertion validity period as specified by the element's NotBefore and\n\t\/\/ NotOnOrAfter attributes. If both attributes are present, the value for\n\t\/\/ NotBefore MUST be less than (earlier than) the value for NotOnOrAfter.\n\n\tif validUntil := assertion.Subject.SubjectConfirmation.SubjectConfirmationData.NotOnOrAfter; validUntil.Before(now.Add(-ClockDriftTolerance)) {\n\t\terr := errors.Errorf(\"Assertion conditions already expired, got %v current time is %v\", validUntil, now)\n\t\treturn nil, errors.Wrap(err, \"Assertion conditions already expired\")\n\t}\n\n\t\/\/ if assertion.Conditions != nil && assertion.Conditions.AudienceRestriction != nil {\n\t\/\/ if assertion.Conditions.AudienceRestriction.Audience.Value != sp.MetadataURL {\n\t\/\/ returnt.Errorf(\"Audience restriction mismatch, got %q, expected %q\", assertion.Conditions.AudienceRestriction.Audience.Value, sp.MetadataURL), errors.New(\"Audience restriction mismatch\")\n\t\/\/ }\n\t\/\/ }\n\n\texpectedResponse = false\n\tfor i := range responseIDs {\n\t\tif responseIDs[i] == assertion.Subject.SubjectConfirmation.SubjectConfirmationData.InResponseTo {\n\t\t\texpectedResponse = true\n\t\t}\n\t}\n\tif len(responseIDs) == 1 && responseIDs[0] == \"\" {\n\t\texpectedResponse = true\n\t}\n\n\tif !expectedResponse && len(responseIDs) > 0 {\n\t\treturn nil, errors.New(\"Unexpected assertion InResponseTo value\")\n\t}\n\n\treturn assertion, nil\n}\n\nfunc validateSignedNode(signature *xmlsec.Signature, nodeID string) error {\n\tsignatureURI := signature.Reference.URI\n\tif signatureURI == \"\" {\n\t\treturn nil\n\t}\n\tif strings.HasPrefix(signatureURI, \"#\") {\n\t\tif nodeID == signatureURI[1:] {\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"signed Reference.URI %q does not match ID %v\", signatureURI, nodeID)\n\t}\n\treturn fmt.Errorf(\"cannot lookup external URIs (%q)\", signatureURI)\n}\nVerify signature of decoded response\/\/ Package sp provides tools for buildin an SP such as serving metadata,\n\/\/ authenticating an assertion and building assertions for IdPs.\npackage saml\n\nimport (\n\t\"bytes\"\n\t\"compress\/flate\"\n\t\"encoding\/base64\"\n\t\"encoding\/xml\"\n\t\"fmt\"\n\t\"net\/url\"\n\t\"strings\"\n\n\t\"github.com\/goware\/saml\/xmlsec\"\n\t\"github.com\/pkg\/errors\"\n)\n\n\/\/ AuthnRequestURL creates SAML 2.0 AuthnRequest redirect URL,\n\/\/ aka SP-initiated login (SP->IdP).\n\/\/ The data is passed in the ?SAMLRequest query parameter and\n\/\/ the value is base64 encoded and deflate-compressed \n\/\/ XML element. The final redirect destination that will be invoked\n\/\/ on successful login is passed using ?RelayState query parameter.\nfunc (sp *ServiceProvider) AuthnRequestURL(relayState string) (string, error) {\n\tdestination, err := sp.GetIdPAuthResource()\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"failed to get IdP destination\")\n\t}\n\n\tauthnRequest, err := sp.NewAuthnRequest(destination)\n\tif err != nil {\n\t\treturn \"\", errors.Wrapf(err, \"failed to make auth request to %v\", destination)\n\t}\n\n\tbuf, err := xml.MarshalIndent(authnRequest, \"\", \"\\t\")\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"Failed to marshal auth request\")\n\t}\n\n\tflateBuf := bytes.NewBuffer(nil)\n\tflateWriter, err := flate.NewWriter(flateBuf, flate.DefaultCompression)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"failed to create flate writer\")\n\t}\n\n\t_, err = flateWriter.Write(buf)\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"failed to write to flate writer\")\n\t}\n\tflateWriter.Close()\n\tmessage := base64.StdEncoding.EncodeToString(flateBuf.Bytes())\n\n\tredirectURL := destination + fmt.Sprintf(`?RelayState=%s&SAMLRequest=%s`, url.QueryEscape(relayState), url.QueryEscape(message))\n\n\treturn redirectURL, nil\n}\n\n\/\/ MetadataXML returns SAML 2.0 Service Provider metadata XML.\nfunc (sp *ServiceProvider) MetadataXML() ([]byte, error) {\n\tmetadata, err := sp.Metadata()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not build nor serve metadata XML\")\n\t}\n\n\tout, err := xml.MarshalIndent(metadata, \"\", \"\\t\")\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not format metadata\")\n\t}\n\n\treturn out, nil\n}\n\nfunc (sp *ServiceProvider) possibleResponseIDs() []string {\n\tresponseIDs := []string{}\n\tif sp.AllowIdpInitiated {\n\t\tresponseIDs = append(responseIDs, \"\")\n\t}\n\treturn responseIDs\n}\n\nfunc (sp *ServiceProvider) verifySignature(plaintextMessage []byte) error {\n\tidpCertFile, err := sp.GetIdPCertFile()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = xmlsec.Verify(plaintextMessage, idpCertFile, &xmlsec.ValidationOptions{\n\t\tDTDFile: sp.DTDFile,\n\t})\n\tif err == nil {\n\t\t\/\/ No error, this message is OK\n\t\treturn nil\n\t}\n\n\t\/\/ We got an error...\n\tif !IsSecurityException(err, &sp.SecurityOpts) {\n\t\t\/\/ ...but it was not a security exception, so we ignore it and accept\n\t\t\/\/ the verification.\n\t\treturn nil\n\t}\n\n\treturn err\n}\n\nfunc (sp *ServiceProvider) AssertResponse(samlResponse string) (*Assertion, error) {\n\tnow := Now()\n\n\tsamlResponseXML, err := base64.StdEncoding.DecodeString(samlResponse)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to base64-decode SAML response\")\n\t}\n\n\tvar res Response\n\terr = xml.Unmarshal(samlResponseXML, &res)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to unmarshal XML document: %s\", string(samlResponseXML))\n\t}\n\n\t\/\/ TODO: Do we really need to check the IdP metadata here?\n\tif _, err := sp.GetIdPMetadata(); err != nil {\n\t\treturn nil, errors.Wrap(err, \"unable to retrieve IdP metadata\")\n\t}\n\n\t\/\/ Validate message.\n\n\tif res.Destination != sp.AcsURL {\n\t\t\/\/ Note: OneLogin triggers this error when the Recipient field\n\t\t\/\/ is left blank (or when not set to the correct ACS endpoint)\n\t\t\/\/ in the OneLogin SAML configuration page. OneLogin returns\n\t\t\/\/ Destination=\"{recipient}\" in the SAML reponse in this case.\n\t\treturn nil, errors.Errorf(\"Wrong ACS destination, expected %q, got %q\", sp.AcsURL, res.Destination)\n\t}\n\n\tif sp.IdPMetadata.EntityID != \"\" {\n\t\tif res.Issuer == nil {\n\t\t\treturn nil, errors.New(`Issuer does not match expected entity ID: Missing \"Issuer\" node`)\n\t\t}\n\t\tif res.Issuer.Value != sp.IdPMetadata.EntityID {\n\t\t\treturn nil, errors.Errorf(\"Issuer does not match expected entity ID: expected %q, got %q\", sp.IdPMetadata.EntityID, res.Issuer.Value)\n\t\t}\n\t}\n\n\tif res.Status.StatusCode.Value != \"urn:oasis:names:tc:SAML:2.0:status:Success\" {\n\t\treturn nil, errors.Errorf(\"Unexpected status code: %v\", res.Status.StatusCode.Value)\n\t}\n\n\texpectedResponse := false\n\tresponseIDs := sp.possibleResponseIDs()\n\tfor i := range responseIDs {\n\t\tif responseIDs[i] == res.InResponseTo {\n\t\t\texpectedResponse = true\n\t\t}\n\t}\n\tif len(responseIDs) == 1 && responseIDs[0] == \"\" {\n\t\texpectedResponse = true\n\t}\n\tif !expectedResponse && len(responseIDs) > 0 {\n\t\treturn nil, errors.Errorf(\"Expecting a proper InResponseTo value, got %#v\", responseIDs)\n\t}\n\n\t\/\/ Try getting the IdP's cert file before using it.\n\tif _, err := sp.GetIdPCertFile(); err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to get private key\")\n\t}\n\n\t\/\/ Validate signatures\n\n\tif res.Signature != nil {\n\t\terr := validateSignedNode(res.Signature, res.ID)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to validate Response + Signature\")\n\t\t}\n\t}\n\n\tif res.Assertion != nil && res.Assertion.Signature != nil {\n\t\terr := validateSignedNode(res.Assertion.Signature, res.Assertion.ID)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to validate Assertion + Signature\")\n\t\t}\n\t}\n\n\t\/\/ Validating message.\n\tsignatureOK := false\n\n\tif res.Signature != nil || (res.Assertion != nil && res.Assertion.Signature != nil) {\n\t\terr := sp.verifySignature(samlResponseXML)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"Unable to verify message signature\")\n\t\t} else {\n\t\t\tsignatureOK = true\n\t\t}\n\t}\n\n\t\/\/ Retrieve assertion\n\tvar assertion *Assertion\n\n\tif res.EncryptedAssertion != nil {\n\t\tkeyFile, err := sp.PrivkeyFile()\n\t\tif err != nil {\n\t\t\treturn nil, errors.Errorf(\"Failed to get private key: %v\", err)\n\t\t}\n\n\t\tplainTextAssertion, err := xmlsec.Decrypt(res.EncryptedAssertion.EncryptedData, keyFile)\n\t\tif err != nil {\n\t\t\tif IsSecurityException(err, &sp.SecurityOpts) {\n\t\t\t\treturn nil, errors.Wrap(err, \"Unable to decrypt message\")\n\t\t\t}\n\t\t}\n\n\t\tassertion = &Assertion{}\n\t\tif err := xml.Unmarshal(plainTextAssertion, assertion); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"Unable to parse assertion\")\n\t\t}\n\n\t\tif assertion.Signature != nil {\n\t\t\terr := validateSignedNode(assertion.Signature, assertion.ID)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Wrap(err, \"failed to validate Assertion + Signature\")\n\t\t\t}\n\n\t\t\terr = sp.verifySignature(plainTextAssertion)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, errors.Wrapf(err, \"Unable to verify assertion signature\")\n\t\t\t} else {\n\t\t\t\tsignatureOK = true\n\t\t\t}\n\t\t}\n\t} else {\n\t\tassertion = res.Assertion\n\t}\n\tif assertion == nil {\n\t\treturn nil, errors.New(\"Missing assertion\")\n\t}\n\n\t\/\/ Did we receive a signature?\n\tif !signatureOK {\n\t\treturn nil, errors.New(\"Unable to validate signature: node not found\")\n\t}\n\n\t\/\/ Validate assertion.\n\tswitch {\n\tcase sp.IdPMetadata.EntityID == \"\":\n\t\t\/\/ Skip issuer validation\n\tcase res.Issuer == nil:\n\t\treturn nil, errors.New(`Assertion issuer does not match expected entity ID: missing Assertion > Issuer`)\n\tcase assertion.Issuer.Value != sp.IdPMetadata.EntityID:\n\t\treturn nil, errors.Errorf(\"Assertion issuer does not match expected entity ID: Expected %q, got %q\", sp.IdPMetadata.EntityID, assertion.Issuer.Value)\n\t}\n\n\t\/\/ Validate recipient\n\t{\n\t\tvar err error\n\t\tswitch {\n\t\tcase assertion.Subject == nil:\n\t\t\terr = errors.New(`missing Assertion > Subject`)\n\t\tcase assertion.Subject.SubjectConfirmation == nil:\n\t\t\terr = errors.New(`missing Assertion > Subject > SubjectConfirmation`)\n\t\tcase assertion.Subject.SubjectConfirmation.SubjectConfirmationData.Recipient != sp.AcsURL:\n\t\t\terr = errors.Errorf(\"unexpected assertion recipient, expected %q, got %q\", sp.AcsURL, assertion.Subject.SubjectConfirmation.SubjectConfirmationData.Recipient)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrapf(err, \"invalid assertion recipient\")\n\t\t}\n\t}\n\n\t\/\/ Make sure we have Conditions\n\tif assertion.Conditions == nil {\n\t\treturn nil, errors.New(`missing Assertion > Conditions`)\n\t}\n\n\t\/\/ The NotBefore and NotOnOrAfter attributes specify time limits on the\n\t\/\/ validity of the assertion within the context of its profile(s) of use.\n\t\/\/ They do not guarantee that the statements in the assertion will be\n\t\/\/ correct or accurate throughout the validity period. The NotBefore\n\t\/\/ attribute specifies the time instant at which the validity interval\n\t\/\/ begins. The NotOnOrAfter attribute specifies the time instant at which\n\t\/\/ the validity interval has ended. If the value for either NotBefore or\n\t\/\/ NotOnOrAfter is omitted, then it is considered unspecified.\n\t{\n\t\tvalidFrom := assertion.Conditions.NotBefore\n\t\tif !validFrom.IsZero() && validFrom.After(now.Add(ClockDriftTolerance)) {\n\t\t\treturn nil, errors.Errorf(\"Assertion conditions are not valid yet, got %v, current time is %v\", validFrom, now)\n\t\t}\n\t}\n\n\t{\n\t\tvalidUntil := assertion.Conditions.NotOnOrAfter\n\t\tif !validUntil.IsZero() && validUntil.Before(now.Add(-ClockDriftTolerance)) {\n\t\t\treturn nil, errors.Errorf(\"Assertion conditions already expired, got %v current time is %v, extra time is %v\", validUntil, now, now.Add(-ClockDriftTolerance))\n\t\t}\n\t}\n\n\t\/\/ A time instant at which the subject can no longer be confirmed. The time\n\t\/\/ value is encoded in UTC, as described in Section 1.3.3.\n\t\/\/\n\t\/\/ Note that the time period specified by the optional NotBefore and\n\t\/\/ NotOnOrAfter attributes, if present, SHOULD fall within the overall\n\t\/\/ assertion validity period as specified by the element's NotBefore and\n\t\/\/ NotOnOrAfter attributes. If both attributes are present, the value for\n\t\/\/ NotBefore MUST be less than (earlier than) the value for NotOnOrAfter.\n\n\tif validUntil := assertion.Subject.SubjectConfirmation.SubjectConfirmationData.NotOnOrAfter; validUntil.Before(now.Add(-ClockDriftTolerance)) {\n\t\terr := errors.Errorf(\"Assertion conditions already expired, got %v current time is %v\", validUntil, now)\n\t\treturn nil, errors.Wrap(err, \"Assertion conditions already expired\")\n\t}\n\n\t\/\/ if assertion.Conditions != nil && assertion.Conditions.AudienceRestriction != nil {\n\t\/\/ if assertion.Conditions.AudienceRestriction.Audience.Value != sp.MetadataURL {\n\t\/\/ returnt.Errorf(\"Audience restriction mismatch, got %q, expected %q\", assertion.Conditions.AudienceRestriction.Audience.Value, sp.MetadataURL), errors.New(\"Audience restriction mismatch\")\n\t\/\/ }\n\t\/\/ }\n\n\texpectedResponse = false\n\tfor i := range responseIDs {\n\t\tif responseIDs[i] == assertion.Subject.SubjectConfirmation.SubjectConfirmationData.InResponseTo {\n\t\t\texpectedResponse = true\n\t\t}\n\t}\n\tif len(responseIDs) == 1 && responseIDs[0] == \"\" {\n\t\texpectedResponse = true\n\t}\n\n\tif !expectedResponse && len(responseIDs) > 0 {\n\t\treturn nil, errors.New(\"Unexpected assertion InResponseTo value\")\n\t}\n\n\treturn assertion, nil\n}\n\nfunc validateSignedNode(signature *xmlsec.Signature, nodeID string) error {\n\tsignatureURI := signature.Reference.URI\n\tif signatureURI == \"\" {\n\t\treturn nil\n\t}\n\tif strings.HasPrefix(signatureURI, \"#\") {\n\t\tif nodeID == signatureURI[1:] {\n\t\t\treturn nil\n\t\t}\n\t\treturn fmt.Errorf(\"signed Reference.URI %q does not match ID %v\", signatureURI, nodeID)\n\t}\n\treturn fmt.Errorf(\"cannot lookup external URIs (%q)\", signatureURI)\n}\n<|endoftext|>"} {"text":"package space\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/pivotalservices\/cf-mgmt\/cloudcontroller\"\n\t\"github.com\/pivotalservices\/cf-mgmt\/ldap\"\n\t\"github.com\/pivotalservices\/cf-mgmt\/uaa\"\n\t\"github.com\/xchapter7x\/lo\"\n)\n\n\/\/ UserMgr - interface type encapsulating Update space users behavior\ntype UserMgr interface {\n\tUpdateSpaceUsers(config *ldap.Config, uaaUsers map[string]string, updateUsersInput UpdateUsersInput) error\n}\n\n\/\/ NewUserManager -\nfunc NewUserManager(\n\tcloudController cloudcontroller.Manager,\n\tldapMgr ldap.Manager,\n\tuaaMgr uaa.Manager) UserMgr {\n\treturn &UserManager{\n\t\tcloudController: cloudController,\n\t\tLdapMgr: ldapMgr,\n\t\tuaaMgr: uaaMgr,\n\t}\n}\n\ntype UserManager struct {\n\tcloudController cloudcontroller.Manager\n\tLdapMgr ldap.Manager\n\tuaaMgr uaa.Manager\n}\n\n\/\/ UpdateSpaceUserInput\ntype UpdateUsersInput struct {\n\tSpaceGUID string\n\tOrgGUID string\n\tRole string\n\tLdapUsers, Users, LdapGroupNames, SamlUsers []string\n\tSpaceName string\n\tOrgName string\n\tRemoveUsers bool\n}\n\n\/\/UpdateSpaceUsers Update space users\nfunc (m *UserManager) UpdateSpaceUsers(config *ldap.Config, uaaUsers map[string]string, updateUsersInput UpdateUsersInput) error {\n\tspaceUsers, err := m.cloudController.GetCFUsers(updateUsersInput.SpaceGUID, SPACES, updateUsersInput.Role)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlo.G.Debugf(\"SpaceUsers before: %v\", spaceUsers)\n\tif config.Enabled {\n\t\tvar ldapUsers []ldap.User\n\t\tldapUsers, err = m.getLdapUsers(config, updateUsersInput.LdapGroupNames, updateUsersInput.LdapUsers)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlo.G.Debugf(\"LdapUsers: %v\", ldapUsers)\n\t\tfor _, user := range ldapUsers {\n\t\t\terr = m.updateLdapUser(config, updateUsersInput.SpaceGUID, updateUsersInput.OrgGUID, updateUsersInput.Role, updateUsersInput.OrgName, updateUsersInput.SpaceName, uaaUsers, user, spaceUsers)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t} else {\n\t\tlo.G.Debug(\"Skipping LDAP sync as LDAP is disabled (enable by updating config\/ldap.yml)\")\n\t}\n\tfor _, userID := range updateUsersInput.Users {\n\t\tlowerUserID := strings.ToLower(userID)\n\t\tif _, userExists := uaaUsers[lowerUserID]; !userExists {\n\t\t\treturn fmt.Errorf(\"user %s doesn't exist in cloud foundry, so must add internal user first\", lowerUserID)\n\t\t}\n\t\tif _, ok := spaceUsers[lowerUserID]; !ok {\n\t\t\tif err = m.addUserToOrgAndRole(userID, updateUsersInput.OrgGUID, updateUsersInput.SpaceGUID, updateUsersInput.Role, updateUsersInput.OrgName, updateUsersInput.SpaceName); err != nil {\n\t\t\t\tlo.G.Error(err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tdelete(spaceUsers, lowerUserID)\n\t\t}\n\t}\n\n\tfor _, userEmail := range updateUsersInput.SamlUsers {\n\t\tlowerUserEmail := strings.ToLower(userEmail)\n\t\tif _, userExists := uaaUsers[lowerUserEmail]; !userExists {\n\t\t\tlo.G.Debug(\"User\", userEmail, \"doesn't exist in cloud foundry, so creating user\")\n\t\t\tif err = m.uaaMgr.CreateExternalUser(userEmail, userEmail, userEmail, config.Origin); err != nil {\n\t\t\t\tlo.G.Errorf(\"Unable to create user [%s] due to error %s\", userEmail, err.Error())\n\t\t\t\treturn err\n\t\t\t} else {\n\t\t\t\tuaaUsers[userEmail] = userEmail\n\t\t\t}\n\t\t}\n\t\tif _, ok := spaceUsers[lowerUserEmail]; !ok {\n\t\t\tif err = m.addUserToOrgAndRole(userEmail, updateUsersInput.OrgGUID, updateUsersInput.SpaceGUID, updateUsersInput.Role, updateUsersInput.OrgName, updateUsersInput.SpaceName); err != nil {\n\t\t\t\tlo.G.Error(err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tdelete(spaceUsers, lowerUserEmail)\n\t\t}\n\t}\n\tif updateUsersInput.RemoveUsers {\n\t\tlo.G.Debugf(\"Deleting users for org\/space: %s\/%s\", updateUsersInput.OrgName, updateUsersInput.SpaceName)\n\t\tfor spaceUser, spaceUserGUID := range spaceUsers {\n\t\t\tlo.G.Infof(\"removing user: %s from space: %s and role: %s\", spaceUser, updateUsersInput.SpaceName, updateUsersInput.Role)\n\t\t\terr = m.cloudController.RemoveCFUser(updateUsersInput.SpaceGUID, SPACES, spaceUserGUID, updateUsersInput.Role)\n\t\t\tif err != nil {\n\t\t\t\tlo.G.Errorf(\"Unable to remove user : %s from space %s role in space : %s\", spaceUser, updateUsersInput.Role, updateUsersInput.SpaceName)\n\t\t\t\tlo.G.Errorf(\"Cloud controller API error: %s\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t} else {\n\t\tlo.G.Debugf(\"Not removing users. Set enable-remove-users: true to spaceConfig for org\/space: %s\/%s\", updateUsersInput.OrgName, updateUsersInput.SpaceName)\n\t}\n\n\tlo.G.Debugf(\"SpaceUsers after: %v\", spaceUsers)\n\treturn nil\n}\n\nfunc (m *UserManager) updateLdapUser(config *ldap.Config, spaceGUID, orgGUID string,\n\trole string, orgName, spaceName string, uaaUsers map[string]string,\n\tuser ldap.User, spaceUsers map[string]string) error {\n\n\tuserID := user.UserID\n\texternalID := user.UserDN\n\tif config.Origin != \"ldap\" {\n\t\tuserID = user.Email\n\t\texternalID = user.Email\n\t} else {\n\t\tif user.Email == \"\" {\n\t\t\tuser.Email = fmt.Sprintf(\"%s@user.from.ldap.cf\", userID)\n\t\t}\n\t}\n\tuserID = strings.ToLower(userID)\n\n\tif _, ok := spaceUsers[userID]; !ok {\n\t\tlo.G.Debugf(\"User[%s] not found in: %v\", userID, spaceUsers)\n\t\tif _, userExists := uaaUsers[userID]; !userExists {\n\t\t\tlo.G.Debug(\"User\", userID, \"doesn't exist in cloud foundry, so creating user\")\n\t\t\tif err := m.uaaMgr.CreateExternalUser(userID, user.Email, externalID, config.Origin); err != nil {\n\t\t\t\tlo.G.Errorf(\"Unable to create user [%s] due to error %s\", userID, err.Error())\n\t\t\t} else {\n\t\t\t\tuaaUsers[userID] = userID\n\t\t\t\tif err := m.addUserToOrgAndRole(userID, orgGUID, spaceGUID, role, orgName, spaceName); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif err := m.addUserToOrgAndRole(userID, orgGUID, spaceGUID, role, orgName, spaceName); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t} else {\n\t\tdelete(spaceUsers, userID)\n\t}\n\treturn nil\n}\n\nfunc (m *UserManager) getLdapUsers(config *ldap.Config, groupNames []string, userList []string) ([]ldap.User, error) {\n\tusers := []ldap.User{}\n\tfor _, groupName := range groupNames {\n\t\tif groupName != \"\" {\n\t\t\tlo.G.Debug(\"Finding LDAP user for group:\", groupName)\n\t\t\tif groupUsers, err := m.LdapMgr.GetUserIDs(config, groupName); err == nil {\n\t\t\t\tusers = append(users, groupUsers...)\n\t\t\t} else {\n\t\t\t\tlo.G.Warning(err)\n\t\t\t}\n\t\t}\n\t}\n\tfor _, user := range userList {\n\t\tif ldapUser, err := m.LdapMgr.GetUser(config, user); err == nil {\n\t\t\tif ldapUser != nil {\n\t\t\t\tusers = append(users, *ldapUser)\n\t\t\t}\n\t\t} else {\n\t\t\tlo.G.Warning(err)\n\t\t}\n\t}\n\treturn users, nil\n}\n\nfunc (m *UserManager) addUserToOrgAndRole(userID, orgGUID, spaceGUID, role, orgName, spaceName string) error {\n\tif err := m.cloudController.AddUserToOrg(userID, orgGUID); err != nil {\n\t\tlo.G.Error(err)\n\t\treturn err\n\t}\n\tlo.G.Infof(\"Adding user: %s to org\/space: %s\/%s with role: %s\", userID, orgName, spaceName, role)\n\tif err := m.cloudController.AddUserToSpaceRole(userID, role, spaceGUID); err != nil {\n\t\tlo.G.Error(err)\n\t\treturn err\n\t}\n\treturn nil\n}\nadding logic to prevent duplicate users from being aggregated together from ldap groups\/users listpackage space\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com\/pivotalservices\/cf-mgmt\/cloudcontroller\"\n\t\"github.com\/pivotalservices\/cf-mgmt\/ldap\"\n\t\"github.com\/pivotalservices\/cf-mgmt\/uaa\"\n\t\"github.com\/xchapter7x\/lo\"\n)\n\n\/\/ UserMgr - interface type encapsulating Update space users behavior\ntype UserMgr interface {\n\tUpdateSpaceUsers(config *ldap.Config, uaaUsers map[string]string, updateUsersInput UpdateUsersInput) error\n}\n\n\/\/ NewUserManager -\nfunc NewUserManager(\n\tcloudController cloudcontroller.Manager,\n\tldapMgr ldap.Manager,\n\tuaaMgr uaa.Manager) UserMgr {\n\treturn &UserManager{\n\t\tcloudController: cloudController,\n\t\tLdapMgr: ldapMgr,\n\t\tuaaMgr: uaaMgr,\n\t}\n}\n\ntype UserManager struct {\n\tcloudController cloudcontroller.Manager\n\tLdapMgr ldap.Manager\n\tuaaMgr uaa.Manager\n}\n\n\/\/ UpdateSpaceUserInput\ntype UpdateUsersInput struct {\n\tSpaceGUID string\n\tOrgGUID string\n\tRole string\n\tLdapUsers, Users, LdapGroupNames, SamlUsers []string\n\tSpaceName string\n\tOrgName string\n\tRemoveUsers bool\n}\n\n\/\/UpdateSpaceUsers Update space users\nfunc (m *UserManager) UpdateSpaceUsers(config *ldap.Config, uaaUsers map[string]string, updateUsersInput UpdateUsersInput) error {\n\tspaceUsers, err := m.cloudController.GetCFUsers(updateUsersInput.SpaceGUID, SPACES, updateUsersInput.Role)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlo.G.Debugf(\"SpaceUsers before: %v\", spaceUsers)\n\tif config.Enabled {\n\t\tvar ldapUsers []ldap.User\n\t\tldapUsers, err = m.getLdapUsers(config, updateUsersInput.LdapGroupNames, updateUsersInput.LdapUsers)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlo.G.Debugf(\"LdapUsers: %v\", ldapUsers)\n\t\tfor _, user := range ldapUsers {\n\t\t\terr = m.updateLdapUser(config, updateUsersInput.SpaceGUID, updateUsersInput.OrgGUID, updateUsersInput.Role, updateUsersInput.OrgName, updateUsersInput.SpaceName, uaaUsers, user, spaceUsers)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t} else {\n\t\tlo.G.Debug(\"Skipping LDAP sync as LDAP is disabled (enable by updating config\/ldap.yml)\")\n\t}\n\tfor _, userID := range updateUsersInput.Users {\n\t\tlowerUserID := strings.ToLower(userID)\n\t\tif _, userExists := uaaUsers[lowerUserID]; !userExists {\n\t\t\treturn fmt.Errorf(\"user %s doesn't exist in cloud foundry, so must add internal user first\", lowerUserID)\n\t\t}\n\t\tif _, ok := spaceUsers[lowerUserID]; !ok {\n\t\t\tif err = m.addUserToOrgAndRole(userID, updateUsersInput.OrgGUID, updateUsersInput.SpaceGUID, updateUsersInput.Role, updateUsersInput.OrgName, updateUsersInput.SpaceName); err != nil {\n\t\t\t\tlo.G.Error(err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tdelete(spaceUsers, lowerUserID)\n\t\t}\n\t}\n\n\tfor _, userEmail := range updateUsersInput.SamlUsers {\n\t\tlowerUserEmail := strings.ToLower(userEmail)\n\t\tif _, userExists := uaaUsers[lowerUserEmail]; !userExists {\n\t\t\tlo.G.Debug(\"User\", userEmail, \"doesn't exist in cloud foundry, so creating user\")\n\t\t\tif err = m.uaaMgr.CreateExternalUser(userEmail, userEmail, userEmail, config.Origin); err != nil {\n\t\t\t\tlo.G.Errorf(\"Unable to create user [%s] due to error %s\", userEmail, err.Error())\n\t\t\t\treturn err\n\t\t\t} else {\n\t\t\t\tuaaUsers[userEmail] = userEmail\n\t\t\t}\n\t\t}\n\t\tif _, ok := spaceUsers[lowerUserEmail]; !ok {\n\t\t\tif err = m.addUserToOrgAndRole(userEmail, updateUsersInput.OrgGUID, updateUsersInput.SpaceGUID, updateUsersInput.Role, updateUsersInput.OrgName, updateUsersInput.SpaceName); err != nil {\n\t\t\t\tlo.G.Error(err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tdelete(spaceUsers, lowerUserEmail)\n\t\t}\n\t}\n\tif updateUsersInput.RemoveUsers {\n\t\tlo.G.Debugf(\"Deleting users for org\/space: %s\/%s\", updateUsersInput.OrgName, updateUsersInput.SpaceName)\n\t\tfor spaceUser, spaceUserGUID := range spaceUsers {\n\t\t\tlo.G.Infof(\"removing user: %s from space: %s and role: %s\", spaceUser, updateUsersInput.SpaceName, updateUsersInput.Role)\n\t\t\terr = m.cloudController.RemoveCFUser(updateUsersInput.SpaceGUID, SPACES, spaceUserGUID, updateUsersInput.Role)\n\t\t\tif err != nil {\n\t\t\t\tlo.G.Errorf(\"Unable to remove user : %s from space %s role in space : %s\", spaceUser, updateUsersInput.Role, updateUsersInput.SpaceName)\n\t\t\t\tlo.G.Errorf(\"Cloud controller API error: %s\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t} else {\n\t\tlo.G.Debugf(\"Not removing users. Set enable-remove-users: true to spaceConfig for org\/space: %s\/%s\", updateUsersInput.OrgName, updateUsersInput.SpaceName)\n\t}\n\n\tlo.G.Debugf(\"SpaceUsers after: %v\", spaceUsers)\n\treturn nil\n}\n\nfunc (m *UserManager) updateLdapUser(config *ldap.Config, spaceGUID, orgGUID string,\n\trole string, orgName, spaceName string, uaaUsers map[string]string,\n\tuser ldap.User, spaceUsers map[string]string) error {\n\n\tuserID := user.UserID\n\texternalID := user.UserDN\n\tif config.Origin != \"ldap\" {\n\t\tuserID = user.Email\n\t\texternalID = user.Email\n\t} else {\n\t\tif user.Email == \"\" {\n\t\t\tuser.Email = fmt.Sprintf(\"%s@user.from.ldap.cf\", userID)\n\t\t}\n\t}\n\tuserID = strings.ToLower(userID)\n\n\tif _, ok := spaceUsers[userID]; !ok {\n\t\tlo.G.Debugf(\"User[%s] not found in: %v\", userID, spaceUsers)\n\t\tif _, userExists := uaaUsers[userID]; !userExists {\n\t\t\tlo.G.Debug(\"User\", userID, \"doesn't exist in cloud foundry, so creating user\")\n\t\t\tif err := m.uaaMgr.CreateExternalUser(userID, user.Email, externalID, config.Origin); err != nil {\n\t\t\t\tlo.G.Errorf(\"Unable to create user [%s] due to error %s\", userID, err.Error())\n\t\t\t} else {\n\t\t\t\tuaaUsers[userID] = userID\n\t\t\t\tif err := m.addUserToOrgAndRole(userID, orgGUID, spaceGUID, role, orgName, spaceName); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif err := m.addUserToOrgAndRole(userID, orgGUID, spaceGUID, role, orgName, spaceName); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t} else {\n\t\tdelete(spaceUsers, userID)\n\t}\n\treturn nil\n}\n\nfunc (m *UserManager) getLdapUsers(config *ldap.Config, groupNames []string, userList []string) ([]ldap.User, error) {\n\tuniqueUsers := make(map[string]string)\n\tusers := []ldap.User{}\n\tfor _, groupName := range groupNames {\n\t\tif groupName != \"\" {\n\t\t\tlo.G.Debug(\"Finding LDAP user for group:\", groupName)\n\t\t\tif groupUsers, err := m.LdapMgr.GetUserIDs(config, groupName); err == nil {\n\t\t\t\tfor _, user := range groupUsers {\n\t\t\t\t\tif _, ok := uniqueUsers[user.Email]; !ok {\n\t\t\t\t\t\tusers = append(users, user)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlo.G.Debugf(\"User %v is already added to list\", user)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlo.G.Warning(err)\n\t\t\t}\n\t\t}\n\t}\n\tfor _, user := range userList {\n\t\tif ldapUser, err := m.LdapMgr.GetUser(config, user); err == nil {\n\t\t\tif ldapUser != nil {\n\t\t\t\tif _, ok := uniqueUsers[ldapUser.Email]; !ok {\n\t\t\t\t\tusers = append(users, *ldapUser)\n\t\t\t\t} else {\n\t\t\t\t\tlo.G.Debugf(\"User %v is already added to list\", ldapUser)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tlo.G.Warning(err)\n\t\t}\n\t}\n\treturn users, nil\n}\n\nfunc (m *UserManager) addUserToOrgAndRole(userID, orgGUID, spaceGUID, role, orgName, spaceName string) error {\n\tif err := m.cloudController.AddUserToOrg(userID, orgGUID); err != nil {\n\t\tlo.G.Error(err)\n\t\treturn err\n\t}\n\tlo.G.Infof(\"Adding user: %s to org\/space: %s\/%s with role: %s\", userID, orgName, spaceName, role)\n\tif err := m.cloudController.AddUserToSpaceRole(userID, role, spaceGUID); err != nil {\n\t\tlo.G.Error(err)\n\t\treturn err\n\t}\n\treturn nil\n}\n<|endoftext|>"} {"text":"package routes\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"strings\"\n\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/petergtz\/bitsgo\/logger\"\n\t\"github.com\/uber-go\/zap\"\n)\n\ntype ResourceHandler struct {\n\tblobstore Blobstore\n\tresourceType string\n}\n\nfunc (handler *ResourceHandler) Put(responseWriter http.ResponseWriter, request *http.Request) {\n\tvar (\n\t\tredirectLocation string\n\t\te error\n\t)\n\tif strings.Contains(request.Header.Get(\"Content-Type\"), \"multipart\/form-data\") {\n\t\tlogger.From(request).Info(\"Multipart upload\")\n\t\tfile, _, e := request.FormFile(handler.resourceType)\n\t\tif e != nil {\n\t\t\tbadRequest(responseWriter, \"Could not retrieve '%s' form parameter\", handler.resourceType)\n\t\t\treturn\n\t\t}\n\t\tdefer file.Close()\n\n\t\tredirectLocation, e = handler.blobstore.Put(mux.Vars(request)[\"identifier\"], file)\n\t} else {\n\t\tlogger.From(request).Info(\"Copy source guid\")\n\t\tredirectLocation, e = handler.copySourceGuid(request.Body, mux.Vars(request)[\"identifier\"], responseWriter)\n\t}\n\n\tswitch e.(type) {\n\tcase *NotFoundError:\n\t\tresponseWriter.WriteHeader(http.StatusNotFound)\n\t\treturn\n\tcase error:\n\t\tinternalServerError(responseWriter, e)\n\t\treturn\n\t}\n\n\tif redirectLocation != \"\" {\n\t\tredirect(responseWriter, redirectLocation)\n\t\treturn\n\t}\n\n\tresponseWriter.WriteHeader(http.StatusCreated)\n}\n\nfunc (handler *ResourceHandler) copySourceGuid(body io.ReadCloser, targetGuid string, responseWriter http.ResponseWriter) (string, error) {\n\tif body == nil {\n\t\tbadRequest(responseWriter, \"Body must contain source_guid when request is not multipart\/form-data\")\n\t\treturn \"\", nil\n\t}\n\tdefer body.Close()\n\tcontent, e := ioutil.ReadAll(body)\n\tif e != nil {\n\t\tinternalServerError(responseWriter, e)\n\t\treturn \"\", nil\n\t}\n\tvar payload struct {\n\t\tSourceGuid string `json:\"source_guid\"`\n\t}\n\te = json.Unmarshal(content, &payload)\n\tif e != nil {\n\t\tbadRequest(responseWriter, \"Body must be valid JSON when request is not multipart\/form-data. %+v\", e)\n\t\treturn \"\", nil\n\t}\n\treturn handler.blobstore.Copy(payload.SourceGuid, targetGuid)\n}\n\nfunc (handler *ResourceHandler) Head(responseWriter http.ResponseWriter, request *http.Request) {\n\tbody, redirectLocation, e := handler.blobstore.Get(mux.Vars(request)[\"identifier\"])\n\tswitch e.(type) {\n\tcase *NotFoundError:\n\t\tresponseWriter.WriteHeader(http.StatusNotFound)\n\t\treturn\n\tcase error:\n\t\tinternalServerError(responseWriter, e)\n\t\treturn\n\t}\n\tif redirectLocation != \"\" {\n\t\tredirect(responseWriter, redirectLocation)\n\t\treturn\n\t}\n\tdefer body.Close()\n\tresponseWriter.WriteHeader(http.StatusOK)\n}\n\nfunc (handler *ResourceHandler) Get(responseWriter http.ResponseWriter, request *http.Request) {\n\tbody, redirectLocation, e := handler.blobstore.Get(mux.Vars(request)[\"identifier\"])\n\tswitch e.(type) {\n\tcase *NotFoundError:\n\t\tresponseWriter.WriteHeader(http.StatusNotFound)\n\t\treturn\n\tcase error:\n\t\tinternalServerError(responseWriter, e)\n\t\treturn\n\t}\n\tif redirectLocation != \"\" {\n\t\tredirect(responseWriter, redirectLocation)\n\t\treturn\n\t}\n\tdefer body.Close()\n\tresponseWriter.WriteHeader(http.StatusOK)\n\tio.Copy(responseWriter, body)\n}\n\nfunc (handler *ResourceHandler) Delete(responseWriter http.ResponseWriter, request *http.Request) {\n\texists, e := handler.blobstore.Exists(mux.Vars(request)[\"identifier\"])\n\tif e != nil {\n\t\tinternalServerError(responseWriter, e)\n\t\treturn\n\t}\n\tif !exists {\n\t\tresponseWriter.WriteHeader(http.StatusNotFound)\n\t\treturn\n\t}\n\n\te = handler.blobstore.Delete(mux.Vars(request)[\"identifier\"])\n\tif e != nil {\n\t\tinternalServerError(responseWriter, e)\n\t\treturn\n\t}\n\tresponseWriter.WriteHeader(http.StatusNoContent)\n}\n\nfunc (handler *ResourceHandler) DeleteDir(responseWriter http.ResponseWriter, request *http.Request) {\n\te := handler.blobstore.DeletePrefix(mux.Vars(request)[\"identifier\"])\n\tif e != nil {\n\t\twriteResponseBasedOnError(responseWriter, e)\n\t\treturn\n\t}\n\tresponseWriter.WriteHeader(http.StatusNoContent)\n}\n\nfunc writeResponseBasedOnError(responseWriter http.ResponseWriter, e error) {\n\tswitch e.(type) {\n\tcase *NotFoundError:\n\t\tresponseWriter.WriteHeader(http.StatusNoContent)\n\t\treturn\n\tcase error:\n\t\tinternalServerError(responseWriter, e)\n\t\treturn\n\t}\n\tresponseWriter.WriteHeader(http.StatusNoContent)\n}\n\nfunc redirect(responseWriter http.ResponseWriter, redirectLocation string) {\n\tresponseWriter.Header().Set(\"Location\", redirectLocation)\n\tresponseWriter.WriteHeader(http.StatusFound)\n}\n\nfunc internalServerError(responseWriter http.ResponseWriter, e error) {\n\tlogger.Log.Error(\"Internal Server Error.\", zap.String(\"error\", fmt.Sprintf(\"%+v\", e)))\n\tresponseWriter.WriteHeader(http.StatusInternalServerError)\n}\n\nfunc badRequest(responseWriter http.ResponseWriter, message string, args ...interface{}) {\n\tresponseWriter.WriteHeader(http.StatusBadRequest)\n\tfmt.Fprintf(responseWriter, message, args...)\n}\nRefactor ResourceHandler Put methodpackage routes\n\nimport (\n\t\"encoding\/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"strings\"\n\n\t\"github.com\/gorilla\/mux\"\n\t\"github.com\/petergtz\/bitsgo\/logger\"\n\t\"github.com\/uber-go\/zap\"\n)\n\ntype ResourceHandler struct {\n\tblobstore Blobstore\n\tresourceType string\n}\n\nfunc (handler *ResourceHandler) Put(responseWriter http.ResponseWriter, request *http.Request) {\n\tif strings.Contains(request.Header.Get(\"Content-Type\"), \"multipart\/form-data\") {\n\t\tlogger.From(request).Debug(\"Multipart upload\")\n\t\thandler.uploadMultipart(responseWriter, request)\n\t} else {\n\t\tlogger.From(request).Debug(\"Copy source guid\")\n\t\thandler.copySourceGuid(responseWriter, request)\n\t}\n}\n\nfunc (handler *ResourceHandler) uploadMultipart(responseWriter http.ResponseWriter, request *http.Request) {\n\tfile, _, e := request.FormFile(handler.resourceType)\n\tif e != nil {\n\t\tbadRequest(responseWriter, \"Could not retrieve '%s' form parameter\", handler.resourceType)\n\t\treturn\n\t}\n\tdefer file.Close()\n\n\tredirectLocation, e := handler.blobstore.Put(mux.Vars(request)[\"identifier\"], file)\n\thandleBlobstoreResult(redirectLocation, e, responseWriter)\n}\n\nfunc (handler *ResourceHandler) copySourceGuid(responseWriter http.ResponseWriter, request *http.Request) {\n\tif request.Body == nil {\n\t\tbadRequest(responseWriter, \"Body must contain source_guid when request is not multipart\/form-data\")\n\t\treturn\n\t}\n\tsourceGuid := sourceGuidFrom(request.Body, responseWriter)\n\tif sourceGuid == \"\" {\n\t\treturn \/\/ response is already handled in sourceGuidFrom\n\t}\n\tredirectLocation, e := handler.blobstore.Copy(sourceGuid, mux.Vars(request)[\"identifier\"])\n\tif _, isNotFoundError := e.(*NotFoundError); isNotFoundError {\n\t\tresponseWriter.WriteHeader(http.StatusNotFound)\n\t\treturn\n\t}\n\thandleBlobstoreResult(redirectLocation, e, responseWriter)\n}\n\nfunc sourceGuidFrom(body io.ReadCloser, responseWriter http.ResponseWriter) string {\n\tdefer body.Close()\n\tcontent, e := ioutil.ReadAll(body)\n\tif e != nil {\n\t\tinternalServerError(responseWriter, e)\n\t\treturn \"\"\n\t}\n\tvar payload struct {\n\t\tSourceGuid string `json:\"source_guid\"`\n\t}\n\te = json.Unmarshal(content, &payload)\n\tif e != nil {\n\t\tbadRequest(responseWriter, \"Body must be valid JSON when request is not multipart\/form-data. %+v\", e)\n\t\treturn \"\"\n\t}\n\treturn payload.SourceGuid\n}\n\nfunc handleBlobstoreResult(redirectLocation string, e error, responseWriter http.ResponseWriter) {\n\tif e != nil {\n\t\tinternalServerError(responseWriter, e)\n\t\treturn\n\t}\n\n\tif redirectLocation != \"\" {\n\t\tredirect(responseWriter, redirectLocation)\n\t\treturn\n\t}\n\n\tresponseWriter.WriteHeader(http.StatusCreated)\n}\n\nfunc (handler *ResourceHandler) Head(responseWriter http.ResponseWriter, request *http.Request) {\n\tredirectLocation, e := handler.blobstore.Head(mux.Vars(request)[\"identifier\"])\n\tswitch e.(type) {\n\tcase *NotFoundError:\n\t\tresponseWriter.WriteHeader(http.StatusNotFound)\n\t\treturn\n\tcase error:\n\t\tinternalServerError(responseWriter, e)\n\t\treturn\n\t}\n\tif redirectLocation != \"\" {\n\t\tredirect(responseWriter, redirectLocation)\n\t\treturn\n\t}\n\tresponseWriter.WriteHeader(http.StatusOK)\n}\n\nfunc (handler *ResourceHandler) Get(responseWriter http.ResponseWriter, request *http.Request) {\n\tbody, redirectLocation, e := handler.blobstore.Get(mux.Vars(request)[\"identifier\"])\n\tswitch e.(type) {\n\tcase *NotFoundError:\n\t\tresponseWriter.WriteHeader(http.StatusNotFound)\n\t\treturn\n\tcase error:\n\t\tinternalServerError(responseWriter, e)\n\t\treturn\n\t}\n\tif redirectLocation != \"\" {\n\t\tredirect(responseWriter, redirectLocation)\n\t\treturn\n\t}\n\tdefer body.Close()\n\tresponseWriter.WriteHeader(http.StatusOK)\n\tio.Copy(responseWriter, body)\n}\n\nfunc (handler *ResourceHandler) Delete(responseWriter http.ResponseWriter, request *http.Request) {\n\texists, e := handler.blobstore.Exists(mux.Vars(request)[\"identifier\"])\n\tif e != nil {\n\t\tinternalServerError(responseWriter, e)\n\t\treturn\n\t}\n\tif !exists {\n\t\tresponseWriter.WriteHeader(http.StatusNotFound)\n\t\treturn\n\t}\n\n\te = handler.blobstore.Delete(mux.Vars(request)[\"identifier\"])\n\tif e != nil {\n\t\tinternalServerError(responseWriter, e)\n\t\treturn\n\t}\n\tresponseWriter.WriteHeader(http.StatusNoContent)\n}\n\nfunc (handler *ResourceHandler) DeleteDir(responseWriter http.ResponseWriter, request *http.Request) {\n\te := handler.blobstore.DeletePrefix(mux.Vars(request)[\"identifier\"])\n\tif e != nil {\n\t\twriteResponseBasedOnError(responseWriter, e)\n\t\treturn\n\t}\n\tresponseWriter.WriteHeader(http.StatusNoContent)\n}\n\nfunc writeResponseBasedOnError(responseWriter http.ResponseWriter, e error) {\n\tswitch e.(type) {\n\tcase *NotFoundError:\n\t\tresponseWriter.WriteHeader(http.StatusNoContent)\n\t\treturn\n\tcase error:\n\t\tinternalServerError(responseWriter, e)\n\t\treturn\n\t}\n\tresponseWriter.WriteHeader(http.StatusNoContent)\n}\n\nfunc redirect(responseWriter http.ResponseWriter, redirectLocation string) {\n\tresponseWriter.Header().Set(\"Location\", redirectLocation)\n\tresponseWriter.WriteHeader(http.StatusFound)\n}\n\nfunc internalServerError(responseWriter http.ResponseWriter, e error) {\n\tlogger.Log.Error(\"Internal Server Error.\", zap.String(\"error\", fmt.Sprintf(\"%+v\", e)))\n\tresponseWriter.WriteHeader(http.StatusInternalServerError)\n}\n\nfunc badRequest(responseWriter http.ResponseWriter, message string, args ...interface{}) {\n\tresponseWriter.WriteHeader(http.StatusBadRequest)\n\tfmt.Fprintf(responseWriter, message, args...)\n}\n<|endoftext|>"} {"text":"package main\n\nimport \"testing\"\n\nfunc TestSubMain_interrupt(t *testing.T) {\n\tt.Skip(\"This test isn't implemented for Windows yet\")\n}\n\n\/*************************************\n * Helper functions\n *************************************\/\n\nfunc startService(t *testing.T, serviceName string) {\n\trunCmd(t, \"net\", \"start\", serviceName)\n}\n\nfunc stopService(t *testing.T, serviceName string) {\n\trunCmd(t, \"net\", \"stop\", serviceName)\n}\nFix windows service tests s\/runCmd\/runOSCmd\/package main\n\nimport \"testing\"\n\nfunc TestSubMain_interrupt(t *testing.T) {\n\tt.Skip(\"This test isn't implemented for Windows yet\")\n}\n\n\/*************************************\n * Helper functions\n *************************************\/\n\nfunc startService(t *testing.T, serviceName string) {\n\trunOSCmd(t, \"net\", \"start\", serviceName)\n}\n\nfunc stopService(t *testing.T, serviceName string) {\n\trunOSCmd(t, \"net\", \"stop\", serviceName)\n}\n<|endoftext|>"} {"text":"package sphere\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/gin-gonic\/gin\"\n\t\"github.com\/gorilla\/websocket\"\n)\n\nvar (\n\taddress = func() string {\n\t\tl, _ := net.Listen(\"tcp\", \":0\")\n\t\tdefer l.Close()\n\t\treturn fmt.Sprintf(\"127.0.0.1:%d\", l.Addr().(*net.TCPAddr).Port)\n\t}()\n)\n\ntype TestSphereModel struct {\n\t*ChannelModel\n}\n\nfunc (m *TestSphereModel) Subscribe(room string, connection *Connection) bool {\n\treturn true\n}\n\nfunc (m *TestSphereModel) Disconnect(room string, connection *Connection) bool {\n\treturn true\n}\n\nfunc (m *TestSphereModel) Receive(event string, message string) (string, error) {\n\treturn \"you_got_me\", nil\n}\n\nfunc init() {\n\tgin.SetMode(gin.ReleaseMode)\n\ta := NewRedisBroker()\n\ts, r := NewSphere(a), gin.New()\n\ts.ChannelModels(&TestSphereModel{ExtendChannelModel(\"test\")})\n\tr.GET(\"\/sync\", func(c *gin.Context) {\n\t\ts.Handler(c.Writer, c.Request)\n\t})\n\tgo r.Run(address)\n}\n\nfunc CreateConnection() (c *websocket.Conn, response *http.Response, err error) {\n\tu, err := url.Parse(\"ws:\/\/\" + address + \"\/sync\")\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\trawConn, err := net.Dial(\"tcp\", u.Host)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\twsHeaders := http.Header{\n\t\t\"Origin\": {\"http:\/\/\" + address},\n\t}\n\treturn websocket.NewClient(rawConn, u, wsHeaders, 1024, 1024)\n}\n\nfunc TestSphereReady(t *testing.T) {\n\tcount := 0\n\tticker := time.NewTicker(time.Millisecond * 60)\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\ts, err := net.Dial(\"tcp\", address)\n\t\t\tdefer s.Close()\n\t\t\tif err == nil || count > 3 {\n\t\t\t\tdefer ticker.Stop()\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(\"Server could not get started\")\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tcount++\n\t}\n}\n\nfunc TestSphereConnection(t *testing.T) {\n\tc, _, err := CreateConnection()\n\tif err != nil {\n\t\tt.Fatal(err.Error())\n\t}\n\tdefer c.Close()\n}\n\nfunc TestSphereSendMessage(t *testing.T) {\n\tc, _, err := CreateConnection()\n\tif err != nil {\n\t\tt.Fatal(err.Error())\n\t}\n\tdefer c.Close()\n\tp := &Packet{Type: PacketTypePing}\n\tres, err := p.toJSON()\n\tif err != nil {\n\t\tt.Fatal(err.Error())\n\t}\n\tif err := c.WriteMessage(TextMessage, res); err != nil {\n\t\tt.Fatal(err.Error())\n\t}\n}\n\nfunc TestSphereMessagePingPong(t *testing.T) {\n\tdone := make(chan error)\n\tc, _, err := CreateConnection()\n\tif err != nil {\n\t\tt.Fatal(err.Error())\n\t}\n\tdefer c.Close()\n\tgo func() {\n\t\tfor {\n\t\t\t_, _, err := c.ReadMessage()\n\t\t\tif err != nil {\n\t\t\t\tdone <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdone <- nil\n\t\t\treturn\n\t\t}\n\t}()\n\tp := &Packet{Type: PacketTypePing}\n\tres, err := p.toJSON()\n\tif err != nil {\n\t\tt.Fatal(err.Error())\n\t}\n\tif err := c.WriteMessage(TextMessage, res); err != nil {\n\t\tt.Fatal(err.Error())\n\t}\n\t<-done\n}\n\nfunc TestSphereSubscribeChannel(t *testing.T) {\n\tdone := make(chan error)\n\tc, _, err := CreateConnection()\n\tif err != nil {\n\t\tt.Fatal(err.Error())\n\t}\n\tdefer c.Close()\n\tgo func() {\n\t\tfor {\n\t\t\t_, _, err := c.ReadMessage()\n\t\t\tif err != nil {\n\t\t\t\tdone <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdone <- nil\n\t\t\treturn\n\t\t}\n\t}()\n\tp := &Packet{Type: PacketTypeSubscribe, Namespace: \"test\", Room: \"helloworld\"}\n\tres, err := p.toJSON()\n\tif err != nil {\n\t\tt.Fatal(err.Error())\n\t}\n\tif err := c.WriteMessage(TextMessage, res); err != nil {\n\t\tt.Fatal(err.Error())\n\t}\n\tif err := <-done; err != nil {\n\t\tt.Fatal(err.Error())\n\t}\n}\n\nfunc TestSphereChannelMessage(t *testing.T) {\n\tdone := make(chan error)\n\tc, _, err := CreateConnection()\n\tif err != nil {\n\t\tt.Fatal(err.Error())\n\t}\n\tdefer c.Close()\n\tgo func() {\n\t\tfor {\n\t\t\t_, msg, err := c.ReadMessage()\n\t\t\tif err != nil {\n\t\t\t\tdone <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t\tp, err := ParsePacket(msg)\n\t\t\tif err != nil {\n\t\t\t\tdone <- err\n\t\t\t} else {\n\t\t\t\tswitch {\n\t\t\t\tcase p.Type == PacketTypeSubscribed && p.Error == nil:\n\t\t\t\t\tm := &Packet{Type: PacketTypeChannel, Namespace: \"test\", Room: \"helloworld\", Message: &Message{Event: \"HelloEvent\", Data: \"HelloWorld\"}}\n\t\t\t\t\tif json, err := m.toJSON(); err == nil {\n\t\t\t\t\t\tif err := c.WriteMessage(TextMessage, json); err != nil {\n\t\t\t\t\t\t\tdone <- err\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdone <- err\n\t\t\t\t\t}\n\t\t\t\tcase p.Type == PacketTypeChannel && p.Error == nil:\n\t\t\t\t\tdone <- nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\tp := &Packet{Type: PacketTypeSubscribe, Namespace: \"test\", Room: \"helloworld\"}\n\tres, err := p.toJSON()\n\tif err != nil {\n\t\tt.Fatal(err.Error())\n\t}\n\tif err := c.WriteMessage(TextMessage, res); err != nil {\n\t\tt.Fatal(err.Error())\n\t}\n\tif err := <-done; err != nil {\n\t\tt.Fatal(err.Error())\n\t}\n}\nuse SimpleBroker as default brokerpackage sphere\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/gin-gonic\/gin\"\n\t\"github.com\/gorilla\/websocket\"\n)\n\nvar (\n\taddress = func() string {\n\t\tl, _ := net.Listen(\"tcp\", \":0\")\n\t\tdefer l.Close()\n\t\treturn fmt.Sprintf(\"127.0.0.1:%d\", l.Addr().(*net.TCPAddr).Port)\n\t}()\n)\n\ntype TestSphereModel struct {\n\t*ChannelModel\n}\n\nfunc (m *TestSphereModel) Subscribe(room string, connection *Connection) bool {\n\treturn true\n}\n\nfunc (m *TestSphereModel) Disconnect(room string, connection *Connection) bool {\n\treturn true\n}\n\nfunc (m *TestSphereModel) Receive(event string, message string) (string, error) {\n\treturn \"you_got_me\", nil\n}\n\nfunc init() {\n\tgin.SetMode(gin.ReleaseMode)\n\ts, r := NewSphere(), gin.New()\n\ts.ChannelModels(&TestSphereModel{ExtendChannelModel(\"test\")})\n\tr.GET(\"\/sync\", func(c *gin.Context) {\n\t\ts.Handler(c.Writer, c.Request)\n\t})\n\tgo r.Run(address)\n}\n\nfunc CreateConnection() (c *websocket.Conn, response *http.Response, err error) {\n\tu, err := url.Parse(\"ws:\/\/\" + address + \"\/sync\")\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\trawConn, err := net.Dial(\"tcp\", u.Host)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\twsHeaders := http.Header{\n\t\t\"Origin\": {\"http:\/\/\" + address},\n\t}\n\treturn websocket.NewClient(rawConn, u, wsHeaders, 1024, 1024)\n}\n\nfunc TestSphereReady(t *testing.T) {\n\tcount := 0\n\tticker := time.NewTicker(time.Millisecond * 60)\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\ts, err := net.Dial(\"tcp\", address)\n\t\t\tdefer s.Close()\n\t\t\tif err == nil || count > 3 {\n\t\t\t\tdefer ticker.Stop()\n\t\t\t\tif err != nil {\n\t\t\t\t\tt.Fatal(\"Server could not get started\")\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tcount++\n\t}\n}\n\nfunc TestSphereConnection(t *testing.T) {\n\tc, _, err := CreateConnection()\n\tif err != nil {\n\t\tt.Fatal(err.Error())\n\t}\n\tdefer c.Close()\n}\n\nfunc TestSphereSendMessage(t *testing.T) {\n\tc, _, err := CreateConnection()\n\tif err != nil {\n\t\tt.Fatal(err.Error())\n\t}\n\tdefer c.Close()\n\tp := &Packet{Type: PacketTypePing}\n\tres, err := p.toJSON()\n\tif err != nil {\n\t\tt.Fatal(err.Error())\n\t}\n\tif err := c.WriteMessage(TextMessage, res); err != nil {\n\t\tt.Fatal(err.Error())\n\t}\n}\n\nfunc TestSphereMessagePingPong(t *testing.T) {\n\tdone := make(chan error)\n\tc, _, err := CreateConnection()\n\tif err != nil {\n\t\tt.Fatal(err.Error())\n\t}\n\tdefer c.Close()\n\tgo func() {\n\t\tfor {\n\t\t\t_, _, err := c.ReadMessage()\n\t\t\tif err != nil {\n\t\t\t\tdone <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdone <- nil\n\t\t\treturn\n\t\t}\n\t}()\n\tp := &Packet{Type: PacketTypePing}\n\tres, err := p.toJSON()\n\tif err != nil {\n\t\tt.Fatal(err.Error())\n\t}\n\tif err := c.WriteMessage(TextMessage, res); err != nil {\n\t\tt.Fatal(err.Error())\n\t}\n\t<-done\n}\n\nfunc TestSphereSubscribeChannel(t *testing.T) {\n\tdone := make(chan error)\n\tc, _, err := CreateConnection()\n\tif err != nil {\n\t\tt.Fatal(err.Error())\n\t}\n\tdefer c.Close()\n\tgo func() {\n\t\tfor {\n\t\t\t_, _, err := c.ReadMessage()\n\t\t\tif err != nil {\n\t\t\t\tdone <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t\tdone <- nil\n\t\t\treturn\n\t\t}\n\t}()\n\tp := &Packet{Type: PacketTypeSubscribe, Namespace: \"test\", Room: \"helloworld\"}\n\tres, err := p.toJSON()\n\tif err != nil {\n\t\tt.Fatal(err.Error())\n\t}\n\tif err := c.WriteMessage(TextMessage, res); err != nil {\n\t\tt.Fatal(err.Error())\n\t}\n\tif err := <-done; err != nil {\n\t\tt.Fatal(err.Error())\n\t}\n}\n\nfunc TestSphereChannelMessage(t *testing.T) {\n\tdone := make(chan error)\n\tc, _, err := CreateConnection()\n\tif err != nil {\n\t\tt.Fatal(err.Error())\n\t}\n\tdefer c.Close()\n\tgo func() {\n\t\tfor {\n\t\t\t_, msg, err := c.ReadMessage()\n\t\t\tif err != nil {\n\t\t\t\tdone <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t\tp, err := ParsePacket(msg)\n\t\t\tif err != nil {\n\t\t\t\tdone <- err\n\t\t\t} else {\n\t\t\t\tswitch {\n\t\t\t\tcase p.Type == PacketTypeSubscribed && p.Error == nil:\n\t\t\t\t\tm := &Packet{Type: PacketTypeChannel, Namespace: \"test\", Room: \"helloworld\", Message: &Message{Event: \"HelloEvent\", Data: \"HelloWorld\"}}\n\t\t\t\t\tif json, err := m.toJSON(); err == nil {\n\t\t\t\t\t\tif err := c.WriteMessage(TextMessage, json); err != nil {\n\t\t\t\t\t\t\tdone <- err\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdone <- err\n\t\t\t\t\t}\n\t\t\t\tcase p.Type == PacketTypeChannel && p.Error == nil:\n\t\t\t\t\tdone <- nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}()\n\tp := &Packet{Type: PacketTypeSubscribe, Namespace: \"test\", Room: \"helloworld\"}\n\tres, err := p.toJSON()\n\tif err != nil {\n\t\tt.Fatal(err.Error())\n\t}\n\tif err := c.WriteMessage(TextMessage, res); err != nil {\n\t\tt.Fatal(err.Error())\n\t}\n\tif err := <-done; err != nil {\n\t\tt.Fatal(err.Error())\n\t}\n}\n<|endoftext|>"} {"text":"\/*\n Copyright The containerd Authors.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\npackage v2\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/containerd\/containerd\/namespaces\"\n\tclient \"github.com\/containerd\/containerd\/runtime\/v2\/shim\"\n\t\"github.com\/pkg\/errors\"\n)\n\ntype deferredPipeConnection struct {\n\tctx context.Context\n\n\twg sync.WaitGroup\n\tonce sync.Once\n\n\tc net.Conn\n\tconerr error\n}\n\nfunc (dpc *deferredPipeConnection) Read(p []byte) (n int, err error) {\n\tif dpc.c == nil {\n\t\tdpc.wg.Wait()\n\t\tif dpc.c == nil {\n\t\t\treturn 0, dpc.conerr\n\t\t}\n\t}\n\treturn dpc.c.Read(p)\n}\nfunc (dpc *deferredPipeConnection) Close() error {\n\tvar err error\n\tdpc.once.Do(func() {\n\t\tdpc.wg.Wait()\n\t\tif dpc.c != nil {\n\t\t\terr = dpc.c.Close()\n\t\t} else if dpc.conerr != nil {\n\t\t\terr = dpc.conerr\n\t\t}\n\t})\n\treturn err\n}\n\n\/\/ openShimLog on Windows acts as the client of the log pipe. In this way the\n\/\/ containerd daemon can reconnect to the shim log stream if it is restarted.\nfunc openShimLog(ctx context.Context, bundle *Bundle) (io.ReadCloser, error) {\n\tns, err := namespaces.NamespaceRequired(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdpc := &deferredPipeConnection{\n\t\tctx: ctx,\n\t}\n\tdpc.wg.Add(1)\n\tgo func() {\n\t\tc, conerr := client.AnonDialer(\n\t\t\tfmt.Sprintf(\"\\\\\\\\.\\\\pipe\\\\containerd-shim-%s-%s-log\", ns, bundle.ID),\n\t\t\ttime.Second*10,\n\t\t)\n\t\tif conerr != nil {\n\t\t\tdpc.conerr = errors.Wrap(err, \"failed to connect to shim log\")\n\t\t}\n\t\tdpc.c = c\n\t\tdpc.wg.Done()\n\t}()\n\treturn dpc, nil\n}\nFix a bug in shim log on Windows that can cause 100% CPU utilization\/*\n Copyright The containerd Authors.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\npackage v2\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com\/containerd\/containerd\/namespaces\"\n\tclient \"github.com\/containerd\/containerd\/runtime\/v2\/shim\"\n\t\"github.com\/pkg\/errors\"\n)\n\ntype deferredPipeConnection struct {\n\tctx context.Context\n\n\twg sync.WaitGroup\n\tonce sync.Once\n\n\tc net.Conn\n\tconerr error\n}\n\nfunc (dpc *deferredPipeConnection) Read(p []byte) (n int, err error) {\n\tif dpc.c == nil {\n\t\tdpc.wg.Wait()\n\t\tif dpc.c == nil {\n\t\t\treturn 0, dpc.conerr\n\t\t}\n\t}\n\treturn dpc.c.Read(p)\n}\nfunc (dpc *deferredPipeConnection) Close() error {\n\tvar err error\n\tdpc.once.Do(func() {\n\t\tdpc.wg.Wait()\n\t\tif dpc.c != nil {\n\t\t\terr = dpc.c.Close()\n\t\t} else if dpc.conerr != nil {\n\t\t\terr = dpc.conerr\n\t\t}\n\t})\n\treturn err\n}\n\n\/\/ openShimLog on Windows acts as the client of the log pipe. In this way the\n\/\/ containerd daemon can reconnect to the shim log stream if it is restarted.\nfunc openShimLog(ctx context.Context, bundle *Bundle) (io.ReadCloser, error) {\n\tns, err := namespaces.NamespaceRequired(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdpc := &deferredPipeConnection{\n\t\tctx: ctx,\n\t}\n\tdpc.wg.Add(1)\n\tgo func() {\n\t\tc, conerr := client.AnonDialer(\n\t\t\tfmt.Sprintf(\"\\\\\\\\.\\\\pipe\\\\containerd-shim-%s-%s-log\", ns, bundle.ID),\n\t\t\ttime.Second*10,\n\t\t)\n\t\tif conerr != nil {\n\t\t\tdpc.conerr = errors.Wrap(conerr, \"failed to connect to shim log\")\n\t\t}\n\t\tdpc.c = c\n\t\tdpc.wg.Done()\n\t}()\n\treturn dpc, nil\n}\n<|endoftext|>"} {"text":"package httplog\n\n\ntype HttpLogger interface {\n\tFatal(...interface{})\n\tFatalf(string, ...interface{})\n\tFatalln(...interface{})\n\n\tPanic(...interface{})\n\tPanicf(string, ...interface{})\n\tPanicln(...interface{})\n\n\tPrint(...interface{})\n\tPrintf(string, ...interface{})\n\tPrintln(...interface{})\n\n\tBadRequest()\n\tUnauthorized()\n\tPaymentRequired()\n\tForbidden()\n\tNotFound()\n\tMethodNotAllowed()\n\tNotAcceptable()\n\tProxyAuthRequired()\n\tRequestTimeout()\n\tConflict()\n\tGone()\n\tLengthRequired()\n\tPreconditionFailed()\n\tRequestEntityTooLarge()\n\tRequestURITooLong()\n\tUnsupportedMediaType()\n\tRequestedRangeNotSatisfiable()\n\tExpectationFailed()\n\tTeapot()\n\n\tInternalServerError()\n\tStatusNotImplemented()\n\tStatusBadGateway()\n\tServiceUnavailable()\n\tGatewayTimeout()\n\tHTTPVersionNotSupported()\n}\nupdated HttpLogger interface. the methods for the 4xx client erros and 5xx server errors take an http.ResponseWriter as a parameter.package httplog\n\n\nimport (\n\t\"net\/http\"\n)\n\n\ntype HttpLogger interface {\n\tFatal(...interface{})\n\tFatalf(string, ...interface{})\n\tFatalln(...interface{})\n\n\tPanic(...interface{})\n\tPanicf(string, ...interface{})\n\tPanicln(...interface{})\n\n\tPrint(...interface{})\n\tPrintf(string, ...interface{})\n\tPrintln(...interface{})\n\n\tBadRequest(http.ResponseWriter)\n\tUnauthorized(http.ResponseWriter)\n\tPaymentRequired(http.ResponseWriter)\n\tForbidden(http.ResponseWriter)\n\tNotFound(http.ResponseWriter)\n\tMethodNotAllowed(http.ResponseWriter)\n\tNotAcceptable(http.ResponseWriter)\n\tProxyAuthRequired(http.ResponseWriter)\n\tRequestTimeout(http.ResponseWriter)\n\tConflict(http.ResponseWriter)\n\tGone(http.ResponseWriter)\n\tLengthRequired(http.ResponseWriter)\n\tPreconditionFailed(http.ResponseWriter)\n\tRequestEntityTooLarge(http.ResponseWriter)\n\tRequestURITooLong(http.ResponseWriter)\n\tUnsupportedMediaType(http.ResponseWriter)\n\tRequestedRangeNotSatisfiable(http.ResponseWriter)\n\tExpectationFailed(http.ResponseWriter)\n\tTeapot(http.ResponseWriter)\n\n\tInternalServerError(http.ResponseWriter)\n\tNotImplemented(http.ResponseWriter)\n\tBadGateway(http.ResponseWriter)\n\tServiceUnavailable(http.ResponseWriter)\n\tGatewayTimeout(http.ResponseWriter)\n\tHTTPVersionNotSupported(http.ResponseWriter)\n}\n<|endoftext|>"} {"text":"package collectors\n\nimport (\n\t\"github.com\/StackExchange\/tcollector\/opentsdb\"\n\t\"github.com\/StackExchange\/wmi\"\n\t\"regexp\"\n)\n\nfunc init() {\n\tcollectors = append(collectors, c_cpu_windows)\n\tcollectors = append(collectors, c_network_windows)\n\tcollectors = append(collectors, c_physical_disk_windows)\n\tcollectors = append(collectors, c_simple_mem_windows)\n}\n\nconst CPU_QUERY = `\n\tSELECT Name, PercentPrivilegedTime, PercentInterruptTime, PercentUserTime\n\tFROM Win32_PerfRawData_PerfOS_Processor\n\tWHERE Name <> '_Total'\n`\n\n\/\/KMB Moving Excludes to Go, we didn't notice the WHERE changing performance much and a regex\n\/\/is easier than building the WHERE string\nconst NETWORK_QUERY = `\n\tSELECT Name, BytesReceivedPerSec, BytesSentPerSec,\n\t\tPacketsReceivedPerSec, PacketsSentPerSec,\n\t\tPacketsOutboundDiscarded, PacketsOutboundErrors,\n\t\tPacketsReceivedDiscarded, PacketsReceivedErrors\n\tFROM Win32_PerfRawData_Tcpip_NetworkInterface\n`\nconst INTERFACE_EXCLUSIONS = `isatap|Teredo`\n\nconst PHYSICAL_DISK_QUERY = `\n\tSELECT Name, AvgDisksecPerRead, AvgDisksecPerWrite,\n\t\tAvgDiskReadQueueLength, AvgDiskWriteQueueLength, \n\t\tDiskReadBytesPersec, DiskReadsPersec,\n\t\tDiskWriteBytesPersec, DiskWritesPersec, \n\t\tSplitIOPerSec, PercentDiskReadTime, PercentDiskWriteTime\n\tFROM Win32_PerfRawData_PerfDisk_PhysicalDisk\n`\n\n\/\/Memory Needs to be expanded upon, Should be deeper in Utilization (What is Cache etc) \n\/\/as well as Saturation (i.e. Paging Activity). Lot of that is in Win32_PerfRawData_PerfOS_Memory\n\n\/\/Win32_Operating_System's units are KBytes\nconst SIMPLE_MEMORY_QUERY = `\n\tSELECT FreePhysicalMemory, FreeVirtualMemory,\n\tTotalVisibleMemorySize, TotalVirtualMemorySize\n\tFROM Win32_OperatingSystem\n`\n\nfunc c_cpu_windows() opentsdb.MultiDataPoint {\n\tvar dst []wmi.Win32_PerfRawData_PerfOS_Processor\n\terr := wmi.Query(CPU_QUERY, &dst)\n\tif err != nil {\n\t\tl.Println(\"cpu:\", err)\n\t\treturn nil\n\t}\n\tvar md opentsdb.MultiDataPoint\n\tfor _, v := range dst {\n\t\tAdd(&md, \"cpu.time\", v.PercentPrivilegedTime, opentsdb.TagSet{\"cpu\": v.Name, \"type\": \"privileged\"})\n\t\tAdd(&md, \"cpu.time\", v.PercentInterruptTime, opentsdb.TagSet{\"cpu\": v.Name, \"type\": \"interrupt\"})\n\t\tAdd(&md, \"cpu.time\", v.PercentUserTime, opentsdb.TagSet{\"cpu\": v.Name, \"type\": \"user\"})\n\t}\n\treturn md\n}\n\nfunc c_simple_mem_windows() opentsdb.MultiDataPoint {\n\tvar dst []wmi.Win32_OperatingSystem\n\terr := wmi.Query(SIMPLE_MEMORY_QUERY, &dst)\n\tif err != nil {\n\t\tl.Println(\"simple_mem:\", err)\n\t\treturn nil\n\t}\n\tvar md opentsdb.MultiDataPoint\n\tfor _, v := range dst {\n\t\tAdd(&md, \"mem.virtual.total\", v.TotalVirtualMemorySize * 1024, opentsdb.TagSet{})\n\t\tAdd(&md, \"mem.virtual.free\", v.FreeVirtualMemory * 1024, opentsdb.TagSet{})\n\t\tAdd(&md, \"mem.physical.total\", v.TotalVisibleMemorySize * 1024, opentsdb.TagSet{})\n\t\tAdd(&md, \"mem.physical.free\", v.FreePhysicalMemory * 1024, opentsdb.TagSet{})\n\t}\n\treturn md\n}\n\nfunc c_physical_disk_windows() opentsdb.MultiDataPoint {\n\tvar dst []wmi.Win32_PerfRawData_PerfDisk_PhysicalDisk\n\terr := wmi.Query(PHYSICAL_DISK_QUERY, &dst)\n\tif err != nil {\n\t\tl.Println(\"disk_physical:\", err)\n\t\treturn nil\n\t}\n\tvar md opentsdb.MultiDataPoint\n\tfor _, v := range dst {\n\t\tAdd(&md, \"disk.physical.duration\", v.AvgDiskSecPerRead, opentsdb.TagSet{\"disk\": v.Name, \"type\": \"read\"})\n\t\tAdd(&md, \"disk.physical.duration\", v.AvgDiskSecPerWrite, opentsdb.TagSet{\"disk\": v.Name, \"type\": \"write\"})\n\t\tAdd(&md, \"disk.physical.queue\", v.AvgDiskReadQueueLength, opentsdb.TagSet{\"disk\": v.Name, \"type\": \"read\"})\n\t\tAdd(&md, \"disk.physical.queue\", v.AvgDiskWriteQueueLength, opentsdb.TagSet{\"disk\": v.Name, \"type\": \"write\"})\n\t\tAdd(&md, \"disk.physical.ops\", v.DiskReadsPerSec, opentsdb.TagSet{\"disk\": v.Name, \"type\": \"read\"})\n\t\tAdd(&md, \"disk.physical.ops\", v.DiskWritesPerSec, opentsdb.TagSet{\"disk\": v.Name, \"type\": \"write\"})\n\t\tAdd(&md, \"disk.physical.bytes\", v.DiskReadBytesPerSec, opentsdb.TagSet{\"disk\": v.Name, \"type\": \"read\"})\n\t\tAdd(&md, \"disk.physical.bytes\", v.DiskWriteBytesPerSec, opentsdb.TagSet{\"disk\": v.Name, \"type\": \"write\"})\n\t\tAdd(&md, \"disk.physical.percenttime\", v.PercentDiskReadTime, opentsdb.TagSet{\"disk\": v.Name, \"type\": \"read\"})\n\t\tAdd(&md, \"disk.physical.percenttime\", v.PercentDiskWriteTime, opentsdb.TagSet{\"disk\": v.Name, \"type\": \"write\"})\n\t\tAdd(&md, \"disk.physical.spltio\", v.SplitIOPerSec, opentsdb.TagSet{\"disk\": v.Name})\n\t}\n\treturn md\n}\n\nfunc c_network_windows() opentsdb.MultiDataPoint {\n\tvar dst []wmi.Win32_PerfRawData_Tcpip_NetworkInterface\n\terr := wmi.Query(NETWORK_QUERY, &dst)\n\tif err != nil {\n\t\tl.Println(\"network:\", err)\n\t\treturn nil\n\t}\n\tvar md opentsdb.MultiDataPoint\n\texclusions := regexp.MustCompile(INTERFACE_EXCLUSIONS)\n\tfor _, v := range dst {\n\t\tif ! exclusions.MatchString(v.Name) {\n\t\t\tAdd(&md, \"network.bytes\", v.BytesReceivedPerSec, opentsdb.TagSet{\"iface\": v.Name, \"direction\": \"in\"})\n\t\t\tAdd(&md, \"network.bytes\", v.BytesSentPerSec, opentsdb.TagSet{\"iface\": v.Name, \"direction\": \"out\"})\n\t\t\tAdd(&md, \"network.packets\", v.PacketsReceivedPerSec, opentsdb.TagSet{\"iface\": v.Name, \"direction\": \"in\"})\n\t\t\tAdd(&md, \"network.packets\", v.PacketsSentPerSec, opentsdb.TagSet{\"iface\": v.Name, \"direction\": \"out\"})\n\t\t\tAdd(&md, \"network.err\", v.PacketsOutboundDiscarded, opentsdb.TagSet{\"iface\": v.Name, \"type\": \"discard\", \"direction\": \"out\"})\n\t\t\tAdd(&md, \"network.err\", v.PacketsReceivedDiscarded, opentsdb.TagSet{\"iface\": v.Name, \"type\": \"discard\", \"direction\": \"in\"})\n\t\t\tAdd(&md, \"network.err\", v.PacketsOutboundErrors, opentsdb.TagSet{\"iface\": v.Name, \"type\": \"error\", \"direction\": \"out\"})\n\t\t\tAdd(&md, \"network.err\", v.PacketsReceivedErrors, opentsdb.TagSet{\"iface\": v.Name, \"type\": \"error\", \"direction\": \"in\"})\n\t\t}\n\t}\n\treturn md\n}\n\ncmd\/scollector: Disk space utilization via wmipackage collectors\n\nimport (\n\t\"github.com\/StackExchange\/tcollector\/opentsdb\"\n\t\"github.com\/StackExchange\/wmi\"\n\t\"regexp\"\n)\n\nfunc init() {\n\tcollectors = append(collectors, c_cpu_windows)\n\tcollectors = append(collectors, c_network_windows)\n\tcollectors = append(collectors, c_physical_disk_windows)\n\tcollectors = append(collectors, c_simple_mem_windows)\n\tcollectors = append(collectors, c_disk_space_windows)\n}\n\nconst CPU_QUERY = `\n\tSELECT Name, PercentPrivilegedTime, PercentInterruptTime, PercentUserTime\n\tFROM Win32_PerfRawData_PerfOS_Processor\n\tWHERE Name <> '_Total'\n`\n\n\/\/KMB Moving Excludes to Go, we didn't notice the WHERE changing performance much and a regex\n\/\/is easier than building the WHERE string\nconst NETWORK_QUERY = `\n\tSELECT Name, BytesReceivedPerSec, BytesSentPerSec,\n\t\tPacketsReceivedPerSec, PacketsSentPerSec,\n\t\tPacketsOutboundDiscarded, PacketsOutboundErrors,\n\t\tPacketsReceivedDiscarded, PacketsReceivedErrors\n\tFROM Win32_PerfRawData_Tcpip_NetworkInterface\n`\nconst INTERFACE_EXCLUSIONS = `isatap|Teredo`\n\nconst PHYSICAL_DISK_QUERY = `\n\tSELECT Name, AvgDisksecPerRead, AvgDisksecPerWrite,\n\t\tAvgDiskReadQueueLength, AvgDiskWriteQueueLength, \n\t\tDiskReadBytesPersec, DiskReadsPersec,\n\t\tDiskWriteBytesPersec, DiskWritesPersec, \n\t\tSplitIOPerSec, PercentDiskReadTime, PercentDiskWriteTime\n\tFROM Win32_PerfRawData_PerfDisk_PhysicalDisk\n\tWHERE Name <> '_Total'\n`\n\n\/\/Similar Breakdowns exist as to physical, but for now just using this for the space utilization \nconst DISKSPACE_QUERY = `\n\tSELECT Name, FreeMegaBytes, PercentFreeSpace\n\tFROM Win32_PerfRawData_PerfDisk_LogicalDisk\n\tWHERE Name <> '_Total'\n`\n\n\/\/Memory Needs to be expanded upon, Should be deeper in Utilization (What is Cache etc) \n\/\/as well as Saturation (i.e. Paging Activity). Lot of that is in Win32_PerfRawData_PerfOS_Memory\n\/\/Win32_Operating_System's units are KBytes\n\nconst SIMPLE_MEMORY_QUERY = `\n\tSELECT FreePhysicalMemory, FreeVirtualMemory,\n\tTotalVisibleMemorySize, TotalVirtualMemorySize\n\tFROM Win32_OperatingSystem\n`\n\nfunc c_cpu_windows() opentsdb.MultiDataPoint {\n\tvar dst []wmi.Win32_PerfRawData_PerfOS_Processor\n\terr := wmi.Query(CPU_QUERY, &dst)\n\tif err != nil {\n\t\tl.Println(\"cpu:\", err)\n\t\treturn nil\n\t}\n\tvar md opentsdb.MultiDataPoint\n\tfor _, v := range dst {\n\t\tAdd(&md, \"cpu.time\", v.PercentPrivilegedTime, opentsdb.TagSet{\"cpu\": v.Name, \"type\": \"privileged\"})\n\t\tAdd(&md, \"cpu.time\", v.PercentInterruptTime, opentsdb.TagSet{\"cpu\": v.Name, \"type\": \"interrupt\"})\n\t\tAdd(&md, \"cpu.time\", v.PercentUserTime, opentsdb.TagSet{\"cpu\": v.Name, \"type\": \"user\"})\n\t}\n\treturn md\n}\n\nfunc c_simple_mem_windows() opentsdb.MultiDataPoint {\n\tvar dst []wmi.Win32_OperatingSystem\n\terr := wmi.Query(SIMPLE_MEMORY_QUERY, &dst)\n\tif err != nil {\n\t\tl.Println(\"simple_mem:\", err)\n\t\treturn nil\n\t}\n\tvar md opentsdb.MultiDataPoint\n\tfor _, v := range dst {\n\t\tAdd(&md, \"mem.virtual.total\", v.TotalVirtualMemorySize * 1024, opentsdb.TagSet{})\n\t\tAdd(&md, \"mem.virtual.free\", v.FreeVirtualMemory * 1024, opentsdb.TagSet{})\n\t\tAdd(&md, \"mem.physical.total\", v.TotalVisibleMemorySize * 1024, opentsdb.TagSet{})\n\t\tAdd(&md, \"mem.physical.free\", v.FreePhysicalMemory * 1024, opentsdb.TagSet{})\n\t}\n\treturn md\n}\n\nfunc c_disk_space_windows() opentsdb.MultiDataPoint {\n\tvar dst []wmi.Win32_PerfRawData_PerfDisk_LogicalDisk\n\terr := wmi.Query(DISKSPACE_QUERY, &dst)\n\tif err != nil {\n\t\tl.Println(\"simple_mem:\", err)\n\t\treturn nil\n\t}\n\tvar md opentsdb.MultiDataPoint\n\tfor _, v := range dst {\n\t\tAdd(&md, \"disk.logical.free_bytes\", v.FreeMegabytes * 1048576, opentsdb.TagSet{\"partition\": v.Name})\n\t\tAdd(&md, \"disk.logical.percent_free\", v.PercentFreeSpace, opentsdb.TagSet{\"partition\": v.Name})\n\t}\n\treturn md\n}\n\nfunc c_physical_disk_windows() opentsdb.MultiDataPoint {\n\tvar dst []wmi.Win32_PerfRawData_PerfDisk_PhysicalDisk\n\terr := wmi.Query(PHYSICAL_DISK_QUERY, &dst)\n\tif err != nil {\n\t\tl.Println(\"disk_physical:\", err)\n\t\treturn nil\n\t}\n\tvar md opentsdb.MultiDataPoint\n\tfor _, v := range dst {\n\t\tAdd(&md, \"disk.physical.duration\", v.AvgDiskSecPerRead, opentsdb.TagSet{\"disk\": v.Name, \"type\": \"read\"})\n\t\tAdd(&md, \"disk.physical.duration\", v.AvgDiskSecPerWrite, opentsdb.TagSet{\"disk\": v.Name, \"type\": \"write\"})\n\t\tAdd(&md, \"disk.physical.queue\", v.AvgDiskReadQueueLength, opentsdb.TagSet{\"disk\": v.Name, \"type\": \"read\"})\n\t\tAdd(&md, \"disk.physical.queue\", v.AvgDiskWriteQueueLength, opentsdb.TagSet{\"disk\": v.Name, \"type\": \"write\"})\n\t\tAdd(&md, \"disk.physical.ops\", v.DiskReadsPerSec, opentsdb.TagSet{\"disk\": v.Name, \"type\": \"read\"})\n\t\tAdd(&md, \"disk.physical.ops\", v.DiskWritesPerSec, opentsdb.TagSet{\"disk\": v.Name, \"type\": \"write\"})\n\t\tAdd(&md, \"disk.physical.bytes\", v.DiskReadBytesPerSec, opentsdb.TagSet{\"disk\": v.Name, \"type\": \"read\"})\n\t\tAdd(&md, \"disk.physical.bytes\", v.DiskWriteBytesPerSec, opentsdb.TagSet{\"disk\": v.Name, \"type\": \"write\"})\n\t\tAdd(&md, \"disk.physical.percenttime\", v.PercentDiskReadTime, opentsdb.TagSet{\"disk\": v.Name, \"type\": \"read\"})\n\t\tAdd(&md, \"disk.physical.percenttime\", v.PercentDiskWriteTime, opentsdb.TagSet{\"disk\": v.Name, \"type\": \"write\"})\n\t\tAdd(&md, \"disk.physical.spltio\", v.SplitIOPerSec, opentsdb.TagSet{\"disk\": v.Name})\n\t}\n\treturn md\n}\n\nfunc c_network_windows() opentsdb.MultiDataPoint {\n\tvar dst []wmi.Win32_PerfRawData_Tcpip_NetworkInterface\n\terr := wmi.Query(NETWORK_QUERY, &dst)\n\tif err != nil {\n\t\tl.Println(\"network:\", err)\n\t\treturn nil\n\t}\n\tvar md opentsdb.MultiDataPoint\n\texclusions := regexp.MustCompile(INTERFACE_EXCLUSIONS)\n\tfor _, v := range dst {\n\t\tif ! exclusions.MatchString(v.Name) {\n\t\t\tAdd(&md, \"network.bytes\", v.BytesReceivedPerSec, opentsdb.TagSet{\"iface\": v.Name, \"direction\": \"in\"})\n\t\t\tAdd(&md, \"network.bytes\", v.BytesSentPerSec, opentsdb.TagSet{\"iface\": v.Name, \"direction\": \"out\"})\n\t\t\tAdd(&md, \"network.packets\", v.PacketsReceivedPerSec, opentsdb.TagSet{\"iface\": v.Name, \"direction\": \"in\"})\n\t\t\tAdd(&md, \"network.packets\", v.PacketsSentPerSec, opentsdb.TagSet{\"iface\": v.Name, \"direction\": \"out\"})\n\t\t\tAdd(&md, \"network.err\", v.PacketsOutboundDiscarded, opentsdb.TagSet{\"iface\": v.Name, \"type\": \"discard\", \"direction\": \"out\"})\n\t\t\tAdd(&md, \"network.err\", v.PacketsReceivedDiscarded, opentsdb.TagSet{\"iface\": v.Name, \"type\": \"discard\", \"direction\": \"in\"})\n\t\t\tAdd(&md, \"network.err\", v.PacketsOutboundErrors, opentsdb.TagSet{\"iface\": v.Name, \"type\": \"error\", \"direction\": \"out\"})\n\t\t\tAdd(&md, \"network.err\", v.PacketsReceivedErrors, opentsdb.TagSet{\"iface\": v.Name, \"type\": \"error\", \"direction\": \"in\"})\n\t\t}\n\t}\n\treturn md\n}\n\n<|endoftext|>"} {"text":"\/\/ Same copyright and license as the rest of the files in this project\n\/\/ This file contains style related functions and structures\n\npackage gtk\n\n\/\/ #include \n\/\/ #include \"gtk.go.h\"\nimport \"C\"\nimport (\n\t\"unsafe\"\n\n\t\"github.com\/gotk3\/gotk3\/pango\"\n\n\t\"github.com\/gotk3\/gotk3\/glib\"\n)\n\n\/*\n * GtkLabel\n *\/\n\n\/\/ Label is a representation of GTK's GtkLabel.\ntype Label struct {\n\tWidget\n}\n\n\/\/ native returns a pointer to the underlying GtkLabel.\nfunc (v *Label) native() *C.GtkLabel {\n\tif v == nil || v.GObject == nil {\n\t\treturn nil\n\t}\n\tp := unsafe.Pointer(v.GObject)\n\treturn C.toGtkLabel(p)\n}\n\nfunc marshalLabel(p uintptr) (interface{}, error) {\n\tc := C.g_value_get_object((*C.GValue)(unsafe.Pointer(p)))\n\tobj := glib.Take(unsafe.Pointer(c))\n\treturn wrapLabel(obj), nil\n}\n\nfunc wrapLabel(obj *glib.Object) *Label {\n\treturn &Label{Widget{glib.InitiallyUnowned{obj}}}\n}\n\nfunc WidgetToLabel(widget *Widget) (interface{}, error) {\n\tobj := glib.Take(unsafe.Pointer(widget.GObject))\n\treturn wrapLabel(obj), nil\n}\n\n\/\/ LabelNew is a wrapper around gtk_label_new().\nfunc LabelNew(str string) (*Label, error) {\n\tcstr := C.CString(str)\n\tdefer C.free(unsafe.Pointer(cstr))\n\tc := C.gtk_label_new((*C.gchar)(cstr))\n\tif c == nil {\n\t\treturn nil, nilPtrErr\n\t}\n\tobj := glib.Take(unsafe.Pointer(c))\n\treturn wrapLabel(obj), nil\n}\n\n\/\/ SetText is a wrapper around gtk_label_set_text().\nfunc (v *Label) SetText(str string) {\n\tcstr := C.CString(str)\n\tdefer C.free(unsafe.Pointer(cstr))\n\tC.gtk_label_set_text(v.native(), (*C.gchar)(cstr))\n}\n\n\/\/ TODO:\n\/\/ gtk_label_set_text_with_mnemonic().\n\/\/ gtk_label_set_attributes().\n\/\/ gtk_label_get_attributes().\n\n\/\/ SetMarkup is a wrapper around gtk_label_set_markup().\nfunc (v *Label) SetMarkup(str string) {\n\tcstr := C.CString(str)\n\tdefer C.free(unsafe.Pointer(cstr))\n\tC.gtk_label_set_markup(v.native(), (*C.gchar)(cstr))\n}\n\n\/\/ SetMarkupWithMnemonic is a wrapper around\n\/\/ gtk_label_set_markup_with_mnemonic().\nfunc (v *Label) SetMarkupWithMnemonic(str string) {\n\tcstr := C.CString(str)\n\tdefer C.free(unsafe.Pointer(cstr))\n\tC.gtk_label_set_markup_with_mnemonic(v.native(), (*C.gchar)(cstr))\n}\n\n\/\/ SetPattern is a wrapper around gtk_label_set_pattern().\nfunc (v *Label) SetPattern(patern string) {\n\tcstr := C.CString(patern)\n\tdefer C.free(unsafe.Pointer(cstr))\n\tC.gtk_label_set_pattern(v.native(), (*C.gchar)(cstr))\n}\n\n\/\/ SetJustify is a wrapper around gtk_label_set_justify().\nfunc (v *Label) SetJustify(jtype Justification) {\n\tC.gtk_label_set_justify(v.native(), C.GtkJustification(jtype))\n}\n\n\/\/ SetEllipsize is a wrapper around gtk_label_set_ellipsize().\nfunc (v *Label) SetEllipsize(mode pango.EllipsizeMode) {\n\tC.gtk_label_set_ellipsize(v.native(), C.PangoEllipsizeMode(mode))\n}\n\n\/\/ GetWidthChars is a wrapper around gtk_label_get_width_chars().\nfunc (v *Label) GetWidthChars() int {\n\tc := C.gtk_label_get_width_chars(v.native())\n\treturn int(c)\n}\n\n\/\/ SetWidthChars is a wrapper around gtk_label_set_width_chars().\nfunc (v *Label) SetWidthChars(nChars int) {\n\tC.gtk_label_set_width_chars(v.native(), C.gint(nChars))\n}\n\n\/\/ GetMaxWidthChars is a wrapper around gtk_label_get_max_width_chars().\nfunc (v *Label) GetMaxWidthChars() int {\n\tc := C.gtk_label_get_max_width_chars(v.native())\n\treturn int(c)\n}\n\n\/\/ SetMaxWidthChars is a wrapper around gtk_label_set_max_width_chars().\nfunc (v *Label) SetMaxWidthChars(nChars int) {\n\tC.gtk_label_set_max_width_chars(v.native(), C.gint(nChars))\n}\n\n\/\/ GetLineWrap is a wrapper around gtk_label_get_line_wrap().\nfunc (v *Label) GetLineWrap() bool {\n\tc := C.gtk_label_get_line_wrap(v.native())\n\treturn gobool(c)\n}\n\n\/\/ SetLineWrap is a wrapper around gtk_label_set_line_wrap().\nfunc (v *Label) SetLineWrap(wrap bool) {\n\tC.gtk_label_set_line_wrap(v.native(), gbool(wrap))\n}\n\n\/\/ SetLineWrapMode is a wrapper around gtk_label_set_line_wrap_mode().\nfunc (v *Label) SetLineWrapMode(wrapMode pango.WrapMode) {\n\tC.gtk_label_set_line_wrap_mode(v.native(), C.PangoWrapMode(wrapMode))\n}\n\n\/\/ TODO:\n\/\/ gtk_label_get_line_wrap_mode().\n\/\/ gtk_label_get_layout_offsets().\n\/\/ gtk_label_get_layout().\n\/\/ gtk_label_get_mnemonic_widget().\n\n\/\/ GetSelectable is a wrapper around gtk_label_get_selectable().\nfunc (v *Label) GetSelectable() bool {\n\tc := C.gtk_label_get_selectable(v.native())\n\treturn gobool(c)\n}\n\n\/\/ GetText is a wrapper around gtk_label_get_text().\nfunc (v *Label) GetText() (string, error) {\n\tc := C.gtk_label_get_text(v.native())\n\tif c == nil {\n\t\treturn \"\", nilPtrErr\n\t}\n\treturn C.GoString((*C.char)(c)), nil\n}\n\n\/\/ GetJustify is a wrapper around gtk_label_get_justify().\nfunc (v *Label) GetJustify() Justification {\n\tc := C.gtk_label_get_justify(v.native())\n\treturn Justification(c)\n}\n\n\/\/ GetEllipsize is a wrapper around gtk_label_get_ellipsize().\nfunc (v *Label) GetEllipsize() pango.EllipsizeMode {\n\tc := C.gtk_label_get_ellipsize(v.native())\n\treturn pango.EllipsizeMode(c)\n}\n\n\/\/ GetCurrentUri is a wrapper around gtk_label_get_current_uri().\nfunc (v *Label) GetCurrentUri() string {\n\tc := C.gtk_label_get_current_uri(v.native())\n\treturn C.GoString((*C.char)(c))\n}\n\n\/\/ GetTrackVisitedLinks is a wrapper around gtk_label_get_track_visited_links().\nfunc (v *Label) GetTrackVisitedLinks() bool {\n\tc := C.gtk_label_get_track_visited_links(v.native())\n\treturn gobool(c)\n}\n\n\/\/ SetTrackVisitedLinks is a wrapper around gtk_label_set_track_visited_links().\nfunc (v *Label) SetTrackVisitedLinks(trackLinks bool) {\n\tC.gtk_label_set_track_visited_links(v.native(), gbool(trackLinks))\n}\n\n\/\/ GetAngle is a wrapper around gtk_label_get_angle().\nfunc (v *Label) GetAngle() float64 {\n\tc := C.gtk_label_get_angle(v.native())\n\treturn float64(c)\n}\n\n\/\/ SetAngle is a wrapper around gtk_label_set_angle().\nfunc (v *Label) SetAngle(angle float64) {\n\tC.gtk_label_set_angle(v.native(), C.gdouble(angle))\n}\n\n\/\/ GetSelectionBounds is a wrapper around gtk_label_get_selection_bounds().\nfunc (v *Label) GetSelectionBounds() (start, end int, nonEmpty bool) {\n\tvar cstart, cend C.gint\n\tc := C.gtk_label_get_selection_bounds(v.native(), &cstart, &cend)\n\treturn int(cstart), int(cend), gobool(c)\n}\n\n\/\/ GetSingleLineMode is a wrapper around gtk_label_get_single_line_mode().\nfunc (v *Label) GetSingleLineMode() bool {\n\tc := C.gtk_label_get_single_line_mode(v.native())\n\treturn gobool(c)\n}\n\n\/\/ SetSingleLineMode is a wrapper around gtk_label_set_single_line_mode().\nfunc (v *Label) SetSingleLineMode(mode bool) {\n\tC.gtk_label_set_single_line_mode(v.native(), gbool(mode))\n}\n\n\/\/ GetUseMarkup is a wrapper around gtk_label_get_use_markup().\nfunc (v *Label) GetUseMarkup() bool {\n\tc := C.gtk_label_get_use_markup(v.native())\n\treturn gobool(c)\n}\n\n\/\/ SetUseMarkup is a wrapper around gtk_label_set_use_markup().\nfunc (v *Label) SetUseMarkup(use bool) {\n\tC.gtk_label_set_use_markup(v.native(), gbool(use))\n}\n\n\/\/ GetUseUnderline is a wrapper around gtk_label_get_use_underline().\nfunc (v *Label) GetUseUnderline() bool {\n\tc := C.gtk_label_get_use_underline(v.native())\n\treturn gobool(c)\n}\n\n\/\/ SetUseUnderline is a wrapper around gtk_label_set_use_underline().\nfunc (v *Label) SetUseUnderline(use bool) {\n\tC.gtk_label_set_use_underline(v.native(), gbool(use))\n}\n\n\/\/ LabelNewWithMnemonic is a wrapper around gtk_label_new_with_mnemonic().\nfunc LabelNewWithMnemonic(str string) (*Label, error) {\n\tcstr := C.CString(str)\n\tdefer C.free(unsafe.Pointer(cstr))\n\tc := C.gtk_label_new_with_mnemonic((*C.gchar)(cstr))\n\tif c == nil {\n\t\treturn nil, nilPtrErr\n\t}\n\tobj := glib.Take(unsafe.Pointer(c))\n\treturn wrapLabel(obj), nil\n}\n\n\/\/ SelectRegion is a wrapper around gtk_label_select_region().\nfunc (v *Label) SelectRegion(startOffset, endOffset int) {\n\tC.gtk_label_select_region(v.native(), C.gint(startOffset),\n\t\tC.gint(endOffset))\n}\n\n\/\/ SetSelectable is a wrapper around gtk_label_set_selectable().\nfunc (v *Label) SetSelectable(setting bool) {\n\tC.gtk_label_set_selectable(v.native(), gbool(setting))\n}\n\n\/\/ SetLabel is a wrapper around gtk_label_set_label().\nfunc (v *Label) SetLabel(str string) {\n\tcstr := C.CString(str)\n\tdefer C.free(unsafe.Pointer(cstr))\n\tC.gtk_label_set_label(v.native(), (*C.gchar)(cstr))\n}\n\n\/\/ GetLabel is a wrapper around gtk_label_get_label().\nfunc (v *Label) GetLabel() string {\n\tc := C.gtk_label_get_label(v.native())\n\tif c == nil {\n\t\treturn \"\"\n\t}\n\treturn C.GoString((*C.char)(c))\n}\n\n\/\/ GetMnemonicKeyval is a wrapper around gtk_label_get_mnemonic_keyval().\nfunc (v *Label) GetMnemonicKeyval() uint {\n\treturn uint(C.gtk_label_get_mnemonic_keyval(v.native()))\n}\n\n\/\/ SetMnemonicWidget is a wrapper around gtk_label_set_mnemonic_widget().\nfunc (v *Label) SetMnemonicWidget(widget IWidget) {\n\tC.gtk_label_set_mnemonic_widget(v.native(), widget.toWidget())\n}\nif you say you cast to *Label, then return that\/\/ Same copyright and license as the rest of the files in this project\n\/\/ This file contains style related functions and structures\n\npackage gtk\n\n\/\/ #include \n\/\/ #include \"gtk.go.h\"\nimport \"C\"\nimport (\n\t\"unsafe\"\n\n\t\"github.com\/gotk3\/gotk3\/pango\"\n\n\t\"github.com\/gotk3\/gotk3\/glib\"\n)\n\n\/*\n * GtkLabel\n *\/\n\n\/\/ Label is a representation of GTK's GtkLabel.\ntype Label struct {\n\tWidget\n}\n\n\/\/ native returns a pointer to the underlying GtkLabel.\nfunc (v *Label) native() *C.GtkLabel {\n\tif v == nil || v.GObject == nil {\n\t\treturn nil\n\t}\n\tp := unsafe.Pointer(v.GObject)\n\treturn C.toGtkLabel(p)\n}\n\nfunc marshalLabel(p uintptr) (interface{}, error) {\n\tc := C.g_value_get_object((*C.GValue)(unsafe.Pointer(p)))\n\tobj := glib.Take(unsafe.Pointer(c))\n\treturn wrapLabel(obj), nil\n}\n\nfunc wrapLabel(obj *glib.Object) *Label {\n\treturn &Label{Widget{glib.InitiallyUnowned{obj}}}\n}\n\n\/\/ WidgetToLabel is a convience func that casts the given *Widget into a *Label.\nfunc WidgetToLabel(widget *Widget) (*Label, error) {\n\tobj := glib.Take(unsafe.Pointer(widget.GObject))\n\treturn wrapLabel(obj), nil\n}\n\n\/\/ LabelNew is a wrapper around gtk_label_new().\nfunc LabelNew(str string) (*Label, error) {\n\tcstr := C.CString(str)\n\tdefer C.free(unsafe.Pointer(cstr))\n\tc := C.gtk_label_new((*C.gchar)(cstr))\n\tif c == nil {\n\t\treturn nil, nilPtrErr\n\t}\n\tobj := glib.Take(unsafe.Pointer(c))\n\treturn wrapLabel(obj), nil\n}\n\n\/\/ SetText is a wrapper around gtk_label_set_text().\nfunc (v *Label) SetText(str string) {\n\tcstr := C.CString(str)\n\tdefer C.free(unsafe.Pointer(cstr))\n\tC.gtk_label_set_text(v.native(), (*C.gchar)(cstr))\n}\n\n\/\/ TODO:\n\/\/ gtk_label_set_text_with_mnemonic().\n\/\/ gtk_label_set_attributes().\n\/\/ gtk_label_get_attributes().\n\n\/\/ SetMarkup is a wrapper around gtk_label_set_markup().\nfunc (v *Label) SetMarkup(str string) {\n\tcstr := C.CString(str)\n\tdefer C.free(unsafe.Pointer(cstr))\n\tC.gtk_label_set_markup(v.native(), (*C.gchar)(cstr))\n}\n\n\/\/ SetMarkupWithMnemonic is a wrapper around\n\/\/ gtk_label_set_markup_with_mnemonic().\nfunc (v *Label) SetMarkupWithMnemonic(str string) {\n\tcstr := C.CString(str)\n\tdefer C.free(unsafe.Pointer(cstr))\n\tC.gtk_label_set_markup_with_mnemonic(v.native(), (*C.gchar)(cstr))\n}\n\n\/\/ SetPattern is a wrapper around gtk_label_set_pattern().\nfunc (v *Label) SetPattern(patern string) {\n\tcstr := C.CString(patern)\n\tdefer C.free(unsafe.Pointer(cstr))\n\tC.gtk_label_set_pattern(v.native(), (*C.gchar)(cstr))\n}\n\n\/\/ SetJustify is a wrapper around gtk_label_set_justify().\nfunc (v *Label) SetJustify(jtype Justification) {\n\tC.gtk_label_set_justify(v.native(), C.GtkJustification(jtype))\n}\n\n\/\/ SetEllipsize is a wrapper around gtk_label_set_ellipsize().\nfunc (v *Label) SetEllipsize(mode pango.EllipsizeMode) {\n\tC.gtk_label_set_ellipsize(v.native(), C.PangoEllipsizeMode(mode))\n}\n\n\/\/ GetWidthChars is a wrapper around gtk_label_get_width_chars().\nfunc (v *Label) GetWidthChars() int {\n\tc := C.gtk_label_get_width_chars(v.native())\n\treturn int(c)\n}\n\n\/\/ SetWidthChars is a wrapper around gtk_label_set_width_chars().\nfunc (v *Label) SetWidthChars(nChars int) {\n\tC.gtk_label_set_width_chars(v.native(), C.gint(nChars))\n}\n\n\/\/ GetMaxWidthChars is a wrapper around gtk_label_get_max_width_chars().\nfunc (v *Label) GetMaxWidthChars() int {\n\tc := C.gtk_label_get_max_width_chars(v.native())\n\treturn int(c)\n}\n\n\/\/ SetMaxWidthChars is a wrapper around gtk_label_set_max_width_chars().\nfunc (v *Label) SetMaxWidthChars(nChars int) {\n\tC.gtk_label_set_max_width_chars(v.native(), C.gint(nChars))\n}\n\n\/\/ GetLineWrap is a wrapper around gtk_label_get_line_wrap().\nfunc (v *Label) GetLineWrap() bool {\n\tc := C.gtk_label_get_line_wrap(v.native())\n\treturn gobool(c)\n}\n\n\/\/ SetLineWrap is a wrapper around gtk_label_set_line_wrap().\nfunc (v *Label) SetLineWrap(wrap bool) {\n\tC.gtk_label_set_line_wrap(v.native(), gbool(wrap))\n}\n\n\/\/ SetLineWrapMode is a wrapper around gtk_label_set_line_wrap_mode().\nfunc (v *Label) SetLineWrapMode(wrapMode pango.WrapMode) {\n\tC.gtk_label_set_line_wrap_mode(v.native(), C.PangoWrapMode(wrapMode))\n}\n\n\/\/ TODO:\n\/\/ gtk_label_get_line_wrap_mode().\n\/\/ gtk_label_get_layout_offsets().\n\/\/ gtk_label_get_layout().\n\/\/ gtk_label_get_mnemonic_widget().\n\n\/\/ GetSelectable is a wrapper around gtk_label_get_selectable().\nfunc (v *Label) GetSelectable() bool {\n\tc := C.gtk_label_get_selectable(v.native())\n\treturn gobool(c)\n}\n\n\/\/ GetText is a wrapper around gtk_label_get_text().\nfunc (v *Label) GetText() (string, error) {\n\tc := C.gtk_label_get_text(v.native())\n\tif c == nil {\n\t\treturn \"\", nilPtrErr\n\t}\n\treturn C.GoString((*C.char)(c)), nil\n}\n\n\/\/ GetJustify is a wrapper around gtk_label_get_justify().\nfunc (v *Label) GetJustify() Justification {\n\tc := C.gtk_label_get_justify(v.native())\n\treturn Justification(c)\n}\n\n\/\/ GetEllipsize is a wrapper around gtk_label_get_ellipsize().\nfunc (v *Label) GetEllipsize() pango.EllipsizeMode {\n\tc := C.gtk_label_get_ellipsize(v.native())\n\treturn pango.EllipsizeMode(c)\n}\n\n\/\/ GetCurrentUri is a wrapper around gtk_label_get_current_uri().\nfunc (v *Label) GetCurrentUri() string {\n\tc := C.gtk_label_get_current_uri(v.native())\n\treturn C.GoString((*C.char)(c))\n}\n\n\/\/ GetTrackVisitedLinks is a wrapper around gtk_label_get_track_visited_links().\nfunc (v *Label) GetTrackVisitedLinks() bool {\n\tc := C.gtk_label_get_track_visited_links(v.native())\n\treturn gobool(c)\n}\n\n\/\/ SetTrackVisitedLinks is a wrapper around gtk_label_set_track_visited_links().\nfunc (v *Label) SetTrackVisitedLinks(trackLinks bool) {\n\tC.gtk_label_set_track_visited_links(v.native(), gbool(trackLinks))\n}\n\n\/\/ GetAngle is a wrapper around gtk_label_get_angle().\nfunc (v *Label) GetAngle() float64 {\n\tc := C.gtk_label_get_angle(v.native())\n\treturn float64(c)\n}\n\n\/\/ SetAngle is a wrapper around gtk_label_set_angle().\nfunc (v *Label) SetAngle(angle float64) {\n\tC.gtk_label_set_angle(v.native(), C.gdouble(angle))\n}\n\n\/\/ GetSelectionBounds is a wrapper around gtk_label_get_selection_bounds().\nfunc (v *Label) GetSelectionBounds() (start, end int, nonEmpty bool) {\n\tvar cstart, cend C.gint\n\tc := C.gtk_label_get_selection_bounds(v.native(), &cstart, &cend)\n\treturn int(cstart), int(cend), gobool(c)\n}\n\n\/\/ GetSingleLineMode is a wrapper around gtk_label_get_single_line_mode().\nfunc (v *Label) GetSingleLineMode() bool {\n\tc := C.gtk_label_get_single_line_mode(v.native())\n\treturn gobool(c)\n}\n\n\/\/ SetSingleLineMode is a wrapper around gtk_label_set_single_line_mode().\nfunc (v *Label) SetSingleLineMode(mode bool) {\n\tC.gtk_label_set_single_line_mode(v.native(), gbool(mode))\n}\n\n\/\/ GetUseMarkup is a wrapper around gtk_label_get_use_markup().\nfunc (v *Label) GetUseMarkup() bool {\n\tc := C.gtk_label_get_use_markup(v.native())\n\treturn gobool(c)\n}\n\n\/\/ SetUseMarkup is a wrapper around gtk_label_set_use_markup().\nfunc (v *Label) SetUseMarkup(use bool) {\n\tC.gtk_label_set_use_markup(v.native(), gbool(use))\n}\n\n\/\/ GetUseUnderline is a wrapper around gtk_label_get_use_underline().\nfunc (v *Label) GetUseUnderline() bool {\n\tc := C.gtk_label_get_use_underline(v.native())\n\treturn gobool(c)\n}\n\n\/\/ SetUseUnderline is a wrapper around gtk_label_set_use_underline().\nfunc (v *Label) SetUseUnderline(use bool) {\n\tC.gtk_label_set_use_underline(v.native(), gbool(use))\n}\n\n\/\/ LabelNewWithMnemonic is a wrapper around gtk_label_new_with_mnemonic().\nfunc LabelNewWithMnemonic(str string) (*Label, error) {\n\tcstr := C.CString(str)\n\tdefer C.free(unsafe.Pointer(cstr))\n\tc := C.gtk_label_new_with_mnemonic((*C.gchar)(cstr))\n\tif c == nil {\n\t\treturn nil, nilPtrErr\n\t}\n\tobj := glib.Take(unsafe.Pointer(c))\n\treturn wrapLabel(obj), nil\n}\n\n\/\/ SelectRegion is a wrapper around gtk_label_select_region().\nfunc (v *Label) SelectRegion(startOffset, endOffset int) {\n\tC.gtk_label_select_region(v.native(), C.gint(startOffset),\n\t\tC.gint(endOffset))\n}\n\n\/\/ SetSelectable is a wrapper around gtk_label_set_selectable().\nfunc (v *Label) SetSelectable(setting bool) {\n\tC.gtk_label_set_selectable(v.native(), gbool(setting))\n}\n\n\/\/ SetLabel is a wrapper around gtk_label_set_label().\nfunc (v *Label) SetLabel(str string) {\n\tcstr := C.CString(str)\n\tdefer C.free(unsafe.Pointer(cstr))\n\tC.gtk_label_set_label(v.native(), (*C.gchar)(cstr))\n}\n\n\/\/ GetLabel is a wrapper around gtk_label_get_label().\nfunc (v *Label) GetLabel() string {\n\tc := C.gtk_label_get_label(v.native())\n\tif c == nil {\n\t\treturn \"\"\n\t}\n\treturn C.GoString((*C.char)(c))\n}\n\n\/\/ GetMnemonicKeyval is a wrapper around gtk_label_get_mnemonic_keyval().\nfunc (v *Label) GetMnemonicKeyval() uint {\n\treturn uint(C.gtk_label_get_mnemonic_keyval(v.native()))\n}\n\n\/\/ SetMnemonicWidget is a wrapper around gtk_label_set_mnemonic_widget().\nfunc (v *Label) SetMnemonicWidget(widget IWidget) {\n\tC.gtk_label_set_mnemonic_widget(v.native(), widget.toWidget())\n}\n<|endoftext|>"} {"text":"\/\/ NOTE: SHOULD BE RUN FROM run_tests directory\n\/\/ note: deploy2deter must be run from within it's directory\n\/\/\n\/\/ Outputting data: output to csv files (for loading into excel)\n\/\/ make a datastructure per test output file\n\/\/ all output should be in the test_data subdirectory\n\/\/\n\/\/ connect with logging server (receive json until \"EOF\" seen or \"terminating\")\n\/\/ connect to websocket ws:\/\/localhost:8080\/log\n\/\/ receive each message as bytes\n\/\/\t\t if bytes contains \"EOF\" or contains \"terminating\"\n\/\/ wrap up the round, output to test_data directory, kill deploy2deter\n\/\/\n\/\/ for memstats check localhost:8080\/d\/server-0-0\/debug\/vars\n\/\/ parse out the memstats zones that we are concerned with\n\/\/\n\/\/ different graphs needed rounds:\n\/\/ load on the x-axis: increase messages per round holding everything else constant\n\/\/\t\t\thpn=40 bf=10, bf=50\n\/\/\n\/\/ run time command with the deploy2deter exec.go (timestamper) instance associated with the root\n\/\/ and a random set of servers\n\/\/\n\/\/ latency on y-axis, timestamp servers on x-axis push timestampers as higher as possible\n\/\/\n\/\/\n\/\/ RunTest(hpn, bf), Monitor() -> RunStats() -> csv -> Excel\n\/\/\npackage main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strconv\"\n\t\"time\"\n)\n\ntype T struct {\n\tnmachs int\n\thpn int\n\tbf int\n\trate int\n\trounds int\n\tfailures int\n\trFail int\n\tfFail int\n\ttestConnect bool\n}\n\nvar DefaultMachs int = 32\n\n\/\/ time-per-round * DefaultRounds = 10 * 20 = 3.3 minutes now\n\/\/ this leaves us with 7 minutes for test setup and tear-down\nvar DefaultRounds int = 20\n\nvar view bool\nvar debug string = \"-debug=false\"\n\n\/\/ hpn, bf, nmsgsG\nfunc RunTest(t T) (RunStats, error) {\n\t\/\/ add timeout for 10 minutes?\n\tdone := make(chan struct{})\n\tvar rs RunStats\n\tnmachs := fmt.Sprintf(\"-nmachs=%d\", t.nmachs)\n\thpn := fmt.Sprintf(\"-hpn=%d\", t.hpn)\n\tnmsgs := fmt.Sprintf(\"-nmsgs=%d\", -1)\n\tbf := fmt.Sprintf(\"-bf=%d\", t.bf)\n\trate := fmt.Sprintf(\"-rate=%d\", t.rate)\n\trounds := fmt.Sprintf(\"-rounds=%d\", t.rounds)\n\tfailures := fmt.Sprintf(\"-failures=%d\", t.failures)\n\trFail := fmt.Sprintf(\"-rfail=%d\", t.rFail)\n\tfFail := fmt.Sprintf(\"-ffail=%d\", t.fFail)\n\ttcon := fmt.Sprintf(\"-test_connect=%t\", t.testConnect)\n\tcmd := exec.Command(\".\/deploy2deter\", nmachs, hpn, nmsgs, bf, rate, rounds, debug, failures, rFail, fFail, tcon)\n\tlog.Println(\"RUNNING TEST:\", cmd.Args)\n\tlog.Println(\"FAILURES PERCENT:\", t.failures)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\n\terr := cmd.Start()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ give it a while to start up\n\ttime.Sleep(30 * time.Second)\n\n\tgo func() {\n\t\trs = Monitor(t.bf)\n\t\tcmd.Process.Kill()\n\t\tfmt.Println(\"TEST COMPLETE:\", rs)\n\t\tdone <- struct{}{}\n\t}()\n\n\t\/\/ timeout the command if it takes too long\n\tselect {\n\tcase <-done:\n\t\tif isZero(rs.MinTime) || isZero(rs.MaxTime) || isZero(rs.AvgTime) || math.IsNaN(rs.Rate) || math.IsInf(rs.Rate, 0) {\n\t\t\treturn rs, errors.New(\"unable to get good data\")\n\t\t}\n\t\treturn rs, nil\n\tcase <-time.After(10 * time.Minute):\n\t\treturn rs, errors.New(\"timed out\")\n\t}\n}\n\n\/\/ RunTests runs the given tests and puts the output into the\n\/\/ given file name. It outputs RunStats in a CSV format.\nfunc RunTests(name string, ts []T) {\n\n\trs := make([]RunStats, len(ts))\n\tf, err := os.OpenFile(TestFile(name), os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0660)\n\tif err != nil {\n\t\tlog.Fatal(\"error opening test file:\", err)\n\t}\n\t_, err = f.Write(rs[0].CSVHeader())\n\tif err != nil {\n\t\tlog.Fatal(\"error writing test file header:\", err)\n\t}\n\terr = f.Sync()\n\tif err != nil {\n\t\tlog.Fatal(\"error syncing test file:\", err)\n\t}\n\n\tnTimes := 2\n\tstopOnSuccess := true\n\tfor i, t := range ts {\n\t\t\/\/ run test t nTimes times\n\t\t\/\/ take the average of all successfull runs\n\t\tvar runs []RunStats\n\t\tfor r := 0; r < nTimes; r++ {\n\t\t\trun, err := RunTest(t)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"error running test:\", err)\n\t\t\t}\n\n\t\t\t\/\/ Clean Up after test\n\t\t\tlog.Println(\"KILLING REMAINING PROCESSES\")\n\t\t\tcmd := exec.Command(\".\/deploy2deter\", \"-kill=true\")\n\t\t\tcmd.Stdout = os.Stdout\n\t\t\tcmd.Stderr = os.Stderr\n\t\t\tcmd.Run()\n\t\t\tif err == nil {\n\t\t\t\truns = append(runs, run)\n\t\t\t\tif stopOnSuccess {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\n\t\tif len(runs) == 0 {\n\t\t\tlog.Println(\"unable to get any data for test:\", t)\n\t\t\tcontinue\n\t\t}\n\n\t\trs[i] = RunStatsAvg(runs)\n\t\t_, err := f.Write(rs[i].CSV())\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"error writing data to test file:\", err)\n\t\t}\n\t\terr = f.Sync()\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"error syncing data to test file:\", err)\n\t\t}\n\n\t\tcl, err := os.OpenFile(\n\t\t\tTestFile(\"client_latency_\"+name+\"_\"+strconv.Itoa(i)),\n\t\t\tos.O_CREATE|os.O_RDWR|os.O_TRUNC, 0660)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"error opening test file:\", err)\n\t\t}\n\t\t_, err = cl.Write(rs[i].TimesCSV())\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"error writing client latencies to file:\", err)\n\t\t}\n\t\terr = cl.Sync()\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"error syncing data to latency file:\", err)\n\t\t}\n\t\tcl.Close()\n\n\t}\n}\n\n\/\/ high and low specify how many milliseconds between messages\nfunc RateLoadTest(hpn, bf int) []T {\n\treturn []T{\n\t\t{DefaultMachs, hpn, bf, 5000, DefaultRounds, 0, 0, 0, false}, \/\/ never send a message\n\t\t{DefaultMachs, hpn, bf, 5000, DefaultRounds, 0, 0, 0, false}, \/\/ one per round\n\t\t{DefaultMachs, hpn, bf, 500, DefaultRounds, 0, 0, 0, false}, \/\/ 10 per round\n\t\t{DefaultMachs, hpn, bf, 50, DefaultRounds, 0, 0, 0, false}, \/\/ 100 per round\n\t\t{DefaultMachs, hpn, bf, 30, DefaultRounds, 0, 0, 0, false}, \/\/ 1000 per round\n\t}\n}\n\nfunc DepthTest(hpn, low, high, step int) []T {\n\tts := make([]T, 0)\n\tfor bf := low; bf <= high; bf += step {\n\t\tts = append(ts, T{DefaultMachs, hpn, bf, 10, DefaultRounds, 0, 0, 0, false})\n\t}\n\treturn ts\n}\n\nfunc DepthTestFixed(hpn int) []T {\n\treturn []T{\n\t\t{DefaultMachs, hpn, 1, 30, DefaultRounds, 0, 0, 0, false},\n\t\t{DefaultMachs, hpn, 2, 30, DefaultRounds, 0, 0, 0, false},\n\t\t{DefaultMachs, hpn, 4, 30, DefaultRounds, 0, 0, 0, false},\n\t\t{DefaultMachs, hpn, 8, 30, DefaultRounds, 0, 0, 0, false},\n\t\t{DefaultMachs, hpn, 16, 30, DefaultRounds, 0, 0, 0, false},\n\t\t{DefaultMachs, hpn, 32, 30, DefaultRounds, 0, 0, 0, false},\n\t\t{DefaultMachs, hpn, 64, 30, DefaultRounds, 0, 0, 0, false},\n\t\t{DefaultMachs, hpn, 128, 30, DefaultRounds, 0, 0, 0, false},\n\t\t{DefaultMachs, hpn, 256, 30, DefaultRounds, 0, 0, 0, false},\n\t\t{DefaultMachs, hpn, 512, 30, DefaultRounds, 0, 0, 0, false},\n\t}\n}\n\nfunc ScaleTest(bf, low, high, mult int) []T {\n\tts := make([]T, 0)\n\tfor hpn := low; hpn <= high; hpn *= mult {\n\t\tts = append(ts, T{DefaultMachs, hpn, bf, 10, DefaultRounds, 0, 0, 0, false})\n\t}\n\treturn ts\n}\n\n\/\/ nmachs=32, hpn=128, bf=16, rate=500, failures=20, root failures, failures\nvar FailureTests = []T{\n\t{DefaultMachs, 64, 16, 30, 50, 0, 0, 0, false},\n\t{DefaultMachs, 64, 16, 30, 50, 0, 5, 0, false},\n\t{DefaultMachs, 64, 16, 30, 50, 0, 10, 0, false},\n\t{DefaultMachs, 64, 16, 30, 50, 5, 0, 5, false},\n\t{DefaultMachs, 64, 16, 30, 50, 5, 0, 10, false},\n\t{DefaultMachs, 64, 16, 30, 50, 5, 0, 10, true},\n}\n\nvar VotingTest = []T{\n\t{DefaultMachs, 64, 16, 30, 50, 0, 0, 0, true},\n\t{DefaultMachs, 64, 16, 30, 50, 0, 0, 0, false},\n}\n\nfunc FullTests() []T {\n\tvar nmachs = []int{1, 16, 32}\n\tvar hpns = []int{1, 16, 32, 128}\n\tvar bfs = []int{2, 4, 8, 16, 128}\n\tvar rates = []int{5000, 500, 100, 30}\n\tfailures := 0\n\n\tvar tests []T\n\tfor _, nmach := range nmachs {\n\t\tfor _, hpn := range hpns {\n\t\t\tfor _, bf := range bfs {\n\t\t\t\tfor _, rate := range rates {\n\t\t\t\t\ttests = append(tests, T{nmach, hpn, bf, rate, DefaultRounds, failures, 0, 0, false})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn tests\n}\n\nvar HostsTest = []T{\n\t{DefaultMachs, 1, 2, 30, 20, 0, 0, 0, false},\n\t{DefaultMachs, 2, 3, 30, 20, 0, 0, 0, false},\n\t{DefaultMachs, 4, 3, 30, 20, 0, 0, 0, false},\n\t{DefaultMachs, 8, 8, 30, 20, 0, 0, 0, false},\n\t{DefaultMachs, 16, 16, 30, 20, 0, 0, 0, false},\n\t{DefaultMachs, 32, 16, 30, 20, 0, 0, 0, false},\n\t{DefaultMachs, 64, 16, 30, 20, 0, 0, 0, false},\n\t{DefaultMachs, 128, 16, 30, 50, 0, 0, 0, false},\n}\n\nfunc main() {\n\tSetDebug(false)\n\t\/\/ view = true\n\tos.Chdir(\"..\")\n\n\tMkTestDir()\n\n\terr := exec.Command(\"go\", \"build\", \"-v\").Run()\n\tif err != nil {\n\t\tlog.Fatalln(\"error building deploy2deter:\", err)\n\t}\n\tlog.Println(\"KILLING REMAINING PROCESSES\")\n\tcmd := exec.Command(\".\/deploy2deter\", \"-kill=true\")\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tcmd.Run()\n\n\t\/\/ test the testing framework\n\n\t\/\/ DefaultRounds = 5\n\t\/\/ t := FailureTests\n\t\/\/ RunTests(\"failure_test.csv\", t)\n\tRunTests(\"vote_test\", VotingTest)\n\tRunTests(\"failure_test\", FailureTests)\n\t\/\/ RunTests(\"host_test\", HostsTest)\n\t\/\/ t := FailureTests\n\t\/\/ RunTests(\"failure_test\", t)\n\t\/\/ t = ScaleTest(10, 1, 100, 2)\n\t\/\/ RunTests(\"scale_test.csv\", t)\n\t\/\/ how does the branching factor effect speed\n\t\/\/ t = DepthTestFixed(100)\n\t\/\/ RunTests(\"depth_test.csv\", t)\n\n\t\/\/ load test the client\n\t\/\/ t = RateLoadTest(40, 10)\n\t\/\/ RunTests(\"load_rate_test_bf10.csv\", t)\n\t\/\/ t = RateLoadTest(40, 50)\n\t\/\/ RunTests(\"load_rate_test_bf50.csv\", t)\n\n}\n\nfunc MkTestDir() {\n\terr := os.MkdirAll(\"test_data\/\", 0777)\n\tif err != nil {\n\t\tlog.Fatal(\"failed to make test directory\")\n\t}\n}\n\nfunc TestFile(name string) string {\n\treturn \"test_data\/\" + name + \".csv\"\n}\n\nfunc SetDebug(b bool) {\n\tif b {\n\t\tdebug = \"-debug=true\"\n\t} else {\n\t\tdebug = \"-debug=false\"\n\t}\n}\n\nfunc isZero(f float64) bool {\n\treturn math.Abs(f) < 0.0000001\n}\nmade test for voting\/\/ NOTE: SHOULD BE RUN FROM run_tests directory\n\/\/ note: deploy2deter must be run from within it's directory\n\/\/\n\/\/ Outputting data: output to csv files (for loading into excel)\n\/\/ make a datastructure per test output file\n\/\/ all output should be in the test_data subdirectory\n\/\/\n\/\/ connect with logging server (receive json until \"EOF\" seen or \"terminating\")\n\/\/ connect to websocket ws:\/\/localhost:8080\/log\n\/\/ receive each message as bytes\n\/\/\t\t if bytes contains \"EOF\" or contains \"terminating\"\n\/\/ wrap up the round, output to test_data directory, kill deploy2deter\n\/\/\n\/\/ for memstats check localhost:8080\/d\/server-0-0\/debug\/vars\n\/\/ parse out the memstats zones that we are concerned with\n\/\/\n\/\/ different graphs needed rounds:\n\/\/ load on the x-axis: increase messages per round holding everything else constant\n\/\/\t\t\thpn=40 bf=10, bf=50\n\/\/\n\/\/ run time command with the deploy2deter exec.go (timestamper) instance associated with the root\n\/\/ and a random set of servers\n\/\/\n\/\/ latency on y-axis, timestamp servers on x-axis push timestampers as higher as possible\n\/\/\n\/\/\n\/\/ RunTest(hpn, bf), Monitor() -> RunStats() -> csv -> Excel\n\/\/\npackage main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"math\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"strconv\"\n\t\"time\"\n)\n\ntype T struct {\n\tnmachs int\n\thpn int\n\tbf int\n\trate int\n\trounds int\n\tfailures int\n\trFail int\n\tfFail int\n\ttestConnect bool\n}\n\nvar DefaultMachs int = 32\n\n\/\/ time-per-round * DefaultRounds = 10 * 20 = 3.3 minutes now\n\/\/ this leaves us with 7 minutes for test setup and tear-down\nvar DefaultRounds int = 20\n\nvar view bool\nvar debug string = \"-debug=false\"\n\n\/\/ hpn, bf, nmsgsG\nfunc RunTest(t T) (RunStats, error) {\n\t\/\/ add timeout for 10 minutes?\n\tdone := make(chan struct{})\n\tvar rs RunStats\n\tnmachs := fmt.Sprintf(\"-nmachs=%d\", t.nmachs)\n\thpn := fmt.Sprintf(\"-hpn=%d\", t.hpn)\n\tnmsgs := fmt.Sprintf(\"-nmsgs=%d\", -1)\n\tbf := fmt.Sprintf(\"-bf=%d\", t.bf)\n\trate := fmt.Sprintf(\"-rate=%d\", t.rate)\n\trounds := fmt.Sprintf(\"-rounds=%d\", t.rounds)\n\tfailures := fmt.Sprintf(\"-failures=%d\", t.failures)\n\trFail := fmt.Sprintf(\"-rfail=%d\", t.rFail)\n\tfFail := fmt.Sprintf(\"-ffail=%d\", t.fFail)\n\ttcon := fmt.Sprintf(\"-test_connect=%t\", t.testConnect)\n\tcmd := exec.Command(\".\/deploy2deter\", nmachs, hpn, nmsgs, bf, rate, rounds, debug, failures, rFail, fFail, tcon)\n\tlog.Println(\"RUNNING TEST:\", cmd.Args)\n\tlog.Println(\"FAILURES PERCENT:\", t.failures)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\n\terr := cmd.Start()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ give it a while to start up\n\ttime.Sleep(30 * time.Second)\n\n\tgo func() {\n\t\trs = Monitor(t.bf)\n\t\tcmd.Process.Kill()\n\t\tfmt.Println(\"TEST COMPLETE:\", rs)\n\t\tdone <- struct{}{}\n\t}()\n\n\t\/\/ timeout the command if it takes too long\n\tselect {\n\tcase <-done:\n\t\tif isZero(rs.MinTime) || isZero(rs.MaxTime) || isZero(rs.AvgTime) || math.IsNaN(rs.Rate) || math.IsInf(rs.Rate, 0) {\n\t\t\treturn rs, errors.New(\"unable to get good data\")\n\t\t}\n\t\treturn rs, nil\n\tcase <-time.After(10 * time.Minute):\n\t\treturn rs, errors.New(\"timed out\")\n\t}\n}\n\n\/\/ RunTests runs the given tests and puts the output into the\n\/\/ given file name. It outputs RunStats in a CSV format.\nfunc RunTests(name string, ts []T) {\n\n\trs := make([]RunStats, len(ts))\n\tf, err := os.OpenFile(TestFile(name), os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0660)\n\tif err != nil {\n\t\tlog.Fatal(\"error opening test file:\", err)\n\t}\n\t_, err = f.Write(rs[0].CSVHeader())\n\tif err != nil {\n\t\tlog.Fatal(\"error writing test file header:\", err)\n\t}\n\terr = f.Sync()\n\tif err != nil {\n\t\tlog.Fatal(\"error syncing test file:\", err)\n\t}\n\n\tnTimes := 2\n\tstopOnSuccess := true\n\tfor i, t := range ts {\n\t\t\/\/ run test t nTimes times\n\t\t\/\/ take the average of all successfull runs\n\t\tvar runs []RunStats\n\t\tfor r := 0; r < nTimes; r++ {\n\t\t\trun, err := RunTest(t)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"error running test:\", err)\n\t\t\t}\n\n\t\t\t\/\/ Clean Up after test\n\t\t\tlog.Println(\"KILLING REMAINING PROCESSES\")\n\t\t\tcmd := exec.Command(\".\/deploy2deter\", \"-kill=true\")\n\t\t\tcmd.Stdout = os.Stdout\n\t\t\tcmd.Stderr = os.Stderr\n\t\t\tcmd.Run()\n\t\t\tif err == nil {\n\t\t\t\truns = append(runs, run)\n\t\t\t\tif stopOnSuccess {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\n\t\tif len(runs) == 0 {\n\t\t\tlog.Println(\"unable to get any data for test:\", t)\n\t\t\tcontinue\n\t\t}\n\n\t\trs[i] = RunStatsAvg(runs)\n\t\t_, err := f.Write(rs[i].CSV())\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"error writing data to test file:\", err)\n\t\t}\n\t\terr = f.Sync()\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"error syncing data to test file:\", err)\n\t\t}\n\n\t\tcl, err := os.OpenFile(\n\t\t\tTestFile(\"client_latency_\"+name+\"_\"+strconv.Itoa(i)),\n\t\t\tos.O_CREATE|os.O_RDWR|os.O_TRUNC, 0660)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"error opening test file:\", err)\n\t\t}\n\t\t_, err = cl.Write(rs[i].TimesCSV())\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"error writing client latencies to file:\", err)\n\t\t}\n\t\terr = cl.Sync()\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"error syncing data to latency file:\", err)\n\t\t}\n\t\tcl.Close()\n\n\t}\n}\n\n\/\/ high and low specify how many milliseconds between messages\nfunc RateLoadTest(hpn, bf int) []T {\n\treturn []T{\n\t\t{DefaultMachs, hpn, bf, 5000, DefaultRounds, 0, 0, 0, false}, \/\/ never send a message\n\t\t{DefaultMachs, hpn, bf, 5000, DefaultRounds, 0, 0, 0, false}, \/\/ one per round\n\t\t{DefaultMachs, hpn, bf, 500, DefaultRounds, 0, 0, 0, false}, \/\/ 10 per round\n\t\t{DefaultMachs, hpn, bf, 50, DefaultRounds, 0, 0, 0, false}, \/\/ 100 per round\n\t\t{DefaultMachs, hpn, bf, 30, DefaultRounds, 0, 0, 0, false}, \/\/ 1000 per round\n\t}\n}\n\nfunc DepthTest(hpn, low, high, step int) []T {\n\tts := make([]T, 0)\n\tfor bf := low; bf <= high; bf += step {\n\t\tts = append(ts, T{DefaultMachs, hpn, bf, 10, DefaultRounds, 0, 0, 0, false})\n\t}\n\treturn ts\n}\n\nfunc DepthTestFixed(hpn int) []T {\n\treturn []T{\n\t\t{DefaultMachs, hpn, 1, 30, DefaultRounds, 0, 0, 0, false},\n\t\t{DefaultMachs, hpn, 2, 30, DefaultRounds, 0, 0, 0, false},\n\t\t{DefaultMachs, hpn, 4, 30, DefaultRounds, 0, 0, 0, false},\n\t\t{DefaultMachs, hpn, 8, 30, DefaultRounds, 0, 0, 0, false},\n\t\t{DefaultMachs, hpn, 16, 30, DefaultRounds, 0, 0, 0, false},\n\t\t{DefaultMachs, hpn, 32, 30, DefaultRounds, 0, 0, 0, false},\n\t\t{DefaultMachs, hpn, 64, 30, DefaultRounds, 0, 0, 0, false},\n\t\t{DefaultMachs, hpn, 128, 30, DefaultRounds, 0, 0, 0, false},\n\t\t{DefaultMachs, hpn, 256, 30, DefaultRounds, 0, 0, 0, false},\n\t\t{DefaultMachs, hpn, 512, 30, DefaultRounds, 0, 0, 0, false},\n\t}\n}\n\nfunc ScaleTest(bf, low, high, mult int) []T {\n\tts := make([]T, 0)\n\tfor hpn := low; hpn <= high; hpn *= mult {\n\t\tts = append(ts, T{DefaultMachs, hpn, bf, 10, DefaultRounds, 0, 0, 0, false})\n\t}\n\treturn ts\n}\n\n\/\/ nmachs=32, hpn=128, bf=16, rate=500, failures=20, root failures, failures\nvar FailureTests = []T{\n\t{DefaultMachs, 64, 16, 30, 50, 0, 0, 0, false},\n\t{DefaultMachs, 64, 16, 30, 50, 0, 5, 0, false},\n\t{DefaultMachs, 64, 16, 30, 50, 0, 10, 0, false},\n\t{DefaultMachs, 64, 16, 30, 50, 5, 0, 5, false},\n\t{DefaultMachs, 64, 16, 30, 50, 5, 0, 10, false},\n\t{DefaultMachs, 64, 16, 30, 50, 5, 0, 10, true},\n}\n\nvar VotingTest = []T{\n\t{DefaultMachs, 64, 16, 30, 50, 0, 0, 0, true},\n\t{DefaultMachs, 64, 16, 30, 50, 0, 0, 0, false},\n}\n\nfunc FullTests() []T {\n\tvar nmachs = []int{1, 16, 32}\n\tvar hpns = []int{1, 16, 32, 128}\n\tvar bfs = []int{2, 4, 8, 16, 128}\n\tvar rates = []int{5000, 500, 100, 30}\n\tfailures := 0\n\n\tvar tests []T\n\tfor _, nmach := range nmachs {\n\t\tfor _, hpn := range hpns {\n\t\t\tfor _, bf := range bfs {\n\t\t\t\tfor _, rate := range rates {\n\t\t\t\t\ttests = append(tests, T{nmach, hpn, bf, rate, DefaultRounds, failures, 0, 0, false})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn tests\n}\n\nvar HostsTest = []T{\n\t{DefaultMachs, 1, 2, 30, 20, 0, 0, 0, false},\n\t{DefaultMachs, 2, 3, 30, 20, 0, 0, 0, false},\n\t{DefaultMachs, 4, 3, 30, 20, 0, 0, 0, false},\n\t{DefaultMachs, 8, 8, 30, 20, 0, 0, 0, false},\n\t{DefaultMachs, 16, 16, 30, 20, 0, 0, 0, false},\n\t{DefaultMachs, 32, 16, 30, 20, 0, 0, 0, false},\n\t{DefaultMachs, 64, 16, 30, 20, 0, 0, 0, false},\n\t{DefaultMachs, 128, 16, 30, 50, 0, 0, 0, false},\n}\nvar VTest = []T{\n\t{DefaultMachs, 1, 2, 10000000, 50, 0, 0, 0, false},\n}\n\nfunc main() {\n\tSetDebug(false)\n\t\/\/ view = true\n\tos.Chdir(\"..\")\n\n\tMkTestDir()\n\n\terr := exec.Command(\"go\", \"build\", \"-v\").Run()\n\tif err != nil {\n\t\tlog.Fatalln(\"error building deploy2deter:\", err)\n\t}\n\tlog.Println(\"KILLING REMAINING PROCESSES\")\n\tcmd := exec.Command(\".\/deploy2deter\", \"-kill=true\")\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tcmd.Run()\n\n\t\/\/ test the testing framework\n\tRunTests(\"vote_test_no_signing.csv\", VTest)\n\t\/\/ DefaultRounds = 5\n\t\/\/ t := FailureTests\n\t\/\/ RunTests(\"failure_test.csv\", t)\n\t\/\/ RunTests(\"vote_test\", VotingTest)\n\t\/\/ RunTests(\"failure_test\", FailureTests)\n\t\/\/ RunTests(\"host_test\", HostsTest)\n\t\/\/ t := FailureTests\n\t\/\/ RunTests(\"failure_test\", t)\n\t\/\/ t = ScaleTest(10, 1, 100, 2)\n\t\/\/ RunTests(\"scale_test.csv\", t)\n\t\/\/ how does the branching factor effect speed\n\t\/\/ t = DepthTestFixed(100)\n\t\/\/ RunTests(\"depth_test.csv\", t)\n\n\t\/\/ load test the client\n\t\/\/ t = RateLoadTest(40, 10)\n\t\/\/ RunTests(\"load_rate_test_bf10.csv\", t)\n\t\/\/ t = RateLoadTest(40, 50)\n\t\/\/ RunTests(\"load_rate_test_bf50.csv\", t)\n\n}\n\nfunc MkTestDir() {\n\terr := os.MkdirAll(\"test_data\/\", 0777)\n\tif err != nil {\n\t\tlog.Fatal(\"failed to make test directory\")\n\t}\n}\n\nfunc TestFile(name string) string {\n\treturn \"test_data\/\" + name + \".csv\"\n}\n\nfunc SetDebug(b bool) {\n\tif b {\n\t\tdebug = \"-debug=true\"\n\t} else {\n\t\tdebug = \"-debug=false\"\n\t}\n}\n\nfunc isZero(f float64) bool {\n\treturn math.Abs(f) < 0.0000001\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2011 Aaron Jacobs. All Rights Reserved.\n\/\/ Author: aaronjjacobs@gmail.com (Aaron Jacobs)\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage oglematchers\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"math\"\n\t\"reflect\"\n)\n\n\/\/ LessThan returns a matcher that matches integer, floating point, or strings\n\/\/ values v such that v < x. Comparison is not defined between numeric and\n\/\/ string types, but is defined between all integer and floating point types.\n\/\/\n\/\/ x must itself be an integer, floating point, or string type; otherwise,\n\/\/ LessThan will panic.\nfunc LessThan(x interface{}) Matcher {\n\tv := reflect.ValueOf(x)\n\tkind := v.Kind()\n\n\tswitch {\n\tcase isInteger(v):\n\tcase isFloat(v):\n\tcase kind == reflect.String:\n\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"LessThan: unexpected kind %v\", kind))\n\t}\n\n\treturn &lessThanMatcher{v}\n}\n\ntype lessThanMatcher struct {\n\tlimit reflect.Value\n}\n\nfunc (m *lessThanMatcher) Description() string {\n\t\/\/ Special case: make it clear that strings are strings.\n\tif m.limit.Kind() == reflect.String {\n\t\treturn fmt.Sprintf(\"less than \\\"%s\\\"\", m.limit.String())\n\t}\n\n\treturn fmt.Sprintf(\"less than %v\", m.limit.Interface())\n}\n\nfunc compareIntegers(v1, v2 reflect.Value) (res MatchResult, err error) {\n\tres = MATCH_FALSE\n\tswitch {\n\tcase isSignedInteger(v1) && isSignedInteger(v2):\n\t\tif v1.Int() < v2.Int() {\n\t\t\tres = MATCH_TRUE\n\t\t}\n\t\treturn\n\n\tcase isSignedInteger(v1) && isUnsignedInteger(v2):\n\t\tif v1.Int() < 0 || uint64(v1.Int()) < v2.Uint() {\n\t\t\tres = MATCH_TRUE\n\t\t}\n\t\treturn\n\n\tcase isUnsignedInteger(v1) && isSignedInteger(v2):\n\t\tif v1.Uint() <= math.MaxInt64 && int64(v1.Uint()) < v2.Int() {\n\t\t\tres = MATCH_TRUE\n\t\t}\n\t\treturn\n\n\tcase isUnsignedInteger(v1) && isUnsignedInteger(v2):\n\t\tif v1.Uint() < v2.Uint() {\n\t\t\tres = MATCH_TRUE\n\t\t}\n\t\treturn\n\t}\n\n\tpanic(fmt.Sprintf(\"compareIntegers: %v %v\", v1, v2))\n}\n\nfunc getFloat(v reflect.Value) float64 {\n\tswitch {\n\tcase isSignedInteger(v):\n\t\treturn float64(v.Int())\n\n\tcase isUnsignedInteger(v):\n\t\treturn float64(v.Uint())\n\n\tcase isFloat(v):\n\t\treturn v.Float()\n\t}\n\n\tpanic(fmt.Sprintf(\"getFloat: %v\", v))\n}\n\nfunc (m *lessThanMatcher) Matches(c interface{}) (res MatchResult, err error) {\n\tv1 := reflect.ValueOf(c)\n\tv2 := m.limit\n\n\tres = MATCH_FALSE\n\n\t\/\/ Handle strings as a special case.\n\tif v1.Kind() == reflect.String && v2.Kind() == reflect.String {\n\t\tif v1.String() < v2.String() {\n\t\t\tres = MATCH_TRUE\n\t\t}\n\t\treturn\n\t}\n\n\t\/\/ If we get here, we require that we are dealing with integers or floats.\n\tv1Legal := isInteger(v1) || isFloat(v1)\n\tv2Legal := isInteger(v2) || isFloat(v2)\n\tif !v1Legal || !v2Legal {\n\t\tres = MATCH_UNDEFINED\n\t\terr = errors.New(\"which is not comparable\")\n\t\treturn\n\t}\n\n\t\/\/ Handle the various comparison cases.\n\tswitch {\n\t\/\/ Both integers\n\tcase isInteger(v1) && isInteger(v2):\n\t\treturn compareIntegers(v1, v2)\n\n\t\/\/ At least one float32\n\tcase v1.Kind() == reflect.Float32 || v2.Kind() == reflect.Float32:\n\t\tif float32(getFloat(v1)) < float32(getFloat(v2)) {\n\t\t\tres = MATCH_TRUE\n\t\t}\n\t\treturn\n\n\t\/\/ At least one float64\n\tcase v1.Kind() == reflect.Float64 || v2.Kind() == reflect.Float64:\n\t\tif getFloat(v1) < getFloat(v2) {\n\t\t\tres = MATCH_TRUE\n\t\t}\n\t\treturn\n\t}\n\n\t\/\/ We shouldn't get here.\n\tpanic(fmt.Sprintf(\"lessThanMatcher.Matches: Shouldn't get here: %v %v\", v1, v2))\n}\nFixed up less_than.go for #20.\/\/ Copyright 2011 Aaron Jacobs. All Rights Reserved.\n\/\/ Author: aaronjjacobs@gmail.com (Aaron Jacobs)\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\npackage oglematchers\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"math\"\n\t\"reflect\"\n)\n\n\/\/ LessThan returns a matcher that matches integer, floating point, or strings\n\/\/ values v such that v < x. Comparison is not defined between numeric and\n\/\/ string types, but is defined between all integer and floating point types.\n\/\/\n\/\/ x must itself be an integer, floating point, or string type; otherwise,\n\/\/ LessThan will panic.\nfunc LessThan(x interface{}) Matcher {\n\tv := reflect.ValueOf(x)\n\tkind := v.Kind()\n\n\tswitch {\n\tcase isInteger(v):\n\tcase isFloat(v):\n\tcase kind == reflect.String:\n\n\tdefault:\n\t\tpanic(fmt.Sprintf(\"LessThan: unexpected kind %v\", kind))\n\t}\n\n\treturn &lessThanMatcher{v}\n}\n\ntype lessThanMatcher struct {\n\tlimit reflect.Value\n}\n\nfunc (m *lessThanMatcher) Description() string {\n\t\/\/ Special case: make it clear that strings are strings.\n\tif m.limit.Kind() == reflect.String {\n\t\treturn fmt.Sprintf(\"less than \\\"%s\\\"\", m.limit.String())\n\t}\n\n\treturn fmt.Sprintf(\"less than %v\", m.limit.Interface())\n}\n\nfunc compareIntegers(v1, v2 reflect.Value) (res bool, err error) {\n\tres = false\n\terr = errors.New(\"\")\n\n\tswitch {\n\tcase isSignedInteger(v1) && isSignedInteger(v2):\n\t\tif v1.Int() < v2.Int() {\n\t\t\tres = true\n\t\t\terr = nil\n\t\t}\n\t\treturn\n\n\tcase isSignedInteger(v1) && isUnsignedInteger(v2):\n\t\tif v1.Int() < 0 || uint64(v1.Int()) < v2.Uint() {\n\t\t\tres = true\n\t\t\terr = nil\n\t\t}\n\t\treturn\n\n\tcase isUnsignedInteger(v1) && isSignedInteger(v2):\n\t\tif v1.Uint() <= math.MaxInt64 && int64(v1.Uint()) < v2.Int() {\n\t\t\tres = true\n\t\t\terr = nil\n\t\t}\n\t\treturn\n\n\tcase isUnsignedInteger(v1) && isUnsignedInteger(v2):\n\t\tif v1.Uint() < v2.Uint() {\n\t\t\tres = true\n\t\t\terr = nil\n\t\t}\n\t\treturn\n\t}\n\n\tpanic(fmt.Sprintf(\"compareIntegers: %v %v\", v1, v2))\n}\n\nfunc getFloat(v reflect.Value) float64 {\n\tswitch {\n\tcase isSignedInteger(v):\n\t\treturn float64(v.Int())\n\n\tcase isUnsignedInteger(v):\n\t\treturn float64(v.Uint())\n\n\tcase isFloat(v):\n\t\treturn v.Float()\n\t}\n\n\tpanic(fmt.Sprintf(\"getFloat: %v\", v))\n}\n\nfunc (m *lessThanMatcher) Matches(c interface{}) (res bool, err error) {\n\tv1 := reflect.ValueOf(c)\n\tv2 := m.limit\n\n\tres = false\n\terr = errors.New(\"\")\n\n\t\/\/ Handle strings as a special case.\n\tif v1.Kind() == reflect.String && v2.Kind() == reflect.String {\n\t\tif v1.String() < v2.String() {\n\t\t\tres = true\n\t\t\terr = nil\n\t\t}\n\t\treturn\n\t}\n\n\t\/\/ If we get here, we require that we are dealing with integers or floats.\n\tv1Legal := isInteger(v1) || isFloat(v1)\n\tv2Legal := isInteger(v2) || isFloat(v2)\n\tif !v1Legal || !v2Legal {\n\t\tres = false\n\t\terr = NewFatalError(\"which is not comparable\")\n\t\treturn\n\t}\n\n\t\/\/ Handle the various comparison cases.\n\tswitch {\n\t\/\/ Both integers\n\tcase isInteger(v1) && isInteger(v2):\n\t\treturn compareIntegers(v1, v2)\n\n\t\/\/ At least one float32\n\tcase v1.Kind() == reflect.Float32 || v2.Kind() == reflect.Float32:\n\t\tif float32(getFloat(v1)) < float32(getFloat(v2)) {\n\t\t\tres = true\n\t\t\terr = nil\n\t\t}\n\t\treturn\n\n\t\/\/ At least one float64\n\tcase v1.Kind() == reflect.Float64 || v2.Kind() == reflect.Float64:\n\t\tif getFloat(v1) < getFloat(v2) {\n\t\t\tres = true\n\t\t\terr = nil\n\t\t}\n\t\treturn\n\t}\n\n\t\/\/ We shouldn't get here.\n\tpanic(fmt.Sprintf(\"lessThanMatcher.Matches: Shouldn't get here: %v %v\", v1, v2))\n}\n<|endoftext|>"} {"text":"package git\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst (\n\t\/\/ GitCommandDateLayout corresponds to `git log --date=format:%FT%T%z` date format.\n\tGitCommandDateLayout = \"2006-01-02T15:04:05-0700\"\n\n\tgitPrettyFormat = \"%H\\n%an\\n%cn\\n%cd\\n%s\"\n\tgitDateFormat = \"format:%FT%T%z\"\n)\n\nvar (\n\tgitPrettyFormatFieldsNum = strings.Count(gitPrettyFormat, \"\\n\") + 1\n\terrUnexpectedExit = errors.New(\"unexpected exit\")\n)\n\ntype systemGit string\n\n\/\/ SystemGit returns an object that wraps system git command and implements git.Command interface.\n\/\/ If git is not found in PATH an error will be returned.\nfunc SystemGit() (systemGit, error) {\n\tcmd, err := exec.LookPath(\"git\")\n\tif err != nil {\n\t\treturn systemGit(\"\"), errors.New(\"git is not found in PATH\")\n\t}\n\n\treturn systemGit(cmd), nil\n}\n\n\/\/ Exec runs specified Git command in path and returns its output. If Git returns a non-zero\n\/\/ status, an error is returned and output contains error details.\nfunc (gitCmd systemGit) Exec(path, command string, args ...string) (output []byte, err error) {\n\tcmd := exec.Command(string(gitCmd), append([]string{command}, args...)...)\n\tcmd.Dir = path\n\n\toutput, err = cmd.Output()\n\tif err != nil {\n\t\tif exitErr, ok := err.(*exec.ExitError); ok {\n\t\t\terr = errors.New(string(exitErr.Stderr))\n\t\t} else {\n\t\t\terr = errUnexpectedExit\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\treturn bytes.TrimSpace(output), nil\n}\n\n\/\/ IsRepository checks if there if `path` is a git repository.\nfunc (gitCmd systemGit) IsRepository(path string) bool {\n\tif fileInfo, err := os.Stat(path); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn false\n\t\t}\n\n\t\tlog.Printf(\"[WARN] failed to stat %s (%s)\", path, err)\n\t\treturn false\n\t} else if !fileInfo.IsDir() {\n\t\treturn false\n\t}\n\n\toutput, err := gitCmd.Exec(path, \"rev-parse\", \"--is-inside-work-tree\")\n\tif err == errUnexpectedExit {\n\t\tlog.Printf(\"[WARN] git rev-parse --is-inside-work-tree returned %s for %s (%s)\", err, path, string(output))\n\t} else if err != nil {\n\t\treturn false\n\t}\n\n\tswitch string(output) {\n\tcase \"true\":\n\t\treturn true\n\tcase \"false\":\n\t\treturn false\n\tdefault:\n\t\tlog.Printf(\"[WARN] git rev-parse --is-inside-work-tree returned unexpected output for %s: %q\", path, string(output))\n\t\treturn false\n\t}\n}\n\n\/\/ CurrentBranch returns the name of current branch in `path`.\nfunc (gitCmd systemGit) CurrentBranch(path string) string {\n\trefName, err := gitCmd.Exec(path, \"symbolic-ref\", \"HEAD\")\n\tif err != nil {\n\t\tlog.Printf(\"[WARN] git symbolic-ref HEAD returned %s for %s (%s)\", err, path, string(refName))\n\t\treturn DefaultMaster\n\t}\n\n\tif !bytes.HasPrefix(refName, []byte(\"refs\/heads\/\")) {\n\t\tlog.Printf(\"[WARN] unexpected reference name for %s (%q)\", path, refName)\n\t\treturn DefaultMaster\n\t}\n\n\treturn string(bytes.TrimPrefix(refName, []byte(\"refs\/heads\/\")))\n}\n\n\/\/ LastCommit returns the latest commit from `path`.\nfunc (gitCmd systemGit) LastCommit(path string) (commit Commit, err error) {\n\toutput, err := gitCmd.Exec(path, \"log\", \"-n\", \"1\", \"--pretty=\"+gitPrettyFormat, \"--date=\"+gitDateFormat)\n\tif err != nil {\n\t\tlog.Printf(\"[WARN] git log returned error %s for %s (%s)\", err, path, string(output))\n\t\treturn commit, nil\n\t}\n\n\tlines := strings.SplitN(string(output), \"\\n\", gitPrettyFormatFieldsNum)\n\tif len(lines) < gitPrettyFormatFieldsNum {\n\t\tlog.Printf(\"[WARN] unexpected output from git log for %s (%s)\", path, string(output))\n\t\treturn commit, nil\n\t}\n\n\tcommit.SHA, commit.Author, commit.Committer, commit.Message = lines[0], lines[1], lines[2], lines[4]\n\tcommit.Date, err = time.Parse(GitCommandDateLayout, lines[3])\n\tif err != nil {\n\t\tlog.Printf(\"[WARN] unexpected date format from git log for %s (%s)\", path, lines[3])\n\t\tcommit.Date = time.Time{}\n\t}\n\n\treturn commit, nil\n}\n\n\/\/ CloneMirror performs mirror clone of specified git URL to `path`.\nfunc (gitCmd systemGit) CloneMirror(gitURL, path string) error {\n\tdir, projectName := filepath.Dir(path), filepath.Base(path)\n\n\tif err := os.MkdirAll(dir, 0755); err != nil {\n\t\tlog.Printf(\"failed to create %s (%s)\", dir, err)\n\t\treturn fmt.Errorf(\"failed to clone %s to %s\", gitURL, path)\n\t}\n\n\toutput, err := gitCmd.Exec(dir, \"clone\", \"--mirror\", gitURL, projectName)\n\tif err != nil {\n\t\tlog.Printf(\"git clone --mirror %s to %s returned %s (%s)\", gitURL, path, err, string(output))\n\t\treturn fmt.Errorf(\"failed to clone %s to %s\", gitURL, path)\n\t}\n\n\treturn nil\n}\n\n\/\/ UpdateRemote does `git remote update` in specified `path`.\nfunc (gitCmd systemGit) UpdateRemote(path string) error {\n\toutput, err := gitCmd.Exec(path, \"remote\", \"update\")\n\tif err != nil {\n\t\tlog.Printf(\"[WARN] git remote update returned %s for %s (%s)\", err, path, string(output))\n\t\treturn errors.New(\"update failed\")\n\t}\n\n\treturn nil\n}\nRevert \"Use `git rev-parse --is-inside-work-tree` to check if dir is a repository\"package git\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"path\/filepath\"\n\t\"strings\"\n\t\"time\"\n)\n\nconst (\n\t\/\/ GitCommandDateLayout corresponds to `git log --date=format:%FT%T%z` date format.\n\tGitCommandDateLayout = \"2006-01-02T15:04:05-0700\"\n\n\tgitPrettyFormat = \"%H\\n%an\\n%cn\\n%cd\\n%s\"\n\tgitDateFormat = \"format:%FT%T%z\"\n)\n\nvar (\n\tgitPrettyFormatFieldsNum = strings.Count(gitPrettyFormat, \"\\n\") + 1\n\terrUnexpectedExit = errors.New(\"unexpected exit\")\n)\n\ntype systemGit string\n\n\/\/ SystemGit returns an object that wraps system git command and implements git.Command interface.\n\/\/ If git is not found in PATH an error will be returned.\nfunc SystemGit() (systemGit, error) {\n\tcmd, err := exec.LookPath(\"git\")\n\tif err != nil {\n\t\treturn systemGit(\"\"), errors.New(\"git is not found in PATH\")\n\t}\n\n\treturn systemGit(cmd), nil\n}\n\n\/\/ Exec runs specified Git command in path and returns its output. If Git returns a non-zero\n\/\/ status, an error is returned and output contains error details.\nfunc (gitCmd systemGit) Exec(path, command string, args ...string) (output []byte, err error) {\n\tcmd := exec.Command(string(gitCmd), append([]string{command}, args...)...)\n\tcmd.Dir = path\n\n\toutput, err = cmd.Output()\n\tif err != nil {\n\t\tif exitErr, ok := err.(*exec.ExitError); ok {\n\t\t\terr = errors.New(string(exitErr.Stderr))\n\t\t} else {\n\t\t\terr = errUnexpectedExit\n\t\t}\n\n\t\treturn nil, err\n\t}\n\n\treturn bytes.TrimSpace(output), nil\n}\n\n\/\/ IsRepository checks if there if `path` is a git repository.\nfunc (gitCmd systemGit) IsRepository(path string) bool {\n\tif fileInfo, err := os.Stat(path); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn false\n\t\t}\n\n\t\tlog.Printf(\"[WARN] failed to stat %s (%s)\", path, err)\n\t\treturn false\n\t} else if !fileInfo.IsDir() {\n\t\treturn false\n\t}\n\n\toutput, err := gitCmd.Exec(path, \"rev-parse\", \"--is-inside-git-dir\")\n\tif err == errUnexpectedExit {\n\t\tlog.Printf(\"[WARN] git rev-parse --is-inside-git-dir returned %s for %s (%s)\", err, path, string(output))\n\t} else if err != nil {\n\t\treturn false\n\t}\n\n\tswitch string(output) {\n\tcase \"true\":\n\t\treturn true\n\tcase \"false\":\n\t\treturn false\n\tdefault:\n\t\tlog.Printf(\"[WARN] git rev-parse --is-inside-git-dir returned unexpected output for %s: %q\", path, string(output))\n\t\treturn false\n\t}\n}\n\n\/\/ CurrentBranch returns the name of current branch in `path`.\nfunc (gitCmd systemGit) CurrentBranch(path string) string {\n\trefName, err := gitCmd.Exec(path, \"symbolic-ref\", \"HEAD\")\n\tif err != nil {\n\t\tlog.Printf(\"[WARN] git symbolic-ref HEAD returned %s for %s (%s)\", err, path, string(refName))\n\t\treturn DefaultMaster\n\t}\n\n\tif !bytes.HasPrefix(refName, []byte(\"refs\/heads\/\")) {\n\t\tlog.Printf(\"[WARN] unexpected reference name for %s (%q)\", path, refName)\n\t\treturn DefaultMaster\n\t}\n\n\treturn string(bytes.TrimPrefix(refName, []byte(\"refs\/heads\/\")))\n}\n\n\/\/ LastCommit returns the latest commit from `path`.\nfunc (gitCmd systemGit) LastCommit(path string) (commit Commit, err error) {\n\toutput, err := gitCmd.Exec(path, \"log\", \"-n\", \"1\", \"--pretty=\"+gitPrettyFormat, \"--date=\"+gitDateFormat)\n\tif err != nil {\n\t\tlog.Printf(\"[WARN] git log returned error %s for %s (%s)\", err, path, string(output))\n\t\treturn commit, nil\n\t}\n\n\tlines := strings.SplitN(string(output), \"\\n\", gitPrettyFormatFieldsNum)\n\tif len(lines) < gitPrettyFormatFieldsNum {\n\t\tlog.Printf(\"[WARN] unexpected output from git log for %s (%s)\", path, string(output))\n\t\treturn commit, nil\n\t}\n\n\tcommit.SHA, commit.Author, commit.Committer, commit.Message = lines[0], lines[1], lines[2], lines[4]\n\tcommit.Date, err = time.Parse(GitCommandDateLayout, lines[3])\n\tif err != nil {\n\t\tlog.Printf(\"[WARN] unexpected date format from git log for %s (%s)\", path, lines[3])\n\t\tcommit.Date = time.Time{}\n\t}\n\n\treturn commit, nil\n}\n\n\/\/ CloneMirror performs mirror clone of specified git URL to `path`.\nfunc (gitCmd systemGit) CloneMirror(gitURL, path string) error {\n\tdir, projectName := filepath.Dir(path), filepath.Base(path)\n\n\tif err := os.MkdirAll(dir, 0755); err != nil {\n\t\tlog.Printf(\"failed to create %s (%s)\", dir, err)\n\t\treturn fmt.Errorf(\"failed to clone %s to %s\", gitURL, path)\n\t}\n\n\toutput, err := gitCmd.Exec(dir, \"clone\", \"--mirror\", gitURL, projectName)\n\tif err != nil {\n\t\tlog.Printf(\"git clone --mirror %s to %s returned %s (%s)\", gitURL, path, err, string(output))\n\t\treturn fmt.Errorf(\"failed to clone %s to %s\", gitURL, path)\n\t}\n\n\treturn nil\n}\n\n\/\/ UpdateRemote does `git remote update` in specified `path`.\nfunc (gitCmd systemGit) UpdateRemote(path string) error {\n\toutput, err := gitCmd.Exec(path, \"remote\", \"update\")\n\tif err != nil {\n\t\tlog.Printf(\"[WARN] git remote update returned %s for %s (%s)\", err, path, string(output))\n\t\treturn errors.New(\"update failed\")\n\t}\n\n\treturn nil\n}\n<|endoftext|>"} {"text":"package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/rlister\/let-me-in\/Godeps\/_workspace\/src\/github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/rlister\/let-me-in\/Godeps\/_workspace\/src\/github.com\/aws\/aws-sdk-go\/aws\/awserr\"\n\t\"github.com\/rlister\/let-me-in\/Godeps\/_workspace\/src\/github.com\/aws\/aws-sdk-go\/service\/ec2\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"text\/tabwriter\"\n)\n\nvar VERSION = \"dev\"\n\ntype LmiInput struct {\n\tGroupId *string\n\tIpProtocol *string\n\tFromPort *int64\n\tToPort *int64\n\tCidrIp *string\n}\n\n\/\/ error handler\nfunc check(e error) {\n\tif e != nil {\n\t\tpanic(e.Error())\n\t}\n}\n\n\/\/ return array of security group objects for given group names\nfunc getGroups(client *ec2.EC2, names []string) ([]*ec2.SecurityGroup, error) {\n\n\t\/\/ get names as array of aws.String objects\n\tvalues := make([]*string, len(names))\n\tfor i, name := range names {\n\t\tvalues[i] = aws.String(name)\n\t}\n\n\t\/\/ request params as filter for names\n\tparams := &ec2.DescribeSecurityGroupsInput{\n\t\tFilters: []*ec2.Filter{\n\t\t\t{\n\t\t\t\tName: aws.String(\"group-name\"),\n\t\t\t\tValues: values,\n\t\t\t},\n\t\t},\n\t}\n\n\t\/\/ send request\n\tresp, err := client.DescribeSecurityGroups(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp.SecurityGroups, nil\n}\n\nfunc authorizeGroup(client *ec2.EC2, group *ec2.SecurityGroup, input LmiInput) {\n\t_, err := client.AuthorizeSecurityGroupIngress(&ec2.AuthorizeSecurityGroupIngressInput{\n\t\tGroupId: group.GroupId,\n\t\tIpProtocol: input.IpProtocol,\n\t\tFromPort: input.FromPort,\n\t\tToPort: input.ToPort,\n\t\tCidrIp: input.CidrIp,\n\t})\n\n\t\/\/ be idempotent, i.e. skip error if this permission already exists in group\n\tif err != nil {\n\t\tif err.(awserr.Error).Code() != \"InvalidPermission.Duplicate\" {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}\n\nfunc revokeGroup(client *ec2.EC2, group *ec2.SecurityGroup, input LmiInput) {\n\t_, err := client.RevokeSecurityGroupIngress(&ec2.RevokeSecurityGroupIngressInput{\n\t\tGroupId: group.GroupId,\n\t\tIpProtocol: input.IpProtocol,\n\t\tFromPort: input.FromPort,\n\t\tToPort: input.ToPort,\n\t\tCidrIp: input.CidrIp,\n\t})\n\n\t\/\/ be idempotent, i.e. skip error if this permission already exists in group\n\tif err != nil {\n\t\tif err.(awserr.Error).Code() != \"InvalidPermission.NotFound\" {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}\n\n\/\/ revoke all existing permissions for security group\nfunc cleanGroup(client *ec2.EC2, group *ec2.SecurityGroup) {\n\tfor _, perm := range group.IpPermissions {\n\t\tfor _, cidr := range perm.IpRanges {\n\t\t\trevokeGroup(client, group, LmiInput{\n\t\t\t\tIpProtocol: perm.IpProtocol,\n\t\t\t\tFromPort: perm.FromPort,\n\t\t\t\tToPort: perm.ToPort,\n\t\t\t\tCidrIp: cidr.CidrIp,\n\t\t\t})\n\t\t}\n\t}\n}\n\n\/\/ get my external-facing IP as a string\nfunc getMyIp(ident string) string {\n\tresp, err := http.Get(ident)\n\tcheck(err)\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tcheck(err)\n\n\treturn string(body)\n}\n\n\/\/ parse cmdline argv into args before '--' and cmd to exec afterwards\nfunc parseArgs(argv []string) ([]string, []string) {\n\n\t\/\/ if -- found, return slices before and after\n\tfor i, arg := range flag.Args() {\n\t\tif arg == \"--\" {\n\t\t\treturn argv[0:i], argv[i+1:]\n\t\t}\n\t}\n\n\t\/\/ no -- found, return all of argv\n\treturn argv, nil\n}\n\n\/\/ print out table of current IP permissions for given security groups\nfunc printIpRanges(groups []*ec2.SecurityGroup) {\n\tw := new(tabwriter.Writer)\n\tw.Init(os.Stdout, 0, 8, 0, '\\t', 0)\n\tfor _, group := range groups {\n\t\tfor _, perm := range group.IpPermissions {\n\t\t\tfor _, cidr := range perm.IpRanges {\n\t\t\t\tfmt.Fprintf(w, \"%v\\t%v\\t%v\\t%v\\n\", *group.GroupName, *perm.IpProtocol, *cidr.CidrIp, *perm.FromPort)\n\t\t\t}\n\t\t}\n\t}\n\tw.Flush()\n}\n\nfunc main() {\n\n\t\/\/ cmdline options\n\tversionFlag := flag.Bool(\"v\", false, \"show version and exit\")\n\tcidr := flag.String(\"c\", \"\", \"set a specific cidr block (default: current public ip)\")\n\tprotocol := flag.String(\"P\", \"TCP\", \"protocol to allow (default: TCP)\")\n\tport := flag.Int(\"p\", 22, \"port number to allow (default: 22)\")\n\trevoke := flag.Bool(\"r\", false, \"revoke access from security groups (default: false)\")\n\tcleanFlag := flag.Bool(\"clean\", false, \"clean listed groups, i.e. revoke all access\")\n\tlist := flag.Bool(\"l\", false, \"list current rules for groups\")\n\tflag.Parse()\n\n\t\/\/ show version and exit\n\tif *versionFlag {\n\t\tfmt.Printf(\"let-me-in %v\\n\", VERSION)\n\t\treturn\n\t}\n\n\t\/\/ if cidr not given get ip from external service\n\tif *cidr == \"\" {\n\t\tident := os.Getenv(\"LMI_IDENT_URL\")\n\t\tif ident == \"\" {\n\t\t\tident = \"http:\/\/v4.ident.me\/\"\n\t\t}\n\t\tip := getMyIp(ident) + \"\/32\"\n\t\tcidr = &ip\n\t}\n\n\tinput := LmiInput{\n\t\tIpProtocol: protocol,\n\t\tFromPort: aws.Int64(int64(*port)),\n\t\tToPort: aws.Int64(int64(*port)),\n\t\tCidrIp: cidr,\n\t}\n\n\t\/\/ configure aws-sdk from AWS_* env vars\n\tclient := ec2.New(&aws.Config{})\n\n\t\/\/ get security group names and any command to exec after '--'\n\tgroupNames, cmd := parseArgs(flag.Args())\n\n\t\/\/ get details for listed groups\n\tgroups, err := getGroups(client, groupNames)\n\tif err != nil {\n\t\tfmt.Printf(\"%v\\n\", err) \/\/ if AWS creds not configured, report it here\n\t\treturn\n\t}\n\n\t\/\/ print list of current IP permissions for groups\n\tif *list {\n\t\tprintIpRanges(groups)\n\t\treturn\n\t}\n\n\tif *cleanFlag {\n\t\tfor _, group := range groups {\n\t\t\tcleanGroup(client, group)\n\t\t}\n\t\treturn\n\t}\n\n\t\/\/ revoke on -r option\n\tif *revoke {\n\t\tfor _, group := range groups {\n\t\t\trevokeGroup(client, group, input)\n\t\t}\n\t\treturn\n\t}\n\n\t\/\/ default behaviour\n\tfor _, group := range groups {\n\t\tauthorizeGroup(client, group, input)\n\t}\n\n\t\/\/ exec any command after '--', then revoke\n\tif cmd != nil {\n\t\tc := exec.Command(cmd[0], cmd[1:]...)\n\t\tc.Stdout = os.Stdout\n\t\tc.Stdin = os.Stdin\n\t\tc.Stderr = os.Stderr\n\n\t\terr := c.Run()\n\t\tif err != nil {\n\t\t\tfmt.Println(err) \/\/ show err and keep running so we hit revoke below\n\t\t}\n\n\t\tfor _, group := range groups {\n\t\t\trevokeGroup(client, group, input)\n\t\t}\n\t}\n\n}\nadd convenience functions to call multiple groupspackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"github.com\/rlister\/let-me-in\/Godeps\/_workspace\/src\/github.com\/aws\/aws-sdk-go\/aws\"\n\t\"github.com\/rlister\/let-me-in\/Godeps\/_workspace\/src\/github.com\/aws\/aws-sdk-go\/aws\/awserr\"\n\t\"github.com\/rlister\/let-me-in\/Godeps\/_workspace\/src\/github.com\/aws\/aws-sdk-go\/service\/ec2\"\n\t\"io\/ioutil\"\n\t\"net\/http\"\n\t\"os\"\n\t\"os\/exec\"\n\t\"text\/tabwriter\"\n)\n\nvar VERSION = \"dev\"\n\ntype LmiInput struct {\n\tGroupId *string\n\tIpProtocol *string\n\tFromPort *int64\n\tToPort *int64\n\tCidrIp *string\n}\n\n\/\/ error handler\nfunc check(e error) {\n\tif e != nil {\n\t\tpanic(e.Error())\n\t}\n}\n\n\/\/ return array of security group objects for given group names\nfunc getGroups(client *ec2.EC2, names []string) ([]*ec2.SecurityGroup, error) {\n\n\t\/\/ get names as array of aws.String objects\n\tvalues := make([]*string, len(names))\n\tfor i, name := range names {\n\t\tvalues[i] = aws.String(name)\n\t}\n\n\t\/\/ request params as filter for names\n\tparams := &ec2.DescribeSecurityGroupsInput{\n\t\tFilters: []*ec2.Filter{\n\t\t\t{\n\t\t\t\tName: aws.String(\"group-name\"),\n\t\t\t\tValues: values,\n\t\t\t},\n\t\t},\n\t}\n\n\t\/\/ send request\n\tresp, err := client.DescribeSecurityGroups(params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp.SecurityGroups, nil\n}\n\nfunc authorizeGroups(client *ec2.EC2, groups []*ec2.SecurityGroup, input LmiInput) {\n\tfor _, group := range groups {\n\t\tauthorizeGroup(client, group, input)\n\t}\n}\n\n\/\/ add given permission to security group\nfunc authorizeGroup(client *ec2.EC2, group *ec2.SecurityGroup, input LmiInput) {\n\t_, err := client.AuthorizeSecurityGroupIngress(&ec2.AuthorizeSecurityGroupIngressInput{\n\t\tGroupId: group.GroupId,\n\t\tIpProtocol: input.IpProtocol,\n\t\tFromPort: input.FromPort,\n\t\tToPort: input.ToPort,\n\t\tCidrIp: input.CidrIp,\n\t})\n\n\t\/\/ be idempotent, i.e. skip error if this permission already exists in group\n\tif err != nil {\n\t\tif err.(awserr.Error).Code() != \"InvalidPermission.Duplicate\" {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}\n\nfunc revokeGroups(client *ec2.EC2, groups []*ec2.SecurityGroup, input LmiInput) {\n\tfor _, group := range groups {\n\t\trevokeGroup(client, group, input)\n\t}\n}\n\n\/\/ revoke given permission for security group\nfunc revokeGroup(client *ec2.EC2, group *ec2.SecurityGroup, input LmiInput) {\n\t_, err := client.RevokeSecurityGroupIngress(&ec2.RevokeSecurityGroupIngressInput{\n\t\tGroupId: group.GroupId,\n\t\tIpProtocol: input.IpProtocol,\n\t\tFromPort: input.FromPort,\n\t\tToPort: input.ToPort,\n\t\tCidrIp: input.CidrIp,\n\t})\n\n\t\/\/ be idempotent, i.e. skip error if this permission already exists in group\n\tif err != nil {\n\t\tif err.(awserr.Error).Code() != \"InvalidPermission.NotFound\" {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}\n\nfunc cleanGroups(client *ec2.EC2, groups []*ec2.SecurityGroup) {\n\tfor _, group := range groups {\n\t\tcleanGroup(client, group)\n\t}\n}\n\n\/\/ revoke all existing permissions for security group\nfunc cleanGroup(client *ec2.EC2, group *ec2.SecurityGroup) {\n\tfor _, perm := range group.IpPermissions {\n\t\tfor _, cidr := range perm.IpRanges {\n\t\t\trevokeGroup(client, group, LmiInput{\n\t\t\t\tIpProtocol: perm.IpProtocol,\n\t\t\t\tFromPort: perm.FromPort,\n\t\t\t\tToPort: perm.ToPort,\n\t\t\t\tCidrIp: cidr.CidrIp,\n\t\t\t})\n\t\t}\n\t}\n}\n\n\/\/ get my external-facing IP as a string\nfunc getMyIp(ident string) string {\n\tresp, err := http.Get(ident)\n\tcheck(err)\n\tdefer resp.Body.Close()\n\n\tbody, err := ioutil.ReadAll(resp.Body)\n\tcheck(err)\n\n\treturn string(body)\n}\n\n\/\/ parse cmdline argv into args before '--' and cmd to exec afterwards\nfunc parseArgs(argv []string) ([]string, []string) {\n\n\t\/\/ if -- found, return slices before and after\n\tfor i, arg := range flag.Args() {\n\t\tif arg == \"--\" {\n\t\t\treturn argv[0:i], argv[i+1:]\n\t\t}\n\t}\n\n\t\/\/ no -- found, return all of argv\n\treturn argv, nil\n}\n\n\/\/ print out table of current IP permissions for given security groups\nfunc printIpRanges(groups []*ec2.SecurityGroup) {\n\tw := new(tabwriter.Writer)\n\tw.Init(os.Stdout, 0, 8, 0, '\\t', 0)\n\tfor _, group := range groups {\n\t\tfor _, perm := range group.IpPermissions {\n\t\t\tfor _, cidr := range perm.IpRanges {\n\t\t\t\tfmt.Fprintf(w, \"%v\\t%v\\t%v\\t%v\\n\", *group.GroupName, *perm.IpProtocol, *cidr.CidrIp, *perm.FromPort)\n\t\t\t}\n\t\t}\n\t}\n\tw.Flush()\n}\n\nfunc main() {\n\n\t\/\/ cmdline options\n\tversionFlag := flag.Bool(\"v\", false, \"show version and exit\")\n\tcidr := flag.String(\"c\", \"\", \"set a specific cidr block (default: current public ip)\")\n\tprotocol := flag.String(\"P\", \"TCP\", \"protocol to allow (default: TCP)\")\n\tport := flag.Int(\"p\", 22, \"port number to allow (default: 22)\")\n\trevoke := flag.Bool(\"r\", false, \"revoke access from security groups (default: false)\")\n\tcleanFlag := flag.Bool(\"clean\", false, \"clean listed groups, i.e. revoke all access\")\n\tlist := flag.Bool(\"l\", false, \"list current rules for groups\")\n\tflag.Parse()\n\n\t\/\/ show version and exit\n\tif *versionFlag {\n\t\tfmt.Printf(\"let-me-in %v\\n\", VERSION)\n\t\treturn\n\t}\n\n\t\/\/ if cidr not given get ip from external service\n\tif *cidr == \"\" {\n\t\tident := os.Getenv(\"LMI_IDENT_URL\")\n\t\tif ident == \"\" {\n\t\t\tident = \"http:\/\/v4.ident.me\/\"\n\t\t}\n\t\tip := getMyIp(ident) + \"\/32\"\n\t\tcidr = &ip\n\t}\n\n\tinput := LmiInput{\n\t\tIpProtocol: protocol,\n\t\tFromPort: aws.Int64(int64(*port)),\n\t\tToPort: aws.Int64(int64(*port)),\n\t\tCidrIp: cidr,\n\t}\n\n\t\/\/ configure aws-sdk from AWS_* env vars\n\tclient := ec2.New(&aws.Config{})\n\n\t\/\/ get security group names and any command to exec after '--'\n\tgroupNames, cmd := parseArgs(flag.Args())\n\n\t\/\/ get details for listed groups\n\tgroups, err := getGroups(client, groupNames)\n\tif err != nil {\n\t\tfmt.Printf(\"%v\\n\", err) \/\/ if AWS creds not configured, report it here\n\t\treturn\n\t}\n\n\t\/\/ print list of current IP permissions for groups\n\tif *list {\n\t\tprintIpRanges(groups)\n\t\treturn\n\t}\n\n\t\/\/ remove all existing permissions for groups\n\tif *cleanFlag {\n\t\tcleanGroups(client, groups)\n\t\treturn\n\t}\n\n\t\/\/ revoke given permission for groups\n\tif *revoke {\n\t\trevokeGroups(client, groups, input)\n\t\treturn\n\t}\n\n\t\/\/ default behaviour\n\tauthorizeGroups(client, groups, input)\n\n\t\/\/ exec any command after '--', then revoke\n\tif cmd != nil {\n\t\tc := exec.Command(cmd[0], cmd[1:]...)\n\t\tc.Stdout = os.Stdout\n\t\tc.Stdin = os.Stdin\n\t\tc.Stderr = os.Stderr\n\n\t\terr := c.Run()\n\t\tif err != nil {\n\t\t\tfmt.Println(err) \/\/ show err and keep running so we hit revoke below\n\t\t}\n\n\t\trevokeGroups(client, groups, input)\n\t}\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\n\/\/ A package of simple functions to manipulate strings.\npackage strings\n\nimport (\n\t\"unicode\"\n\t\"utf8\"\n)\n\n\/\/ explode splits s into an array of UTF-8 sequences, one per Unicode character (still strings) up to a maximum of n (n <= 0 means no limit).\n\/\/ Invalid UTF-8 sequences become correct encodings of U+FFF8.\nfunc explode(s string, n int) []string {\n\tif n <= 0 {\n\t\tn = len(s)\n\t}\n\ta := make([]string, n)\n\tvar size, rune int\n\tna := 0\n\tfor len(s) > 0 {\n\t\tif na+1 >= n {\n\t\t\ta[na] = s\n\t\t\tna++\n\t\t\tbreak\n\t\t}\n\t\trune, size = utf8.DecodeRuneInString(s)\n\t\ts = s[size:]\n\t\ta[na] = string(rune)\n\t\tna++\n\t}\n\treturn a[0:na]\n}\n\n\/\/ Count counts the number of non-overlapping instances of sep in s.\nfunc Count(s, sep string) int {\n\tif sep == \"\" {\n\t\treturn utf8.RuneCountInString(s) + 1\n\t}\n\tc := sep[0]\n\tn := 0\n\tfor i := 0; i+len(sep) <= len(s); i++ {\n\t\tif s[i] == c && (len(sep) == 1 || s[i:i+len(sep)] == sep) {\n\t\t\tn++\n\t\t\ti += len(sep) - 1\n\t\t}\n\t}\n\treturn n\n}\n\n\/\/ Index returns the index of the first instance of sep in s, or -1 if sep is not present in s.\nfunc Index(s, sep string) int {\n\tn := len(sep)\n\tif n == 0 {\n\t\treturn 0\n\t}\n\tc := sep[0]\n\tif n == 1 {\n\t\t\/\/ special case worth making fast\n\t\tfor i := 0; i < len(s); i++ {\n\t\t\tif s[i] == c {\n\t\t\t\treturn i\n\t\t\t}\n\t\t}\n\t\treturn -1\n\t}\n\tfor i := 0; i+n <= len(s); i++ {\n\t\tif s[i] == c && (n == 1 || s[i:i+n] == sep) {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}\n\n\/\/ LastIndex returns the index of the last instance of sep in s, or -1 if sep is not present in s.\nfunc LastIndex(s, sep string) int {\n\tn := len(sep)\n\tif n == 0 {\n\t\treturn len(s)\n\t}\n\tc := sep[0]\n\tif n == 1 {\n\t\t\/\/ special case worth making fast\n\t\tfor i := len(s) - 1; i >= 0; i-- {\n\t\t\tif s[i] == c {\n\t\t\t\treturn i\n\t\t\t}\n\t\t}\n\t\treturn -1\n\t}\n\tfor i := len(s) - n; i >= 0; i-- {\n\t\tif s[i] == c && (n == 1 || s[i:i+n] == sep) {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}\n\n\/\/ Generic split: splits after each instance of sep,\n\/\/ including sepSave bytes of sep in the subarrays.\nfunc genSplit(s, sep string, sepSave, n int) []string {\n\tif sep == \"\" {\n\t\treturn explode(s, n)\n\t}\n\tif n <= 0 {\n\t\tn = Count(s, sep) + 1\n\t}\n\tc := sep[0]\n\tstart := 0\n\ta := make([]string, n)\n\tna := 0\n\tfor i := 0; i+len(sep) <= len(s) && na+1 < n; i++ {\n\t\tif s[i] == c && (len(sep) == 1 || s[i:i+len(sep)] == sep) {\n\t\t\ta[na] = s[start : i+sepSave]\n\t\t\tna++\n\t\t\tstart = i + len(sep)\n\t\t\ti += len(sep) - 1\n\t\t}\n\t}\n\ta[na] = s[start:]\n\treturn a[0 : na+1]\n}\n\n\/\/ Split splits the string s around each instance of sep, returning an array of substrings of s.\n\/\/ If sep is empty, Split splits s after each UTF-8 sequence.\n\/\/ If n > 0, Split splits s into at most n substrings; the last substring will be the unsplit remainder.\nfunc Split(s, sep string, n int) []string { return genSplit(s, sep, 0, n) }\n\n\/\/ SplitAfter splits the string s after each instance of sep, returning an array of substrings of s.\n\/\/ If sep is empty, SplitAfter splits s after each UTF-8 sequence.\n\/\/ If n > 0, SplitAfter splits s into at most n substrings; the last substring will be the unsplit remainder.\nfunc SplitAfter(s, sep string, n int) []string {\n\treturn genSplit(s, sep, len(sep), n)\n}\n\n\/\/ Fields splits the string s around each instance of one or more consecutive white space\n\/\/ characters, returning an array of substrings of s or an empty list if s contains only white space.\nfunc Fields(s string) []string {\n\tn := 0\n\tinField := false\n\tfor _, rune := range s {\n\t\twasInField := inField\n\t\tinField = !unicode.IsSpace(rune)\n\t\tif inField && !wasInField {\n\t\t\tn++\n\t\t}\n\t}\n\n\ta := make([]string, n)\n\tna := 0\n\tfieldStart := -1\n\tfor i, rune := range s {\n\t\tif unicode.IsSpace(rune) {\n\t\t\tif fieldStart >= 0 {\n\t\t\t\ta[na] = s[fieldStart:i]\n\t\t\t\tna++\n\t\t\t\tfieldStart = -1\n\t\t\t}\n\t\t} else if fieldStart == -1 {\n\t\t\tfieldStart = i\n\t\t}\n\t}\n\tif fieldStart != -1 {\n\t\ta[na] = s[fieldStart:]\n\t\tna++\n\t}\n\treturn a[0:na]\n}\n\n\/\/ Join concatenates the elements of a to create a single string. The separator string\n\/\/ sep is placed between elements in the resulting string.\nfunc Join(a []string, sep string) string {\n\tif len(a) == 0 {\n\t\treturn \"\"\n\t}\n\tif len(a) == 1 {\n\t\treturn a[0]\n\t}\n\tn := len(sep) * (len(a) - 1)\n\tfor i := 0; i < len(a); i++ {\n\t\tn += len(a[i])\n\t}\n\n\tb := make([]byte, n)\n\tbp := 0\n\tfor i := 0; i < len(a); i++ {\n\t\ts := a[i]\n\t\tfor j := 0; j < len(s); j++ {\n\t\t\tb[bp] = s[j]\n\t\t\tbp++\n\t\t}\n\t\tif i+1 < len(a) {\n\t\t\ts = sep\n\t\t\tfor j := 0; j < len(s); j++ {\n\t\t\t\tb[bp] = s[j]\n\t\t\t\tbp++\n\t\t\t}\n\t\t}\n\t}\n\treturn string(b)\n}\n\n\/\/ HasPrefix tests whether the string s begins with prefix.\nfunc HasPrefix(s, prefix string) bool {\n\treturn len(s) >= len(prefix) && s[0:len(prefix)] == prefix\n}\n\n\/\/ HasSuffix tests whether the string s ends with suffix.\nfunc HasSuffix(s, suffix string) bool {\n\treturn len(s) >= len(suffix) && s[len(s)-len(suffix):] == suffix\n}\n\n\/\/ Map returns a copy of the string s with all its characters modified\n\/\/ according to the mapping function. If mapping returns a negative value, the character is\n\/\/ dropped from the string with no replacement.\nfunc Map(mapping func(rune int) int, s string) string {\n\t\/\/ In the worst case, the string can grow when mapped, making\n\t\/\/ things unpleasant. But it's so rare we barge in assuming it's\n\t\/\/ fine. It could also shrink but that falls out naturally.\n\tmaxbytes := len(s) \/\/ length of b\n\tnbytes := 0 \/\/ number of bytes encoded in b\n\tb := make([]byte, maxbytes)\n\tfor _, c := range s {\n\t\trune := mapping(c)\n\t\tif rune >= 0 {\n\t\t\twid := 1\n\t\t\tif rune >= utf8.RuneSelf {\n\t\t\t\twid = utf8.RuneLen(rune)\n\t\t\t}\n\t\t\tif nbytes+wid > maxbytes {\n\t\t\t\t\/\/ Grow the buffer.\n\t\t\t\tmaxbytes = maxbytes*2 + utf8.UTFMax\n\t\t\t\tnb := make([]byte, maxbytes)\n\t\t\t\tfor i, c := range b[0:nbytes] {\n\t\t\t\t\tnb[i] = c\n\t\t\t\t}\n\t\t\t\tb = nb\n\t\t\t}\n\t\t\tnbytes += utf8.EncodeRune(rune, b[nbytes:maxbytes])\n\t\t}\n\t}\n\treturn string(b[0:nbytes])\n}\n\n\/\/ Repeat returns a new string consisting of count copies of the string s.\nfunc Repeat(s string, count int) string {\n\tb := make([]byte, len(s)*count)\n\tbp := 0\n\tfor i := 0; i < count; i++ {\n\t\tfor j := 0; j < len(s); j++ {\n\t\t\tb[bp] = s[j]\n\t\t\tbp++\n\t\t}\n\t}\n\treturn string(b)\n}\n\n\n\/\/ ToUpper returns a copy of the string s with all Unicode letters mapped to their upper case.\nfunc ToUpper(s string) string { return Map(unicode.ToUpper, s) }\n\n\/\/ ToLower returns a copy of the string s with all Unicode letters mapped to their lower case.\nfunc ToLower(s string) string { return Map(unicode.ToLower, s) }\n\n\/\/ ToTitle returns a copy of the string s with all Unicode letters mapped to their title case.\nfunc ToTitle(s string) string { return Map(unicode.ToTitle, s) }\n\n\/\/ Trim returns a slice of the string s, with all leading and trailing white space\n\/\/ removed, as defined by Unicode.\nfunc TrimSpace(s string) string {\n\tstart, end := 0, len(s)\n\tfor start < end {\n\t\twid := 1\n\t\trune := int(s[start])\n\t\tif rune >= utf8.RuneSelf {\n\t\t\trune, wid = utf8.DecodeRuneInString(s[start:end])\n\t\t}\n\t\tif !unicode.IsSpace(rune) {\n\t\t\tbreak\n\t\t}\n\t\tstart += wid\n\t}\n\tfor start < end {\n\t\twid := 1\n\t\trune := int(s[end-1])\n\t\tif rune >= utf8.RuneSelf {\n\t\t\t\/\/ Back up carefully looking for beginning of rune. Mustn't pass start.\n\t\t\tfor wid = 2; start <= end-wid && !utf8.RuneStart(s[end-wid]); wid++ {\n\t\t\t}\n\t\t\tif start > end-wid { \/\/ invalid UTF-8 sequence; stop processing\n\t\t\t\treturn s[start:end]\n\t\t\t}\n\t\t\trune, wid = utf8.DecodeRuneInString(s[end-wid : end])\n\t\t}\n\t\tif !unicode.IsSpace(rune) {\n\t\t\tbreak\n\t\t}\n\t\tend -= wid\n\t}\n\treturn s[start:end]\n}\n\n\/\/ Bytes returns a new slice containing the bytes in s.\nfunc Bytes(s string) []byte {\n\tb := make([]byte, len(s))\n\tfor i := 0; i < len(s); i++ {\n\t\tb[i] = s[i]\n\t}\n\treturn b\n}\n\n\/\/ Runes returns a slice of runes (Unicode code points) equivalent to the string s.\nfunc Runes(s string) []int {\n\tt := make([]int, utf8.RuneCountInString(s))\n\ti := 0\n\tfor _, r := range s {\n\t\tt[i] = r\n\t\ti++\n\t}\n\treturn t\n}\nstrings: remove a couple of redundant tests (per suggestion from Heresy.Mc@gmail.com)\/\/ Copyright 2009 The Go Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n\/\/ A package of simple functions to manipulate strings.\npackage strings\n\nimport (\n\t\"unicode\"\n\t\"utf8\"\n)\n\n\/\/ explode splits s into an array of UTF-8 sequences, one per Unicode character (still strings) up to a maximum of n (n <= 0 means no limit).\n\/\/ Invalid UTF-8 sequences become correct encodings of U+FFF8.\nfunc explode(s string, n int) []string {\n\tif n <= 0 {\n\t\tn = len(s)\n\t}\n\ta := make([]string, n)\n\tvar size, rune int\n\tna := 0\n\tfor len(s) > 0 {\n\t\tif na+1 >= n {\n\t\t\ta[na] = s\n\t\t\tna++\n\t\t\tbreak\n\t\t}\n\t\trune, size = utf8.DecodeRuneInString(s)\n\t\ts = s[size:]\n\t\ta[na] = string(rune)\n\t\tna++\n\t}\n\treturn a[0:na]\n}\n\n\/\/ Count counts the number of non-overlapping instances of sep in s.\nfunc Count(s, sep string) int {\n\tif sep == \"\" {\n\t\treturn utf8.RuneCountInString(s) + 1\n\t}\n\tc := sep[0]\n\tn := 0\n\tfor i := 0; i+len(sep) <= len(s); i++ {\n\t\tif s[i] == c && (len(sep) == 1 || s[i:i+len(sep)] == sep) {\n\t\t\tn++\n\t\t\ti += len(sep) - 1\n\t\t}\n\t}\n\treturn n\n}\n\n\/\/ Index returns the index of the first instance of sep in s, or -1 if sep is not present in s.\nfunc Index(s, sep string) int {\n\tn := len(sep)\n\tif n == 0 {\n\t\treturn 0\n\t}\n\tc := sep[0]\n\tif n == 1 {\n\t\t\/\/ special case worth making fast\n\t\tfor i := 0; i < len(s); i++ {\n\t\t\tif s[i] == c {\n\t\t\t\treturn i\n\t\t\t}\n\t\t}\n\t\treturn -1\n\t}\n\t\/\/ n > 1\n\tfor i := 0; i+n <= len(s); i++ {\n\t\tif s[i] == c && s[i:i+n] == sep {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}\n\n\/\/ LastIndex returns the index of the last instance of sep in s, or -1 if sep is not present in s.\nfunc LastIndex(s, sep string) int {\n\tn := len(sep)\n\tif n == 0 {\n\t\treturn len(s)\n\t}\n\tc := sep[0]\n\tif n == 1 {\n\t\t\/\/ special case worth making fast\n\t\tfor i := len(s) - 1; i >= 0; i-- {\n\t\t\tif s[i] == c {\n\t\t\t\treturn i\n\t\t\t}\n\t\t}\n\t\treturn -1\n\t}\n\t\/\/ n > 1\n\tfor i := len(s) - n; i >= 0; i-- {\n\t\tif s[i] == c && s[i:i+n] == sep {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}\n\n\/\/ Generic split: splits after each instance of sep,\n\/\/ including sepSave bytes of sep in the subarrays.\nfunc genSplit(s, sep string, sepSave, n int) []string {\n\tif sep == \"\" {\n\t\treturn explode(s, n)\n\t}\n\tif n <= 0 {\n\t\tn = Count(s, sep) + 1\n\t}\n\tc := sep[0]\n\tstart := 0\n\ta := make([]string, n)\n\tna := 0\n\tfor i := 0; i+len(sep) <= len(s) && na+1 < n; i++ {\n\t\tif s[i] == c && (len(sep) == 1 || s[i:i+len(sep)] == sep) {\n\t\t\ta[na] = s[start : i+sepSave]\n\t\t\tna++\n\t\t\tstart = i + len(sep)\n\t\t\ti += len(sep) - 1\n\t\t}\n\t}\n\ta[na] = s[start:]\n\treturn a[0 : na+1]\n}\n\n\/\/ Split splits the string s around each instance of sep, returning an array of substrings of s.\n\/\/ If sep is empty, Split splits s after each UTF-8 sequence.\n\/\/ If n > 0, Split splits s into at most n substrings; the last substring will be the unsplit remainder.\nfunc Split(s, sep string, n int) []string { return genSplit(s, sep, 0, n) }\n\n\/\/ SplitAfter splits the string s after each instance of sep, returning an array of substrings of s.\n\/\/ If sep is empty, SplitAfter splits s after each UTF-8 sequence.\n\/\/ If n > 0, SplitAfter splits s into at most n substrings; the last substring will be the unsplit remainder.\nfunc SplitAfter(s, sep string, n int) []string {\n\treturn genSplit(s, sep, len(sep), n)\n}\n\n\/\/ Fields splits the string s around each instance of one or more consecutive white space\n\/\/ characters, returning an array of substrings of s or an empty list if s contains only white space.\nfunc Fields(s string) []string {\n\tn := 0\n\tinField := false\n\tfor _, rune := range s {\n\t\twasInField := inField\n\t\tinField = !unicode.IsSpace(rune)\n\t\tif inField && !wasInField {\n\t\t\tn++\n\t\t}\n\t}\n\n\ta := make([]string, n)\n\tna := 0\n\tfieldStart := -1\n\tfor i, rune := range s {\n\t\tif unicode.IsSpace(rune) {\n\t\t\tif fieldStart >= 0 {\n\t\t\t\ta[na] = s[fieldStart:i]\n\t\t\t\tna++\n\t\t\t\tfieldStart = -1\n\t\t\t}\n\t\t} else if fieldStart == -1 {\n\t\t\tfieldStart = i\n\t\t}\n\t}\n\tif fieldStart != -1 {\n\t\ta[na] = s[fieldStart:]\n\t\tna++\n\t}\n\treturn a[0:na]\n}\n\n\/\/ Join concatenates the elements of a to create a single string. The separator string\n\/\/ sep is placed between elements in the resulting string.\nfunc Join(a []string, sep string) string {\n\tif len(a) == 0 {\n\t\treturn \"\"\n\t}\n\tif len(a) == 1 {\n\t\treturn a[0]\n\t}\n\tn := len(sep) * (len(a) - 1)\n\tfor i := 0; i < len(a); i++ {\n\t\tn += len(a[i])\n\t}\n\n\tb := make([]byte, n)\n\tbp := 0\n\tfor i := 0; i < len(a); i++ {\n\t\ts := a[i]\n\t\tfor j := 0; j < len(s); j++ {\n\t\t\tb[bp] = s[j]\n\t\t\tbp++\n\t\t}\n\t\tif i+1 < len(a) {\n\t\t\ts = sep\n\t\t\tfor j := 0; j < len(s); j++ {\n\t\t\t\tb[bp] = s[j]\n\t\t\t\tbp++\n\t\t\t}\n\t\t}\n\t}\n\treturn string(b)\n}\n\n\/\/ HasPrefix tests whether the string s begins with prefix.\nfunc HasPrefix(s, prefix string) bool {\n\treturn len(s) >= len(prefix) && s[0:len(prefix)] == prefix\n}\n\n\/\/ HasSuffix tests whether the string s ends with suffix.\nfunc HasSuffix(s, suffix string) bool {\n\treturn len(s) >= len(suffix) && s[len(s)-len(suffix):] == suffix\n}\n\n\/\/ Map returns a copy of the string s with all its characters modified\n\/\/ according to the mapping function. If mapping returns a negative value, the character is\n\/\/ dropped from the string with no replacement.\nfunc Map(mapping func(rune int) int, s string) string {\n\t\/\/ In the worst case, the string can grow when mapped, making\n\t\/\/ things unpleasant. But it's so rare we barge in assuming it's\n\t\/\/ fine. It could also shrink but that falls out naturally.\n\tmaxbytes := len(s) \/\/ length of b\n\tnbytes := 0 \/\/ number of bytes encoded in b\n\tb := make([]byte, maxbytes)\n\tfor _, c := range s {\n\t\trune := mapping(c)\n\t\tif rune >= 0 {\n\t\t\twid := 1\n\t\t\tif rune >= utf8.RuneSelf {\n\t\t\t\twid = utf8.RuneLen(rune)\n\t\t\t}\n\t\t\tif nbytes+wid > maxbytes {\n\t\t\t\t\/\/ Grow the buffer.\n\t\t\t\tmaxbytes = maxbytes*2 + utf8.UTFMax\n\t\t\t\tnb := make([]byte, maxbytes)\n\t\t\t\tfor i, c := range b[0:nbytes] {\n\t\t\t\t\tnb[i] = c\n\t\t\t\t}\n\t\t\t\tb = nb\n\t\t\t}\n\t\t\tnbytes += utf8.EncodeRune(rune, b[nbytes:maxbytes])\n\t\t}\n\t}\n\treturn string(b[0:nbytes])\n}\n\n\/\/ Repeat returns a new string consisting of count copies of the string s.\nfunc Repeat(s string, count int) string {\n\tb := make([]byte, len(s)*count)\n\tbp := 0\n\tfor i := 0; i < count; i++ {\n\t\tfor j := 0; j < len(s); j++ {\n\t\t\tb[bp] = s[j]\n\t\t\tbp++\n\t\t}\n\t}\n\treturn string(b)\n}\n\n\n\/\/ ToUpper returns a copy of the string s with all Unicode letters mapped to their upper case.\nfunc ToUpper(s string) string { return Map(unicode.ToUpper, s) }\n\n\/\/ ToLower returns a copy of the string s with all Unicode letters mapped to their lower case.\nfunc ToLower(s string) string { return Map(unicode.ToLower, s) }\n\n\/\/ ToTitle returns a copy of the string s with all Unicode letters mapped to their title case.\nfunc ToTitle(s string) string { return Map(unicode.ToTitle, s) }\n\n\/\/ Trim returns a slice of the string s, with all leading and trailing white space\n\/\/ removed, as defined by Unicode.\nfunc TrimSpace(s string) string {\n\tstart, end := 0, len(s)\n\tfor start < end {\n\t\twid := 1\n\t\trune := int(s[start])\n\t\tif rune >= utf8.RuneSelf {\n\t\t\trune, wid = utf8.DecodeRuneInString(s[start:end])\n\t\t}\n\t\tif !unicode.IsSpace(rune) {\n\t\t\tbreak\n\t\t}\n\t\tstart += wid\n\t}\n\tfor start < end {\n\t\twid := 1\n\t\trune := int(s[end-1])\n\t\tif rune >= utf8.RuneSelf {\n\t\t\t\/\/ Back up carefully looking for beginning of rune. Mustn't pass start.\n\t\t\tfor wid = 2; start <= end-wid && !utf8.RuneStart(s[end-wid]); wid++ {\n\t\t\t}\n\t\t\tif start > end-wid { \/\/ invalid UTF-8 sequence; stop processing\n\t\t\t\treturn s[start:end]\n\t\t\t}\n\t\t\trune, wid = utf8.DecodeRuneInString(s[end-wid : end])\n\t\t}\n\t\tif !unicode.IsSpace(rune) {\n\t\t\tbreak\n\t\t}\n\t\tend -= wid\n\t}\n\treturn s[start:end]\n}\n\n\/\/ Bytes returns a new slice containing the bytes in s.\nfunc Bytes(s string) []byte {\n\tb := make([]byte, len(s))\n\tfor i := 0; i < len(s); i++ {\n\t\tb[i] = s[i]\n\t}\n\treturn b\n}\n\n\/\/ Runes returns a slice of runes (Unicode code points) equivalent to the string s.\nfunc Runes(s string) []int {\n\tt := make([]int, utf8.RuneCountInString(s))\n\ti := 0\n\tfor _, r := range s {\n\t\tt[i] = r\n\t\ti++\n\t}\n\treturn t\n}\n<|endoftext|>"} {"text":"package imgbom\n\nimport (\n\t\"github.com\/anchore\/imgbom\/imgbom\/cataloger\"\n\t\"github.com\/anchore\/imgbom\/imgbom\/distro\"\n\t\"github.com\/anchore\/imgbom\/imgbom\/logger\"\n\t\"github.com\/anchore\/imgbom\/imgbom\/pkg\"\n\t\"github.com\/anchore\/imgbom\/imgbom\/scope\"\n\t\"github.com\/anchore\/imgbom\/internal\/bus\"\n\t\"github.com\/anchore\/imgbom\/internal\/log\"\n\t\"github.com\/anchore\/stereoscope\/pkg\/image\"\n\t\"github.com\/wagoodman\/go-partybus\"\n)\n\nfunc IdentifyDistro(s scope.Scope) *distro.Distro {\n\treturn distro.Identify(s)\n}\n\nfunc GetScopeFromDir(d string, o scope.Option) (scope.Scope, error) {\n\treturn scope.NewScopeFromDir(d, o)\n}\n\nfunc GetScopeFromImage(img *image.Image, o scope.Option) (scope.Scope, error) {\n\treturn scope.NewScopeFromImage(img, o)\n}\n\nfunc Catalog(s scope.Scope) (*pkg.Catalog, error) {\n\treturn cataloger.Catalog(s)\n}\n\nfunc SetLogger(logger logger.Logger) {\n\tlog.Log = logger\n}\n\nfunc SetBus(b *partybus.Bus) {\n\tbus.SetPublisher(b)\n}\nlib: implement a NewScope to produce scopes from inputspackage imgbom\n\nimport (\n\t\"fmt\"\n\n\t\"github.com\/anchore\/imgbom\/imgbom\/cataloger\"\n\t\"github.com\/anchore\/imgbom\/imgbom\/distro\"\n\t\"github.com\/anchore\/imgbom\/imgbom\/logger\"\n\t\"github.com\/anchore\/imgbom\/imgbom\/pkg\"\n\t\"github.com\/anchore\/imgbom\/imgbom\/scope\"\n\t\"github.com\/anchore\/imgbom\/internal\/bus\"\n\t\"github.com\/anchore\/imgbom\/internal\/log\"\n\t\"github.com\/anchore\/stereoscope\"\n\t\"github.com\/anchore\/stereoscope\/pkg\/image\"\n\t\"github.com\/wagoodman\/go-partybus\"\n)\n\nfunc IdentifyDistro(s scope.Scope) *distro.Distro {\n\treturn distro.Identify(s)\n}\n\n\/\/ NewScope produces a Scope based on userInput like dir:\/\/ or image:tag\nfunc NewScope(userInput string, o scope.Option) (scope.Scope, func(), error) {\n\tprotocol := NewProtocol(userInput)\n\tlog.Debugf(\"protocol: %+v\", protocol)\n\n\tswitch protocol.Type {\n\tcase DirProtocol:\n\t\t\/\/ populate the scope object for dir\n\t\ts, err := GetScopeFromDir(protocol.Value, o)\n\t\tif err != nil {\n\t\t\treturn scope.Scope{}, func() {}, fmt.Errorf(\"could not populate scope from path (%s): %w\", protocol.Value, err)\n\t\t}\n\t\treturn s, func() {}, nil\n\n\tcase ImageProtocol:\n\t\tlog.Infof(\"Fetching image '%s'\", userInput)\n\t\timg, err := stereoscope.GetImage(userInput)\n\t\tcleanup := func() {\n\t\t\tstereoscope.Cleanup()\n\t\t}\n\n\t\tif err != nil || img == nil {\n\t\t\treturn scope.Scope{}, cleanup, fmt.Errorf(\"could not fetch image '%s': %w\", userInput, err)\n\t\t}\n\n\t\ts, err := GetScopeFromImage(img, o)\n\t\tif err != nil {\n\t\t\treturn scope.Scope{}, cleanup, fmt.Errorf(\"could not populate scope with image: %w\", err)\n\t\t}\n\t\treturn s, cleanup, nil\n\n\tdefault:\n\t\treturn scope.Scope{}, func() {}, fmt.Errorf(\"unable to process input for scanning: '%s'\", userInput)\n\t}\n}\n\nfunc GetScopeFromDir(d string, o scope.Option) (scope.Scope, error) {\n\treturn scope.NewScopeFromDir(d, o)\n}\n\nfunc GetScopeFromImage(img *image.Image, o scope.Option) (scope.Scope, error) {\n\treturn scope.NewScopeFromImage(img, o)\n}\n\nfunc Catalog(s scope.Scope) (*pkg.Catalog, error) {\n\treturn cataloger.Catalog(s)\n}\n\nfunc SetLogger(logger logger.Logger) {\n\tlog.Log = logger\n}\n\nfunc SetBus(b *partybus.Bus) {\n\tbus.SetPublisher(b)\n}\n<|endoftext|>"} {"text":"package controllers\n\nimport (\n\t\"database\/sql\"\n\t\/\/ _ \"github.com\/go-sql-driver\/mysql\"\n\t\"github.com\/robfig\/revel\"\n\t\"github.com\/robfig\/revel\/modules\/db\/app\"\n\t\"math\/rand\"\n\t\"runtime\"\n\t\"sort\"\n\t\"sync\"\n)\n\ntype MessageStruct struct {\n\tMessage string `json:\"message\"`\n}\n\ntype World struct {\n\tId uint16 `json:\"id\"`\n\tRandomNumber uint16 `json:\"randomNumber\"`\n}\n\ntype Fortune struct {\n\tId uint16 `json:\"id\"`\n\tMessage string `json:\"message\"`\n}\n\nconst (\n\tWorldSelect = \"SELECT id,randomNumber FROM World where id=?\"\n\tFortuneSelect = \"SELECT id,message FROM Fortune\"\n\tWorldRowCount = 10000\n\tMaxConnectionCount = 100\n)\n\nvar (\n\tworldStatement *sql.Stmt\n\tfortuneStatement *sql.Stmt\n)\n\nfunc init() {\n\trevel.OnAppStart(func() {\n\t\tvar err error\n\t\truntime.GOMAXPROCS(runtime.NumCPU())\n\t\tdb.DbPlugin{}.OnAppStart()\n\t\tdb.Db.SetMaxIdleConns(MaxConnectionCount)\n\t\tif worldStatement, err = db.Db.Prepare(WorldSelect); err != nil {\n\t\t\trevel.ERROR.Fatalln(err)\n\t\t}\n\t\tif fortuneStatement, err = db.Db.Prepare(FortuneSelect); err != nil {\n\t\t\trevel.ERROR.Fatalln(err)\n\t\t}\n\t})\n}\n\ntype App struct {\n\t*revel.Controller\n}\n\nfunc (c App) Json() revel.Result {\n\tc.Response.ContentType = \"application\/json\"\n\treturn c.RenderJson(MessageStruct{\"Hello, world\"})\n}\n\nfunc (c App) Db(queries int) revel.Result {\n\trowNum := rand.Intn(WorldRowCount) + 1\n\tif queries <= 1 {\n\t\tvar w World\n\t\tworldStatement.QueryRow(rowNum).Scan(&w.Id, &w.RandomNumber)\n\t\treturn c.RenderJson(w)\n\t}\n\n\tww := make([]World, queries)\n\tvar wg sync.WaitGroup\n\twg.Add(queries)\n\tfor i := 0; i < queries; i++ {\n\t\tgo func(i int) {\n\t\t\terr := worldStatement.QueryRow(rowNum).Scan(&ww[i].Id, &ww[i].RandomNumber)\n\t\t\tif err != nil {\n\t\t\t\trevel.ERROR.Fatalf(\"Error scanning world row: %v\", err)\n\t\t\t}\n\t\t\twg.Done()\n\t\t}(i)\n\t}\n\twg.Wait()\n\treturn c.RenderJson(ww)\n}\n\nfunc (c App) Fortune() revel.Result {\n\tfortunes := make([]*Fortune, 0, 16)\n\n\trows, err := fortuneStatement.Query()\n\tif err != nil {\n\t\trevel.ERROR.Fatalf(\"Error preparing statement: %v\", err)\n\t}\n\n\ti := 0\n\tvar fortune *Fortune\n\tfor rows.Next() {\n\t\tfortune = new(Fortune)\n\t\tif err = rows.Scan(&fortune.Id, &fortune.Message); err != nil {\n\t\t\trevel.ERROR.Fatalf(\"Error scanning fortune row: %v\", err)\n\t\t}\n\t\tfortunes = append(fortunes, fortune)\n\t\ti++\n\t}\n\tfortunes = append(fortunes, &Fortune{Message: \"Additional fortune added at request time.\"})\n\n\tsort.Sort(ByMessage{fortunes})\n\treturn c.Render(fortunes)\n}\n\ntype Fortunes []*Fortune\n\nfunc (s Fortunes) Len() int { return len(s) }\nfunc (s Fortunes) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\n\ntype ByMessage struct{ Fortunes }\n\nfunc (s ByMessage) Less(i, j int) bool { return s.Fortunes[i].Message < s.Fortunes[j].Message }\nFix: pick different rows for concurrent reqspackage controllers\n\nimport (\n\t\"database\/sql\"\n\t\/\/ _ \"github.com\/go-sql-driver\/mysql\"\n\t\"github.com\/robfig\/revel\"\n\t\"github.com\/robfig\/revel\/modules\/db\/app\"\n\t\"math\/rand\"\n\t\"runtime\"\n\t\"sort\"\n\t\"sync\"\n)\n\ntype MessageStruct struct {\n\tMessage string `json:\"message\"`\n}\n\ntype World struct {\n\tId uint16 `json:\"id\"`\n\tRandomNumber uint16 `json:\"randomNumber\"`\n}\n\ntype Fortune struct {\n\tId uint16 `json:\"id\"`\n\tMessage string `json:\"message\"`\n}\n\nconst (\n\tWorldSelect = \"SELECT id,randomNumber FROM World where id=?\"\n\tFortuneSelect = \"SELECT id,message FROM Fortune\"\n\tWorldRowCount = 10000\n\tMaxConnectionCount = 100\n)\n\nvar (\n\tworldStatement *sql.Stmt\n\tfortuneStatement *sql.Stmt\n)\n\nfunc init() {\n\trevel.OnAppStart(func() {\n\t\tvar err error\n\t\truntime.GOMAXPROCS(runtime.NumCPU())\n\t\tdb.DbPlugin{}.OnAppStart()\n\t\tdb.Db.SetMaxIdleConns(MaxConnectionCount)\n\t\tif worldStatement, err = db.Db.Prepare(WorldSelect); err != nil {\n\t\t\trevel.ERROR.Fatalln(err)\n\t\t}\n\t\tif fortuneStatement, err = db.Db.Prepare(FortuneSelect); err != nil {\n\t\t\trevel.ERROR.Fatalln(err)\n\t\t}\n\t})\n}\n\ntype App struct {\n\t*revel.Controller\n}\n\nfunc (c App) Json() revel.Result {\n\tc.Response.ContentType = \"application\/json\"\n\treturn c.RenderJson(MessageStruct{\"Hello, world\"})\n}\n\nfunc (c App) Db(queries int) revel.Result {\n\tif queries <= 1 {\n\t\trowNum := rand.Intn(WorldRowCount) + 1\n\t\tvar w World\n\t\tworldStatement.QueryRow(rowNum).Scan(&w.Id, &w.RandomNumber)\n\t\treturn c.RenderJson(w)\n\t}\n\n\tww := make([]World, queries)\n\tvar wg sync.WaitGroup\n\twg.Add(queries)\n\tfor i := 0; i < queries; i++ {\n\t\tgo func(i int) {\n\t\t\trowNum := rand.Intn(WorldRowCount) + 1\n\t\t\terr := worldStatement.QueryRow(rowNum).Scan(&ww[i].Id, &ww[i].RandomNumber)\n\t\t\tif err != nil {\n\t\t\t\trevel.ERROR.Fatalf(\"Error scanning world row: %v\", err)\n\t\t\t}\n\t\t\twg.Done()\n\t\t}(i)\n\t}\n\twg.Wait()\n\treturn c.RenderJson(ww)\n}\n\nfunc (c App) Fortune() revel.Result {\n\tfortunes := make([]*Fortune, 0, 16)\n\n\trows, err := fortuneStatement.Query()\n\tif err != nil {\n\t\trevel.ERROR.Fatalf(\"Error preparing statement: %v\", err)\n\t}\n\n\ti := 0\n\tvar fortune *Fortune\n\tfor rows.Next() {\n\t\tfortune = new(Fortune)\n\t\tif err = rows.Scan(&fortune.Id, &fortune.Message); err != nil {\n\t\t\trevel.ERROR.Fatalf(\"Error scanning fortune row: %v\", err)\n\t\t}\n\t\tfortunes = append(fortunes, fortune)\n\t\ti++\n\t}\n\tfortunes = append(fortunes, &Fortune{Message: \"Additional fortune added at request time.\"})\n\n\tsort.Sort(ByMessage{fortunes})\n\treturn c.Render(fortunes)\n}\n\ntype Fortunes []*Fortune\n\nfunc (s Fortunes) Len() int { return len(s) }\nfunc (s Fortunes) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\n\ntype ByMessage struct{ Fortunes }\n\nfunc (s ByMessage) Less(i, j int) bool { return s.Fortunes[i].Message < s.Fortunes[j].Message }\n<|endoftext|>"} {"text":"package v7\n\nimport (\n\t\"strings\"\n\n\t\"code.cloudfoundry.org\/cli\/util\/ui\"\n)\n\ntype IsolationSegmentsCommand struct {\n\tBaseCommand\n\tusage interface{} `usage:\"CF_NAME isolation-segments\"`\n\trelatedCommands interface{} `related_commands:\"enable-org-isolation, create-isolation-segment\"`\n}\n\nfunc (cmd IsolationSegmentsCommand) Execute(args []string) error {\n\terr := cmd.SharedActor.CheckTarget(false, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tuser, err := cmd.Config.CurrentUser()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmd.UI.DisplayTextWithFlavor(\"Getting isolation segments as {{.CurrentUser}}...\", map[string]interface{}{\n\t\t\"CurrentUser\": user.Name,\n\t})\n\n\tsummaries, warnings, err := cmd.Actor.GetIsolationSegmentSummaries()\n\tcmd.UI.DisplayWarnings(warnings)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttable := [][]string{\n\t\t{\n\t\t\tcmd.UI.TranslateText(\"name\"),\n\t\t\tcmd.UI.TranslateText(\"orgs\"),\n\t\t},\n\t}\n\n\tfor _, summary := range summaries {\n\t\ttable = append(\n\t\t\ttable,\n\t\t\t[]string{\n\t\t\t\tsummary.Name,\n\t\t\t\tstrings.Join(summary.EntitledOrgs, \", \"),\n\t\t\t},\n\t\t)\n\t}\n\n\tcmd.UI.DisplayTableWithHeader(\"\", table, ui.DefaultTableSpacePadding)\n\treturn nil\n}\n**V7**: add whitespace to list isolation segmentspackage v7\n\nimport (\n\t\"strings\"\n\n\t\"code.cloudfoundry.org\/cli\/util\/ui\"\n)\n\ntype IsolationSegmentsCommand struct {\n\tBaseCommand\n\tusage interface{} `usage:\"CF_NAME isolation-segments\"`\n\trelatedCommands interface{} `related_commands:\"enable-org-isolation, create-isolation-segment\"`\n}\n\nfunc (cmd IsolationSegmentsCommand) Execute(args []string) error {\n\terr := cmd.SharedActor.CheckTarget(false, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tuser, err := cmd.Config.CurrentUser()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcmd.UI.DisplayTextWithFlavor(\"Getting isolation segments as {{.CurrentUser}}...\", map[string]interface{}{\n\t\t\"CurrentUser\": user.Name,\n\t})\n\n\tcmd.UI.DisplayNewline()\n\n\tsummaries, warnings, err := cmd.Actor.GetIsolationSegmentSummaries()\n\tcmd.UI.DisplayWarnings(warnings)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttable := [][]string{\n\t\t{\n\t\t\tcmd.UI.TranslateText(\"name\"),\n\t\t\tcmd.UI.TranslateText(\"orgs\"),\n\t\t},\n\t}\n\n\tfor _, summary := range summaries {\n\t\ttable = append(\n\t\t\ttable,\n\t\t\t[]string{\n\t\t\t\tsummary.Name,\n\t\t\t\tstrings.Join(summary.EntitledOrgs, \", \"),\n\t\t\t},\n\t\t)\n\t}\n\n\tcmd.UI.DisplayTableWithHeader(\"\", table, ui.DefaultTableSpacePadding)\n\treturn nil\n}\n<|endoftext|>"} {"text":"package fritz\n\nimport (\n\t\"log\"\n\t\"testing\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\n\/\/ TestAPIGetSwitchList unit test.\nfunc TestAPIGetSwitchList(t *testing.T) {\n\tts, fritzClient := serverAndClient(\"testdata\/examplechallenge_test.xml\", \"testdata\/examplechallenge_sid_test.xml\")\n\tdefer ts.Close()\n\tfritzClient.Login()\n\tfritz := UsingClient(fritzClient)\n\t_, err := fritz.GetSwitchList()\n\tassert.NoError(t, err)\n}\n\n\/\/ TestAPIGetSwitchListErrorServerDown unit test.\nfunc TestAPIGetSwitchListErrorServerDown(t *testing.T) {\n\tts, fritzClient := serverAndClient(\"testdata\/examplechallenge_test.xml\", \"testdata\/examplechallenge_sid_test.xml\")\n\tdefer ts.Close()\n\tfritzClient.Login()\n\tfritz := UsingClient(fritzClient)\n\tts.Close()\n\t_, err := fritz.GetSwitchList()\n\tassert.Error(t, err)\n}\n\n\/\/ TestGetWithAin unit test.\nfunc TestGetWithAin(t *testing.T) {\n\tts, fritzClient := serverAndClient(\"testdata\/examplechallenge_test.xml\", \"testdata\/examplechallenge_sid_test.xml\")\n\tdefer ts.Close()\n\tfritzClient.Login()\n\tfritz := UsingClient(fritzClient).(*fritzImpl)\n\t_, err := fritz.getWithAinAndParam(\"ain\", \"cmd\", \"x=y\")\n\tassert.NoError(t, err)\n}\n\n\/\/ TestGetDeviceList unit test.\nfunc TestGetDeviceList(t *testing.T) {\n\tts, fritzClient := serverAndClient(\"testdata\/examplechallenge_sid_test.xml\",\n\t\t\"testdata\/examplechallenge_sid_test.xml\", \"testdata\/devicelist_test.xml\")\n\tdefer ts.Close()\n\tfritzClient.Login()\n\tfritz := UsingClient(fritzClient)\n\tdevList, err := fritz.ListDevices()\n\tlog.Println(*devList)\n\tassert.NoError(t, err)\n\tassert.NotNil(t, devList)\n\tassert.NotEmpty(t, devList.Devices)\n\tassert.NotEmpty(t, devList.Devices[0].ID)\n\tassert.NotEmpty(t, devList.Devices[0].Identifier)\n\tassert.NotEmpty(t, devList.Devices[0].Functionbitmask)\n\tassert.NotEmpty(t, devList.Devices[0].Fwversion)\n\tassert.NotEmpty(t, devList.Devices[0].Manufacturer)\n\tassert.Equal(t, devList.Devices[0].Present, 1)\n\tassert.NotEmpty(t, devList.Devices[0].Name)\n\n}\n\n\/\/ TestAPIGetDeviceListErrorServerDown unit test.\nfunc TestAPIGetDeviceListErrorServerDown(t *testing.T) {\n\tts, fritzClient := serverAndClient(\"testdata\/examplechallenge_test.xml\", \"testdata\/examplechallenge_sid_test.xml\")\n\tdefer ts.Close()\n\tfritzClient.Login()\n\tfritz := UsingClient(fritzClient)\n\tts.Close()\n\t_, err := fritz.ListDevices()\n\tassert.Error(t, err)\n}\n\n\/\/ TestAPIGetSwitchDeviceOn unit test.\nfunc TestAPIGetSwitchDeviceOn(t *testing.T) {\n\tts, fritzClient := serverAndClient(\"testdata\/examplechallenge_test.xml\", \"testdata\/examplechallenge_sid_test.xml\", \"testdata\/devicelist_test.xml\", \"testdata\/answer_switch_on_test\")\n\tdefer ts.Close()\n\tfritzClient.Login()\n\tfritz := UsingClient(fritzClient)\n\tresp, err := fritz.Switch(\"DER device\", \"on\")\n\tassert.NoError(t, err)\n\tassert.NotEmpty(t, resp)\n}\n\n\/\/ TestAPIGetSwitchDeviceOff unit test.\nfunc TestAPIGetSwitchDeviceOff(t *testing.T) {\n\tts, fritzClient := serverAndClient(\"testdata\/examplechallenge_test.xml\", \"testdata\/examplechallenge_sid_test.xml\", \"testdata\/devicelist_test.xml\", \"testdata\/answer_switch_on_test\")\n\tdefer ts.Close()\n\tfritzClient.Login()\n\tfritz := UsingClient(fritzClient)\n\tresp, err := fritz.Switch(\"DER device\", \"off\")\n\tassert.NoError(t, err)\n\tassert.NotEmpty(t, resp)\n}\n\n\/\/ TestAPIGetSwitchDeviceErrorServerDownAtListingStage unit test.\nfunc TestAPIGetSwitchDeviceErrorServerDownAtListingStage(t *testing.T) {\n\tts, fritzClient := serverAndClient(\"testdata\/examplechallenge_test.xml\", \"testdata\/examplechallenge_sid_test.xml\", \"testdata\/devicelist_test.xml\", \"testdata\/answer_switch_on_test\")\n\tdefer ts.Close()\n\tfritzClient.Login()\n\tts.Close()\n\tfritz := UsingClient(fritzClient)\n\t_, err := fritz.Switch(\"DER device\", \"off\")\n\tassert.Error(t, err)\n}\n\n\/\/ TestAPIGetSwitchDeviceErrorUnkownDevice unit test.\nfunc TestAPIGetSwitchDeviceErrorUnkownDevice(t *testing.T) {\n\tts, fritzClient := serverAndClient(\"testdata\/examplechallenge_test.xml\", \"testdata\/examplechallenge_sid_test.xml\", \"testdata\/devicelist_empty_test.xml\")\n\tdefer ts.Close()\n\tfritzClient.Login()\n\tfritz := UsingClient(fritzClient)\n\t_, err := fritz.Switch(\"DER device\", \"off\")\n\tassert.Error(t, err)\n}\n\n\/\/ TestAPIGetSwitchByAinWithError unit test.\nfunc TestAPIGetSwitchByAinWithError(t *testing.T) {\n\tts, fritzClient := serverAndClient(\"testdata\/examplechallenge_test.xml\", \"testdata\/examplechallenge_sid_test.xml\", \"testdata\/devicelist_empty_test.xml\")\n\tdefer ts.Close()\n\tfritzClient.Login()\n\tfritz := UsingClient(fritzClient).(*fritzImpl)\n\tts.Close()\n\t_, err := fritz.switchForAin(\"123344\", \"off\")\n\tassert.Error(t, err)\n}\n\n\/\/ TestAPIToggleDevice unit test.\nfunc TestAPIToggleDevice(t *testing.T) {\n\tts, fritzClient := serverAndClient(\"testdata\/examplechallenge_test.xml\", \"testdata\/examplechallenge_sid_test.xml\", \"testdata\/devicelist_test.xml\", \"testdata\/answer_switch_on_test\")\n\tdefer ts.Close()\n\tfritzClient.Login()\n\tfritz := UsingClient(fritzClient)\n\tresp, err := fritz.Toggle(\"DER device\")\n\tassert.NoError(t, err)\n\tassert.NotEmpty(t, resp)\n}\n\n\/\/ TestAPIToggleDeviceErrorServerDownAtListingStage unit test.\nfunc TestAPIToggleDeviceErrorServerDownAtListingStage(t *testing.T) {\n\tts, fritzClient := serverAndClient(\"testdata\/examplechallenge_test.xml\", \"testdata\/examplechallenge_sid_test.xml\", \"testdata\/devicelist_test.xml\", \"testdata\/answer_switch_on_test\")\n\tdefer ts.Close()\n\tfritzClient.Login()\n\tts.Close()\n\tfritz := UsingClient(fritzClient)\n\t_, err := fritz.Toggle(\"DER device\")\n\tassert.Error(t, err)\n}\n\n\/\/ TestAPIToggleDeviceErrorServerDownAtToggleStage unit test.\nfunc TestAPIToggleDeviceErrorServerDownAtToggleStage(t *testing.T) {\n\tts, fritzClient := serverAndClient(\"testdata\/examplechallenge_test.xml\", \"testdata\/examplechallenge_sid_test.xml\", \"testdata\/devicelist_test.xml\", \"testdata\/answer_switch_on_test\")\n\tdefer ts.Close()\n\tfritzClient.Login()\n\tfritz := UsingClient(fritzClient).(*fritzImpl)\n\tts.Close()\n\t_, err := fritz.toggleForAin(\"DER device\")\n\tassert.Error(t, err)\n}\n\n\/\/ TestAPISetHkr unit test.\nfunc TestAPISetHkr(t *testing.T) {\n\tts, fritzClient := serverAndClient(\"testdata\/examplechallenge_test.xml\", \"testdata\/examplechallenge_sid_test.xml\", \"testdata\/devicelist_test.xml\", \"testdata\/answer_switch_on_test\")\n\tdefer ts.Close()\n\tfritzClient.Login()\n\tfritz := UsingClient(fritzClient).(*fritzImpl)\n\t_, err := fritz.Temperature(\"DER device\", 12.5)\n\tassert.NoError(t, err)\n}\n\n\/\/ TestAPISetHkrDevNotFound unit test.\nfunc TestAPISetHkrDevNotFound(t *testing.T) {\n\tts, fritzClient := serverAndClient(\"testdata\/examplechallenge_test.xml\", \"testdata\/examplechallenge_sid_test.xml\", \"testdata\/devicelist_test.xml\", \"testdata\/answer_switch_on_test\")\n\tdefer ts.Close()\n\tfritzClient.Login()\n\tfritz := UsingClient(fritzClient).(*fritzImpl)\n\t_, err := fritz.Temperature(\"DOES-NOT-EXIST\", 12.5)\n\tassert.Error(t, err)\n}\n\n\/\/ TestAPISetHkrErrorServerDownAtCommandStage unit test.\nfunc TestAPISetHkrErrorServerDownAtCommandStage(t *testing.T) {\n\tts, fritzClient := serverAndClient(\"testdata\/examplechallenge_test.xml\", \"testdata\/examplechallenge_sid_test.xml\", \"testdata\/devicelist_test.xml\", \"testdata\/answer_switch_on_test\")\n\tdefer ts.Close()\n\tfritzClient.Login()\n\tfritz := UsingClient(fritzClient).(*fritzImpl)\n\tts.Close()\n\t_, err := fritz.temperatureForAin(\"12345\", 12.5)\n\tassert.Error(t, err)\n}\n\nfunc TestRd(t *testing.T) {\n\tassert.Equal(t, int64(1), round(0.5))\n\tassert.Equal(t, int64(0), round(0.4))\n\tassert.Equal(t, int64(0), round(0.1))\n\tassert.Equal(t, int64(0), round(-0.1))\n\tassert.Equal(t, int64(0), round(-0.499))\n\tassert.Equal(t, int64(156), round(156))\n}\nadd comment to testpackage fritz\n\nimport (\n\t\"log\"\n\t\"testing\"\n\n\t\"github.com\/stretchr\/testify\/assert\"\n)\n\n\/\/ TestAPIGetSwitchList unit test.\nfunc TestAPIGetSwitchList(t *testing.T) {\n\tts, fritzClient := serverAndClient(\"testdata\/examplechallenge_test.xml\", \"testdata\/examplechallenge_sid_test.xml\")\n\tdefer ts.Close()\n\tfritzClient.Login()\n\tfritz := UsingClient(fritzClient)\n\t_, err := fritz.GetSwitchList()\n\tassert.NoError(t, err)\n}\n\n\/\/ TestAPIGetSwitchListErrorServerDown unit test.\nfunc TestAPIGetSwitchListErrorServerDown(t *testing.T) {\n\tts, fritzClient := serverAndClient(\"testdata\/examplechallenge_test.xml\", \"testdata\/examplechallenge_sid_test.xml\")\n\tdefer ts.Close()\n\tfritzClient.Login()\n\tfritz := UsingClient(fritzClient)\n\tts.Close()\n\t_, err := fritz.GetSwitchList()\n\tassert.Error(t, err)\n}\n\n\/\/ TestGetWithAin unit test.\nfunc TestGetWithAin(t *testing.T) {\n\tts, fritzClient := serverAndClient(\"testdata\/examplechallenge_test.xml\", \"testdata\/examplechallenge_sid_test.xml\")\n\tdefer ts.Close()\n\tfritzClient.Login()\n\tfritz := UsingClient(fritzClient).(*fritzImpl)\n\t_, err := fritz.getWithAinAndParam(\"ain\", \"cmd\", \"x=y\")\n\tassert.NoError(t, err)\n}\n\n\/\/ TestGetDeviceList unit test.\nfunc TestGetDeviceList(t *testing.T) {\n\tts, fritzClient := serverAndClient(\"testdata\/examplechallenge_sid_test.xml\",\n\t\t\"testdata\/examplechallenge_sid_test.xml\", \"testdata\/devicelist_test.xml\")\n\tdefer ts.Close()\n\tfritzClient.Login()\n\tfritz := UsingClient(fritzClient)\n\tdevList, err := fritz.ListDevices()\n\tlog.Println(*devList)\n\tassert.NoError(t, err)\n\tassert.NotNil(t, devList)\n\tassert.NotEmpty(t, devList.Devices)\n\tassert.NotEmpty(t, devList.Devices[0].ID)\n\tassert.NotEmpty(t, devList.Devices[0].Identifier)\n\tassert.NotEmpty(t, devList.Devices[0].Functionbitmask)\n\tassert.NotEmpty(t, devList.Devices[0].Fwversion)\n\tassert.NotEmpty(t, devList.Devices[0].Manufacturer)\n\tassert.Equal(t, devList.Devices[0].Present, 1)\n\tassert.NotEmpty(t, devList.Devices[0].Name)\n\n}\n\n\/\/ TestAPIGetDeviceListErrorServerDown unit test.\nfunc TestAPIGetDeviceListErrorServerDown(t *testing.T) {\n\tts, fritzClient := serverAndClient(\"testdata\/examplechallenge_test.xml\", \"testdata\/examplechallenge_sid_test.xml\")\n\tdefer ts.Close()\n\tfritzClient.Login()\n\tfritz := UsingClient(fritzClient)\n\tts.Close()\n\t_, err := fritz.ListDevices()\n\tassert.Error(t, err)\n}\n\n\/\/ TestAPIGetSwitchDeviceOn unit test.\nfunc TestAPIGetSwitchDeviceOn(t *testing.T) {\n\tts, fritzClient := serverAndClient(\"testdata\/examplechallenge_test.xml\", \"testdata\/examplechallenge_sid_test.xml\", \"testdata\/devicelist_test.xml\", \"testdata\/answer_switch_on_test\")\n\tdefer ts.Close()\n\tfritzClient.Login()\n\tfritz := UsingClient(fritzClient)\n\tresp, err := fritz.Switch(\"DER device\", \"on\")\n\tassert.NoError(t, err)\n\tassert.NotEmpty(t, resp)\n}\n\n\/\/ TestAPIGetSwitchDeviceOff unit test.\nfunc TestAPIGetSwitchDeviceOff(t *testing.T) {\n\tts, fritzClient := serverAndClient(\"testdata\/examplechallenge_test.xml\", \"testdata\/examplechallenge_sid_test.xml\", \"testdata\/devicelist_test.xml\", \"testdata\/answer_switch_on_test\")\n\tdefer ts.Close()\n\tfritzClient.Login()\n\tfritz := UsingClient(fritzClient)\n\tresp, err := fritz.Switch(\"DER device\", \"off\")\n\tassert.NoError(t, err)\n\tassert.NotEmpty(t, resp)\n}\n\n\/\/ TestAPIGetSwitchDeviceErrorServerDownAtListingStage unit test.\nfunc TestAPIGetSwitchDeviceErrorServerDownAtListingStage(t *testing.T) {\n\tts, fritzClient := serverAndClient(\"testdata\/examplechallenge_test.xml\", \"testdata\/examplechallenge_sid_test.xml\", \"testdata\/devicelist_test.xml\", \"testdata\/answer_switch_on_test\")\n\tdefer ts.Close()\n\tfritzClient.Login()\n\tts.Close()\n\tfritz := UsingClient(fritzClient)\n\t_, err := fritz.Switch(\"DER device\", \"off\")\n\tassert.Error(t, err)\n}\n\n\/\/ TestAPIGetSwitchDeviceErrorUnkownDevice unit test.\nfunc TestAPIGetSwitchDeviceErrorUnkownDevice(t *testing.T) {\n\tts, fritzClient := serverAndClient(\"testdata\/examplechallenge_test.xml\", \"testdata\/examplechallenge_sid_test.xml\", \"testdata\/devicelist_empty_test.xml\")\n\tdefer ts.Close()\n\tfritzClient.Login()\n\tfritz := UsingClient(fritzClient)\n\t_, err := fritz.Switch(\"DER device\", \"off\")\n\tassert.Error(t, err)\n}\n\n\/\/ TestAPIGetSwitchByAinWithError unit test.\nfunc TestAPIGetSwitchByAinWithError(t *testing.T) {\n\tts, fritzClient := serverAndClient(\"testdata\/examplechallenge_test.xml\", \"testdata\/examplechallenge_sid_test.xml\", \"testdata\/devicelist_empty_test.xml\")\n\tdefer ts.Close()\n\tfritzClient.Login()\n\tfritz := UsingClient(fritzClient).(*fritzImpl)\n\tts.Close()\n\t_, err := fritz.switchForAin(\"123344\", \"off\")\n\tassert.Error(t, err)\n}\n\n\/\/ TestAPIToggleDevice unit test.\nfunc TestAPIToggleDevice(t *testing.T) {\n\tts, fritzClient := serverAndClient(\"testdata\/examplechallenge_test.xml\", \"testdata\/examplechallenge_sid_test.xml\", \"testdata\/devicelist_test.xml\", \"testdata\/answer_switch_on_test\")\n\tdefer ts.Close()\n\tfritzClient.Login()\n\tfritz := UsingClient(fritzClient)\n\tresp, err := fritz.Toggle(\"DER device\")\n\tassert.NoError(t, err)\n\tassert.NotEmpty(t, resp)\n}\n\n\/\/ TestAPIToggleDeviceErrorServerDownAtListingStage unit test.\nfunc TestAPIToggleDeviceErrorServerDownAtListingStage(t *testing.T) {\n\tts, fritzClient := serverAndClient(\"testdata\/examplechallenge_test.xml\", \"testdata\/examplechallenge_sid_test.xml\", \"testdata\/devicelist_test.xml\", \"testdata\/answer_switch_on_test\")\n\tdefer ts.Close()\n\tfritzClient.Login()\n\tts.Close()\n\tfritz := UsingClient(fritzClient)\n\t_, err := fritz.Toggle(\"DER device\")\n\tassert.Error(t, err)\n}\n\n\/\/ TestAPIToggleDeviceErrorServerDownAtToggleStage unit test.\nfunc TestAPIToggleDeviceErrorServerDownAtToggleStage(t *testing.T) {\n\tts, fritzClient := serverAndClient(\"testdata\/examplechallenge_test.xml\", \"testdata\/examplechallenge_sid_test.xml\", \"testdata\/devicelist_test.xml\", \"testdata\/answer_switch_on_test\")\n\tdefer ts.Close()\n\tfritzClient.Login()\n\tfritz := UsingClient(fritzClient).(*fritzImpl)\n\tts.Close()\n\t_, err := fritz.toggleForAin(\"DER device\")\n\tassert.Error(t, err)\n}\n\n\/\/ TestAPISetHkr unit test.\nfunc TestAPISetHkr(t *testing.T) {\n\tts, fritzClient := serverAndClient(\"testdata\/examplechallenge_test.xml\", \"testdata\/examplechallenge_sid_test.xml\", \"testdata\/devicelist_test.xml\", \"testdata\/answer_switch_on_test\")\n\tdefer ts.Close()\n\tfritzClient.Login()\n\tfritz := UsingClient(fritzClient).(*fritzImpl)\n\t_, err := fritz.Temperature(\"DER device\", 12.5)\n\tassert.NoError(t, err)\n}\n\n\/\/ TestAPISetHkrDevNotFound unit test.\nfunc TestAPISetHkrDevNotFound(t *testing.T) {\n\tts, fritzClient := serverAndClient(\"testdata\/examplechallenge_test.xml\", \"testdata\/examplechallenge_sid_test.xml\", \"testdata\/devicelist_test.xml\", \"testdata\/answer_switch_on_test\")\n\tdefer ts.Close()\n\tfritzClient.Login()\n\tfritz := UsingClient(fritzClient).(*fritzImpl)\n\t_, err := fritz.Temperature(\"DOES-NOT-EXIST\", 12.5)\n\tassert.Error(t, err)\n}\n\n\/\/ TestAPISetHkrErrorServerDownAtCommandStage unit test.\nfunc TestAPISetHkrErrorServerDownAtCommandStage(t *testing.T) {\n\tts, fritzClient := serverAndClient(\"testdata\/examplechallenge_test.xml\", \"testdata\/examplechallenge_sid_test.xml\", \"testdata\/devicelist_test.xml\", \"testdata\/answer_switch_on_test\")\n\tdefer ts.Close()\n\tfritzClient.Login()\n\tfritz := UsingClient(fritzClient).(*fritzImpl)\n\tts.Close()\n\t_, err := fritz.temperatureForAin(\"12345\", 12.5)\n\tassert.Error(t, err)\n}\n\n\/\/ TestRounding tests rounding.\nfunc TestRounding(t *testing.T) {\n\tassert.Equal(t, int64(1), round(0.5))\n\tassert.Equal(t, int64(0), round(0.4))\n\tassert.Equal(t, int64(0), round(0.1))\n\tassert.Equal(t, int64(0), round(-0.1))\n\tassert.Equal(t, int64(0), round(-0.499))\n\tassert.Equal(t, int64(156), round(156))\n}\n<|endoftext|>"} {"text":"package hal\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n)\n\n\/\/ provides a persistent configuration store\n\n\/\/ Order of precendence for prefs:\n\/\/ user -> room -> broker -> plugin -> global -> default\n\n\/\/ PREFS_TABLE contains the SQL to create the prefs table\n\/\/ key field is called pkey because key is a reserved word\nconst PREFS_TABLE = `\nCREATE TABLE IF NOT EXISTS prefs (\n\t user VARCHAR(32) DEFAULT \"\",\n\t room VARCHAR(32) DEFAULT \"\",\n\t broker VARCHAR(32) DEFAULT \"\",\n\t plugin VARCHAR(32) DEFAULT \"\",\n\t pkey VARCHAR(32) NOT NULL,\n\t value TEXT,\n\t PRIMARY KEY(user, room, broker, plugin, pkey)\n)`\n\n\/*\n -- test data, will remove once there are automated tests\n INSERT INTO prefs (user,room,broker,plugin,pkey,value) VALUES (\"tobert\", \"\", \"\", \"\", \"foo\", \"user\");\n INSERT INTO prefs (user,room,broker,plugin,pkey,value) VALUES (\"tobert\", \"CORE\", \"\", \"\", \"foo\",\n \"user-room\");\n INSERT INTO prefs (user,room,broker,plugin,pkey,value) VALUES (\"tobert\", \"CORE\", \"slack\", \"\", \"foo\",\n \"user-room-broker\");\n INSERT INTO prefs (user,room,broker,plugin,pkey,value) VALUES (\"tobert\", \"CORE\", \"slack\", \"uptime\",\n \"foo\", \"user-room-broker-plugin\");\n INSERT INTO prefs (user,room,broker,plugin,pkey,value) VALUES (\"tobert\", \"\", \"slack\", \"uptime\", \"foo\",\n \"user-broker-plugin\");\n INSERT INTO prefs (user,room,broker,plugin,pkey,value) VALUES (\"tobert\", \"CORE\", \"\", \"uptime\",\n \"foo\", \"user-room-plugin\");\n INSERT INTO prefs (user,room,broker,plugin,pkey,value) VALUES (\"tobert\", \"\", \"\", \"uptime\", \"foo\",\n \"user-plugin\");\n*\/\n\n\/\/ !prefs list --scope plugin --plugin autoresponder\n\/\/ !prefs get --scope room --plugin autoresponder --room CORE --key timezone\n\/\/ !prefs set --scope user --plugin autoresponder --room CORE\n\n\/\/ Pref is a key\/value pair associated with a combination of user, plugin,\n\/\/ borker, or room.\ntype Pref struct {\n\tUser string\n\tPlugin string\n\tBroker string\n\tRoom string\n\tKey string\n\tValue string\n\tDefault string\n\tSuccess bool\n\tError error\n}\n\ntype Prefs []*Pref\n\n\/\/ GetPref will retreive the most-specific preference from pref\n\/\/ storage using the parameters provided. This is a bit like pattern\n\/\/ matching. If no match is found, the provided default is returned.\n\/\/ TODO: explain this better\nfunc GetPref(user, broker, room, plugin, key, def string) Pref {\n\tpref := Pref{\n\t\tUser: user,\n\t\tRoom: room,\n\t\tBroker: broker,\n\t\tPlugin: plugin,\n\t\tKey: key,\n\t\tDefault: def,\n\t}\n\n\tup := pref.Get()\n\tif up.Success {\n\t\treturn up\n\t}\n\n\t\/\/ no match, return the default\n\tpref.Value = def\n\treturn pref\n}\n\n\/\/ SetPref sets a preference and is shorthand for Pref{}.Set().\nfunc SetPref(user, broker, room, plugin, key, value string) error {\n\tpref := Pref{\n\t\tUser: user,\n\t\tRoom: room,\n\t\tBroker: broker,\n\t\tPlugin: plugin,\n\t\tKey: key,\n\t\tValue: value,\n\t}\n\n\treturn pref.Set()\n}\n\n\/\/ GetPrefs retrieves a set of preferences from the database. The\n\/\/ settings are matched exactly on user,broker,room,plugin.\n\/\/ e.g. GetPrefs(\"\", \"\", \"\", \"uptime\") would get only records that\n\/\/ have user\/broker\/room set to the empty string and room\n\/\/ set to \"uptime\". A record with user \"pford\" and plugin \"uptime\"\n\/\/ would not be included.\nfunc GetPrefs(user, broker, room, plugin string) Prefs {\n\tpref := Pref{\n\t\tUser: user,\n\t\tBroker: broker,\n\t\tRoom: room,\n\t\tPlugin: plugin,\n\t}\n\treturn pref.get()\n}\n\n\/\/ FindPrefs gets all records that match any of the inputs that are\n\/\/ not empty strings. (hint: user=\"x\", broker=\"y\"; WHERE user=? OR broker=?)\nfunc FindPrefs(user, broker, room, plugin, key string) Prefs {\n\tpref := Pref{\n\t\tUser: user,\n\t\tBroker: broker,\n\t\tRoom: room,\n\t\tPlugin: plugin,\n\t\tKey: key,\n\t}\n\treturn pref.Find()\n}\n\n\/\/ Get retrieves a value from the database. If the database returns\n\/\/ an error, Success will be false and the Error field will be populated.\nfunc (in *Pref) Get() Pref {\n\tprefs := in.get()\n\n\tif len(prefs) == 1 {\n\t\treturn *prefs[0]\n\t} else if len(prefs) > 1 {\n\t\tpanic(\"TOO MANY PREFS\")\n\t} else if len(prefs) == 0 {\n\t\tout := *in\n\t\t\/\/ only set success to false if there is also an error\n\t\t\/\/ queries with 0 rows are successful\n\t\tif out.Error != nil {\n\t\t\tout.Success = false\n\t\t} else {\n\t\t\tout.Success = true\n\t\t\tout.Value = out.Default\n\t\t}\n\t\treturn out\n\t}\n\n\tpanic(\"BUG: should be impossible to reach this point\")\n}\n\n\/\/ GetPrefs returns all preferences that match the fields set in the handle.\nfunc (in *Pref) GetPrefs() Prefs {\n\treturn in.get()\n}\n\nfunc (in *Pref) get() Prefs {\n\tSqlInit(PREFS_TABLE)\n\n\tsql := `SELECT user,room,broker,plugin,pkey,value\n\t FROM prefs\n\t WHERE user=?\n\t\t\t AND room=?\n\t\t\t AND broker=?\n\t\t\t AND plugin=?`\n\tparams := []interface{}{&in.User, &in.Room, &in.Broker, &in.Plugin}\n\n\t\/\/ only query by key if it's specified, otherwise get all keys for the selection\n\tif in.Key != \"\" {\n\t\tsql += \" AND pkey=?\"\n\t\tparams = append(params, &in.Key)\n\t}\n\n\tdb := SqlDB()\n\n\trows, err := db.Query(sql, params...)\n\tif err != nil {\n\t\tlog.Printf(\"Returning default due to SQL query failure: %s\", err)\n\t\treturn Prefs{}\n\t}\n\n\tdefer rows.Close()\n\n\tout := make(Prefs, 0)\n\n\tfor rows.Next() {\n\t\tp := *in\n\n\t\terr := rows.Scan(&p.User, &p.Room, &p.Broker, &p.Plugin, &p.Key, &p.Value)\n\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Returning default due to row iteration failure: %s\", err)\n\t\t\tp.Success = false\n\t\t\tp.Value = in.Default\n\t\t\tp.Error = err\n\t\t} else {\n\t\t\tp.Success = true\n\t\t\tp.Error = nil\n\t\t}\n\n\t\tout = append(out, &p)\n\t}\n\n\treturn out\n}\n\n\/\/ Set writes the value and returns a new struct with the new value.\nfunc (in *Pref) Set() error {\n\tdb := SqlDB()\n\tSqlInit(PREFS_TABLE)\n\n\tsql := `INSERT INTO prefs\n\t\t\t\t\t\t(value,user,room,broker,plugin,pkey)\n\t\t\tVALUES (?,?,?,?,?,?)\n\t\t\tON DUPLICATE KEY\n\t\t\tUPDATE value=?, user=?, room=?, broker=?, plugin=?, pkey=?`\n\n\tparams := []interface{}{\n\t\t&in.Value, &in.User, &in.Room, &in.Broker, &in.Plugin, &in.Key,\n\t\t&in.Value, &in.User, &in.Room, &in.Broker, &in.Plugin, &in.Key,\n\t}\n\n\t_, err := db.Exec(sql, params...)\n\tif err != nil {\n\t\tlog.Printf(\"Pref.Set() write failed: %s\", err)\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ Set writes the value and returns a new struct with the new value.\nfunc (in *Pref) Delete() error {\n\tdb := SqlDB()\n\tSqlInit(PREFS_TABLE)\n\n\tsql := `DELETE FROM prefs\n\t\t\tWHERE user=?\n\t\t\t AND room=?\n\t\t\t AND broker=?\n\t\t\t AND plugin=?\n\t\t\t AND pkey=?`\n\n\t\/\/ TODO: verify only one row was deleted\n\t_, err := db.Exec(sql, &in.User, &in.Room, &in.Broker, &in.Plugin, &in.Key)\n\tif err != nil {\n\t\tlog.Printf(\"Pref.Delete() write failed: %s\", err)\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ Find retrieves all preferences from the database that match any field in the\n\/\/ handle's fields.\n\/\/ Unlike Get(), empty string fields are not included in the (generated) query\n\/\/ so it can potentially match a lot of rows.\n\/\/ Returns an empty list and logs upon errors.\nfunc (p Pref) Find() Prefs {\n\tSqlInit(PREFS_TABLE)\n\n\tfields := make([]string, 0)\n\tparams := make([]interface{}, 0)\n\n\tif p.User != \"\" {\n\t\tfields = append(fields, \"user=?\")\n\t\tparams = append(params, p.User)\n\t}\n\n\tif p.Room != \"\" {\n\t\tfields = append(fields, \"room=?\")\n\t\tparams = append(params, p.Room)\n\t}\n\n\tif p.Broker != \"\" {\n\t\tfields = append(fields, \"broker=?\")\n\t\tparams = append(params, p.Broker)\n\t}\n\n\tif p.Plugin != \"\" {\n\t\tfields = append(fields, \"plugin=?\")\n\t\tparams = append(params, p.Plugin)\n\t}\n\n\tif p.Key != \"\" {\n\t\tfields = append(fields, \"pkey=?\")\n\t\tparams = append(params, p.Key)\n\t}\n\n\tq := bytes.NewBufferString(\"SELECT user,room,broker,plugin,pkey,value\\n\")\n\tq.WriteString(\"FROM prefs\\n\")\n\n\t\/\/ TODO: maybe it's silly to make it easy for Find() to get all preferences\n\t\/\/ but let's cross that bridge when we come to it\n\tif len(fields) > 0 {\n\t\tq.WriteString(\"\\nWHERE \")\n\t\t\/\/ might make sense to add a param to this func to make it easy to\n\t\t\/\/ switch this between AND\/OR for unions\/intersections\n\t\tq.WriteString(strings.Join(fields, \"\\n OR \"))\n\t}\n\n\t\/\/ TODO: add deterministic ordering at query time\n\n\tdb := SqlDB()\n\tout := make(Prefs, 0)\n\trows, err := db.Query(q.String(), params...)\n\tif err != nil {\n\t\tlog.Println(q.String())\n\t\tlog.Printf(\"Query failed: %s\", err)\n\t\treturn out\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\trow := Pref{}\n\t\terr = rows.Scan(&row.User, &row.Room, &row.Broker, &row.Plugin, &row.Key, &row.Value)\n\t\t\/\/ improbable in practice - follows previously mentioned conventions for errors\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Fetching a row failed: %s\\n\", err)\n\t\t\trow.Error = err\n\t\t\trow.Success = false\n\t\t\trow.Value = p.Default\n\t\t} else {\n\t\t\trow.Error = nil\n\t\t\trow.Success = true\n\t\t}\n\n\t\tout = append(out, &row)\n\t}\n\n\treturn out\n}\n\n\/\/ User filters the preference list by user, returning a new Prefs\n\/\/ e.g. uprefs = prefs.User(\"adent\")\nfunc (prefs Prefs) User(user string) Prefs {\n\tout := make(Prefs, 0)\n\n\tfor _, pref := range prefs {\n\t\tif pref.User == user {\n\t\t\tout = append(out, pref)\n\t\t}\n\t}\n\n\treturn out\n}\n\n\/\/ Room filters the preference list by room, returning a new Prefs\n\/\/ e.g. instprefs = prefs.Room(\"magrathea\").Plugin(\"uptime\").Broker(\"slack\")\nfunc (prefs Prefs) Room(room string) Prefs {\n\tout := make(Prefs, 0)\n\n\tfor _, pref := range prefs {\n\t\tif pref.Room == room {\n\t\t\tout = append(out, pref)\n\t\t}\n\t}\n\n\treturn out\n}\n\n\/\/ Broker filters the preference list by broker, returning a new Prefs\nfunc (prefs Prefs) Broker(broker string) Prefs {\n\tout := make(Prefs, 0)\n\n\tfor _, pref := range prefs {\n\t\tif pref.Broker == broker {\n\t\t\tout = append(out, pref)\n\t\t}\n\t}\n\n\treturn out\n}\n\n\/\/ Plugin filters the preference list by plugin, returning a new Prefs\nfunc (prefs Prefs) Plugin(plugin string) Prefs {\n\tout := make(Prefs, 0)\n\n\tfor _, pref := range prefs {\n\t\tif pref.Plugin == plugin {\n\t\t\tout = append(out, pref)\n\t\t}\n\t}\n\n\treturn out\n}\n\n\/\/ ready to hand off to e.g. hal.AsciiTable()\nfunc (prefs Prefs) Table() [][]string {\n\tout := make([][]string, 1)\n\tout[0] = []string{\"User\", \"Room\", \"Broker\", \"Plugin\", \"Key\", \"Value\"}\n\n\tfor _, pref := range prefs {\n\t\tm := []string{\n\t\t\tpref.User,\n\t\t\tpref.Room,\n\t\t\tpref.Broker,\n\t\t\tpref.Plugin,\n\t\t\tpref.Key,\n\t\t\tpref.Value,\n\t\t}\n\n\t\tout = append(out, m)\n\t}\n\n\treturn out\n}\n\nfunc (p *Pref) String() string {\n\treturn fmt.Sprintf(`Pref{\n\tUser: %q,\n\tRoom: %q,\n\tBroker: %q,\n\tPlugin: %q,\n\tKey: %q,\n\tValue: %q,\n\tDefault: %q,\n\tSuccess: %t,\n\tError: %v,\n}`, p.User, p.Room, p.Broker, p.Plugin, p.Key, p.Value, p.Default, p.Success, p.Error)\n\n}\n\nfunc (p *Prefs) String() string {\n\tdata := p.Table()\n\treturn AsciiTable(data[0], data[1:])\n}\nChange Prefs to []Pref for literals, add methods.package hal\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"log\"\n\t\"strings\"\n)\n\n\/\/ provides a persistent configuration store\n\n\/\/ Order of precendence for prefs:\n\/\/ user -> room -> broker -> plugin -> global -> default\n\n\/\/ PREFS_TABLE contains the SQL to create the prefs table\n\/\/ key field is called pkey because key is a reserved word\nconst PREFS_TABLE = `\nCREATE TABLE IF NOT EXISTS prefs (\n\t user VARCHAR(32) DEFAULT \"\",\n\t room VARCHAR(32) DEFAULT \"\",\n\t broker VARCHAR(32) DEFAULT \"\",\n\t plugin VARCHAR(32) DEFAULT \"\",\n\t pkey VARCHAR(32) NOT NULL,\n\t value TEXT,\n\t PRIMARY KEY(user, room, broker, plugin, pkey)\n)`\n\n\/*\n -- test data, will remove once there are automated tests\n INSERT INTO prefs (user,room,broker,plugin,pkey,value) VALUES (\"tobert\", \"\", \"\", \"\", \"foo\", \"user\");\n INSERT INTO prefs (user,room,broker,plugin,pkey,value) VALUES (\"tobert\", \"CORE\", \"\", \"\", \"foo\",\n \"user-room\");\n INSERT INTO prefs (user,room,broker,plugin,pkey,value) VALUES (\"tobert\", \"CORE\", \"slack\", \"\", \"foo\",\n \"user-room-broker\");\n INSERT INTO prefs (user,room,broker,plugin,pkey,value) VALUES (\"tobert\", \"CORE\", \"slack\", \"uptime\",\n \"foo\", \"user-room-broker-plugin\");\n INSERT INTO prefs (user,room,broker,plugin,pkey,value) VALUES (\"tobert\", \"\", \"slack\", \"uptime\", \"foo\",\n \"user-broker-plugin\");\n INSERT INTO prefs (user,room,broker,plugin,pkey,value) VALUES (\"tobert\", \"CORE\", \"\", \"uptime\",\n \"foo\", \"user-room-plugin\");\n INSERT INTO prefs (user,room,broker,plugin,pkey,value) VALUES (\"tobert\", \"\", \"\", \"uptime\", \"foo\",\n \"user-plugin\");\n*\/\n\n\/\/ !prefs list --scope plugin --plugin autoresponder\n\/\/ !prefs get --scope room --plugin autoresponder --room CORE --key timezone\n\/\/ !prefs set --scope user --plugin autoresponder --room CORE\n\n\/\/ Pref is a key\/value pair associated with a combination of user, plugin,\n\/\/ borker, or room.\ntype Pref struct {\n\tUser string\n\tPlugin string\n\tBroker string\n\tRoom string\n\tKey string\n\tValue string\n\tDefault string\n\tSuccess bool\n\tError error\n}\n\ntype Prefs []Pref\n\n\/\/ GetPref will retreive the most-specific preference from pref\n\/\/ storage using the parameters provided. This is a bit like pattern\n\/\/ matching. If no match is found, the provided default is returned.\n\/\/ TODO: explain this better\nfunc GetPref(user, broker, room, plugin, key, def string) Pref {\n\tpref := Pref{\n\t\tUser: user,\n\t\tRoom: room,\n\t\tBroker: broker,\n\t\tPlugin: plugin,\n\t\tKey: key,\n\t\tDefault: def,\n\t}\n\n\tup := pref.Get()\n\tif up.Success {\n\t\treturn up\n\t}\n\n\t\/\/ no match, return the default\n\tpref.Value = def\n\treturn pref\n}\n\n\/\/ SetPref sets a preference and is shorthand for Pref{}.Set().\nfunc SetPref(user, broker, room, plugin, key, value string) error {\n\tpref := Pref{\n\t\tUser: user,\n\t\tRoom: room,\n\t\tBroker: broker,\n\t\tPlugin: plugin,\n\t\tKey: key,\n\t\tValue: value,\n\t}\n\n\treturn pref.Set()\n}\n\n\/\/ GetPrefs retrieves a set of preferences from the database. The\n\/\/ settings are matched exactly on user,broker,room,plugin.\n\/\/ e.g. GetPrefs(\"\", \"\", \"\", \"uptime\") would get only records that\n\/\/ have user\/broker\/room set to the empty string and room\n\/\/ set to \"uptime\". A record with user \"pford\" and plugin \"uptime\"\n\/\/ would not be included.\nfunc GetPrefs(user, broker, room, plugin string) Prefs {\n\tpref := Pref{\n\t\tUser: user,\n\t\tBroker: broker,\n\t\tRoom: room,\n\t\tPlugin: plugin,\n\t}\n\treturn pref.get()\n}\n\n\/\/ FindPrefs gets all records that match any of the inputs that are\n\/\/ not empty strings. (hint: user=\"x\", broker=\"y\"; WHERE user=? OR broker=?)\nfunc FindPrefs(user, broker, room, plugin, key string) Prefs {\n\tpref := Pref{\n\t\tUser: user,\n\t\tBroker: broker,\n\t\tRoom: room,\n\t\tPlugin: plugin,\n\t\tKey: key,\n\t}\n\treturn pref.Find()\n}\n\n\/\/ Get retrieves a value from the database. If the database returns\n\/\/ an error, Success will be false and the Error field will be populated.\nfunc (in *Pref) Get() Pref {\n\tprefs := in.get()\n\n\tif len(prefs) == 1 {\n\t\treturn prefs[0]\n\t} else if len(prefs) > 1 {\n\t\tpanic(\"TOO MANY PREFS\")\n\t} else if len(prefs) == 0 {\n\t\tout := *in\n\t\t\/\/ only set success to false if there is also an error\n\t\t\/\/ queries with 0 rows are successful\n\t\tif out.Error != nil {\n\t\t\tout.Success = false\n\t\t} else {\n\t\t\tout.Success = true\n\t\t\tout.Value = out.Default\n\t\t}\n\t\treturn out\n\t}\n\n\tpanic(\"BUG: should be impossible to reach this point\")\n}\n\n\/\/ GetPrefs returns all preferences that match the fields set in the handle.\nfunc (in *Pref) GetPrefs() Prefs {\n\treturn in.get()\n}\n\nfunc (in *Pref) get() Prefs {\n\tSqlInit(PREFS_TABLE)\n\n\tsql := `SELECT user,room,broker,plugin,pkey,value\n\t FROM prefs\n\t WHERE user=?\n\t\t\t AND room=?\n\t\t\t AND broker=?\n\t\t\t AND plugin=?`\n\tparams := []interface{}{&in.User, &in.Room, &in.Broker, &in.Plugin}\n\n\t\/\/ only query by key if it's specified, otherwise get all keys for the selection\n\tif in.Key != \"\" {\n\t\tsql += \" AND pkey=?\"\n\t\tparams = append(params, &in.Key)\n\t}\n\n\tdb := SqlDB()\n\n\trows, err := db.Query(sql, params...)\n\tif err != nil {\n\t\tlog.Printf(\"Returning default due to SQL query failure: %s\", err)\n\t\treturn Prefs{}\n\t}\n\n\tdefer rows.Close()\n\n\tout := make(Prefs, 0)\n\n\tfor rows.Next() {\n\t\tp := *in\n\n\t\terr := rows.Scan(&p.User, &p.Room, &p.Broker, &p.Plugin, &p.Key, &p.Value)\n\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Returning default due to row iteration failure: %s\", err)\n\t\t\tp.Success = false\n\t\t\tp.Value = in.Default\n\t\t\tp.Error = err\n\t\t} else {\n\t\t\tp.Success = true\n\t\t\tp.Error = nil\n\t\t}\n\n\t\tout = append(out, p)\n\t}\n\n\treturn out\n}\n\n\/\/ Set writes the value and returns a new struct with the new value.\nfunc (in *Pref) Set() error {\n\tdb := SqlDB()\n\tSqlInit(PREFS_TABLE)\n\n\tsql := `INSERT INTO prefs\n\t\t\t\t\t\t(value,user,room,broker,plugin,pkey)\n\t\t\tVALUES (?,?,?,?,?,?)\n\t\t\tON DUPLICATE KEY\n\t\t\tUPDATE value=?, user=?, room=?, broker=?, plugin=?, pkey=?`\n\n\tparams := []interface{}{\n\t\t&in.Value, &in.User, &in.Room, &in.Broker, &in.Plugin, &in.Key,\n\t\t&in.Value, &in.User, &in.Room, &in.Broker, &in.Plugin, &in.Key,\n\t}\n\n\t_, err := db.Exec(sql, params...)\n\tif err != nil {\n\t\tlog.Printf(\"Pref.Set() write failed: %s\", err)\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ Set writes the value and returns a new struct with the new value.\nfunc (in *Pref) Delete() error {\n\tdb := SqlDB()\n\tSqlInit(PREFS_TABLE)\n\n\tsql := `DELETE FROM prefs\n\t\t\tWHERE user=?\n\t\t\t AND room=?\n\t\t\t AND broker=?\n\t\t\t AND plugin=?\n\t\t\t AND pkey=?`\n\n\t\/\/ TODO: verify only one row was deleted\n\t_, err := db.Exec(sql, &in.User, &in.Room, &in.Broker, &in.Plugin, &in.Key)\n\tif err != nil {\n\t\tlog.Printf(\"Pref.Delete() write failed: %s\", err)\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\n\/\/ Find retrieves all preferences from the database that match any field in the\n\/\/ handle's fields.\n\/\/ Unlike Get(), empty string fields are not included in the (generated) query\n\/\/ so it can potentially match a lot of rows.\n\/\/ Returns an empty list and logs upon errors.\nfunc (p Pref) Find() Prefs {\n\tSqlInit(PREFS_TABLE)\n\n\tfields := make([]string, 0)\n\tparams := make([]interface{}, 0)\n\n\tif p.User != \"\" {\n\t\tfields = append(fields, \"user=?\")\n\t\tparams = append(params, p.User)\n\t}\n\n\tif p.Room != \"\" {\n\t\tfields = append(fields, \"room=?\")\n\t\tparams = append(params, p.Room)\n\t}\n\n\tif p.Broker != \"\" {\n\t\tfields = append(fields, \"broker=?\")\n\t\tparams = append(params, p.Broker)\n\t}\n\n\tif p.Plugin != \"\" {\n\t\tfields = append(fields, \"plugin=?\")\n\t\tparams = append(params, p.Plugin)\n\t}\n\n\tif p.Key != \"\" {\n\t\tfields = append(fields, \"pkey=?\")\n\t\tparams = append(params, p.Key)\n\t}\n\n\tq := bytes.NewBufferString(\"SELECT user,room,broker,plugin,pkey,value\\n\")\n\tq.WriteString(\"FROM prefs\\n\")\n\n\t\/\/ TODO: maybe it's silly to make it easy for Find() to get all preferences\n\t\/\/ but let's cross that bridge when we come to it\n\tif len(fields) > 0 {\n\t\tq.WriteString(\"\\nWHERE \")\n\t\t\/\/ might make sense to add a param to this func to make it easy to\n\t\t\/\/ switch this between AND\/OR for unions\/intersections\n\t\tq.WriteString(strings.Join(fields, \"\\n OR \"))\n\t}\n\n\t\/\/ TODO: add deterministic ordering at query time\n\n\tdb := SqlDB()\n\tout := make(Prefs, 0)\n\trows, err := db.Query(q.String(), params...)\n\tif err != nil {\n\t\tlog.Println(q.String())\n\t\tlog.Printf(\"Query failed: %s\", err)\n\t\treturn out\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\trow := Pref{}\n\t\terr = rows.Scan(&row.User, &row.Room, &row.Broker, &row.Plugin, &row.Key, &row.Value)\n\t\t\/\/ improbable in practice - follows previously mentioned conventions for errors\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Fetching a row failed: %s\\n\", err)\n\t\t\trow.Error = err\n\t\t\trow.Success = false\n\t\t\trow.Value = p.Default\n\t\t} else {\n\t\t\trow.Error = nil\n\t\t\trow.Success = true\n\t\t}\n\n\t\tout = append(out, row)\n\t}\n\n\treturn out\n}\n\n\/\/ Clone returns a full\/deep copy of the Prefs list.\nfunc (prefs Prefs) Clone() Prefs {\n\tout := make(Prefs, len(prefs))\n\n\tfor i, pref := range prefs {\n\t\tcopy := pref\n\t\tout[i] = copy\n\t}\n\n\treturn out\n}\n\n\/\/ User filters the preference list by user, returning a new Prefs\n\/\/ e.g. uprefs = prefs.User(\"adent\")\nfunc (prefs Prefs) User(user string) Prefs {\n\tout := make(Prefs, 0)\n\n\tfor _, pref := range prefs {\n\t\tif pref.User == user {\n\t\t\tout = append(out, pref)\n\t\t}\n\t}\n\n\treturn out\n}\n\n\/\/ Room filters the preference list by room, returning a new Prefs\n\/\/ e.g. instprefs = prefs.Room(\"magrathea\").Plugin(\"uptime\").Broker(\"slack\")\nfunc (prefs Prefs) Room(room string) Prefs {\n\tout := make(Prefs, 0)\n\n\tfor _, pref := range prefs {\n\t\tif pref.Room == room {\n\t\t\tout = append(out, pref)\n\t\t}\n\t}\n\n\treturn out\n}\n\n\/\/ Broker filters the preference list by broker, returning a new Prefs\nfunc (prefs Prefs) Broker(broker string) Prefs {\n\tout := make(Prefs, 0)\n\n\tfor _, pref := range prefs {\n\t\tif pref.Broker == broker {\n\t\t\tout = append(out, pref)\n\t\t}\n\t}\n\n\treturn out\n}\n\n\/\/ Plugin filters the preference list by plugin, returning a new Prefs\nfunc (prefs Prefs) Plugin(plugin string) Prefs {\n\tout := make(Prefs, 0)\n\n\tfor _, pref := range prefs {\n\t\tif pref.Plugin == plugin {\n\t\t\tout = append(out, pref)\n\t\t}\n\t}\n\n\treturn out\n}\n\n\/\/ Key filters the preference list by key, returning a new Prefs\nfunc (prefs Prefs) Key(key string) Prefs {\n\tout := make(Prefs, 0)\n\n\tfor _, pref := range prefs {\n\t\tif pref.Key == key {\n\t\t\tout = append(out, pref)\n\t\t}\n\t}\n\n\treturn out\n}\n\n\/\/ ready to hand off to e.g. hal.AsciiTable()\nfunc (prefs Prefs) Table() [][]string {\n\tout := make([][]string, 1)\n\tout[0] = []string{\"User\", \"Room\", \"Broker\", \"Plugin\", \"Key\", \"Value\"}\n\n\tfor _, pref := range prefs {\n\t\tm := []string{\n\t\t\tpref.User,\n\t\t\tpref.Room,\n\t\t\tpref.Broker,\n\t\t\tpref.Plugin,\n\t\t\tpref.Key,\n\t\t\tpref.Value,\n\t\t}\n\n\t\tout = append(out, m)\n\t}\n\n\treturn out\n}\n\nfunc (p *Pref) String() string {\n\treturn fmt.Sprintf(`Pref{\n\tUser: %q,\n\tRoom: %q,\n\tBroker: %q,\n\tPlugin: %q,\n\tKey: %q,\n\tValue: %q,\n\tDefault: %q,\n\tSuccess: %t,\n\tError: %v,\n}`, p.User, p.Room, p.Broker, p.Plugin, p.Key, p.Value, p.Default, p.Success, p.Error)\n\n}\n\nfunc (p *Prefs) String() string {\n\tdata := p.Table()\n\treturn AsciiTable(data[0], data[1:])\n}\n<|endoftext|>"} {"text":"package gitmedia\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/github\/git-media\/git\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n)\n\nvar (\n\tvalueRegexp = regexp.MustCompile(\"\\\\Agit[\\\\-\\\\s]media\")\n\tprePushHook = []byte(\"#!\/bin\/sh\\ngit media push --stdin $*\\n\")\n\tNotInARepositoryError = errors.New(\"Not in a repository\")\n)\n\ntype HookExists struct {\n\tName string\n\tPath string\n}\n\nfunc (e *HookExists) Error() string {\n\treturn fmt.Sprintf(\"Hook already exists: %s\", e.Name)\n}\n\nfunc InstallHooks(force bool) error {\n\tif !InRepo() {\n\t\treturn NotInARepositoryError\n\t}\n\n\tif err := os.MkdirAll(filepath.Join(LocalGitDir, \"hooks\"), 0755); err != nil {\n\t\treturn err\n\t}\n\n\thookPath := filepath.Join(LocalGitDir, \"hooks\", \"pre-push\")\n\tif _, err := os.Stat(hookPath); err == nil && !force {\n\t\treturn &HookExists{\"pre-push\", hookPath}\n\t} else {\n\t\treturn ioutil.WriteFile(hookPath, prePushHook, 0755)\n\t}\n}\n\nfunc InstallFilters() error {\n\tvar err error\n\terr = setFilter(\"clean\")\n\tif err == nil {\n\t\terr = setFilter(\"smudge\")\n\t}\n\tif err == nil {\n\t\terr = requireFilters()\n\t}\n\treturn err\n}\n\nfunc setFilter(filterName string) error {\n\tkey := fmt.Sprintf(\"filter.media.%s\", filterName)\n\tvalue := fmt.Sprintf(\"git hawser %s %%f\", filterName)\n\n\texisting := git.Config.Find(key)\n\tif shouldReset(existing) {\n\t\tgit.Config.UnsetGlobal(key)\n\t\tgit.Config.SetGlobal(key, value)\n\t} else if existing != value {\n\t\treturn fmt.Errorf(\"The %s filter should be \\\"%s\\\" but is \\\"%s\\\"\", filterName, value, existing)\n\t}\n\n\treturn nil\n}\n\nfunc requireFilters() error {\n\tkey := \"filter.media.required\"\n\tvalue := \"true\"\n\n\texisting := git.Config.Find(key)\n\tif shouldReset(existing) {\n\t\tgit.Config.UnsetGlobal(key)\n\t\tgit.Config.SetGlobal(key, value)\n\t} else if existing != value {\n\t\treturn errors.New(\"Media filters should be required but are not.\")\n\t}\n\n\treturn nil\n}\n\nfunc shouldReset(value string) bool {\n\tif len(value) == 0 {\n\t\treturn true\n\t}\n\treturn valueRegexp.MatchString(value)\n}\nUpdate pre-push hookpackage gitmedia\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"github.com\/github\/git-media\/git\"\n\t\"io\/ioutil\"\n\t\"os\"\n\t\"path\/filepath\"\n\t\"regexp\"\n)\n\nvar (\n\tvalueRegexp = regexp.MustCompile(\"\\\\Agit[\\\\-\\\\s]media\")\n\tprePushHook = []byte(\"#!\/bin\/sh\\ngit hawser push --stdin $*\\n\")\n\tNotInARepositoryError = errors.New(\"Not in a repository\")\n)\n\ntype HookExists struct {\n\tName string\n\tPath string\n}\n\nfunc (e *HookExists) Error() string {\n\treturn fmt.Sprintf(\"Hook already exists: %s\", e.Name)\n}\n\nfunc InstallHooks(force bool) error {\n\tif !InRepo() {\n\t\treturn NotInARepositoryError\n\t}\n\n\tif err := os.MkdirAll(filepath.Join(LocalGitDir, \"hooks\"), 0755); err != nil {\n\t\treturn err\n\t}\n\n\thookPath := filepath.Join(LocalGitDir, \"hooks\", \"pre-push\")\n\tif _, err := os.Stat(hookPath); err == nil && !force {\n\t\treturn &HookExists{\"pre-push\", hookPath}\n\t} else {\n\t\treturn ioutil.WriteFile(hookPath, prePushHook, 0755)\n\t}\n}\n\nfunc InstallFilters() error {\n\tvar err error\n\terr = setFilter(\"clean\")\n\tif err == nil {\n\t\terr = setFilter(\"smudge\")\n\t}\n\tif err == nil {\n\t\terr = requireFilters()\n\t}\n\treturn err\n}\n\nfunc setFilter(filterName string) error {\n\tkey := fmt.Sprintf(\"filter.media.%s\", filterName)\n\tvalue := fmt.Sprintf(\"git hawser %s %%f\", filterName)\n\n\texisting := git.Config.Find(key)\n\tif shouldReset(existing) {\n\t\tgit.Config.UnsetGlobal(key)\n\t\tgit.Config.SetGlobal(key, value)\n\t} else if existing != value {\n\t\treturn fmt.Errorf(\"The %s filter should be \\\"%s\\\" but is \\\"%s\\\"\", filterName, value, existing)\n\t}\n\n\treturn nil\n}\n\nfunc requireFilters() error {\n\tkey := \"filter.media.required\"\n\tvalue := \"true\"\n\n\texisting := git.Config.Find(key)\n\tif shouldReset(existing) {\n\t\tgit.Config.UnsetGlobal(key)\n\t\tgit.Config.SetGlobal(key, value)\n\t} else if existing != value {\n\t\treturn errors.New(\"Media filters should be required but are not.\")\n\t}\n\n\treturn nil\n}\n\nfunc shouldReset(value string) bool {\n\tif len(value) == 0 {\n\t\treturn true\n\t}\n\treturn valueRegexp.MatchString(value)\n}\n<|endoftext|>"} {"text":"package sql\n\nimport (\n\t\"bufio\"\n\t\"database\/sql\"\n\t\"fmt\"\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/go-sql-driver\/mysql\"\n)\n\nvar (\n\ttestCfg *mysql.Config\n\ttestDB *sql.DB\n)\n\nfunc TestMain(m *testing.M) {\n\tfmt.Println(os.Getenv(\"SQLFLOW_TEST_DB\"))\n\tswitch os.Getenv(\"SQLFLOW_TEST_DB\") {\n\tcase \"sqlite3\":\n\t\ttestDB, testCfg = openSQLite3()\n\t\tfmt.Println(\"opened sqlite3\")\n\t\tdefer testDB.Close()\n\tcase \"mysql\":\n\t\ttestDB, testCfg = openMySQL()\n\t\tdefer testDB.Close()\n\tdefault:\n\t\tlog.Fatalf(\"Unrecognized environment variable value SQLFLOW_TEST_DB==%s\", os.Getenv(\"SQLFLOW_TEST_DB\"))\n\t}\n\tfmt.Println(\"opened db\")\n\tpopularize(testDB, \"testdata\/iris.sql\")\n\tpopularize(testDB, \"testdata\/churn.sql\")\n\tfmt.Println(\"popularized\")\n\tos.Exit(m.Run())\n}\n\nfunc openSQLite3() (*sql.DB, *mysql.Config) {\n\tn := fmt.Sprintf(\"%d%d\", time.Now().Unix(), os.Getpid())\n\tdb, e := sql.Open(\"sqlite3\", n)\n\tif e != nil {\n\t\tlog.Fatalf(\"TestMain cannot connect to SQLite3: %q.\", e)\n\t}\n\treturn db, nil\n}\n\nfunc openMySQL() (*sql.DB, *mysql.Config) {\n\tcfg := &mysql.Config{\n\t\tUser: \"root\",\n\t\tPasswd: \"root\",\n\t\tAddr: \"localhost:3306\",\n\t}\n\tdb, e := sql.Open(\"mysql\", cfg.FormatDSN())\n\tif e != nil {\n\t\tlog.Fatalf(\"TestMain cannot connect to MySQL: %q.\\n\"+\n\t\t\t\"Please run MySQL server as in example\/datasets\/README.md.\", e)\n\t}\n\treturn db, cfg\n}\n\n\/\/ popularize reads SQL statements from the file named sqlfile in the\n\/\/ .\/testdata directory, and runs each SQL statement with db.\nfunc popularize(db *sql.DB, sqlfile string) error {\n\tf, e := os.Open(sqlfile)\n\tif e != nil {\n\t\treturn e\n\t}\n\tdefer f.Close()\n\n\tonSemicolon := func(data []byte, atEOF bool) (advance int, token []byte, err error) {\n\t\tfor i := 0; i < len(data); i++ {\n\t\t\tif data[i] == ';' {\n\t\t\t\treturn i + 1, data[:i], nil\n\t\t\t}\n\t\t}\n\t\treturn 0, nil, nil\n\t}\n\n\tscanner := bufio.NewScanner(f)\n\tscanner.Split(onSemicolon)\n\n\tfor scanner.Scan() {\n\t\t_, e := db.Exec(scanner.Text())\n\t\tif e != nil {\n\t\t\treturn e\n\t\t}\n\t}\n\treturn scanner.Err()\n}\nstashpackage sql\n\nimport (\n\t\"bufio\"\n\t\"database\/sql\"\n\t\"fmt\"\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com\/go-sql-driver\/mysql\"\n\t_ \"github.com\/mattn\/go-sqlite3\"\n)\n\nvar (\n\ttestCfg *mysql.Config\n\ttestDB *sql.DB\n)\n\nfunc TestMain(m *testing.M) {\n\tdbms := os.Getenv(\"SQLFLOW_TEST_DB\")\n\tif dbms == \"\" {\n\t\tdbms = \"sqlite3\"\n\t}\n\n\tvar e error\n\tswitch dbms {\n\tcase \"sqlite3\":\n\t\ttestDB, testCfg, e = openSQLite3()\n\t\tdefer testDB.Close()\n\tcase \"mysql\":\n\t\ttestDB, testCfg, e = openMySQL()\n\t\tdefer testDB.Close()\n\tdefault:\n\t\te = fmt.Errorf(\"Unrecognized environment variable SQLFLOW_TEST_DB %s\\n\", dbms)\n\t}\n\tassertNoErr(e)\n\n\tassertNoErr(popularize(testDB, \"testdata\/iris.sql\"))\n\tassertNoErr(popularize(testDB, \"testdata\/churn.sql\"))\n\n\tos.Exit(m.Run())\n}\n\n\/\/ assertNoError prints the error if there is any in TestMain, which\n\/\/ log doesn't work.\nfunc assertNoErr(e error) {\n\tif e != nil {\n\t\tfmt.Println(e)\n\t\tos.Exit(-1)\n\t}\n}\n\nfunc openSQLite3() (*sql.DB, *mysql.Config, error) {\n\tn := fmt.Sprintf(\"%d%d\", time.Now().Unix(), os.Getpid())\n\tdb, e := sql.Open(\"sqlite3\", n)\n\treturn db, nil, e\n}\n\nfunc openMySQL() (*sql.DB, *mysql.Config, error) {\n\tcfg := &mysql.Config{\n\t\tUser: \"root\",\n\t\tPasswd: \"root\",\n\t\tAddr: \"localhost:3306\",\n\t}\n\tdb, e := sql.Open(\"mysql\", cfg.FormatDSN())\n\treturn db, cfg, e\n}\n\n\/\/ popularize reads SQL statements from the file named sqlfile in the\n\/\/ .\/testdata directory, and runs each SQL statement with db.\nfunc popularize(db *sql.DB, sqlfile string) error {\n\tf, e := os.Open(sqlfile)\n\tif e != nil {\n\t\treturn e\n\t}\n\tdefer f.Close()\n\n\tonSemicolon := func(data []byte, atEOF bool) (advance int, token []byte, err error) {\n\t\tfor i := 0; i < len(data); i++ {\n\t\t\tif data[i] == ';' {\n\t\t\t\treturn i + 1, data[:i], nil\n\t\t\t}\n\t\t}\n\t\treturn 0, nil, nil\n\t}\n\n\tscanner := bufio.NewScanner(f)\n\tscanner.Split(onSemicolon)\n\n\tfor scanner.Scan() {\n\t\t_, e := db.Exec(scanner.Text())\n\t\tif e != nil {\n\t\t\treturn e\n\t\t}\n\t}\n\treturn scanner.Err()\n}\n<|endoftext|>"} {"text":"package utp\n\nimport (\n\t\"bytes\"\n\t\"net\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestSharedConnRecvPacket(t *testing.T) {\n\taddr, err := ResolveAddr(\"utp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tc, err := getSharedBaseConn(\"utp\", addr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer c.Close()\n\n\tuaddr, err := net.ResolveUDPAddr(\"udp\", c.LocalAddr().String())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tuc, err := net.DialUDP(\"udp\", nil, uaddr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer uc.Close()\n\n\tch := make(chan *packet)\n\tc.Register(5, ch)\n\n\tfor i := 0; i < 100; i++ {\n\t\tp := &packet{header: header{typ: stData, ver: version, id: 5}}\n\t\tpayload, err := p.MarshalBinary()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tgo func() {\n\t\t\tuc.Write(payload)\n\t\t}()\n\t\t<-ch\n\t}\n\n\tc.Unregister(5)\n}\n\nfunc TestSharedConnSendPacket(t *testing.T) {\n\taddr, err := ResolveAddr(\"utp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tc, err := getSharedBaseConn(\"utp\", addr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer c.Close()\n\n\tuaddr, err := net.ResolveUDPAddr(\"udp\", c.LocalAddr().String())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tuc, err := net.DialUDP(\"udp\", nil, uaddr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer uc.Close()\n\n\tfor i := 0; i < 100; i++ {\n\t\taddr, err := net.ResolveUDPAddr(\"udp\", uc.LocalAddr().String())\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tp := &packet{header: header{typ: stData, ver: version, id: 5}, addr: addr}\n\t\tpayload, err := p.MarshalBinary()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tc.Send(p)\n\n\t\tvar b [256]byte\n\t\tl, err := uc.Read(b[:])\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tif !bytes.Equal(b[:l], payload) {\n\t\t\tt.Errorf(\"expected packet of %v; got %v\", payload, b[:l])\n\t\t}\n\t}\n}\n\nfunc TestSharedConnRecvSyn(t *testing.T) {\n\taddr, err := ResolveAddr(\"utp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tc, err := getSharedBaseConn(\"utp\", addr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer c.Close()\n\n\tuaddr, err := net.ResolveUDPAddr(\"udp\", c.LocalAddr().String())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tuc, err := net.DialUDP(\"udp\", nil, uaddr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer uc.Close()\n\n\tfor i := 0; i < 100; i++ {\n\t\tp := &packet{header: header{typ: stSyn, ver: version}}\n\t\tpayload, err := p.MarshalBinary()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tgo func() {\n\t\t\tuc.Write(payload)\n\t\t}()\n\t\tp, err = c.RecvSyn(time.Duration(0))\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tif p == nil {\n\t\t\tt.Errorf(\"packet must not be nil\")\n\t\t}\n\t}\n}\n\nfunc TestSharedConnRecvOutOfBound(t *testing.T) {\n\taddr, err := ResolveAddr(\"utp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tc, err := getSharedBaseConn(\"utp\", addr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer c.Close()\n\n\tuaddr, err := net.ResolveUDPAddr(\"udp\", c.LocalAddr().String())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tuc, err := net.DialUDP(\"udp\", nil, uaddr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer uc.Close()\n\n\tfor i := 0; i < 100; i++ {\n\t\tpayload := []byte(\"Hello\")\n\t\tgo func() {\n\t\t\tuc.Write(payload)\n\t\t}()\n\t\tvar b [256]byte\n\t\tl, _, err := c.ReadFrom(b[:])\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tif !bytes.Equal(payload, b[:l]) {\n\t\t\tt.Errorf(\"expected packet of %v; got %v\", payload, b[:l])\n\t\t}\n\t}\n}\n\nfunc TestSharedConnSendOutOfBound(t *testing.T) {\n\taddr, err := ResolveAddr(\"utp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tc, err := getSharedBaseConn(\"utp\", addr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer c.Close()\n\n\tuaddr, err := net.ResolveUDPAddr(\"udp\", c.LocalAddr().String())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tuc, err := net.DialUDP(\"udp\", nil, uaddr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer uc.Close()\n\n\tfor i := 0; i < 100; i++ {\n\t\taddr, err := net.ResolveUDPAddr(\"udp\", uc.LocalAddr().String())\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tpayload := []byte(\"Hello\")\n\t\t_, err = c.WriteTo(payload, addr)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tvar b [256]byte\n\t\tl, err := uc.Read(b[:])\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tif !bytes.Equal(payload, b[:l]) {\n\t\t\tt.Errorf(\"expected packet of %v; got %v\", payload, b[:l])\n\t\t}\n\t}\n}\n\nfunc TestSharedConnReferenceCount(t *testing.T) {\n\taddr, err := ResolveAddr(\"utp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tc, err := getSharedBaseConn(\"utp\", addr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer c.Close()\n\n\tvar w sync.WaitGroup\n\n\tc.Register(-1, nil)\n\n\tfor i := 0; i < 5; i++ {\n\t\tw.Add(1)\n\t\tgo func(i int) {\n\t\t\tdefer w.Done()\n\t\t\tc.Register(int32(i), make(chan *packet))\n\t\t}(i)\n\t}\n\n\tw.Wait()\n\tfor i := 0; i < 5; i++ {\n\t\tw.Add(1)\n\t\tgo func(i int) {\n\t\t\tdefer w.Done()\n\t\t\tc.Unregister(int32(i))\n\t\t}(i)\n\t}\n\n\tw.Wait()\n\tc.Unregister(-1)\n\tc.Close()\n\n\tc = baseConnMap[addr.String()]\n\tif c != nil {\n\t\tt.Errorf(\"baseConn should be released\", c.ref)\n\t}\n}\n\nfunc TestSharedConnClose(t *testing.T) {\n\taddr, err := ResolveAddr(\"utp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tc, err := getSharedBaseConn(\"utp\", addr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer c.Close()\n\n\tfor i := 0; i < 5; i++ {\n\t\tc.Close()\n\t}\n\n\tvar b [256]byte\n\t_, _, err = c.ReadFrom(b[:])\n\tif err == nil {\n\t\tt.Fatal(\"ReadFrom should fail\")\n\t}\n\n\tuaddr, err := net.ResolveUDPAddr(\"udp\", c.LocalAddr().String())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tuc, err := net.DialUDP(\"udp\", nil, uaddr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer uc.Close()\n\n\tpayload := []byte(\"Hello\")\n\t_, err = c.WriteTo(payload, uc.LocalAddr())\n\tif err == nil {\n\t\tt.Fatal(\"WriteTo should fail\")\n\t}\n}\nFix typo in testpackage utp\n\nimport (\n\t\"bytes\"\n\t\"net\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestSharedConnRecvPacket(t *testing.T) {\n\taddr, err := ResolveAddr(\"utp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tc, err := getSharedBaseConn(\"utp\", addr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer c.Close()\n\n\tuaddr, err := net.ResolveUDPAddr(\"udp\", c.LocalAddr().String())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tuc, err := net.DialUDP(\"udp\", nil, uaddr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer uc.Close()\n\n\tch := make(chan *packet)\n\tc.Register(5, ch)\n\n\tfor i := 0; i < 100; i++ {\n\t\tp := &packet{header: header{typ: stData, ver: version, id: 5}}\n\t\tpayload, err := p.MarshalBinary()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tgo func() {\n\t\t\tuc.Write(payload)\n\t\t}()\n\t\t<-ch\n\t}\n\n\tc.Unregister(5)\n}\n\nfunc TestSharedConnSendPacket(t *testing.T) {\n\taddr, err := ResolveAddr(\"utp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tc, err := getSharedBaseConn(\"utp\", addr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer c.Close()\n\n\tuaddr, err := net.ResolveUDPAddr(\"udp\", c.LocalAddr().String())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tuc, err := net.DialUDP(\"udp\", nil, uaddr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer uc.Close()\n\n\tfor i := 0; i < 100; i++ {\n\t\taddr, err := net.ResolveUDPAddr(\"udp\", uc.LocalAddr().String())\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tp := &packet{header: header{typ: stData, ver: version, id: 5}, addr: addr}\n\t\tpayload, err := p.MarshalBinary()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tc.Send(p)\n\n\t\tvar b [256]byte\n\t\tl, err := uc.Read(b[:])\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tif !bytes.Equal(b[:l], payload) {\n\t\t\tt.Errorf(\"expected packet of %v; got %v\", payload, b[:l])\n\t\t}\n\t}\n}\n\nfunc TestSharedConnRecvSyn(t *testing.T) {\n\taddr, err := ResolveAddr(\"utp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tc, err := getSharedBaseConn(\"utp\", addr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer c.Close()\n\n\tuaddr, err := net.ResolveUDPAddr(\"udp\", c.LocalAddr().String())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tuc, err := net.DialUDP(\"udp\", nil, uaddr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer uc.Close()\n\n\tfor i := 0; i < 100; i++ {\n\t\tp := &packet{header: header{typ: stSyn, ver: version}}\n\t\tpayload, err := p.MarshalBinary()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tgo func() {\n\t\t\tuc.Write(payload)\n\t\t}()\n\t\tp, err = c.RecvSyn(time.Duration(0))\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tif p == nil {\n\t\t\tt.Errorf(\"packet must not be nil\")\n\t\t}\n\t}\n}\n\nfunc TestSharedConnRecvOutOfBound(t *testing.T) {\n\taddr, err := ResolveAddr(\"utp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tc, err := getSharedBaseConn(\"utp\", addr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer c.Close()\n\n\tuaddr, err := net.ResolveUDPAddr(\"udp\", c.LocalAddr().String())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tuc, err := net.DialUDP(\"udp\", nil, uaddr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer uc.Close()\n\n\tfor i := 0; i < 100; i++ {\n\t\tpayload := []byte(\"Hello\")\n\t\tgo func() {\n\t\t\tuc.Write(payload)\n\t\t}()\n\t\tvar b [256]byte\n\t\tl, _, err := c.ReadFrom(b[:])\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tif !bytes.Equal(payload, b[:l]) {\n\t\t\tt.Errorf(\"expected packet of %v; got %v\", payload, b[:l])\n\t\t}\n\t}\n}\n\nfunc TestSharedConnSendOutOfBound(t *testing.T) {\n\taddr, err := ResolveAddr(\"utp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tc, err := getSharedBaseConn(\"utp\", addr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer c.Close()\n\n\tuaddr, err := net.ResolveUDPAddr(\"udp\", c.LocalAddr().String())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tuc, err := net.DialUDP(\"udp\", nil, uaddr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer uc.Close()\n\n\tfor i := 0; i < 100; i++ {\n\t\taddr, err := net.ResolveUDPAddr(\"udp\", uc.LocalAddr().String())\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tpayload := []byte(\"Hello\")\n\t\t_, err = c.WriteTo(payload, addr)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tvar b [256]byte\n\t\tl, err := uc.Read(b[:])\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tif !bytes.Equal(payload, b[:l]) {\n\t\t\tt.Errorf(\"expected packet of %v; got %v\", payload, b[:l])\n\t\t}\n\t}\n}\n\nfunc TestSharedConnReferenceCount(t *testing.T) {\n\taddr, err := ResolveAddr(\"utp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tc, err := getSharedBaseConn(\"utp\", addr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer c.Close()\n\n\tvar w sync.WaitGroup\n\n\tc.Register(-1, nil)\n\n\tfor i := 0; i < 5; i++ {\n\t\tw.Add(1)\n\t\tgo func(i int) {\n\t\t\tdefer w.Done()\n\t\t\tc.Register(int32(i), make(chan *packet))\n\t\t}(i)\n\t}\n\n\tw.Wait()\n\tfor i := 0; i < 5; i++ {\n\t\tw.Add(1)\n\t\tgo func(i int) {\n\t\t\tdefer w.Done()\n\t\t\tc.Unregister(int32(i))\n\t\t}(i)\n\t}\n\n\tw.Wait()\n\tc.Unregister(-1)\n\tc.Close()\n\n\tc = baseConnMap[addr.String()]\n\tif c != nil {\n\t\tt.Errorf(\"baseConn should be released: %v\", c.ref)\n\t}\n}\n\nfunc TestSharedConnClose(t *testing.T) {\n\taddr, err := ResolveAddr(\"utp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tc, err := getSharedBaseConn(\"utp\", addr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer c.Close()\n\n\tfor i := 0; i < 5; i++ {\n\t\tc.Close()\n\t}\n\n\tvar b [256]byte\n\t_, _, err = c.ReadFrom(b[:])\n\tif err == nil {\n\t\tt.Fatal(\"ReadFrom should fail\")\n\t}\n\n\tuaddr, err := net.ResolveUDPAddr(\"udp\", c.LocalAddr().String())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tuc, err := net.DialUDP(\"udp\", nil, uaddr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer uc.Close()\n\n\tpayload := []byte(\"Hello\")\n\t_, err = c.WriteTo(payload, uc.LocalAddr())\n\tif err == nil {\n\t\tt.Fatal(\"WriteTo should fail\")\n\t}\n}\n<|endoftext|>"} {"text":"\/\/An easy way to convert BBCode to HTML with Go.\npackage bbConvert\n\nimport(\n \"strings\"\n)\n\nvar(\n classes string\n styleness string\n)\n\n\/\/Takes in a string slice (with bbcode) and converts it to proper HTML as a single string\n\/\/If pWrap == true then each part of the slice is surrounded in paragraph tags\n\/\/If pWrap == true and it finds a list, it will wrap the list in paragraph tags\nfunc Convert(strs []string, pWrap bool) string{\n parsedStrs := make([]string,0)\n for i:= 0;i\"\n tmp += bbConv(v) + \"<\/p>\"\n }else{\n tmp = bbConv(v)\n }\n out += tmp\n }\n return out\n}\n\n\/\/If pWrap == true, then the paragraphs will have this class\n\/\/Can be called multiple times to add multiple classes\nfunc AddParagraphClass(class string){\n class = strings.TrimSpace(class)\n classes += \" \" + class\n classes = strings.TrimSpace(classes)\n}\n\n\/\/Removes any classes set for pWrap\nfunc ClearParagraphClasses(){\n classes = \"\"\n}\n\n\/\/Removes any paragraph style set for pWrap\nfunc ClearParagraphStyle(){\n styleness = \"\"\n}\n\n\/\/If pWrap == true then the paragraph will have this in the style= parameter\n\/\/Can be called multiple times to add multiple styles\n\/\/Can be used with the style ending in a semicolon or not\nfunc AddStyle(style string){\n style = strings.TrimSpace(style)\n if strings.HasSuffix(style,\";\"){\n styleness += style\n }else{\n styleness += style + \";\"\n }\n}\n\nfunc bbConv(str string) string{\n for i:=0;i0;i--{\n if str[i:i+2]==\"[\/\"{\n tmp = str[i:]\n end = str[i+2:len(str)-1]\n break;\n }\n }\n if strings.ToLower(beg) != strings.ToLower(end){\n return str\n }\n for i,v := range str{\n if v ==']'{\n beg = str[1:i]\n break\n }\n }\n if strings.HasPrefix(tmp,\"[\/\") && strings.HasSuffix(tmp,\"]\") && !isBBTag(tmp[2:len(tmp)-1]){\n return str\n }\n str = bbToTag(str[len(beg)+2:len(str)-len(tmp)],beg)\n return str\n}\n\nfunc isBBTag(str string) bool{\n str = strings.ToLower(str)\n tf := str==\"b\" ||str==\"i\" ||str==\"u\" ||str==\"s\" ||str==\"url\" ||str==\"img\" ||str==\"quote\" ||str==\"style\" ||str==\"color\" ||str==\"youtube\" ||str==\"ol\" ||str==\"ul\"\n return tf\n}\n\nfunc bbToTag(in,bb string) string{\n lwrbb := strings.ToLower(bb)\n var str string\n if lwrbb==\"img\"{\n str = \"\"\n }else if strings.HasPrefix(lwrbb,\"img\"){\n tagness := \"\"\n style := make(map[string]string)\n style[\"float\"]=\"left\"\n style[\"width\"]=\"20%\"\n other := make(map[string]string)\n pos := make(map[string]int)\n if strings.Contains(lwrbb,\"alt=\\\"\")||strings.Contains(lwrbb,\"alt='\"){\n pos[\"alt\"]=strings.Index(lwrbb,\"alt=\")\n for i:=strings.Index(bb,\"alt=\")+5;i pos[\"altEnd\"]) && (pos[\"titleEnd\"]==0 || strings.LastIndex(lwrbb,\"height=\") > pos[\"titleEnd\"]){\n var sz string\n for i:=strings.LastIndex(lwrbb,\"height=\")+7;i pos[\"altEnd\"]) && (pos[\"titleEnd\"] ==0 || strings.LastIndex(lwrbb,\"width=\") > pos[\"titleEnd\"]){\n var sz string\n for i:=strings.LastIndex(lwrbb,\"width=\")+7;i pos[\"altEnd\"]) && (pos[\"titleEnd\"]==0 || strings.LastIndex(lwrbb,\"left\") > pos[\"titleEnd\"])){\n style[\"float\"]=\"left\"\n }\n }else if strings.Contains(lwrbb,\"right\"){\n if ((pos[\"alt\"]==0 || strings.Index(lwrbb,\"right\") < pos[\"alt\"]) && (pos[\"title\"]==0 || strings.Index(lwrbb,\"right\") < pos[\"title\"])) || ((pos[\"altEnd\"]==0 || strings.LastIndex(lwrbb,\"right\") > pos[\"altEnd\"]) && (pos[\"titleEnd\"]==0 || strings.LastIndex(lwrbb,\"right\") > pos[\"titleEnd\"])){\n style[\"float\"]=\"right\"\n }\n }\n tagness = \" style='\"\n for i,v := range style{\n tagness += i + \":\" + v + \";\"\n }\n tagness += \"'\"\n if other[\"alt\"]!=\"\"{\n tagness += \" alt='\"+other[\"alt\"]+\"'\"\n }\n if other[\"title\"]!=\"\"{\n tagness += \" title='\"+other[\"title\"]+\"'\"\n }\n str = \"\"\n }else if lwrbb==\"b\" || lwrbb==\"i\" || lwrbb==\"u\" || lwrbb==\"s\"{\n str = \"<\"+bb+\">\"+in+\"<\/\"+bb+\">\"\n }else if lwrbb==\"url\"{\n str = \"\" + in + \"<\/a>\"\n }else if strings.HasPrefix(lwrbb,\"url=\"){\n str = \"\" + in + \"<\/a>\"\n }else if strings.HasPrefix(lwrbb,\"color=\"){\n str = \"\" + in + \"<\/span>\"\n }else if strings.HasPrefix(lwrbb,\"quote=\\\"\")|| strings.HasPrefix(lwrbb,\"quote='\"){\n str = \"
\"+bb[7:len(bb)-1]+\"
\"+in+\"<\/blockquote><\/div>\"\n }else if strings.HasPrefix(lwrbb,\"quote=\"){\n str = \"
\"+bb[6:]+\"
\"+in+\"<\/blockquote><\/div>\"\n }else if lwrbb==\"youtube\"{\n lwrin := strings.ToLower(in)\n parsed:=\"\"\n if strings.HasPrefix(lwrin,\"http:\/\/\") || strings.HasPrefix(lwrin,\"https:\/\/\") || strings.HasPrefix(in,\"youtu\") || strings.HasPrefix(lwrin,\"www.\"){\n tmp := in[7:]\n tmp = strings.Trim(tmp,\"\/\")\n ytb := strings.Split(tmp,\"\/\")\n if strings.HasPrefix(ytb[len(ytb)-1],\"watch?v=\"){\n parsed = ytb[len(ytb)-1][8:]\n }else{\n parsed = ytb[len(ytb)-1]\n }\n }else{\n parsed = in\n }\n str = \"