prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>help.py<|end_file_name|><|fim▁begin|># Author: Nick Raptis <[email protected]> """ Module for listing commands and help. """ from basemodule import BaseModule, BaseCommandContext from alternatives import _ class HelpContext(BaseCommandContext): def cmd_list(self, argument): """List commands""" arg = argument.lower() index = self.bot.help_index public = "public commands -- %s" % " ".join(index['public']) private = "private commands -- %s" % " ".join(index['private']) if 'all' in arg or 'both' in arg: output = "\n".join((public, private)) elif 'pub' in arg or self.target.startswith('#'): output = public elif 'priv' in arg or not self.target.startswith('#'): output = private else: # we shouldn't be here self.logger.error("cmd_list") return self.send(self.target, output) def cmd_modules(self, argument): """List active modules""" index = self.bot.help_index output = "active modules -- %s" % " ".join(index['modules'].keys()) self.send(self.target, output) def cmd_help(self, argument): """Get help on a command or module""" arg = argument.lower() index = self.bot.help_index target = self.target args = arg.split() if not args: <|fim_middle|> elif args[0] == 'module': args.pop(0) if not args: self.send(target, "usage: help module <module>") else: help_item = index['modules'].get(args[0]) if help_item: self.send(target, help_item['summary']) else: self.send(target, _("No help for %s"), args[0]) else: args.append("") cmd = args.pop(0) cmd_type = args.pop(0) if 'pu' in cmd_type or self.target.startswith('#'): cmd_type = 'public' elif 'pr' in cmd_type or not self.target.startswith('#'): cmd_type = 'private' else: # we shouldn't be here self.logger.error("cmd_list") return help_item = index[cmd_type].get(cmd) if help_item: self.send(target, index[cmd_type][cmd]['summary']) else: self.send(target, _("No help for %s"), cmd) class HelpModule(BaseModule): context_class = HelpContext module = HelpModule <|fim▁end|>
s = "usage: help <command> [public|private] / help module <module>" self.send(target, s)
<|file_name|>help.py<|end_file_name|><|fim▁begin|># Author: Nick Raptis <[email protected]> """ Module for listing commands and help. """ from basemodule import BaseModule, BaseCommandContext from alternatives import _ class HelpContext(BaseCommandContext): def cmd_list(self, argument): """List commands""" arg = argument.lower() index = self.bot.help_index public = "public commands -- %s" % " ".join(index['public']) private = "private commands -- %s" % " ".join(index['private']) if 'all' in arg or 'both' in arg: output = "\n".join((public, private)) elif 'pub' in arg or self.target.startswith('#'): output = public elif 'priv' in arg or not self.target.startswith('#'): output = private else: # we shouldn't be here self.logger.error("cmd_list") return self.send(self.target, output) def cmd_modules(self, argument): """List active modules""" index = self.bot.help_index output = "active modules -- %s" % " ".join(index['modules'].keys()) self.send(self.target, output) def cmd_help(self, argument): """Get help on a command or module""" arg = argument.lower() index = self.bot.help_index target = self.target args = arg.split() if not args: s = "usage: help <command> [public|private] / help module <module>" self.send(target, s) elif args[0] == 'module': <|fim_middle|> else: args.append("") cmd = args.pop(0) cmd_type = args.pop(0) if 'pu' in cmd_type or self.target.startswith('#'): cmd_type = 'public' elif 'pr' in cmd_type or not self.target.startswith('#'): cmd_type = 'private' else: # we shouldn't be here self.logger.error("cmd_list") return help_item = index[cmd_type].get(cmd) if help_item: self.send(target, index[cmd_type][cmd]['summary']) else: self.send(target, _("No help for %s"), cmd) class HelpModule(BaseModule): context_class = HelpContext module = HelpModule <|fim▁end|>
args.pop(0) if not args: self.send(target, "usage: help module <module>") else: help_item = index['modules'].get(args[0]) if help_item: self.send(target, help_item['summary']) else: self.send(target, _("No help for %s"), args[0])
<|file_name|>help.py<|end_file_name|><|fim▁begin|># Author: Nick Raptis <[email protected]> """ Module for listing commands and help. """ from basemodule import BaseModule, BaseCommandContext from alternatives import _ class HelpContext(BaseCommandContext): def cmd_list(self, argument): """List commands""" arg = argument.lower() index = self.bot.help_index public = "public commands -- %s" % " ".join(index['public']) private = "private commands -- %s" % " ".join(index['private']) if 'all' in arg or 'both' in arg: output = "\n".join((public, private)) elif 'pub' in arg or self.target.startswith('#'): output = public elif 'priv' in arg or not self.target.startswith('#'): output = private else: # we shouldn't be here self.logger.error("cmd_list") return self.send(self.target, output) def cmd_modules(self, argument): """List active modules""" index = self.bot.help_index output = "active modules -- %s" % " ".join(index['modules'].keys()) self.send(self.target, output) def cmd_help(self, argument): """Get help on a command or module""" arg = argument.lower() index = self.bot.help_index target = self.target args = arg.split() if not args: s = "usage: help <command> [public|private] / help module <module>" self.send(target, s) elif args[0] == 'module': args.pop(0) if not args: <|fim_middle|> else: help_item = index['modules'].get(args[0]) if help_item: self.send(target, help_item['summary']) else: self.send(target, _("No help for %s"), args[0]) else: args.append("") cmd = args.pop(0) cmd_type = args.pop(0) if 'pu' in cmd_type or self.target.startswith('#'): cmd_type = 'public' elif 'pr' in cmd_type or not self.target.startswith('#'): cmd_type = 'private' else: # we shouldn't be here self.logger.error("cmd_list") return help_item = index[cmd_type].get(cmd) if help_item: self.send(target, index[cmd_type][cmd]['summary']) else: self.send(target, _("No help for %s"), cmd) class HelpModule(BaseModule): context_class = HelpContext module = HelpModule <|fim▁end|>
self.send(target, "usage: help module <module>")
<|file_name|>help.py<|end_file_name|><|fim▁begin|># Author: Nick Raptis <[email protected]> """ Module for listing commands and help. """ from basemodule import BaseModule, BaseCommandContext from alternatives import _ class HelpContext(BaseCommandContext): def cmd_list(self, argument): """List commands""" arg = argument.lower() index = self.bot.help_index public = "public commands -- %s" % " ".join(index['public']) private = "private commands -- %s" % " ".join(index['private']) if 'all' in arg or 'both' in arg: output = "\n".join((public, private)) elif 'pub' in arg or self.target.startswith('#'): output = public elif 'priv' in arg or not self.target.startswith('#'): output = private else: # we shouldn't be here self.logger.error("cmd_list") return self.send(self.target, output) def cmd_modules(self, argument): """List active modules""" index = self.bot.help_index output = "active modules -- %s" % " ".join(index['modules'].keys()) self.send(self.target, output) def cmd_help(self, argument): """Get help on a command or module""" arg = argument.lower() index = self.bot.help_index target = self.target args = arg.split() if not args: s = "usage: help <command> [public|private] / help module <module>" self.send(target, s) elif args[0] == 'module': args.pop(0) if not args: self.send(target, "usage: help module <module>") else: <|fim_middle|> else: args.append("") cmd = args.pop(0) cmd_type = args.pop(0) if 'pu' in cmd_type or self.target.startswith('#'): cmd_type = 'public' elif 'pr' in cmd_type or not self.target.startswith('#'): cmd_type = 'private' else: # we shouldn't be here self.logger.error("cmd_list") return help_item = index[cmd_type].get(cmd) if help_item: self.send(target, index[cmd_type][cmd]['summary']) else: self.send(target, _("No help for %s"), cmd) class HelpModule(BaseModule): context_class = HelpContext module = HelpModule <|fim▁end|>
help_item = index['modules'].get(args[0]) if help_item: self.send(target, help_item['summary']) else: self.send(target, _("No help for %s"), args[0])
<|file_name|>help.py<|end_file_name|><|fim▁begin|># Author: Nick Raptis <[email protected]> """ Module for listing commands and help. """ from basemodule import BaseModule, BaseCommandContext from alternatives import _ class HelpContext(BaseCommandContext): def cmd_list(self, argument): """List commands""" arg = argument.lower() index = self.bot.help_index public = "public commands -- %s" % " ".join(index['public']) private = "private commands -- %s" % " ".join(index['private']) if 'all' in arg or 'both' in arg: output = "\n".join((public, private)) elif 'pub' in arg or self.target.startswith('#'): output = public elif 'priv' in arg or not self.target.startswith('#'): output = private else: # we shouldn't be here self.logger.error("cmd_list") return self.send(self.target, output) def cmd_modules(self, argument): """List active modules""" index = self.bot.help_index output = "active modules -- %s" % " ".join(index['modules'].keys()) self.send(self.target, output) def cmd_help(self, argument): """Get help on a command or module""" arg = argument.lower() index = self.bot.help_index target = self.target args = arg.split() if not args: s = "usage: help <command> [public|private] / help module <module>" self.send(target, s) elif args[0] == 'module': args.pop(0) if not args: self.send(target, "usage: help module <module>") else: help_item = index['modules'].get(args[0]) if help_item: <|fim_middle|> else: self.send(target, _("No help for %s"), args[0]) else: args.append("") cmd = args.pop(0) cmd_type = args.pop(0) if 'pu' in cmd_type or self.target.startswith('#'): cmd_type = 'public' elif 'pr' in cmd_type or not self.target.startswith('#'): cmd_type = 'private' else: # we shouldn't be here self.logger.error("cmd_list") return help_item = index[cmd_type].get(cmd) if help_item: self.send(target, index[cmd_type][cmd]['summary']) else: self.send(target, _("No help for %s"), cmd) class HelpModule(BaseModule): context_class = HelpContext module = HelpModule <|fim▁end|>
self.send(target, help_item['summary'])
<|file_name|>help.py<|end_file_name|><|fim▁begin|># Author: Nick Raptis <[email protected]> """ Module for listing commands and help. """ from basemodule import BaseModule, BaseCommandContext from alternatives import _ class HelpContext(BaseCommandContext): def cmd_list(self, argument): """List commands""" arg = argument.lower() index = self.bot.help_index public = "public commands -- %s" % " ".join(index['public']) private = "private commands -- %s" % " ".join(index['private']) if 'all' in arg or 'both' in arg: output = "\n".join((public, private)) elif 'pub' in arg or self.target.startswith('#'): output = public elif 'priv' in arg or not self.target.startswith('#'): output = private else: # we shouldn't be here self.logger.error("cmd_list") return self.send(self.target, output) def cmd_modules(self, argument): """List active modules""" index = self.bot.help_index output = "active modules -- %s" % " ".join(index['modules'].keys()) self.send(self.target, output) def cmd_help(self, argument): """Get help on a command or module""" arg = argument.lower() index = self.bot.help_index target = self.target args = arg.split() if not args: s = "usage: help <command> [public|private] / help module <module>" self.send(target, s) elif args[0] == 'module': args.pop(0) if not args: self.send(target, "usage: help module <module>") else: help_item = index['modules'].get(args[0]) if help_item: self.send(target, help_item['summary']) else: <|fim_middle|> else: args.append("") cmd = args.pop(0) cmd_type = args.pop(0) if 'pu' in cmd_type or self.target.startswith('#'): cmd_type = 'public' elif 'pr' in cmd_type or not self.target.startswith('#'): cmd_type = 'private' else: # we shouldn't be here self.logger.error("cmd_list") return help_item = index[cmd_type].get(cmd) if help_item: self.send(target, index[cmd_type][cmd]['summary']) else: self.send(target, _("No help for %s"), cmd) class HelpModule(BaseModule): context_class = HelpContext module = HelpModule <|fim▁end|>
self.send(target, _("No help for %s"), args[0])
<|file_name|>help.py<|end_file_name|><|fim▁begin|># Author: Nick Raptis <[email protected]> """ Module for listing commands and help. """ from basemodule import BaseModule, BaseCommandContext from alternatives import _ class HelpContext(BaseCommandContext): def cmd_list(self, argument): """List commands""" arg = argument.lower() index = self.bot.help_index public = "public commands -- %s" % " ".join(index['public']) private = "private commands -- %s" % " ".join(index['private']) if 'all' in arg or 'both' in arg: output = "\n".join((public, private)) elif 'pub' in arg or self.target.startswith('#'): output = public elif 'priv' in arg or not self.target.startswith('#'): output = private else: # we shouldn't be here self.logger.error("cmd_list") return self.send(self.target, output) def cmd_modules(self, argument): """List active modules""" index = self.bot.help_index output = "active modules -- %s" % " ".join(index['modules'].keys()) self.send(self.target, output) def cmd_help(self, argument): """Get help on a command or module""" arg = argument.lower() index = self.bot.help_index target = self.target args = arg.split() if not args: s = "usage: help <command> [public|private] / help module <module>" self.send(target, s) elif args[0] == 'module': args.pop(0) if not args: self.send(target, "usage: help module <module>") else: help_item = index['modules'].get(args[0]) if help_item: self.send(target, help_item['summary']) else: self.send(target, _("No help for %s"), args[0]) else: <|fim_middle|> class HelpModule(BaseModule): context_class = HelpContext module = HelpModule <|fim▁end|>
args.append("") cmd = args.pop(0) cmd_type = args.pop(0) if 'pu' in cmd_type or self.target.startswith('#'): cmd_type = 'public' elif 'pr' in cmd_type or not self.target.startswith('#'): cmd_type = 'private' else: # we shouldn't be here self.logger.error("cmd_list") return help_item = index[cmd_type].get(cmd) if help_item: self.send(target, index[cmd_type][cmd]['summary']) else: self.send(target, _("No help for %s"), cmd)
<|file_name|>help.py<|end_file_name|><|fim▁begin|># Author: Nick Raptis <[email protected]> """ Module for listing commands and help. """ from basemodule import BaseModule, BaseCommandContext from alternatives import _ class HelpContext(BaseCommandContext): def cmd_list(self, argument): """List commands""" arg = argument.lower() index = self.bot.help_index public = "public commands -- %s" % " ".join(index['public']) private = "private commands -- %s" % " ".join(index['private']) if 'all' in arg or 'both' in arg: output = "\n".join((public, private)) elif 'pub' in arg or self.target.startswith('#'): output = public elif 'priv' in arg or not self.target.startswith('#'): output = private else: # we shouldn't be here self.logger.error("cmd_list") return self.send(self.target, output) def cmd_modules(self, argument): """List active modules""" index = self.bot.help_index output = "active modules -- %s" % " ".join(index['modules'].keys()) self.send(self.target, output) def cmd_help(self, argument): """Get help on a command or module""" arg = argument.lower() index = self.bot.help_index target = self.target args = arg.split() if not args: s = "usage: help <command> [public|private] / help module <module>" self.send(target, s) elif args[0] == 'module': args.pop(0) if not args: self.send(target, "usage: help module <module>") else: help_item = index['modules'].get(args[0]) if help_item: self.send(target, help_item['summary']) else: self.send(target, _("No help for %s"), args[0]) else: args.append("") cmd = args.pop(0) cmd_type = args.pop(0) if 'pu' in cmd_type or self.target.startswith('#'): <|fim_middle|> elif 'pr' in cmd_type or not self.target.startswith('#'): cmd_type = 'private' else: # we shouldn't be here self.logger.error("cmd_list") return help_item = index[cmd_type].get(cmd) if help_item: self.send(target, index[cmd_type][cmd]['summary']) else: self.send(target, _("No help for %s"), cmd) class HelpModule(BaseModule): context_class = HelpContext module = HelpModule <|fim▁end|>
cmd_type = 'public'
<|file_name|>help.py<|end_file_name|><|fim▁begin|># Author: Nick Raptis <[email protected]> """ Module for listing commands and help. """ from basemodule import BaseModule, BaseCommandContext from alternatives import _ class HelpContext(BaseCommandContext): def cmd_list(self, argument): """List commands""" arg = argument.lower() index = self.bot.help_index public = "public commands -- %s" % " ".join(index['public']) private = "private commands -- %s" % " ".join(index['private']) if 'all' in arg or 'both' in arg: output = "\n".join((public, private)) elif 'pub' in arg or self.target.startswith('#'): output = public elif 'priv' in arg or not self.target.startswith('#'): output = private else: # we shouldn't be here self.logger.error("cmd_list") return self.send(self.target, output) def cmd_modules(self, argument): """List active modules""" index = self.bot.help_index output = "active modules -- %s" % " ".join(index['modules'].keys()) self.send(self.target, output) def cmd_help(self, argument): """Get help on a command or module""" arg = argument.lower() index = self.bot.help_index target = self.target args = arg.split() if not args: s = "usage: help <command> [public|private] / help module <module>" self.send(target, s) elif args[0] == 'module': args.pop(0) if not args: self.send(target, "usage: help module <module>") else: help_item = index['modules'].get(args[0]) if help_item: self.send(target, help_item['summary']) else: self.send(target, _("No help for %s"), args[0]) else: args.append("") cmd = args.pop(0) cmd_type = args.pop(0) if 'pu' in cmd_type or self.target.startswith('#'): cmd_type = 'public' elif 'pr' in cmd_type or not self.target.startswith('#'): <|fim_middle|> else: # we shouldn't be here self.logger.error("cmd_list") return help_item = index[cmd_type].get(cmd) if help_item: self.send(target, index[cmd_type][cmd]['summary']) else: self.send(target, _("No help for %s"), cmd) class HelpModule(BaseModule): context_class = HelpContext module = HelpModule <|fim▁end|>
cmd_type = 'private'
<|file_name|>help.py<|end_file_name|><|fim▁begin|># Author: Nick Raptis <[email protected]> """ Module for listing commands and help. """ from basemodule import BaseModule, BaseCommandContext from alternatives import _ class HelpContext(BaseCommandContext): def cmd_list(self, argument): """List commands""" arg = argument.lower() index = self.bot.help_index public = "public commands -- %s" % " ".join(index['public']) private = "private commands -- %s" % " ".join(index['private']) if 'all' in arg or 'both' in arg: output = "\n".join((public, private)) elif 'pub' in arg or self.target.startswith('#'): output = public elif 'priv' in arg or not self.target.startswith('#'): output = private else: # we shouldn't be here self.logger.error("cmd_list") return self.send(self.target, output) def cmd_modules(self, argument): """List active modules""" index = self.bot.help_index output = "active modules -- %s" % " ".join(index['modules'].keys()) self.send(self.target, output) def cmd_help(self, argument): """Get help on a command or module""" arg = argument.lower() index = self.bot.help_index target = self.target args = arg.split() if not args: s = "usage: help <command> [public|private] / help module <module>" self.send(target, s) elif args[0] == 'module': args.pop(0) if not args: self.send(target, "usage: help module <module>") else: help_item = index['modules'].get(args[0]) if help_item: self.send(target, help_item['summary']) else: self.send(target, _("No help for %s"), args[0]) else: args.append("") cmd = args.pop(0) cmd_type = args.pop(0) if 'pu' in cmd_type or self.target.startswith('#'): cmd_type = 'public' elif 'pr' in cmd_type or not self.target.startswith('#'): cmd_type = 'private' else: # we shouldn't be here <|fim_middle|> help_item = index[cmd_type].get(cmd) if help_item: self.send(target, index[cmd_type][cmd]['summary']) else: self.send(target, _("No help for %s"), cmd) class HelpModule(BaseModule): context_class = HelpContext module = HelpModule <|fim▁end|>
self.logger.error("cmd_list") return
<|file_name|>help.py<|end_file_name|><|fim▁begin|># Author: Nick Raptis <[email protected]> """ Module for listing commands and help. """ from basemodule import BaseModule, BaseCommandContext from alternatives import _ class HelpContext(BaseCommandContext): def cmd_list(self, argument): """List commands""" arg = argument.lower() index = self.bot.help_index public = "public commands -- %s" % " ".join(index['public']) private = "private commands -- %s" % " ".join(index['private']) if 'all' in arg or 'both' in arg: output = "\n".join((public, private)) elif 'pub' in arg or self.target.startswith('#'): output = public elif 'priv' in arg or not self.target.startswith('#'): output = private else: # we shouldn't be here self.logger.error("cmd_list") return self.send(self.target, output) def cmd_modules(self, argument): """List active modules""" index = self.bot.help_index output = "active modules -- %s" % " ".join(index['modules'].keys()) self.send(self.target, output) def cmd_help(self, argument): """Get help on a command or module""" arg = argument.lower() index = self.bot.help_index target = self.target args = arg.split() if not args: s = "usage: help <command> [public|private] / help module <module>" self.send(target, s) elif args[0] == 'module': args.pop(0) if not args: self.send(target, "usage: help module <module>") else: help_item = index['modules'].get(args[0]) if help_item: self.send(target, help_item['summary']) else: self.send(target, _("No help for %s"), args[0]) else: args.append("") cmd = args.pop(0) cmd_type = args.pop(0) if 'pu' in cmd_type or self.target.startswith('#'): cmd_type = 'public' elif 'pr' in cmd_type or not self.target.startswith('#'): cmd_type = 'private' else: # we shouldn't be here self.logger.error("cmd_list") return help_item = index[cmd_type].get(cmd) if help_item: <|fim_middle|> else: self.send(target, _("No help for %s"), cmd) class HelpModule(BaseModule): context_class = HelpContext module = HelpModule <|fim▁end|>
self.send(target, index[cmd_type][cmd]['summary'])
<|file_name|>help.py<|end_file_name|><|fim▁begin|># Author: Nick Raptis <[email protected]> """ Module for listing commands and help. """ from basemodule import BaseModule, BaseCommandContext from alternatives import _ class HelpContext(BaseCommandContext): def cmd_list(self, argument): """List commands""" arg = argument.lower() index = self.bot.help_index public = "public commands -- %s" % " ".join(index['public']) private = "private commands -- %s" % " ".join(index['private']) if 'all' in arg or 'both' in arg: output = "\n".join((public, private)) elif 'pub' in arg or self.target.startswith('#'): output = public elif 'priv' in arg or not self.target.startswith('#'): output = private else: # we shouldn't be here self.logger.error("cmd_list") return self.send(self.target, output) def cmd_modules(self, argument): """List active modules""" index = self.bot.help_index output = "active modules -- %s" % " ".join(index['modules'].keys()) self.send(self.target, output) def cmd_help(self, argument): """Get help on a command or module""" arg = argument.lower() index = self.bot.help_index target = self.target args = arg.split() if not args: s = "usage: help <command> [public|private] / help module <module>" self.send(target, s) elif args[0] == 'module': args.pop(0) if not args: self.send(target, "usage: help module <module>") else: help_item = index['modules'].get(args[0]) if help_item: self.send(target, help_item['summary']) else: self.send(target, _("No help for %s"), args[0]) else: args.append("") cmd = args.pop(0) cmd_type = args.pop(0) if 'pu' in cmd_type or self.target.startswith('#'): cmd_type = 'public' elif 'pr' in cmd_type or not self.target.startswith('#'): cmd_type = 'private' else: # we shouldn't be here self.logger.error("cmd_list") return help_item = index[cmd_type].get(cmd) if help_item: self.send(target, index[cmd_type][cmd]['summary']) else: <|fim_middle|> class HelpModule(BaseModule): context_class = HelpContext module = HelpModule <|fim▁end|>
self.send(target, _("No help for %s"), cmd)
<|file_name|>help.py<|end_file_name|><|fim▁begin|># Author: Nick Raptis <[email protected]> """ Module for listing commands and help. """ from basemodule import BaseModule, BaseCommandContext from alternatives import _ class HelpContext(BaseCommandContext): def <|fim_middle|>(self, argument): """List commands""" arg = argument.lower() index = self.bot.help_index public = "public commands -- %s" % " ".join(index['public']) private = "private commands -- %s" % " ".join(index['private']) if 'all' in arg or 'both' in arg: output = "\n".join((public, private)) elif 'pub' in arg or self.target.startswith('#'): output = public elif 'priv' in arg or not self.target.startswith('#'): output = private else: # we shouldn't be here self.logger.error("cmd_list") return self.send(self.target, output) def cmd_modules(self, argument): """List active modules""" index = self.bot.help_index output = "active modules -- %s" % " ".join(index['modules'].keys()) self.send(self.target, output) def cmd_help(self, argument): """Get help on a command or module""" arg = argument.lower() index = self.bot.help_index target = self.target args = arg.split() if not args: s = "usage: help <command> [public|private] / help module <module>" self.send(target, s) elif args[0] == 'module': args.pop(0) if not args: self.send(target, "usage: help module <module>") else: help_item = index['modules'].get(args[0]) if help_item: self.send(target, help_item['summary']) else: self.send(target, _("No help for %s"), args[0]) else: args.append("") cmd = args.pop(0) cmd_type = args.pop(0) if 'pu' in cmd_type or self.target.startswith('#'): cmd_type = 'public' elif 'pr' in cmd_type or not self.target.startswith('#'): cmd_type = 'private' else: # we shouldn't be here self.logger.error("cmd_list") return help_item = index[cmd_type].get(cmd) if help_item: self.send(target, index[cmd_type][cmd]['summary']) else: self.send(target, _("No help for %s"), cmd) class HelpModule(BaseModule): context_class = HelpContext module = HelpModule <|fim▁end|>
cmd_list
<|file_name|>help.py<|end_file_name|><|fim▁begin|># Author: Nick Raptis <[email protected]> """ Module for listing commands and help. """ from basemodule import BaseModule, BaseCommandContext from alternatives import _ class HelpContext(BaseCommandContext): def cmd_list(self, argument): """List commands""" arg = argument.lower() index = self.bot.help_index public = "public commands -- %s" % " ".join(index['public']) private = "private commands -- %s" % " ".join(index['private']) if 'all' in arg or 'both' in arg: output = "\n".join((public, private)) elif 'pub' in arg or self.target.startswith('#'): output = public elif 'priv' in arg or not self.target.startswith('#'): output = private else: # we shouldn't be here self.logger.error("cmd_list") return self.send(self.target, output) def <|fim_middle|>(self, argument): """List active modules""" index = self.bot.help_index output = "active modules -- %s" % " ".join(index['modules'].keys()) self.send(self.target, output) def cmd_help(self, argument): """Get help on a command or module""" arg = argument.lower() index = self.bot.help_index target = self.target args = arg.split() if not args: s = "usage: help <command> [public|private] / help module <module>" self.send(target, s) elif args[0] == 'module': args.pop(0) if not args: self.send(target, "usage: help module <module>") else: help_item = index['modules'].get(args[0]) if help_item: self.send(target, help_item['summary']) else: self.send(target, _("No help for %s"), args[0]) else: args.append("") cmd = args.pop(0) cmd_type = args.pop(0) if 'pu' in cmd_type or self.target.startswith('#'): cmd_type = 'public' elif 'pr' in cmd_type or not self.target.startswith('#'): cmd_type = 'private' else: # we shouldn't be here self.logger.error("cmd_list") return help_item = index[cmd_type].get(cmd) if help_item: self.send(target, index[cmd_type][cmd]['summary']) else: self.send(target, _("No help for %s"), cmd) class HelpModule(BaseModule): context_class = HelpContext module = HelpModule <|fim▁end|>
cmd_modules
<|file_name|>help.py<|end_file_name|><|fim▁begin|># Author: Nick Raptis <[email protected]> """ Module for listing commands and help. """ from basemodule import BaseModule, BaseCommandContext from alternatives import _ class HelpContext(BaseCommandContext): def cmd_list(self, argument): """List commands""" arg = argument.lower() index = self.bot.help_index public = "public commands -- %s" % " ".join(index['public']) private = "private commands -- %s" % " ".join(index['private']) if 'all' in arg or 'both' in arg: output = "\n".join((public, private)) elif 'pub' in arg or self.target.startswith('#'): output = public elif 'priv' in arg or not self.target.startswith('#'): output = private else: # we shouldn't be here self.logger.error("cmd_list") return self.send(self.target, output) def cmd_modules(self, argument): """List active modules""" index = self.bot.help_index output = "active modules -- %s" % " ".join(index['modules'].keys()) self.send(self.target, output) def <|fim_middle|>(self, argument): """Get help on a command or module""" arg = argument.lower() index = self.bot.help_index target = self.target args = arg.split() if not args: s = "usage: help <command> [public|private] / help module <module>" self.send(target, s) elif args[0] == 'module': args.pop(0) if not args: self.send(target, "usage: help module <module>") else: help_item = index['modules'].get(args[0]) if help_item: self.send(target, help_item['summary']) else: self.send(target, _("No help for %s"), args[0]) else: args.append("") cmd = args.pop(0) cmd_type = args.pop(0) if 'pu' in cmd_type or self.target.startswith('#'): cmd_type = 'public' elif 'pr' in cmd_type or not self.target.startswith('#'): cmd_type = 'private' else: # we shouldn't be here self.logger.error("cmd_list") return help_item = index[cmd_type].get(cmd) if help_item: self.send(target, index[cmd_type][cmd]['summary']) else: self.send(target, _("No help for %s"), cmd) class HelpModule(BaseModule): context_class = HelpContext module = HelpModule <|fim▁end|>
cmd_help
<|file_name|>serializers.py<|end_file_name|><|fim▁begin|>from bluebottle.projects.serializers import ProjectPreviewSerializer from bluebottle.quotes.serializers import QuoteSerializer from bluebottle.slides.serializers import SlideSerializer from bluebottle.statistics.serializers import StatisticSerializer from rest_framework import serializers class HomePageSerializer(serializers.Serializer): id = serializers.CharField() quotes = QuoteSerializer(many=True) slides = SlideSerializer(many=True)<|fim▁hole|><|fim▁end|>
statistics = StatisticSerializer(many=True) projects = ProjectPreviewSerializer(many=True)
<|file_name|>serializers.py<|end_file_name|><|fim▁begin|>from bluebottle.projects.serializers import ProjectPreviewSerializer from bluebottle.quotes.serializers import QuoteSerializer from bluebottle.slides.serializers import SlideSerializer from bluebottle.statistics.serializers import StatisticSerializer from rest_framework import serializers class HomePageSerializer(serializers.Serializer): <|fim_middle|> <|fim▁end|>
id = serializers.CharField() quotes = QuoteSerializer(many=True) slides = SlideSerializer(many=True) statistics = StatisticSerializer(many=True) projects = ProjectPreviewSerializer(many=True)
<|file_name|>apps.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals from django.apps import AppConfig<|fim▁hole|> name = 'RFHistory'<|fim▁end|>
class RfhistoryConfig(AppConfig):
<|file_name|>apps.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals from django.apps import AppConfig class RfhistoryConfig(AppConfig): <|fim_middle|> <|fim▁end|>
name = 'RFHistory'
<|file_name|>CCipher.py<|end_file_name|><|fim▁begin|><|fim▁hole|>Single Round Match 147 Round 1 - Division II, Level One """ class CCipher: def decode(self, cipherText, shift): a = ord('A') decoder = [a + (c - shift if c >= shift else c - shift + 26) for c in range(26)] plain = [chr(decoder[ord(c) - a]) for c in cipherText] return ''.join(plain)<|fim▁end|>
""" http://community.topcoder.com/stat?c=problem_statement&pm=1667
<|file_name|>CCipher.py<|end_file_name|><|fim▁begin|>""" http://community.topcoder.com/stat?c=problem_statement&pm=1667 Single Round Match 147 Round 1 - Division II, Level One """ class CCipher: <|fim_middle|> <|fim▁end|>
def decode(self, cipherText, shift): a = ord('A') decoder = [a + (c - shift if c >= shift else c - shift + 26) for c in range(26)] plain = [chr(decoder[ord(c) - a]) for c in cipherText] return ''.join(plain)
<|file_name|>CCipher.py<|end_file_name|><|fim▁begin|>""" http://community.topcoder.com/stat?c=problem_statement&pm=1667 Single Round Match 147 Round 1 - Division II, Level One """ class CCipher: def decode(self, cipherText, shift): <|fim_middle|> <|fim▁end|>
a = ord('A') decoder = [a + (c - shift if c >= shift else c - shift + 26) for c in range(26)] plain = [chr(decoder[ord(c) - a]) for c in cipherText] return ''.join(plain)
<|file_name|>CCipher.py<|end_file_name|><|fim▁begin|>""" http://community.topcoder.com/stat?c=problem_statement&pm=1667 Single Round Match 147 Round 1 - Division II, Level One """ class CCipher: def <|fim_middle|>(self, cipherText, shift): a = ord('A') decoder = [a + (c - shift if c >= shift else c - shift + 26) for c in range(26)] plain = [chr(decoder[ord(c) - a]) for c in cipherText] return ''.join(plain) <|fim▁end|>
decode
<|file_name|>aws_logs.py<|end_file_name|><|fim▁begin|># Copyright 2018 PerfKitBenchmarker Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module containing classes related to AWS CloudWatch Logs.""" import json from perfkitbenchmarker import resource from perfkitbenchmarker import vm_util from perfkitbenchmarker.providers.aws import util class LogGroup(resource.BaseResource): """Class representing a CloudWatch log group.""" def __init__(self, region, name, retention_in_days=7): super(LogGroup, self).__init__() self.region = region self.name = name self.retention_in_days = retention_in_days def _Create(self): """Create the log group.""" create_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'create-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(create_cmd) def _Delete(self): """Delete the log group.""" delete_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'delete-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(delete_cmd, raise_on_failure=False) def Exists(self): """Returns True if the log group exists.""" describe_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'describe-log-groups', '--log-group-name-prefix', self.name, '--no-paginate' ] stdout, _, _ = vm_util.IssueCommand(describe_cmd) log_groups = json.loads(stdout)['logGroups'] group = next((group for group in log_groups if group['logGroupName'] == self.name), None) return bool(group) def _PostCreate(self): """Set the retention policy.""" put_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'put-retention-policy', '--log-group-name', self.name, '--retention-in-days', str(self.retention_in_days) ] vm_util.IssueCommand(put_cmd) def GetLogs(region, stream_name, group_name, token=None): """Fetches the JSON formatted log stream starting at the token.""" get_cmd = util.AWS_PREFIX + [ '--region', region, 'logs', 'get-log-events', '--start-from-head', '--log-group-name', group_name, '--log-stream-name', stream_name, ] if token: get_cmd.extend(['--next-token', token]) stdout, _, _ = vm_util.IssueCommand(get_cmd) return json.loads(stdout) def GetLogStreamAsString(region, stream_name, log_group): """Returns the messages of the log stream as a string.""" log_lines = [] token = None events = [] while token is None or events:<|fim▁hole|> for event in events: log_lines.append(event['message']) return '\n'.join(log_lines)<|fim▁end|>
response = GetLogs(region, stream_name, log_group, token) events = response['events'] token = response['nextForwardToken']
<|file_name|>aws_logs.py<|end_file_name|><|fim▁begin|># Copyright 2018 PerfKitBenchmarker Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module containing classes related to AWS CloudWatch Logs.""" import json from perfkitbenchmarker import resource from perfkitbenchmarker import vm_util from perfkitbenchmarker.providers.aws import util class LogGroup(resource.BaseResource): <|fim_middle|> def GetLogs(region, stream_name, group_name, token=None): """Fetches the JSON formatted log stream starting at the token.""" get_cmd = util.AWS_PREFIX + [ '--region', region, 'logs', 'get-log-events', '--start-from-head', '--log-group-name', group_name, '--log-stream-name', stream_name, ] if token: get_cmd.extend(['--next-token', token]) stdout, _, _ = vm_util.IssueCommand(get_cmd) return json.loads(stdout) def GetLogStreamAsString(region, stream_name, log_group): """Returns the messages of the log stream as a string.""" log_lines = [] token = None events = [] while token is None or events: response = GetLogs(region, stream_name, log_group, token) events = response['events'] token = response['nextForwardToken'] for event in events: log_lines.append(event['message']) return '\n'.join(log_lines) <|fim▁end|>
"""Class representing a CloudWatch log group.""" def __init__(self, region, name, retention_in_days=7): super(LogGroup, self).__init__() self.region = region self.name = name self.retention_in_days = retention_in_days def _Create(self): """Create the log group.""" create_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'create-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(create_cmd) def _Delete(self): """Delete the log group.""" delete_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'delete-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(delete_cmd, raise_on_failure=False) def Exists(self): """Returns True if the log group exists.""" describe_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'describe-log-groups', '--log-group-name-prefix', self.name, '--no-paginate' ] stdout, _, _ = vm_util.IssueCommand(describe_cmd) log_groups = json.loads(stdout)['logGroups'] group = next((group for group in log_groups if group['logGroupName'] == self.name), None) return bool(group) def _PostCreate(self): """Set the retention policy.""" put_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'put-retention-policy', '--log-group-name', self.name, '--retention-in-days', str(self.retention_in_days) ] vm_util.IssueCommand(put_cmd)
<|file_name|>aws_logs.py<|end_file_name|><|fim▁begin|># Copyright 2018 PerfKitBenchmarker Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module containing classes related to AWS CloudWatch Logs.""" import json from perfkitbenchmarker import resource from perfkitbenchmarker import vm_util from perfkitbenchmarker.providers.aws import util class LogGroup(resource.BaseResource): """Class representing a CloudWatch log group.""" def __init__(self, region, name, retention_in_days=7): <|fim_middle|> def _Create(self): """Create the log group.""" create_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'create-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(create_cmd) def _Delete(self): """Delete the log group.""" delete_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'delete-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(delete_cmd, raise_on_failure=False) def Exists(self): """Returns True if the log group exists.""" describe_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'describe-log-groups', '--log-group-name-prefix', self.name, '--no-paginate' ] stdout, _, _ = vm_util.IssueCommand(describe_cmd) log_groups = json.loads(stdout)['logGroups'] group = next((group for group in log_groups if group['logGroupName'] == self.name), None) return bool(group) def _PostCreate(self): """Set the retention policy.""" put_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'put-retention-policy', '--log-group-name', self.name, '--retention-in-days', str(self.retention_in_days) ] vm_util.IssueCommand(put_cmd) def GetLogs(region, stream_name, group_name, token=None): """Fetches the JSON formatted log stream starting at the token.""" get_cmd = util.AWS_PREFIX + [ '--region', region, 'logs', 'get-log-events', '--start-from-head', '--log-group-name', group_name, '--log-stream-name', stream_name, ] if token: get_cmd.extend(['--next-token', token]) stdout, _, _ = vm_util.IssueCommand(get_cmd) return json.loads(stdout) def GetLogStreamAsString(region, stream_name, log_group): """Returns the messages of the log stream as a string.""" log_lines = [] token = None events = [] while token is None or events: response = GetLogs(region, stream_name, log_group, token) events = response['events'] token = response['nextForwardToken'] for event in events: log_lines.append(event['message']) return '\n'.join(log_lines) <|fim▁end|>
super(LogGroup, self).__init__() self.region = region self.name = name self.retention_in_days = retention_in_days
<|file_name|>aws_logs.py<|end_file_name|><|fim▁begin|># Copyright 2018 PerfKitBenchmarker Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module containing classes related to AWS CloudWatch Logs.""" import json from perfkitbenchmarker import resource from perfkitbenchmarker import vm_util from perfkitbenchmarker.providers.aws import util class LogGroup(resource.BaseResource): """Class representing a CloudWatch log group.""" def __init__(self, region, name, retention_in_days=7): super(LogGroup, self).__init__() self.region = region self.name = name self.retention_in_days = retention_in_days def _Create(self): <|fim_middle|> def _Delete(self): """Delete the log group.""" delete_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'delete-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(delete_cmd, raise_on_failure=False) def Exists(self): """Returns True if the log group exists.""" describe_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'describe-log-groups', '--log-group-name-prefix', self.name, '--no-paginate' ] stdout, _, _ = vm_util.IssueCommand(describe_cmd) log_groups = json.loads(stdout)['logGroups'] group = next((group for group in log_groups if group['logGroupName'] == self.name), None) return bool(group) def _PostCreate(self): """Set the retention policy.""" put_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'put-retention-policy', '--log-group-name', self.name, '--retention-in-days', str(self.retention_in_days) ] vm_util.IssueCommand(put_cmd) def GetLogs(region, stream_name, group_name, token=None): """Fetches the JSON formatted log stream starting at the token.""" get_cmd = util.AWS_PREFIX + [ '--region', region, 'logs', 'get-log-events', '--start-from-head', '--log-group-name', group_name, '--log-stream-name', stream_name, ] if token: get_cmd.extend(['--next-token', token]) stdout, _, _ = vm_util.IssueCommand(get_cmd) return json.loads(stdout) def GetLogStreamAsString(region, stream_name, log_group): """Returns the messages of the log stream as a string.""" log_lines = [] token = None events = [] while token is None or events: response = GetLogs(region, stream_name, log_group, token) events = response['events'] token = response['nextForwardToken'] for event in events: log_lines.append(event['message']) return '\n'.join(log_lines) <|fim▁end|>
"""Create the log group.""" create_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'create-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(create_cmd)
<|file_name|>aws_logs.py<|end_file_name|><|fim▁begin|># Copyright 2018 PerfKitBenchmarker Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module containing classes related to AWS CloudWatch Logs.""" import json from perfkitbenchmarker import resource from perfkitbenchmarker import vm_util from perfkitbenchmarker.providers.aws import util class LogGroup(resource.BaseResource): """Class representing a CloudWatch log group.""" def __init__(self, region, name, retention_in_days=7): super(LogGroup, self).__init__() self.region = region self.name = name self.retention_in_days = retention_in_days def _Create(self): """Create the log group.""" create_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'create-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(create_cmd) def _Delete(self): <|fim_middle|> def Exists(self): """Returns True if the log group exists.""" describe_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'describe-log-groups', '--log-group-name-prefix', self.name, '--no-paginate' ] stdout, _, _ = vm_util.IssueCommand(describe_cmd) log_groups = json.loads(stdout)['logGroups'] group = next((group for group in log_groups if group['logGroupName'] == self.name), None) return bool(group) def _PostCreate(self): """Set the retention policy.""" put_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'put-retention-policy', '--log-group-name', self.name, '--retention-in-days', str(self.retention_in_days) ] vm_util.IssueCommand(put_cmd) def GetLogs(region, stream_name, group_name, token=None): """Fetches the JSON formatted log stream starting at the token.""" get_cmd = util.AWS_PREFIX + [ '--region', region, 'logs', 'get-log-events', '--start-from-head', '--log-group-name', group_name, '--log-stream-name', stream_name, ] if token: get_cmd.extend(['--next-token', token]) stdout, _, _ = vm_util.IssueCommand(get_cmd) return json.loads(stdout) def GetLogStreamAsString(region, stream_name, log_group): """Returns the messages of the log stream as a string.""" log_lines = [] token = None events = [] while token is None or events: response = GetLogs(region, stream_name, log_group, token) events = response['events'] token = response['nextForwardToken'] for event in events: log_lines.append(event['message']) return '\n'.join(log_lines) <|fim▁end|>
"""Delete the log group.""" delete_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'delete-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(delete_cmd, raise_on_failure=False)
<|file_name|>aws_logs.py<|end_file_name|><|fim▁begin|># Copyright 2018 PerfKitBenchmarker Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module containing classes related to AWS CloudWatch Logs.""" import json from perfkitbenchmarker import resource from perfkitbenchmarker import vm_util from perfkitbenchmarker.providers.aws import util class LogGroup(resource.BaseResource): """Class representing a CloudWatch log group.""" def __init__(self, region, name, retention_in_days=7): super(LogGroup, self).__init__() self.region = region self.name = name self.retention_in_days = retention_in_days def _Create(self): """Create the log group.""" create_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'create-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(create_cmd) def _Delete(self): """Delete the log group.""" delete_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'delete-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(delete_cmd, raise_on_failure=False) def Exists(self): <|fim_middle|> def _PostCreate(self): """Set the retention policy.""" put_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'put-retention-policy', '--log-group-name', self.name, '--retention-in-days', str(self.retention_in_days) ] vm_util.IssueCommand(put_cmd) def GetLogs(region, stream_name, group_name, token=None): """Fetches the JSON formatted log stream starting at the token.""" get_cmd = util.AWS_PREFIX + [ '--region', region, 'logs', 'get-log-events', '--start-from-head', '--log-group-name', group_name, '--log-stream-name', stream_name, ] if token: get_cmd.extend(['--next-token', token]) stdout, _, _ = vm_util.IssueCommand(get_cmd) return json.loads(stdout) def GetLogStreamAsString(region, stream_name, log_group): """Returns the messages of the log stream as a string.""" log_lines = [] token = None events = [] while token is None or events: response = GetLogs(region, stream_name, log_group, token) events = response['events'] token = response['nextForwardToken'] for event in events: log_lines.append(event['message']) return '\n'.join(log_lines) <|fim▁end|>
"""Returns True if the log group exists.""" describe_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'describe-log-groups', '--log-group-name-prefix', self.name, '--no-paginate' ] stdout, _, _ = vm_util.IssueCommand(describe_cmd) log_groups = json.loads(stdout)['logGroups'] group = next((group for group in log_groups if group['logGroupName'] == self.name), None) return bool(group)
<|file_name|>aws_logs.py<|end_file_name|><|fim▁begin|># Copyright 2018 PerfKitBenchmarker Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module containing classes related to AWS CloudWatch Logs.""" import json from perfkitbenchmarker import resource from perfkitbenchmarker import vm_util from perfkitbenchmarker.providers.aws import util class LogGroup(resource.BaseResource): """Class representing a CloudWatch log group.""" def __init__(self, region, name, retention_in_days=7): super(LogGroup, self).__init__() self.region = region self.name = name self.retention_in_days = retention_in_days def _Create(self): """Create the log group.""" create_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'create-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(create_cmd) def _Delete(self): """Delete the log group.""" delete_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'delete-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(delete_cmd, raise_on_failure=False) def Exists(self): """Returns True if the log group exists.""" describe_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'describe-log-groups', '--log-group-name-prefix', self.name, '--no-paginate' ] stdout, _, _ = vm_util.IssueCommand(describe_cmd) log_groups = json.loads(stdout)['logGroups'] group = next((group for group in log_groups if group['logGroupName'] == self.name), None) return bool(group) def _PostCreate(self): <|fim_middle|> def GetLogs(region, stream_name, group_name, token=None): """Fetches the JSON formatted log stream starting at the token.""" get_cmd = util.AWS_PREFIX + [ '--region', region, 'logs', 'get-log-events', '--start-from-head', '--log-group-name', group_name, '--log-stream-name', stream_name, ] if token: get_cmd.extend(['--next-token', token]) stdout, _, _ = vm_util.IssueCommand(get_cmd) return json.loads(stdout) def GetLogStreamAsString(region, stream_name, log_group): """Returns the messages of the log stream as a string.""" log_lines = [] token = None events = [] while token is None or events: response = GetLogs(region, stream_name, log_group, token) events = response['events'] token = response['nextForwardToken'] for event in events: log_lines.append(event['message']) return '\n'.join(log_lines) <|fim▁end|>
"""Set the retention policy.""" put_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'put-retention-policy', '--log-group-name', self.name, '--retention-in-days', str(self.retention_in_days) ] vm_util.IssueCommand(put_cmd)
<|file_name|>aws_logs.py<|end_file_name|><|fim▁begin|># Copyright 2018 PerfKitBenchmarker Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module containing classes related to AWS CloudWatch Logs.""" import json from perfkitbenchmarker import resource from perfkitbenchmarker import vm_util from perfkitbenchmarker.providers.aws import util class LogGroup(resource.BaseResource): """Class representing a CloudWatch log group.""" def __init__(self, region, name, retention_in_days=7): super(LogGroup, self).__init__() self.region = region self.name = name self.retention_in_days = retention_in_days def _Create(self): """Create the log group.""" create_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'create-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(create_cmd) def _Delete(self): """Delete the log group.""" delete_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'delete-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(delete_cmd, raise_on_failure=False) def Exists(self): """Returns True if the log group exists.""" describe_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'describe-log-groups', '--log-group-name-prefix', self.name, '--no-paginate' ] stdout, _, _ = vm_util.IssueCommand(describe_cmd) log_groups = json.loads(stdout)['logGroups'] group = next((group for group in log_groups if group['logGroupName'] == self.name), None) return bool(group) def _PostCreate(self): """Set the retention policy.""" put_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'put-retention-policy', '--log-group-name', self.name, '--retention-in-days', str(self.retention_in_days) ] vm_util.IssueCommand(put_cmd) def GetLogs(region, stream_name, group_name, token=None): <|fim_middle|> def GetLogStreamAsString(region, stream_name, log_group): """Returns the messages of the log stream as a string.""" log_lines = [] token = None events = [] while token is None or events: response = GetLogs(region, stream_name, log_group, token) events = response['events'] token = response['nextForwardToken'] for event in events: log_lines.append(event['message']) return '\n'.join(log_lines) <|fim▁end|>
"""Fetches the JSON formatted log stream starting at the token.""" get_cmd = util.AWS_PREFIX + [ '--region', region, 'logs', 'get-log-events', '--start-from-head', '--log-group-name', group_name, '--log-stream-name', stream_name, ] if token: get_cmd.extend(['--next-token', token]) stdout, _, _ = vm_util.IssueCommand(get_cmd) return json.loads(stdout)
<|file_name|>aws_logs.py<|end_file_name|><|fim▁begin|># Copyright 2018 PerfKitBenchmarker Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module containing classes related to AWS CloudWatch Logs.""" import json from perfkitbenchmarker import resource from perfkitbenchmarker import vm_util from perfkitbenchmarker.providers.aws import util class LogGroup(resource.BaseResource): """Class representing a CloudWatch log group.""" def __init__(self, region, name, retention_in_days=7): super(LogGroup, self).__init__() self.region = region self.name = name self.retention_in_days = retention_in_days def _Create(self): """Create the log group.""" create_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'create-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(create_cmd) def _Delete(self): """Delete the log group.""" delete_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'delete-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(delete_cmd, raise_on_failure=False) def Exists(self): """Returns True if the log group exists.""" describe_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'describe-log-groups', '--log-group-name-prefix', self.name, '--no-paginate' ] stdout, _, _ = vm_util.IssueCommand(describe_cmd) log_groups = json.loads(stdout)['logGroups'] group = next((group for group in log_groups if group['logGroupName'] == self.name), None) return bool(group) def _PostCreate(self): """Set the retention policy.""" put_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'put-retention-policy', '--log-group-name', self.name, '--retention-in-days', str(self.retention_in_days) ] vm_util.IssueCommand(put_cmd) def GetLogs(region, stream_name, group_name, token=None): """Fetches the JSON formatted log stream starting at the token.""" get_cmd = util.AWS_PREFIX + [ '--region', region, 'logs', 'get-log-events', '--start-from-head', '--log-group-name', group_name, '--log-stream-name', stream_name, ] if token: get_cmd.extend(['--next-token', token]) stdout, _, _ = vm_util.IssueCommand(get_cmd) return json.loads(stdout) def GetLogStreamAsString(region, stream_name, log_group): <|fim_middle|> <|fim▁end|>
"""Returns the messages of the log stream as a string.""" log_lines = [] token = None events = [] while token is None or events: response = GetLogs(region, stream_name, log_group, token) events = response['events'] token = response['nextForwardToken'] for event in events: log_lines.append(event['message']) return '\n'.join(log_lines)
<|file_name|>aws_logs.py<|end_file_name|><|fim▁begin|># Copyright 2018 PerfKitBenchmarker Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module containing classes related to AWS CloudWatch Logs.""" import json from perfkitbenchmarker import resource from perfkitbenchmarker import vm_util from perfkitbenchmarker.providers.aws import util class LogGroup(resource.BaseResource): """Class representing a CloudWatch log group.""" def __init__(self, region, name, retention_in_days=7): super(LogGroup, self).__init__() self.region = region self.name = name self.retention_in_days = retention_in_days def _Create(self): """Create the log group.""" create_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'create-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(create_cmd) def _Delete(self): """Delete the log group.""" delete_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'delete-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(delete_cmd, raise_on_failure=False) def Exists(self): """Returns True if the log group exists.""" describe_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'describe-log-groups', '--log-group-name-prefix', self.name, '--no-paginate' ] stdout, _, _ = vm_util.IssueCommand(describe_cmd) log_groups = json.loads(stdout)['logGroups'] group = next((group for group in log_groups if group['logGroupName'] == self.name), None) return bool(group) def _PostCreate(self): """Set the retention policy.""" put_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'put-retention-policy', '--log-group-name', self.name, '--retention-in-days', str(self.retention_in_days) ] vm_util.IssueCommand(put_cmd) def GetLogs(region, stream_name, group_name, token=None): """Fetches the JSON formatted log stream starting at the token.""" get_cmd = util.AWS_PREFIX + [ '--region', region, 'logs', 'get-log-events', '--start-from-head', '--log-group-name', group_name, '--log-stream-name', stream_name, ] if token: <|fim_middle|> stdout, _, _ = vm_util.IssueCommand(get_cmd) return json.loads(stdout) def GetLogStreamAsString(region, stream_name, log_group): """Returns the messages of the log stream as a string.""" log_lines = [] token = None events = [] while token is None or events: response = GetLogs(region, stream_name, log_group, token) events = response['events'] token = response['nextForwardToken'] for event in events: log_lines.append(event['message']) return '\n'.join(log_lines) <|fim▁end|>
get_cmd.extend(['--next-token', token])
<|file_name|>aws_logs.py<|end_file_name|><|fim▁begin|># Copyright 2018 PerfKitBenchmarker Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module containing classes related to AWS CloudWatch Logs.""" import json from perfkitbenchmarker import resource from perfkitbenchmarker import vm_util from perfkitbenchmarker.providers.aws import util class LogGroup(resource.BaseResource): """Class representing a CloudWatch log group.""" def <|fim_middle|>(self, region, name, retention_in_days=7): super(LogGroup, self).__init__() self.region = region self.name = name self.retention_in_days = retention_in_days def _Create(self): """Create the log group.""" create_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'create-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(create_cmd) def _Delete(self): """Delete the log group.""" delete_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'delete-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(delete_cmd, raise_on_failure=False) def Exists(self): """Returns True if the log group exists.""" describe_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'describe-log-groups', '--log-group-name-prefix', self.name, '--no-paginate' ] stdout, _, _ = vm_util.IssueCommand(describe_cmd) log_groups = json.loads(stdout)['logGroups'] group = next((group for group in log_groups if group['logGroupName'] == self.name), None) return bool(group) def _PostCreate(self): """Set the retention policy.""" put_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'put-retention-policy', '--log-group-name', self.name, '--retention-in-days', str(self.retention_in_days) ] vm_util.IssueCommand(put_cmd) def GetLogs(region, stream_name, group_name, token=None): """Fetches the JSON formatted log stream starting at the token.""" get_cmd = util.AWS_PREFIX + [ '--region', region, 'logs', 'get-log-events', '--start-from-head', '--log-group-name', group_name, '--log-stream-name', stream_name, ] if token: get_cmd.extend(['--next-token', token]) stdout, _, _ = vm_util.IssueCommand(get_cmd) return json.loads(stdout) def GetLogStreamAsString(region, stream_name, log_group): """Returns the messages of the log stream as a string.""" log_lines = [] token = None events = [] while token is None or events: response = GetLogs(region, stream_name, log_group, token) events = response['events'] token = response['nextForwardToken'] for event in events: log_lines.append(event['message']) return '\n'.join(log_lines) <|fim▁end|>
__init__
<|file_name|>aws_logs.py<|end_file_name|><|fim▁begin|># Copyright 2018 PerfKitBenchmarker Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module containing classes related to AWS CloudWatch Logs.""" import json from perfkitbenchmarker import resource from perfkitbenchmarker import vm_util from perfkitbenchmarker.providers.aws import util class LogGroup(resource.BaseResource): """Class representing a CloudWatch log group.""" def __init__(self, region, name, retention_in_days=7): super(LogGroup, self).__init__() self.region = region self.name = name self.retention_in_days = retention_in_days def <|fim_middle|>(self): """Create the log group.""" create_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'create-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(create_cmd) def _Delete(self): """Delete the log group.""" delete_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'delete-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(delete_cmd, raise_on_failure=False) def Exists(self): """Returns True if the log group exists.""" describe_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'describe-log-groups', '--log-group-name-prefix', self.name, '--no-paginate' ] stdout, _, _ = vm_util.IssueCommand(describe_cmd) log_groups = json.loads(stdout)['logGroups'] group = next((group for group in log_groups if group['logGroupName'] == self.name), None) return bool(group) def _PostCreate(self): """Set the retention policy.""" put_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'put-retention-policy', '--log-group-name', self.name, '--retention-in-days', str(self.retention_in_days) ] vm_util.IssueCommand(put_cmd) def GetLogs(region, stream_name, group_name, token=None): """Fetches the JSON formatted log stream starting at the token.""" get_cmd = util.AWS_PREFIX + [ '--region', region, 'logs', 'get-log-events', '--start-from-head', '--log-group-name', group_name, '--log-stream-name', stream_name, ] if token: get_cmd.extend(['--next-token', token]) stdout, _, _ = vm_util.IssueCommand(get_cmd) return json.loads(stdout) def GetLogStreamAsString(region, stream_name, log_group): """Returns the messages of the log stream as a string.""" log_lines = [] token = None events = [] while token is None or events: response = GetLogs(region, stream_name, log_group, token) events = response['events'] token = response['nextForwardToken'] for event in events: log_lines.append(event['message']) return '\n'.join(log_lines) <|fim▁end|>
_Create
<|file_name|>aws_logs.py<|end_file_name|><|fim▁begin|># Copyright 2018 PerfKitBenchmarker Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module containing classes related to AWS CloudWatch Logs.""" import json from perfkitbenchmarker import resource from perfkitbenchmarker import vm_util from perfkitbenchmarker.providers.aws import util class LogGroup(resource.BaseResource): """Class representing a CloudWatch log group.""" def __init__(self, region, name, retention_in_days=7): super(LogGroup, self).__init__() self.region = region self.name = name self.retention_in_days = retention_in_days def _Create(self): """Create the log group.""" create_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'create-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(create_cmd) def <|fim_middle|>(self): """Delete the log group.""" delete_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'delete-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(delete_cmd, raise_on_failure=False) def Exists(self): """Returns True if the log group exists.""" describe_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'describe-log-groups', '--log-group-name-prefix', self.name, '--no-paginate' ] stdout, _, _ = vm_util.IssueCommand(describe_cmd) log_groups = json.loads(stdout)['logGroups'] group = next((group for group in log_groups if group['logGroupName'] == self.name), None) return bool(group) def _PostCreate(self): """Set the retention policy.""" put_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'put-retention-policy', '--log-group-name', self.name, '--retention-in-days', str(self.retention_in_days) ] vm_util.IssueCommand(put_cmd) def GetLogs(region, stream_name, group_name, token=None): """Fetches the JSON formatted log stream starting at the token.""" get_cmd = util.AWS_PREFIX + [ '--region', region, 'logs', 'get-log-events', '--start-from-head', '--log-group-name', group_name, '--log-stream-name', stream_name, ] if token: get_cmd.extend(['--next-token', token]) stdout, _, _ = vm_util.IssueCommand(get_cmd) return json.loads(stdout) def GetLogStreamAsString(region, stream_name, log_group): """Returns the messages of the log stream as a string.""" log_lines = [] token = None events = [] while token is None or events: response = GetLogs(region, stream_name, log_group, token) events = response['events'] token = response['nextForwardToken'] for event in events: log_lines.append(event['message']) return '\n'.join(log_lines) <|fim▁end|>
_Delete
<|file_name|>aws_logs.py<|end_file_name|><|fim▁begin|># Copyright 2018 PerfKitBenchmarker Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module containing classes related to AWS CloudWatch Logs.""" import json from perfkitbenchmarker import resource from perfkitbenchmarker import vm_util from perfkitbenchmarker.providers.aws import util class LogGroup(resource.BaseResource): """Class representing a CloudWatch log group.""" def __init__(self, region, name, retention_in_days=7): super(LogGroup, self).__init__() self.region = region self.name = name self.retention_in_days = retention_in_days def _Create(self): """Create the log group.""" create_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'create-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(create_cmd) def _Delete(self): """Delete the log group.""" delete_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'delete-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(delete_cmd, raise_on_failure=False) def <|fim_middle|>(self): """Returns True if the log group exists.""" describe_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'describe-log-groups', '--log-group-name-prefix', self.name, '--no-paginate' ] stdout, _, _ = vm_util.IssueCommand(describe_cmd) log_groups = json.loads(stdout)['logGroups'] group = next((group for group in log_groups if group['logGroupName'] == self.name), None) return bool(group) def _PostCreate(self): """Set the retention policy.""" put_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'put-retention-policy', '--log-group-name', self.name, '--retention-in-days', str(self.retention_in_days) ] vm_util.IssueCommand(put_cmd) def GetLogs(region, stream_name, group_name, token=None): """Fetches the JSON formatted log stream starting at the token.""" get_cmd = util.AWS_PREFIX + [ '--region', region, 'logs', 'get-log-events', '--start-from-head', '--log-group-name', group_name, '--log-stream-name', stream_name, ] if token: get_cmd.extend(['--next-token', token]) stdout, _, _ = vm_util.IssueCommand(get_cmd) return json.loads(stdout) def GetLogStreamAsString(region, stream_name, log_group): """Returns the messages of the log stream as a string.""" log_lines = [] token = None events = [] while token is None or events: response = GetLogs(region, stream_name, log_group, token) events = response['events'] token = response['nextForwardToken'] for event in events: log_lines.append(event['message']) return '\n'.join(log_lines) <|fim▁end|>
Exists
<|file_name|>aws_logs.py<|end_file_name|><|fim▁begin|># Copyright 2018 PerfKitBenchmarker Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module containing classes related to AWS CloudWatch Logs.""" import json from perfkitbenchmarker import resource from perfkitbenchmarker import vm_util from perfkitbenchmarker.providers.aws import util class LogGroup(resource.BaseResource): """Class representing a CloudWatch log group.""" def __init__(self, region, name, retention_in_days=7): super(LogGroup, self).__init__() self.region = region self.name = name self.retention_in_days = retention_in_days def _Create(self): """Create the log group.""" create_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'create-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(create_cmd) def _Delete(self): """Delete the log group.""" delete_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'delete-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(delete_cmd, raise_on_failure=False) def Exists(self): """Returns True if the log group exists.""" describe_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'describe-log-groups', '--log-group-name-prefix', self.name, '--no-paginate' ] stdout, _, _ = vm_util.IssueCommand(describe_cmd) log_groups = json.loads(stdout)['logGroups'] group = next((group for group in log_groups if group['logGroupName'] == self.name), None) return bool(group) def <|fim_middle|>(self): """Set the retention policy.""" put_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'put-retention-policy', '--log-group-name', self.name, '--retention-in-days', str(self.retention_in_days) ] vm_util.IssueCommand(put_cmd) def GetLogs(region, stream_name, group_name, token=None): """Fetches the JSON formatted log stream starting at the token.""" get_cmd = util.AWS_PREFIX + [ '--region', region, 'logs', 'get-log-events', '--start-from-head', '--log-group-name', group_name, '--log-stream-name', stream_name, ] if token: get_cmd.extend(['--next-token', token]) stdout, _, _ = vm_util.IssueCommand(get_cmd) return json.loads(stdout) def GetLogStreamAsString(region, stream_name, log_group): """Returns the messages of the log stream as a string.""" log_lines = [] token = None events = [] while token is None or events: response = GetLogs(region, stream_name, log_group, token) events = response['events'] token = response['nextForwardToken'] for event in events: log_lines.append(event['message']) return '\n'.join(log_lines) <|fim▁end|>
_PostCreate
<|file_name|>aws_logs.py<|end_file_name|><|fim▁begin|># Copyright 2018 PerfKitBenchmarker Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module containing classes related to AWS CloudWatch Logs.""" import json from perfkitbenchmarker import resource from perfkitbenchmarker import vm_util from perfkitbenchmarker.providers.aws import util class LogGroup(resource.BaseResource): """Class representing a CloudWatch log group.""" def __init__(self, region, name, retention_in_days=7): super(LogGroup, self).__init__() self.region = region self.name = name self.retention_in_days = retention_in_days def _Create(self): """Create the log group.""" create_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'create-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(create_cmd) def _Delete(self): """Delete the log group.""" delete_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'delete-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(delete_cmd, raise_on_failure=False) def Exists(self): """Returns True if the log group exists.""" describe_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'describe-log-groups', '--log-group-name-prefix', self.name, '--no-paginate' ] stdout, _, _ = vm_util.IssueCommand(describe_cmd) log_groups = json.loads(stdout)['logGroups'] group = next((group for group in log_groups if group['logGroupName'] == self.name), None) return bool(group) def _PostCreate(self): """Set the retention policy.""" put_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'put-retention-policy', '--log-group-name', self.name, '--retention-in-days', str(self.retention_in_days) ] vm_util.IssueCommand(put_cmd) def <|fim_middle|>(region, stream_name, group_name, token=None): """Fetches the JSON formatted log stream starting at the token.""" get_cmd = util.AWS_PREFIX + [ '--region', region, 'logs', 'get-log-events', '--start-from-head', '--log-group-name', group_name, '--log-stream-name', stream_name, ] if token: get_cmd.extend(['--next-token', token]) stdout, _, _ = vm_util.IssueCommand(get_cmd) return json.loads(stdout) def GetLogStreamAsString(region, stream_name, log_group): """Returns the messages of the log stream as a string.""" log_lines = [] token = None events = [] while token is None or events: response = GetLogs(region, stream_name, log_group, token) events = response['events'] token = response['nextForwardToken'] for event in events: log_lines.append(event['message']) return '\n'.join(log_lines) <|fim▁end|>
GetLogs
<|file_name|>aws_logs.py<|end_file_name|><|fim▁begin|># Copyright 2018 PerfKitBenchmarker Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module containing classes related to AWS CloudWatch Logs.""" import json from perfkitbenchmarker import resource from perfkitbenchmarker import vm_util from perfkitbenchmarker.providers.aws import util class LogGroup(resource.BaseResource): """Class representing a CloudWatch log group.""" def __init__(self, region, name, retention_in_days=7): super(LogGroup, self).__init__() self.region = region self.name = name self.retention_in_days = retention_in_days def _Create(self): """Create the log group.""" create_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'create-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(create_cmd) def _Delete(self): """Delete the log group.""" delete_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'delete-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(delete_cmd, raise_on_failure=False) def Exists(self): """Returns True if the log group exists.""" describe_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'describe-log-groups', '--log-group-name-prefix', self.name, '--no-paginate' ] stdout, _, _ = vm_util.IssueCommand(describe_cmd) log_groups = json.loads(stdout)['logGroups'] group = next((group for group in log_groups if group['logGroupName'] == self.name), None) return bool(group) def _PostCreate(self): """Set the retention policy.""" put_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'put-retention-policy', '--log-group-name', self.name, '--retention-in-days', str(self.retention_in_days) ] vm_util.IssueCommand(put_cmd) def GetLogs(region, stream_name, group_name, token=None): """Fetches the JSON formatted log stream starting at the token.""" get_cmd = util.AWS_PREFIX + [ '--region', region, 'logs', 'get-log-events', '--start-from-head', '--log-group-name', group_name, '--log-stream-name', stream_name, ] if token: get_cmd.extend(['--next-token', token]) stdout, _, _ = vm_util.IssueCommand(get_cmd) return json.loads(stdout) def <|fim_middle|>(region, stream_name, log_group): """Returns the messages of the log stream as a string.""" log_lines = [] token = None events = [] while token is None or events: response = GetLogs(region, stream_name, log_group, token) events = response['events'] token = response['nextForwardToken'] for event in events: log_lines.append(event['message']) return '\n'.join(log_lines) <|fim▁end|>
GetLogStreamAsString
<|file_name|>experiments.py<|end_file_name|><|fim▁begin|># This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # experiments.py # Copyright (C) 2015 Fracpete (pythonwekawrapper at gmail dot com) import unittest import weka.core.jvm as jvm import weka.core.converters as converters import weka.classifiers as classifiers import weka.experiments as experiments import weka.plot.experiments as plot import wekatests.tests.weka_test as weka_test class TestExperiments(weka_test.WekaTest): <|fim▁hole|> datasets = [self.datafile("bolts.arff"), self.datafile("bodyfat.arff"), self.datafile("autoPrice.arff")] cls = [ classifiers.Classifier("weka.classifiers.trees.REPTree"), classifiers.Classifier("weka.classifiers.functions.LinearRegression"), classifiers.Classifier("weka.classifiers.functions.SMOreg"), ] outfile = self.tempfile("results-rs.arff") exp = experiments.SimpleRandomSplitExperiment( classification=False, runs=10, percentage=66.6, preserve_order=False, datasets=datasets, classifiers=cls, result=outfile) exp.setup() exp.run() # evaluate loader = converters.loader_for_file(outfile) data = loader.load_file(outfile) matrix = experiments.ResultMatrix("weka.experiment.ResultMatrixPlainText") tester = experiments.Tester("weka.experiment.PairedCorrectedTTester") tester.resultmatrix = matrix comparison_col = data.attribute_by_name("Correlation_coefficient").index tester.instances = data tester.header(comparison_col) tester.multi_resultset_full(0, comparison_col) # plot plot.plot_experiment(matrix, title="Random split (w/ StdDev)", measure="Correlation coefficient", show_stdev=True, wait=False) plot.plot_experiment(matrix, title="Random split", measure="Correlation coefficient", wait=False) def suite(): """ Returns the test suite. :return: the test suite :rtype: unittest.TestSuite """ return unittest.TestLoader().loadTestsFromTestCase(TestExperiments) if __name__ == '__main__': jvm.start() unittest.TextTestRunner().run(suite()) jvm.stop()<|fim▁end|>
def test_plot_experiment(self): """ Tests the plot_experiment method. """
<|file_name|>experiments.py<|end_file_name|><|fim▁begin|># This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # experiments.py # Copyright (C) 2015 Fracpete (pythonwekawrapper at gmail dot com) import unittest import weka.core.jvm as jvm import weka.core.converters as converters import weka.classifiers as classifiers import weka.experiments as experiments import weka.plot.experiments as plot import wekatests.tests.weka_test as weka_test class TestExperiments(weka_test.WekaTest): <|fim_middle|> def suite(): """ Returns the test suite. :return: the test suite :rtype: unittest.TestSuite """ return unittest.TestLoader().loadTestsFromTestCase(TestExperiments) if __name__ == '__main__': jvm.start() unittest.TextTestRunner().run(suite()) jvm.stop() <|fim▁end|>
def test_plot_experiment(self): """ Tests the plot_experiment method. """ datasets = [self.datafile("bolts.arff"), self.datafile("bodyfat.arff"), self.datafile("autoPrice.arff")] cls = [ classifiers.Classifier("weka.classifiers.trees.REPTree"), classifiers.Classifier("weka.classifiers.functions.LinearRegression"), classifiers.Classifier("weka.classifiers.functions.SMOreg"), ] outfile = self.tempfile("results-rs.arff") exp = experiments.SimpleRandomSplitExperiment( classification=False, runs=10, percentage=66.6, preserve_order=False, datasets=datasets, classifiers=cls, result=outfile) exp.setup() exp.run() # evaluate loader = converters.loader_for_file(outfile) data = loader.load_file(outfile) matrix = experiments.ResultMatrix("weka.experiment.ResultMatrixPlainText") tester = experiments.Tester("weka.experiment.PairedCorrectedTTester") tester.resultmatrix = matrix comparison_col = data.attribute_by_name("Correlation_coefficient").index tester.instances = data tester.header(comparison_col) tester.multi_resultset_full(0, comparison_col) # plot plot.plot_experiment(matrix, title="Random split (w/ StdDev)", measure="Correlation coefficient", show_stdev=True, wait=False) plot.plot_experiment(matrix, title="Random split", measure="Correlation coefficient", wait=False)
<|file_name|>experiments.py<|end_file_name|><|fim▁begin|># This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # experiments.py # Copyright (C) 2015 Fracpete (pythonwekawrapper at gmail dot com) import unittest import weka.core.jvm as jvm import weka.core.converters as converters import weka.classifiers as classifiers import weka.experiments as experiments import weka.plot.experiments as plot import wekatests.tests.weka_test as weka_test class TestExperiments(weka_test.WekaTest): def test_plot_experiment(self): <|fim_middle|> def suite(): """ Returns the test suite. :return: the test suite :rtype: unittest.TestSuite """ return unittest.TestLoader().loadTestsFromTestCase(TestExperiments) if __name__ == '__main__': jvm.start() unittest.TextTestRunner().run(suite()) jvm.stop() <|fim▁end|>
""" Tests the plot_experiment method. """ datasets = [self.datafile("bolts.arff"), self.datafile("bodyfat.arff"), self.datafile("autoPrice.arff")] cls = [ classifiers.Classifier("weka.classifiers.trees.REPTree"), classifiers.Classifier("weka.classifiers.functions.LinearRegression"), classifiers.Classifier("weka.classifiers.functions.SMOreg"), ] outfile = self.tempfile("results-rs.arff") exp = experiments.SimpleRandomSplitExperiment( classification=False, runs=10, percentage=66.6, preserve_order=False, datasets=datasets, classifiers=cls, result=outfile) exp.setup() exp.run() # evaluate loader = converters.loader_for_file(outfile) data = loader.load_file(outfile) matrix = experiments.ResultMatrix("weka.experiment.ResultMatrixPlainText") tester = experiments.Tester("weka.experiment.PairedCorrectedTTester") tester.resultmatrix = matrix comparison_col = data.attribute_by_name("Correlation_coefficient").index tester.instances = data tester.header(comparison_col) tester.multi_resultset_full(0, comparison_col) # plot plot.plot_experiment(matrix, title="Random split (w/ StdDev)", measure="Correlation coefficient", show_stdev=True, wait=False) plot.plot_experiment(matrix, title="Random split", measure="Correlation coefficient", wait=False)
<|file_name|>experiments.py<|end_file_name|><|fim▁begin|># This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # experiments.py # Copyright (C) 2015 Fracpete (pythonwekawrapper at gmail dot com) import unittest import weka.core.jvm as jvm import weka.core.converters as converters import weka.classifiers as classifiers import weka.experiments as experiments import weka.plot.experiments as plot import wekatests.tests.weka_test as weka_test class TestExperiments(weka_test.WekaTest): def test_plot_experiment(self): """ Tests the plot_experiment method. """ datasets = [self.datafile("bolts.arff"), self.datafile("bodyfat.arff"), self.datafile("autoPrice.arff")] cls = [ classifiers.Classifier("weka.classifiers.trees.REPTree"), classifiers.Classifier("weka.classifiers.functions.LinearRegression"), classifiers.Classifier("weka.classifiers.functions.SMOreg"), ] outfile = self.tempfile("results-rs.arff") exp = experiments.SimpleRandomSplitExperiment( classification=False, runs=10, percentage=66.6, preserve_order=False, datasets=datasets, classifiers=cls, result=outfile) exp.setup() exp.run() # evaluate loader = converters.loader_for_file(outfile) data = loader.load_file(outfile) matrix = experiments.ResultMatrix("weka.experiment.ResultMatrixPlainText") tester = experiments.Tester("weka.experiment.PairedCorrectedTTester") tester.resultmatrix = matrix comparison_col = data.attribute_by_name("Correlation_coefficient").index tester.instances = data tester.header(comparison_col) tester.multi_resultset_full(0, comparison_col) # plot plot.plot_experiment(matrix, title="Random split (w/ StdDev)", measure="Correlation coefficient", show_stdev=True, wait=False) plot.plot_experiment(matrix, title="Random split", measure="Correlation coefficient", wait=False) def suite(): <|fim_middle|> if __name__ == '__main__': jvm.start() unittest.TextTestRunner().run(suite()) jvm.stop() <|fim▁end|>
""" Returns the test suite. :return: the test suite :rtype: unittest.TestSuite """ return unittest.TestLoader().loadTestsFromTestCase(TestExperiments)
<|file_name|>experiments.py<|end_file_name|><|fim▁begin|># This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # experiments.py # Copyright (C) 2015 Fracpete (pythonwekawrapper at gmail dot com) import unittest import weka.core.jvm as jvm import weka.core.converters as converters import weka.classifiers as classifiers import weka.experiments as experiments import weka.plot.experiments as plot import wekatests.tests.weka_test as weka_test class TestExperiments(weka_test.WekaTest): def test_plot_experiment(self): """ Tests the plot_experiment method. """ datasets = [self.datafile("bolts.arff"), self.datafile("bodyfat.arff"), self.datafile("autoPrice.arff")] cls = [ classifiers.Classifier("weka.classifiers.trees.REPTree"), classifiers.Classifier("weka.classifiers.functions.LinearRegression"), classifiers.Classifier("weka.classifiers.functions.SMOreg"), ] outfile = self.tempfile("results-rs.arff") exp = experiments.SimpleRandomSplitExperiment( classification=False, runs=10, percentage=66.6, preserve_order=False, datasets=datasets, classifiers=cls, result=outfile) exp.setup() exp.run() # evaluate loader = converters.loader_for_file(outfile) data = loader.load_file(outfile) matrix = experiments.ResultMatrix("weka.experiment.ResultMatrixPlainText") tester = experiments.Tester("weka.experiment.PairedCorrectedTTester") tester.resultmatrix = matrix comparison_col = data.attribute_by_name("Correlation_coefficient").index tester.instances = data tester.header(comparison_col) tester.multi_resultset_full(0, comparison_col) # plot plot.plot_experiment(matrix, title="Random split (w/ StdDev)", measure="Correlation coefficient", show_stdev=True, wait=False) plot.plot_experiment(matrix, title="Random split", measure="Correlation coefficient", wait=False) def suite(): """ Returns the test suite. :return: the test suite :rtype: unittest.TestSuite """ return unittest.TestLoader().loadTestsFromTestCase(TestExperiments) if __name__ == '__main__': <|fim_middle|> <|fim▁end|>
jvm.start() unittest.TextTestRunner().run(suite()) jvm.stop()
<|file_name|>experiments.py<|end_file_name|><|fim▁begin|># This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # experiments.py # Copyright (C) 2015 Fracpete (pythonwekawrapper at gmail dot com) import unittest import weka.core.jvm as jvm import weka.core.converters as converters import weka.classifiers as classifiers import weka.experiments as experiments import weka.plot.experiments as plot import wekatests.tests.weka_test as weka_test class TestExperiments(weka_test.WekaTest): def <|fim_middle|>(self): """ Tests the plot_experiment method. """ datasets = [self.datafile("bolts.arff"), self.datafile("bodyfat.arff"), self.datafile("autoPrice.arff")] cls = [ classifiers.Classifier("weka.classifiers.trees.REPTree"), classifiers.Classifier("weka.classifiers.functions.LinearRegression"), classifiers.Classifier("weka.classifiers.functions.SMOreg"), ] outfile = self.tempfile("results-rs.arff") exp = experiments.SimpleRandomSplitExperiment( classification=False, runs=10, percentage=66.6, preserve_order=False, datasets=datasets, classifiers=cls, result=outfile) exp.setup() exp.run() # evaluate loader = converters.loader_for_file(outfile) data = loader.load_file(outfile) matrix = experiments.ResultMatrix("weka.experiment.ResultMatrixPlainText") tester = experiments.Tester("weka.experiment.PairedCorrectedTTester") tester.resultmatrix = matrix comparison_col = data.attribute_by_name("Correlation_coefficient").index tester.instances = data tester.header(comparison_col) tester.multi_resultset_full(0, comparison_col) # plot plot.plot_experiment(matrix, title="Random split (w/ StdDev)", measure="Correlation coefficient", show_stdev=True, wait=False) plot.plot_experiment(matrix, title="Random split", measure="Correlation coefficient", wait=False) def suite(): """ Returns the test suite. :return: the test suite :rtype: unittest.TestSuite """ return unittest.TestLoader().loadTestsFromTestCase(TestExperiments) if __name__ == '__main__': jvm.start() unittest.TextTestRunner().run(suite()) jvm.stop() <|fim▁end|>
test_plot_experiment
<|file_name|>experiments.py<|end_file_name|><|fim▁begin|># This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # experiments.py # Copyright (C) 2015 Fracpete (pythonwekawrapper at gmail dot com) import unittest import weka.core.jvm as jvm import weka.core.converters as converters import weka.classifiers as classifiers import weka.experiments as experiments import weka.plot.experiments as plot import wekatests.tests.weka_test as weka_test class TestExperiments(weka_test.WekaTest): def test_plot_experiment(self): """ Tests the plot_experiment method. """ datasets = [self.datafile("bolts.arff"), self.datafile("bodyfat.arff"), self.datafile("autoPrice.arff")] cls = [ classifiers.Classifier("weka.classifiers.trees.REPTree"), classifiers.Classifier("weka.classifiers.functions.LinearRegression"), classifiers.Classifier("weka.classifiers.functions.SMOreg"), ] outfile = self.tempfile("results-rs.arff") exp = experiments.SimpleRandomSplitExperiment( classification=False, runs=10, percentage=66.6, preserve_order=False, datasets=datasets, classifiers=cls, result=outfile) exp.setup() exp.run() # evaluate loader = converters.loader_for_file(outfile) data = loader.load_file(outfile) matrix = experiments.ResultMatrix("weka.experiment.ResultMatrixPlainText") tester = experiments.Tester("weka.experiment.PairedCorrectedTTester") tester.resultmatrix = matrix comparison_col = data.attribute_by_name("Correlation_coefficient").index tester.instances = data tester.header(comparison_col) tester.multi_resultset_full(0, comparison_col) # plot plot.plot_experiment(matrix, title="Random split (w/ StdDev)", measure="Correlation coefficient", show_stdev=True, wait=False) plot.plot_experiment(matrix, title="Random split", measure="Correlation coefficient", wait=False) def <|fim_middle|>(): """ Returns the test suite. :return: the test suite :rtype: unittest.TestSuite """ return unittest.TestLoader().loadTestsFromTestCase(TestExperiments) if __name__ == '__main__': jvm.start() unittest.TextTestRunner().run(suite()) jvm.stop() <|fim▁end|>
suite
<|file_name|>molt_app.py<|end_file_name|><|fim▁begin|>"""Molt Web API with Interface.""" import re import redis import docker import subprocess<|fim▁hole|>import shlex import requests import sys import argparse from flask import Flask, Response, render_template, abort, request from molt import Molt, MoltError app = Flask(__name__) # コマンドライン引数のパース parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', help='config file path') args = parser.parse_args() if args.config: cfg_file = args.config else: cfg_file = 'config/molt_app.cfg' if not os.path.exists(cfg_file): app.logger.error("{} が存在しません".format(cfg_file)) sys.exit(1) app.config.from_pyfile(cfg_file, silent=True) @app.route('/<virtual_host>', strict_slashes=False) def index(virtual_host): """Moltの実行をプレビューするページ.""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) vhost = {'rev': rev, 'repo': repo, 'user': user, 'full': virtual_host} redirect_url = '//{}.{}/'.format(virtual_host, app.config['BASE_DOMAIN']) return render_template('index.html', vhost=vhost, redirect_url=redirect_url) @app.route('/molt/<virtual_host>', methods=['GET'], strict_slashes=False) def molt(virtual_host): """Moltの実行をストリーミングする(Server-Sent Eventを使ったAPI).""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) m = Molt(rev, repo, user, app.config['BASE_DOMAIN'], app.config['GITHUB_USER'], app.config['GITHUB_TOKEN']) r = redis.StrictRedis(host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT']) def generate(m, r): """Dockerイメージ立ち上げ(ストリーミングするための関数). git clone から docker-compose upまでの一連の処理のSTDIOの送信と、Dockerイメージ の情報取得・設定をする """ # コマンド群の実行 try: for row in m.molt(): row = row.decode() data = row.split('\r')[-1] # CRのみの行は保留されるので取り除く yield event_stream_parser(data) except MoltError as e: yield event_stream_parser(e, event='failure') except Exception: yield event_stream_parser('Molt内部でエラーが発生しました。終了します...', event='failure') else: # RedisへIPアドレスとバーチャルホストの対応を書き込む r.hset('mirror-store', virtual_host, m.get_container_ip()) yield event_stream_parser('', event='success') return Response(generate(m, r), mimetype='text/event-stream') @app.route('/favicon.ico') def favicon(): """favicon.ico.""" abort(404) @app.template_filter('base_domain') def base_domain_filter(path): """Staticファイルを呼び出す際のドメインを指定する.""" return '//' + app.config['BASE_DOMAIN'] + ':' + str(app.config['PORT']) + \ '/' + path @app.route("/hook", methods=['POST']) def hook(): event = request.headers["X-GitHub-Event"] req = request.json if event != "pull_request": return "ok", 200 elif req["action"] not in {"opened", "synchronize"}: return "ok", 200 pr = req["pull_request"] pr_url = pr["comments_url"] pr_sha = pr["head"]["sha"][:7] pr_reponame = pr["head"]["repo"]["name"] pr_owner = pr["head"]["repo"]["owner"]["login"] payload = { "event": "COMMENT", "body": "Launched the preview environment!\nhttp://{}.{}.{}.{}\ ".format(pr_sha, pr_reponame, pr_owner, app.config["BASE_DOMAIN"]), } headers = { "Accept": "application/vnd.github.v3+json", "Content-Type": "application/json", "Authorization": "token {}".format(app.config["GITHUB_TOKEN"]), } requests.post( pr_url, json=payload, headers=headers, ) return "ok", 200 def virtual_host_parse(virtual_host): """Virtual_hostの文字列を 'rev', 'repo', 'user' に分割する. e.g.(1) "host.repo.sitory.user" => "host", "repo.sitory", "user" e.g.(2) "host.repository.user" => "host", "repository", "user" """ p = re.compile(r'(?P<rev>^.+?)\.(?P<repo>.+)\.(?P<user>.+)$') m = p.search(virtual_host) return m.group('rev'), m.group('repo'), m.group('user') def event_stream_parser(data, event=None, id=None, retry=None): """Server-Sent Event 形式へのパーサ.""" event_stream = '' if event: event_stream += 'event: {}\n'.format(event) event_stream += 'data: {}\n'.format(data) if id: event_stream += 'id: {}\n'.format(id) if retry: event_stream += 'retry: {}\n'.format(id) event_stream += '\n' return event_stream if __name__ == '__main__': # RSA鍵の生成 user = os.getenv('USER') ssh_key_path = os.path.expanduser("~")+"/.ssh/molt_deploy_key" if not os.path.exists(ssh_key_path): command = 'ssh-keygen -t rsa -N "" -f {}'.format(ssh_key_path) command = shlex.split(command) subprocess.Popen(command) # Dockerネットワークの作成 clinet = docker.from_env() networks = clinet.networks.list() if 'molt-network' not in [network.name for network in networks]: command = 'docker network create --subnet=172.31.255.0/24 \ --ip-range=172.31.255.0/24 --gateway=172.31.255.254 \ -o "com.docker.network.bridge.host_binding_ipv4"="0.0.0.0" \ molt-network' command = shlex.split(command) subprocess.Popen(command) app.run(host=app.config['HOST'], port=app.config['PORT'])<|fim▁end|>
import os
<|file_name|>molt_app.py<|end_file_name|><|fim▁begin|>"""Molt Web API with Interface.""" import re import redis import docker import subprocess import os import shlex import requests import sys import argparse from flask import Flask, Response, render_template, abort, request from molt import Molt, MoltError app = Flask(__name__) # コマンドライン引数のパース parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', help='config file path') args = parser.parse_args() if args.config: cfg_file = args.config else: cfg_file = 'config/molt_app.cfg' if not os.path.exists(cfg_file): app.logger.error("{} が存在しません".format(cfg_file)) sys.exit(1) app.config.from_pyfile(cfg_file, silent=True) @app.route('/<virtual_host>', strict_slashes=False) def index(virtual_host): """Moltの実行をプレビューするページ.""" try: <|fim_middle|> s=False) def molt(virtual_host): """Moltの実行をストリーミングする(Server-Sent Eventを使ったAPI).""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) m = Molt(rev, repo, user, app.config['BASE_DOMAIN'], app.config['GITHUB_USER'], app.config['GITHUB_TOKEN']) r = redis.StrictRedis(host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT']) def generate(m, r): """Dockerイメージ立ち上げ(ストリーミングするための関数). git clone から docker-compose upまでの一連の処理のSTDIOの送信と、Dockerイメージ の情報取得・設定をする """ # コマンド群の実行 try: for row in m.molt(): row = row.decode() data = row.split('\r')[-1] # CRのみの行は保留されるので取り除く yield event_stream_parser(data) except MoltError as e: yield event_stream_parser(e, event='failure') except Exception: yield event_stream_parser('Molt内部でエラーが発生しました。終了します...', event='failure') else: # RedisへIPアドレスとバーチャルホストの対応を書き込む r.hset('mirror-store', virtual_host, m.get_container_ip()) yield event_stream_parser('', event='success') return Response(generate(m, r), mimetype='text/event-stream') @app.route('/favicon.ico') def favicon(): """favicon.ico.""" abort(404) @app.template_filter('base_domain') def base_domain_filter(path): """Staticファイルを呼び出す際のドメインを指定する.""" return '//' + app.config['BASE_DOMAIN'] + ':' + str(app.config['PORT']) + \ '/' + path @app.route("/hook", methods=['POST']) def hook(): event = request.headers["X-GitHub-Event"] req = request.json if event != "pull_request": return "ok", 200 elif req["action"] not in {"opened", "synchronize"}: return "ok", 200 pr = req["pull_request"] pr_url = pr["comments_url"] pr_sha = pr["head"]["sha"][:7] pr_reponame = pr["head"]["repo"]["name"] pr_owner = pr["head"]["repo"]["owner"]["login"] payload = { "event": "COMMENT", "body": "Launched the preview environment!\nhttp://{}.{}.{}.{}\ ".format(pr_sha, pr_reponame, pr_owner, app.config["BASE_DOMAIN"]), } headers = { "Accept": "application/vnd.github.v3+json", "Content-Type": "application/json", "Authorization": "token {}".format(app.config["GITHUB_TOKEN"]), } requests.post( pr_url, json=payload, headers=headers, ) return "ok", 200 def virtual_host_parse(virtual_host): """Virtual_hostの文字列を 'rev', 'repo', 'user' に分割する. e.g.(1) "host.repo.sitory.user" => "host", "repo.sitory", "user" e.g.(2) "host.repository.user" => "host", "repository", "user" """ p = re.compile(r'(?P<rev>^.+?)\.(?P<repo>.+)\.(?P<user>.+)$') m = p.search(virtual_host) return m.group('rev'), m.group('repo'), m.group('user') def event_stream_parser(data, event=None, id=None, retry=None): """Server-Sent Event 形式へのパーサ.""" event_stream = '' if event: event_stream += 'event: {}\n'.format(event) event_stream += 'data: {}\n'.format(data) if id: event_stream += 'id: {}\n'.format(id) if retry: event_stream += 'retry: {}\n'.format(id) event_stream += '\n' return event_stream if __name__ == '__main__': # RSA鍵の生成 user = os.getenv('USER') ssh_key_path = os.path.expanduser("~")+"/.ssh/molt_deploy_key" if not os.path.exists(ssh_key_path): command = 'ssh-keygen -t rsa -N "" -f {}'.format(ssh_key_path) command = shlex.split(command) subprocess.Popen(command) # Dockerネットワークの作成 clinet = docker.from_env() networks = clinet.networks.list() if 'molt-network' not in [network.name for network in networks]: command = 'docker network create --subnet=172.31.255.0/24 \ --ip-range=172.31.255.0/24 --gateway=172.31.255.254 \ -o "com.docker.network.bridge.host_binding_ipv4"="0.0.0.0" \ molt-network' command = shlex.split(command) subprocess.Popen(command) app.run(host=app.config['HOST'], port=app.config['PORT']) <|fim▁end|>
rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) vhost = {'rev': rev, 'repo': repo, 'user': user, 'full': virtual_host} redirect_url = '//{}.{}/'.format(virtual_host, app.config['BASE_DOMAIN']) return render_template('index.html', vhost=vhost, redirect_url=redirect_url) @app.route('/molt/<virtual_host>', methods=['GET'], strict_slashe
<|file_name|>molt_app.py<|end_file_name|><|fim▁begin|>"""Molt Web API with Interface.""" import re import redis import docker import subprocess import os import shlex import requests import sys import argparse from flask import Flask, Response, render_template, abort, request from molt import Molt, MoltError app = Flask(__name__) # コマンドライン引数のパース parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', help='config file path') args = parser.parse_args() if args.config: cfg_file = args.config else: cfg_file = 'config/molt_app.cfg' if not os.path.exists(cfg_file): app.logger.error("{} が存在しません".format(cfg_file)) sys.exit(1) app.config.from_pyfile(cfg_file, silent=True) @app.route('/<virtual_host>', strict_slashes=False) def index(virtual_host): """Moltの実行をプレビューするページ.""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) vhost = {'rev': rev, 'repo': repo, 'user': user, 'full': virtual_host} redirect_url = '//{}.{}/'.format(virtual_host, app.config['BASE_DOMAIN']) return render_template('index.html', vhost=vhost, redirect_url=redirect_url) @app.route('/molt/<virtual_host>', methods=['GET'], strict_slashes=False) def molt(virtual_host): """Moltの実行をストリーミングする(Server-Sent Eventを使ったAPI).""" try: <|fim_middle|> : event = request.headers["X-GitHub-Event"] req = request.json if event != "pull_request": return "ok", 200 elif req["action"] not in {"opened", "synchronize"}: return "ok", 200 pr = req["pull_request"] pr_url = pr["comments_url"] pr_sha = pr["head"]["sha"][:7] pr_reponame = pr["head"]["repo"]["name"] pr_owner = pr["head"]["repo"]["owner"]["login"] payload = { "event": "COMMENT", "body": "Launched the preview environment!\nhttp://{}.{}.{}.{}\ ".format(pr_sha, pr_reponame, pr_owner, app.config["BASE_DOMAIN"]), } headers = { "Accept": "application/vnd.github.v3+json", "Content-Type": "application/json", "Authorization": "token {}".format(app.config["GITHUB_TOKEN"]), } requests.post( pr_url, json=payload, headers=headers, ) return "ok", 200 def virtual_host_parse(virtual_host): """Virtual_hostの文字列を 'rev', 'repo', 'user' に分割する. e.g.(1) "host.repo.sitory.user" => "host", "repo.sitory", "user" e.g.(2) "host.repository.user" => "host", "repository", "user" """ p = re.compile(r'(?P<rev>^.+?)\.(?P<repo>.+)\.(?P<user>.+)$') m = p.search(virtual_host) return m.group('rev'), m.group('repo'), m.group('user') def event_stream_parser(data, event=None, id=None, retry=None): """Server-Sent Event 形式へのパーサ.""" event_stream = '' if event: event_stream += 'event: {}\n'.format(event) event_stream += 'data: {}\n'.format(data) if id: event_stream += 'id: {}\n'.format(id) if retry: event_stream += 'retry: {}\n'.format(id) event_stream += '\n' return event_stream if __name__ == '__main__': # RSA鍵の生成 user = os.getenv('USER') ssh_key_path = os.path.expanduser("~")+"/.ssh/molt_deploy_key" if not os.path.exists(ssh_key_path): command = 'ssh-keygen -t rsa -N "" -f {}'.format(ssh_key_path) command = shlex.split(command) subprocess.Popen(command) # Dockerネットワークの作成 clinet = docker.from_env() networks = clinet.networks.list() if 'molt-network' not in [network.name for network in networks]: command = 'docker network create --subnet=172.31.255.0/24 \ --ip-range=172.31.255.0/24 --gateway=172.31.255.254 \ -o "com.docker.network.bridge.host_binding_ipv4"="0.0.0.0" \ molt-network' command = shlex.split(command) subprocess.Popen(command) app.run(host=app.config['HOST'], port=app.config['PORT']) <|fim▁end|>
rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) m = Molt(rev, repo, user, app.config['BASE_DOMAIN'], app.config['GITHUB_USER'], app.config['GITHUB_TOKEN']) r = redis.StrictRedis(host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT']) def generate(m, r): """Dockerイメージ立ち上げ(ストリーミングするための関数). git clone から docker-compose upまでの一連の処理のSTDIOの送信と、Dockerイメージ の情報取得・設定をする """ # コマンド群の実行 try: for row in m.molt(): row = row.decode() data = row.split('\r')[-1] # CRのみの行は保留されるので取り除く yield event_stream_parser(data) except MoltError as e: yield event_stream_parser(e, event='failure') except Exception: yield event_stream_parser('Molt内部でエラーが発生しました。終了します...', event='failure') else: # RedisへIPアドレスとバーチャルホストの対応を書き込む r.hset('mirror-store', virtual_host, m.get_container_ip()) yield event_stream_parser('', event='success') return Response(generate(m, r), mimetype='text/event-stream') @app.route('/favicon.ico') def favicon(): """favicon.ico.""" abort(404) @app.template_filter('base_domain') def base_domain_filter(path): """Staticファイルを呼び出す際のドメインを指定する.""" return '//' + app.config['BASE_DOMAIN'] + ':' + str(app.config['PORT']) + \ '/' + path @app.route("/hook", methods=['POST']) def hook()
<|file_name|>molt_app.py<|end_file_name|><|fim▁begin|>"""Molt Web API with Interface.""" import re import redis import docker import subprocess import os import shlex import requests import sys import argparse from flask import Flask, Response, render_template, abort, request from molt import Molt, MoltError app = Flask(__name__) # コマンドライン引数のパース parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', help='config file path') args = parser.parse_args() if args.config: cfg_file = args.config else: cfg_file = 'config/molt_app.cfg' if not os.path.exists(cfg_file): app.logger.error("{} が存在しません".format(cfg_file)) sys.exit(1) app.config.from_pyfile(cfg_file, silent=True) @app.route('/<virtual_host>', strict_slashes=False) def index(virtual_host): """Moltの実行をプレビューするページ.""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) vhost = {'rev': rev, 'repo': repo, 'user': user, 'full': virtual_host} redirect_url = '//{}.{}/'.format(virtual_host, app.config['BASE_DOMAIN']) return render_template('index.html', vhost=vhost, redirect_url=redirect_url) @app.route('/molt/<virtual_host>', methods=['GET'], strict_slashes=False) def molt(virtual_host): """Moltの実行をストリーミングする(Server-Sent Eventを使ったAPI).""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) m = Molt(rev, repo, user, app.config['BASE_DOMAIN'], app.config['GITHUB_USER'], app.config['GITHUB_TOKEN']) r = redis.StrictRedis(host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT']) def generate(m, r): """Dockerイメージ立ち上げ(ストリーミングするための関数). git clone から docker-compose upまでの一連の処理のSTDIOの送信と、Dockerイメー<|fim_middle|> '/' + path @app.route("/hook", methods=['POST']) def hook(): event = request.headers["X-GitHub-Event"] req = request.json if event != "pull_request": return "ok", 200 elif req["action"] not in {"opened", "synchronize"}: return "ok", 200 pr = req["pull_request"] pr_url = pr["comments_url"] pr_sha = pr["head"]["sha"][:7] pr_reponame = pr["head"]["repo"]["name"] pr_owner = pr["head"]["repo"]["owner"]["login"] payload = { "event": "COMMENT", "body": "Launched the preview environment!\nhttp://{}.{}.{}.{}\ ".format(pr_sha, pr_reponame, pr_owner, app.config["BASE_DOMAIN"]), } headers = { "Accept": "application/vnd.github.v3+json", "Content-Type": "application/json", "Authorization": "token {}".format(app.config["GITHUB_TOKEN"]), } requests.post( pr_url, json=payload, headers=headers, ) return "ok", 200 def virtual_host_parse(virtual_host): """Virtual_hostの文字列を 'rev', 'repo', 'user' に分割する. e.g.(1) "host.repo.sitory.user" => "host", "repo.sitory", "user" e.g.(2) "host.repository.user" => "host", "repository", "user" """ p = re.compile(r'(?P<rev>^.+?)\.(?P<repo>.+)\.(?P<user>.+)$') m = p.search(virtual_host) return m.group('rev'), m.group('repo'), m.group('user') def event_stream_parser(data, event=None, id=None, retry=None): """Server-Sent Event 形式へのパーサ.""" event_stream = '' if event: event_stream += 'event: {}\n'.format(event) event_stream += 'data: {}\n'.format(data) if id: event_stream += 'id: {}\n'.format(id) if retry: event_stream += 'retry: {}\n'.format(id) event_stream += '\n' return event_stream if __name__ == '__main__': # RSA鍵の生成 user = os.getenv('USER') ssh_key_path = os.path.expanduser("~")+"/.ssh/molt_deploy_key" if not os.path.exists(ssh_key_path): command = 'ssh-keygen -t rsa -N "" -f {}'.format(ssh_key_path) command = shlex.split(command) subprocess.Popen(command) # Dockerネットワークの作成 clinet = docker.from_env() networks = clinet.networks.list() if 'molt-network' not in [network.name for network in networks]: command = 'docker network create --subnet=172.31.255.0/24 \ --ip-range=172.31.255.0/24 --gateway=172.31.255.254 \ -o "com.docker.network.bridge.host_binding_ipv4"="0.0.0.0" \ molt-network' command = shlex.split(command) subprocess.Popen(command) app.run(host=app.config['HOST'], port=app.config['PORT']) <|fim▁end|>
ジ の情報取得・設定をする """ # コマンド群の実行 try: for row in m.molt(): row = row.decode() data = row.split('\r')[-1] # CRのみの行は保留されるので取り除く yield event_stream_parser(data) except MoltError as e: yield event_stream_parser(e, event='failure') except Exception: yield event_stream_parser('Molt内部でエラーが発生しました。終了します...', event='failure') else: # RedisへIPアドレスとバーチャルホストの対応を書き込む r.hset('mirror-store', virtual_host, m.get_container_ip()) yield event_stream_parser('', event='success') return Response(generate(m, r), mimetype='text/event-stream') @app.route('/favicon.ico') def favicon(): """favicon.ico.""" abort(404) @app.template_filter('base_domain') def base_domain_filter(path): """Staticファイルを呼び出す際のドメインを指定する.""" return '//' + app.config['BASE_DOMAIN'] + ':' + str(app.config['PORT']) + \
<|file_name|>molt_app.py<|end_file_name|><|fim▁begin|>"""Molt Web API with Interface.""" import re import redis import docker import subprocess import os import shlex import requests import sys import argparse from flask import Flask, Response, render_template, abort, request from molt import Molt, MoltError app = Flask(__name__) # コマンドライン引数のパース parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', help='config file path') args = parser.parse_args() if args.config: cfg_file = args.config else: cfg_file = 'config/molt_app.cfg' if not os.path.exists(cfg_file): app.logger.error("{} が存在しません".format(cfg_file)) sys.exit(1) app.config.from_pyfile(cfg_file, silent=True) @app.route('/<virtual_host>', strict_slashes=False) def index(virtual_host): """Moltの実行をプレビューするページ.""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) vhost = {'rev': rev, 'repo': repo, 'user': user, 'full': virtual_host} redirect_url = '//{}.{}/'.format(virtual_host, app.config['BASE_DOMAIN']) return render_template('index.html', vhost=vhost, redirect_url=redirect_url) @app.route('/molt/<virtual_host>', methods=['GET'], strict_slashes=False) def molt(virtual_host): """Moltの実行をストリーミングする(Server-Sent Eventを使ったAPI).""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) m = Molt(rev, repo, user, app.config['BASE_DOMAIN'], app.config['GITHUB_USER'], app.config['GITHUB_TOKEN']) r = redis.StrictRedis(host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT']) def generate(m, r): """Dockerイメージ立ち上げ(ストリーミングするための関数). git clone から docker-compose upまでの一連の処理のSTDIOの送信と、Dockerイメージ の情報取得・設定をする """ # コマンド群の実行 try: for row in m.molt(): row = row.decode() data = row.split('\r')[-1] # CRのみの行は保留されるので取り除く yield event_stream_parser(data) except MoltError as e: yield event_stream_parser(e, event='failure') except Exception: yield event_stream_parser('Molt内部でエラーが発生しました。終了します...', event='failure') else: # RedisへIPアドレスとバーチャルホストの対応を書き込む r.hset('mirror-store', virtual_host, m.get_container_ip()) yield event_stream_parser('', event='success') return Response(generate(m, r), mimetype='text/event-stream') @app.route('/favicon.ico') def favicon(): """favicon.ico.""" abort(404) @app.template_filter('base_domain') def base_domain_filter(path): """Staticファイルを呼び出す際のドメインを指定する.""" return '//' + app.config['BASE_DOMAIN'] + ':' + str(app.config['PORT']) + \ '/' + path @app.route("/hook", methods=['POST']) def hook(): event = request.headers["X-GitHub-Event"] <|fim_middle|> t != "pull_request": return "ok", 200 elif req["action"] not in {"opened", "synchronize"}: return "ok", 200 pr = req["pull_request"] pr_url = pr["comments_url"] pr_sha = pr["head"]["sha"][:7] pr_reponame = pr["head"]["repo"]["name"] pr_owner = pr["head"]["repo"]["owner"]["login"] payload = { "event": "COMMENT", "body": "Launched the preview environment!\nhttp://{}.{}.{}.{}\ ".format(pr_sha, pr_reponame, pr_owner, app.config["BASE_DOMAIN"]), } headers = { "Accept": "application/vnd.github.v3+json", "Content-Type": "application/json", "Authorization": "token {}".format(app.config["GITHUB_TOKEN"]), } requests.post( pr_url, json=payload, headers=headers, ) return "ok", 200 def virtual_host_parse(virtual_host): """Virtual_hostの文字列を 'rev', 'repo', 'user' に分割する. e.g.(1) "host.repo.sitory.user" => "host", "repo.sitory", "user" e.g.(2) "host.repository.user" => "host", "repository", "user" """ p = re.compile(r'(?P<rev>^.+?)\.(?P<repo>.+)\.(?P<user>.+)$') m = p.search(virtual_host) return m.group('rev'), m.group('repo'), m.group('user') def event_stream_parser(data, event=None, id=None, retry=None): """Server-Sent Event 形式へのパーサ.""" event_stream = '' if event: event_stream += 'event: {}\n'.format(event) event_stream += 'data: {}\n'.format(data) if id: event_stream += 'id: {}\n'.format(id) if retry: event_stream += 'retry: {}\n'.format(id) event_stream += '\n' return event_stream if __name__ == '__main__': # RSA鍵の生成 user = os.getenv('USER') ssh_key_path = os.path.expanduser("~")+"/.ssh/molt_deploy_key" if not os.path.exists(ssh_key_path): command = 'ssh-keygen -t rsa -N "" -f {}'.format(ssh_key_path) command = shlex.split(command) subprocess.Popen(command) # Dockerネットワークの作成 clinet = docker.from_env() networks = clinet.networks.list() if 'molt-network' not in [network.name for network in networks]: command = 'docker network create --subnet=172.31.255.0/24 \ --ip-range=172.31.255.0/24 --gateway=172.31.255.254 \ -o "com.docker.network.bridge.host_binding_ipv4"="0.0.0.0" \ molt-network' command = shlex.split(command) subprocess.Popen(command) app.run(host=app.config['HOST'], port=app.config['PORT']) <|fim▁end|>
req = request.json if even
<|file_name|>molt_app.py<|end_file_name|><|fim▁begin|>"""Molt Web API with Interface.""" import re import redis import docker import subprocess import os import shlex import requests import sys import argparse from flask import Flask, Response, render_template, abort, request from molt import Molt, MoltError app = Flask(__name__) # コマンドライン引数のパース parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', help='config file path') args = parser.parse_args() if args.config: cfg_file = args.config else: cfg_file = 'config/molt_app.cfg' if not os.path.exists(cfg_file): app.logger.error("{} が存在しません".format(cfg_file)) sys.exit(1) app.config.from_pyfile(cfg_file, silent=True) @app.route('/<virtual_host>', strict_slashes=False) def index(virtual_host): """Moltの実行をプレビューするページ.""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) vhost = {'rev': rev, 'repo': repo, 'user': user, 'full': virtual_host} redirect_url = '//{}.{}/'.format(virtual_host, app.config['BASE_DOMAIN']) return render_template('index.html', vhost=vhost, redirect_url=redirect_url) @app.route('/molt/<virtual_host>', methods=['GET'], strict_slashes=False) def molt(virtual_host): """Moltの実行をストリーミングする(Server-Sent Eventを使ったAPI).""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) m = Molt(rev, repo, user, app.config['BASE_DOMAIN'], app.config['GITHUB_USER'], app.config['GITHUB_TOKEN']) r = redis.StrictRedis(host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT']) def generate(m, r): """Dockerイメージ立ち上げ(ストリーミングするための関数). git clone から docker-compose upまでの一連の処理のSTDIOの送信と、Dockerイメージ の情報取得・設定をする """ # コマンド群の実行 try: for row in m.molt(): row = row.decode() data = row.split('\r')[-1] # CRのみの行は保留されるので取り除く yield event_stream_parser(data) except MoltError as e: yield event_stream_parser(e, event='failure') except Exception: yield event_stream_parser('Molt内部でエラーが発生しました。終了します...', event='failure') else: # RedisへIPアドレスとバーチャルホストの対応を書き込む r.hset('mirror-store', virtual_host, m.get_container_ip()) yield event_stream_parser('', event='success') return Response(generate(m, r), mimetype='text/event-stream') @app.route('/favicon.ico') def favicon(): """favicon.ico.""" abort(404) @app.template_filter('base_domain') def base_domain_filter(path): """Staticファイルを呼び出す際のドメインを指定する.""" return '//' + app.config['BASE_DOMAIN'] + ':' + str(app.config['PORT']) + \ '/' + path @app.route("/hook", methods=['POST']) def hook(): event = request.headers["X-GitHub-Event"] req = request.json if event != "pull_request": return "ok", 200 elif req["action"] not <|fim_middle|> ["head"]["repo"]["name"] pr_owner = pr["head"]["repo"]["owner"]["login"] payload = { "event": "COMMENT", "body": "Launched the preview environment!\nhttp://{}.{}.{}.{}\ ".format(pr_sha, pr_reponame, pr_owner, app.config["BASE_DOMAIN"]), } headers = { "Accept": "application/vnd.github.v3+json", "Content-Type": "application/json", "Authorization": "token {}".format(app.config["GITHUB_TOKEN"]), } requests.post( pr_url, json=payload, headers=headers, ) return "ok", 200 def virtual_host_parse(virtual_host): """Virtual_hostの文字列を 'rev', 'repo', 'user' に分割する. e.g.(1) "host.repo.sitory.user" => "host", "repo.sitory", "user" e.g.(2) "host.repository.user" => "host", "repository", "user" """ p = re.compile(r'(?P<rev>^.+?)\.(?P<repo>.+)\.(?P<user>.+)$') m = p.search(virtual_host) return m.group('rev'), m.group('repo'), m.group('user') def event_stream_parser(data, event=None, id=None, retry=None): """Server-Sent Event 形式へのパーサ.""" event_stream = '' if event: event_stream += 'event: {}\n'.format(event) event_stream += 'data: {}\n'.format(data) if id: event_stream += 'id: {}\n'.format(id) if retry: event_stream += 'retry: {}\n'.format(id) event_stream += '\n' return event_stream if __name__ == '__main__': # RSA鍵の生成 user = os.getenv('USER') ssh_key_path = os.path.expanduser("~")+"/.ssh/molt_deploy_key" if not os.path.exists(ssh_key_path): command = 'ssh-keygen -t rsa -N "" -f {}'.format(ssh_key_path) command = shlex.split(command) subprocess.Popen(command) # Dockerネットワークの作成 clinet = docker.from_env() networks = clinet.networks.list() if 'molt-network' not in [network.name for network in networks]: command = 'docker network create --subnet=172.31.255.0/24 \ --ip-range=172.31.255.0/24 --gateway=172.31.255.254 \ -o "com.docker.network.bridge.host_binding_ipv4"="0.0.0.0" \ molt-network' command = shlex.split(command) subprocess.Popen(command) app.run(host=app.config['HOST'], port=app.config['PORT']) <|fim▁end|>
in {"opened", "synchronize"}: return "ok", 200 pr = req["pull_request"] pr_url = pr["comments_url"] pr_sha = pr["head"]["sha"][:7] pr_reponame = pr
<|file_name|>molt_app.py<|end_file_name|><|fim▁begin|>"""Molt Web API with Interface.""" import re import redis import docker import subprocess import os import shlex import requests import sys import argparse from flask import Flask, Response, render_template, abort, request from molt import Molt, MoltError app = Flask(__name__) # コマンドライン引数のパース parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', help='config file path') args = parser.parse_args() if args.config: cfg_file = args.config else: cfg_file = 'config/molt_app.cfg' if not os.path.exists(cfg_file): app.logger.error("{} が存在しません".format(cfg_file)) sys.exit(1) app.config.from_pyfile(cfg_file, silent=True) @app.route('/<virtual_host>', strict_slashes=False) def index(virtual_host): """Moltの実行をプレビューするページ.""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) vhost = {'rev': rev, 'repo': repo, 'user': user, 'full': virtual_host} redirect_url = '//{}.{}/'.format(virtual_host, app.config['BASE_DOMAIN']) return render_template('index.html', vhost=vhost, redirect_url=redirect_url) @app.route('/molt/<virtual_host>', methods=['GET'], strict_slashes=False) def molt(virtual_host): """Moltの実行をストリーミングする(Server-Sent Eventを使ったAPI).""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) m = Molt(rev, repo, user, app.config['BASE_DOMAIN'], app.config['GITHUB_USER'], app.config['GITHUB_TOKEN']) r = redis.StrictRedis(host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT']) def generate(m, r): """Dockerイメージ立ち上げ(ストリーミングするための関数). git clone から docker-compose upまでの一連の処理のSTDIOの送信と、Dockerイメージ の情報取得・設定をする """ # コマンド群の実行 try: for row in m.molt(): row = row.decode() data = row.split('\r')[-1] # CRのみの行は保留されるので取り除く yield event_stream_parser(data) except MoltError as e: yield event_stream_parser(e, event='failure') except Exception: yield event_stream_parser('Molt内部でエラーが発生しました。終了します...', event='failure') else: # RedisへIPアドレスとバーチャルホストの対応を書き込む r.hset('mirror-store', virtual_host, m.get_container_ip()) yield event_stream_parser('', event='success') return Response(generate(m, r), mimetype='text/event-stream') @app.route('/favicon.ico') def favicon(): """favicon.ico.""" abort(404) @app.template_filter('base_domain') def base_domain_filter(path): """Staticファイルを呼び出す際のドメインを指定する.""" return '//' + app.config['BASE_DOMAIN'] + ':' + str(app.config['PORT']) + \ '/' + path @app.route("/hook", methods=['POST']) def hook(): event = request.headers["X-GitHub-Event"] req = request.json if event != "pull_request": return "ok", 200 elif req["action"] not in {"opened", "synchronize"}: return "ok", 200 pr = req["pull_request"] pr_url = pr["comments_url"] pr_sha = pr["head"]["sha"][:7] pr_reponame = pr["head"]["repo"]["name"] pr_owner = pr["head"]["repo"<|fim_middle|> ), m.group('user') def event_stream_parser(data, event=None, id=None, retry=None): """Server-Sent Event 形式へのパーサ.""" event_stream = '' if event: event_stream += 'event: {}\n'.format(event) event_stream += 'data: {}\n'.format(data) if id: event_stream += 'id: {}\n'.format(id) if retry: event_stream += 'retry: {}\n'.format(id) event_stream += '\n' return event_stream if __name__ == '__main__': # RSA鍵の生成 user = os.getenv('USER') ssh_key_path = os.path.expanduser("~")+"/.ssh/molt_deploy_key" if not os.path.exists(ssh_key_path): command = 'ssh-keygen -t rsa -N "" -f {}'.format(ssh_key_path) command = shlex.split(command) subprocess.Popen(command) # Dockerネットワークの作成 clinet = docker.from_env() networks = clinet.networks.list() if 'molt-network' not in [network.name for network in networks]: command = 'docker network create --subnet=172.31.255.0/24 \ --ip-range=172.31.255.0/24 --gateway=172.31.255.254 \ -o "com.docker.network.bridge.host_binding_ipv4"="0.0.0.0" \ molt-network' command = shlex.split(command) subprocess.Popen(command) app.run(host=app.config['HOST'], port=app.config['PORT']) <|fim▁end|>
]["owner"]["login"] payload = { "event": "COMMENT", "body": "Launched the preview environment!\nhttp://{}.{}.{}.{}\ ".format(pr_sha, pr_reponame, pr_owner, app.config["BASE_DOMAIN"]), } headers = { "Accept": "application/vnd.github.v3+json", "Content-Type": "application/json", "Authorization": "token {}".format(app.config["GITHUB_TOKEN"]), } requests.post( pr_url, json=payload, headers=headers, ) return "ok", 200 def virtual_host_parse(virtual_host): """Virtual_hostの文字列を 'rev', 'repo', 'user' に分割する. e.g.(1) "host.repo.sitory.user" => "host", "repo.sitory", "user" e.g.(2) "host.repository.user" => "host", "repository", "user" """ p = re.compile(r'(?P<rev>^.+?)\.(?P<repo>.+)\.(?P<user>.+)$') m = p.search(virtual_host) return m.group('rev'), m.group('repo'
<|file_name|>molt_app.py<|end_file_name|><|fim▁begin|>"""Molt Web API with Interface.""" import re import redis import docker import subprocess import os import shlex import requests import sys import argparse from flask import Flask, Response, render_template, abort, request from molt import Molt, MoltError app = Flask(__name__) # コマンドライン引数のパース parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', help='config file path') args = parser.parse_args() if args.config: cfg_file = args.config else: cfg_file = 'config/molt_app.cfg' if not os.path.exists(cfg_file): app.logger.error("{} が存在しません".format(cfg_file)) sys.exit(1) app.config.from_pyfile(cfg_file, silent=True) @app.route('/<virtual_host>', strict_slashes=False) def index(virtual_host): """Moltの実行をプレビューするページ.""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) vhost = {'rev': rev, 'repo': repo, 'user': user, 'full': virtual_host} redirect_url = '//{}.{}/'.format(virtual_host, app.config['BASE_DOMAIN']) return render_template('index.html', vhost=vhost, redirect_url=redirect_url) @app.route('/molt/<virtual_host>', methods=['GET'], strict_slashes=False) def molt(virtual_host): """Moltの実行をストリーミングする(Server-Sent Eventを使ったAPI).""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) m = Molt(rev, repo, user, app.config['BASE_DOMAIN'], app.config['GITHUB_USER'], app.config['GITHUB_TOKEN']) r = redis.StrictRedis(host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT']) def generate(m, r): """Dockerイメージ立ち上げ(ストリーミングするための関数). git clone から docker-compose upまでの一連の処理のSTDIOの送信と、Dockerイメージ の情報取得・設定をする """ # コマンド群の実行 try: for row in m.molt(): row = row.decode() data = row.split('\r')[-1] # CRのみの行は保留されるので取り除く yield event_stream_parser(data) except MoltError as e: yield event_stream_parser(e, event='failure') except Exception: yield event_stream_parser('Molt内部でエラーが発生しました。終了します...', event='failure') else: # RedisへIPアドレスとバーチャルホストの対応を書き込む r.hset('mirror-store', virtual_host, m.get_container_ip()) yield event_stream_parser('', event='success') return Response(generate(m, r), mimetype='text/event-stream') @app.route('/favicon.ico') def favicon(): """favicon.ico.""" abort(404) @app.template_filter('base_domain') def base_domain_filter(path): """Staticファイルを呼び出す際のドメインを指定する.""" return '//' + app.config['BASE_DOMAIN'] + ':' + str(app.config['PORT']) + \ '/' + path @app.route("/hook", methods=['POST']) def hook(): event = request.headers["X-GitHub-Event"] req = request.json if event != "pull_request": return "ok", 200 elif req["action"] not in {"opened", "synchronize"}: return "ok", 200 pr = req["pull_request"] pr_url = pr["comments_url"] pr_sha = pr["head"]["sha"][:7] pr_reponame = pr["head"]["repo"]["name"] pr_owner = pr["head"]["repo"]["owner"]["login"] payload = { "event": "COMMENT", "body": "Launched the preview environment!\nhttp://{}.{}.{}.{}\ ".format(pr_sha, pr_reponame, pr_owner, app.config["BASE_DOMAIN"]), } headers = { "Accept": "application/vnd.github.v3+json", "Content-Type": "application/json", "Authorization": "token {}".format(app.config["GITHUB_TOKEN"]), } requests.post( pr_url, json=payload, headers=headers, ) return "ok", 200 def virtual_host_parse(virtual_host): """Virtual_hostの文字列を 'rev', 'repo', 'user' に分割する. e.g.(1) "host.repo.sitory.user" => "host", "repo.sitory", "user" e.g.(2) "host.repository.user" => "host", "repository", "user" """ p = re.compile(r'(?P<rev>^.+?)\.(?P<repo>.+)\.(?P<user>.+)$') m = p.search(virtual_host) return m.group('rev'), m.group('repo'), m.group('user') def event_stream_parser(<|fim_middle|> t_stream if __name__ == '__main__': # RSA鍵の生成 user = os.getenv('USER') ssh_key_path = os.path.expanduser("~")+"/.ssh/molt_deploy_key" if not os.path.exists(ssh_key_path): command = 'ssh-keygen -t rsa -N "" -f {}'.format(ssh_key_path) command = shlex.split(command) subprocess.Popen(command) # Dockerネットワークの作成 clinet = docker.from_env() networks = clinet.networks.list() if 'molt-network' not in [network.name for network in networks]: command = 'docker network create --subnet=172.31.255.0/24 \ --ip-range=172.31.255.0/24 --gateway=172.31.255.254 \ -o "com.docker.network.bridge.host_binding_ipv4"="0.0.0.0" \ molt-network' command = shlex.split(command) subprocess.Popen(command) app.run(host=app.config['HOST'], port=app.config['PORT']) <|fim▁end|>
data, event=None, id=None, retry=None): """Server-Sent Event 形式へのパーサ.""" event_stream = '' if event: event_stream += 'event: {}\n'.format(event) event_stream += 'data: {}\n'.format(data) if id: event_stream += 'id: {}\n'.format(id) if retry: event_stream += 'retry: {}\n'.format(id) event_stream += '\n' return even
<|file_name|>molt_app.py<|end_file_name|><|fim▁begin|>"""Molt Web API with Interface.""" import re import redis import docker import subprocess import os import shlex import requests import sys import argparse from flask import Flask, Response, render_template, abort, request from molt import Molt, MoltError app = Flask(__name__) # コマンドライン引数のパース parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', help='config file path') args = parser.parse_args() if args.config: cfg_file = args.config else: cfg_file = 'config/molt_app.cfg' if not os.path.exists(cfg_file): app.logger.error("{} が存在しません".format(cfg_file)) sys.exit(1) app.config.from_pyfile(cfg_file, silent=True) @app.route('/<virtual_host>', strict_slashes=False) def index(virtual_host): """Moltの実行をプレビューするページ.""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) vhost = {'rev': rev, 'repo': repo, 'user': user, 'full': virtual_host} redirect_url = '//{}.{}/'.format(virtual_host, app.config['BASE_DOMAIN']) return render_template('index.html', vhost=vhost, redirect_url=redirect_url) @app.route('/molt/<virtual_host>', methods=['GET'], strict_slashes=False) def molt(virtual_host): """Moltの実行をストリーミングする(Server-Sent Eventを使ったAPI).""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) m = Molt(rev, repo, user, app.config['BASE_DOMAIN'], app.config['GITHUB_USER'], app.config['GITHUB_TOKEN']) r = redis.StrictRedis(host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT']) def generate(m, r): """Dockerイメージ立ち上げ(ストリーミングするための関数). git clone から docker-compose upまでの一連の処理のSTDIOの送信と、Dockerイメージ の情報取得・設定をする """ # コマンド群の実行 try: for row in m.molt(): row = row.decode() data = row.split('\r')[-1] # CRのみの行は保留されるので取り除く yield event_stream_parser(data) except MoltError as e: yield event_stream_parser(e, event='failure') except Exception: yield event_stream_parser('Molt内部でエラーが発生しました。終了します...', event='failure') else: # RedisへIPアドレスとバーチャルホストの対応を書き込む r.hset('mirror-store', virtual_host, m.get_container_ip()) yield event_stream_parser('', event='success') return Response(generate(m, r), mimetype='text/event-stream') @app.route('/favicon.ico') def favicon(): """favicon.ico.""" abort(404) @app.template_filter('base_domain') def base_domain_filter(path): """Staticファイルを呼び出す際のドメインを指定する.""" return '//' + app.config['BASE_DOMAIN'] + ':' + str(app.config['PORT']) + \ '/' + path @app.route("/hook", methods=['POST']) def hook(): event = request.headers["X-GitHub-Event"] req = request.json if event != "pull_request": return "ok", 200 elif req["action"] not in {"opened", "synchronize"}: return "ok", 200 pr = req["pull_request"] pr_url = pr["comments_url"] pr_sha = pr["head"]["sha"][:7] pr_reponame = pr["head"]["repo"]["name"] pr_owner = pr["head"]["repo"]["owner"]["login"] payload = { "event": "COMMENT", "body": "Launched the preview environment!\nhttp://{}.{}.{}.{}\ ".format(pr_sha, pr_reponame, pr_owner, app.config["BASE_DOMAIN"]), } headers = { "Accept": "application/vnd.github.v3+json", "Content-Type": "application/json", "Authorization": "token {}".format(app.config["GITHUB_TOKEN"]), } requests.post( pr_url, json=payload, headers=headers, ) return "ok", 200 def virtual_host_parse(virtual_host): """Virtual_hostの文字列を 'rev', 'repo', 'user' に分割する. e.g.(1) "host.repo.sitory.user" => "host", "repo.sitory", "user" e.g.(2) "host.repository.user" => "host", "repository", "user" """ p = re.compile(r'(?P<rev>^.+?)\.(?P<repo>.+)\.(?P<user>.+)$') m = p.search(virtual_host) return m.group('rev'), m.group('repo'), m.group('user') def event_stream_parser(data, event=None, id=None, retry=None): """Server-Sent Event 形式へのパーサ.""" event_stream = '' if event: event_stream += 'event: {}\n'.format(event) event_stream += 'data: {}\n'.format(data) if id: event_stream += 'id: {}\n'.format(id) if retry: event_stream += 'retry: {}\n'.format(id) event_stream += '\n' return event_stream if __name__ == '__main__': # RSA鍵の生成 user = os.geten<|fim_middle|> st() if 'molt-network' not in [network.name for network in networks]: command = 'docker network create --subnet=172.31.255.0/24 \ --ip-range=172.31.255.0/24 --gateway=172.31.255.254 \ -o "com.docker.network.bridge.host_binding_ipv4"="0.0.0.0" \ molt-network' command = shlex.split(command) subprocess.Popen(command) app.run(host=app.config['HOST'], port=app.config['PORT']) <|fim▁end|>
v('USER') ssh_key_path = os.path.expanduser("~")+"/.ssh/molt_deploy_key" if not os.path.exists(ssh_key_path): command = 'ssh-keygen -t rsa -N "" -f {}'.format(ssh_key_path) command = shlex.split(command) subprocess.Popen(command) # Dockerネットワークの作成 clinet = docker.from_env() networks = clinet.networks.li
<|file_name|>molt_app.py<|end_file_name|><|fim▁begin|>"""Molt Web API with Interface.""" import re import redis import docker import subprocess import os import shlex import requests import sys import argparse from flask import Flask, Response, render_template, abort, request from molt import Molt, MoltError app = Flask(__name__) # コマンドライン引数のパース parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', help='config file path') args = parser.parse_args() if args.config: cfg_file = args.config els <|fim_middle|> fig/molt_app.cfg' if not os.path.exists(cfg_file): app.logger.error("{} が存在しません".format(cfg_file)) sys.exit(1) app.config.from_pyfile(cfg_file, silent=True) @app.route('/<virtual_host>', strict_slashes=False) def index(virtual_host): """Moltの実行をプレビューするページ.""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) vhost = {'rev': rev, 'repo': repo, 'user': user, 'full': virtual_host} redirect_url = '//{}.{}/'.format(virtual_host, app.config['BASE_DOMAIN']) return render_template('index.html', vhost=vhost, redirect_url=redirect_url) @app.route('/molt/<virtual_host>', methods=['GET'], strict_slashes=False) def molt(virtual_host): """Moltの実行をストリーミングする(Server-Sent Eventを使ったAPI).""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) m = Molt(rev, repo, user, app.config['BASE_DOMAIN'], app.config['GITHUB_USER'], app.config['GITHUB_TOKEN']) r = redis.StrictRedis(host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT']) def generate(m, r): """Dockerイメージ立ち上げ(ストリーミングするための関数). git clone から docker-compose upまでの一連の処理のSTDIOの送信と、Dockerイメージ の情報取得・設定をする """ # コマンド群の実行 try: for row in m.molt(): row = row.decode() data = row.split('\r')[-1] # CRのみの行は保留されるので取り除く yield event_stream_parser(data) except MoltError as e: yield event_stream_parser(e, event='failure') except Exception: yield event_stream_parser('Molt内部でエラーが発生しました。終了します...', event='failure') else: # RedisへIPアドレスとバーチャルホストの対応を書き込む r.hset('mirror-store', virtual_host, m.get_container_ip()) yield event_stream_parser('', event='success') return Response(generate(m, r), mimetype='text/event-stream') @app.route('/favicon.ico') def favicon(): """favicon.ico.""" abort(404) @app.template_filter('base_domain') def base_domain_filter(path): """Staticファイルを呼び出す際のドメインを指定する.""" return '//' + app.config['BASE_DOMAIN'] + ':' + str(app.config['PORT']) + \ '/' + path @app.route("/hook", methods=['POST']) def hook(): event = request.headers["X-GitHub-Event"] req = request.json if event != "pull_request": return "ok", 200 elif req["action"] not in {"opened", "synchronize"}: return "ok", 200 pr = req["pull_request"] pr_url = pr["comments_url"] pr_sha = pr["head"]["sha"][:7] pr_reponame = pr["head"]["repo"]["name"] pr_owner = pr["head"]["repo"]["owner"]["login"] payload = { "event": "COMMENT", "body": "Launched the preview environment!\nhttp://{}.{}.{}.{}\ ".format(pr_sha, pr_reponame, pr_owner, app.config["BASE_DOMAIN"]), } headers = { "Accept": "application/vnd.github.v3+json", "Content-Type": "application/json", "Authorization": "token {}".format(app.config["GITHUB_TOKEN"]), } requests.post( pr_url, json=payload, headers=headers, ) return "ok", 200 def virtual_host_parse(virtual_host): """Virtual_hostの文字列を 'rev', 'repo', 'user' に分割する. e.g.(1) "host.repo.sitory.user" => "host", "repo.sitory", "user" e.g.(2) "host.repository.user" => "host", "repository", "user" """ p = re.compile(r'(?P<rev>^.+?)\.(?P<repo>.+)\.(?P<user>.+)$') m = p.search(virtual_host) return m.group('rev'), m.group('repo'), m.group('user') def event_stream_parser(data, event=None, id=None, retry=None): """Server-Sent Event 形式へのパーサ.""" event_stream = '' if event: event_stream += 'event: {}\n'.format(event) event_stream += 'data: {}\n'.format(data) if id: event_stream += 'id: {}\n'.format(id) if retry: event_stream += 'retry: {}\n'.format(id) event_stream += '\n' return event_stream if __name__ == '__main__': # RSA鍵の生成 user = os.getenv('USER') ssh_key_path = os.path.expanduser("~")+"/.ssh/molt_deploy_key" if not os.path.exists(ssh_key_path): command = 'ssh-keygen -t rsa -N "" -f {}'.format(ssh_key_path) command = shlex.split(command) subprocess.Popen(command) # Dockerネットワークの作成 clinet = docker.from_env() networks = clinet.networks.list() if 'molt-network' not in [network.name for network in networks]: command = 'docker network create --subnet=172.31.255.0/24 \ --ip-range=172.31.255.0/24 --gateway=172.31.255.254 \ -o "com.docker.network.bridge.host_binding_ipv4"="0.0.0.0" \ molt-network' command = shlex.split(command) subprocess.Popen(command) app.run(host=app.config['HOST'], port=app.config['PORT']) <|fim▁end|>
e: cfg_file = 'con
<|file_name|>molt_app.py<|end_file_name|><|fim▁begin|>"""Molt Web API with Interface.""" import re import redis import docker import subprocess import os import shlex import requests import sys import argparse from flask import Flask, Response, render_template, abort, request from molt import Molt, MoltError app = Flask(__name__) # コマンドライン引数のパース parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', help='config file path') args = parser.parse_args() if args.config: cfg_file = args.config else: cfg_file = 'config/molt_ap <|fim_middle|> g_file): app.logger.error("{} が存在しません".format(cfg_file)) sys.exit(1) app.config.from_pyfile(cfg_file, silent=True) @app.route('/<virtual_host>', strict_slashes=False) def index(virtual_host): """Moltの実行をプレビューするページ.""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) vhost = {'rev': rev, 'repo': repo, 'user': user, 'full': virtual_host} redirect_url = '//{}.{}/'.format(virtual_host, app.config['BASE_DOMAIN']) return render_template('index.html', vhost=vhost, redirect_url=redirect_url) @app.route('/molt/<virtual_host>', methods=['GET'], strict_slashes=False) def molt(virtual_host): """Moltの実行をストリーミングする(Server-Sent Eventを使ったAPI).""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) m = Molt(rev, repo, user, app.config['BASE_DOMAIN'], app.config['GITHUB_USER'], app.config['GITHUB_TOKEN']) r = redis.StrictRedis(host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT']) def generate(m, r): """Dockerイメージ立ち上げ(ストリーミングするための関数). git clone から docker-compose upまでの一連の処理のSTDIOの送信と、Dockerイメージ の情報取得・設定をする """ # コマンド群の実行 try: for row in m.molt(): row = row.decode() data = row.split('\r')[-1] # CRのみの行は保留されるので取り除く yield event_stream_parser(data) except MoltError as e: yield event_stream_parser(e, event='failure') except Exception: yield event_stream_parser('Molt内部でエラーが発生しました。終了します...', event='failure') else: # RedisへIPアドレスとバーチャルホストの対応を書き込む r.hset('mirror-store', virtual_host, m.get_container_ip()) yield event_stream_parser('', event='success') return Response(generate(m, r), mimetype='text/event-stream') @app.route('/favicon.ico') def favicon(): """favicon.ico.""" abort(404) @app.template_filter('base_domain') def base_domain_filter(path): """Staticファイルを呼び出す際のドメインを指定する.""" return '//' + app.config['BASE_DOMAIN'] + ':' + str(app.config['PORT']) + \ '/' + path @app.route("/hook", methods=['POST']) def hook(): event = request.headers["X-GitHub-Event"] req = request.json if event != "pull_request": return "ok", 200 elif req["action"] not in {"opened", "synchronize"}: return "ok", 200 pr = req["pull_request"] pr_url = pr["comments_url"] pr_sha = pr["head"]["sha"][:7] pr_reponame = pr["head"]["repo"]["name"] pr_owner = pr["head"]["repo"]["owner"]["login"] payload = { "event": "COMMENT", "body": "Launched the preview environment!\nhttp://{}.{}.{}.{}\ ".format(pr_sha, pr_reponame, pr_owner, app.config["BASE_DOMAIN"]), } headers = { "Accept": "application/vnd.github.v3+json", "Content-Type": "application/json", "Authorization": "token {}".format(app.config["GITHUB_TOKEN"]), } requests.post( pr_url, json=payload, headers=headers, ) return "ok", 200 def virtual_host_parse(virtual_host): """Virtual_hostの文字列を 'rev', 'repo', 'user' に分割する. e.g.(1) "host.repo.sitory.user" => "host", "repo.sitory", "user" e.g.(2) "host.repository.user" => "host", "repository", "user" """ p = re.compile(r'(?P<rev>^.+?)\.(?P<repo>.+)\.(?P<user>.+)$') m = p.search(virtual_host) return m.group('rev'), m.group('repo'), m.group('user') def event_stream_parser(data, event=None, id=None, retry=None): """Server-Sent Event 形式へのパーサ.""" event_stream = '' if event: event_stream += 'event: {}\n'.format(event) event_stream += 'data: {}\n'.format(data) if id: event_stream += 'id: {}\n'.format(id) if retry: event_stream += 'retry: {}\n'.format(id) event_stream += '\n' return event_stream if __name__ == '__main__': # RSA鍵の生成 user = os.getenv('USER') ssh_key_path = os.path.expanduser("~")+"/.ssh/molt_deploy_key" if not os.path.exists(ssh_key_path): command = 'ssh-keygen -t rsa -N "" -f {}'.format(ssh_key_path) command = shlex.split(command) subprocess.Popen(command) # Dockerネットワークの作成 clinet = docker.from_env() networks = clinet.networks.list() if 'molt-network' not in [network.name for network in networks]: command = 'docker network create --subnet=172.31.255.0/24 \ --ip-range=172.31.255.0/24 --gateway=172.31.255.254 \ -o "com.docker.network.bridge.host_binding_ipv4"="0.0.0.0" \ molt-network' command = shlex.split(command) subprocess.Popen(command) app.run(host=app.config['HOST'], port=app.config['PORT']) <|fim▁end|>
p.cfg' if not os.path.exists(cf
<|file_name|>molt_app.py<|end_file_name|><|fim▁begin|>"""Molt Web API with Interface.""" import re import redis import docker import subprocess import os import shlex import requests import sys import argparse from flask import Flask, Response, render_template, abort, request from molt import Molt, MoltError app = Flask(__name__) # コマンドライン引数のパース parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', help='config file path') args = parser.parse_args() if args.config: cfg_file = args.config else: cfg_file = 'config/molt_app.cfg' if not os.path.exists(cfg_file): app.logger.error("{} が存在しま <|fim_middle|> t=True) @app.route('/<virtual_host>', strict_slashes=False) def index(virtual_host): """Moltの実行をプレビューするページ.""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) vhost = {'rev': rev, 'repo': repo, 'user': user, 'full': virtual_host} redirect_url = '//{}.{}/'.format(virtual_host, app.config['BASE_DOMAIN']) return render_template('index.html', vhost=vhost, redirect_url=redirect_url) @app.route('/molt/<virtual_host>', methods=['GET'], strict_slashes=False) def molt(virtual_host): """Moltの実行をストリーミングする(Server-Sent Eventを使ったAPI).""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) m = Molt(rev, repo, user, app.config['BASE_DOMAIN'], app.config['GITHUB_USER'], app.config['GITHUB_TOKEN']) r = redis.StrictRedis(host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT']) def generate(m, r): """Dockerイメージ立ち上げ(ストリーミングするための関数). git clone から docker-compose upまでの一連の処理のSTDIOの送信と、Dockerイメージ の情報取得・設定をする """ # コマンド群の実行 try: for row in m.molt(): row = row.decode() data = row.split('\r')[-1] # CRのみの行は保留されるので取り除く yield event_stream_parser(data) except MoltError as e: yield event_stream_parser(e, event='failure') except Exception: yield event_stream_parser('Molt内部でエラーが発生しました。終了します...', event='failure') else: # RedisへIPアドレスとバーチャルホストの対応を書き込む r.hset('mirror-store', virtual_host, m.get_container_ip()) yield event_stream_parser('', event='success') return Response(generate(m, r), mimetype='text/event-stream') @app.route('/favicon.ico') def favicon(): """favicon.ico.""" abort(404) @app.template_filter('base_domain') def base_domain_filter(path): """Staticファイルを呼び出す際のドメインを指定する.""" return '//' + app.config['BASE_DOMAIN'] + ':' + str(app.config['PORT']) + \ '/' + path @app.route("/hook", methods=['POST']) def hook(): event = request.headers["X-GitHub-Event"] req = request.json if event != "pull_request": return "ok", 200 elif req["action"] not in {"opened", "synchronize"}: return "ok", 200 pr = req["pull_request"] pr_url = pr["comments_url"] pr_sha = pr["head"]["sha"][:7] pr_reponame = pr["head"]["repo"]["name"] pr_owner = pr["head"]["repo"]["owner"]["login"] payload = { "event": "COMMENT", "body": "Launched the preview environment!\nhttp://{}.{}.{}.{}\ ".format(pr_sha, pr_reponame, pr_owner, app.config["BASE_DOMAIN"]), } headers = { "Accept": "application/vnd.github.v3+json", "Content-Type": "application/json", "Authorization": "token {}".format(app.config["GITHUB_TOKEN"]), } requests.post( pr_url, json=payload, headers=headers, ) return "ok", 200 def virtual_host_parse(virtual_host): """Virtual_hostの文字列を 'rev', 'repo', 'user' に分割する. e.g.(1) "host.repo.sitory.user" => "host", "repo.sitory", "user" e.g.(2) "host.repository.user" => "host", "repository", "user" """ p = re.compile(r'(?P<rev>^.+?)\.(?P<repo>.+)\.(?P<user>.+)$') m = p.search(virtual_host) return m.group('rev'), m.group('repo'), m.group('user') def event_stream_parser(data, event=None, id=None, retry=None): """Server-Sent Event 形式へのパーサ.""" event_stream = '' if event: event_stream += 'event: {}\n'.format(event) event_stream += 'data: {}\n'.format(data) if id: event_stream += 'id: {}\n'.format(id) if retry: event_stream += 'retry: {}\n'.format(id) event_stream += '\n' return event_stream if __name__ == '__main__': # RSA鍵の生成 user = os.getenv('USER') ssh_key_path = os.path.expanduser("~")+"/.ssh/molt_deploy_key" if not os.path.exists(ssh_key_path): command = 'ssh-keygen -t rsa -N "" -f {}'.format(ssh_key_path) command = shlex.split(command) subprocess.Popen(command) # Dockerネットワークの作成 clinet = docker.from_env() networks = clinet.networks.list() if 'molt-network' not in [network.name for network in networks]: command = 'docker network create --subnet=172.31.255.0/24 \ --ip-range=172.31.255.0/24 --gateway=172.31.255.254 \ -o "com.docker.network.bridge.host_binding_ipv4"="0.0.0.0" \ molt-network' command = shlex.split(command) subprocess.Popen(command) app.run(host=app.config['HOST'], port=app.config['PORT']) <|fim▁end|>
せん".format(cfg_file)) sys.exit(1) app.config.from_pyfile(cfg_file, silen
<|file_name|>molt_app.py<|end_file_name|><|fim▁begin|>"""Molt Web API with Interface.""" import re import redis import docker import subprocess import os import shlex import requests import sys import argparse from flask import Flask, Response, render_template, abort, request from molt import Molt, MoltError app = Flask(__name__) # コマンドライン引数のパース parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', help='config file path') args = parser.parse_args() if args.config: cfg_file = args.config else: cfg_file = 'config/molt_app.cfg' if not os.path.exists(cfg_file): app.logger.error("{} が存在しません".format(cfg_file)) sys.exit(1) app.config.from_pyfile(cfg_file, silent=True) @app.route('/<virtual_host>', strict_slashes=False) def index(virtual_host): """Moltの実行をプレビューするページ.""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) vhost = {'rev': rev, 'repo': repo, 'user': user, 'full': virtual_host} redirect_url = '//{}.{}/'.format(virtual_host, app.config['BASE_DOMAIN']) return render_template('index.html', vhost=vhost, redirect_url=redirect_url) @app.route('/molt/<virtual_host>', methods=['GET'], strict_slashes=False) def molt(virtual_host): """Moltの実行をストリーミングする(Server-Sent Eventを使ったAPI).""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) m = Molt(rev, repo, user, app.config['BASE_DOMAIN'], app.config['GITHUB_USER'], app.config['GITHUB_TOKEN']) r = redis.StrictRedis(host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT']) def generate(m, r): """Dockerイメージ立ち上げ(ストリーミングするための関数). git clone から docker-compose upまでの一連の処理のSTDIOの送信と、Dockerイメージ の情報取得・設定をする """ # コマンド群の実行 try: for row in m.molt(): row = row.decode() data = row.split('\r')[-1] # CRのみの行は保留されるので取り除く yield event_stream_parser(data) except MoltError as e: yield event_stream_parser(e, event='failure') except Exception: yield event_stream_parser('Molt内部でエラーが発生しました。終了します...', event='failure') else: # RedisへIPアドレスとバーチャルホストの対応を書き込む r.hset('mirror-store', virtual_host, m.get_container_ip()) yield event_stream_parser('', event='success') return Response(generate(m, r), mimetype='text/event-stream') @app.route('/favicon.ico') def favicon(): """favicon.ico.""" abort(404) @app.template_filter('base_domain') def base_domain_filter(path): <|fim_middle|> '/' + path @app.route("/hook", methods=['POST']) def hook(): event = request.headers["X-GitHub-Event"] req = request.json if event != "pull_request": return "ok", 200 elif req["action"] not in {"opened", "synchronize"}: return "ok", 200 pr = req["pull_request"] pr_url = pr["comments_url"] pr_sha = pr["head"]["sha"][:7] pr_reponame = pr["head"]["repo"]["name"] pr_owner = pr["head"]["repo"]["owner"]["login"] payload = { "event": "COMMENT", "body": "Launched the preview environment!\nhttp://{}.{}.{}.{}\ ".format(pr_sha, pr_reponame, pr_owner, app.config["BASE_DOMAIN"]), } headers = { "Accept": "application/vnd.github.v3+json", "Content-Type": "application/json", "Authorization": "token {}".format(app.config["GITHUB_TOKEN"]), } requests.post( pr_url, json=payload, headers=headers, ) return "ok", 200 def virtual_host_parse(virtual_host): """Virtual_hostの文字列を 'rev', 'repo', 'user' に分割する. e.g.(1) "host.repo.sitory.user" => "host", "repo.sitory", "user" e.g.(2) "host.repository.user" => "host", "repository", "user" """ p = re.compile(r'(?P<rev>^.+?)\.(?P<repo>.+)\.(?P<user>.+)$') m = p.search(virtual_host) return m.group('rev'), m.group('repo'), m.group('user') def event_stream_parser(data, event=None, id=None, retry=None): """Server-Sent Event 形式へのパーサ.""" event_stream = '' if event: event_stream += 'event: {}\n'.format(event) event_stream += 'data: {}\n'.format(data) if id: event_stream += 'id: {}\n'.format(id) if retry: event_stream += 'retry: {}\n'.format(id) event_stream += '\n' return event_stream if __name__ == '__main__': # RSA鍵の生成 user = os.getenv('USER') ssh_key_path = os.path.expanduser("~")+"/.ssh/molt_deploy_key" if not os.path.exists(ssh_key_path): command = 'ssh-keygen -t rsa -N "" -f {}'.format(ssh_key_path) command = shlex.split(command) subprocess.Popen(command) # Dockerネットワークの作成 clinet = docker.from_env() networks = clinet.networks.list() if 'molt-network' not in [network.name for network in networks]: command = 'docker network create --subnet=172.31.255.0/24 \ --ip-range=172.31.255.0/24 --gateway=172.31.255.254 \ -o "com.docker.network.bridge.host_binding_ipv4"="0.0.0.0" \ molt-network' command = shlex.split(command) subprocess.Popen(command) app.run(host=app.config['HOST'], port=app.config['PORT']) <|fim▁end|>
"""Staticファイルを呼び出す際のドメインを指定する.""" return '//' + app.config['BASE_DOMAIN'] + ':' + str(app.config['PORT']) + \
<|file_name|>molt_app.py<|end_file_name|><|fim▁begin|>"""Molt Web API with Interface.""" import re import redis import docker import subprocess import os import shlex import requests import sys import argparse from flask import Flask, Response, render_template, abort, request from molt import Molt, MoltError app = Flask(__name__) # コマンドライン引数のパース parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', help='config file path') args = parser.parse_args() if args.config: cfg_file = args.config else: cfg_file = 'config/molt_app.cfg' if not os.path.exists(cfg_file): app.logger.error("{} が存在しません".format(cfg_file)) sys.exit(1) app.config.from_pyfile(cfg_file, silent=True) @app.route('/<virtual_host>', strict_slashes=False) def index(virtual_host): """Moltの実行をプレビューするページ.""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) vhost = {'rev': rev, 'repo': repo, 'user': user, 'full': virtual_host} redirect_url = '//{}.{}/'.format(virtual_host, app.config['BASE_DOMAIN']) return render_template('index.html', vhost=vhost, redirect_url=redirect_url) @app.route('/molt/<virtual_host>', methods=['GET'], strict_slashes=False) def molt(virtual_host): """Moltの実行をストリーミングする(Server-Sent Eventを使ったAPI).""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) m = Molt(rev, repo, user, app.config['BASE_DOMAIN'], app.config['GITHUB_USER'], app.config['GITHUB_TOKEN']) r = redis.StrictRedis(host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT']) def generate(m, r): """Dockerイメージ立ち上げ(ストリーミングするための関数). git clone から docker-compose upまでの一連の処理のSTDIOの送信と、Dockerイメージ の情報取得・設定をする """ # コマンド群の実行 try: for row in m.molt(): row = row.decode() data = row.split('\r')[-1] # CRのみの行は保留されるので取り除く yield event_stream_parser(data) except MoltError as e: yield event_stream_parser(e, event='failure') except Exception: yield event_stream_parser('Molt内部でエラーが発生しました。終了します...', event='failure') else: # RedisへIPアドレスとバーチャルホストの対応を書き込む r.hset('mirror-store', virtual_host, m.get_container_ip()) yield event_stream_parser('', event='success') return Response(generate(m, r), mimetype='text/event-stream') @app.route('/favicon.ico') def favicon(): """favicon.ico.""" abort(404) @app.template_filter('base_domain') def base_domain_filter(path): """Staticファイルを呼び出す際のドメインを指定する.""" return '//' + app.config['BASE_DOMAIN'] + ':' + str(app.config['PORT']) + \ '/' + path @app.route("/hook", methods=['POST']) def hook(): event = request.headers["X-GitHub-Event"] req = request.json if event != "pull_request": return "ok", 200 elif req["action"] not in {"opened", "synchronize"}: return "ok", 200 pr = req["pull_request"] pr_url = pr["comments_url"] pr_sha = pr["head"]["sha"][:7] pr_reponame = pr["head"]["repo"]["name"] pr_owner = pr["head"]["repo"]["owner"]["login"] payload = { "event": "COMMENT", "body": "Launched the preview en <|fim_middle|> ://{}.{}.{}.{}\ ".format(pr_sha, pr_reponame, pr_owner, app.config["BASE_DOMAIN"]), } headers = { "Accept": "application/vnd.github.v3+json", "Content-Type": "application/json", "Authorization": "token {}".format(app.config["GITHUB_TOKEN"]), } requests.post( pr_url, json=payload, headers=headers, ) return "ok", 200 def virtual_host_parse(virtual_host): """Virtual_hostの文字列を 'rev', 'repo', 'user' に分割する. e.g.(1) "host.repo.sitory.user" => "host", "repo.sitory", "user" e.g.(2) "host.repository.user" => "host", "repository", "user" """ p = re.compile(r'(?P<rev>^.+?)\.(?P<repo>.+)\.(?P<user>.+)$') m = p.search(virtual_host) return m.group('rev'), m.group('repo'), m.group('user') def event_stream_parser(data, event=None, id=None, retry=None): """Server-Sent Event 形式へのパーサ.""" event_stream = '' if event: event_stream += 'event: {}\n'.format(event) event_stream += 'data: {}\n'.format(data) if id: event_stream += 'id: {}\n'.format(id) if retry: event_stream += 'retry: {}\n'.format(id) event_stream += '\n' return event_stream if __name__ == '__main__': # RSA鍵の生成 user = os.getenv('USER') ssh_key_path = os.path.expanduser("~")+"/.ssh/molt_deploy_key" if not os.path.exists(ssh_key_path): command = 'ssh-keygen -t rsa -N "" -f {}'.format(ssh_key_path) command = shlex.split(command) subprocess.Popen(command) # Dockerネットワークの作成 clinet = docker.from_env() networks = clinet.networks.list() if 'molt-network' not in [network.name for network in networks]: command = 'docker network create --subnet=172.31.255.0/24 \ --ip-range=172.31.255.0/24 --gateway=172.31.255.254 \ -o "com.docker.network.bridge.host_binding_ipv4"="0.0.0.0" \ molt-network' command = shlex.split(command) subprocess.Popen(command) app.run(host=app.config['HOST'], port=app.config['PORT']) <|fim▁end|>
vironment!\nhttp
<|file_name|>molt_app.py<|end_file_name|><|fim▁begin|>"""Molt Web API with Interface.""" import re import redis import docker import subprocess import os import shlex import requests import sys import argparse from flask import Flask, Response, render_template, abort, request from molt import Molt, MoltError app = Flask(__name__) # コマンドライン引数のパース parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', help='config file path') args = parser.parse_args() if args.config: cfg_file = args.config else: cfg_file = 'config/molt_app.cfg' if not os.path.exists(cfg_file): app.logger.error("{} が存在しません".format(cfg_file)) sys.exit(1) app.config.from_pyfile(cfg_file, silent=True) @app.route('/<virtual_host>', strict_slashes=False) def index(virtual_host): """Moltの実行をプレビューするページ.""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) vhost = {'rev': rev, 'repo': repo, 'user': user, 'full': virtual_host} redirect_url = '//{}.{}/'.format(virtual_host, app.config['BASE_DOMAIN']) return render_template('index.html', vhost=vhost, redirect_url=redirect_url) @app.route('/molt/<virtual_host>', methods=['GET'], strict_slashes=False) def molt(virtual_host): """Moltの実行をストリーミングする(Server-Sent Eventを使ったAPI).""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) m = Molt(rev, repo, user, app.config['BASE_DOMAIN'], app.config['GITHUB_USER'], app.config['GITHUB_TOKEN']) r = redis.StrictRedis(host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT']) def generate(m, r): """Dockerイメージ立ち上げ(ストリーミングするための関数). git clone から docker-compose upまでの一連の処理のSTDIOの送信と、Dockerイメージ の情報取得・設定をする """ # コマンド群の実行 try: for row in m.molt(): row = row.decode() data = row.split('\r')[-1] # CRのみの行は保留されるので取り除く yield event_stream_parser(data) except MoltError as e: yield event_stream_parser(e, event='failure') except Exception: yield event_stream_parser('Molt内部でエラーが発生しました。終了します...', event='failure') else: # RedisへIPアドレスとバーチャルホストの対応を書き込む r.hset('mirror-store', virtual_host, m.get_container_ip()) yield event_stream_parser('', event='success') return Response(generate(m, r), mimetype='text/event-stream') @app.route('/favicon.ico') def favicon(): """favicon.ico.""" abort(404) @app.template_filter('base_domain') def base_domain_filter(path): """Staticファイルを呼び出す際のドメインを指定する.""" return '//' + app.config['BASE_DOMAIN'] + ':' + str(app.config['PORT']) + \ '/' + path @app.route("/hook", methods=['POST']) def hook(): event = request.headers["X-GitHub-Event"] req = request.json if event != "pull_request": return "ok", 200 elif req["action"] not in {"opened", "synchronize"}: return "ok", 200 pr = req["pull_request"] pr_url = pr["comments_url"] pr_sha = pr["head"]["sha"][:7] pr_reponame = pr["head"]["repo"]["name"] pr_owner = pr["head"]["repo"]["owner"]["login"] payload = { "event": "COMMENT", "body": "Launched the preview environment!\nhttp://{}.{}.{}.{}\ ".format(pr_sha, pr_reponame, pr_owner, ap <|fim_middle|> OMAIN"]), } headers = { "Accept": "application/vnd.github.v3+json", "Content-Type": "application/json", "Authorization": "token {}".format(app.config["GITHUB_TOKEN"]), } requests.post( pr_url, json=payload, headers=headers, ) return "ok", 200 def virtual_host_parse(virtual_host): """Virtual_hostの文字列を 'rev', 'repo', 'user' に分割する. e.g.(1) "host.repo.sitory.user" => "host", "repo.sitory", "user" e.g.(2) "host.repository.user" => "host", "repository", "user" """ p = re.compile(r'(?P<rev>^.+?)\.(?P<repo>.+)\.(?P<user>.+)$') m = p.search(virtual_host) return m.group('rev'), m.group('repo'), m.group('user') def event_stream_parser(data, event=None, id=None, retry=None): """Server-Sent Event 形式へのパーサ.""" event_stream = '' if event: event_stream += 'event: {}\n'.format(event) event_stream += 'data: {}\n'.format(data) if id: event_stream += 'id: {}\n'.format(id) if retry: event_stream += 'retry: {}\n'.format(id) event_stream += '\n' return event_stream if __name__ == '__main__': # RSA鍵の生成 user = os.getenv('USER') ssh_key_path = os.path.expanduser("~")+"/.ssh/molt_deploy_key" if not os.path.exists(ssh_key_path): command = 'ssh-keygen -t rsa -N "" -f {}'.format(ssh_key_path) command = shlex.split(command) subprocess.Popen(command) # Dockerネットワークの作成 clinet = docker.from_env() networks = clinet.networks.list() if 'molt-network' not in [network.name for network in networks]: command = 'docker network create --subnet=172.31.255.0/24 \ --ip-range=172.31.255.0/24 --gateway=172.31.255.254 \ -o "com.docker.network.bridge.host_binding_ipv4"="0.0.0.0" \ molt-network' command = shlex.split(command) subprocess.Popen(command) app.run(host=app.config['HOST'], port=app.config['PORT']) <|fim▁end|>
p.config["BASE_D
<|file_name|>molt_app.py<|end_file_name|><|fim▁begin|>"""Molt Web API with Interface.""" import re import redis import docker import subprocess import os import shlex import requests import sys import argparse from flask import Flask, Response, render_template, abort, request from molt import Molt, MoltError app = Flask(__name__) # コマンドライン引数のパース parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', help='config file path') args = parser.parse_args() if args.config: cfg_file = args.config else: cfg_file = 'config/molt_app.cfg' if not os.path.exists(cfg_file): app.logger.error("{} が存在しません".format(cfg_file)) sys.exit(1) app.config.from_pyfile(cfg_file, silent=True) @app.route('/<virtual_host>', strict_slashes=False) def index(virtual_host): """Moltの実行をプレビューするページ.""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) vhost = {'rev': rev, 'repo': repo, 'user': user, 'full': virtual_host} redirect_url = '//{}.{}/'.format(virtual_host, app.config['BASE_DOMAIN']) return render_template('index.html', vhost=vhost, redirect_url=redirect_url) @app.route('/molt/<virtual_host>', methods=['GET'], strict_slashes=False) def molt(virtual_host): """Moltの実行をストリーミングする(Server-Sent Eventを使ったAPI).""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) m = Molt(rev, repo, user, app.config['BASE_DOMAIN'], app.config['GITHUB_USER'], app.config['GITHUB_TOKEN']) r = redis.StrictRedis(host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT']) def generate(m, r): """Dockerイメージ立ち上げ(ストリーミングするための関数). git clone から docker-compose upまでの一連の処理のSTDIOの送信と、Dockerイメージ の情報取得・設定をする """ # コマンド群の実行 try: for row in m.molt(): row = row.decode() data = row.split('\r')[-1] # CRのみの行は保留されるので取り除く yield event_stream_parser(data) except MoltError as e: yield event_stream_parser(e, event='failure') except Exception: yield event_stream_parser('Molt内部でエラーが発生しました。終了します...', event='failure') else: # RedisへIPアドレスとバーチャルホストの対応を書き込む r.hset('mirror-store', virtual_host, m.get_container_ip()) yield event_stream_parser('', event='success') return Response(generate(m, r), mimetype='text/event-stream') @app.route('/favicon.ico') def favicon(): """favicon.ico.""" abort(404) @app.template_filter('base_domain') def base_domain_filter(path): """Staticファイルを呼び出す際のドメインを指定する.""" return '//' + app.config['BASE_DOMAIN'] + ':' + str(app.config['PORT']) + \ '/' + path @app.route("/hook", methods=['POST']) def hook(): event = request.headers["X-GitHub-Event"] req = request.json if event != "pull_request": return "ok", 200 elif req["action"] not in {"opened", "synchronize"}: return "ok", 200 pr = req["pull_request"] pr_url = pr["comments_url"] pr_sha = pr["head"]["sha"][:7] pr_reponame = pr["head"]["repo"]["name"] pr_owner = pr["head"]["repo"]["owner"]["login"] payload = { "event": "COMMENT", "body": "Launched the preview environment!\nhttp://{}.{}.{}.{}\ ".format(pr_sha, pr_reponame, pr_owner, app.config["BASE_DOMAIN"]), } headers = { "Accept": "application/vnd.github.v3+json", "Content-Type": "application/json", "Authorization": "token {}".format(app.config["GITHUB_TOKEN"]), } requests.post( pr_url, json=payload, headers=headers, ) return "ok", 200 def virtual_host_parse(virtual_host): """Virtual_hostの文字列を 'rev', 'repo', 'user' に分割する. e.g.(1) "host.repo.sitory.user" => "host", "repo.sitory", "user" e.g.(2) "host.repository.user" => "host", "repository", "user" """ p = re.compile(r'(?P<rev>^.+?)\.(?P<repo>.+)\.(?P<user>.+)$') m = p.search(virtual_host) return m.group('rev'), m.group('repo'), m.group('user') def event_stream_parser(data, event=None, id=None, retry=None): """Server-Sent Event 形式へのパーサ.""" event_stream = '' if event: event_stream += 'event: {}\n'.format(event) event_stream += 'data: {}\n'.format(data) if id: event_stream += 'id: {}\n'.format(id) if retry: event_stream += 'retry: {}\n'.format(id) event_stream += '\n' return event_stream if __name__ == '__main__': # RSA鍵の生成 user = os.getenv('USER') ssh_key_path = os.path.expanduser("~")+"/.ssh/molt_deploy_key" if not os. <|fim_middle|> = 'ssh-keygen -t rsa -N "" -f {}'.format(ssh_key_path) command = shlex.split(command) subprocess.Popen(command) # Dockerネットワークの作成 clinet = docker.from_env() networks = clinet.networks.list() if 'molt-network' not in [network.name for network in networks]: command = 'docker network create --subnet=172.31.255.0/24 \ --ip-range=172.31.255.0/24 --gateway=172.31.255.254 \ -o "com.docker.network.bridge.host_binding_ipv4"="0.0.0.0" \ molt-network' command = shlex.split(command) subprocess.Popen(command) app.run(host=app.config['HOST'], port=app.config['PORT']) <|fim▁end|>
path.exists(ssh_key_path): command
<|file_name|>molt_app.py<|end_file_name|><|fim▁begin|>"""Molt Web API with Interface.""" import re import redis import docker import subprocess import os import shlex import requests import sys import argparse from flask import Flask, Response, render_template, abort, request from molt import Molt, MoltError app = Flask(__name__) # コマンドライン引数のパース parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', help='config file path') args = parser.parse_args() if args.config: cfg_file = args.config else: cfg_file = 'config/molt_app.cfg' if not os.path.exists(cfg_file): app.logger.error("{} が存在しません".format(cfg_file)) sys.exit(1) app.config.from_pyfile(cfg_file, silent=True) @app.route('/<virtual_host>', strict_slashes=False) def index(virtual_host): """Moltの実行をプレビューするページ.""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) vhost = {'rev': rev, 'repo': repo, 'user': user, 'full': virtual_host} redirect_url = '//{}.{}/'.format(virtual_host, app.config['BASE_DOMAIN']) return render_template('index.html', vhost=vhost, redirect_url=redirect_url) @app.route('/molt/<virtual_host>', methods=['GET'], strict_slashes=False) def molt(virtual_host): """Moltの実行をストリーミングする(Server-Sent Eventを使ったAPI).""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) m = Molt(rev, repo, user, app.config['BASE_DOMAIN'], app.config['GITHUB_USER'], app.config['GITHUB_TOKEN']) r = redis.StrictRedis(host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT']) def generate(m, r): """Dockerイメージ立ち上げ(ストリーミングするための関数). git clone から docker-compose upまでの一連の処理のSTDIOの送信と、Dockerイメージ の情報取得・設定をする """ # コマンド群の実行 try: for row in m.molt(): row = row.decode() data = row.split('\r')[-1] # CRのみの行は保留されるので取り除く yield event_stream_parser(data) except MoltError as e: yield event_stream_parser(e, event='failure') except Exception: yield event_stream_parser('Molt内部でエラーが発生しました。終了します...', event='failure') else: # RedisへIPアドレスとバーチャルホストの対応を書き込む r.hset('mirror-store', virtual_host, m.get_container_ip()) yield event_stream_parser('', event='success') return Response(generate(m, r), mimetype='text/event-stream') @app.route('/favicon.ico') def favicon(): """favicon.ico.""" abort(404) @app.template_filter('base_domain') def base_domain_filter(path): """Staticファイルを呼び出す際のドメインを指定する.""" return '//' + app.config['BASE_DOMAIN'] + ':' + str(app.config['PORT']) + \ '/' + path @app.route("/hook", methods=['POST']) def hook(): event = request.headers["X-GitHub-Event"] req = request.json if event != "pull_request": return "ok", 200 elif req["action"] not in {"opened", "synchronize"}: return "ok", 200 pr = req["pull_request"] pr_url = pr["comments_url"] pr_sha = pr["head"]["sha"][:7] pr_reponame = pr["head"]["repo"]["name"] pr_owner = pr["head"]["repo"]["owner"]["login"] payload = { "event": "COMMENT", "body": "Launched the preview environment!\nhttp://{}.{}.{}.{}\ ".format(pr_sha, pr_reponame, pr_owner, app.config["BASE_DOMAIN"]), } headers = { "Accept": "application/vnd.github.v3+json", "Content-Type": "application/json", "Authorization": "token {}".format(app.config["GITHUB_TOKEN"]), } requests.post( pr_url, json=payload, headers=headers, ) return "ok", 200 def virtual_host_parse(virtual_host): """Virtual_hostの文字列を 'rev', 'repo', 'user' に分割する. e.g.(1) "host.repo.sitory.user" => "host", "repo.sitory", "user" e.g.(2) "host.repository.user" => "host", "repository", "user" """ p = re.compile(r'(?P<rev>^.+?)\.(?P<repo>.+)\.(?P<user>.+)$') m = p.search(virtual_host) return m.group('rev'), m.group('repo'), m.group('user') def event_stream_parser(data, event=None, id=None, retry=None): """Server-Sent Event 形式へのパーサ.""" event_stream = '' if event: event_stream += 'event: {}\n'.format(event) event_stream += 'data: {}\n'.format(data) if id: event_stream += 'id: {}\n'.format(id) if retry: event_stream += 'retry: {}\n'.format(id) event_stream += '\n' return event_stream if __name__ == '__main__': # RSA鍵の生成 user = os.getenv('USER') ssh_key_path = os.path.expanduser("~")+"/.ssh/molt_deploy_key" if not os.path.exists(ssh_key_path): command = 'ssh-keygen -t rsa -N "" -f {}'.format(ssh_key_path) com <|fim_middle|> ubprocess.Popen(command) # Dockerネットワークの作成 clinet = docker.from_env() networks = clinet.networks.list() if 'molt-network' not in [network.name for network in networks]: command = 'docker network create --subnet=172.31.255.0/24 \ --ip-range=172.31.255.0/24 --gateway=172.31.255.254 \ -o "com.docker.network.bridge.host_binding_ipv4"="0.0.0.0" \ molt-network' command = shlex.split(command) subprocess.Popen(command) app.run(host=app.config['HOST'], port=app.config['PORT']) <|fim▁end|>
mand = shlex.split(command) s
<|file_name|>molt_app.py<|end_file_name|><|fim▁begin|>"""Molt Web API with Interface.""" import re import redis import docker import subprocess import os import shlex import requests import sys import argparse from flask import Flask, Response, render_template, abort, request from molt import Molt, MoltError app = Flask(__name__) # コマンドライン引数のパース parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', help='config file path') args = parser.parse_args() if args.config: cfg_file = args.config else: cfg_file = 'config/molt_app.cfg' if not os.path.exists(cfg_file): app.logger.error("{} が存在しません".format(cfg_file)) sys.exit(1) app.config.from_pyfile(cfg_file, silent=True) @app.route('/<virtual_host>', strict_slashes=False) def index(virtual_host): """Moltの実行をプレビューするページ.""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) vhost = {'rev': rev, 'repo': repo, 'user': user, 'full': virtual_host} redirect_url = '//{}.{}/'.format(virtual_host, app.config['BASE_DOMAIN']) return render_template('index.html', vhost=vhost, redirect_url=redirect_url) @app.route('/molt/<virtual_host>', methods=['GET'], strict_slashes=False) def molt(virtual_host): """Moltの実行をストリーミングする(Server-Sent Eventを使ったAPI).""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) m = Molt(rev, repo, user, app.config['BASE_DOMAIN'], app.config['GITHUB_USER'], app.config['GITHUB_TOKEN']) r = redis.StrictRedis(host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT']) def generate(m, r): """Dockerイメージ立ち上げ(ストリーミングするための関数). git clone から docker-compose upまでの一連の処理のSTDIOの送信と、Dockerイメージ の情報取得・設定をする """ # コマンド群の実行 try: for row in m.molt(): row = row.decode() data = row.split('\r')[-1] # CRのみの行は保留されるので取り除く yield event_stream_parser(data) except MoltError as e: yield event_stream_parser(e, event='failure') except Exception: yield event_stream_parser('Molt内部でエラーが発生しました。終了します...', event='failure') else: # RedisへIPアドレスとバーチャルホストの対応を書き込む r.hset('mirror-store', virtual_host, m.get_container_ip()) yield event_stream_parser('', event='success') return Response(generate(m, r), mimetype='text/event-stream') @app.route('/favicon.ico') def favicon(): """favicon.ico.""" abort(404) @app.template_filter('base_domain') def base_domain_filter(path): """Staticファイルを呼び出す際のドメインを指定する.""" return '//' + app.config['BASE_DOMAIN'] + ':' + str(app.config['PORT']) + \ '/' + path @app.route("/hook", methods=['POST']) def hook(): event = request.headers["X-GitHub-Event"] req = request.json if event != "pull_request": return "ok", 200 elif req["action"] not in {"opened", "synchronize"}: return "ok", 200 pr = req["pull_request"] pr_url = pr["comments_url"] pr_sha = pr["head"]["sha"][:7] pr_reponame = pr["head"]["repo"]["name"] pr_owner = pr["head"]["repo"]["owner"]["login"] payload = { "event": "COMMENT", "body": "Launched the preview environment!\nhttp://{}.{}.{}.{}\ ".format(pr_sha, pr_reponame, pr_owner, app.config["BASE_DOMAIN"]), } headers = { "Accept": "application/vnd.github.v3+json", "Content-Type": "application/json", "Authorization": "token {}".format(app.config["GITHUB_TOKEN"]), } requests.post( pr_url, json=payload, headers=headers, ) return "ok", 200 def virtual_host_parse(virtual_host): """Virtual_hostの文字列を 'rev', 'repo', 'user' に分割する. e.g.(1) "host.repo.sitory.user" => "host", "repo.sitory", "user" e.g.(2) "host.repository.user" => "host", "repository", "user" """ p = re.compile(r'(?P<rev>^.+?)\.(?P<repo>.+)\.(?P<user>.+)$') m = p.search(virtual_host) return m.group('rev'), m.group('repo'), m.group('user') def event_stream_parser(data, event=None, id=None, retry=None): """Server-Sent Event 形式へのパーサ.""" event_stream = '' if event: event_stream += 'event: {}\n'.format(event) event_stream += 'data: {}\n'.format(data) if id: event_stream += 'id: {}\n'.format(id) if retry: event_stream += 'retry: {}\n'.format(id) event_stream += '\n' return event_stream if __name__ == '__main__': # RSA鍵の生成 user = os.getenv('USER') ssh_key_path = os.path.expanduser("~")+"/.ssh/molt_deploy_key" if not os.path.exists(ssh_key_path): command = 'ssh-keygen -t rsa -N "" -f {}'.format(ssh_key_path) command = shlex.split(command) subprocess.Popen(command <|fim_middle|> cker.from_env() networks = clinet.networks.list() if 'molt-network' not in [network.name for network in networks]: command = 'docker network create --subnet=172.31.255.0/24 \ --ip-range=172.31.255.0/24 --gateway=172.31.255.254 \ -o "com.docker.network.bridge.host_binding_ipv4"="0.0.0.0" \ molt-network' command = shlex.split(command) subprocess.Popen(command) app.run(host=app.config['HOST'], port=app.config['PORT']) <|fim▁end|>
) # Dockerネットワークの作成 clinet = do
<|file_name|>molt_app.py<|end_file_name|><|fim▁begin|>"""Molt Web API with Interface.""" import re import redis import docker import subprocess import os import shlex import requests import sys import argparse from flask import Flask, Response, render_template, abort, request from molt import Molt, MoltError app = Flask(__name__) # コマンドライン引数のパース parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', help='config file path') args = parser.parse_args() if args.config: cfg_file = args.config else: cfg_file = 'config/molt_app.cfg' if not os.path.exists(cfg_file): app.logger.error("{} が存在しません".format(cfg_file)) sys.exit(1) app.config.from_pyfile(cfg_file, silent=True) @app.route('/<virtual_host>', strict_slashes=False) def index(virtual_host): """Moltの実行をプレビューするページ.""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) vhost = {'rev': rev, 'repo': repo, 'user': user, 'full': virtual_host} redirect_url = '//{}.{}/'.format(virtual_host, app.config['BASE_DOMAIN']) return render_template('index.html', vhost=vhost, redirect_url=redirect_url) @app.route('/molt/<virtual_host>', methods=['GET'], strict_slashes=False) def molt(virtual_host): """Moltの実行をストリーミングする(Server-Sent Eventを使ったAPI).""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) m = Molt(rev, repo, user, app.config['BASE_DOMAIN'], app.config['GITHUB_USER'], app.config['GITHUB_TOKEN']) r = redis.StrictRedis(host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT']) def generate(m, r): """Dockerイメージ立ち上げ(ストリーミングするための関数). git clone から docker-compose upまでの一連の処理のSTDIOの送信と、Dockerイメージ の情報取得・設定をする """ # コマンド群の実行 try: for row in m.molt(): row = row.decode() data = row.split('\r')[-1] # CRのみの行は保留されるので取り除く yield event_stream_parser(data) except MoltError as e: yield event_stream_parser(e, event='failure') except Exception: yield event_stream_parser('Molt内部でエラーが発生しました。終了します...', event='failure') else: # RedisへIPアドレスとバーチャルホストの対応を書き込む r.hset('mirror-store', virtual_host, m.get_container_ip()) yield event_stream_parser('', event='success') return Response(generate(m, r), mimetype='text/event-stream') @app.route('/favicon.ico') def favicon(): """favicon.ico.""" abort(404) @app.template_filter('base_domain') def base_domain_filter(path): """Staticファイルを呼び出す際のドメインを指定する.""" return '//' + app.config['BASE_DOMAIN'] + ':' + str(app.config['PORT']) + \ '/' + path @app.route("/hook", methods=['POST']) def hook(): event = request.headers["X-GitHub-Event"] req = request.json if event != "pull_request": return "ok", 200 elif req["action"] not in {"opened", "synchronize"}: return "ok", 200 pr = req["pull_request"] pr_url = pr["comments_url"] pr_sha = pr["head"]["sha"][:7] pr_reponame = pr["head"]["repo"]["name"] pr_owner = pr["head"]["repo"]["owner"]["login"] payload = { "event": "COMMENT", "body": "Launched the preview environment!\nhttp://{}.{}.{}.{}\ ".format(pr_sha, pr_reponame, pr_owner, app.config["BASE_DOMAIN"]), } headers = { "Accept": "application/vnd.github.v3+json", "Content-Type": "application/json", "Authorization": "token {}".format(app.config["GITHUB_TOKEN"]), } requests.post( pr_url, json=payload, headers=headers, ) return "ok", 200 def virtual_host_parse(virtual_host): """Virtual_hostの文字列を 'rev', 'repo', 'user' に分割する. e.g.(1) "host.repo.sitory.user" => "host", "repo.sitory", "user" e.g.(2) "host.repository.user" => "host", "repository", "user" """ p = re.compile(r'(?P<rev>^.+?)\.(?P<repo>.+)\.(?P<user>.+)$') m = p.search(virtual_host) return m.group('rev'), m.group('repo'), m.group('user') def event_stream_parser(data, event=None, id=None, retry=None): """Server-Sent Event 形式へのパーサ.""" event_stream = '' if event: event_stream += 'event: {}\n'.format(event) event_stream += 'data: {}\n'.format(data) if id: event_stream += 'id: {}\n'.format(id) if retry: event_stream += 'retry: {}\n'.format(id) event_stream += '\n' return event_stream if __name__ == '__main__': # RSA鍵の生成 user = os.getenv('USER') ssh_key_path = os.path.expanduser("~")+"/.ssh/molt_deploy_key" if not os.path.exists(ssh_key_path): command = 'ssh-keygen -t rsa -N "" -f {}'.format(ssh_key_path) command = shlex.split(command) subprocess.Popen(command) # Dockerネットワークの作成 clinet = docker.from_env() networks = clinet.networks.list() if 'molt-network' not in [network.name for netw <|fim_middle|> <|fim▁end|>
ork in networks]: command = 'docker network create --subnet=172.31.255.0/24 \ --ip-range=172.31.255.0/24 --gateway=172.31.255.254 \ -o "com.docker.network.bridge.host_binding_ipv4"="0.0.0.0" \ molt-network' command = shlex.split(command) subprocess.Popen(command) app.run(host=app.config['HOST'], port=app.config['PORT'])
<|file_name|>molt_app.py<|end_file_name|><|fim▁begin|>"""Molt Web API with Interface.""" import re import redis import docker import subprocess import os import shlex import requests import sys import argparse from flask import Flask, Response, render_template, abort, request from molt import Molt, MoltError app = Flask(__name__) # コマンドライン引数のパース parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', help='config file path') args = parser.parse_args() if args.config: cfg_file = args.config else: cfg_file = 'config/molt_app.cfg' if not os.path.exists(cfg_file): app.logger.error("{} が存在しません".format(cfg_file)) sys.exit(1) app.config.from_pyfile(cfg_file, silent=True) @app.route('/<virtual_host>', strict_slashes=False) def index(virtual_host): """Moltの実行をプレビューするページ.""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) vhost = {'rev': rev, 'repo': repo, 'user': user, 'full': virtual_host} redirect_url = '//{}.{}/'.format(virtual_host, app.config['BASE_DOMAIN']) return render_template('index.html', vhost=vhost, redirect_url=redirect_url) @app.route('/molt/<virtual_host>', methods=['GET'], strict_slashes=False) def molt(virtual_host): """Moltの実行をストリーミングする(Server-Sent Eventを使ったAPI).""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) m = Molt(rev, repo, user, app.config['BASE_DOMAIN'], app.config['GITHUB_USER'], app.config['GITHUB_TOKEN']) r = redis.StrictRedis(host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT']) def generate(m, r): """Dockerイメージ立ち上げ(ストリーミングするための関数). git clone から docker-compose upまでの一連の処理のSTDIOの送信と、Dockerイメージ の情報取得・設定をする """ # コマンド群の実行 try: for row in m.molt(): row = row.decode() data = row.split('\r')[-1] # CRのみの行は保留されるので取り除く yield event_stream_parser(data) except MoltError as e: yield event_stream_parser(e, event='failure') except Exception: yield event_stream_parser('Molt内部でエラーが発生しました。終了します...', event='failure') else: # RedisへIPアドレスとバーチャルホストの対応を書き込む r.hset('mirror-store', virtual_host, m.get_container_ip()) yield event_stream_parser('', event='success') return Response(generate(m, r), mimetype='text/event-stream') @app.route('/favicon.ico') def favicon(): """favicon.ico.""" abort(404) @app.template_filter('base_domain') def base_domain_filter(path): """Staticファイルを呼び出す際のドメインを指定する.""" return '//' + app.config['BASE_DOMAIN'] + ':' + str(app.config['PORT']) + \ '/' + path @app.route("/hook", methods=['POST']) def hook(): event = request.headers["X-GitHub-Event"] req = request.json if event != "pull_request": return "ok", 200 elif req["action"] not in {"opened", "synchronize"}: return "ok", 200 pr = req["pull_request"] pr_url = pr["comments_url"] pr_sha = pr["head"]["sha"][:7] pr_reponame = pr["head"]["repo"]["name"] pr_owner = pr["head"]["repo"]["owner"]["login"] payload = { "event": "COMMENT", "body": "Launched the preview environment!\nhttp://{}.{}.{}.{}\ ".format(pr_sha, pr_reponame, pr_owner, app.config["BASE_DOMAIN"]), } headers = { "Accept": "application/vnd.github.v3+json", "Content-Type": "application/json", "Authorization": "token {}".format(app.config["GITHUB_TOKEN"]), } requests.post( pr_url, json=payload, headers=headers, ) return "ok", 200 def virtual_host_parse(virtual_host): """Virtual_hostの文字列を 'rev', 'repo', 'user' に分割する. e.g.(1) "host.repo.sitory.user" => "host", "repo.sitory", "user" e.g.(2) "host.repository.user" => "host", "repository", "user" """ p = re.compile(r'(?P<rev>^.+?)\.(?P<repo>.+)\.(?P<user>.+)$') m = p.search(virtual_host) return m.group('rev'), m.group('repo'), m.group('user') def event_stream_parser(data, event=None, id=None, retry=None): """Server-Sent Event 形式へのパーサ.""" event_stream = '' if event: event_stream += 'event: {}\n'.format(event) event_stream += 'data: {}\n'.format(data) if id: event_stream += 'id: {}\n'.format(id) if retry: event_stream += 'retry: {}\n'.format(id) event_stream += '\n' return event_stream if __name__ == '__main__': # RSA鍵の生成 user = os.getenv('USER') ssh_key_path = os.path.expanduser("~")+"/.ssh/molt_deploy_key" if not os.path.exists(ssh_key_path): command = 'ssh-keygen -t rsa -N "" -f {}'.format(ssh_key_path) command = shlex.split(command) subprocess.Popen(command) # Dockerネットワークの作成 clinet = docker.from_env() networks = clinet.networks.list() if 'molt-network' not in [network.name for network in networks]: command = 'docker network create --subnet=172.31.255.0/24 \ --ip-range=172.31.255.0/24 --gateway=172.31 <|fim_middle|> plit(command) subprocess.Popen(command) app.run(host=app.config['HOST'], port=app.config['PORT']) <|fim▁end|>
.255.254 \ -o "com.docker.network.bridge.host_binding_ipv4"="0.0.0.0" \ molt-network' command = shlex.s
<|file_name|>molt_app.py<|end_file_name|><|fim▁begin|>"""Molt Web API with Interface.""" import re import redis import docker import subprocess import os import shlex import requests import sys import argparse from flask import Flask, Response, render_template, abort, request from molt import Molt, MoltError app = Flask(__name__) # コマンドライン引数のパース parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', help='config file path') args = parser.parse_args() if args.config: cfg_file = args.config else: cfg_file = 'config/molt_app.cfg' if not os.path.exists(cfg_file): app.logger.error("{} が存在しません".format(cfg_file)) sys.exit(1) app.config.from_pyfile(cfg_file, silent=True) @app.route('/<virtual_host>', strict_slashes=False) def index(virtual_host): """Moltの実行をプレビューするページ.""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) vhost = {'rev': rev, 'repo': repo, 'user': user, 'full': virtual_host} redirect_url = '//{}.{}/'.format(virtual_host, app.config['BASE_DOMAIN']) return render_template('index.html', vhost=vhost, redirect_url=redirect_url) @app.route('/molt/<virtual_host>', methods=['GET'], strict_slashes=False) def molt(virtual_host): """Moltの実行をストリーミングする(Server-Sent Eventを使ったAPI).""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) m = Molt(rev, repo, user, app.config['BASE_DOMAIN'], app.config['GITHUB_USER'], app.config['GITHUB_TOKEN']) r = redis.StrictRedis(host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT']) def generate(m, r): """Dockerイメージ立ち上げ(ストリーミングするための関数). git clone から docker-compose upまでの一連の処理のSTDIOの送信と、Dockerイメージ の情報取得・設定をする """ # コマンド群の実行 try: for row in m.molt(): row = row.decode() data = row.split('\r')[-1] # CRのみの行は保留されるので取り除く yield event_stream_parser(data) except MoltError as e: yield event_stream_parser(e, event='failure') except Exception: yield event_stream_parser('Molt内部でエラーが発生しました。終了します...', event='failure') else: # RedisへIPアドレスとバーチャルホストの対応を書き込む r.hset('mirror-store', virtual_host, m.get_container_ip()) yield event_stream_parser('', event='success') return Response(generate(m, r), mimetype='text/event-stream') @app.route('/favicon.ico') def favicon(): """favicon.ico.""" abort(404) @app.template_filter('base_domain') def base_domain_filter(path): """Staticファイルを呼び出す際のドメインを指定する.""" return '//' + app.config['BASE_DOMAIN'] + ':' + str(app.config['PORT']) + \ '/' + path @app.route("/hook", methods=['POST']) def hook(): event = request.headers["X-GitHub-Event"] req = request.json if event != "pull_request": return "ok", 200 elif req["action"] not in {"opened", "synchronize"}: return "ok", 200 pr = req["pull_request"] pr_url = pr["comments_url"] pr_sha = pr["head"]["sha"][:7] pr_reponame = pr["head"]["repo"]["name"] pr_owner = pr["head"]["repo"]["owner"]["login"] payload = { "event": "COMMENT", "body": "Launched the preview environment!\nhttp://{}.{}.{}.{}\ ".format(pr_sha, pr_reponame, pr_owner, app.config["BASE_DOMAIN"]), } headers = { "Accept": "application/vnd.github.v3+json", "Content-Type": "application/json", "Authorization": "token {}".format(app.config["GITHUB_TOKEN"]), } requests.post( pr_url, json=payload, headers=headers, ) return "ok", 200 def virtual_host_parse(virtual_host): """Virtual_hostの文字列を 'rev', 'repo', 'user' に分割する. e.g.(1) "host.repo.sitory.user" => "host", "repo.sitory", "user" e.g.(2) "host.repository.user" => "host", "repository", "user" """ p = re.compile(r'(?P<rev>^.+?)\.(?P<repo>.+)\.(?P<user>.+)$') m = p.search(virtual_host) return m.group('rev'), m.group('repo'), m.group('user') def event_stream_parser(data, event=None, id=None, retry=None): """Server-Sent Event 形式へのパーサ.""" event_stream = '' if event: event_stream += 'event: {}\n'.format(event) event_stream += 'data: {}\n'.format(data) if id: event_stream += 'id: {}\n'.format(id) if retry: event_stream += 'retry: {}\n'.format(id) event_stream += '\n' return event_stream if __name__ == '__main__': # RSA鍵の生成 user = os.getenv('USER') ssh_key_path = os.path.expanduser("~")+"/.ssh/molt_deploy_key" if not os.path.exists(ssh_key_path): command = 'ssh-keygen -t rsa -N "" -f {}'.format(ssh_key_path) command = shlex.split(command) subprocess.Popen(command) # Dockerネットワークの作成 clinet = docker.from_env() networks = clinet.networks.list() if 'molt-network' not in [network.name for network in networks]: command = 'docker network create --subnet=172.31.255.0/24 \ --ip-range=172.31.255.0/24 --gateway=172.31.255.254 \ -o "com.docker.network.bridge.host_binding_ipv4"="0.0.0.0" \ molt-network' command = shlex.split(command) subprocess.Popen(command) app.run(host=app.config['HOST'], port=app.config['PORT']) <|fim_middle|> <|fim▁end|>
<|file_name|>molt_app.py<|end_file_name|><|fim▁begin|>"""Molt Web API with Interface.""" import re import redis import docker import subprocess import os import shlex import requests import sys import argparse from flask import Flask, Response, render_template, abort, request from molt import Molt, MoltError app = Flask(__name__) # コマンドライン引数のパース parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', help='config file path') args = parser.parse_args() if args.config: cfg_file = args.config else: cfg_file = 'config/molt_app.cfg' if not os.path.exists(cfg_file): app.logger.error("{} が存在しません".format(cfg_file)) sys.exit(1) app.config.from_pyfile(cfg_file, silent=True) @app.route('/<virtual_host>', strict_slashes=False) def index(virtual_host): """Moltの実行をプレビュ<|fim_middle|>ジ.""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) vhost = {'rev': rev, 'repo': repo, 'user': user, 'full': virtual_host} redirect_url = '//{}.{}/'.format(virtual_host, app.config['BASE_DOMAIN']) return render_template('index.html', vhost=vhost, redirect_url=redirect_url) @app.route('/molt/<virtual_host>', methods=['GET'], strict_slashes=False) def molt(virtual_host): """Moltの実行をストリーミングする(Server-Sent Eventを使ったAPI).""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) m = Molt(rev, repo, user, app.config['BASE_DOMAIN'], app.config['GITHUB_USER'], app.config['GITHUB_TOKEN']) r = redis.StrictRedis(host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT']) def generate(m, r): """Dockerイメージ立ち上げ(ストリーミングするための関数). git clone から docker-compose upまでの一連の処理のSTDIOの送信と、Dockerイメージ の情報取得・設定をする """ # コマンド群の実行 try: for row in m.molt(): row = row.decode() data = row.split('\r')[-1] # CRのみの行は保留されるので取り除く yield event_stream_parser(data) except MoltError as e: yield event_stream_parser(e, event='failure') except Exception: yield event_stream_parser('Molt内部でエラーが発生しました。終了します...', event='failure') else: # RedisへIPアドレスとバーチャルホストの対応を書き込む r.hset('mirror-store', virtual_host, m.get_container_ip()) yield event_stream_parser('', event='success') return Response(generate(m, r), mimetype='text/event-stream') @app.route('/favicon.ico') def favicon(): """favicon.ico.""" abort(404) @app.template_filter('base_domain') def base_domain_filter(path): """Staticファイルを呼び出す際のドメインを指定する.""" return '//' + app.config['BASE_DOMAIN'] + ':' + str(app.config['PORT']) + \ '/' + path @app.route("/hook", methods=['POST']) def hook(): event = request.headers["X-GitHub-Event"] req = request.json if event != "pull_request": return "ok", 200 elif req["action"] not in {"opened", "synchronize"}: return "ok", 200 pr = req["pull_request"] pr_url = pr["comments_url"] pr_sha = pr["head"]["sha"][:7] pr_reponame = pr["head"]["repo"]["name"] pr_owner = pr["head"]["repo"]["owner"]["login"] payload = { "event": "COMMENT", "body": "Launched the preview environment!\nhttp://{}.{}.{}.{}\ ".format(pr_sha, pr_reponame, pr_owner, app.config["BASE_DOMAIN"]), } headers = { "Accept": "application/vnd.github.v3+json", "Content-Type": "application/json", "Authorization": "token {}".format(app.config["GITHUB_TOKEN"]), } requests.post( pr_url, json=payload, headers=headers, ) return "ok", 200 def virtual_host_parse(virtual_host): """Virtual_hostの文字列を 'rev', 'repo', 'user' に分割する. e.g.(1) "host.repo.sitory.user" => "host", "repo.sitory", "user" e.g.(2) "host.repository.user" => "host", "repository", "user" """ p = re.compile(r'(?P<rev>^.+?)\.(?P<repo>.+)\.(?P<user>.+)$') m = p.search(virtual_host) return m.group('rev'), m.group('repo'), m.group('user') def event_stream_parser(data, event=None, id=None, retry=None): """Server-Sent Event 形式へのパーサ.""" event_stream = '' if event: event_stream += 'event: {}\n'.format(event) event_stream += 'data: {}\n'.format(data) if id: event_stream += 'id: {}\n'.format(id) if retry: event_stream += 'retry: {}\n'.format(id) event_stream += '\n' return event_stream if __name__ == '__main__': # RSA鍵の生成 user = os.getenv('USER') ssh_key_path = os.path.expanduser("~")+"/.ssh/molt_deploy_key" if not os.path.exists(ssh_key_path): command = 'ssh-keygen -t rsa -N "" -f {}'.format(ssh_key_path) command = shlex.split(command) subprocess.Popen(command) # Dockerネットワークの作成 clinet = docker.from_env() networks = clinet.networks.list() if 'molt-network' not in [network.name for network in networks]: command = 'docker network create --subnet=172.31.255.0/24 \ --ip-range=172.31.255.0/24 --gateway=172.31.255.254 \ -o "com.docker.network.bridge.host_binding_ipv4"="0.0.0.0" \ molt-network' command = shlex.split(command) subprocess.Popen(command) app.run(host=app.config['HOST'], port=app.config['PORT']) <|fim▁end|>
ーするペー
<|file_name|>molt_app.py<|end_file_name|><|fim▁begin|>"""Molt Web API with Interface.""" import re import redis import docker import subprocess import os import shlex import requests import sys import argparse from flask import Flask, Response, render_template, abort, request from molt import Molt, MoltError app = Flask(__name__) # コマンドライン引数のパース parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', help='config file path') args = parser.parse_args() if args.config: cfg_file = args.config else: cfg_file = 'config/molt_app.cfg' if not os.path.exists(cfg_file): app.logger.error("{} が存在しません".format(cfg_file)) sys.exit(1) app.config.from_pyfile(cfg_file, silent=True) @app.route('/<virtual_host>', strict_slashes=False) def index(virtual_host): """Moltの実行をプレビューするページ.""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) vhost = {'rev': rev, 'repo': repo, 'user': user, 'full': virtual_host} redirect_url = '//{}.{}/'.format(virtual_host, app.config['BASE_DOMAIN']) return render_template('index.html', vhost=vhost, redirect_url=redirect_url) @app.route('/molt/<virtual_host>', methods=['GET'], strict_slashes=False) def molt(virtual_host): """Moltの実行をストリーミングする(Server-Sent Eventを使ったAP<|fim_middle|>"" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) m = Molt(rev, repo, user, app.config['BASE_DOMAIN'], app.config['GITHUB_USER'], app.config['GITHUB_TOKEN']) r = redis.StrictRedis(host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT']) def generate(m, r): """Dockerイメージ立ち上げ(ストリーミングするための関数). git clone から docker-compose upまでの一連の処理のSTDIOの送信と、Dockerイメージ の情報取得・設定をする """ # コマンド群の実行 try: for row in m.molt(): row = row.decode() data = row.split('\r')[-1] # CRのみの行は保留されるので取り除く yield event_stream_parser(data) except MoltError as e: yield event_stream_parser(e, event='failure') except Exception: yield event_stream_parser('Molt内部でエラーが発生しました。終了します...', event='failure') else: # RedisへIPアドレスとバーチャルホストの対応を書き込む r.hset('mirror-store', virtual_host, m.get_container_ip()) yield event_stream_parser('', event='success') return Response(generate(m, r), mimetype='text/event-stream') @app.route('/favicon.ico') def favicon(): """favicon.ico.""" abort(404) @app.template_filter('base_domain') def base_domain_filter(path): """Staticファイルを呼び出す際のドメインを指定する.""" return '//' + app.config['BASE_DOMAIN'] + ':' + str(app.config['PORT']) + \ '/' + path @app.route("/hook", methods=['POST']) def hook(): event = request.headers["X-GitHub-Event"] req = request.json if event != "pull_request": return "ok", 200 elif req["action"] not in {"opened", "synchronize"}: return "ok", 200 pr = req["pull_request"] pr_url = pr["comments_url"] pr_sha = pr["head"]["sha"][:7] pr_reponame = pr["head"]["repo"]["name"] pr_owner = pr["head"]["repo"]["owner"]["login"] payload = { "event": "COMMENT", "body": "Launched the preview environment!\nhttp://{}.{}.{}.{}\ ".format(pr_sha, pr_reponame, pr_owner, app.config["BASE_DOMAIN"]), } headers = { "Accept": "application/vnd.github.v3+json", "Content-Type": "application/json", "Authorization": "token {}".format(app.config["GITHUB_TOKEN"]), } requests.post( pr_url, json=payload, headers=headers, ) return "ok", 200 def virtual_host_parse(virtual_host): """Virtual_hostの文字列を 'rev', 'repo', 'user' に分割する. e.g.(1) "host.repo.sitory.user" => "host", "repo.sitory", "user" e.g.(2) "host.repository.user" => "host", "repository", "user" """ p = re.compile(r'(?P<rev>^.+?)\.(?P<repo>.+)\.(?P<user>.+)$') m = p.search(virtual_host) return m.group('rev'), m.group('repo'), m.group('user') def event_stream_parser(data, event=None, id=None, retry=None): """Server-Sent Event 形式へのパーサ.""" event_stream = '' if event: event_stream += 'event: {}\n'.format(event) event_stream += 'data: {}\n'.format(data) if id: event_stream += 'id: {}\n'.format(id) if retry: event_stream += 'retry: {}\n'.format(id) event_stream += '\n' return event_stream if __name__ == '__main__': # RSA鍵の生成 user = os.getenv('USER') ssh_key_path = os.path.expanduser("~")+"/.ssh/molt_deploy_key" if not os.path.exists(ssh_key_path): command = 'ssh-keygen -t rsa -N "" -f {}'.format(ssh_key_path) command = shlex.split(command) subprocess.Popen(command) # Dockerネットワークの作成 clinet = docker.from_env() networks = clinet.networks.list() if 'molt-network' not in [network.name for network in networks]: command = 'docker network create --subnet=172.31.255.0/24 \ --ip-range=172.31.255.0/24 --gateway=172.31.255.254 \ -o "com.docker.network.bridge.host_binding_ipv4"="0.0.0.0" \ molt-network' command = shlex.split(command) subprocess.Popen(command) app.run(host=app.config['HOST'], port=app.config['PORT']) <|fim▁end|>
I)."
<|file_name|>molt_app.py<|end_file_name|><|fim▁begin|>"""Molt Web API with Interface.""" import re import redis import docker import subprocess import os import shlex import requests import sys import argparse from flask import Flask, Response, render_template, abort, request from molt import Molt, MoltError app = Flask(__name__) # コマンドライン引数のパース parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', help='config file path') args = parser.parse_args() if args.config: cfg_file = args.config else: cfg_file = 'config/molt_app.cfg' if not os.path.exists(cfg_file): app.logger.error("{} が存在しません".format(cfg_file)) sys.exit(1) app.config.from_pyfile(cfg_file, silent=True) @app.route('/<virtual_host>', strict_slashes=False) def index(virtual_host): """Moltの実行をプレビューするページ.""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) vhost = {'rev': rev, 'repo': repo, 'user': user, 'full': virtual_host} redirect_url = '//{}.{}/'.format(virtual_host, app.config['BASE_DOMAIN']) return render_template('index.html', vhost=vhost, redirect_url=redirect_url) @app.route('/molt/<virtual_host>', methods=['GET'], strict_slashes=False) def molt(virtual_host): """Moltの実行をストリーミングする(Server-Sent Eventを使ったAPI).""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) m = Molt(rev, repo, user, app.config['BASE_DOMAIN'], app.config['GITHUB_USER'], app.config['GITHUB_TOKEN']) r = redis.StrictRedis(host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT']) def generate(m, r): """Dockerイメージ立ち上げ(ストリーミングするための関数). git clone から docker-compose upまでの一<|fim_middle|>IOの送信と、Dockerイメージ の情報取得・設定をする """ # コマンド群の実行 try: for row in m.molt(): row = row.decode() data = row.split('\r')[-1] # CRのみの行は保留されるので取り除く yield event_stream_parser(data) except MoltError as e: yield event_stream_parser(e, event='failure') except Exception: yield event_stream_parser('Molt内部でエラーが発生しました。終了します...', event='failure') else: # RedisへIPアドレスとバーチャルホストの対応を書き込む r.hset('mirror-store', virtual_host, m.get_container_ip()) yield event_stream_parser('', event='success') return Response(generate(m, r), mimetype='text/event-stream') @app.route('/favicon.ico') def favicon(): """favicon.ico.""" abort(404) @app.template_filter('base_domain') def base_domain_filter(path): """Staticファイルを呼び出す際のドメインを指定する.""" return '//' + app.config['BASE_DOMAIN'] + ':' + str(app.config['PORT']) + \ '/' + path @app.route("/hook", methods=['POST']) def hook(): event = request.headers["X-GitHub-Event"] req = request.json if event != "pull_request": return "ok", 200 elif req["action"] not in {"opened", "synchronize"}: return "ok", 200 pr = req["pull_request"] pr_url = pr["comments_url"] pr_sha = pr["head"]["sha"][:7] pr_reponame = pr["head"]["repo"]["name"] pr_owner = pr["head"]["repo"]["owner"]["login"] payload = { "event": "COMMENT", "body": "Launched the preview environment!\nhttp://{}.{}.{}.{}\ ".format(pr_sha, pr_reponame, pr_owner, app.config["BASE_DOMAIN"]), } headers = { "Accept": "application/vnd.github.v3+json", "Content-Type": "application/json", "Authorization": "token {}".format(app.config["GITHUB_TOKEN"]), } requests.post( pr_url, json=payload, headers=headers, ) return "ok", 200 def virtual_host_parse(virtual_host): """Virtual_hostの文字列を 'rev', 'repo', 'user' に分割する. e.g.(1) "host.repo.sitory.user" => "host", "repo.sitory", "user" e.g.(2) "host.repository.user" => "host", "repository", "user" """ p = re.compile(r'(?P<rev>^.+?)\.(?P<repo>.+)\.(?P<user>.+)$') m = p.search(virtual_host) return m.group('rev'), m.group('repo'), m.group('user') def event_stream_parser(data, event=None, id=None, retry=None): """Server-Sent Event 形式へのパーサ.""" event_stream = '' if event: event_stream += 'event: {}\n'.format(event) event_stream += 'data: {}\n'.format(data) if id: event_stream += 'id: {}\n'.format(id) if retry: event_stream += 'retry: {}\n'.format(id) event_stream += '\n' return event_stream if __name__ == '__main__': # RSA鍵の生成 user = os.getenv('USER') ssh_key_path = os.path.expanduser("~")+"/.ssh/molt_deploy_key" if not os.path.exists(ssh_key_path): command = 'ssh-keygen -t rsa -N "" -f {}'.format(ssh_key_path) command = shlex.split(command) subprocess.Popen(command) # Dockerネットワークの作成 clinet = docker.from_env() networks = clinet.networks.list() if 'molt-network' not in [network.name for network in networks]: command = 'docker network create --subnet=172.31.255.0/24 \ --ip-range=172.31.255.0/24 --gateway=172.31.255.254 \ -o "com.docker.network.bridge.host_binding_ipv4"="0.0.0.0" \ molt-network' command = shlex.split(command) subprocess.Popen(command) app.run(host=app.config['HOST'], port=app.config['PORT']) <|fim▁end|>
連の処理のSTD
<|file_name|>molt_app.py<|end_file_name|><|fim▁begin|>"""Molt Web API with Interface.""" import re import redis import docker import subprocess import os import shlex import requests import sys import argparse from flask import Flask, Response, render_template, abort, request from molt import Molt, MoltError app = Flask(__name__) # コマンドライン引数のパース parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', help='config file path') args = parser.parse_args() if args.config: cfg_file = args.config else: cfg_file = 'config/molt_app.cfg' if not os.path.exists(cfg_file): app.logger.error("{} が存在しません".format(cfg_file)) sys.exit(1) app.config.from_pyfile(cfg_file, silent=True) @app.route('/<virtual_host>', strict_slashes=False) def index(virtual_host): """Moltの実行をプレビューするページ.""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) vhost = {'rev': rev, 'repo': repo, 'user': user, 'full': virtual_host} redirect_url = '//{}.{}/'.format(virtual_host, app.config['BASE_DOMAIN']) return render_template('index.html', vhost=vhost, redirect_url=redirect_url) @app.route('/molt/<virtual_host>', methods=['GET'], strict_slashes=False) def molt(virtual_host): """Moltの実行をストリーミングする(Server-Sent Eventを使ったAPI).""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) m = Molt(rev, repo, user, app.config['BASE_DOMAIN'], app.config['GITHUB_USER'], app.config['GITHUB_TOKEN']) r = redis.StrictRedis(host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT']) def generate(m, r): """Dockerイメージ立ち上げ(ストリーミングするための関数). git clone から docker-compose upまでの一連の処理のSTDIOの送信と、Dockerイメージ の情報取得・設定をする """ # コマンド群の実行 try: for row in m.molt(): row = row.decode() data = row.split('\r')[-1] # CRのみの行は保留されるので取り除く yield event_stream_parser(data) except MoltError as e: yield event_stream_parser(e, event='failure') except Exception: yield event_stream_parser('Molt内部でエラーが発生しました。終了します...', event='failure') else: # RedisへIPアドレスとバーチャルホストの対応を書き込む r.hset('mirror-store', virtual_host, m.get_container_ip()) yield event_stream_parser('', event='success') return Response(generate(m, r), mimetype='text/event-stream') @app.route('/favicon.ico') def favicon(): """favicon.ico.""" abort(404) @app.template_filter('base_domain') def base_domain_filter(path): """Staticファイルを呼び出す際のドメインを指定する.""" return '//' + app.config['BASE_DOMAIN'] + ':' + str(app.config['PORT']) + \ '/' + path @app.route("/hook", methods=['POST']) def hook(): event = request.headers["X-G<|fim_middle|>vent"] req = request.json if event != "pull_request": return "ok", 200 elif req["action"] not in {"opened", "synchronize"}: return "ok", 200 pr = req["pull_request"] pr_url = pr["comments_url"] pr_sha = pr["head"]["sha"][:7] pr_reponame = pr["head"]["repo"]["name"] pr_owner = pr["head"]["repo"]["owner"]["login"] payload = { "event": "COMMENT", "body": "Launched the preview environment!\nhttp://{}.{}.{}.{}\ ".format(pr_sha, pr_reponame, pr_owner, app.config["BASE_DOMAIN"]), } headers = { "Accept": "application/vnd.github.v3+json", "Content-Type": "application/json", "Authorization": "token {}".format(app.config["GITHUB_TOKEN"]), } requests.post( pr_url, json=payload, headers=headers, ) return "ok", 200 def virtual_host_parse(virtual_host): """Virtual_hostの文字列を 'rev', 'repo', 'user' に分割する. e.g.(1) "host.repo.sitory.user" => "host", "repo.sitory", "user" e.g.(2) "host.repository.user" => "host", "repository", "user" """ p = re.compile(r'(?P<rev>^.+?)\.(?P<repo>.+)\.(?P<user>.+)$') m = p.search(virtual_host) return m.group('rev'), m.group('repo'), m.group('user') def event_stream_parser(data, event=None, id=None, retry=None): """Server-Sent Event 形式へのパーサ.""" event_stream = '' if event: event_stream += 'event: {}\n'.format(event) event_stream += 'data: {}\n'.format(data) if id: event_stream += 'id: {}\n'.format(id) if retry: event_stream += 'retry: {}\n'.format(id) event_stream += '\n' return event_stream if __name__ == '__main__': # RSA鍵の生成 user = os.getenv('USER') ssh_key_path = os.path.expanduser("~")+"/.ssh/molt_deploy_key" if not os.path.exists(ssh_key_path): command = 'ssh-keygen -t rsa -N "" -f {}'.format(ssh_key_path) command = shlex.split(command) subprocess.Popen(command) # Dockerネットワークの作成 clinet = docker.from_env() networks = clinet.networks.list() if 'molt-network' not in [network.name for network in networks]: command = 'docker network create --subnet=172.31.255.0/24 \ --ip-range=172.31.255.0/24 --gateway=172.31.255.254 \ -o "com.docker.network.bridge.host_binding_ipv4"="0.0.0.0" \ molt-network' command = shlex.split(command) subprocess.Popen(command) app.run(host=app.config['HOST'], port=app.config['PORT']) <|fim▁end|>
itHub-E
<|file_name|>molt_app.py<|end_file_name|><|fim▁begin|>"""Molt Web API with Interface.""" import re import redis import docker import subprocess import os import shlex import requests import sys import argparse from flask import Flask, Response, render_template, abort, request from molt import Molt, MoltError app = Flask(__name__) # コマンドライン引数のパース parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', help='config file path') args = parser.parse_args() if args.config: cfg_file = args.config else: cfg_file = 'config/molt_app.cfg' if not os.path.exists(cfg_file): app.logger.error("{} が存在しません".format(cfg_file)) sys.exit(1) app.config.from_pyfile(cfg_file, silent=True) @app.route('/<virtual_host>', strict_slashes=False) def index(virtual_host): """Moltの実行をプレビューするページ.""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) vhost = {'rev': rev, 'repo': repo, 'user': user, 'full': virtual_host} redirect_url = '//{}.{}/'.format(virtual_host, app.config['BASE_DOMAIN']) return render_template('index.html', vhost=vhost, redirect_url=redirect_url) @app.route('/molt/<virtual_host>', methods=['GET'], strict_slashes=False) def molt(virtual_host): """Moltの実行をストリーミングする(Server-Sent Eventを使ったAPI).""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) m = Molt(rev, repo, user, app.config['BASE_DOMAIN'], app.config['GITHUB_USER'], app.config['GITHUB_TOKEN']) r = redis.StrictRedis(host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT']) def generate(m, r): """Dockerイメージ立ち上げ(ストリーミングするための関数). git clone から docker-compose upまでの一連の処理のSTDIOの送信と、Dockerイメージ の情報取得・設定をする """ # コマンド群の実行 try: for row in m.molt(): row = row.decode() data = row.split('\r')[-1] # CRのみの行は保留されるので取り除く yield event_stream_parser(data) except MoltError as e: yield event_stream_parser(e, event='failure') except Exception: yield event_stream_parser('Molt内部でエラーが発生しました。終了します...', event='failure') else: # RedisへIPアドレスとバーチャルホストの対応を書き込む r.hset('mirror-store', virtual_host, m.get_container_ip()) yield event_stream_parser('', event='success') return Response(generate(m, r), mimetype='text/event-stream') @app.route('/favicon.ico') def favicon(): """favicon.ico.""" abort(404) @app.template_filter('base_domain') def base_domain_filter(path): """Staticファイルを呼び出す際のドメインを指定する.""" return '//' + app.config['BASE_DOMAIN'] + ':' + str(app.config['PORT']) + \ '/' + path @app.route("/hook", methods=['POST']) def hook(): event = request.headers["X-GitHub-Event"] req = request.json if event != "pull_request": return "ok", 2<|fim_middle|>ction"] not in {"opened", "synchronize"}: return "ok", 200 pr = req["pull_request"] pr_url = pr["comments_url"] pr_sha = pr["head"]["sha"][:7] pr_reponame = pr["head"]["repo"]["name"] pr_owner = pr["head"]["repo"]["owner"]["login"] payload = { "event": "COMMENT", "body": "Launched the preview environment!\nhttp://{}.{}.{}.{}\ ".format(pr_sha, pr_reponame, pr_owner, app.config["BASE_DOMAIN"]), } headers = { "Accept": "application/vnd.github.v3+json", "Content-Type": "application/json", "Authorization": "token {}".format(app.config["GITHUB_TOKEN"]), } requests.post( pr_url, json=payload, headers=headers, ) return "ok", 200 def virtual_host_parse(virtual_host): """Virtual_hostの文字列を 'rev', 'repo', 'user' に分割する. e.g.(1) "host.repo.sitory.user" => "host", "repo.sitory", "user" e.g.(2) "host.repository.user" => "host", "repository", "user" """ p = re.compile(r'(?P<rev>^.+?)\.(?P<repo>.+)\.(?P<user>.+)$') m = p.search(virtual_host) return m.group('rev'), m.group('repo'), m.group('user') def event_stream_parser(data, event=None, id=None, retry=None): """Server-Sent Event 形式へのパーサ.""" event_stream = '' if event: event_stream += 'event: {}\n'.format(event) event_stream += 'data: {}\n'.format(data) if id: event_stream += 'id: {}\n'.format(id) if retry: event_stream += 'retry: {}\n'.format(id) event_stream += '\n' return event_stream if __name__ == '__main__': # RSA鍵の生成 user = os.getenv('USER') ssh_key_path = os.path.expanduser("~")+"/.ssh/molt_deploy_key" if not os.path.exists(ssh_key_path): command = 'ssh-keygen -t rsa -N "" -f {}'.format(ssh_key_path) command = shlex.split(command) subprocess.Popen(command) # Dockerネットワークの作成 clinet = docker.from_env() networks = clinet.networks.list() if 'molt-network' not in [network.name for network in networks]: command = 'docker network create --subnet=172.31.255.0/24 \ --ip-range=172.31.255.0/24 --gateway=172.31.255.254 \ -o "com.docker.network.bridge.host_binding_ipv4"="0.0.0.0" \ molt-network' command = shlex.split(command) subprocess.Popen(command) app.run(host=app.config['HOST'], port=app.config['PORT']) <|fim▁end|>
00 elif req["a
<|file_name|>molt_app.py<|end_file_name|><|fim▁begin|>"""Molt Web API with Interface.""" import re import redis import docker import subprocess import os import shlex import requests import sys import argparse from flask import Flask, Response, render_template, abort, request from molt import Molt, MoltError app = Flask(__name__) # コマンドライン引数のパース parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', help='config file path') args = parser.parse_args() if args.config: cfg_file = args.config else: cfg_file = 'config/molt_app.cfg' if not os.path.exists(cfg_file): app.logger.error("{} が存在しません".format(cfg_file)) sys.exit(1) app.config.from_pyfile(cfg_file, silent=True) @app.route('/<virtual_host>', strict_slashes=False) def index(virtual_host): """Moltの実行をプレビューするページ.""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) vhost = {'rev': rev, 'repo': repo, 'user': user, 'full': virtual_host} redirect_url = '//{}.{}/'.format(virtual_host, app.config['BASE_DOMAIN']) return render_template('index.html', vhost=vhost, redirect_url=redirect_url) @app.route('/molt/<virtual_host>', methods=['GET'], strict_slashes=False) def molt(virtual_host): """Moltの実行をストリーミングする(Server-Sent Eventを使ったAPI).""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) m = Molt(rev, repo, user, app.config['BASE_DOMAIN'], app.config['GITHUB_USER'], app.config['GITHUB_TOKEN']) r = redis.StrictRedis(host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT']) def generate(m, r): """Dockerイメージ立ち上げ(ストリーミングするための関数). git clone から docker-compose upまでの一連の処理のSTDIOの送信と、Dockerイメージ の情報取得・設定をする """ # コマンド群の実行 try: for row in m.molt(): row = row.decode() data = row.split('\r')[-1] # CRのみの行は保留されるので取り除く yield event_stream_parser(data) except MoltError as e: yield event_stream_parser(e, event='failure') except Exception: yield event_stream_parser('Molt内部でエラーが発生しました。終了します...', event='failure') else: # RedisへIPアドレスとバーチャルホストの対応を書き込む r.hset('mirror-store', virtual_host, m.get_container_ip()) yield event_stream_parser('', event='success') return Response(generate(m, r), mimetype='text/event-stream') @app.route('/favicon.ico') def favicon(): """favicon.ico.""" abort(404) @app.template_filter('base_domain') def base_domain_filter(path): """Staticファイルを呼び出す際のドメインを指定する.""" return '//' + app.config['BASE_DOMAIN'] + ':' + str(app.config['PORT']) + \ '/' + path @app.route("/hook", methods=['POST']) def hook(): event = request.headers["X-GitHub-Event"] req = request.json if event != "pull_request": return "ok", 200 elif req["action"] not in {"opened", "synchronize"}: return "ok", 200 pr = req["pull_request"] pr_url = pr["comments_url"] pr_sha = pr["head"]["sha"][:7] pr_reponame = pr["head"]["repo"]["name"] pr_owner = pr["h<|fim_middle|>]["repo"]["owner"]["login"] payload = { "event": "COMMENT", "body": "Launched the preview environment!\nhttp://{}.{}.{}.{}\ ".format(pr_sha, pr_reponame, pr_owner, app.config["BASE_DOMAIN"]), } headers = { "Accept": "application/vnd.github.v3+json", "Content-Type": "application/json", "Authorization": "token {}".format(app.config["GITHUB_TOKEN"]), } requests.post( pr_url, json=payload, headers=headers, ) return "ok", 200 def virtual_host_parse(virtual_host): """Virtual_hostの文字列を 'rev', 'repo', 'user' に分割する. e.g.(1) "host.repo.sitory.user" => "host", "repo.sitory", "user" e.g.(2) "host.repository.user" => "host", "repository", "user" """ p = re.compile(r'(?P<rev>^.+?)\.(?P<repo>.+)\.(?P<user>.+)$') m = p.search(virtual_host) return m.group('rev'), m.group('repo'), m.group('user') def event_stream_parser(data, event=None, id=None, retry=None): """Server-Sent Event 形式へのパーサ.""" event_stream = '' if event: event_stream += 'event: {}\n'.format(event) event_stream += 'data: {}\n'.format(data) if id: event_stream += 'id: {}\n'.format(id) if retry: event_stream += 'retry: {}\n'.format(id) event_stream += '\n' return event_stream if __name__ == '__main__': # RSA鍵の生成 user = os.getenv('USER') ssh_key_path = os.path.expanduser("~")+"/.ssh/molt_deploy_key" if not os.path.exists(ssh_key_path): command = 'ssh-keygen -t rsa -N "" -f {}'.format(ssh_key_path) command = shlex.split(command) subprocess.Popen(command) # Dockerネットワークの作成 clinet = docker.from_env() networks = clinet.networks.list() if 'molt-network' not in [network.name for network in networks]: command = 'docker network create --subnet=172.31.255.0/24 \ --ip-range=172.31.255.0/24 --gateway=172.31.255.254 \ -o "com.docker.network.bridge.host_binding_ipv4"="0.0.0.0" \ molt-network' command = shlex.split(command) subprocess.Popen(command) app.run(host=app.config['HOST'], port=app.config['PORT']) <|fim▁end|>
ead"
<|file_name|>molt_app.py<|end_file_name|><|fim▁begin|>"""Molt Web API with Interface.""" import re import redis import docker import subprocess import os import shlex import requests import sys import argparse from flask import Flask, Response, render_template, abort, request from molt import Molt, MoltError app = Flask(__name__) # コマンドライン引数のパース parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', help='config file path') args = parser.parse_args() if args.config: cfg_file = args.config else: cfg_file = 'config/molt_app.cfg' if not os.path.exists(cfg_file): app.logger.error("{} が存在しません".format(cfg_file)) sys.exit(1) app.config.from_pyfile(cfg_file, silent=True) @app.route('/<virtual_host>', strict_slashes=False) def index(virtual_host): """Moltの実行をプレビューするページ.""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) vhost = {'rev': rev, 'repo': repo, 'user': user, 'full': virtual_host} redirect_url = '//{}.{}/'.format(virtual_host, app.config['BASE_DOMAIN']) return render_template('index.html', vhost=vhost, redirect_url=redirect_url) @app.route('/molt/<virtual_host>', methods=['GET'], strict_slashes=False) def molt(virtual_host): """Moltの実行をストリーミングする(Server-Sent Eventを使ったAPI).""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) m = Molt(rev, repo, user, app.config['BASE_DOMAIN'], app.config['GITHUB_USER'], app.config['GITHUB_TOKEN']) r = redis.StrictRedis(host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT']) def generate(m, r): """Dockerイメージ立ち上げ(ストリーミングするための関数). git clone から docker-compose upまでの一連の処理のSTDIOの送信と、Dockerイメージ の情報取得・設定をする """ # コマンド群の実行 try: for row in m.molt(): row = row.decode() data = row.split('\r')[-1] # CRのみの行は保留されるので取り除く yield event_stream_parser(data) except MoltError as e: yield event_stream_parser(e, event='failure') except Exception: yield event_stream_parser('Molt内部でエラーが発生しました。終了します...', event='failure') else: # RedisへIPアドレスとバーチャルホストの対応を書き込む r.hset('mirror-store', virtual_host, m.get_container_ip()) yield event_stream_parser('', event='success') return Response(generate(m, r), mimetype='text/event-stream') @app.route('/favicon.ico') def favicon(): """favicon.ico.""" abort(404) @app.template_filter('base_domain') def base_domain_filter(path): """Staticファイルを呼び出す際のドメインを指定する.""" return '//' + app.config['BASE_DOMAIN'] + ':' + str(app.config['PORT']) + \ '/' + path @app.route("/hook", methods=['POST']) def hook(): event = request.headers["X-GitHub-Event"] req = request.json if event != "pull_request": return "ok", 200 elif req["action"] not in {"opened", "synchronize"}: return "ok", 200 pr = req["pull_request"] pr_url = pr["comments_url"] pr_sha = pr["head"]["sha"][:7] pr_reponame = pr["head"]["repo"]["name"] pr_owner = pr["head"]["repo"]["owner"]["login"] payload = { "event": "COMMENT", "body": "Launched the preview environment!\nhttp://{}.{}.{}.{}\ ".format(pr_sha, pr_reponame, pr_owner, app.config["BASE_DOMAIN"]), } headers = { "Accept": "application/vnd.github.v3+json", "Content-Type": "application/json", "Authorization": "token {}".format(app.config["GITHUB_TOKEN"]), } requests.post( pr_url, json=payload, headers=headers, ) return "ok", 200 def virtual_host_parse(virtual_host): """Virtual_hostの文字列を 'rev', 'repo', 'user' に分割する. e.g.(1) "host.repo.sitory.user" => "host", "repo.sitory", "user" e.g.(2) "host.repository.user" => "host", "repository", "user" """ p = re.compile(r'(?P<rev>^.+?)\.(?P<repo>.+)\.(?P<user>.+)$') m = p.search(virtual_host) return m.group('rev'), m.group('repo'), m.gr<|fim_middle|>event_stream_parser(data, event=None, id=None, retry=None): """Server-Sent Event 形式へのパーサ.""" event_stream = '' if event: event_stream += 'event: {}\n'.format(event) event_stream += 'data: {}\n'.format(data) if id: event_stream += 'id: {}\n'.format(id) if retry: event_stream += 'retry: {}\n'.format(id) event_stream += '\n' return event_stream if __name__ == '__main__': # RSA鍵の生成 user = os.getenv('USER') ssh_key_path = os.path.expanduser("~")+"/.ssh/molt_deploy_key" if not os.path.exists(ssh_key_path): command = 'ssh-keygen -t rsa -N "" -f {}'.format(ssh_key_path) command = shlex.split(command) subprocess.Popen(command) # Dockerネットワークの作成 clinet = docker.from_env() networks = clinet.networks.list() if 'molt-network' not in [network.name for network in networks]: command = 'docker network create --subnet=172.31.255.0/24 \ --ip-range=172.31.255.0/24 --gateway=172.31.255.254 \ -o "com.docker.network.bridge.host_binding_ipv4"="0.0.0.0" \ molt-network' command = shlex.split(command) subprocess.Popen(command) app.run(host=app.config['HOST'], port=app.config['PORT']) <|fim▁end|>
oup('user') def
<|file_name|>molt_app.py<|end_file_name|><|fim▁begin|>"""Molt Web API with Interface.""" import re import redis import docker import subprocess import os import shlex import requests import sys import argparse from flask import Flask, Response, render_template, abort, request from molt import Molt, MoltError app = Flask(__name__) # コマンドライン引数のパース parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', help='config file path') args = parser.parse_args() if args.config: cfg_file = args.config else: cfg_file = 'config/molt_app.cfg' if not os.path.exists(cfg_file): app.logger.error("{} が存在しません".format(cfg_file)) sys.exit(1) app.config.from_pyfile(cfg_file, silent=True) @app.route('/<virtual_host>', strict_slashes=False) def index(virtual_host): """Moltの実行をプレビューするページ.""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) vhost = {'rev': rev, 'repo': repo, 'user': user, 'full': virtual_host} redirect_url = '//{}.{}/'.format(virtual_host, app.config['BASE_DOMAIN']) return render_template('index.html', vhost=vhost, redirect_url=redirect_url) @app.route('/molt/<virtual_host>', methods=['GET'], strict_slashes=False) def molt(virtual_host): """Moltの実行をストリーミングする(Server-Sent Eventを使ったAPI).""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) m = Molt(rev, repo, user, app.config['BASE_DOMAIN'], app.config['GITHUB_USER'], app.config['GITHUB_TOKEN']) r = redis.StrictRedis(host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT']) def generate(m, r): """Dockerイメージ立ち上げ(ストリーミングするための関数). git clone から docker-compose upまでの一連の処理のSTDIOの送信と、Dockerイメージ の情報取得・設定をする """ # コマンド群の実行 try: for row in m.molt(): row = row.decode() data = row.split('\r')[-1] # CRのみの行は保留されるので取り除く yield event_stream_parser(data) except MoltError as e: yield event_stream_parser(e, event='failure') except Exception: yield event_stream_parser('Molt内部でエラーが発生しました。終了します...', event='failure') else: # RedisへIPアドレスとバーチャルホストの対応を書き込む r.hset('mirror-store', virtual_host, m.get_container_ip()) yield event_stream_parser('', event='success') return Response(generate(m, r), mimetype='text/event-stream') @app.route('/favicon.ico') def favicon(): """favicon.ico.""" abort(404) @app.template_filter('base_domain') def base_domain_filter(path): """Staticファイルを呼び出す際のドメインを指定する.""" return '//' + app.config['BASE_DOMAIN'] + ':' + str(app.config['PORT']) + \ '/' + path @app.route("/hook", methods=['POST']) def hook(): event = request.headers["X-GitHub-Event"] req = request.json if event != "pull_request": return "ok", 200 elif req["action"] not in {"opened", "synchronize"}: return "ok", 200 pr = req["pull_request"] pr_url = pr["comments_url"] pr_sha = pr["head"]["sha"][:7] pr_reponame = pr["head"]["repo"]["name"] pr_owner = pr["head"]["repo"]["owner"]["login"] payload = { "event": "COMMENT", "body": "Launched the preview environment!\nhttp://{}.{}.{}.{}\ ".format(pr_sha, pr_reponame, pr_owner, app.config["BASE_DOMAIN"]), } headers = { "Accept": "application/vnd.github.v3+json", "Content-Type": "application/json", "Authorization": "token {}".format(app.config["GITHUB_TOKEN"]), } requests.post( pr_url, json=payload, headers=headers, ) return "ok", 200 def virtual_host_parse(virtual_host): """Virtual_hostの文字列を 'rev', 'repo', 'user' に分割する. e.g.(1) "host.repo.sitory.user" => "host", "repo.sitory", "user" e.g.(2) "host.repository.user" => "host", "repository", "user" """ p = re.compile(r'(?P<rev>^.+?)\.(?P<repo>.+)\.(?P<user>.+)$') m = p.search(virtual_host) return m.group('rev'), m.group('repo'), m.group('user') def event_stream_parser(data, event=None, id=None, retry=None): """Server-Sent Event 形式へのパーサ.""" event_stream = '' if event: event_stream += 'event: {}\n'.format(event) event_stream += 'data: {}\n'.format(data) if id: event_stream += 'id: {}\n'.format(id) if retry: event_stream += 'retry: {}\n'.format(id) event_stream += '\n' return event_strea<|fim_middle|>'__main__': # RSA鍵の生成 user = os.getenv('USER') ssh_key_path = os.path.expanduser("~")+"/.ssh/molt_deploy_key" if not os.path.exists(ssh_key_path): command = 'ssh-keygen -t rsa -N "" -f {}'.format(ssh_key_path) command = shlex.split(command) subprocess.Popen(command) # Dockerネットワークの作成 clinet = docker.from_env() networks = clinet.networks.list() if 'molt-network' not in [network.name for network in networks]: command = 'docker network create --subnet=172.31.255.0/24 \ --ip-range=172.31.255.0/24 --gateway=172.31.255.254 \ -o "com.docker.network.bridge.host_binding_ipv4"="0.0.0.0" \ molt-network' command = shlex.split(command) subprocess.Popen(command) app.run(host=app.config['HOST'], port=app.config['PORT']) <|fim▁end|>
m if __name__ ==
<|file_name|>base.py<|end_file_name|><|fim▁begin|>from ..parsers.errors import ErrorResponse from warnings import warn def raise_for_error(f):<|fim▁hole|> :param f: :return: """ def inner(*args, **kwargs): warn('`raise_for_error` is deprecated and will not process any response content.') return f(*args, **kwargs) # e = ErrorResponse.load(content) # e.raise_for_error() # return content return inner def raise_response_for_error(f): """ Wrapper method to parse a response object and raise the ErrorResponse instance if an error is encountered in the response body. :param f: :return: """ def inner(*args, **kwargs): warn('`raise_response_for_error` is deprecated and will not process any response content.') return f(*args, **kwargs) return inner<|fim▁end|>
""" Wrapper method to parse any error response and raise the ErrorResponse instance if an error is encountered.
<|file_name|>base.py<|end_file_name|><|fim▁begin|>from ..parsers.errors import ErrorResponse from warnings import warn def raise_for_error(f): <|fim_middle|> def raise_response_for_error(f): """ Wrapper method to parse a response object and raise the ErrorResponse instance if an error is encountered in the response body. :param f: :return: """ def inner(*args, **kwargs): warn('`raise_response_for_error` is deprecated and will not process any response content.') return f(*args, **kwargs) return inner <|fim▁end|>
""" Wrapper method to parse any error response and raise the ErrorResponse instance if an error is encountered. :param f: :return: """ def inner(*args, **kwargs): warn('`raise_for_error` is deprecated and will not process any response content.') return f(*args, **kwargs) # e = ErrorResponse.load(content) # e.raise_for_error() # return content return inner
<|file_name|>base.py<|end_file_name|><|fim▁begin|>from ..parsers.errors import ErrorResponse from warnings import warn def raise_for_error(f): """ Wrapper method to parse any error response and raise the ErrorResponse instance if an error is encountered. :param f: :return: """ def inner(*args, **kwargs): <|fim_middle|> return inner def raise_response_for_error(f): """ Wrapper method to parse a response object and raise the ErrorResponse instance if an error is encountered in the response body. :param f: :return: """ def inner(*args, **kwargs): warn('`raise_response_for_error` is deprecated and will not process any response content.') return f(*args, **kwargs) return inner <|fim▁end|>
warn('`raise_for_error` is deprecated and will not process any response content.') return f(*args, **kwargs) # e = ErrorResponse.load(content) # e.raise_for_error() # return content
<|file_name|>base.py<|end_file_name|><|fim▁begin|>from ..parsers.errors import ErrorResponse from warnings import warn def raise_for_error(f): """ Wrapper method to parse any error response and raise the ErrorResponse instance if an error is encountered. :param f: :return: """ def inner(*args, **kwargs): warn('`raise_for_error` is deprecated and will not process any response content.') return f(*args, **kwargs) # e = ErrorResponse.load(content) # e.raise_for_error() # return content return inner def raise_response_for_error(f): <|fim_middle|> <|fim▁end|>
""" Wrapper method to parse a response object and raise the ErrorResponse instance if an error is encountered in the response body. :param f: :return: """ def inner(*args, **kwargs): warn('`raise_response_for_error` is deprecated and will not process any response content.') return f(*args, **kwargs) return inner
<|file_name|>base.py<|end_file_name|><|fim▁begin|>from ..parsers.errors import ErrorResponse from warnings import warn def raise_for_error(f): """ Wrapper method to parse any error response and raise the ErrorResponse instance if an error is encountered. :param f: :return: """ def inner(*args, **kwargs): warn('`raise_for_error` is deprecated and will not process any response content.') return f(*args, **kwargs) # e = ErrorResponse.load(content) # e.raise_for_error() # return content return inner def raise_response_for_error(f): """ Wrapper method to parse a response object and raise the ErrorResponse instance if an error is encountered in the response body. :param f: :return: """ def inner(*args, **kwargs): <|fim_middle|> return inner <|fim▁end|>
warn('`raise_response_for_error` is deprecated and will not process any response content.') return f(*args, **kwargs)
<|file_name|>base.py<|end_file_name|><|fim▁begin|>from ..parsers.errors import ErrorResponse from warnings import warn def <|fim_middle|>(f): """ Wrapper method to parse any error response and raise the ErrorResponse instance if an error is encountered. :param f: :return: """ def inner(*args, **kwargs): warn('`raise_for_error` is deprecated and will not process any response content.') return f(*args, **kwargs) # e = ErrorResponse.load(content) # e.raise_for_error() # return content return inner def raise_response_for_error(f): """ Wrapper method to parse a response object and raise the ErrorResponse instance if an error is encountered in the response body. :param f: :return: """ def inner(*args, **kwargs): warn('`raise_response_for_error` is deprecated and will not process any response content.') return f(*args, **kwargs) return inner <|fim▁end|>
raise_for_error
<|file_name|>base.py<|end_file_name|><|fim▁begin|>from ..parsers.errors import ErrorResponse from warnings import warn def raise_for_error(f): """ Wrapper method to parse any error response and raise the ErrorResponse instance if an error is encountered. :param f: :return: """ def <|fim_middle|>(*args, **kwargs): warn('`raise_for_error` is deprecated and will not process any response content.') return f(*args, **kwargs) # e = ErrorResponse.load(content) # e.raise_for_error() # return content return inner def raise_response_for_error(f): """ Wrapper method to parse a response object and raise the ErrorResponse instance if an error is encountered in the response body. :param f: :return: """ def inner(*args, **kwargs): warn('`raise_response_for_error` is deprecated and will not process any response content.') return f(*args, **kwargs) return inner <|fim▁end|>
inner
<|file_name|>base.py<|end_file_name|><|fim▁begin|>from ..parsers.errors import ErrorResponse from warnings import warn def raise_for_error(f): """ Wrapper method to parse any error response and raise the ErrorResponse instance if an error is encountered. :param f: :return: """ def inner(*args, **kwargs): warn('`raise_for_error` is deprecated and will not process any response content.') return f(*args, **kwargs) # e = ErrorResponse.load(content) # e.raise_for_error() # return content return inner def <|fim_middle|>(f): """ Wrapper method to parse a response object and raise the ErrorResponse instance if an error is encountered in the response body. :param f: :return: """ def inner(*args, **kwargs): warn('`raise_response_for_error` is deprecated and will not process any response content.') return f(*args, **kwargs) return inner <|fim▁end|>
raise_response_for_error
<|file_name|>base.py<|end_file_name|><|fim▁begin|>from ..parsers.errors import ErrorResponse from warnings import warn def raise_for_error(f): """ Wrapper method to parse any error response and raise the ErrorResponse instance if an error is encountered. :param f: :return: """ def inner(*args, **kwargs): warn('`raise_for_error` is deprecated and will not process any response content.') return f(*args, **kwargs) # e = ErrorResponse.load(content) # e.raise_for_error() # return content return inner def raise_response_for_error(f): """ Wrapper method to parse a response object and raise the ErrorResponse instance if an error is encountered in the response body. :param f: :return: """ def <|fim_middle|>(*args, **kwargs): warn('`raise_response_for_error` is deprecated and will not process any response content.') return f(*args, **kwargs) return inner <|fim▁end|>
inner
<|file_name|>wsgi.py<|end_file_name|><|fim▁begin|>""" WSGI config for nykampweb project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ """ import os <|fim▁hole|> application = get_wsgi_application()<|fim▁end|>
from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "nykampweb.settings")
<|file_name|>pilot.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from modules import Robot import time r = Robot.Robot() state = [0, 1000, 1500] (run, move, write) = range(3) i = run slowdown = 1 flag_A = 0 flag_C = 0 lock = [0, 0, 0, 0] while(True): a = r.Read() for it in range(len(lock)): if lock[it]: lock[it] = lock[it] - 1 if a[0]: # kontrolka ciągła flag_A = 0 flag_C = 0 if a[0] == 1 or a[0] == 5 or a[0] == 6: r.A.run_forever(r.S/slowdown) elif a[0] == 2 or a[0] == 7 or a[0] == 8: r.A.run_forever(-r.S/slowdown) else: r.A.stop() if a[0] == 3 or a[0] == 5 or a[0] == 7: r.C.run_forever(r.S/slowdown) elif a[0] == 4 or a[0] == 6 or a[0] == 8: r.C.run_forever(-r.S/slowdown) else: r.C.stop() elif a[1] and not lock[1]: # kontrolka lewa: dyskretna if a[1] == 1 and i is not run: # kontrolka prawa: ciągła r.changestate(state[i]-state[i-1]) i = i-1 time.sleep(0.5) # (state[i]-state[i-1])/r.S if i is run: slowdown = 1 elif a[1] == 2 and i is not write: r.changestate(state[i]-state[i+1]) i = i+1 slowdown = 5 time.sleep(0.5) # (state[i+1]-state[i])/r.S elif a[1] == 3: r.B.run_forever(r.S) elif a[1] == 4: r.B.run_forever(-r.S) elif a[1] == 9: r.B.stop() else: pass elif a[2]: # kontrolka one-klick if a[2] == 1 or a[2] == 5 or a[2] == 6: # stop na 9 (beacon) if flag_A == -1: r.A.stop() flag_A = 0 lock[0] = 30 # lock = 30 elif not lock[0]: r.A.run_forever(r.S/slowdown) flag_A = 1 elif a[2] == 2 or a[2] == 7 or a[2] == 8: if flag_A == 1: r.A.stop() flag_A = 0 lock[1] = 30 # lock = 30 elif not lock[1]: r.A.run_forever(-r.S/slowdown) flag_A = -1 if a[2] == 3 or a[2] == 5 or a[2] == 7: if flag_C == -1: r.C.stop() flag_C = 0 lock[2] = 30 # lock = 30 elif not lock[2]: r.C.run_forever(r.S/slowdown) flag_C = 1 elif a[2] == 4 or a[2] == 6 or a[2] == 8: if flag_C == 1: r.C.stop flag_C = 0 lock[3] = 30 # lock = 30 elif not lock[3]: r.C.run_forever(-r.S/slowdown) flag_C = -1<|fim▁hole|> flag_C = 0 elif a[3]: # alternatywna one-klick if a[3] == 1: # 1 przycisk - oba silniki if flag_A == -1 and flag_C == -1: r.stop() flag_A = 0 flag_C = 0 lock[0] = 30 # lock = 30 elif not lock[0]: r.run(r.S/slowdown, r.S/slowdown) flag_A = 1 flag_C = 1 elif a[3] == 2: if flag_A == 1 and flag_C == 1: r.stop() flag_A = 0 flag_C = 0 lock[1] = 30 # lock = 30 elif not lock[1]: r.run(-r.S/slowdown, -r.S/slowdown) flag_A = -1 flag_C = -1 elif a[3] == 3: if flag_A == 1 and flag_C == -1: r.stop() flag_A = 0 flag_C = 0 lock[2] = 30 # lock = 30 elif not lock[2]: r.run(-r.S/slowdown, r.S/slowdown) flag_A = -1 flag_C = 1 elif a[3] == 4: if flag_A == -1 and flag_C == 1: r.stop() flag_A = 0 flag_C = 0 lock[3] = 30 # lock = 30 elif not lock[3]: r.run(r.S/slowdown, -r.S/slowdown) flag_A = 1 flag_C = -1 elif a[3] == 9: r.stop() flag_A = 0 flag_C = 0 else: if not flag_A: r.A.stop() if not flag_C: r.C.stop()<|fim▁end|>
if a[2] == 9: r.stop() flag_A = 0
<|file_name|>pilot.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from modules import Robot import time r = Robot.Robot() state = [0, 1000, 1500] (run, move, write) = range(3) i = run slowdown = 1 flag_A = 0 flag_C = 0 lock = [0, 0, 0, 0] while(True): a = r.Read() for it in range(len(lock)): if lock[it]: <|fim_middle|> if a[0]: # kontrolka ciągła flag_A = 0 flag_C = 0 if a[0] == 1 or a[0] == 5 or a[0] == 6: r.A.run_forever(r.S/slowdown) elif a[0] == 2 or a[0] == 7 or a[0] == 8: r.A.run_forever(-r.S/slowdown) else: r.A.stop() if a[0] == 3 or a[0] == 5 or a[0] == 7: r.C.run_forever(r.S/slowdown) elif a[0] == 4 or a[0] == 6 or a[0] == 8: r.C.run_forever(-r.S/slowdown) else: r.C.stop() elif a[1] and not lock[1]: # kontrolka lewa: dyskretna if a[1] == 1 and i is not run: # kontrolka prawa: ciągła r.changestate(state[i]-state[i-1]) i = i-1 time.sleep(0.5) # (state[i]-state[i-1])/r.S if i is run: slowdown = 1 elif a[1] == 2 and i is not write: r.changestate(state[i]-state[i+1]) i = i+1 slowdown = 5 time.sleep(0.5) # (state[i+1]-state[i])/r.S elif a[1] == 3: r.B.run_forever(r.S) elif a[1] == 4: r.B.run_forever(-r.S) elif a[1] == 9: r.B.stop() else: pass elif a[2]: # kontrolka one-klick if a[2] == 1 or a[2] == 5 or a[2] == 6: # stop na 9 (beacon) if flag_A == -1: r.A.stop() flag_A = 0 lock[0] = 30 # lock = 30 elif not lock[0]: r.A.run_forever(r.S/slowdown) flag_A = 1 elif a[2] == 2 or a[2] == 7 or a[2] == 8: if flag_A == 1: r.A.stop() flag_A = 0 lock[1] = 30 # lock = 30 elif not lock[1]: r.A.run_forever(-r.S/slowdown) flag_A = -1 if a[2] == 3 or a[2] == 5 or a[2] == 7: if flag_C == -1: r.C.stop() flag_C = 0 lock[2] = 30 # lock = 30 elif not lock[2]: r.C.run_forever(r.S/slowdown) flag_C = 1 elif a[2] == 4 or a[2] == 6 or a[2] == 8: if flag_C == 1: r.C.stop flag_C = 0 lock[3] = 30 # lock = 30 elif not lock[3]: r.C.run_forever(-r.S/slowdown) flag_C = -1 if a[2] == 9: r.stop() flag_A = 0 flag_C = 0 elif a[3]: # alternatywna one-klick if a[3] == 1: # 1 przycisk - oba silniki if flag_A == -1 and flag_C == -1: r.stop() flag_A = 0 flag_C = 0 lock[0] = 30 # lock = 30 elif not lock[0]: r.run(r.S/slowdown, r.S/slowdown) flag_A = 1 flag_C = 1 elif a[3] == 2: if flag_A == 1 and flag_C == 1: r.stop() flag_A = 0 flag_C = 0 lock[1] = 30 # lock = 30 elif not lock[1]: r.run(-r.S/slowdown, -r.S/slowdown) flag_A = -1 flag_C = -1 elif a[3] == 3: if flag_A == 1 and flag_C == -1: r.stop() flag_A = 0 flag_C = 0 lock[2] = 30 # lock = 30 elif not lock[2]: r.run(-r.S/slowdown, r.S/slowdown) flag_A = -1 flag_C = 1 elif a[3] == 4: if flag_A == -1 and flag_C == 1: r.stop() flag_A = 0 flag_C = 0 lock[3] = 30 # lock = 30 elif not lock[3]: r.run(r.S/slowdown, -r.S/slowdown) flag_A = 1 flag_C = -1 elif a[3] == 9: r.stop() flag_A = 0 flag_C = 0 else: if not flag_A: r.A.stop() if not flag_C: r.C.stop() <|fim▁end|>
lock[it] = lock[it] - 1
<|file_name|>pilot.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from modules import Robot import time r = Robot.Robot() state = [0, 1000, 1500] (run, move, write) = range(3) i = run slowdown = 1 flag_A = 0 flag_C = 0 lock = [0, 0, 0, 0] while(True): a = r.Read() for it in range(len(lock)): if lock[it]: lock[it] = lock[it] - 1 if a[0]: # kontrolka ciągła fl <|fim_middle|> elif a[1] and not lock[1]: # kontrolka lewa: dyskretna if a[1] == 1 and i is not run: # kontrolka prawa: ciągła r.changestate(state[i]-state[i-1]) i = i-1 time.sleep(0.5) # (state[i]-state[i-1])/r.S if i is run: slowdown = 1 elif a[1] == 2 and i is not write: r.changestate(state[i]-state[i+1]) i = i+1 slowdown = 5 time.sleep(0.5) # (state[i+1]-state[i])/r.S elif a[1] == 3: r.B.run_forever(r.S) elif a[1] == 4: r.B.run_forever(-r.S) elif a[1] == 9: r.B.stop() else: pass elif a[2]: # kontrolka one-klick if a[2] == 1 or a[2] == 5 or a[2] == 6: # stop na 9 (beacon) if flag_A == -1: r.A.stop() flag_A = 0 lock[0] = 30 # lock = 30 elif not lock[0]: r.A.run_forever(r.S/slowdown) flag_A = 1 elif a[2] == 2 or a[2] == 7 or a[2] == 8: if flag_A == 1: r.A.stop() flag_A = 0 lock[1] = 30 # lock = 30 elif not lock[1]: r.A.run_forever(-r.S/slowdown) flag_A = -1 if a[2] == 3 or a[2] == 5 or a[2] == 7: if flag_C == -1: r.C.stop() flag_C = 0 lock[2] = 30 # lock = 30 elif not lock[2]: r.C.run_forever(r.S/slowdown) flag_C = 1 elif a[2] == 4 or a[2] == 6 or a[2] == 8: if flag_C == 1: r.C.stop flag_C = 0 lock[3] = 30 # lock = 30 elif not lock[3]: r.C.run_forever(-r.S/slowdown) flag_C = -1 if a[2] == 9: r.stop() flag_A = 0 flag_C = 0 elif a[3]: # alternatywna one-klick if a[3] == 1: # 1 przycisk - oba silniki if flag_A == -1 and flag_C == -1: r.stop() flag_A = 0 flag_C = 0 lock[0] = 30 # lock = 30 elif not lock[0]: r.run(r.S/slowdown, r.S/slowdown) flag_A = 1 flag_C = 1 elif a[3] == 2: if flag_A == 1 and flag_C == 1: r.stop() flag_A = 0 flag_C = 0 lock[1] = 30 # lock = 30 elif not lock[1]: r.run(-r.S/slowdown, -r.S/slowdown) flag_A = -1 flag_C = -1 elif a[3] == 3: if flag_A == 1 and flag_C == -1: r.stop() flag_A = 0 flag_C = 0 lock[2] = 30 # lock = 30 elif not lock[2]: r.run(-r.S/slowdown, r.S/slowdown) flag_A = -1 flag_C = 1 elif a[3] == 4: if flag_A == -1 and flag_C == 1: r.stop() flag_A = 0 flag_C = 0 lock[3] = 30 # lock = 30 elif not lock[3]: r.run(r.S/slowdown, -r.S/slowdown) flag_A = 1 flag_C = -1 elif a[3] == 9: r.stop() flag_A = 0 flag_C = 0 else: if not flag_A: r.A.stop() if not flag_C: r.C.stop() <|fim▁end|>
ag_A = 0 flag_C = 0 if a[0] == 1 or a[0] == 5 or a[0] == 6: r.A.run_forever(r.S/slowdown) elif a[0] == 2 or a[0] == 7 or a[0] == 8: r.A.run_forever(-r.S/slowdown) else: r.A.stop() if a[0] == 3 or a[0] == 5 or a[0] == 7: r.C.run_forever(r.S/slowdown) elif a[0] == 4 or a[0] == 6 or a[0] == 8: r.C.run_forever(-r.S/slowdown) else: r.C.stop()
<|file_name|>pilot.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from modules import Robot import time r = Robot.Robot() state = [0, 1000, 1500] (run, move, write) = range(3) i = run slowdown = 1 flag_A = 0 flag_C = 0 lock = [0, 0, 0, 0] while(True): a = r.Read() for it in range(len(lock)): if lock[it]: lock[it] = lock[it] - 1 if a[0]: # kontrolka ciągła flag_A = 0 flag_C = 0 if a[0] == 1 or a[0] == 5 or a[0] == 6: r. <|fim_middle|> elif a[0] == 2 or a[0] == 7 or a[0] == 8: r.A.run_forever(-r.S/slowdown) else: r.A.stop() if a[0] == 3 or a[0] == 5 or a[0] == 7: r.C.run_forever(r.S/slowdown) elif a[0] == 4 or a[0] == 6 or a[0] == 8: r.C.run_forever(-r.S/slowdown) else: r.C.stop() elif a[1] and not lock[1]: # kontrolka lewa: dyskretna if a[1] == 1 and i is not run: # kontrolka prawa: ciągła r.changestate(state[i]-state[i-1]) i = i-1 time.sleep(0.5) # (state[i]-state[i-1])/r.S if i is run: slowdown = 1 elif a[1] == 2 and i is not write: r.changestate(state[i]-state[i+1]) i = i+1 slowdown = 5 time.sleep(0.5) # (state[i+1]-state[i])/r.S elif a[1] == 3: r.B.run_forever(r.S) elif a[1] == 4: r.B.run_forever(-r.S) elif a[1] == 9: r.B.stop() else: pass elif a[2]: # kontrolka one-klick if a[2] == 1 or a[2] == 5 or a[2] == 6: # stop na 9 (beacon) if flag_A == -1: r.A.stop() flag_A = 0 lock[0] = 30 # lock = 30 elif not lock[0]: r.A.run_forever(r.S/slowdown) flag_A = 1 elif a[2] == 2 or a[2] == 7 or a[2] == 8: if flag_A == 1: r.A.stop() flag_A = 0 lock[1] = 30 # lock = 30 elif not lock[1]: r.A.run_forever(-r.S/slowdown) flag_A = -1 if a[2] == 3 or a[2] == 5 or a[2] == 7: if flag_C == -1: r.C.stop() flag_C = 0 lock[2] = 30 # lock = 30 elif not lock[2]: r.C.run_forever(r.S/slowdown) flag_C = 1 elif a[2] == 4 or a[2] == 6 or a[2] == 8: if flag_C == 1: r.C.stop flag_C = 0 lock[3] = 30 # lock = 30 elif not lock[3]: r.C.run_forever(-r.S/slowdown) flag_C = -1 if a[2] == 9: r.stop() flag_A = 0 flag_C = 0 elif a[3]: # alternatywna one-klick if a[3] == 1: # 1 przycisk - oba silniki if flag_A == -1 and flag_C == -1: r.stop() flag_A = 0 flag_C = 0 lock[0] = 30 # lock = 30 elif not lock[0]: r.run(r.S/slowdown, r.S/slowdown) flag_A = 1 flag_C = 1 elif a[3] == 2: if flag_A == 1 and flag_C == 1: r.stop() flag_A = 0 flag_C = 0 lock[1] = 30 # lock = 30 elif not lock[1]: r.run(-r.S/slowdown, -r.S/slowdown) flag_A = -1 flag_C = -1 elif a[3] == 3: if flag_A == 1 and flag_C == -1: r.stop() flag_A = 0 flag_C = 0 lock[2] = 30 # lock = 30 elif not lock[2]: r.run(-r.S/slowdown, r.S/slowdown) flag_A = -1 flag_C = 1 elif a[3] == 4: if flag_A == -1 and flag_C == 1: r.stop() flag_A = 0 flag_C = 0 lock[3] = 30 # lock = 30 elif not lock[3]: r.run(r.S/slowdown, -r.S/slowdown) flag_A = 1 flag_C = -1 elif a[3] == 9: r.stop() flag_A = 0 flag_C = 0 else: if not flag_A: r.A.stop() if not flag_C: r.C.stop() <|fim▁end|>
A.run_forever(r.S/slowdown)
<|file_name|>pilot.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from modules import Robot import time r = Robot.Robot() state = [0, 1000, 1500] (run, move, write) = range(3) i = run slowdown = 1 flag_A = 0 flag_C = 0 lock = [0, 0, 0, 0] while(True): a = r.Read() for it in range(len(lock)): if lock[it]: lock[it] = lock[it] - 1 if a[0]: # kontrolka ciągła flag_A = 0 flag_C = 0 if a[0] == 1 or a[0] == 5 or a[0] == 6: r.A.run_forever(r.S/slowdown) elif a[0] == 2 or a[0] == 7 or a[0] == 8: r. <|fim_middle|> else: r.A.stop() if a[0] == 3 or a[0] == 5 or a[0] == 7: r.C.run_forever(r.S/slowdown) elif a[0] == 4 or a[0] == 6 or a[0] == 8: r.C.run_forever(-r.S/slowdown) else: r.C.stop() elif a[1] and not lock[1]: # kontrolka lewa: dyskretna if a[1] == 1 and i is not run: # kontrolka prawa: ciągła r.changestate(state[i]-state[i-1]) i = i-1 time.sleep(0.5) # (state[i]-state[i-1])/r.S if i is run: slowdown = 1 elif a[1] == 2 and i is not write: r.changestate(state[i]-state[i+1]) i = i+1 slowdown = 5 time.sleep(0.5) # (state[i+1]-state[i])/r.S elif a[1] == 3: r.B.run_forever(r.S) elif a[1] == 4: r.B.run_forever(-r.S) elif a[1] == 9: r.B.stop() else: pass elif a[2]: # kontrolka one-klick if a[2] == 1 or a[2] == 5 or a[2] == 6: # stop na 9 (beacon) if flag_A == -1: r.A.stop() flag_A = 0 lock[0] = 30 # lock = 30 elif not lock[0]: r.A.run_forever(r.S/slowdown) flag_A = 1 elif a[2] == 2 or a[2] == 7 or a[2] == 8: if flag_A == 1: r.A.stop() flag_A = 0 lock[1] = 30 # lock = 30 elif not lock[1]: r.A.run_forever(-r.S/slowdown) flag_A = -1 if a[2] == 3 or a[2] == 5 or a[2] == 7: if flag_C == -1: r.C.stop() flag_C = 0 lock[2] = 30 # lock = 30 elif not lock[2]: r.C.run_forever(r.S/slowdown) flag_C = 1 elif a[2] == 4 or a[2] == 6 or a[2] == 8: if flag_C == 1: r.C.stop flag_C = 0 lock[3] = 30 # lock = 30 elif not lock[3]: r.C.run_forever(-r.S/slowdown) flag_C = -1 if a[2] == 9: r.stop() flag_A = 0 flag_C = 0 elif a[3]: # alternatywna one-klick if a[3] == 1: # 1 przycisk - oba silniki if flag_A == -1 and flag_C == -1: r.stop() flag_A = 0 flag_C = 0 lock[0] = 30 # lock = 30 elif not lock[0]: r.run(r.S/slowdown, r.S/slowdown) flag_A = 1 flag_C = 1 elif a[3] == 2: if flag_A == 1 and flag_C == 1: r.stop() flag_A = 0 flag_C = 0 lock[1] = 30 # lock = 30 elif not lock[1]: r.run(-r.S/slowdown, -r.S/slowdown) flag_A = -1 flag_C = -1 elif a[3] == 3: if flag_A == 1 and flag_C == -1: r.stop() flag_A = 0 flag_C = 0 lock[2] = 30 # lock = 30 elif not lock[2]: r.run(-r.S/slowdown, r.S/slowdown) flag_A = -1 flag_C = 1 elif a[3] == 4: if flag_A == -1 and flag_C == 1: r.stop() flag_A = 0 flag_C = 0 lock[3] = 30 # lock = 30 elif not lock[3]: r.run(r.S/slowdown, -r.S/slowdown) flag_A = 1 flag_C = -1 elif a[3] == 9: r.stop() flag_A = 0 flag_C = 0 else: if not flag_A: r.A.stop() if not flag_C: r.C.stop() <|fim▁end|>
A.run_forever(-r.S/slowdown)
<|file_name|>pilot.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from modules import Robot import time r = Robot.Robot() state = [0, 1000, 1500] (run, move, write) = range(3) i = run slowdown = 1 flag_A = 0 flag_C = 0 lock = [0, 0, 0, 0] while(True): a = r.Read() for it in range(len(lock)): if lock[it]: lock[it] = lock[it] - 1 if a[0]: # kontrolka ciągła flag_A = 0 flag_C = 0 if a[0] == 1 or a[0] == 5 or a[0] == 6: r.A.run_forever(r.S/slowdown) elif a[0] == 2 or a[0] == 7 or a[0] == 8: r.A.run_forever(-r.S/slowdown) else: r. <|fim_middle|> if a[0] == 3 or a[0] == 5 or a[0] == 7: r.C.run_forever(r.S/slowdown) elif a[0] == 4 or a[0] == 6 or a[0] == 8: r.C.run_forever(-r.S/slowdown) else: r.C.stop() elif a[1] and not lock[1]: # kontrolka lewa: dyskretna if a[1] == 1 and i is not run: # kontrolka prawa: ciągła r.changestate(state[i]-state[i-1]) i = i-1 time.sleep(0.5) # (state[i]-state[i-1])/r.S if i is run: slowdown = 1 elif a[1] == 2 and i is not write: r.changestate(state[i]-state[i+1]) i = i+1 slowdown = 5 time.sleep(0.5) # (state[i+1]-state[i])/r.S elif a[1] == 3: r.B.run_forever(r.S) elif a[1] == 4: r.B.run_forever(-r.S) elif a[1] == 9: r.B.stop() else: pass elif a[2]: # kontrolka one-klick if a[2] == 1 or a[2] == 5 or a[2] == 6: # stop na 9 (beacon) if flag_A == -1: r.A.stop() flag_A = 0 lock[0] = 30 # lock = 30 elif not lock[0]: r.A.run_forever(r.S/slowdown) flag_A = 1 elif a[2] == 2 or a[2] == 7 or a[2] == 8: if flag_A == 1: r.A.stop() flag_A = 0 lock[1] = 30 # lock = 30 elif not lock[1]: r.A.run_forever(-r.S/slowdown) flag_A = -1 if a[2] == 3 or a[2] == 5 or a[2] == 7: if flag_C == -1: r.C.stop() flag_C = 0 lock[2] = 30 # lock = 30 elif not lock[2]: r.C.run_forever(r.S/slowdown) flag_C = 1 elif a[2] == 4 or a[2] == 6 or a[2] == 8: if flag_C == 1: r.C.stop flag_C = 0 lock[3] = 30 # lock = 30 elif not lock[3]: r.C.run_forever(-r.S/slowdown) flag_C = -1 if a[2] == 9: r.stop() flag_A = 0 flag_C = 0 elif a[3]: # alternatywna one-klick if a[3] == 1: # 1 przycisk - oba silniki if flag_A == -1 and flag_C == -1: r.stop() flag_A = 0 flag_C = 0 lock[0] = 30 # lock = 30 elif not lock[0]: r.run(r.S/slowdown, r.S/slowdown) flag_A = 1 flag_C = 1 elif a[3] == 2: if flag_A == 1 and flag_C == 1: r.stop() flag_A = 0 flag_C = 0 lock[1] = 30 # lock = 30 elif not lock[1]: r.run(-r.S/slowdown, -r.S/slowdown) flag_A = -1 flag_C = -1 elif a[3] == 3: if flag_A == 1 and flag_C == -1: r.stop() flag_A = 0 flag_C = 0 lock[2] = 30 # lock = 30 elif not lock[2]: r.run(-r.S/slowdown, r.S/slowdown) flag_A = -1 flag_C = 1 elif a[3] == 4: if flag_A == -1 and flag_C == 1: r.stop() flag_A = 0 flag_C = 0 lock[3] = 30 # lock = 30 elif not lock[3]: r.run(r.S/slowdown, -r.S/slowdown) flag_A = 1 flag_C = -1 elif a[3] == 9: r.stop() flag_A = 0 flag_C = 0 else: if not flag_A: r.A.stop() if not flag_C: r.C.stop() <|fim▁end|>
A.stop()
<|file_name|>pilot.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from modules import Robot import time r = Robot.Robot() state = [0, 1000, 1500] (run, move, write) = range(3) i = run slowdown = 1 flag_A = 0 flag_C = 0 lock = [0, 0, 0, 0] while(True): a = r.Read() for it in range(len(lock)): if lock[it]: lock[it] = lock[it] - 1 if a[0]: # kontrolka ciągła flag_A = 0 flag_C = 0 if a[0] == 1 or a[0] == 5 or a[0] == 6: r.A.run_forever(r.S/slowdown) elif a[0] == 2 or a[0] == 7 or a[0] == 8: r.A.run_forever(-r.S/slowdown) else: r.A.stop() if a[0] == 3 or a[0] == 5 or a[0] == 7: r. <|fim_middle|> elif a[0] == 4 or a[0] == 6 or a[0] == 8: r.C.run_forever(-r.S/slowdown) else: r.C.stop() elif a[1] and not lock[1]: # kontrolka lewa: dyskretna if a[1] == 1 and i is not run: # kontrolka prawa: ciągła r.changestate(state[i]-state[i-1]) i = i-1 time.sleep(0.5) # (state[i]-state[i-1])/r.S if i is run: slowdown = 1 elif a[1] == 2 and i is not write: r.changestate(state[i]-state[i+1]) i = i+1 slowdown = 5 time.sleep(0.5) # (state[i+1]-state[i])/r.S elif a[1] == 3: r.B.run_forever(r.S) elif a[1] == 4: r.B.run_forever(-r.S) elif a[1] == 9: r.B.stop() else: pass elif a[2]: # kontrolka one-klick if a[2] == 1 or a[2] == 5 or a[2] == 6: # stop na 9 (beacon) if flag_A == -1: r.A.stop() flag_A = 0 lock[0] = 30 # lock = 30 elif not lock[0]: r.A.run_forever(r.S/slowdown) flag_A = 1 elif a[2] == 2 or a[2] == 7 or a[2] == 8: if flag_A == 1: r.A.stop() flag_A = 0 lock[1] = 30 # lock = 30 elif not lock[1]: r.A.run_forever(-r.S/slowdown) flag_A = -1 if a[2] == 3 or a[2] == 5 or a[2] == 7: if flag_C == -1: r.C.stop() flag_C = 0 lock[2] = 30 # lock = 30 elif not lock[2]: r.C.run_forever(r.S/slowdown) flag_C = 1 elif a[2] == 4 or a[2] == 6 or a[2] == 8: if flag_C == 1: r.C.stop flag_C = 0 lock[3] = 30 # lock = 30 elif not lock[3]: r.C.run_forever(-r.S/slowdown) flag_C = -1 if a[2] == 9: r.stop() flag_A = 0 flag_C = 0 elif a[3]: # alternatywna one-klick if a[3] == 1: # 1 przycisk - oba silniki if flag_A == -1 and flag_C == -1: r.stop() flag_A = 0 flag_C = 0 lock[0] = 30 # lock = 30 elif not lock[0]: r.run(r.S/slowdown, r.S/slowdown) flag_A = 1 flag_C = 1 elif a[3] == 2: if flag_A == 1 and flag_C == 1: r.stop() flag_A = 0 flag_C = 0 lock[1] = 30 # lock = 30 elif not lock[1]: r.run(-r.S/slowdown, -r.S/slowdown) flag_A = -1 flag_C = -1 elif a[3] == 3: if flag_A == 1 and flag_C == -1: r.stop() flag_A = 0 flag_C = 0 lock[2] = 30 # lock = 30 elif not lock[2]: r.run(-r.S/slowdown, r.S/slowdown) flag_A = -1 flag_C = 1 elif a[3] == 4: if flag_A == -1 and flag_C == 1: r.stop() flag_A = 0 flag_C = 0 lock[3] = 30 # lock = 30 elif not lock[3]: r.run(r.S/slowdown, -r.S/slowdown) flag_A = 1 flag_C = -1 elif a[3] == 9: r.stop() flag_A = 0 flag_C = 0 else: if not flag_A: r.A.stop() if not flag_C: r.C.stop() <|fim▁end|>
C.run_forever(r.S/slowdown)
<|file_name|>pilot.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from modules import Robot import time r = Robot.Robot() state = [0, 1000, 1500] (run, move, write) = range(3) i = run slowdown = 1 flag_A = 0 flag_C = 0 lock = [0, 0, 0, 0] while(True): a = r.Read() for it in range(len(lock)): if lock[it]: lock[it] = lock[it] - 1 if a[0]: # kontrolka ciągła flag_A = 0 flag_C = 0 if a[0] == 1 or a[0] == 5 or a[0] == 6: r.A.run_forever(r.S/slowdown) elif a[0] == 2 or a[0] == 7 or a[0] == 8: r.A.run_forever(-r.S/slowdown) else: r.A.stop() if a[0] == 3 or a[0] == 5 or a[0] == 7: r.C.run_forever(r.S/slowdown) elif a[0] == 4 or a[0] == 6 or a[0] == 8: r. <|fim_middle|> else: r.C.stop() elif a[1] and not lock[1]: # kontrolka lewa: dyskretna if a[1] == 1 and i is not run: # kontrolka prawa: ciągła r.changestate(state[i]-state[i-1]) i = i-1 time.sleep(0.5) # (state[i]-state[i-1])/r.S if i is run: slowdown = 1 elif a[1] == 2 and i is not write: r.changestate(state[i]-state[i+1]) i = i+1 slowdown = 5 time.sleep(0.5) # (state[i+1]-state[i])/r.S elif a[1] == 3: r.B.run_forever(r.S) elif a[1] == 4: r.B.run_forever(-r.S) elif a[1] == 9: r.B.stop() else: pass elif a[2]: # kontrolka one-klick if a[2] == 1 or a[2] == 5 or a[2] == 6: # stop na 9 (beacon) if flag_A == -1: r.A.stop() flag_A = 0 lock[0] = 30 # lock = 30 elif not lock[0]: r.A.run_forever(r.S/slowdown) flag_A = 1 elif a[2] == 2 or a[2] == 7 or a[2] == 8: if flag_A == 1: r.A.stop() flag_A = 0 lock[1] = 30 # lock = 30 elif not lock[1]: r.A.run_forever(-r.S/slowdown) flag_A = -1 if a[2] == 3 or a[2] == 5 or a[2] == 7: if flag_C == -1: r.C.stop() flag_C = 0 lock[2] = 30 # lock = 30 elif not lock[2]: r.C.run_forever(r.S/slowdown) flag_C = 1 elif a[2] == 4 or a[2] == 6 or a[2] == 8: if flag_C == 1: r.C.stop flag_C = 0 lock[3] = 30 # lock = 30 elif not lock[3]: r.C.run_forever(-r.S/slowdown) flag_C = -1 if a[2] == 9: r.stop() flag_A = 0 flag_C = 0 elif a[3]: # alternatywna one-klick if a[3] == 1: # 1 przycisk - oba silniki if flag_A == -1 and flag_C == -1: r.stop() flag_A = 0 flag_C = 0 lock[0] = 30 # lock = 30 elif not lock[0]: r.run(r.S/slowdown, r.S/slowdown) flag_A = 1 flag_C = 1 elif a[3] == 2: if flag_A == 1 and flag_C == 1: r.stop() flag_A = 0 flag_C = 0 lock[1] = 30 # lock = 30 elif not lock[1]: r.run(-r.S/slowdown, -r.S/slowdown) flag_A = -1 flag_C = -1 elif a[3] == 3: if flag_A == 1 and flag_C == -1: r.stop() flag_A = 0 flag_C = 0 lock[2] = 30 # lock = 30 elif not lock[2]: r.run(-r.S/slowdown, r.S/slowdown) flag_A = -1 flag_C = 1 elif a[3] == 4: if flag_A == -1 and flag_C == 1: r.stop() flag_A = 0 flag_C = 0 lock[3] = 30 # lock = 30 elif not lock[3]: r.run(r.S/slowdown, -r.S/slowdown) flag_A = 1 flag_C = -1 elif a[3] == 9: r.stop() flag_A = 0 flag_C = 0 else: if not flag_A: r.A.stop() if not flag_C: r.C.stop() <|fim▁end|>
C.run_forever(-r.S/slowdown)
<|file_name|>pilot.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from modules import Robot import time r = Robot.Robot() state = [0, 1000, 1500] (run, move, write) = range(3) i = run slowdown = 1 flag_A = 0 flag_C = 0 lock = [0, 0, 0, 0] while(True): a = r.Read() for it in range(len(lock)): if lock[it]: lock[it] = lock[it] - 1 if a[0]: # kontrolka ciągła flag_A = 0 flag_C = 0 if a[0] == 1 or a[0] == 5 or a[0] == 6: r.A.run_forever(r.S/slowdown) elif a[0] == 2 or a[0] == 7 or a[0] == 8: r.A.run_forever(-r.S/slowdown) else: r.A.stop() if a[0] == 3 or a[0] == 5 or a[0] == 7: r.C.run_forever(r.S/slowdown) elif a[0] == 4 or a[0] == 6 or a[0] == 8: r.C.run_forever(-r.S/slowdown) else: r. <|fim_middle|> elif a[1] and not lock[1]: # kontrolka lewa: dyskretna if a[1] == 1 and i is not run: # kontrolka prawa: ciągła r.changestate(state[i]-state[i-1]) i = i-1 time.sleep(0.5) # (state[i]-state[i-1])/r.S if i is run: slowdown = 1 elif a[1] == 2 and i is not write: r.changestate(state[i]-state[i+1]) i = i+1 slowdown = 5 time.sleep(0.5) # (state[i+1]-state[i])/r.S elif a[1] == 3: r.B.run_forever(r.S) elif a[1] == 4: r.B.run_forever(-r.S) elif a[1] == 9: r.B.stop() else: pass elif a[2]: # kontrolka one-klick if a[2] == 1 or a[2] == 5 or a[2] == 6: # stop na 9 (beacon) if flag_A == -1: r.A.stop() flag_A = 0 lock[0] = 30 # lock = 30 elif not lock[0]: r.A.run_forever(r.S/slowdown) flag_A = 1 elif a[2] == 2 or a[2] == 7 or a[2] == 8: if flag_A == 1: r.A.stop() flag_A = 0 lock[1] = 30 # lock = 30 elif not lock[1]: r.A.run_forever(-r.S/slowdown) flag_A = -1 if a[2] == 3 or a[2] == 5 or a[2] == 7: if flag_C == -1: r.C.stop() flag_C = 0 lock[2] = 30 # lock = 30 elif not lock[2]: r.C.run_forever(r.S/slowdown) flag_C = 1 elif a[2] == 4 or a[2] == 6 or a[2] == 8: if flag_C == 1: r.C.stop flag_C = 0 lock[3] = 30 # lock = 30 elif not lock[3]: r.C.run_forever(-r.S/slowdown) flag_C = -1 if a[2] == 9: r.stop() flag_A = 0 flag_C = 0 elif a[3]: # alternatywna one-klick if a[3] == 1: # 1 przycisk - oba silniki if flag_A == -1 and flag_C == -1: r.stop() flag_A = 0 flag_C = 0 lock[0] = 30 # lock = 30 elif not lock[0]: r.run(r.S/slowdown, r.S/slowdown) flag_A = 1 flag_C = 1 elif a[3] == 2: if flag_A == 1 and flag_C == 1: r.stop() flag_A = 0 flag_C = 0 lock[1] = 30 # lock = 30 elif not lock[1]: r.run(-r.S/slowdown, -r.S/slowdown) flag_A = -1 flag_C = -1 elif a[3] == 3: if flag_A == 1 and flag_C == -1: r.stop() flag_A = 0 flag_C = 0 lock[2] = 30 # lock = 30 elif not lock[2]: r.run(-r.S/slowdown, r.S/slowdown) flag_A = -1 flag_C = 1 elif a[3] == 4: if flag_A == -1 and flag_C == 1: r.stop() flag_A = 0 flag_C = 0 lock[3] = 30 # lock = 30 elif not lock[3]: r.run(r.S/slowdown, -r.S/slowdown) flag_A = 1 flag_C = -1 elif a[3] == 9: r.stop() flag_A = 0 flag_C = 0 else: if not flag_A: r.A.stop() if not flag_C: r.C.stop() <|fim▁end|>
C.stop()
<|file_name|>pilot.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from modules import Robot import time r = Robot.Robot() state = [0, 1000, 1500] (run, move, write) = range(3) i = run slowdown = 1 flag_A = 0 flag_C = 0 lock = [0, 0, 0, 0] while(True): a = r.Read() for it in range(len(lock)): if lock[it]: lock[it] = lock[it] - 1 if a[0]: # kontrolka ciągła flag_A = 0 flag_C = 0 if a[0] == 1 or a[0] == 5 or a[0] == 6: r.A.run_forever(r.S/slowdown) elif a[0] == 2 or a[0] == 7 or a[0] == 8: r.A.run_forever(-r.S/slowdown) else: r.A.stop() if a[0] == 3 or a[0] == 5 or a[0] == 7: r.C.run_forever(r.S/slowdown) elif a[0] == 4 or a[0] == 6 or a[0] == 8: r.C.run_forever(-r.S/slowdown) else: r.C.stop() elif a[1] and not lock[1]: # kontrolka lewa: dyskretna if <|fim_middle|> elif a[2]: # kontrolka one-klick if a[2] == 1 or a[2] == 5 or a[2] == 6: # stop na 9 (beacon) if flag_A == -1: r.A.stop() flag_A = 0 lock[0] = 30 # lock = 30 elif not lock[0]: r.A.run_forever(r.S/slowdown) flag_A = 1 elif a[2] == 2 or a[2] == 7 or a[2] == 8: if flag_A == 1: r.A.stop() flag_A = 0 lock[1] = 30 # lock = 30 elif not lock[1]: r.A.run_forever(-r.S/slowdown) flag_A = -1 if a[2] == 3 or a[2] == 5 or a[2] == 7: if flag_C == -1: r.C.stop() flag_C = 0 lock[2] = 30 # lock = 30 elif not lock[2]: r.C.run_forever(r.S/slowdown) flag_C = 1 elif a[2] == 4 or a[2] == 6 or a[2] == 8: if flag_C == 1: r.C.stop flag_C = 0 lock[3] = 30 # lock = 30 elif not lock[3]: r.C.run_forever(-r.S/slowdown) flag_C = -1 if a[2] == 9: r.stop() flag_A = 0 flag_C = 0 elif a[3]: # alternatywna one-klick if a[3] == 1: # 1 przycisk - oba silniki if flag_A == -1 and flag_C == -1: r.stop() flag_A = 0 flag_C = 0 lock[0] = 30 # lock = 30 elif not lock[0]: r.run(r.S/slowdown, r.S/slowdown) flag_A = 1 flag_C = 1 elif a[3] == 2: if flag_A == 1 and flag_C == 1: r.stop() flag_A = 0 flag_C = 0 lock[1] = 30 # lock = 30 elif not lock[1]: r.run(-r.S/slowdown, -r.S/slowdown) flag_A = -1 flag_C = -1 elif a[3] == 3: if flag_A == 1 and flag_C == -1: r.stop() flag_A = 0 flag_C = 0 lock[2] = 30 # lock = 30 elif not lock[2]: r.run(-r.S/slowdown, r.S/slowdown) flag_A = -1 flag_C = 1 elif a[3] == 4: if flag_A == -1 and flag_C == 1: r.stop() flag_A = 0 flag_C = 0 lock[3] = 30 # lock = 30 elif not lock[3]: r.run(r.S/slowdown, -r.S/slowdown) flag_A = 1 flag_C = -1 elif a[3] == 9: r.stop() flag_A = 0 flag_C = 0 else: if not flag_A: r.A.stop() if not flag_C: r.C.stop() <|fim▁end|>
a[1] == 1 and i is not run: # kontrolka prawa: ciągła r.changestate(state[i]-state[i-1]) i = i-1 time.sleep(0.5) # (state[i]-state[i-1])/r.S if i is run: slowdown = 1 elif a[1] == 2 and i is not write: r.changestate(state[i]-state[i+1]) i = i+1 slowdown = 5 time.sleep(0.5) # (state[i+1]-state[i])/r.S elif a[1] == 3: r.B.run_forever(r.S) elif a[1] == 4: r.B.run_forever(-r.S) elif a[1] == 9: r.B.stop() else: pass
<|file_name|>pilot.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from modules import Robot import time r = Robot.Robot() state = [0, 1000, 1500] (run, move, write) = range(3) i = run slowdown = 1 flag_A = 0 flag_C = 0 lock = [0, 0, 0, 0] while(True): a = r.Read() for it in range(len(lock)): if lock[it]: lock[it] = lock[it] - 1 if a[0]: # kontrolka ciągła flag_A = 0 flag_C = 0 if a[0] == 1 or a[0] == 5 or a[0] == 6: r.A.run_forever(r.S/slowdown) elif a[0] == 2 or a[0] == 7 or a[0] == 8: r.A.run_forever(-r.S/slowdown) else: r.A.stop() if a[0] == 3 or a[0] == 5 or a[0] == 7: r.C.run_forever(r.S/slowdown) elif a[0] == 4 or a[0] == 6 or a[0] == 8: r.C.run_forever(-r.S/slowdown) else: r.C.stop() elif a[1] and not lock[1]: # kontrolka lewa: dyskretna if a[1] == 1 and i is not run: # kontrolka prawa: ciągła r.ch <|fim_middle|> elif a[1] == 2 and i is not write: r.changestate(state[i]-state[i+1]) i = i+1 slowdown = 5 time.sleep(0.5) # (state[i+1]-state[i])/r.S elif a[1] == 3: r.B.run_forever(r.S) elif a[1] == 4: r.B.run_forever(-r.S) elif a[1] == 9: r.B.stop() else: pass elif a[2]: # kontrolka one-klick if a[2] == 1 or a[2] == 5 or a[2] == 6: # stop na 9 (beacon) if flag_A == -1: r.A.stop() flag_A = 0 lock[0] = 30 # lock = 30 elif not lock[0]: r.A.run_forever(r.S/slowdown) flag_A = 1 elif a[2] == 2 or a[2] == 7 or a[2] == 8: if flag_A == 1: r.A.stop() flag_A = 0 lock[1] = 30 # lock = 30 elif not lock[1]: r.A.run_forever(-r.S/slowdown) flag_A = -1 if a[2] == 3 or a[2] == 5 or a[2] == 7: if flag_C == -1: r.C.stop() flag_C = 0 lock[2] = 30 # lock = 30 elif not lock[2]: r.C.run_forever(r.S/slowdown) flag_C = 1 elif a[2] == 4 or a[2] == 6 or a[2] == 8: if flag_C == 1: r.C.stop flag_C = 0 lock[3] = 30 # lock = 30 elif not lock[3]: r.C.run_forever(-r.S/slowdown) flag_C = -1 if a[2] == 9: r.stop() flag_A = 0 flag_C = 0 elif a[3]: # alternatywna one-klick if a[3] == 1: # 1 przycisk - oba silniki if flag_A == -1 and flag_C == -1: r.stop() flag_A = 0 flag_C = 0 lock[0] = 30 # lock = 30 elif not lock[0]: r.run(r.S/slowdown, r.S/slowdown) flag_A = 1 flag_C = 1 elif a[3] == 2: if flag_A == 1 and flag_C == 1: r.stop() flag_A = 0 flag_C = 0 lock[1] = 30 # lock = 30 elif not lock[1]: r.run(-r.S/slowdown, -r.S/slowdown) flag_A = -1 flag_C = -1 elif a[3] == 3: if flag_A == 1 and flag_C == -1: r.stop() flag_A = 0 flag_C = 0 lock[2] = 30 # lock = 30 elif not lock[2]: r.run(-r.S/slowdown, r.S/slowdown) flag_A = -1 flag_C = 1 elif a[3] == 4: if flag_A == -1 and flag_C == 1: r.stop() flag_A = 0 flag_C = 0 lock[3] = 30 # lock = 30 elif not lock[3]: r.run(r.S/slowdown, -r.S/slowdown) flag_A = 1 flag_C = -1 elif a[3] == 9: r.stop() flag_A = 0 flag_C = 0 else: if not flag_A: r.A.stop() if not flag_C: r.C.stop() <|fim▁end|>
angestate(state[i]-state[i-1]) i = i-1 time.sleep(0.5) # (state[i]-state[i-1])/r.S if i is run: slowdown = 1
<|file_name|>pilot.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from modules import Robot import time r = Robot.Robot() state = [0, 1000, 1500] (run, move, write) = range(3) i = run slowdown = 1 flag_A = 0 flag_C = 0 lock = [0, 0, 0, 0] while(True): a = r.Read() for it in range(len(lock)): if lock[it]: lock[it] = lock[it] - 1 if a[0]: # kontrolka ciągła flag_A = 0 flag_C = 0 if a[0] == 1 or a[0] == 5 or a[0] == 6: r.A.run_forever(r.S/slowdown) elif a[0] == 2 or a[0] == 7 or a[0] == 8: r.A.run_forever(-r.S/slowdown) else: r.A.stop() if a[0] == 3 or a[0] == 5 or a[0] == 7: r.C.run_forever(r.S/slowdown) elif a[0] == 4 or a[0] == 6 or a[0] == 8: r.C.run_forever(-r.S/slowdown) else: r.C.stop() elif a[1] and not lock[1]: # kontrolka lewa: dyskretna if a[1] == 1 and i is not run: # kontrolka prawa: ciągła r.changestate(state[i]-state[i-1]) i = i-1 time.sleep(0.5) # (state[i]-state[i-1])/r.S if i is run: slow <|fim_middle|> elif a[1] == 2 and i is not write: r.changestate(state[i]-state[i+1]) i = i+1 slowdown = 5 time.sleep(0.5) # (state[i+1]-state[i])/r.S elif a[1] == 3: r.B.run_forever(r.S) elif a[1] == 4: r.B.run_forever(-r.S) elif a[1] == 9: r.B.stop() else: pass elif a[2]: # kontrolka one-klick if a[2] == 1 or a[2] == 5 or a[2] == 6: # stop na 9 (beacon) if flag_A == -1: r.A.stop() flag_A = 0 lock[0] = 30 # lock = 30 elif not lock[0]: r.A.run_forever(r.S/slowdown) flag_A = 1 elif a[2] == 2 or a[2] == 7 or a[2] == 8: if flag_A == 1: r.A.stop() flag_A = 0 lock[1] = 30 # lock = 30 elif not lock[1]: r.A.run_forever(-r.S/slowdown) flag_A = -1 if a[2] == 3 or a[2] == 5 or a[2] == 7: if flag_C == -1: r.C.stop() flag_C = 0 lock[2] = 30 # lock = 30 elif not lock[2]: r.C.run_forever(r.S/slowdown) flag_C = 1 elif a[2] == 4 or a[2] == 6 or a[2] == 8: if flag_C == 1: r.C.stop flag_C = 0 lock[3] = 30 # lock = 30 elif not lock[3]: r.C.run_forever(-r.S/slowdown) flag_C = -1 if a[2] == 9: r.stop() flag_A = 0 flag_C = 0 elif a[3]: # alternatywna one-klick if a[3] == 1: # 1 przycisk - oba silniki if flag_A == -1 and flag_C == -1: r.stop() flag_A = 0 flag_C = 0 lock[0] = 30 # lock = 30 elif not lock[0]: r.run(r.S/slowdown, r.S/slowdown) flag_A = 1 flag_C = 1 elif a[3] == 2: if flag_A == 1 and flag_C == 1: r.stop() flag_A = 0 flag_C = 0 lock[1] = 30 # lock = 30 elif not lock[1]: r.run(-r.S/slowdown, -r.S/slowdown) flag_A = -1 flag_C = -1 elif a[3] == 3: if flag_A == 1 and flag_C == -1: r.stop() flag_A = 0 flag_C = 0 lock[2] = 30 # lock = 30 elif not lock[2]: r.run(-r.S/slowdown, r.S/slowdown) flag_A = -1 flag_C = 1 elif a[3] == 4: if flag_A == -1 and flag_C == 1: r.stop() flag_A = 0 flag_C = 0 lock[3] = 30 # lock = 30 elif not lock[3]: r.run(r.S/slowdown, -r.S/slowdown) flag_A = 1 flag_C = -1 elif a[3] == 9: r.stop() flag_A = 0 flag_C = 0 else: if not flag_A: r.A.stop() if not flag_C: r.C.stop() <|fim▁end|>
down = 1
<|file_name|>pilot.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from modules import Robot import time r = Robot.Robot() state = [0, 1000, 1500] (run, move, write) = range(3) i = run slowdown = 1 flag_A = 0 flag_C = 0 lock = [0, 0, 0, 0] while(True): a = r.Read() for it in range(len(lock)): if lock[it]: lock[it] = lock[it] - 1 if a[0]: # kontrolka ciągła flag_A = 0 flag_C = 0 if a[0] == 1 or a[0] == 5 or a[0] == 6: r.A.run_forever(r.S/slowdown) elif a[0] == 2 or a[0] == 7 or a[0] == 8: r.A.run_forever(-r.S/slowdown) else: r.A.stop() if a[0] == 3 or a[0] == 5 or a[0] == 7: r.C.run_forever(r.S/slowdown) elif a[0] == 4 or a[0] == 6 or a[0] == 8: r.C.run_forever(-r.S/slowdown) else: r.C.stop() elif a[1] and not lock[1]: # kontrolka lewa: dyskretna if a[1] == 1 and i is not run: # kontrolka prawa: ciągła r.changestate(state[i]-state[i-1]) i = i-1 time.sleep(0.5) # (state[i]-state[i-1])/r.S if i is run: slowdown = 1 elif a[1] == 2 and i is not write: r.ch <|fim_middle|> elif a[1] == 3: r.B.run_forever(r.S) elif a[1] == 4: r.B.run_forever(-r.S) elif a[1] == 9: r.B.stop() else: pass elif a[2]: # kontrolka one-klick if a[2] == 1 or a[2] == 5 or a[2] == 6: # stop na 9 (beacon) if flag_A == -1: r.A.stop() flag_A = 0 lock[0] = 30 # lock = 30 elif not lock[0]: r.A.run_forever(r.S/slowdown) flag_A = 1 elif a[2] == 2 or a[2] == 7 or a[2] == 8: if flag_A == 1: r.A.stop() flag_A = 0 lock[1] = 30 # lock = 30 elif not lock[1]: r.A.run_forever(-r.S/slowdown) flag_A = -1 if a[2] == 3 or a[2] == 5 or a[2] == 7: if flag_C == -1: r.C.stop() flag_C = 0 lock[2] = 30 # lock = 30 elif not lock[2]: r.C.run_forever(r.S/slowdown) flag_C = 1 elif a[2] == 4 or a[2] == 6 or a[2] == 8: if flag_C == 1: r.C.stop flag_C = 0 lock[3] = 30 # lock = 30 elif not lock[3]: r.C.run_forever(-r.S/slowdown) flag_C = -1 if a[2] == 9: r.stop() flag_A = 0 flag_C = 0 elif a[3]: # alternatywna one-klick if a[3] == 1: # 1 przycisk - oba silniki if flag_A == -1 and flag_C == -1: r.stop() flag_A = 0 flag_C = 0 lock[0] = 30 # lock = 30 elif not lock[0]: r.run(r.S/slowdown, r.S/slowdown) flag_A = 1 flag_C = 1 elif a[3] == 2: if flag_A == 1 and flag_C == 1: r.stop() flag_A = 0 flag_C = 0 lock[1] = 30 # lock = 30 elif not lock[1]: r.run(-r.S/slowdown, -r.S/slowdown) flag_A = -1 flag_C = -1 elif a[3] == 3: if flag_A == 1 and flag_C == -1: r.stop() flag_A = 0 flag_C = 0 lock[2] = 30 # lock = 30 elif not lock[2]: r.run(-r.S/slowdown, r.S/slowdown) flag_A = -1 flag_C = 1 elif a[3] == 4: if flag_A == -1 and flag_C == 1: r.stop() flag_A = 0 flag_C = 0 lock[3] = 30 # lock = 30 elif not lock[3]: r.run(r.S/slowdown, -r.S/slowdown) flag_A = 1 flag_C = -1 elif a[3] == 9: r.stop() flag_A = 0 flag_C = 0 else: if not flag_A: r.A.stop() if not flag_C: r.C.stop() <|fim▁end|>
angestate(state[i]-state[i+1]) i = i+1 slowdown = 5 time.sleep(0.5) # (state[i+1]-state[i])/r.S
<|file_name|>pilot.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from modules import Robot import time r = Robot.Robot() state = [0, 1000, 1500] (run, move, write) = range(3) i = run slowdown = 1 flag_A = 0 flag_C = 0 lock = [0, 0, 0, 0] while(True): a = r.Read() for it in range(len(lock)): if lock[it]: lock[it] = lock[it] - 1 if a[0]: # kontrolka ciągła flag_A = 0 flag_C = 0 if a[0] == 1 or a[0] == 5 or a[0] == 6: r.A.run_forever(r.S/slowdown) elif a[0] == 2 or a[0] == 7 or a[0] == 8: r.A.run_forever(-r.S/slowdown) else: r.A.stop() if a[0] == 3 or a[0] == 5 or a[0] == 7: r.C.run_forever(r.S/slowdown) elif a[0] == 4 or a[0] == 6 or a[0] == 8: r.C.run_forever(-r.S/slowdown) else: r.C.stop() elif a[1] and not lock[1]: # kontrolka lewa: dyskretna if a[1] == 1 and i is not run: # kontrolka prawa: ciągła r.changestate(state[i]-state[i-1]) i = i-1 time.sleep(0.5) # (state[i]-state[i-1])/r.S if i is run: slowdown = 1 elif a[1] == 2 and i is not write: r.changestate(state[i]-state[i+1]) i = i+1 slowdown = 5 time.sleep(0.5) # (state[i+1]-state[i])/r.S elif a[1] == 3: r.B. <|fim_middle|> elif a[1] == 4: r.B.run_forever(-r.S) elif a[1] == 9: r.B.stop() else: pass elif a[2]: # kontrolka one-klick if a[2] == 1 or a[2] == 5 or a[2] == 6: # stop na 9 (beacon) if flag_A == -1: r.A.stop() flag_A = 0 lock[0] = 30 # lock = 30 elif not lock[0]: r.A.run_forever(r.S/slowdown) flag_A = 1 elif a[2] == 2 or a[2] == 7 or a[2] == 8: if flag_A == 1: r.A.stop() flag_A = 0 lock[1] = 30 # lock = 30 elif not lock[1]: r.A.run_forever(-r.S/slowdown) flag_A = -1 if a[2] == 3 or a[2] == 5 or a[2] == 7: if flag_C == -1: r.C.stop() flag_C = 0 lock[2] = 30 # lock = 30 elif not lock[2]: r.C.run_forever(r.S/slowdown) flag_C = 1 elif a[2] == 4 or a[2] == 6 or a[2] == 8: if flag_C == 1: r.C.stop flag_C = 0 lock[3] = 30 # lock = 30 elif not lock[3]: r.C.run_forever(-r.S/slowdown) flag_C = -1 if a[2] == 9: r.stop() flag_A = 0 flag_C = 0 elif a[3]: # alternatywna one-klick if a[3] == 1: # 1 przycisk - oba silniki if flag_A == -1 and flag_C == -1: r.stop() flag_A = 0 flag_C = 0 lock[0] = 30 # lock = 30 elif not lock[0]: r.run(r.S/slowdown, r.S/slowdown) flag_A = 1 flag_C = 1 elif a[3] == 2: if flag_A == 1 and flag_C == 1: r.stop() flag_A = 0 flag_C = 0 lock[1] = 30 # lock = 30 elif not lock[1]: r.run(-r.S/slowdown, -r.S/slowdown) flag_A = -1 flag_C = -1 elif a[3] == 3: if flag_A == 1 and flag_C == -1: r.stop() flag_A = 0 flag_C = 0 lock[2] = 30 # lock = 30 elif not lock[2]: r.run(-r.S/slowdown, r.S/slowdown) flag_A = -1 flag_C = 1 elif a[3] == 4: if flag_A == -1 and flag_C == 1: r.stop() flag_A = 0 flag_C = 0 lock[3] = 30 # lock = 30 elif not lock[3]: r.run(r.S/slowdown, -r.S/slowdown) flag_A = 1 flag_C = -1 elif a[3] == 9: r.stop() flag_A = 0 flag_C = 0 else: if not flag_A: r.A.stop() if not flag_C: r.C.stop() <|fim▁end|>
run_forever(r.S)