Пример #1
0
func PipeWriter(data map[string]interface{}) {
	w := io.PipeWriter{}
	defer w.Close()
	w.Write([]byte("pipeWriter"))
	// err := tpl.Execute(w, data)
	// if err != nil {
	// 	fmt.Println(err)
	// }

}
Пример #2
0
func (s *GardenServer) streamInput(decoder *json.Decoder, in *io.PipeWriter, process garden.Process, connCloseCh chan struct{}) {
	for {
		var payload transport.ProcessPayload
		err := decoder.Decode(&payload)
		if err != nil {
			close(connCloseCh)
			in.CloseWithError(errors.New("Connection closed"))
			return
		}

		switch {
		case payload.TTY != nil:
			process.SetTTY(*payload.TTY)

		case payload.Source != nil:
			if payload.Data == nil {
				in.Close()
				return
			} else {
				_, err := in.Write([]byte(*payload.Data))
				if err != nil {
					return
				}
			}

		case payload.Signal != nil:
			s.logger.Info("stream-input-process-signal", lager.Data{"payload": payload})

			switch *payload.Signal {
			case garden.SignalKill:
				err = process.Signal(garden.SignalKill)
				if err != nil {
					s.logger.Error("stream-input-process-signal-kill-failed", err, lager.Data{"payload": payload})
				}
			case garden.SignalTerminate:
				err = process.Signal(garden.SignalTerminate)
				if err != nil {
					s.logger.Error("stream-input-process-signal-terminate-failed", err, lager.Data{"payload": payload})
				}
			default:
				s.logger.Error("stream-input-unknown-process-payload-signal", nil, lager.Data{"payload": payload})
				in.Close()
				return
			}

		default:
			s.logger.Error("stream-input-unknown-process-payload", nil, lager.Data{"payload": payload})
			in.Close()
			return
		}
	}
}
Пример #3
0
func PipeWrite(pipeWriter *io.PipeWriter) {
	var (
		i   = 0
		err error
		n   int
	)
	data := []byte("Go语言学习园地")
	for _, err = pipeWriter.Write(data); err == nil; n, err = pipeWriter.Write(data) {
		i++
		if i == 3 {
			pipeWriter.CloseWithError(errors.New("输出3次后结束"))
		}
	}
	fmt.Println("close 后输出的字节数:", n, " error:", err)
}
Пример #4
0
func readDat(filename string, c chan io.Reader) {
	f, err := os.Open("testdata/webkit/" + filename)
	if err != nil {
		c <- pipeErr(err)
		return
	}
	defer f.Close()

	// Loop through the lines of the file. Each line beginning with "#" denotes
	// a new section, which is returned as a separate io.Reader.
	r := bufio.NewReader(f)
	var pw *io.PipeWriter
	for {
		line, err := r.ReadSlice('\n')
		if err != nil {
			if pw != nil {
				pw.CloseWithError(err)
				pw = nil
			} else {
				c <- pipeErr(err)
			}
			return
		}
		if len(line) == 0 {
			continue
		}
		if line[0] == '#' {
			if pw != nil {
				pw.Close()
			}
			var pr *io.PipeReader
			pr, pw = io.Pipe()
			c <- pr
			continue
		}
		if line[0] != '|' {
			// Strip the trailing '\n'.
			line = line[:len(line)-1]
		}
		if pw != nil {
			if _, err := pw.Write(line); err != nil {
				pw.CloseWithError(err)
				pw = nil
			}
		}
	}
}
func importFile(filename string) {
	file, err := os.Open(filename)

	if err != nil {
		log.Printf("Error: %v\n", err)
		return
	}
	defer file.Close()

	stats, _ := file.Stat()
	fileSize := stats.Size()

	log.Printf("Importing %v", filename)

	reader := bufio.NewReaderSize(file, 1024*1024)

	var resps = make(chan Response, 100)
	go handleResponses(filename, fileSize, resps)

	var pReader *io.PipeReader
	var pWriter *io.PipeWriter
	var i int
	for i = 0; err == nil; i++ {
		if i%250 == 0 {
			if pWriter != nil {
				pWriter.Close()
			}
			pReader, pWriter = io.Pipe()
			reqs <- Request{pReader, resps}
		}

		var line []byte
		line, err = reader.ReadBytes('\n')
		pWriter.Write(line)
	}

	if pWriter != nil {
		pWriter.Close()
	}

	if err != nil && err != io.EOF {
		log.Panicf("Scanner error: %v\n", err)
	}

	resps <- Response{nil, nil, true, i - 1}
}
Пример #6
0
func PipeWrite(pipeWriter *io.PipeWriter) {
	var (
		i   = 0
		err error
		n   int
	)
	data := []byte("Go语言学习园地")
	// 循环往管道中写数据,写第三次时,我们调用 CloseWithError 方法关闭管道的写入端,之后再一次调用 Write 方法,发现返回了error,于是退出了循环。
	for _, err = pipeWriter.Write(data); err == nil; n, err = pipeWriter.Write(data) {
		i++
		if i == 3 {
			// 对于管道的close方法(非CloseWithError时),err会被置为EOF
			pipeWriter.CloseWithError(errors.New("输出3次后结束"))
		}
	}
	fmt.Println("close 后输出的字节数:", n, " error:", err)
}
Пример #7
0
func (c *combinedReader) readTo(r io.Reader, w *io.PipeWriter) {
	p := make([]byte, 1e5)
	for {
		n, err := r.Read(p)
		if n > 0 {
			c.wlk.Lock()
			w.Write(p[:n])
			c.wlk.Unlock()
		}
		if err != nil {
			c.wlk.Lock()
			defer c.wlk.Unlock()
			c.closed++
			if c.closed == 2 {
				w.Close()
			}
			return
		}
	}
}
Пример #8
0
func (c *combinedReader) readTo(r io.Reader, w *io.PipeWriter) {
	p := make([]byte, 1e5)
	for {
		// If an incoming line of text is longer then len(p), it may be interleaved with other side content
		n, err := r.Read(p)
		if n > 0 {
			c.wlk.Lock()
			w.Write(p[:n])
			c.wlk.Unlock()
		}
		if err != nil {
			c.wlk.Lock()
			defer c.wlk.Unlock()
			c.closed++
			if c.closed == 2 {
				w.Close()
			}
			return
		}
	}
}
				config.Save()

				test_helpers.ExecuteCommandWithArgs(targetBlobCommand, []string{})

				Expect(outputBuffer).To(test_helpers.SayLine("Blob target not set"))
			})
		})

		Context("setting the blob target", func() {
			It("sets the blob target and credentials", func() {
				fakeTargetVerifier.VerifyBlobTargetReturns(true, nil)

				commandFinishChan := test_helpers.AsyncExecuteCommandWithArgs(targetBlobCommand, []string{"192.168.11.11:8980"})

				Eventually(outputBuffer).Should(test_helpers.Say("Access Key: "))
				stdinWriter.Write([]byte("yaykey\n"))
				Eventually(outputBuffer).Should(test_helpers.Say("Secret Key: "))
				stdinWriter.Write([]byte("superserial\n"))
				Eventually(outputBuffer).Should(test_helpers.Say("Bucket Name [condenser-bucket]: "))
				stdinWriter.Write([]byte("bhuket\n"))

				Eventually(commandFinishChan).Should(BeClosed())

				Expect(fakeTargetVerifier.VerifyBlobTargetCallCount()).To(Equal(1))
				host, port, accessKey, secretKey, bucketName := fakeTargetVerifier.VerifyBlobTargetArgsForCall(0)
				Expect(host).To(Equal("192.168.11.11"))
				Expect(port).To(Equal(uint16(8980)))
				Expect(accessKey).To(Equal("yaykey"))
				Expect(secretKey).To(Equal("superserial"))
				Expect(bucketName).To(Equal("bhuket"))
Пример #10
0
					Source:   "chug-test",
					Message:  "first-session.nested-session-2.modernify",
					Session:  "1.2",
					Data:     lager.Data{},
				}))
			})
		})
	})

	Context("handling lager JSON that is surrounded by non-JSON", func() {
		var input []byte
		var entry Entry

		BeforeEach(func() {
			input = []byte(`[some-component][e]{"timestamp":"1407102779.028711081","source":"chug-test","message":"chug-test.chug","log_level":0,"data":{"some-float":3,"some-string":"foo"}}...some trailing stuff`)
			pipeWriter.Write(input)
			pipeWriter.Write([]byte("\n"))

			Eventually(stream).Should(Receive(&entry))
		})

		It("should be a lager message", func() {
			Ω(entry.IsLager).Should(BeTrue())
		})

		It("should contain all the data in Raw", func() {
			Ω(entry.Raw).Should(Equal(input))
		})

		It("should succesfully parse the lager message", func() {
			Ω(entry.Log.Source).Should(Equal("chug-test"))
			})
		})

		Context("when the receptor requires authentication", func() {
			BeforeEach(func() {
				fakeTargetVerifier.VerifyTargetReturns(true, false, nil)
				fakeBlobStoreVerifier.VerifyReturns(true, nil)
				fakePasswordReader.PromptForPasswordReturns("testpassword")
			})

			It("prompts for credentials and stores them in the config", func() {
				doneChan := test_helpers.AsyncExecuteCommandWithArgs(targetCommand, []string{"myapi.com"})

				Eventually(outputBuffer).Should(test_helpers.Say("Username: "******"testusername\n"))

				Eventually(doneChan, 3).Should(BeClosed())

				Expect(config.Target()).To(Equal("myapi.com"))
				Expect(config.Receptor()).To(Equal("http://*****:*****@receptor.myapi.com"))
				Expect(outputBuffer).To(test_helpers.SayLine("API location set."))

				Expect(fakePasswordReader.PromptForPasswordCallCount()).To(Equal(1))
				Expect(fakePasswordReader.PromptForPasswordArgsForCall(0)).To(Equal("Password"))

				Expect(fakeTargetVerifier.VerifyTargetCallCount()).To(Equal(2))
				Expect(fakeTargetVerifier.VerifyTargetArgsForCall(0)).To(Equal("http://receptor.myapi.com"))
				Expect(fakeTargetVerifier.VerifyTargetArgsForCall(1)).To(Equal("http://*****:*****@receptor.myapi.com"))
			})
Пример #12
0
		})
	})

	Describe("Input Methods", func() {
		Describe("Prompt", func() {
			It("Prompts the user for input", func() {
				answerChan := make(chan string)
				go func() {
					defer GinkgoRecover()

					answerChan <- terminalUI.Prompt("Nickname")
					close(answerChan)
				}()

				Eventually(outputBuffer).Should(test_helpers.Say("Nickname: "))
				stdinWriter.Write([]byte("RockStar\n"))

				Eventually(answerChan).Should(Receive(Equal("RockStar")))
				Eventually(answerChan).Should(BeClosed())
			})
		})

		Describe("PromptWithDefault", func() {
			It("Prompts the user for input", func() {
				answerChan := make(chan string)
				go func() {
					defer GinkgoRecover()

					answerChan <- terminalUI.PromptWithDefault("Nickname", "x")
					close(answerChan)
				}()
Пример #13
0
				})
			})
		})

		Context("setting target that requires auth", func() {
			BeforeEach(func() {
				fakeTargetVerifier.VerifyTargetReturns(true, false, nil)
				fakePasswordReader.PromptForPasswordReturns("testpassword")
			})

			It("sets the api, username, password from the target specified", func() {
				commandFinishChan := test_helpers.AsyncExecuteCommandWithArgs(targetCommand, []string{"myapi.com"})

				Eventually(outputBuffer).Should(test_helpers.Say("Username: "******"testusername\n"))

				Eventually(commandFinishChan).Should(BeClosed())

				Expect(config.Target()).To(Equal("myapi.com"))
				Expect(config.Receptor()).To(Equal("http://*****:*****@receptor.myapi.com"))
				Expect(outputBuffer).To(test_helpers.Say("Api Location Set"))

				Expect(fakePasswordReader.PromptForPasswordCallCount()).To(Equal(1))
				Expect(fakePasswordReader.PromptForPasswordArgsForCall(0)).To(Equal("Password"))

				Expect(fakeTargetVerifier.VerifyTargetCallCount()).To(Equal(2))
				Expect(fakeTargetVerifier.VerifyTargetArgsForCall(0)).To(Equal("http://receptor.myapi.com"))
				Expect(fakeTargetVerifier.VerifyTargetArgsForCall(1)).To(Equal("http://*****:*****@receptor.myapi.com"))
			})
Пример #14
0
			})
		})

		Context("when the receptor requires authentication", func() {
			BeforeEach(func() {
				fakeTargetVerifier.VerifyTargetReturns(true, false, nil)
				fakeBlobStoreVerifier.VerifyReturns(true, nil)
				fakePasswordReader.PromptForPasswordReturns("testpassword")
			})

			It("prompts for credentials and stores them in the config", func() {
				doneChan := test_helpers.AsyncExecuteCommandWithArgs(targetCommand, []string{"myapi.com"})

				Eventually(outputBuffer).Should(test_helpers.Say("Username: "******"testusername\n"))

				Eventually(doneChan).Should(BeClosed())

				Expect(config.Target()).To(Equal("myapi.com"))
				Expect(config.Receptor()).To(Equal("http://*****:*****@receptor.myapi.com"))
				Expect(outputBuffer).To(test_helpers.Say("API location set."))

				Expect(fakePasswordReader.PromptForPasswordCallCount()).To(Equal(1))
				Expect(fakePasswordReader.PromptForPasswordArgsForCall(0)).To(Equal("Password"))

				Expect(fakeTargetVerifier.VerifyTargetCallCount()).To(Equal(2))
				Expect(fakeTargetVerifier.VerifyTargetArgsForCall(0)).To(Equal("http://receptor.myapi.com"))
				Expect(fakeTargetVerifier.VerifyTargetArgsForCall(1)).To(Equal("http://*****:*****@receptor.myapi.com"))
			})
		It("returns empty slice and true", func() {
			out, finished := br.Next()
			Expect(out).To(BeEmpty())
			Expect(finished).To(BeTrue())
		})
	})

	Context("when there is a small amount of output and the writer is done", func() {
		var testFinished chan bool

		BeforeEach(func() {
			testFinished = make(chan bool)

			go func() {
				defer GinkgoRecover()
				_, err := writer.Write([]byte("Hello world!"))
				Expect(err).NotTo(HaveOccurred())
				Expect(writer.Close()).To(Succeed())
				testFinished <- true
			}()
			done = true
		})

		It("returns the output and true", func() {
			out, finished := br.Next()
			Expect(string(out)).To(Equal("Hello world!"))
			Expect(finished).To(BeTrue())
			<-testFinished
		})
	})