Example #1
0
// NewLogger creates a new logger
func NewLogger(stdout string, stderr string) (logger *Logger, err error) {
	var (
		stderrWriter = os.Stderr
		stdoutWriter = os.Stdout
		toClose      []closeable
	)

	if stderr != "" {
		if stderrWriter, err = os.OpenFile(stderr, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666); err != nil {
			return
		}
		toClose = append(toClose, stderrWriter)
	}
	if stdout != "" {
		if stdoutWriter, err = os.OpenFile(stdout, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666); err != nil {
			return
		}
		toClose = append(toClose, stderrWriter)
	}

	logger = &Logger{
		stderr:  log.New(stderrWriter, "ERROR ", log.LstdFlags|log.Lshortfile),
		stdout:  log.New(stdoutWriter, "INFO ", log.LstdFlags|log.Lshortfile),
		toClose: toClose,
	}
	return
}
Example #2
0
func benchmarkBTreeSetACIDFiler(b *testing.B, sz int) {
	dir, testDbName := temp()
	defer os.RemoveAll(dir)

	f, err := os.OpenFile(testDbName, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0600)
	if err != nil {
		b.Fatal(err)
	}

	defer f.Close()

	wal, err := os.OpenFile(testDbName+".wal", os.O_CREATE|os.O_EXCL|os.O_RDWR, 0600)
	if err != nil {
		b.Fatal(err)
	}

	defer wal.Close()

	filer, err := NewACIDFiler(NewSimpleFileFiler(f), wal)
	if err != nil {
		b.Error(err)
		return
	}

	benchmarkBTreeSetFiler(b, filer, sz)
}
Example #3
0
func (node *Node) OpenForReading() (*os.File, error) {
	file, err := os.OpenFile(node.path, os.O_RDONLY|syscall.O_NOATIME, 0)
	if os.IsPermission(err) {
		return os.OpenFile(node.path, os.O_RDONLY, 0)
	}
	return file, err
}
Example #4
0
func initDebugLogger() {
	debugfile := os.Getenv("DEBUG_LOG")
	if debugfile == "" {
		return
	}

	fmt.Fprintf(os.Stderr, "debug log file %v\n", debugfile)

	f, err := os.OpenFile(debugfile, os.O_WRONLY|os.O_APPEND, 0600)

	if err == nil {
		_, err = f.Seek(2, 0)
		if err != nil {
			fmt.Fprintf(os.Stderr, "unable to seek to the end of %v: %v\n", debugfile, err)
			os.Exit(3)
		}
	}

	if err != nil && os.IsNotExist(err) {
		f, err = os.OpenFile(debugfile, os.O_WRONLY|os.O_CREATE, 0600)
	}

	if err != nil {
		fmt.Fprintf(os.Stderr, "unable to open debug log file: %v\n", err)
		os.Exit(2)
	}

	opts.logger = log.New(f, "", log.LstdFlags)
}
Example #5
0
func (v *Volume) load(alsoLoadIndex bool) error {
	var e error
	fileName := path.Join(v.dir, v.Id.String())
	if exists, canRead, canWrite, _ := checkFile(fileName + ".dat"); exists && !canRead {
		return fmt.Errorf("cannot read Volume Data file %s.dat", fileName)
	} else if !exists || canWrite {
		v.dataFile, e = os.OpenFile(fileName+".dat", os.O_RDWR|os.O_CREATE, 0644)
	} else if exists && canRead {
		glog.V(0).Infoln("opening " + fileName + ".dat in READONLY mode")
		v.dataFile, e = os.Open(fileName + ".dat")
		v.readOnly = true
	} else {
		return fmt.Errorf("Unknown state about Volume Data file %s.dat", fileName)
	}
	if e != nil {
		if !os.IsPermission(e) {
			return fmt.Errorf("cannot load Volume Data %s.dat: %s", fileName, e.Error())
		}
	}

	if v.ReplicaType == CopyNil {
		e = v.readSuperBlock()
	} else {
		e = v.maybeWriteSuperBlock()
	}
	if e == nil && alsoLoadIndex {
		var indexFile *os.File
		if v.readOnly {
			glog.V(1).Infoln("open to read file", fileName+".idx")
			if indexFile, e = os.OpenFile(fileName+".idx", os.O_RDONLY, 0644); e != nil {
				return fmt.Errorf("cannot read Volume Data %s.dat: %s", fileName, e.Error())
			}

			if v.ensureConvertIdxToCdb(fileName) {
				v.nm, e = OpenCdbMap(fileName + ".cdb")
				return e
			}
			if indexFile != nil {
				glog.V(0).Infoln("converting %s.idx to %s.cdb", fileName, fileName)
				if e = ConvertIndexToCdb(fileName+".cdb", indexFile); e != nil {
					glog.Errorln("error converting %s.idx to %s.cdb: %s", fileName, fileName, e)
				} else {
					indexFile.Close()
					os.Remove(indexFile.Name())
					indexFile = nil
				}
			}
		} else {
			glog.V(1).Infoln("open to write file", fileName+".idx")
			if indexFile, e = os.OpenFile(fileName+".idx", os.O_RDWR|os.O_CREATE, 0644); e != nil {
				return fmt.Errorf("cannot write Volume Data %s.dat: %s", fileName, e.Error())
			}
		}
		glog.V(0).Infoln("loading file", fileName+".idx", "readonly", v.readOnly)
		if v.nm, e = LoadNeedleMap(indexFile); e != nil {
			glog.V(0).Infoln("loading error:", e)
		}
	}
	return e
}
Example #6
0
// WriteTo writes the entire database to a writer.
// If err == nil then exactly tx.Size() bytes will be written into the writer.
func (tx *Tx) WriteTo(w io.Writer) (n int64, err error) {
	// Attempt to open reader directly.
	var f *os.File
	if f, err = os.OpenFile(tx.db.path, os.O_RDONLY|odirect, 0); err != nil {
		// Fallback to a regular open if that doesn't work.
		if f, err = os.OpenFile(tx.db.path, os.O_RDONLY, 0); err != nil {
			return 0, err
		}
	}

	// Copy the meta pages.
	tx.db.metalock.Lock()
	n, err = io.CopyN(w, f, int64(tx.db.pageSize*2))
	tx.db.metalock.Unlock()
	if err != nil {
		_ = f.Close()
		return n, fmt.Errorf("meta copy: %s", err)
	}

	// Copy data pages.
	wn, err := io.CopyN(w, f, tx.Size()-int64(tx.db.pageSize*2))
	n += wn
	if err != nil {
		_ = f.Close()
		return n, err
	}

	return n, f.Close()
}
Example #7
0
func TestFStatFs(t *testing.T) {
	ts := NewTestCase(t)
	defer ts.Cleanup()

	fOrig, err := os.OpenFile(ts.orig+"/file", os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0644)
	if err != nil {
		t.Fatalf("OpenFile failed: %v", err)
	}
	defer fOrig.Close()

	empty := syscall.Statfs_t{}
	s1 := empty
	errno := syscall.Fstatfs(int(fOrig.Fd()), &s1)
	if errno != nil {
		t.Fatal("statfs orig", err)
	}

	fMnt, err := os.OpenFile(ts.mnt+"/file", os.O_RDWR, 0644)
	if err != nil {
		t.Fatalf("OpenFile failed: %v", err)
	}
	defer fMnt.Close()
	s2 := empty

	errno = syscall.Fstatfs(int(fMnt.Fd()), &s2)
	if errno != nil {
		t.Fatal("statfs mnt", err)
	}

	clearStatfs(&s1)
	clearStatfs(&s2)
	if fmt.Sprintf("%v", s2) != fmt.Sprintf("%v", s1) {
		t.Errorf("statfs mismatch: %#v != %#v", s1, s2)
	}
}
Example #8
0
// openFileAndCehckpoint will create a checkpoint file, open a new file for
// writing a data index, write the header and return the file
func (e *Engine) openFileAndCheckpoint(fileName string) (*os.File, error) {
	checkpointFile := fmt.Sprintf("%s.%s", fileName, CheckpointExtension)
	cf, err := os.OpenFile(checkpointFile, os.O_CREATE, 0666)
	if err != nil {
		return nil, err
	}
	// _, err = cf.Write(u32tob(magicNumber))
	// if err != nil {
	// 	panic(err)
	// }
	if err := cf.Close(); err != nil {
		return nil, err
	}
	_, err = os.Stat(checkpointFile)

	f, err := os.OpenFile(fileName, os.O_CREATE|os.O_RDWR, 0666)
	if err != nil {
		return nil, err
	}

	// write the header, which is just the magic number
	if _, err := f.Write(u32tob(magicNumber)); err != nil {
		f.Close()
		return nil, err
	}

	return f, nil
}
Example #9
0
func benchmarkAllocatorRndGetACIDFiler(b *testing.B, sz int) {
	os.Remove(testDbName)
	os.Remove(walName)
	f, err := os.OpenFile(testDbName, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0600)
	if err != nil {
		b.Fatal(err)
	}

	defer func() {
		f.Close()
		os.Remove(testDbName)
	}()

	wal, err := os.OpenFile(walName, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0600)
	if err != nil {
		b.Fatal(err)
	}

	defer func() {
		wal.Close()
		os.Remove(walName)
	}()

	filer, err := NewACIDFiler(NewSimpleFileFiler(f), wal)
	if err != nil {
		b.Error(err)
		return
	}

	benchmarkAllocatorRndGet(b, filer, sz)
}
Example #10
0
func ReloadLogger(tutumLogFile string, dockerLogFile string) {
	if TutumLogDescriptor.Fd() != os.Stdout.Fd() {
		f, err := os.OpenFile(tutumLogFile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
		if err != nil {
			SendError(err, "Failed to open tutum log file", nil)
			log.Println(err)
			log.Println("Log to stdout instead")
			f = os.Stdout
		}
		Logger = log.New(f, "", log.Ldate|log.Ltime)
		TutumLogDescriptor.Close()
		TutumLogDescriptor = f
		Logger.Print("SIGHUP: Tutum log file descriptor has been reloaded")
	} else {
		Logger.Print("SIGHUP: No need to reload tutum logs when printing to stdout")
	}

	Logger.Print("SIGHUP: Reloading docker log file descriptor")
	f, err := os.OpenFile(dockerLogFile, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		SendError(err, "Failed to set docker log file", nil)
		Logger.Println(err)
		Logger.Println("Cannot set docker log to", dockerLogFile)
	} else {
		go io.Copy(f, DockerLogStdoutDescriptor)
		go io.Copy(f, DockerLogStderrDescriptor)
		DockerLogDescriptor.Close()
		DockerLogDescriptor = f
		Logger.Print("SIGHUP: Docker log file descriptor has been reloaded")
	}
}
Example #11
0
func (n NetworkLinks) Write(path string, appends bool) error {
	var file *os.File
	var err error

	if appends {
		file, err = os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0660)
	} else {
		file, err = os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0660)
		if os.IsExist(err) {
			file, err = os.OpenFile(path, os.O_TRUNC|os.O_WRONLY, 0660)
		}
	}
	if err != nil {
		log.Print("network_links: Unable to open network links file: ", err)
		return err
	}
	defer file.Close()

	for i := range n {
		if _, errw := fmt.Fprintf(file, "%s\t%d\t%d\t%s\n", n[i].FromHost, n[i].FromPort, n[i].ToPort, n[i].ToHost); errw != nil {
			log.Print("network_links: Unable to write network links: ", err)
			return err
		}
	}
	if errc := file.Close(); errc != nil {
		log.Print("network_links: Unable to network links: ", errc)
		return err
	}
	return nil
}
Example #12
0
func (v *Volume) load(alsoLoadIndex bool, createDatIfMissing bool) error {
	var e error
	fileName := v.FileName()

	if exists, canRead, canWrite, _ := checkFile(fileName + ".dat"); exists {
		if !canRead {
			return fmt.Errorf("cannot read Volume Data file %s.dat", fileName)
		}
		if canWrite {
			v.dataFile, e = os.OpenFile(fileName+".dat", os.O_RDWR|os.O_CREATE, 0644)
		} else {
			glog.V(0).Infoln("opening " + fileName + ".dat in READONLY mode")
			v.dataFile, e = os.Open(fileName + ".dat")
			v.readOnly = true
		}
	} else {
		if createDatIfMissing {
			v.dataFile, e = os.OpenFile(fileName+".dat", os.O_RDWR|os.O_CREATE, 0644)
		} else {
			return fmt.Errorf("Volume Data file %s.dat does not exist.", fileName)
		}
	}

	if e != nil {
		if !os.IsPermission(e) {
			return fmt.Errorf("cannot load Volume Data %s.dat: %s", fileName, e.Error())
		}
	}

	if v.ReplicaPlacement == nil {
		e = v.readSuperBlock()
	} else {
		e = v.maybeWriteSuperBlock()
	}
	if e == nil && alsoLoadIndex {
		if v.readOnly {
			if v.ensureConvertIdxToCdb(fileName) {
				v.nm, e = OpenCdbMap(fileName + ".cdb")
				return e
			}
		}
		var indexFile *os.File
		if v.readOnly {
			glog.V(1).Infoln("open to read file", fileName+".idx")
			if indexFile, e = os.OpenFile(fileName+".idx", os.O_RDONLY, 0644); e != nil {
				return fmt.Errorf("cannot read Volume Index %s.idx: %s", fileName, e.Error())
			}
		} else {
			glog.V(1).Infoln("open to write file", fileName+".idx")
			if indexFile, e = os.OpenFile(fileName+".idx", os.O_RDWR|os.O_CREATE, 0644); e != nil {
				return fmt.Errorf("cannot write Volume Index %s.idx: %s", fileName, e.Error())
			}
		}
		glog.V(0).Infoln("loading file", fileName+".idx", "readonly", v.readOnly)
		if v.nm, e = LoadNeedleMap(indexFile); e != nil {
			glog.V(0).Infoln("loading error:", e)
		}
	}
	return e
}
Example #13
0
func Configure(fileName string, appendFile bool) error {
	StripPackage = true
	PadLocation = false
	HideLocation = false

	if len(fileName) > 0 {
		fh, e := os.OpenFile(fileName, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0660)
		if e != nil {
			if appendFile {
				fh, e = os.OpenFile(fileName, os.O_RDWR|os.O_APPEND, 0660)
			} else {
				e = os.Rename(fileName, fileName+time.Now().Format(".20060102-150405"))
				fh, e = os.OpenFile(fileName, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0660)
			}
		}
		if e != nil {
			return e
		}
		fileHandle = fh
		writer = io.MultiWriter(fh, os.Stdout)
	} else {
		writer = os.Stdout
	}
	golog.SetFlags(golog.Ltime)
	golog.SetOutput(writer)
	maxLevel = Info
	return nil
}
func (c *containerProcess) openIo() (err error) {
	defer func() {
		if err != nil {
			c.Cleanup()
		}
	}()

	c.io.stdinf, err = os.OpenFile(c.io.stdin, os.O_RDWR, 0)
	if err != nil {
		return err
	}

	c.io.stdoutf, err = os.OpenFile(c.io.stdout, os.O_RDWR, 0)
	if err != nil {
		return err
	}
	go io.Copy(&c.io.stdoutBuffer, c.io.stdoutf)

	c.io.stderrf, err = os.OpenFile(c.io.stderr, os.O_RDWR, 0)
	if err != nil {
		return err
	}
	go io.Copy(&c.io.stderrBuffer, c.io.stderrf)

	return nil
}
Example #15
0
func OutputRes() {
	//save all result
	allFile, err := os.OpenFile(*saveFile, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0666)
	if err != nil {
		logger.Println("Open file error,", err)
	}
	defer allFile.Close()

	//save has result
	hasFile, err := os.OpenFile(*hasFile, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0666)
	if err != nil {
		logger.Println("Open file error,", err)
	}
	defer hasFile.Close()

	var num int64 = 0
	var has int64 = 0
	for k, address := range Visit {
		str := fmt.Sprintf("%-4d has: %-5t,  url:  %s\n", num, address.Has, k)
		// logger.Printf("%-4d  has: %t,url: %-40s\n", num, address.Has, k)
		logger.Printf(str)
		allFile.WriteString(str)
		if address.Has {
			hasFile.WriteString(fmt.Sprintf("%-4d has: %-5t,  url:  %s\n", has, address.Has, k))
		}
		num++
		has++
	}
}
Example #16
0
func (q *Query) startWriteMode() error {
	var e error
	ci := q.Connection().(*Connection).Info()
	if q.newFileWrite {
		q.tempfile, e = os.OpenFile(q.filePath+".temp", os.O_CREATE, 0666)
	} else {
		q.tempfile, e = os.OpenFile(q.filePath, os.O_RDWR|os.O_APPEND, 0666)
	}

	if e != nil {
		return e
	}

	q.writer = csv.NewWriter(q.tempfile)

	if delimiter := ci.Settings.Get("delimiter", "").(string); delimiter != "" {
		q.writer.Comma = rune(delimiter[0])
	}

	if q.newFileWrite && q.isUseHeader && len(q.headerColumn) > 0 {
		datatemp := make([]string, 0)
		for _, v := range q.headerColumn {
			datatemp = append(datatemp, v.name)
		}

		q.writer.Write(datatemp)
		q.writer.Flush()
	}

	return nil
}
Example #17
0
func logIRC(irc map[string]string) {
	if _, err := os.Stat("./logs"); err != nil {
		if os.IsNotExist(err) {
			color.Green("Creating directory logs")
			os.Mkdir("./logs", 0766)
		}
	}
	if strings.HasPrefix(irc["params"], "#") {
		s := strings.Split(irc["params"], " ")
		f, err := os.OpenFile("logs/"+s[0]+".log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
		if err != nil {
			log.Fatalf("Error opening logfile for %s: %v", irc["params"], err)
		}
		log.SetOutput(f)
		log.Printf("%s %s %s %s\n", irc["prefix"], irc["command"], irc["params"], irc["trailing"])
		defer f.Close()
	} else {
		f, err := os.OpenFile("logs/all.log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
		if err != nil {
			log.Fatalf("Error opening logfile all: %v", err)
		}
		log.SetOutput(f)
		log.Printf("%s %s %s %s %s\n", irc["tags"], irc["prefix"], irc["command"], irc["params"], irc["trailing"])
		defer f.Close()
	}
}
func configureLogger() log.Logger {
	level := configParameters["nagios2opsgenie.logger"]
	var logFilePath = parameters["logPath"]

	if len(logFilePath) == 0 {
		logFilePath = "/var/log/opsgenie/nagios2opsgenie.log"
	}

	var tmpLogger log.Logger

	file, err := os.OpenFile(logFilePath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)

	if err != nil {
		fmt.Println("Could not create log file \""+logFilePath+"\", will log to \"/tmp/nagios2opsgenie.log\" file. Error: ", err)

		fileTmp, errTmp := os.OpenFile("/tmp/nagios2opsgenie.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)

		if errTmp != nil {
			fmt.Println("Logging disabled. Reason: ", errTmp)
		} else {
			tmpLogger = golog.New(fileTmp, levels[strings.ToLower(level)])
		}
	} else {
		tmpLogger = golog.New(file, levels[strings.ToLower(level)])
	}

	return tmpLogger
}
Example #19
0
func (f *FileStorage) writeToFile(item FileStorageItem) error {
	f.mxt.Lock()
	if f.currentFile != nil {
		fInfo, err := f.currentFile.Stat()
		if err != nil || fInfo.Name() != f.getCurrentFileName() {
			f.currentFile.Close()
			f.currentFile, err = os.OpenFile(f.getCurrentFileName(), os.O_CREATE|os.O_RDWR|os.O_APPEND, 0666)
		}
	} else {
		f.currentFile, _ = os.OpenFile(f.getCurrentFileName(), os.O_CREATE|os.O_RDWR|os.O_APPEND, 0666)
	}

	lineBytes, err := item.MarshalBinary()
	if err != nil {
		log.Errorf("Error marshaling %s  data %#v", err.Error(), item)
	}
	_, err = f.currentFile.WriteString(string(lineBytes) + "\n")

	if err != nil {
		log.Errorf("Error write to local storage %s  data %s", err.Error(), string(lineBytes))
	}
	f.mxt.Unlock()

	return err
}
func (d *digitalPin) setMode(mode string) {
	d.Mode = mode

	if mode == "w" {
		fi, err := os.OpenFile(GPIO_PATH+"/gpio"+d.PinNum+"/direction", os.O_WRONLY, 0666)
		if err != nil {
			panic(err)
		}
		fi.WriteString(GPIO_DIRECTION_WRITE)
		fi.Close()
		d.PinFile, err = os.OpenFile(GPIO_PATH+"/gpio"+d.PinNum+"/value", os.O_WRONLY, 0666)
		if err != nil {
			panic(err)
		}
	} else if mode == "r" {
		fi, err := os.OpenFile(GPIO_PATH+"/gpio"+d.PinNum+"/direction", os.O_WRONLY, 0666)
		if err != nil {
			panic(err)
		}
		fi.WriteString(GPIO_DIRECTION_READ)
		fi.Close()
		d.PinFile, err = os.OpenFile(GPIO_PATH+"/gpio"+d.PinNum+"/value", os.O_RDONLY, 0666)
		if err != nil {
			panic(err)
		}
	}
}
Example #21
0
File: modle.go Project: shaalx/gooj
func GenerateOjModle(path_ string, m *Model) error {
	_, err := os.Stat(path_)
	if !goutils.CheckErr(err) {
		os.RemoveAll(path_)
	}
	err = os.Mkdir(path_, 0777)
	if goutils.CheckErr(err) {
		// return err
	}
	fname := m.FuncName + ".go"
	tname := m.FuncName + "_test.go"
	func_file, err := os.OpenFile(filepath.Join(path_, fname), os.O_CREATE|os.O_WRONLY, 0644)
	defer func_file.Close()
	if goutils.CheckErr(err) {
		return err
	}
	if goutils.CheckErr(generateOjFunc(m.Content, func_file)) {
		return fmt.Errorf("generateOjFunc error")
	}

	test_file, err := os.OpenFile(filepath.Join(path_, tname), os.O_CREATE|os.O_WRONLY, 0644)
	defer test_file.Close()
	if goutils.CheckErr(err) {
		return err
	}
	args := make(map[string]interface{})
	args["FUNC"] = m.FuncName
	args["ArgsType"] = m.ArgsType
	args["RetsType"] = m.RetsType
	args["TestCases"] = m.TestCases
	return renderOjModle(args, test_file)
}
Example #22
0
func makeUpgradeKeys([]string) error {
	priv, pub := upgradebin.GenerateKeys(rand.Reader)
	privPem, pubPem := upgradebin.EncodeKeys(priv, pub)
	fmt.Println("")
	fmt.Println(string(privPem))
	fmt.Println("")
	fmt.Println(string(pubPem))

	privFile, err1 := os.OpenFile("upgrades-private-key.pem",
		os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)
	defer privFile.Close()

	pubFile, err2 := os.OpenFile("upgrades-public-key.pem",
		os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)

	defer pubFile.Close()
	if err1 != nil {
		return err1
	}
	if err2 != nil {
		return err2
	}

	_, err1 = privFile.Write(privPem)
	_, err2 = pubFile.Write(pubPem)

	if err1 != nil {
		return err1
	}
	if err2 != nil {
		return err2
	}

	return nil
}
Example #23
0
func main() {
	flag.Parse()

	if *showVersion {
		fmt.Printf("json2csv v1.1\n")
		return
	}

	var reader *bufio.Reader
	var writer *csv.Writer
	if *inputFile != "" {
		file, err := os.OpenFile(*inputFile, os.O_RDONLY, 0600)
		if err != nil {
			log.Printf("Error %s opening %v", err, *inputFile)
			return
		}
		reader = bufio.NewReader(file)
	} else {
		reader = bufio.NewReader(os.Stdin)
	}

	if *outputFile != "" {
		file, err := os.OpenFile(*outputFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
		if err != nil {
			log.Printf("Error %s opening outputFile %v", err, *outputFile)
		}
		writer = csv.NewWriter(file)
	} else {
		writer = csv.NewWriter(os.Stdout)
	}

	json2csv(reader, writer, keys)
}
Example #24
0
func NewProcess(id uint64, bin string, cmd string, args []string, stdout_file, stderr_file string) (*Vproc, error) {
	p := new(Vproc)
	p.Id = id
	p.Cmd = exec.Command(bin, cmd)
	var a = []string{bin, cmd}
	a = append(a, args...)

	p.Cmd.Args = a
	p.Cmd.Env = os.Environ()

	log.Debug("%v\n", a)

	stdout, err := os.OpenFile(stdout_file, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0666)
	if err != nil {
		return nil, err
	}
	p.Cmd.Stdout = stdout

	stderr, err := os.OpenFile(stderr_file, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0666)
	if err != nil {
		return nil, err
	}
	p.Cmd.Stderr = stderr

	return p, nil
}
Example #25
0
func main() {
	filename := flag.String("s", "./log", "log file")
	flag.Parse()
	filename1 := "./1.log"
	filename2 := "./2.log"
	filename3 := "./3.log"
	filename4 := "./4.log"

	var (
		fd  *os.File
		fds [4]*os.File
		err error
	)

	fd, err = os.OpenFile(*filename, os.O_RDWR, 0660)
	fds[0], err = os.OpenFile(filename1, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0660)
	fds[1], err = os.OpenFile(filename2, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0660)
	fds[2], err = os.OpenFile(filename3, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0660)
	fds[3], err = os.OpenFile(filename4, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0660)

	buff := make([]byte, 2048)
	for i := 0; i < 4; i++ {
		_, err = fd.Read(buff)
		if err != nil {
			return
		}
		go func() {
			for i := 0; i < 4; i++ {
				go write_buff(fds[i], buff)
			}
		}()
	}
}
Example #26
0
func main() {
	// Parse the username and password from the flags
	flag.Parse()
	if *uname == "" || *passwd == "" {
		log.Fatal("Invalid username or password: "******"%x", h.Sum(nil))
	defer writeConfig() // write out whenever you quit
	// Request work every time the free RAM reaches >= 25% of total RAM.
	// Keep requesting work whenever you get a notification for the system to be idle and start it off
	ch := make(chan time.Time, 10)
	notifyIdleSystem(ch)
	for t := range ch {
		// request work from the server
		go requestWork()
	}
}
Example #27
0
File: file.go Project: uabassguy/ql
// OpenFile returns a DB backed by a named file. The back end limits the size
// of a record to about 64 kB.
func OpenFile(name string, opt *Options) (db *DB, err error) {
	var f lldb.OSFile
	if f = opt.OSFile; f == nil {
		f, err = os.OpenFile(name, os.O_RDWR, 0666)
		if err != nil {
			if !os.IsNotExist(err) {
				return nil, err
			}

			if !opt.CanCreate {
				return nil, err
			}

			f, err = os.OpenFile(name, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0666)
			if err != nil {
				return nil, err
			}
		}
	}

	fi, err := newFileFromOSFile(f) // always ACID
	if err != nil {
		return
	}

	if fi.tempFile = opt.TempFile; fi.tempFile == nil {
		fi.tempFile = func(dir, prefix string) (f lldb.OSFile, err error) {
			f0, err := ioutil.TempFile(dir, prefix)
			return f0, err
		}
	}

	return newDB(fi)
}
Example #28
0
// OpenPTY Creates a new Master/Slave PTY pair.
func OpenPTY() (*PTY, error) {
	// Opening ptmx gives you the FD of a brand new PTY
	master, err := os.OpenFile("/dev/ptmx", os.O_RDWR, 0)
	if err != nil {
		return nil, err
	}

	// unlock pty slave
	var unlock int // 0 => Unlock
	if _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, uintptr(master.Fd()), uintptr(TIOCSPTLCK), uintptr(unsafe.Pointer(&unlock))); errno != 0 {
		master.Close()
		return nil, errno
	}

	// get path of pts slave
	pty := &PTY{Master: master}
	slaveStr, err := pty.PTSName()
	if err != nil {
		master.Close()
		return nil, err
	}

	// open pty slave
	pty.Slave, err = os.OpenFile(slaveStr, os.O_RDWR|syscall.O_NOCTTY, 0)
	if err != nil {
		master.Close()
		return nil, err
	}

	return pty, nil
}
Example #29
0
func fwrite(t Fataler, p1, p2 string) bool {
	fd1, err1 := os.OpenFile(p1, os.O_WRONLY, 0)
	if fd1 != nil {
		defer fd1.Close()
	}
	fd2, err2 := os.OpenFile(p2, os.O_WRONLY, 0)
	if fd2 != nil {
		defer fd2.Close()
	}
	if err1 != nil && err2 != nil {
		t.Logf("write %s fails", p1)
		return false
	}
	if err1 != nil || err2 != nil {
		t.Fatalf("errors in remove: %v vs %v", err1, err2)
	}
	pos := rand.Intn(maxSeek)
	sz := rand.Intn(len(wbuf))
	n1, err1 := fd1.WriteAt(wbuf[:sz], int64(pos))
	n2, err2 := fd2.WriteAt(wbuf[:sz], int64(pos))
	if n1 != n2 {
		t.Fatalf("write: %d vs %d bytes", n1, n2)
	}
	if err1 != nil && err2 != nil {
		t.Logf("write %s fails", p1)
		return false
	}
	if err1 != nil || err2 != nil {
		t.Fatalf("errors in write: %v vs %v", err1, err2)
	}
	t.Logf("write %s %d [%d] ok", p1, pos, sz)
	return true
}
Example #30
0
func copyToBin() (err error) {
	src, err := osext.Executable()
	if err != nil {
		return
	}

	dst := "/usr/bin/fiddler"

	log.Println("Copying", src, "to", dst, "...")

	sf, err := os.OpenFile(src, os.O_RDONLY, 0666)
	if err != nil {
		return
	}
	defer sf.Close()

	df, err := os.OpenFile(dst, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0744)
	if err != nil {
		return
	}
	defer df.Close()

	_, err = io.Copy(df, sf)
	if err != nil {
		return
	}

	log.Println("Done.")

	return
}