Ejemplo n.º 1
0
func TestGitSubmoduleAddNotInIndex(ot *testing.T) {
	GitTestCb(func() {
		kmgCmd.MustRun("git init")
		kmgFile.MustWriteFileWithMkdir("sub/1.txt", []byte("1"))
		kmgCmd.CmdString("git init").SetDir("sub").MustRun()
		kmgCmd.CmdString("git add -A").SetDir("sub").MustRun()
		kmgCmd.CmdString("git commit -am'save'").SetDir("sub").MustRun()

		repo := MustGetRepositoryFromPath(".")
		repo.MustFakeSubmoduleAdd("sub")
		kmgTest.Equal(repo.MustIsFileInIndex("sub/1.txt"), true)
	})
}
Ejemplo n.º 2
0
func TestGitSubmoduleInitIgnore(ot *testing.T) {
	kmgGit.GitTestCb(func() {
		kmgCmd.MustRun("git init")
		kmgFile.MustWriteFile(".gitignore", []byte("/subIgnored"))
		kmgFile.MustWriteFileWithMkdir("subIgnored/1.txt", []byte("1"))
		kmgCmd.CmdString("git init").SetDir("subIgnored").MustRun()
		kmgCmd.CmdString("git add -A").SetDir("subIgnored").MustRun()
		kmgCmd.CmdString("git commit -am'save'").SetDir("subIgnored").MustRun()

		repo := kmgGit.MustGetRepositoryFromPath(".")
		GitSubmoduleInit(repo)
		kmgTest.Equal(repo.MustIsFileInIndex("subIgnored"), false)
	})
}
Ejemplo n.º 3
0
//每次尝试连接,5秒超时,超时后,重试12次,最多等1分钟
//若 isReachable = false,则 havePermission 没有有意义
func AvailableCheck(remote *RemoteServer) (isReachable, havePermission bool) {
	retry := 0
	for {
		cmd := kmgCmd.CmdString("ssh -o StrictHostKeyChecking=no -o PasswordAuthentication=no -o ConnectTimeout=5 " + remote.String() + " echo ok")
		start := time.Now()
		b, e := cmd.CombinedOutput()
		delta := time.Now().Sub(start)
		fmt.Println("[kmgSsh AvailableCheck] ssh -o StrictHostKeyChecking=no -o PasswordAuthentication=no -o ConnectTimeout=5 " + remote.String() + " echo ok")
		fmt.Println("[kmgSsh AvailableCheck]", remote.Address, string(b))
		if e == nil && strings.HasPrefix(string(b), "ok") {
			return true, true
		}
		if e != nil && strings.Contains(string(b), "Permission denied") {
			return true, false
		}
		delta -= time.Second * 5
		if delta < 0 {
			time.Sleep(-1 * delta)
		}
		retry++
		fmt.Println("[kmgSsh AvailableCheck]", remote.Address, "retry", retry)
		if retry == 24 {
			return false, false
		}
	}
	return false, false
}
Ejemplo n.º 4
0
//目前仅支持linux
func (a DeviceAddr) IpAddrDel() (err error) {
	if !kmgPlatform.IsLinux() {
		panic("[DeviceAddr.IpAddrDel] only support linux now")
	}
	one, _ := a.IPNet.Mask.Size()
	return kmgCmd.CmdString(fmt.Sprintf("ip addr del %s/%d dev %s", a.IP.String(), one, a.DevString)).Run()
}
Ejemplo n.º 5
0
func TestTap(ot *testing.T) {
	tap, err := NewTap("")
	if os.IsPermission(err) {
		ot.Skip("you need root permission to run this test.")
		return
	}
	kmgTest.Equal(err, nil)
	defer tap.Close()
	kmgTest.Equal(tap.GetDeviceType(), DeviceTypeTap)

	err = kmgCmd.CmdString("ifconfig " + tap.Name() + " 10.209.34.1 up").GetExecCmd().Run()
	kmgTest.Equal(err, nil)
	/*
		cmd := kmgCmd.NewOsStdioCmdString("ping 10.0.0.2")
		err = cmd.Start()
		t.Equal(err, nil)
		defer cmd.Process.Kill()

		buf := make([]byte, 4096)
		n, err := tun.Read(buf)
		t.Equal(err, nil)
		t.Ok(n > 0)

		tun2, err := NewTap("")
		t.Equal(err, nil)
		defer tun2.Close()
	*/
}
Ejemplo n.º 6
0
func TestTun(ot *testing.T) {
	fmt.Println(1)
	tun, err := NewTun("")
	fmt.Println(2)
	if os.IsPermission(err) {
		ot.Skip("you need root permission to run this test.")
		return
	}
	kmgTest.Equal(err, nil)
	defer tun.Close()
	kmgTest.Equal(tun.GetDeviceType(), DeviceTypeTun)
	fmt.Println(3)

	err = SetP2PIpAndUp(tun, "10.209.34.1", "10.209.34.2")
	kmgTest.Equal(err, nil)

	err = SetMtu(tun, 1420)
	kmgTest.Equal(err, nil)
	fmt.Println(4)
	cmd := kmgCmd.CmdString("ping 10.209.34.2").GetExecCmd()
	err = cmd.Start()
	kmgTest.Equal(err, nil)
	defer cmd.Process.Kill()

	buf := make([]byte, 4096)
	n, err := tun.Read(buf)
	kmgTest.Equal(err, nil)
	kmgTest.Ok(n > 0)
	/*
		tun2, err := NewTun("")
		t.Equal(err, nil)
		defer tun2.Close()
	*/
}
Ejemplo n.º 7
0
//目前仅支持linux
func GetCurrentDeviceAddr() (ipnets []DeviceAddr, err error) {
	if !kmgPlatform.IsLinux() {
		panic("[GetCurrentDeviceAddr] only support linux now")
	}
	out, err := kmgCmd.CmdString("ip addr").RunAndReturnOutput()
	if err != nil {
		return
	}
	return getCurrentDeviceAddrFromIPAddr(out)
}
Ejemplo n.º 8
0
func TestMustGenerateCode(t *testing.T) {
	kmgGoTpl.MustBuildTplInDirWithCache("src/github.com/bronze1man/kmg/kmgRpc") // 模板变化需要运行两次,才能看到结果.
	kmgFile.MustDelete("testPackage/generated.go")
	MustGenerateCode(&GenerateRequest{
		ObjectPkgPath:        "github.com/bronze1man/kmg/kmgRpc/testPackage",
		ObjectName:           "Demo",
		ObjectIsPointer:      true,
		OutFilePath:          "testPackage/generated.go",
		OutPackageImportPath: "github.com/bronze1man/kmg/kmgRpc/testPackage",
	})
	kmgCmd.CmdString("kmg go test").SetDir("testPackage").Run()
}
Ejemplo n.º 9
0
func (repo *Repository) MustGetIndexFileList() []string {
	output := kmgCmd.CmdString("git ls-files").SetDir(repo.gitPath).MustCombinedOutput()
	outputSlice := []string{}
	for _, s := range strings.Split(string(output), "\n") {
		s = strings.TrimSpace(s)
		if s == "" {
			continue
		}
		outputSlice = append(outputSlice, s)
	}
	return outputSlice
}
Ejemplo n.º 10
0
func TestTplGenerateCode(t *testing.T) {
	out := tplGenerateCode(&tplConfig{
		OutPackageName: "tplTestPackage",
		ObjectName:     "Demo",
		ObjectTypeStr:  "*Demo",
		ApiList: []Api{
			{
				Name: "PostScoreInt",
				InArgsList: []ArgumentNameTypePair{
					{
						Name:          "LbId",
						ObjectTypeStr: "string",
					},
					{
						Name:          "Score",
						ObjectTypeStr: "int",
					},
				},
				OutArgsList: []ArgumentNameTypePair{
					{
						Name:          "Info",
						ObjectTypeStr: "string",
					},
					{
						Name:          "Err",
						ObjectTypeStr: "error",
					},
				},
			},
		},
		ImportPathMap: map[string]bool{
			"encoding/json": true,
			"errors":        true,
			"fmt":           true,
			"github.com/bronze1man/kmg/kmgCrypto":      true,
			"github.com/bronze1man/kmg/kmgLog":         true,
			"github.com/bronze1man/kmg/kmgNet/kmgHttp": true,
			"net/http": true,
			"bytes":    true,
		},
	})
	kmgFile.MustDeleteFile("tplTestPackage/generated.go")
	kmgFile.MustWriteFileWithMkdir("tplTestPackage/generated.go", []byte(out))
	kmgCmd.CmdString("kmg go test").SetDir("tplTestPackage").Run()
}
Ejemplo n.º 11
0
func runCommand(kmgc *kmgConfig.Env, args []string) {
	os.Chdir(kmgc.ProjectPath)
	logDir := filepath.Join(kmgc.LogPath, "run")
	kmgFile.MustMkdirAll(logDir)
	thisLogFilePath := filepath.Join(logDir, time.Now().Format(kmgTime.FormatFileName)+".log")
	kmgFile.MustWriteFile(thisLogFilePath, []byte{})
	if !kmgPlatform.GetCompiledPlatform().Compatible(kmgPlatform.WindowsAmd64) {
		lastLogPath := filepath.Join(logDir, "last.log")
		if kmgFile.MustFileExist(lastLogPath) {
			kmgFile.MustSymlink(kmgFile.MustReadSymbolLink(lastLogPath), filepath.Join(logDir, "last2.log"))
		}
		kmgFile.MustSymlink(filepath.Base(thisLogFilePath), lastLogPath)
	}
	//TODO 大部分命令是 kmg gorun xxx 在这个地方可以直接调用gorun解决问题,这样可以少开一个进程加快了一些速度
	// 问题: 上述做法不靠谱,会导致last.log没有用处.
	//if len(args) >= 2 && args[0] == "kmg" && strings.EqualFold(args[1], "gorun") {
	//	os.Args = append(args[1:], os.Args[1:]...)
	//	goCmd.GoRunCmd()
	//	return
	//}
	// 下面的做法不靠谱,会让signle无法传递
	//err := kmgCmd.CmdSlice(append(args, os.Args[1:]...)).
	//	SetDir(kmgc.ProjectPath).
	//	RunAndTeeOutputToFile(thisLogFilePath)
	// TODO bash转义
	bashCmd := strings.Join(append(args, os.Args[1:]...), " ")
	bashCmdStr := bashCmd + " 2>&1 | tee -i " + thisLogFilePath + " ; test ${PIPESTATUS[0]} -eq 0"
	if kmgPlatform.IsWindows() {
		err := kmgCmd.CmdString(bashCmdStr).SetDir(kmgc.ProjectPath).StdioRun()
		if err != nil {
			err = fmt.Errorf("kmg make: %s", err)
			kmgConsole.ExitOnErr(err)
		}
		return
	} else {
		err := kmgCmd.CmdBash(bashCmdStr).SetDir(kmgc.ProjectPath).StdioRun()
		if err != nil {
			err = fmt.Errorf("kmg make: %s", err)
			kmgConsole.ExitOnErr(err)
		}
		return
	}
}
Ejemplo n.º 12
0
Archivo: cmd.go Proyecto: keysonZZZ/kmg
func MustRpcSshCmd(ip string, cmd ...string) []byte {
	if len(cmd) == 0 {
		return []byte{}
	}
	if ip == "" {
		return []byte{}
	}
	cmdCombine := strings.Join(cmd, "&&")
	out, err := kmgCmd.CmdString("ssh -o StrictHostKeyChecking=no -o PasswordAuthentication=no root@" + ip + " " + cmdCombine).RunAndReturnOutput()
	logPath := "/tmp/rpcSshCmd-" + ip
	kmgFile.MustAppendFile(logPath, []byte(strings.Join([]string{cmdCombine, kmgTime.DefaultFormat(time.Now())}, "\n")))
	kmgFile.MustAppendFile(logPath, out)
	if err != nil {
		//		_, ok := err.(*exec.ExitError)
		//		if ok {
		//			return out
		//		}
		kmgFile.MustAppendFile(logPath, []byte(err.Error()))
		panic(err)
	}
	return out
}
Ejemplo n.º 13
0
func (repo *Repository) MustGetHeadCommitId() string {
	output := kmgCmd.CmdString("git rev-parse HEAD").SetDir(repo.gitPath).MustCombinedOutput()
	return strings.TrimSpace(string(output))
}
Ejemplo n.º 14
0
func (repo *Repository) MustGetCurrentBranchName() string {
	output := kmgCmd.CmdString("git rev-parse --abbrev-ref HEAD").SetDir(repo.gitPath).MustCombinedOutput()
	return strings.TrimSpace(string(output))
}
Ejemplo n.º 15
0
Archivo: cmd.go Proyecto: keysonZZZ/kmg
// 带压缩的ssh下载
func MustSshCmdWithCompress(ip string, cmd string) []byte {
	out := kmgCmd.CmdString("ssh -o StrictHostKeyChecking=no -o PasswordAuthentication=no -C root@" + ip + " " + cmd).MustCombinedOutputWithErrorPrintln()
	return out
}
Ejemplo n.º 16
0
func installMysql() {
	kmgCmd.ProxyRun("apt-get update")
	kmgCmd.CmdString("apt-get -y install mysql-server").MustSetEnv("DEBIAN_FRONTEND", "noninteractive").ProxyRun()
}