// taskDefinitionInput returns an ecs.RegisterTaskDefinitionInput suitable for // creating a task definition from a Process. func taskDefinitionInput(p *scheduler.Process, logConfiguration *ecs.LogConfiguration) (*ecs.RegisterTaskDefinitionInput, error) { args, err := shellwords.Parse(p.Command) if err != nil { return nil, err } // ecs.ContainerDefinition{Command} is expecting a []*string var command []*string for _, s := range args { ss := s command = append(command, &ss) } var environment []*ecs.KeyValuePair for k, v := range p.Env { environment = append(environment, &ecs.KeyValuePair{ Name: aws.String(k), Value: aws.String(v), }) } var ports []*ecs.PortMapping for _, m := range p.Ports { ports = append(ports, &ecs.PortMapping{ HostPort: m.Host, ContainerPort: m.Container, }) } labels := make(map[string]*string) for k, v := range p.Labels { labels[k] = aws.String(v) } return &ecs.RegisterTaskDefinitionInput{ Family: aws.String(p.Type), ContainerDefinitions: []*ecs.ContainerDefinition{ &ecs.ContainerDefinition{ Name: aws.String(p.Type), Cpu: aws.Int64(int64(p.CPUShares)), Command: command, Image: aws.String(p.Image.String()), Essential: aws.Bool(true), Memory: aws.Int64(int64(p.MemoryLimit / MB)), Environment: environment, LogConfiguration: logConfiguration, PortMappings: ports, DockerLabels: labels, }, }, }, nil }
func TestLogger(t *testing.T) { if runtime.GOOS == "windows" { logfilePath = filepath.Join(os.Getenv("TEMP"), logfileName) } else { logfilePath = filepath.Join("/tmp", logfileName) } logger = NewLogger(logfilePath) defer cleanup() SetBackend2FrontendMap(&testBackend2FrontendMap) r := &http.Request{ Header: map[string][]string{ "User-Agent": {testUserAgent}, "Referer": {testReferer}, }, Proto: testProto, Host: testHostname, Method: testMethod, RemoteAddr: fmt.Sprintf("%s:%d", testHostname, testPort), URL: &url.URL{ User: url.UserPassword(testUsername, ""), Path: testPath, }, } logger.ServeHTTP(&logtestResponseWriter{}, r, LogWriterTestHandlerFunc) if logdata, err := ioutil.ReadFile(logfilePath); err != nil { fmt.Printf("%s\n%s\n", string(logdata), err.Error()) assert.Nil(t, err) } else if tokens, err := shellwords.Parse(string(logdata)); err != nil { fmt.Printf("%s\n", err.Error()) assert.Nil(t, err) } else if assert.Equal(t, 14, len(tokens), printLogdata(logdata)) { assert.Equal(t, testHostname, tokens[0], printLogdata(logdata)) assert.Equal(t, testUsername, tokens[2], printLogdata(logdata)) assert.Equal(t, fmt.Sprintf("%s %s %s", testMethod, testPath, testProto), tokens[5], printLogdata(logdata)) assert.Equal(t, fmt.Sprintf("%d", testStatus), tokens[6], printLogdata(logdata)) assert.Equal(t, fmt.Sprintf("%d", len(helloWorld)), tokens[7], printLogdata(logdata)) assert.Equal(t, testReferer, tokens[8], printLogdata(logdata)) assert.Equal(t, testUserAgent, tokens[9], printLogdata(logdata)) assert.Equal(t, "1", tokens[10], printLogdata(logdata)) assert.Equal(t, testFrontendName, tokens[11], printLogdata(logdata)) assert.Equal(t, testBackendName, tokens[12], printLogdata(logdata)) } }
// taskDefinitionInput returns an ecs.RegisterTaskDefinitionInput suitable for // creating a task definition from a Process. func taskDefinitionInput(p *Process) (*ecs.RegisterTaskDefinitionInput, error) { args, err := shellwords.Parse(p.Command) if err != nil { return nil, err } // ecs.ContainerDefinition{Command} is expecting a []*string var command []*string for _, s := range args { ss := s command = append(command, &ss) } var environment []*ecs.KeyValuePair for k, v := range p.Env { environment = append(environment, &ecs.KeyValuePair{ Name: aws.String(k), Value: aws.String(v), }) } var ports []*ecs.PortMapping for _, m := range p.Ports { ports = append(ports, &ecs.PortMapping{ HostPort: m.Host, ContainerPort: m.Container, }) } return &ecs.RegisterTaskDefinitionInput{ Family: aws.String(p.Type), ContainerDefinitions: []*ecs.ContainerDefinition{ &ecs.ContainerDefinition{ Name: aws.String(p.Type), CPU: aws.Long(int64(p.CPUShares)), Command: command, Image: aws.String(p.Image.String()), Essential: aws.Boolean(true), Memory: aws.Long(int64(p.MemoryLimit / MB)), Environment: environment, PortMappings: ports, }, }, }, nil }
func (r *Runner) create(ctx context.Context, opts RunOpts) (*docker.Container, error) { cmd, err := shellwords.Parse(opts.Command) if err != nil { return nil, err } return r.client.CreateContainer(ctx, docker.CreateContainerOptions{ Name: uuid.New(), Config: &docker.Config{ Tty: true, AttachStdin: true, AttachStdout: true, AttachStderr: true, OpenStdin: true, Image: opts.Image.String(), Cmd: cmd, Env: envKeys(opts.Env), }, HostConfig: &docker.HostConfig{}, }) }
// Launches a child process to hold open a ZMQ connection // to the upstream bolo server (send_bolo should take care // of the configuration for how to connect). Upon termination // this process will be respawned. // // Currently, if the send_bolo configuration directive for bmad // is updated on a config reload, the send_bolo process will not // be respawned. A full-daemon restart is required to make use // of the new send_bolo configuration func ConnectToBolo() error { args, err := shellwords.Parse(cfg.Send_bolo) if err != nil { return err } log.Debug("Spawning bolo submitter: %#v", args) send2bolo = exec.Command(args[0], args[1:]...) r, w, err := os.Pipe() if err != nil { return err } send2bolo.Stdin = r writer = w err = send2bolo.Start() if err != nil { writer = nil send2bolo = nil return err } log.Debug("send_bolo: %#v", send2bolo) go func() { send2bolo.Wait(); send2bolo = nil }() return nil }
func (s *AccessLogSuite) TestAccessLog(c *check.C) { // Ensure working directory is clean os.Remove("access.log") os.Remove("traefik.log") // Start Traefik cmd := exec.Command(traefikBinary, "--configFile=fixtures/access_log_config.toml") err := cmd.Start() c.Assert(err, checker.IsNil) defer cmd.Process.Kill() defer os.Remove("access.log") defer os.Remove("traefik.log") time.Sleep(500 * time.Millisecond) // Verify Traefik started OK traefikLog, err := ioutil.ReadFile("traefik.log") c.Assert(err, checker.IsNil) if len(traefikLog) > 0 { fmt.Printf("%s\n", string(traefikLog)) c.Assert(len(traefikLog), checker.Equals, 0) } // Start test servers ts1 := startAccessLogServer(8081) defer ts1.Close() ts2 := startAccessLogServer(8082) defer ts2.Close() ts3 := startAccessLogServer(8083) defer ts3.Close() // Make some requests _, err = http.Get("http://127.0.0.1:8000/test1") c.Assert(err, checker.IsNil) _, err = http.Get("http://127.0.0.1:8000/test2") c.Assert(err, checker.IsNil) _, err = http.Get("http://127.0.0.1:8000/test2") c.Assert(err, checker.IsNil) // Verify access.log output as expected accessLog, err := ioutil.ReadFile("access.log") c.Assert(err, checker.IsNil) lines := strings.Split(string(accessLog), "\n") count := 0 for i, line := range lines { if len(line) > 0 { count++ tokens, err := shellwords.Parse(line) c.Assert(err, checker.IsNil) c.Assert(len(tokens), checker.Equals, 13) c.Assert(tokens[6], checker.Equals, "200") c.Assert(tokens[9], checker.Equals, fmt.Sprintf("%d", i+1)) c.Assert(strings.HasPrefix(tokens[10], "frontend"), checker.True) c.Assert(strings.HasPrefix(tokens[11], "http://127.0.0.1:808"), checker.True) c.Assert(regexp.MustCompile("^\\d+\\.\\d+.*s$").MatchString(tokens[12]), checker.True) } } c.Assert(count, checker.Equals, 3) // Verify no other Traefik problems traefikLog, err = ioutil.ReadFile("traefik.log") c.Assert(err, checker.IsNil) if len(traefikLog) > 0 { fmt.Printf("%s\n", string(traefikLog)) c.Assert(len(traefikLog), checker.Equals, 0) } }
func upstream() { buff := make([]byte, 16384) for { line, err := rl.Readline() if err == readline.ErrInterrupt { line = "exit" } if err == io.EOF { continue } line = strings.TrimSpace(line) switch { case strings.HasPrefix(line, "login "): // arg1 => username args, err := sw.Parse(line) if err != nil { fmt.Fprintln(stderr, "Invalid line:", err.Error()) continue } args = args[1:] if len(args) == 0 { fmt.Fprintf(stderr, "Usage: login username\n") continue } if len(args) == 1 { proto.WriteString(buff, args[0]) pkt := proto.NewPacket(4, buff[:len(args[0])+2]) pkt.Sign(privkey) _, err = user.Conn.Write(pkt.Bytes()) if err != nil { fmt.Fprintf(stderr, "Write packet error: %s\n", err.Error()) panic("Socket error!") } } case strings.HasPrefix(line, "exit"): // arg1 => reason reason := "Disconnected" args, err := sw.Parse(line) if err != nil { fmt.Fprintln(stderr, "Invalid line:", err.Error()) continue } if len(args) >= 2 { reason = args[1] } proto.WriteString(buff, reason) pkt := proto.NewPacket(5, buff[:len(reason)+2]) pkt.Sign(privkey) _, err = user.Conn.Write(pkt.Bytes()) if err != nil { fmt.Fprintf(stderr, "Write packet error: %s\n", err.Error()) panic("Socket error!") } time.Sleep(500 * time.Millisecond) os.Exit(0) case line == "games": pkt := proto.NewPacket(6, []byte{}) pkt.Sign(privkey) _, err = user.Conn.Write(pkt.Bytes()) if err != nil { fmt.Fprintf(stderr, "Write packet error: %s\n", err.Error()) panic("Socket error!") } case line == "players": pkt := proto.NewPacket(7, []byte{}) pkt.Sign(privkey) _, err = user.Conn.Write(pkt.Bytes()) if err != nil { fmt.Fprintf(stderr, "Write packet error: %s\n", err.Error()) panic("Socket error!") } case strings.HasPrefix(line, "join "): // arg1 => roomid args, err := sw.Parse(line) if err != nil { fmt.Fprintln(stderr, "Invalid line:", err.Error()) continue } args = args[1:] if len(args) == 0 { fmt.Fprintf(stderr, "Usage: join roomid\n") continue } if len(args) == 1 { r, err := strconv.Atoi(args[0]) if err != nil { fmt.Fprintf(stderr, "Invalid roomid %s\n", args[0]) } roomid := uint16(r) binary.BigEndian.PutUint16(buff, roomid) pkt := proto.NewPacket(8, buff[:2]) pkt.Sign(privkey) _, err = user.Conn.Write(pkt.Bytes()) if err != nil { fmt.Fprintf(stderr, "Write packet error: %s\n", err.Error()) panic("Socket error!") } } case line == "leave": pkt := proto.NewPacket(9, []byte{}) pkt.Sign(privkey) _, err = user.Conn.Write(pkt.Bytes()) if err != nil { fmt.Fprintf(stderr, "Write packet error: %s\n", err.Error()) panic("Socket error!") return } case line == "restart": pkt := proto.NewPacket(10, []byte{}) pkt.Sign(privkey) _, err = user.Conn.Write(pkt.Bytes()) if err != nil { fmt.Fprintf(stderr, "Write packet error: %s\n", err.Error()) panic("Socket error!") } case strings.HasPrefix(line, "place "): args, err := sw.Parse(line) if err != nil { fmt.Fprintln(stderr, "Invalid line:", err.Error()) continue } args = args[1:] if len(args) < 2 { fmt.Fprintf(stderr, "Usage: place x y\n") continue } // arg1 => x, arg2 => y x, err := strconv.Atoi(args[0]) if err != nil { fmt.Fprintf(stderr, "Invalid number %s\n", args[0]) } y, err := strconv.Atoi(args[1]) if err != nil { fmt.Fprintf(stderr, "Invalid number %s\n", args[1]) } buff[0] = byte((x << 4) | y) pkt := proto.NewPacket(11, buff[:1]) pkt.Sign(privkey) _, err = user.Conn.Write(pkt.Bytes()) if err != nil { fmt.Fprintf(stderr, "Write packet error: %s\n", err.Error()) panic("Socket error!") } case strings.HasPrefix(line, "msg "): args, err := sw.Parse(line) if err != nil { fmt.Fprintln(stderr, "Invalid line:", err.Error()) continue } args = args[1:] if len(args) < 2 { fmt.Fprintf(stderr, "Usage: msg player message\n") continue } b := buff b, _ = proto.WriteString(b, args[0]) b, _ = proto.WriteString(b, args[1]) pkt := proto.NewPacket(13, buff[:len(args[0])+len(args[1])+4]) pkt.Sign(privkey) _, err = user.Conn.Write(pkt.Bytes()) if err != nil { fmt.Fprintf(stderr, "Write packet error: %s\n", err.Error()) panic("Socket error!") } default: fmt.Fprintln(stderr, "Commands: ") fmt.Fprint(stderr, completer.Tree(" ")) } } }
func loadShellCommand(value interface{}) (interface{}, error) { if str, ok := value.(string); ok { return shellwords.Parse(str) } return value, nil }
// ParseCommand parses a string into a Command, taking quotes and other shell // words into account. For example: func ParseCommand(command string) (Command, error) { return shellwords.Parse(command) }
// Takes a new check, and initializes it based on global config defaults, and // hard-coded safeguards, to ensure checks don't run *too* frequently, or get // configured in a messed up way (like setting Timeout above Every, or to 0) func initialize_check(name string, check *Check, defaults *Config) error { if check.Name == "" { check.Name = name } if check.Name == "" { return errors.New("No check name specified") } if check.Command == "" { return errors.New("Unspecified command") } else { var err error check.cmd_args, err = shellwords.Parse(check.Command) if err != nil { return errors.New(fmt.Sprintf("Unable to parse command `%s`: %s", check.Command, err.Error())) } } if check.Every <= 0 { check.Every = defaults.Every } else if check.Every <= MIN_INTERVAL { check.Every = MIN_INTERVAL } if check.Every <= 0 { check.Every = MIN_INTERVAL * 30 } if check.Retry_every <= 0 { check.Retry_every = defaults.Retry_every } if check.Retry_every > check.Every { check.Retry_every = check.Every } if check.Retry_every <= 0 { check.Retry_every = check.Every } if check.Retries <= 0 { check.Retries = defaults.Retries } if check.Retries <= 0 { check.Retries = 1 } if check.Timeout <= 0 { check.Timeout = defaults.Timeout } if check.Timeout >= check.Retry_every || check.Timeout <= 0 { check.Timeout = check.Retry_every - 1 } if check.Bulk == "" { check.Bulk = defaults.Bulk } if check.Report == "" { check.Report = defaults.Report } for key, val := range defaults.Env { if _, ok := check.Env[key]; !ok { check.Env[key] = val } } if check.Env == nil { check.Env = map[string]string{} } check.next_run = first_run(check.Every) return nil }
func main() { sw.ParseEnv = false users = make(map[string]*common.User) games = make(map[uint16]*common.Game) var err error pubkey, privkey, err = ed25519.GenerateKey(rand.Reader) if err != nil { panic(err) } socket, err := utp.NewSocket("udp", ":5428") if err != nil { panic(err) } rl, err = readline.NewEx(&readline.Config{ Prompt: "> ", // HistoryFile: "./readline.history", InterruptPrompt: "Ctrl-C received, exiting ...", EOFPrompt: "\n", AutoComplete: completer, }) if err != nil { panic(err) } go server(socket) // Console part for { line, err := rl.Readline() if err == readline.ErrInterrupt { line = "exit" } if err == io.EOF { continue } line = strings.TrimSpace(line) switch { case line == "exit": fmt.Fprintf(rl.Stderr(), "Exiting... Kick all client\n") for _, user := range users { user.Kick("Server closed") } return case strings.HasPrefix(line, "msg "): args, err := sw.Parse(line) if err != nil { fmt.Fprintln(rl.Stderr(), "Invalid line:", err.Error()) continue } args = args[1:] if len(args) == 0 { fmt.Fprintf(rl.Stderr(), "Usage: msg [user] message\n") continue } if len(args) == 1 { // Broadcast for _, user := range users { go user.SendMessage("", args[0]) } continue } if len(args) == 2 { // Send to specific user user, ok := users[args[0]] if ok { user.SendMessage("", args[1]) } else { fmt.Fprintf(rl.Stderr(), "No such user: %s\n", args[0]) } } case line == "users": fmt.Fprintf(rl.Stderr(), "Online users: \n") for name, user := range users { fmt.Fprintf(rl.Stderr(), " %s [%s]: ", name, user.Conn.RemoteAddr().String()) if user.Game == nil { fmt.Fprintf(rl.Stderr(), "Idle\n") } else { fmt.Fprintf(rl.Stderr(), "In Room %d\n", user.Game.ID) } } case strings.HasPrefix(line, "kick "): args, err := sw.Parse(line) if err != nil { fmt.Fprintln(rl.Stderr(), "Invalid line:", err.Error()) continue } args = args[1:] if len(args) == 0 { fmt.Fprintf(rl.Stderr(), "Usage: kick user [reason]\n") continue } reason := "Kicked with no reason." if len(args) > 1 { reason = fmt.Sprint("Kicked by server: ", args[1]) } user, ok := users[args[0]] if ok { user.Kick(reason) } else { fmt.Fprintf(rl.Stderr(), "No such user: %s\n", args[0]) } case line == "newgame": game := common.NewGame() game.ID = rid rid++ games[game.ID] = game fmt.Fprintf(rl.Stderr(), "New room #%d opened.\n", game.ID) case line == "games": fmt.Fprintf(rl.Stderr(), "Current open game: \n") for _, game := range games { fmt.Fprintf(rl.Stderr(), " Room #%d: ", game.ID) if game.Black != nil { fmt.Fprintf(rl.Stderr(), "Black: %s ", game.Black.Name) } else { fmt.Fprintf(rl.Stderr(), "Black: [free] ") } if game.White != nil { fmt.Fprintf(rl.Stderr(), "White: %s ", game.White.Name) } else { fmt.Fprintf(rl.Stderr(), "White: [free] ") } fmt.Fprintln(rl.Stderr()) } case strings.HasPrefix(line, "watch "): args, err := sw.Parse(line) if err != nil { fmt.Fprintln(rl.Stderr(), "Invalid line:", err.Error()) continue } args = args[1:] if len(args) == 0 { fmt.Fprintf(rl.Stderr(), "Usage: watch ID\n") continue } var rid uint16 if n, err := fmt.Sscanf(args[0], "%d", &rid); n != 1 || err != nil { fmt.Fprintf(rl.Stderr(), "Invalid room ID: %s\n", args[0]) continue } if room, ok := games[rid]; ok { if room.Turn != 0 { for i := 0; i < 8; i++ { for j := 0; j < 8; j++ { ch := '.' if room.Board[i][j] == 1 { ch = 'O' } else if room.Board[i][j] == 2 { ch = 'X' } fmt.Fprintf(rl.Stderr(), "%c", ch) } fmt.Fprintln(rl.Stderr()) } fmt.Fprintln(rl.Stderr()) } if room.Black != nil { fmt.Fprintf(rl.Stderr(), "Black: %s ", room.Black.Name) } else { fmt.Fprintf(rl.Stderr(), "Black: [free] ") } if room.Turn == 1 { fmt.Fprintf(rl.Stderr(), "[Thinking]") } if room.White != nil { fmt.Fprintf(rl.Stderr(), "White: %s ", room.White.Name) } else { fmt.Fprintf(rl.Stderr(), "White: [free] ") } if room.Turn == 2 { fmt.Fprintf(rl.Stderr(), "[Thinking]") } fmt.Fprintln(rl.Stderr()) } else { fmt.Fprintf(rl.Stderr(), "Room #%d does not exists!\n", rid) } case strings.HasPrefix(line, "closegame "): args, err := sw.Parse(line) if err != nil { fmt.Fprintln(rl.Stderr(), "Invalid line:", err.Error()) continue } args = args[1:] if len(args) == 0 { fmt.Fprintf(rl.Stderr(), "Usage: closegame ID\n") continue } var rid uint16 if n, err := fmt.Sscanf(args[0], "%d", &rid); n != 1 || err != nil { fmt.Fprintf(rl.Stderr(), "Invalid room ID: %s\n", args[0]) continue } if room, ok := games[rid]; ok { if room.Black != nil { room.Black.Leave() } if room.White != nil { room.White.Leave() } delete(games, rid) } else { fmt.Fprintf(rl.Stderr(), "Room #%d does not exist!\n", rid) } default: fmt.Fprintln(rl.Stderr(), "Commands: ") fmt.Fprint(rl.Stderr(), completer.Tree(" ")) } } }