<commit_before>/* btckeygenie v1.0.0
 * https://github.com/vsergeev/btckeygenie
 * License: MIT
 */

package btckey

import (
	"math/big"
	"testing"
)

var curve EllipticCurve

func init() {
	/* See SEC2 pg.9 http://www.secg.org/collateral/sec2_final.pdf */
	/* secp256k1 elliptic curve parameters */
	curve.P, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F", 16)
	curve.A, _ = new(big.Int).SetString("0000000000000000000000000000000000000000000000000000000000000000", 16)
	curve.B, _ = new(big.Int).SetString("0000000000000000000000000000000000000000000000000000000000000007", 16)
	curve.G.X, _ = new(big.Int).SetString("79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798", 16)
	curve.G.Y, _ = new(big.Int).SetString("483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8", 16)
	curve.N, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141", 16)
	curve.H, _ = new(big.Int).SetString("01", 16)
}

func hex2int(hexstring string) (v *big.Int) {
	v, _ = new(big.Int).SetString(hexstring, 16)
	return v
}

func TestOnCurve(t *testing.T) {
	if !curve.IsOnCurve(curve.G) {
		t.Fatal("failure G on curve")
	}

	t.Log("G on curve")
}

func TestInfinity(t *testing.T) {
	O := Point{nil, nil}

	/* O not on curve */
	if curve.IsOnCurve(O) {
		t.Fatal("failure O on curve")
	}

	/* O is infinity */
	if !curve.IsInfinity(O) {
		t.Fatal("failure O not infinity on curve")
	}

	t.Log("O is not on curve and is infinity")
}

func TestPointAdd(t *testing.T) {
	X := "50863ad64a87ae8a2fe83c1af1a8403cb53f53e486d8511dad8a04887e5b2352"
	Y := "2cd470243453a299fa9e77237716103abc11a1df38855ed6f2ee187e9c582ba6"

	P := Point{hex2int(X), hex2int(Y)}
	O := Point{nil, nil}

	/* R = O + O = O */
	{
		R := curve.Add(O, O)
		if !curve.IsInfinity(R) {
			t.Fatal("failure O + O = O")
		}
		t.Log("success O + O = O")
	}

	/* R = P + O = P */
	{
		R := curve.Add(P, O)
		if R.X.Cmp(P.X) != 0 || R.Y.Cmp(P.Y) != 0 {
			t.Fatal("failure P + O = P")
		}
		t.Log("success P + O = P")
	}

	/* R = O + Q = Q */
	{
		R := curve.Add(O, P)
		if R.X.Cmp(P.X) != 0 || R.Y.Cmp(P.Y) != 0 {
			t.Fatal("failure O + Q = Q")
		}
		t.Log("success O + Q = Q")
	}

	/* R = (x,y) + (x,-y) = O */
	{
		Q := Point{P.X, subMod(big.NewInt(0), P.Y, curve.P)}

		R := curve.Add(P, Q)
		if !curve.IsInfinity(R) {
			t.Fatal("failure (x,y) + (x,-y) = O")
		}
		t.Log("success (x,y) + (x,-y) = O")
	}

	/* R = P + P */
	{
		PP := Point{hex2int("5dbcd5dfea550eb4fd3b5333f533f086bb5267c776e2a1a9d8e84c16a6743d82"), hex2int("8dde3986b6cbe395da64b6e95fb81f8af73f6e0cf1100555005bb4ba2a6a4a07")}

		R := curve.Add(P, P)
		if R.X.Cmp(PP.X) != 0 || R.Y.Cmp(PP.Y) != 0 {
			t.Fatal("failure P + P")
		}
		t.Log("success P + P")
	}

	Q := Point{hex2int("a83b8de893467d3a88d959c0eb4032d9ce3bf80f175d4d9e75892a3ebb8ab7e5"), hex2int("370f723328c24b7a97fe34063ba68f253fb08f8645d7c8b9a4ff98e3c29e7f0d")}
	PQ := Point{hex2int("fe7d540002e4355eb0ec36c217b4735495de7bd8634055ded3683b0e9da70ef1"), hex2int("fc033c1d74cb34e087a3495e505c0fc0e9e3e8297994878d89d882254ce8a9ef")}

	/* R = P + Q */
	{
		R := curve.Add(P, Q)
		if R.X.Cmp(PQ.X) != 0 || R.Y.Cmp(PQ.Y) != 0 {
			t.Fatal("failure P + Q")
		}
		t.Log("success P + Q")
	}

	/* R = Q + P */
	{
		R := curve.Add(Q, P)
		if R.X.Cmp(PQ.X) != 0 || R.Y.Cmp(PQ.Y) != 0 {
			t.Fatal("failure Q + P")
		}
		t.Log("success Q + P")
	}
}

func TestPointScalarMult(t *testing.T) {
	X := "50863ad64a87ae8a2fe83c1af1a8403cb53f53e486d8511dad8a04887e5b2352"
	Y := "2cd470243453a299fa9e77237716103abc11a1df38855ed6f2ee187e9c582ba6"
	P := Point{hex2int(X), hex2int(Y)}

	/* Q = k*P */
	{
		T := Point{hex2int("87d592bfdd24adb52147fea343db93e10d0585bc66d91e365c359973c0dc7067"), hex2int("a374e206cb7c8cd1074bdf9bf6ddea135f983aaa6475c9ab3bb4c38a0046541b")}
		Q := curve.ScalarMult(hex2int("14eb373700c3836404acd0820d9fa8dfa098d26177ca6e18b1c7f70c6af8fc18"), P)
		if Q.X.Cmp(T.X) != 0 || Q.Y.Cmp(T.Y) != 0 {
			t.Fatal("failure k*P")
		}
		t.Log("success k*P")
	}

	/* Q = n*G = O */
	{
		Q := curve.ScalarMult(curve.N, curve.G)
		if !curve.IsInfinity(Q) {
			t.Fatal("failure n*G = O")
		}
		t.Log("success n*G = O")
	}
}

func TestPointScalarBaseMult(t *testing.T) {
	/* Sample Private Key */
	D := "18e14a7b6a307f426a94f8114701e7c8e774e7f9a47e2c2035db29a206321725"
	/* Sample Corresponding Public Key */
	X := "50863ad64a87ae8a2fe83c1af1a8403cb53f53e486d8511dad8a04887e5b2352"
	Y := "2cd470243453a299fa9e77237716103abc11a1df38855ed6f2ee187e9c582ba6"

	P := Point{hex2int(X), hex2int(Y)}

	/* Q = d*G = P */
	Q := curve.ScalarBaseMult(hex2int(D))
	if P.X.Cmp(Q.X) != 0 || P.Y.Cmp(Q.Y) != 0 {
		t.Fatal("failure Q = d*G")
	}
	t.Log("success Q = d*G")

	/* Q on curve */
	if !curve.IsOnCurve(Q) {
		t.Fatal("failure Q on curve")
	}
	t.Log("success Q on curve")

	/* R = 0*G = O */
	R := curve.ScalarBaseMult(big.NewInt(0))
	if !curve.IsInfinity(R) {
		t.Fatal("failure 0*G = O")
	}
	t.Log("success 0*G = O")
}

func TestPointDecompress(t *testing.T) {
	/* Valid points */
	var validDecompressVectors = []Point{
		{hex2int("50863ad64a87ae8a2fe83c1af1a8403cb53f53e486d8511dad8a04887e5b2352"), hex2int("2cd470243453a299fa9e77237716103abc11a1df38855ed6f2ee187e9c582ba6")},
		{hex2int("a83b8de893467d3a88d959c0eb4032d9ce3bf80f175d4d9e75892a3ebb8ab7e5"), hex2int("370f723328c24b7a97fe34063ba68f253fb08f8645d7c8b9a4ff98e3c29e7f0d")},
		{hex2int("f680556678e25084a82fa39e1b1dfd0944f7e69fddaa4e03ce934bd6b291dca0"), hex2int("52c10b721d34447e173721fb0151c68de1106badb089fb661523b8302a9097f5")},
		{hex2int("241febb8e23cbd77d664a18f66ad6240aaec6ecdc813b088d5b901b2e285131f"), hex2int("513378d9ff94f8d3d6c420bd13981df8cd50fd0fbd0cb5afabb3e66f2750026d")},
	}

	for i := 0; i < len(validDecompressVectors); i++ {
		P, err := curve.Decompress(validDecompressVectors[i].X, validDecompressVectors[i].Y.Bit(0))
		if err != nil {
			t.Fatalf("failure decompress P, got error %v on index %d", err, i)
		}
		if P.X.Cmp(validDecompressVectors[i].X) != 0 || P.Y.Cmp(validDecompressVectors[i].Y) != 0 {
			t.Fatalf("failure decompress P, got mismatch on index", i)
		}
	}
	t.Log("success Decompress() on valid vectors")

	/* Invalid points */
	var invalidDecompressVectors = []struct {
		X    *big.Int
		YLsb uint
	}{
		{hex2int("c8e337cee51ae9af3c0ef923705a0cb1b76f7e8463b3d3060a1c8d795f9630fd"), 0},
		{hex2int("c8e337cee51ae9af3c0ef923705a0cb1b76f7e8463b3d3060a1c8d795f9630fd"), 1},
	}

	for i := 0; i < len(invalidDecompressVectors); i++ {
		_, err := curve.Decompress(invalidDecompressVectors[i].X, invalidDecompressVectors[i].YLsb)
		if err == nil {
			t.Fatalf("failure decompress invalid P, got decompressed point on index %d", i)
		}
	}
	t.Log("success Decompress() on invalid vectors")
}
<commit_msg>add missing format specifier to Fatalf() in elliptic tests<commit_after>/* btckeygenie v1.0.0
 * https://github.com/vsergeev/btckeygenie
 * License: MIT
 */

package btckey

import (
	"math/big"
	"testing"
)

var curve EllipticCurve

func init() {
	/* See SEC2 pg.9 http://www.secg.org/collateral/sec2_final.pdf */
	/* secp256k1 elliptic curve parameters */
	curve.P, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F", 16)
	curve.A, _ = new(big.Int).SetString("0000000000000000000000000000000000000000000000000000000000000000", 16)
	curve.B, _ = new(big.Int).SetString("0000000000000000000000000000000000000000000000000000000000000007", 16)
	curve.G.X, _ = new(big.Int).SetString("79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798", 16)
	curve.G.Y, _ = new(big.Int).SetString("483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8", 16)
	curve.N, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141", 16)
	curve.H, _ = new(big.Int).SetString("01", 16)
}

func hex2int(hexstring string) (v *big.Int) {
	v, _ = new(big.Int).SetString(hexstring, 16)
	return v
}

func TestOnCurve(t *testing.T) {
	if !curve.IsOnCurve(curve.G) {
		t.Fatal("failure G on curve")
	}

	t.Log("G on curve")
}

func TestInfinity(t *testing.T) {
	O := Point{nil, nil}

	/* O not on curve */
	if curve.IsOnCurve(O) {
		t.Fatal("failure O on curve")
	}

	/* O is infinity */
	if !curve.IsInfinity(O) {
		t.Fatal("failure O not infinity on curve")
	}

	t.Log("O is not on curve and is infinity")
}

func TestPointAdd(t *testing.T) {
	X := "50863ad64a87ae8a2fe83c1af1a8403cb53f53e486d8511dad8a04887e5b2352"
	Y := "2cd470243453a299fa9e77237716103abc11a1df38855ed6f2ee187e9c582ba6"

	P := Point{hex2int(X), hex2int(Y)}
	O := Point{nil, nil}

	/* R = O + O = O */
	{
		R := curve.Add(O, O)
		if !curve.IsInfinity(R) {
			t.Fatal("failure O + O = O")
		}
		t.Log("success O + O = O")
	}

	/* R = P + O = P */
	{
		R := curve.Add(P, O)
		if R.X.Cmp(P.X) != 0 || R.Y.Cmp(P.Y) != 0 {
			t.Fatal("failure P + O = P")
		}
		t.Log("success P + O = P")
	}

	/* R = O + Q = Q */
	{
		R := curve.Add(O, P)
		if R.X.Cmp(P.X) != 0 || R.Y.Cmp(P.Y) != 0 {
			t.Fatal("failure O + Q = Q")
		}
		t.Log("success O + Q = Q")
	}

	/* R = (x,y) + (x,-y) = O */
	{
		Q := Point{P.X, subMod(big.NewInt(0), P.Y, curve.P)}

		R := curve.Add(P, Q)
		if !curve.IsInfinity(R) {
			t.Fatal("failure (x,y) + (x,-y) = O")
		}
		t.Log("success (x,y) + (x,-y) = O")
	}

	/* R = P + P */
	{
		PP := Point{hex2int("5dbcd5dfea550eb4fd3b5333f533f086bb5267c776e2a1a9d8e84c16a6743d82"), hex2int("8dde3986b6cbe395da64b6e95fb81f8af73f6e0cf1100555005bb4ba2a6a4a07")}

		R := curve.Add(P, P)
		if R.X.Cmp(PP.X) != 0 || R.Y.Cmp(PP.Y) != 0 {
			t.Fatal("failure P + P")
		}
		t.Log("success P + P")
	}

	Q := Point{hex2int("a83b8de893467d3a88d959c0eb4032d9ce3bf80f175d4d9e75892a3ebb8ab7e5"), hex2int("370f723328c24b7a97fe34063ba68f253fb08f8645d7c8b9a4ff98e3c29e7f0d")}
	PQ := Point{hex2int("fe7d540002e4355eb0ec36c217b4735495de7bd8634055ded3683b0e9da70ef1"), hex2int("fc033c1d74cb34e087a3495e505c0fc0e9e3e8297994878d89d882254ce8a9ef")}

	/* R = P + Q */
	{
		R := curve.Add(P, Q)
		if R.X.Cmp(PQ.X) != 0 || R.Y.Cmp(PQ.Y) != 0 {
			t.Fatal("failure P + Q")
		}
		t.Log("success P + Q")
	}

	/* R = Q + P */
	{
		R := curve.Add(Q, P)
		if R.X.Cmp(PQ.X) != 0 || R.Y.Cmp(PQ.Y) != 0 {
			t.Fatal("failure Q + P")
		}
		t.Log("success Q + P")
	}
}

func TestPointScalarMult(t *testing.T) {
	X := "50863ad64a87ae8a2fe83c1af1a8403cb53f53e486d8511dad8a04887e5b2352"
	Y := "2cd470243453a299fa9e77237716103abc11a1df38855ed6f2ee187e9c582ba6"
	P := Point{hex2int(X), hex2int(Y)}

	/* Q = k*P */
	{
		T := Point{hex2int("87d592bfdd24adb52147fea343db93e10d0585bc66d91e365c359973c0dc7067"), hex2int("a374e206cb7c8cd1074bdf9bf6ddea135f983aaa6475c9ab3bb4c38a0046541b")}
		Q := curve.ScalarMult(hex2int("14eb373700c3836404acd0820d9fa8dfa098d26177ca6e18b1c7f70c6af8fc18"), P)
		if Q.X.Cmp(T.X) != 0 || Q.Y.Cmp(T.Y) != 0 {
			t.Fatal("failure k*P")
		}
		t.Log("success k*P")
	}

	/* Q = n*G = O */
	{
		Q := curve.ScalarMult(curve.N, curve.G)
		if !curve.IsInfinity(Q) {
			t.Fatal("failure n*G = O")
		}
		t.Log("success n*G = O")
	}
}

func TestPointScalarBaseMult(t *testing.T) {
	/* Sample Private Key */
	D := "18e14a7b6a307f426a94f8114701e7c8e774e7f9a47e2c2035db29a206321725"
	/* Sample Corresponding Public Key */
	X := "50863ad64a87ae8a2fe83c1af1a8403cb53f53e486d8511dad8a04887e5b2352"
	Y := "2cd470243453a299fa9e77237716103abc11a1df38855ed6f2ee187e9c582ba6"

	P := Point{hex2int(X), hex2int(Y)}

	/* Q = d*G = P */
	Q := curve.ScalarBaseMult(hex2int(D))
	if P.X.Cmp(Q.X) != 0 || P.Y.Cmp(Q.Y) != 0 {
		t.Fatal("failure Q = d*G")
	}
	t.Log("success Q = d*G")

	/* Q on curve */
	if !curve.IsOnCurve(Q) {
		t.Fatal("failure Q on curve")
	}
	t.Log("success Q on curve")

	/* R = 0*G = O */
	R := curve.ScalarBaseMult(big.NewInt(0))
	if !curve.IsInfinity(R) {
		t.Fatal("failure 0*G = O")
	}
	t.Log("success 0*G = O")
}

func TestPointDecompress(t *testing.T) {
	/* Valid points */
	var validDecompressVectors = []Point{
		{hex2int("50863ad64a87ae8a2fe83c1af1a8403cb53f53e486d8511dad8a04887e5b2352"), hex2int("2cd470243453a299fa9e77237716103abc11a1df38855ed6f2ee187e9c582ba6")},
		{hex2int("a83b8de893467d3a88d959c0eb4032d9ce3bf80f175d4d9e75892a3ebb8ab7e5"), hex2int("370f723328c24b7a97fe34063ba68f253fb08f8645d7c8b9a4ff98e3c29e7f0d")},
		{hex2int("f680556678e25084a82fa39e1b1dfd0944f7e69fddaa4e03ce934bd6b291dca0"), hex2int("52c10b721d34447e173721fb0151c68de1106badb089fb661523b8302a9097f5")},
		{hex2int("241febb8e23cbd77d664a18f66ad6240aaec6ecdc813b088d5b901b2e285131f"), hex2int("513378d9ff94f8d3d6c420bd13981df8cd50fd0fbd0cb5afabb3e66f2750026d")},
	}

	for i := 0; i < len(validDecompressVectors); i++ {
		P, err := curve.Decompress(validDecompressVectors[i].X, validDecompressVectors[i].Y.Bit(0))
		if err != nil {
			t.Fatalf("failure decompress P, got error %v on index %d", err, i)
		}
		if P.X.Cmp(validDecompressVectors[i].X) != 0 || P.Y.Cmp(validDecompressVectors[i].Y) != 0 {
			t.Fatalf("failure decompress P, got mismatch on index %d", i)
		}
	}
	t.Log("success Decompress() on valid vectors")

	/* Invalid points */
	var invalidDecompressVectors = []struct {
		X    *big.Int
		YLsb uint
	}{
		{hex2int("c8e337cee51ae9af3c0ef923705a0cb1b76f7e8463b3d3060a1c8d795f9630fd"), 0},
		{hex2int("c8e337cee51ae9af3c0ef923705a0cb1b76f7e8463b3d3060a1c8d795f9630fd"), 1},
	}

	for i := 0; i < len(invalidDecompressVectors); i++ {
		_, err := curve.Decompress(invalidDecompressVectors[i].X, invalidDecompressVectors[i].YLsb)
		if err == nil {
			t.Fatalf("failure decompress invalid P, got decompressed point on index %d", i)
		}
	}
	t.Log("success Decompress() on invalid vectors")
}
<|endoftext|>


<commit_before>/* gobtcaddr v1.0
 * vsergeev
 * https://github.com/vsergeev/gobtcaddr
 * MIT Licensed
 */

package btckey

import (
	"math/big"
	"testing"
)

var curve EllipticCurve

func init() {
	/* See SEC2 pg.9 http://www.secg.org/collateral/sec2_final.pdf */
	/* secp256k1 elliptic curve parameters */
	curve.P, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F", 16)
	curve.A, _ = new(big.Int).SetString("0000000000000000000000000000000000000000000000000000000000000000", 16)
	curve.B, _ = new(big.Int).SetString("0000000000000000000000000000000000000000000000000000000000000007", 16)
	curve.G.X, _ = new(big.Int).SetString("79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798", 16)
	curve.G.Y, _ = new(big.Int).SetString("483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8", 16)
	curve.N, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141", 16)
	curve.H, _ = new(big.Int).SetString("01", 16)
}

func hex2int(hexstring string) (v *big.Int) {
	v, _ = new(big.Int).SetString(hexstring, 16)
	return v
}

func TestOnCurve(t *testing.T) {
	if !curve.IsOnCurve(curve.G) {
		t.Fatal("failure G on curve")
	}

	t.Log("G on curve")
}

func TestInfinity(t *testing.T) {
	O := Point{nil, nil}

	/* O not on curve */
	if curve.IsOnCurve(O) {
		t.Fatal("failure O on curve")
	}

	/* O is infinity */
	if !curve.IsInfinity(O) {
		t.Fatal("failure O not infinity on curve")
	}

	t.Log("O is not on curve and is infinity")
}

func TestPointAdd(t *testing.T) {
	X := "50863ad64a87ae8a2fe83c1af1a8403cb53f53e486d8511dad8a04887e5b2352"
	Y := "2cd470243453a299fa9e77237716103abc11a1df38855ed6f2ee187e9c582ba6"

	P := Point{hex2int(X), hex2int(Y)}
	O := Point{nil, nil}

	/* R = O + O = O */
	{
		R := curve.Add(O, O)
		if !curve.IsInfinity(R) {
			t.Fatal("failure O + O = O")
		}
		t.Log("success O + O = O")
	}

	/* R = P + O = P */
	{
		R := curve.Add(P, O)
		if R.X.Cmp(P.X) != 0 || R.Y.Cmp(P.Y) != 0 {
			t.Fatal("failure P + O = P")
		}
		t.Log("success P + O = P")
	}

	/* R = O + Q = Q */
	{
		R := curve.Add(O, P)
		if R.X.Cmp(P.X) != 0 || R.Y.Cmp(P.Y) != 0 {
			t.Fatal("failure O + Q = Q")
		}
		t.Log("success O + Q = Q")
	}

	/* R = (x,y) + (x,-y) = O */
	{
		Q := Point{P.X, subMod(big.NewInt(0), P.Y, curve.P)}

		R := curve.Add(P, Q)
		if !curve.IsInfinity(R) {
			t.Fatal("failure (x,y) + (x,-y) = O")
		}
		t.Log("success (x,y) + (x,-y) = O")
	}

	/* R = P + P */
	{
		PP := Point{hex2int("5dbcd5dfea550eb4fd3b5333f533f086bb5267c776e2a1a9d8e84c16a6743d82"), hex2int("8dde3986b6cbe395da64b6e95fb81f8af73f6e0cf1100555005bb4ba2a6a4a07")}

		R := curve.Add(P, P)
		if R.X.Cmp(PP.X) != 0 || R.Y.Cmp(PP.Y) != 0 {
			t.Fatal("failure P + P")
		}
		t.Log("success P + P")
	}

	Q := Point{hex2int("a83b8de893467d3a88d959c0eb4032d9ce3bf80f175d4d9e75892a3ebb8ab7e5"), hex2int("370f723328c24b7a97fe34063ba68f253fb08f8645d7c8b9a4ff98e3c29e7f0d")}
	PQ := Point{hex2int("fe7d540002e4355eb0ec36c217b4735495de7bd8634055ded3683b0e9da70ef1"), hex2int("fc033c1d74cb34e087a3495e505c0fc0e9e3e8297994878d89d882254ce8a9ef")}

	/* R = P + Q */
	{
		R := curve.Add(P, Q)
		if R.X.Cmp(PQ.X) != 0 || R.Y.Cmp(PQ.Y) != 0 {
			t.Fatal("failure P + Q")
		}
		t.Log("success P + Q")
	}

	/* R = Q + P */
	{
		R := curve.Add(Q, P)
		if R.X.Cmp(PQ.X) != 0 || R.Y.Cmp(PQ.Y) != 0 {
			t.Fatal("failure Q + P")
		}
		t.Log("success Q + P")
	}
}

func TestPointScalarMult(t *testing.T) {
	X := "50863ad64a87ae8a2fe83c1af1a8403cb53f53e486d8511dad8a04887e5b2352"
	Y := "2cd470243453a299fa9e77237716103abc11a1df38855ed6f2ee187e9c582ba6"
	P := Point{hex2int(X), hex2int(Y)}

	/* Q = k*P */
	{
		T := Point{hex2int("87d592bfdd24adb52147fea343db93e10d0585bc66d91e365c359973c0dc7067"), hex2int("a374e206cb7c8cd1074bdf9bf6ddea135f983aaa6475c9ab3bb4c38a0046541b")}
		Q := curve.ScalarMult(hex2int("14eb373700c3836404acd0820d9fa8dfa098d26177ca6e18b1c7f70c6af8fc18"), P)
		if Q.X.Cmp(T.X) != 0 || Q.Y.Cmp(T.Y) != 0 {
			t.Fatal("failure k*P")
		}
		t.Log("success k*P")
	}

	/* Q = n*G = O */
	{
		Q := curve.ScalarMult(curve.N, curve.G)
		if !curve.IsInfinity(Q) {
			t.Fatal("failure n*G = O")
		}
		t.Log("success n*G = O")
	}
}

func TestPointScalarBaseMult(t *testing.T) {
	/* Sample Private Key */
	D := "18e14a7b6a307f426a94f8114701e7c8e774e7f9a47e2c2035db29a206321725"
	/* Sample Corresponding Public Key */
	X := "50863ad64a87ae8a2fe83c1af1a8403cb53f53e486d8511dad8a04887e5b2352"
	Y := "2cd470243453a299fa9e77237716103abc11a1df38855ed6f2ee187e9c582ba6"

	P := Point{hex2int(X), hex2int(Y)}

	/* Q = d*G = P */
	Q := curve.ScalarBaseMult(hex2int(D))
	if P.X.Cmp(Q.X) != 0 || P.Y.Cmp(Q.Y) != 0 {
		t.Fatal("failure Q = d*G")
	}
	t.Log("success Q = d*G")

	/* Q on curve */
	if !curve.IsOnCurve(Q) {
		t.Fatal("failure Q on curve")
	}
	t.Log("success Q on curve")
}

func TestPointDecompress(t *testing.T) {
	/* Valid points */
	var validDecompressVectors = []Point{
		{hex2int("50863ad64a87ae8a2fe83c1af1a8403cb53f53e486d8511dad8a04887e5b2352"), hex2int("2cd470243453a299fa9e77237716103abc11a1df38855ed6f2ee187e9c582ba6")},
		{hex2int("a83b8de893467d3a88d959c0eb4032d9ce3bf80f175d4d9e75892a3ebb8ab7e5"), hex2int("370f723328c24b7a97fe34063ba68f253fb08f8645d7c8b9a4ff98e3c29e7f0d")},
		{hex2int("f680556678e25084a82fa39e1b1dfd0944f7e69fddaa4e03ce934bd6b291dca0"), hex2int("52c10b721d34447e173721fb0151c68de1106badb089fb661523b8302a9097f5")},
		{hex2int("241febb8e23cbd77d664a18f66ad6240aaec6ecdc813b088d5b901b2e285131f"), hex2int("513378d9ff94f8d3d6c420bd13981df8cd50fd0fbd0cb5afabb3e66f2750026d")},
	}

	for i := 0; i < len(validDecompressVectors); i++ {
		P, err := curve.Decompress(validDecompressVectors[i].X, validDecompressVectors[i].Y.Bit(0))
		if err != nil {
			t.Fatalf("failure decompress P, got error %v on index %d", err, i)
		}
		if P.X.Cmp(validDecompressVectors[i].X) != 0 || P.Y.Cmp(validDecompressVectors[i].Y) != 0 {
			t.Fatalf("failure decompress P, got mismatch on index", i)
		}
	}
	t.Log("success Decompress() on valid vectors")

	/* Invalid points */
	var invalidDecompressVectors = []struct {
		X    *big.Int
		YLsb uint
	}{
		{hex2int("c8e337cee51ae9af3c0ef923705a0cb1b76f7e8463b3d3060a1c8d795f9630fd"), 0},
		{hex2int("c8e337cee51ae9af3c0ef923705a0cb1b76f7e8463b3d3060a1c8d795f9630fd"), 1},
	}

	for i := 0; i < len(invalidDecompressVectors); i++ {
		_, err := curve.Decompress(invalidDecompressVectors[i].X, invalidDecompressVectors[i].YLsb)
		if err == nil {
			t.Fatalf("failure decompress invalid P, got decompressed point on index %d", i)
		}
	}
	t.Log("success Decompress() on invalid vectors")
}
<commit_msg>add additional test case to elliptic tests<commit_after>/* gobtcaddr v1.0
 * vsergeev
 * https://github.com/vsergeev/gobtcaddr
 * MIT Licensed
 */

package btckey

import (
	"math/big"
	"testing"
)

var curve EllipticCurve

func init() {
	/* See SEC2 pg.9 http://www.secg.org/collateral/sec2_final.pdf */
	/* secp256k1 elliptic curve parameters */
	curve.P, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F", 16)
	curve.A, _ = new(big.Int).SetString("0000000000000000000000000000000000000000000000000000000000000000", 16)
	curve.B, _ = new(big.Int).SetString("0000000000000000000000000000000000000000000000000000000000000007", 16)
	curve.G.X, _ = new(big.Int).SetString("79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798", 16)
	curve.G.Y, _ = new(big.Int).SetString("483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8", 16)
	curve.N, _ = new(big.Int).SetString("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141", 16)
	curve.H, _ = new(big.Int).SetString("01", 16)
}

func hex2int(hexstring string) (v *big.Int) {
	v, _ = new(big.Int).SetString(hexstring, 16)
	return v
}

func TestOnCurve(t *testing.T) {
	if !curve.IsOnCurve(curve.G) {
		t.Fatal("failure G on curve")
	}

	t.Log("G on curve")
}

func TestInfinity(t *testing.T) {
	O := Point{nil, nil}

	/* O not on curve */
	if curve.IsOnCurve(O) {
		t.Fatal("failure O on curve")
	}

	/* O is infinity */
	if !curve.IsInfinity(O) {
		t.Fatal("failure O not infinity on curve")
	}

	t.Log("O is not on curve and is infinity")
}

func TestPointAdd(t *testing.T) {
	X := "50863ad64a87ae8a2fe83c1af1a8403cb53f53e486d8511dad8a04887e5b2352"
	Y := "2cd470243453a299fa9e77237716103abc11a1df38855ed6f2ee187e9c582ba6"

	P := Point{hex2int(X), hex2int(Y)}
	O := Point{nil, nil}

	/* R = O + O = O */
	{
		R := curve.Add(O, O)
		if !curve.IsInfinity(R) {
			t.Fatal("failure O + O = O")
		}
		t.Log("success O + O = O")
	}

	/* R = P + O = P */
	{
		R := curve.Add(P, O)
		if R.X.Cmp(P.X) != 0 || R.Y.Cmp(P.Y) != 0 {
			t.Fatal("failure P + O = P")
		}
		t.Log("success P + O = P")
	}

	/* R = O + Q = Q */
	{
		R := curve.Add(O, P)
		if R.X.Cmp(P.X) != 0 || R.Y.Cmp(P.Y) != 0 {
			t.Fatal("failure O + Q = Q")
		}
		t.Log("success O + Q = Q")
	}

	/* R = (x,y) + (x,-y) = O */
	{
		Q := Point{P.X, subMod(big.NewInt(0), P.Y, curve.P)}

		R := curve.Add(P, Q)
		if !curve.IsInfinity(R) {
			t.Fatal("failure (x,y) + (x,-y) = O")
		}
		t.Log("success (x,y) + (x,-y) = O")
	}

	/* R = P + P */
	{
		PP := Point{hex2int("5dbcd5dfea550eb4fd3b5333f533f086bb5267c776e2a1a9d8e84c16a6743d82"), hex2int("8dde3986b6cbe395da64b6e95fb81f8af73f6e0cf1100555005bb4ba2a6a4a07")}

		R := curve.Add(P, P)
		if R.X.Cmp(PP.X) != 0 || R.Y.Cmp(PP.Y) != 0 {
			t.Fatal("failure P + P")
		}
		t.Log("success P + P")
	}

	Q := Point{hex2int("a83b8de893467d3a88d959c0eb4032d9ce3bf80f175d4d9e75892a3ebb8ab7e5"), hex2int("370f723328c24b7a97fe34063ba68f253fb08f8645d7c8b9a4ff98e3c29e7f0d")}
	PQ := Point{hex2int("fe7d540002e4355eb0ec36c217b4735495de7bd8634055ded3683b0e9da70ef1"), hex2int("fc033c1d74cb34e087a3495e505c0fc0e9e3e8297994878d89d882254ce8a9ef")}

	/* R = P + Q */
	{
		R := curve.Add(P, Q)
		if R.X.Cmp(PQ.X) != 0 || R.Y.Cmp(PQ.Y) != 0 {
			t.Fatal("failure P + Q")
		}
		t.Log("success P + Q")
	}

	/* R = Q + P */
	{
		R := curve.Add(Q, P)
		if R.X.Cmp(PQ.X) != 0 || R.Y.Cmp(PQ.Y) != 0 {
			t.Fatal("failure Q + P")
		}
		t.Log("success Q + P")
	}
}

func TestPointScalarMult(t *testing.T) {
	X := "50863ad64a87ae8a2fe83c1af1a8403cb53f53e486d8511dad8a04887e5b2352"
	Y := "2cd470243453a299fa9e77237716103abc11a1df38855ed6f2ee187e9c582ba6"
	P := Point{hex2int(X), hex2int(Y)}

	/* Q = k*P */
	{
		T := Point{hex2int("87d592bfdd24adb52147fea343db93e10d0585bc66d91e365c359973c0dc7067"), hex2int("a374e206cb7c8cd1074bdf9bf6ddea135f983aaa6475c9ab3bb4c38a0046541b")}
		Q := curve.ScalarMult(hex2int("14eb373700c3836404acd0820d9fa8dfa098d26177ca6e18b1c7f70c6af8fc18"), P)
		if Q.X.Cmp(T.X) != 0 || Q.Y.Cmp(T.Y) != 0 {
			t.Fatal("failure k*P")
		}
		t.Log("success k*P")
	}

	/* Q = n*G = O */
	{
		Q := curve.ScalarMult(curve.N, curve.G)
		if !curve.IsInfinity(Q) {
			t.Fatal("failure n*G = O")
		}
		t.Log("success n*G = O")
	}
}

func TestPointScalarBaseMult(t *testing.T) {
	/* Sample Private Key */
	D := "18e14a7b6a307f426a94f8114701e7c8e774e7f9a47e2c2035db29a206321725"
	/* Sample Corresponding Public Key */
	X := "50863ad64a87ae8a2fe83c1af1a8403cb53f53e486d8511dad8a04887e5b2352"
	Y := "2cd470243453a299fa9e77237716103abc11a1df38855ed6f2ee187e9c582ba6"

	P := Point{hex2int(X), hex2int(Y)}

	/* Q = d*G = P */
	Q := curve.ScalarBaseMult(hex2int(D))
	if P.X.Cmp(Q.X) != 0 || P.Y.Cmp(Q.Y) != 0 {
		t.Fatal("failure Q = d*G")
	}
	t.Log("success Q = d*G")

	/* Q on curve */
	if !curve.IsOnCurve(Q) {
		t.Fatal("failure Q on curve")
	}
	t.Log("success Q on curve")

    /* R = 0*G = O */
    R := curve.ScalarBaseMult(big.NewInt(0))
    if !curve.IsInfinity(R) {
        t.Fatal("failure 0*G = O")
    }
    t.Log("success 0*G = O")
}

func TestPointDecompress(t *testing.T) {
	/* Valid points */
	var validDecompressVectors = []Point{
		{hex2int("50863ad64a87ae8a2fe83c1af1a8403cb53f53e486d8511dad8a04887e5b2352"), hex2int("2cd470243453a299fa9e77237716103abc11a1df38855ed6f2ee187e9c582ba6")},
		{hex2int("a83b8de893467d3a88d959c0eb4032d9ce3bf80f175d4d9e75892a3ebb8ab7e5"), hex2int("370f723328c24b7a97fe34063ba68f253fb08f8645d7c8b9a4ff98e3c29e7f0d")},
		{hex2int("f680556678e25084a82fa39e1b1dfd0944f7e69fddaa4e03ce934bd6b291dca0"), hex2int("52c10b721d34447e173721fb0151c68de1106badb089fb661523b8302a9097f5")},
		{hex2int("241febb8e23cbd77d664a18f66ad6240aaec6ecdc813b088d5b901b2e285131f"), hex2int("513378d9ff94f8d3d6c420bd13981df8cd50fd0fbd0cb5afabb3e66f2750026d")},
	}

	for i := 0; i < len(validDecompressVectors); i++ {
		P, err := curve.Decompress(validDecompressVectors[i].X, validDecompressVectors[i].Y.Bit(0))
		if err != nil {
			t.Fatalf("failure decompress P, got error %v on index %d", err, i)
		}
		if P.X.Cmp(validDecompressVectors[i].X) != 0 || P.Y.Cmp(validDecompressVectors[i].Y) != 0 {
			t.Fatalf("failure decompress P, got mismatch on index", i)
		}
	}
	t.Log("success Decompress() on valid vectors")

	/* Invalid points */
	var invalidDecompressVectors = []struct {
		X    *big.Int
		YLsb uint
	}{
		{hex2int("c8e337cee51ae9af3c0ef923705a0cb1b76f7e8463b3d3060a1c8d795f9630fd"), 0},
		{hex2int("c8e337cee51ae9af3c0ef923705a0cb1b76f7e8463b3d3060a1c8d795f9630fd"), 1},
	}

	for i := 0; i < len(invalidDecompressVectors); i++ {
		_, err := curve.Decompress(invalidDecompressVectors[i].X, invalidDecompressVectors[i].YLsb)
		if err == nil {
			t.Fatalf("failure decompress invalid P, got decompressed point on index %d", i)
		}
	}
	t.Log("success Decompress() on invalid vectors")
}
<|endoftext|>


<commit_before>// Copyright 2016 Google Inc. 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.

package version

var (
	// Major is the current major version of master branch..
	Major = 0
	// Minor is the current minor version of master branch.
	Minor = 1
	// Patch is the curernt patched version of the master branch.
	Patch = 0
	// Release is the current release level of the master branch. Valid values
	// are dev (developement unreleased), rcX (release candidate with current
	// iteration), stable (indicates a final released version).
	Release = "rc1"
)
<commit_msg>Cutting 0.1.0 RC2.<commit_after>// Copyright 2016 Google Inc. 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.

package version

var (
	// Major is the current major version of master branch..
	Major = 0
	// Minor is the current minor version of master branch.
	Minor = 1
	// Patch is the curernt patched version of the master branch.
	Patch = 0
	// Release is the current release level of the master branch. Valid values
	// are dev (developement unreleased), rcX (release candidate with current
	// iteration), stable (indicates a final released version).
	Release = "rc2"
)
<|endoftext|>


<commit_before>// Package rabbitmq provider support for RabbitMQ message broker.
package rabbitmq
<commit_msg>Fixing type in  RabbitMQ broker docs.<commit_after>// Package rabbitmq provides support for RabbitMQ message broker.
package rabbitmq
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"github.com/ryanbressler/CloudForest"
	"log"
	"os"
	"strings"
)

func main() {
	fm := flag.String("fm", "featurematrix.afm", "AFM formated feature matrix to use.")
	rf := flag.String("rfpred", "rface.sf", "A predictor forest.")
	outf := flag.String("leaves", "leaves.tsv", "a case by case sparse matrix of leaf co-occurrence in tsv format")
	boutf := flag.String("branches", "branches.tsv", "a case by feature sparse matrix of leaf co-occurrence in tsv format")

	flag.Parse()

	datafile, err := os.Open(*fm) // For read access.
	if err != nil {
		log.Fatal(err)
	}
	defer datafile.Close()
	data := CloudForest.ParseAFM(datafile)
	log.Print("Data file ", len(data.Data), " by ", data.Data[0].Length())

	counts := new(CloudForest.SparseCounter)
	caseFeatureCounts := new(CloudForest.SparseCounter)

	for _, fn := range strings.Split(*rf, ",") {

		forestfile, err := os.Open(fn) // For read access.
		if err != nil {
			log.Fatal(err)
		}
		defer forestfile.Close()
		forestreader := CloudForest.NewForestReader(forestfile)
		forest, err := forestreader.ReadForest()
		if err != nil {
			log.Fatal(err)
		}
		log.Print("Forest has ", len(forest.Trees), " trees ")

		counts := new(CloudForest.SparseCounter)
		caseFeatureCounts := new(CloudForest.SparseCounter)

		for i := 0; i < len(forest.Trees); i++ {
			leaves := forest.Trees[i].GetLeaves(data, caseFeatureCounts)
			for _, leaf := range leaves {
				for j := 0; j < len(leaf.Cases); j++ {
					for k := 0; k < len(leaf.Cases); k++ {

						counts.Add(leaf.Cases[j], leaf.Cases[k], 1)

					}
				}
			}

		}
	}

	log.Print("Outputting Case Case  Co-Occurrence Counts")
	outfile, err := os.Create(*outf) // For read access.
	if err != nil {
		log.Fatal(err)
	}
	defer outfile.Close()
	counts.WriteTsv(outfile)

	log.Print("Outputting Case Feature Co-Occurrence Counts")
	boutfile, err := os.Create(*boutf) // For read access.
	if err != nil {
		log.Fatal(err)
	}
	defer boutfile.Close()
	caseFeatureCounts.WriteTsv(boutfile)
}
<commit_msg>count in to the same sparse counter<commit_after>package main

import (
	"flag"
	"github.com/ryanbressler/CloudForest"
	"log"
	"os"
	"strings"
)

func main() {
	fm := flag.String("fm", "featurematrix.afm", "AFM formated feature matrix to use.")
	rf := flag.String("rfpred", "rface.sf", "A predictor forest.")
	outf := flag.String("leaves", "leaves.tsv", "a case by case sparse matrix of leaf co-occurrence in tsv format")
	boutf := flag.String("branches", "branches.tsv", "a case by feature sparse matrix of leaf co-occurrence in tsv format")

	flag.Parse()

	datafile, err := os.Open(*fm) // For read access.
	if err != nil {
		log.Fatal(err)
	}
	defer datafile.Close()
	data := CloudForest.ParseAFM(datafile)
	log.Print("Data file ", len(data.Data), " by ", data.Data[0].Length())

	counts := new(CloudForest.SparseCounter)
	caseFeatureCounts := new(CloudForest.SparseCounter)

	for _, fn := range strings.Split(*rf, ",") {

		forestfile, err := os.Open(fn) // For read access.
		if err != nil {
			log.Fatal(err)
		}
		defer forestfile.Close()
		forestreader := CloudForest.NewForestReader(forestfile)
		forest, err := forestreader.ReadForest()
		if err != nil {
			log.Fatal(err)
		}
		log.Print("Forest has ", len(forest.Trees), " trees ")

		for i := 0; i < len(forest.Trees); i++ {
			leaves := forest.Trees[i].GetLeaves(data, caseFeatureCounts)
			for _, leaf := range leaves {
				for j := 0; j < len(leaf.Cases); j++ {
					for k := 0; k < len(leaf.Cases); k++ {

						counts.Add(leaf.Cases[j], leaf.Cases[k], 1)

					}
				}
			}

		}
	}

	log.Print("Outputting Case Case  Co-Occurrence Counts")
	outfile, err := os.Create(*outf) // For read access.
	if err != nil {
		log.Fatal(err)
	}
	defer outfile.Close()
	counts.WriteTsv(outfile)

	log.Print("Outputting Case Feature Co-Occurrence Counts")
	boutfile, err := os.Create(*boutf) // For read access.
	if err != nil {
		log.Fatal(err)
	}
	defer boutfile.Close()
	caseFeatureCounts.WriteTsv(boutfile)
}
<|endoftext|>


<commit_before>package main

import (
	"github.com/pkg/errors"
	"golang.org/x/crypto/ssh"
	"io"
	"io/ioutil"
	"net"
	"sync"
)

type Bastion struct {
	BastionConfig
	*ssh.Client
	wg    *sync.WaitGroup
	errch chan error
}

func (b *Bastion) Forward(t Tunnel) {
	defer b.wg.Done()
	laddr := net.JoinHostPort(t.LocalHost, t.LocalPort)
	raddr := net.JoinHostPort(t.RemoteHost, t.RemotePort)
	server, err := net.Listen("tcp", laddr)
	if err != nil {
		b.errch <- err
		return
	}
	defer server.Close()
	if t.callback != nil {
		t.callback(server.Addr())
	}

	for {
		lc, err := server.Accept()
		if err != nil {
			b.errch <- err
			continue
		}
		defer lc.Close()

		rc, err := b.Dial("tcp", raddr)
		if err != nil {
			b.errch <- err
			continue
		}
		defer rc.Close()
		go transfer(rc, lc, "remote -> local:", b.errch)
		go transfer(lc, rc, "local -> remote:", b.errch)
	}
}

func (b *Bastion) Up() {
	go handleError(b.errch)
	for _, t := range b.Tunnels {
		b.wg.Add(1)
		go b.Forward(t)
	}
	for _, c := range b.Cascades {
		ch := make(chan net.Addr)
		t := Tunnel{"0.0.0.0", "0", c.Host, c.Port, func(addr net.Addr) { ch <- addr }}
		b.wg.Add(1)
		go b.Forward(t)
		var err error
		c.Host, c.Port, err = net.SplitHostPort((<-ch).String())
		if err != nil {
			b.errch <- err
			continue
		}
		b.wg.Add(1)
		go start(c, b.wg, b.errch)
	}
	b.wg.Wait()
}

func NewBastion(config BastionConfig, errch chan error) (*Bastion, error) {
	signer, err := newSignerFromPath(config.CertPath)
	if err != nil {
		return nil, err
	}
	cc := &ssh.ClientConfig{
		User:            config.User,
		Auth:            []ssh.AuthMethod{ssh.PublicKeys(signer)},
		HostKeyCallback: ssh.InsecureIgnoreHostKey(),
	}
	c, err := ssh.Dial("tcp", config.Host, cc)
	if err != nil {
		return nil, err
	}
	return &Bastion{config, c, new(sync.WaitGroup), errch}, nil
}

func newSignerFromPath(path string) (ssh.Signer, error) {
	privkey, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	}

	return ssh.ParsePrivateKey(privkey)
}

func transfer(src, dst net.Conn, label string, errch chan error) {
	_, err := io.Copy(dst, src)
	if err != nil {
		err = errors.Wrap(err, label+err.Error())
		errch <- err
	}
}
<commit_msg>fix to join host and port on starting<commit_after>package main

import (
	"github.com/pkg/errors"
	"golang.org/x/crypto/ssh"
	"io"
	"io/ioutil"
	"net"
	"sync"
)

type Bastion struct {
	BastionConfig
	*ssh.Client
	wg    *sync.WaitGroup
	errch chan error
}

func (b *Bastion) Forward(t Tunnel) {
	defer b.wg.Done()
	laddr := net.JoinHostPort(t.LocalHost, t.LocalPort)
	raddr := net.JoinHostPort(t.RemoteHost, t.RemotePort)
	server, err := net.Listen("tcp", laddr)
	if err != nil {
		b.errch <- err
		return
	}
	defer server.Close()
	if t.callback != nil {
		t.callback(server.Addr())
	}

	for {
		lc, err := server.Accept()
		if err != nil {
			b.errch <- err
			continue
		}
		defer lc.Close()

		rc, err := b.Dial("tcp", raddr)
		if err != nil {
			b.errch <- err
			continue
		}
		defer rc.Close()
		go transfer(rc, lc, "remote -> local:", b.errch)
		go transfer(lc, rc, "local -> remote:", b.errch)
	}
}

func (b *Bastion) Up() {
	go handleError(b.errch)
	for _, t := range b.Tunnels {
		b.wg.Add(1)
		go b.Forward(t)
	}
	for _, c := range b.Cascades {
		ch := make(chan net.Addr)
		t := Tunnel{"0.0.0.0", "0", c.Host, c.Port, func(addr net.Addr) { ch <- addr }}
		b.wg.Add(1)
		go b.Forward(t)
		var err error
		c.Host, c.Port, err = net.SplitHostPort((<-ch).String())
		if err != nil {
			b.errch <- err
			continue
		}
		b.wg.Add(1)
		go start(c, b.wg, b.errch)
	}
	b.wg.Wait()
}

func NewBastion(config BastionConfig, errch chan error) (*Bastion, error) {
	signer, err := newSignerFromPath(config.CertPath)
	if err != nil {
		return nil, err
	}
	cc := &ssh.ClientConfig{
		User:            config.User,
		Auth:            []ssh.AuthMethod{ssh.PublicKeys(signer)},
		HostKeyCallback: ssh.InsecureIgnoreHostKey(),
	}
	addr := net.JoinHostPort(config.Host, config.Port)
	c, err := ssh.Dial("tcp", addr, cc)
	if err != nil {
		return nil, err
	}
	return &Bastion{config, c, new(sync.WaitGroup), errch}, nil
}

func newSignerFromPath(path string) (ssh.Signer, error) {
	privkey, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	}

	return ssh.ParsePrivateKey(privkey)
}

func transfer(src, dst net.Conn, label string, errch chan error) {
	_, err := io.Copy(dst, src)
	if err != nil {
		err = errors.Wrap(err, label+err.Error())
		errch <- err
	}
}
<|endoftext|>


<commit_before>// Package bcryptx ....
package bcryptx

import (
	"errors"
	"sync"
	"time"

	"golang.org/x/crypto/bcrypt"
)

const (
	// GenQuickMaxTime is the default max time used for tuning Bcrypter.quickCost.
	GenQuickMaxTime = time.Millisecond * 500
	// GenStrongMaxTime is the default max time used for tuning Bcrypter.strongCost.
	GenStrongMaxTime = time.Millisecond * 2000
	// GenConcurrency is the default concurrency value used for Gen*FromPass.
	GenConcurrency = 2

	minCost    = bcrypt.MinCost
	maxCost    = bcrypt.MaxCost
	interpTime = time.Millisecond * 50
	testStr    = "#!PnutBudr"
)

var (
	// ErrLowCost is returned by failed IsCost* functions.
	ErrLowCost = errors.New("Hash cost lower than currently configured cost.")
)

// Options holds values to be passed to New.
type Options struct {
	GenQuickMaxTime  time.Duration
	GenStrongMaxTime time.Duration
	GenConcurrency   int
}

// Bcrypter holds
type Bcrypter struct {
	mu         *sync.RWMutex
	tuningWg   *sync.WaitGroup
	Options    *Options
	quickCost  int
	strongCost int
	concCount  chan bool
}

// New returns a *Bcrypter based on Options values or defaults.
func New(opts *Options) *Bcrypter {
	if opts == nil {
		opts = &Options{}
	}

	if opts.GenQuickMaxTime == 0 {
		opts.GenQuickMaxTime = GenQuickMaxTime
	}
	if opts.GenStrongMaxTime == 0 {
		opts.GenStrongMaxTime = GenStrongMaxTime
	}

	if opts.GenConcurrency == 0 {
		opts.GenConcurrency = GenConcurrency
	}

	return &Bcrypter{
		Options: opts, mu: &sync.RWMutex{}, tuningWg: &sync.WaitGroup{},
		concCount: make(chan bool, opts.GenConcurrency),
	}
}

// GenQuickFromPass returns a hash produced using Bcrypter.quickCost.
func (bc *Bcrypter) GenQuickFromPass(pass string) (string, error) {
	bc.concCount <- true
	defer func() { <-bc.concCount }()
	c := bc.CurrentQuickCost()
	b, err := bcrypt.GenerateFromPassword([]byte(pass), c)
	return string(b), err
}

// GenStrongFromPass returns a hash produced using Bcrypter.strongCost.
func (bc *Bcrypter) GenStrongFromPass(pass string) (string, error) {
	bc.concCount <- true
	defer func() { <-bc.concCount }()
	c := bc.CurrentStrongCost()
	b, err := bcrypt.GenerateFromPassword([]byte(pass), c)
	return string(b), err
}

// CompareHashAndPass receives a hashed password and password strings, and returns an
// error if comparison fails.
func (bc *Bcrypter) CompareHashAndPass(hash, pass string) error {
	return bcrypt.CompareHashAndPassword([]byte(hash), []byte(pass))
}

// Tune wraps tune so that Bcrypter.tuningWg is surely used.
func (bc *Bcrypter) Tune() {
	bc.tuningWg.Wait()
	bc.tuningWg.Add(1)
	bc.tune(bc.tuningWg)
}

// IsCostQuick returns the results of testHash with Bcrypter.quickCost.
func (bc *Bcrypter) IsCostQuick(hash string) error {
	c := bc.CurrentQuickCost()
	return testHash(hash, c)
}

// IsCostStrong returns the results of testHash with Bcrypter.strongCost.
func (bc *Bcrypter) IsCostStrong(hash string) error {
	c := bc.CurrentStrongCost()
	return testHash(hash, c)
}

func (bc *Bcrypter) CurrentQuickCost() int {
	bc.tuningWg.Wait()
	bc.mu.RLock()
	c := bc.quickCost
	bc.mu.RUnlock()

	if c == 0 {
		bc.Tune()
		bc.mu.RLock()
		c = bc.quickCost
		bc.mu.RUnlock()
	}
	return c
}

func (bc *Bcrypter) CurrentStrongCost() int {
	bc.tuningWg.Wait()
	bc.mu.RLock()
	c := bc.strongCost
	bc.mu.RUnlock()

	if c == 0 {
		bc.Tune()
		bc.mu.RLock()
		c = bc.strongCost
		bc.mu.RUnlock()
	}
	return c
}

// tune returns any test hash processing errors.
func (bc *Bcrypter) tune(wg *sync.WaitGroup) {
	defer wg.Done()
	var qc, sc int

	cts := []time.Duration{0}
	for i := 1; i <= maxCost; i++ {
		if i < minCost {
			cts = append(cts, 0)
			continue
		}

		if cts[i-1] < interpTime {
			t1 := time.Now()
			_, err := bcrypt.GenerateFromPassword([]byte(testStr), i)
			d := time.Since(t1)
			if err != nil {
				panic("Failed to tune bcryptx: " + err.Error())
			}

			cts = append(cts, d)
			continue
		}

		tct := cts[i-1] * 2
		tct = tct - (tct % (time.Millisecond * 10))
		cts = append(cts, tct)
	}

	for k := range cts {
		if qc == 0 && len(cts) > k+1 && cts[k+1] > bc.Options.GenQuickMaxTime {
			qc = k
		}
		if sc == 0 && len(cts) > k+1 && cts[k+1] > bc.Options.GenStrongMaxTime {
			sc = k
		}
	}

	bc.mu.Lock()
	bc.quickCost = qc
	bc.strongCost = sc
	bc.mu.Unlock()
}

// test returns an error if the apparent cost of the hash is lower than the
// provided cost, or if any errors are encountered during hash analysis.
func testHash(hash string, cost int) error {
	c, err := bcrypt.Cost([]byte(hash))
	if err != nil {
		return err
	}
	if c < cost {
		return ErrLowCost
	}
	return nil
}
<commit_msg>Improved commenting.<commit_after>// Package bcryptx automates the tuning of bcrypt costs based on an
// environment's available processing resources.  Concurrency throttling is
// provided, as well as convenience functions for making use of tuned costs
// with bcrypt functions.
//
// quickCost should be used when a hash should be accessible quickly.
// strongCost should be used when the delay of processing can be mitigated.
package bcryptx

import (
	"errors"
	"sync"
	"time"

	"golang.org/x/crypto/bcrypt"
)

const (
	// GenQuickMaxTime is the default max time used for tuning
	// Bcrypter.quickCost.
	GenQuickMaxTime = time.Millisecond * 500

	// GenStrongMaxTime is the default max time used for tuning
	// Bcrypter.strongCost.
	GenStrongMaxTime = time.Millisecond * 2000

	// GenConcurrency is the default goroutine count used for Gen*FromPass.
	GenConcurrency = 2

	minCost    = bcrypt.MinCost
	maxCost    = bcrypt.MaxCost
	interpTime = time.Millisecond * 50
	testStr    = "#!PnutBudr"
)

var (
	// ErrLowCost is returned by failed IsCost* functions.
	ErrLowCost = errors.New("Hash cost lower than currently configured cost.")
)

// Options holds values to be passed to New.
type Options struct {
	// GenQuickMaxTime is the max time used for tuning Bcrypter.quickCost.
	GenQuickMaxTime  time.Duration

	// GenStrongMaxTime is the max time used for tuning Bcrypter.strongCost.
	GenStrongMaxTime time.Duration

	// GenConcurrency is the goroutine count used for Gen*FromPass.
	GenConcurrency   int
}

// Bcrypter provides an API for bcrypt functions with "quick" or "strong" costs.
// Tune is called on first use of Gen*FromPass if not already called directly.
type Bcrypter struct {
	mu         *sync.RWMutex
	tuningWg   *sync.WaitGroup
	Options    *Options
	quickCost  int
	strongCost int
	concCount  chan bool
}

// New returns a new Bcrypter based on Options values or defaults.
func New(opts *Options) *Bcrypter {
	if opts == nil {
		opts = &Options{}
	}

	if opts.GenQuickMaxTime == 0 {
		opts.GenQuickMaxTime = GenQuickMaxTime
	}
	if opts.GenStrongMaxTime == 0 {
		opts.GenStrongMaxTime = GenStrongMaxTime
	}

	if opts.GenConcurrency == 0 {
		opts.GenConcurrency = GenConcurrency
	}

	return &Bcrypter{
		Options: opts, mu: &sync.RWMutex{}, tuningWg: &sync.WaitGroup{},
		concCount: make(chan bool, opts.GenConcurrency),
	}
}

// GenQuickFromPass returns a hash produced using Bcrypter.quickCost or any
// error encountered during handling.
func (bc *Bcrypter) GenQuickFromPass(pass string) (string, error) {
	bc.concCount <- true
	defer func() { <-bc.concCount }()
	c := bc.CurrentQuickCost()
	b, err := bcrypt.GenerateFromPassword([]byte(pass), c)
	return string(b), err
}

// GenStrongFromPass returns a hash produced using Bcrypter.strongCost or any
// error encountered during handling.
func (bc *Bcrypter) GenStrongFromPass(pass string) (string, error) {
	bc.concCount <- true
	defer func() { <-bc.concCount }()
	c := bc.CurrentStrongCost()
	b, err := bcrypt.GenerateFromPassword([]byte(pass), c)
	return string(b), err
}

// CompareHashAndPass returns an error if comparison fails or any error
// encountered during handling.
func (bc *Bcrypter) CompareHashAndPass(hash, pass string) error {
	return bcrypt.CompareHashAndPassword([]byte(hash), []byte(pass))
}

// Tune wraps tune so that Bcrypter.tuningWg is always used.
func (bc *Bcrypter) Tune() {
	bc.tuningWg.Wait()
	bc.tuningWg.Add(1)
	bc.tune(bc.tuningWg)
}

// IsCostQuick returns the result of testHash with Bcrypter.quickCost.
func (bc *Bcrypter) IsCostQuick(hash string) error {
	c := bc.CurrentQuickCost()
	return testHash(hash, c)
}

// IsCostStrong returns the result of testHash with Bcrypter.strongCost.
func (bc *Bcrypter) IsCostStrong(hash string) error {
	c := bc.CurrentStrongCost()
	return testHash(hash, c)
}

// CurrentQuickCost returns the quickCost as set by Tune.
func (bc *Bcrypter) CurrentQuickCost() int {
	bc.tuningWg.Wait()
	bc.mu.RLock()
	c := bc.quickCost
	bc.mu.RUnlock()

	if c == 0 {
		bc.Tune()
		bc.mu.RLock()
		c = bc.quickCost
		bc.mu.RUnlock()
	}
	return c
}

// CurrentStrongCost returns the strongCost as set by Tune.
func (bc *Bcrypter) CurrentStrongCost() int {
	bc.tuningWg.Wait()
	bc.mu.RLock()
	c := bc.strongCost
	bc.mu.RUnlock()

	if c == 0 {
		bc.Tune()
		bc.mu.RLock()
		c = bc.strongCost
		bc.mu.RUnlock()
	}
	return c
}

// tune returns any test hash processing errors.
func (bc *Bcrypter) tune(wg *sync.WaitGroup) {
	defer wg.Done()
	var qc, sc int

	cts := []time.Duration{0}
	for i := 1; i <= maxCost; i++ {
		if i < minCost {
			cts = append(cts, 0)
			continue
		}

		if cts[i-1] < interpTime {
			t1 := time.Now()
			_, err := bcrypt.GenerateFromPassword([]byte(testStr), i)
			d := time.Since(t1)
			if err != nil {
				panic("Failed to tune bcryptx: " + err.Error())
			}

			cts = append(cts, d)
			continue
		}

		tct := cts[i-1] * 2
		tct = tct - (tct % (time.Millisecond * 10))
		cts = append(cts, tct)
	}

	for k := range cts {
		if qc == 0 && len(cts) > k+1 && cts[k+1] > bc.Options.GenQuickMaxTime {
			qc = k
		}
		if sc == 0 && len(cts) > k+1 && cts[k+1] > bc.Options.GenStrongMaxTime {
			sc = k
		}
	}

	bc.mu.Lock()
	bc.quickCost = qc
	bc.strongCost = sc
	bc.mu.Unlock()
}

// test returns an error if the apparent cost of the hash is lower than the
// provided cost, or if any errors are encountered during hash analysis.
func testHash(hash string, cost int) error {
	c, err := bcrypt.Cost([]byte(hash))
	if err != nil {
		return err
	}
	if c < cost {
		return ErrLowCost
	}
	return nil
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"fmt"
	"github.com/paulhammond/jp"
	"os"
)

func main() {
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "usage: jp [file]\n")
		flag.PrintDefaults()
	}
	format := flag.String("format", "pretty", "output format")

	flag.Parse()
	args := flag.Args()
	if len(args) < 1 {
		flag.Usage()
		os.Exit(2)
	}

	var fd *os.File
	var e error
	if args[0] == "-" {
		fd = os.Stdin
	} else {
		fd, e = os.Open(args[0])
		if e != nil {
			fmt.Fprintln(os.Stderr, "Error:", e)
			os.Exit(1)
		}
	}

	e = jp.Expand(fd, os.Stdout, *format)
	if e != nil {
		fmt.Fprintln(os.Stderr, "Error:", e)
		os.Exit(1)
	}
}
<commit_msg>Better command line flags<commit_after>package main

import (
	"flag"
	"fmt"
	"github.com/paulhammond/jp"
	"os"
)

func main() {
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "usage: jp [file]\n")
		flag.PrintDefaults()
	}
	compact := flag.Bool("compact", false, "compact format")

	flag.Parse()
	args := flag.Args()
	if len(args) < 1 {
		flag.Usage()
		os.Exit(2)
	}

	format := "pretty"
	if *compact {
		format = "compact"
	}

	var fd *os.File
	var e error
	if args[0] == "-" {
		fd = os.Stdin
	} else {
		fd, e = os.Open(args[0])
		if e != nil {
			fmt.Fprintln(os.Stderr, "Error:", e)
			os.Exit(1)
		}
	}

	e = jp.Expand(fd, os.Stdout, format)
	if e != nil {
		fmt.Fprintln(os.Stderr, "Error:", e)
		os.Exit(1)
	}
}
<|endoftext|>


<commit_before>/*
Copyright 2015 The Kubernetes 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.
*/

// Package leaderelection implements leader election of a set of endpoints.
// It uses an annotation in the endpoints object to store the record of the
// election state.
//
// This implementation does not guarantee that only one client is acting as a
// leader (a.k.a. fencing). A client observes timestamps captured locally to
// infer the state of the leader election. Thus the implementation is tolerant
// to arbitrary clock skew, but is not tolerant to arbitrary clock skew rate.
//
// However the level of tolerance to skew rate can be configured by setting
// RenewDeadline and LeaseDuration appropriately. The tolerance expressed as a
// maximum tolerated ratio of time passed on the fastest node to time passed on
// the slowest node can be approximately achieved with a configuration that sets
// the same ratio of LeaseDuration to RenewDeadline. For example if a user wanted
// to tolerate some nodes progressing forward in time twice as fast as other nodes,
// the user could set LeaseDuration to 60 seconds and RenewDeadline to 30 seconds.
//
// While not required, some method of clock synchronization between nodes in the
// cluster is highly recommended. It's important to keep in mind when configuring
// this client that the tolerance to skew rate varies inversely to master
// availability.
//
// Larger clusters often have a more lenient SLA for API latency. This should be
// taken into account when configuring the client. The rate of leader transistions
// should be monitored and RetryPeriod and LeaseDuration should be increased
// until the rate is stable and acceptably low. It's important to keep in mind
// when configuring this client that the tolerance to API latency varies inversely
// to master availability.
//
// DISCLAIMER: this is an alpha API. This library will likely change significantly
// or even be removed entirely in subsequent releases. Depend on this API at
// your own risk.

package leaderelection

import (
	"encoding/json"
	"fmt"
	"reflect"
	"time"

	"github.com/golang/glog"

	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/api/errors"
	"k8s.io/kubernetes/pkg/api/unversioned"
	"k8s.io/kubernetes/pkg/client/record"
	client "k8s.io/kubernetes/pkg/client/unversioned"
	"k8s.io/kubernetes/pkg/util"
	"k8s.io/kubernetes/pkg/util/wait"
)

const (
	JitterFactor = 1.2

	LeaderElectionRecordAnnotationKey = "control-plane.alpha.kubernetes.io/leader"
)

// NewLeadereElector creates a LeaderElector from a LeaderElecitionConfig
func NewLeaderElector(lec LeaderElectionConfig) (*LeaderElector, error) {
	if lec.LeaseDuration <= lec.RenewDeadline {
		return nil, fmt.Errorf("leaseDuration must be greater than renewDeadline")
	}
	if lec.RenewDeadline <= time.Duration(JitterFactor*float64(lec.RetryPeriod)) {
		return nil, fmt.Errorf("renewDeadline must be greater than retryPeriod*JitterFactor")
	}
	if lec.Client == nil {
		return nil, fmt.Errorf("Client must not be nil.")
	}
	if lec.EventRecorder == nil {
		return nil, fmt.Errorf("EventRecorder must not be nil.")
	}
	return &LeaderElector{
		config: lec,
	}, nil
}

type LeaderElectionConfig struct {
	// EndpointsMeta should contain a Name and a Namespace of an
	// Endpoints object that the LeaderElector will attempt to lead.
	EndpointsMeta api.ObjectMeta
	// Identity is a unique identifier of the leader elector.
	Identity string

	Client        client.Interface
	EventRecorder record.EventRecorder

	// LeaseDuration is the duration that non-leader candidates will
	// wait to force acquire leadership. This is measured against time of
	// last observed ack.
	LeaseDuration time.Duration
	// RenewDeadline is the duration that the acting master will retry
	// refreshing leadership before giving up.
	RenewDeadline time.Duration
	// RetryPeriod is the duration the LeaderElector clients should wait
	// between tries of actions.
	RetryPeriod time.Duration

	// Callbacks are callbacks that are triggered during certain lifecycle
	// events of the LeaderElector
	Callbacks LeaderCallbacks
}

// LeaderCallbacks are callbacks that are triggered during certain
// lifecycle events of the LeaderElector. These are invoked asynchronously.
//
// possible future callbacks:
//  * OnChallenge()
//  * OnNewLeader()
type LeaderCallbacks struct {
	// OnStartedLeading is called when a LeaderElector client starts leading
	OnStartedLeading func(stop <-chan struct{})
	// OnStoppedLeading is called when a LeaderElector client stops leading
	OnStoppedLeading func()
}

// LeaderElector is a leader election client.
//
// possible future methods:
//  * (le *LeaderElector) IsLeader()
//  * (le *LeaderElector) GetLeader()
type LeaderElector struct {
	config LeaderElectionConfig
	// internal bookkeeping
	observedRecord LeaderElectionRecord
	observedTime   time.Time
}

// LeaderElectionRecord is the record that is stored in the leader election annotation.
// This information should be used for observational purposes only and could be replaced
// with a random string (e.g. UUID) with only slight modification of this code.
// TODO(mikedanese): this should potentially be versioned
type LeaderElectionRecord struct {
	HolderIdentity       string           `json:"holderIdentity"`
	LeaseDurationSeconds int              `json:"leaseDurationSeconds"`
	AcquireTime          unversioned.Time `json:"acquireTime"`
	RenewTime            unversioned.Time `json:"renewTime"`
}

// Run starts the leader election loop
func (le *LeaderElector) Run() {
	defer func() {
		util.HandleCrash()
		le.config.Callbacks.OnStoppedLeading()
	}()
	le.acquire()
	stop := make(chan struct{})
	go le.config.Callbacks.OnStartedLeading(stop)
	le.renew()
	close(stop)
}

// acquire loops calling tryAcquireOrRenew and returns immediately when tryAcquireOrRenew succeeds.
func (le *LeaderElector) acquire() {
	stop := make(chan struct{})
	util.Until(func() {
		succeeded := le.tryAcquireOrRenew()
		if !succeeded {
			glog.V(4).Infof("failed to renew lease %v/%v", le.config.EndpointsMeta.Namespace, le.config.EndpointsMeta.Name)
			time.Sleep(wait.Jitter(le.config.RetryPeriod, JitterFactor))
			return
		}
		le.config.EventRecorder.Eventf(&api.Endpoints{ObjectMeta: le.config.EndpointsMeta}, api.EventTypeNormal, "%v became leader", le.config.Identity)
		glog.Infof("sucessfully acquired lease %v/%v", le.config.EndpointsMeta.Namespace, le.config.EndpointsMeta.Name)
		close(stop)
	}, 0, stop)
}

// renew loops calling tryAcquireOrRenew and returns immediately when tryAcquireOrRenew fails.
func (le *LeaderElector) renew() {
	stop := make(chan struct{})
	util.Until(func() {
		err := wait.Poll(le.config.RetryPeriod, le.config.RenewDeadline, func() (bool, error) {
			return le.tryAcquireOrRenew(), nil
		})
		if err == nil {
			glog.V(4).Infof("succesfully renewed lease %v/%v", le.config.EndpointsMeta.Namespace, le.config.EndpointsMeta.Name)
			return
		}
		le.config.EventRecorder.Eventf(&api.Endpoints{ObjectMeta: le.config.EndpointsMeta}, api.EventTypeNormal, "%v stopped leading", le.config.Identity)
		glog.Infof("failed to renew lease %v/%v", le.config.EndpointsMeta.Namespace, le.config.EndpointsMeta.Name)
		close(stop)
	}, 0, stop)
}

// tryAcquireOrRenew tries to acquire a leader lease if it is not already acquired,
// else it tries to renew the lease if it has already been acquired. Returns true
// on success else returns false.
func (le *LeaderElector) tryAcquireOrRenew() bool {
	now := unversioned.Now()
	leaderElectionRecord := LeaderElectionRecord{
		HolderIdentity:       le.config.Identity,
		LeaseDurationSeconds: int(le.config.LeaseDuration / time.Second),
		RenewTime:            now,
		AcquireTime:          now,
	}

	e, err := le.config.Client.Endpoints(le.config.EndpointsMeta.Namespace).Get(le.config.EndpointsMeta.Name)
	if err != nil {
		if !errors.IsNotFound(err) {
			return false
		}

		leaderElectionRecordBytes, err := json.Marshal(leaderElectionRecord)
		if err != nil {
			return false
		}
		_, err = le.config.Client.Endpoints(le.config.EndpointsMeta.Namespace).Create(&api.Endpoints{
			ObjectMeta: api.ObjectMeta{
				Name:      le.config.EndpointsMeta.Name,
				Namespace: le.config.EndpointsMeta.Namespace,
				Annotations: map[string]string{
					LeaderElectionRecordAnnotationKey: string(leaderElectionRecordBytes),
				},
			},
		})
		if err != nil {
			glog.Errorf("error initially creating endpoints: %v", err)
			return false
		}
		le.observedRecord = leaderElectionRecord
		le.observedTime = time.Now()
		return true
	}

	if e.Annotations == nil {
		e.Annotations = make(map[string]string)
	}

	if oldLeaderElectionRecordBytes, found := e.Annotations[LeaderElectionRecordAnnotationKey]; found {
		var oldLeaderElectionRecord LeaderElectionRecord
		if err := json.Unmarshal([]byte(oldLeaderElectionRecordBytes), &oldLeaderElectionRecord); err != nil {
			glog.Errorf("error unmarshaling leader election record: %v", err)
			return false
		}
		if !reflect.DeepEqual(le.observedRecord, oldLeaderElectionRecord) {
			le.observedRecord = oldLeaderElectionRecord
			le.observedTime = time.Now()
		}
		if oldLeaderElectionRecord.HolderIdentity == le.config.Identity {
			leaderElectionRecord.AcquireTime = oldLeaderElectionRecord.AcquireTime
		}
		if le.observedTime.Add(le.config.LeaseDuration).After(now.Time) &&
			oldLeaderElectionRecord.HolderIdentity != le.config.Identity {
			glog.Infof("lock is held by %v and has not yet expired", oldLeaderElectionRecord.HolderIdentity)
			return false
		}
	}

	leaderElectionRecordBytes, err := json.Marshal(leaderElectionRecord)
	if err != nil {
		glog.Errorf("err marshaling leader election record: %v", err)
		return false
	}
	e.Annotations[LeaderElectionRecordAnnotationKey] = string(leaderElectionRecordBytes)

	_, err = le.config.Client.Endpoints(le.config.EndpointsMeta.Namespace).Update(e)
	if err != nil {
		glog.Errorf("err: %v", err)
		return false
	}
	le.observedRecord = leaderElectionRecord
	le.observedTime = time.Now()
	return true
}
<commit_msg>fix package doc so it shows up on godoc.org<commit_after>/*
Copyright 2015 The Kubernetes 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.
*/

// Package leaderelection implements leader election of a set of endpoints.
// It uses an annotation in the endpoints object to store the record of the
// election state.
//
// This implementation does not guarantee that only one client is acting as a
// leader (a.k.a. fencing). A client observes timestamps captured locally to
// infer the state of the leader election. Thus the implementation is tolerant
// to arbitrary clock skew, but is not tolerant to arbitrary clock skew rate.
//
// However the level of tolerance to skew rate can be configured by setting
// RenewDeadline and LeaseDuration appropriately. The tolerance expressed as a
// maximum tolerated ratio of time passed on the fastest node to time passed on
// the slowest node can be approximately achieved with a configuration that sets
// the same ratio of LeaseDuration to RenewDeadline. For example if a user wanted
// to tolerate some nodes progressing forward in time twice as fast as other nodes,
// the user could set LeaseDuration to 60 seconds and RenewDeadline to 30 seconds.
//
// While not required, some method of clock synchronization between nodes in the
// cluster is highly recommended. It's important to keep in mind when configuring
// this client that the tolerance to skew rate varies inversely to master
// availability.
//
// Larger clusters often have a more lenient SLA for API latency. This should be
// taken into account when configuring the client. The rate of leader transistions
// should be monitored and RetryPeriod and LeaseDuration should be increased
// until the rate is stable and acceptably low. It's important to keep in mind
// when configuring this client that the tolerance to API latency varies inversely
// to master availability.
//
// DISCLAIMER: this is an alpha API. This library will likely change significantly
// or even be removed entirely in subsequent releases. Depend on this API at
// your own risk.
package leaderelection

import (
	"encoding/json"
	"fmt"
	"reflect"
	"time"

	"github.com/golang/glog"

	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/api/errors"
	"k8s.io/kubernetes/pkg/api/unversioned"
	"k8s.io/kubernetes/pkg/client/record"
	client "k8s.io/kubernetes/pkg/client/unversioned"
	"k8s.io/kubernetes/pkg/util"
	"k8s.io/kubernetes/pkg/util/wait"
)

const (
	JitterFactor = 1.2

	LeaderElectionRecordAnnotationKey = "control-plane.alpha.kubernetes.io/leader"
)

// NewLeadereElector creates a LeaderElector from a LeaderElecitionConfig
func NewLeaderElector(lec LeaderElectionConfig) (*LeaderElector, error) {
	if lec.LeaseDuration <= lec.RenewDeadline {
		return nil, fmt.Errorf("leaseDuration must be greater than renewDeadline")
	}
	if lec.RenewDeadline <= time.Duration(JitterFactor*float64(lec.RetryPeriod)) {
		return nil, fmt.Errorf("renewDeadline must be greater than retryPeriod*JitterFactor")
	}
	if lec.Client == nil {
		return nil, fmt.Errorf("Client must not be nil.")
	}
	if lec.EventRecorder == nil {
		return nil, fmt.Errorf("EventRecorder must not be nil.")
	}
	return &LeaderElector{
		config: lec,
	}, nil
}

type LeaderElectionConfig struct {
	// EndpointsMeta should contain a Name and a Namespace of an
	// Endpoints object that the LeaderElector will attempt to lead.
	EndpointsMeta api.ObjectMeta
	// Identity is a unique identifier of the leader elector.
	Identity string

	Client        client.Interface
	EventRecorder record.EventRecorder

	// LeaseDuration is the duration that non-leader candidates will
	// wait to force acquire leadership. This is measured against time of
	// last observed ack.
	LeaseDuration time.Duration
	// RenewDeadline is the duration that the acting master will retry
	// refreshing leadership before giving up.
	RenewDeadline time.Duration
	// RetryPeriod is the duration the LeaderElector clients should wait
	// between tries of actions.
	RetryPeriod time.Duration

	// Callbacks are callbacks that are triggered during certain lifecycle
	// events of the LeaderElector
	Callbacks LeaderCallbacks
}

// LeaderCallbacks are callbacks that are triggered during certain
// lifecycle events of the LeaderElector. These are invoked asynchronously.
//
// possible future callbacks:
//  * OnChallenge()
//  * OnNewLeader()
type LeaderCallbacks struct {
	// OnStartedLeading is called when a LeaderElector client starts leading
	OnStartedLeading func(stop <-chan struct{})
	// OnStoppedLeading is called when a LeaderElector client stops leading
	OnStoppedLeading func()
}

// LeaderElector is a leader election client.
//
// possible future methods:
//  * (le *LeaderElector) IsLeader()
//  * (le *LeaderElector) GetLeader()
type LeaderElector struct {
	config LeaderElectionConfig
	// internal bookkeeping
	observedRecord LeaderElectionRecord
	observedTime   time.Time
}

// LeaderElectionRecord is the record that is stored in the leader election annotation.
// This information should be used for observational purposes only and could be replaced
// with a random string (e.g. UUID) with only slight modification of this code.
// TODO(mikedanese): this should potentially be versioned
type LeaderElectionRecord struct {
	HolderIdentity       string           `json:"holderIdentity"`
	LeaseDurationSeconds int              `json:"leaseDurationSeconds"`
	AcquireTime          unversioned.Time `json:"acquireTime"`
	RenewTime            unversioned.Time `json:"renewTime"`
}

// Run starts the leader election loop
func (le *LeaderElector) Run() {
	defer func() {
		util.HandleCrash()
		le.config.Callbacks.OnStoppedLeading()
	}()
	le.acquire()
	stop := make(chan struct{})
	go le.config.Callbacks.OnStartedLeading(stop)
	le.renew()
	close(stop)
}

// acquire loops calling tryAcquireOrRenew and returns immediately when tryAcquireOrRenew succeeds.
func (le *LeaderElector) acquire() {
	stop := make(chan struct{})
	util.Until(func() {
		succeeded := le.tryAcquireOrRenew()
		if !succeeded {
			glog.V(4).Infof("failed to renew lease %v/%v", le.config.EndpointsMeta.Namespace, le.config.EndpointsMeta.Name)
			time.Sleep(wait.Jitter(le.config.RetryPeriod, JitterFactor))
			return
		}
		le.config.EventRecorder.Eventf(&api.Endpoints{ObjectMeta: le.config.EndpointsMeta}, api.EventTypeNormal, "%v became leader", le.config.Identity)
		glog.Infof("sucessfully acquired lease %v/%v", le.config.EndpointsMeta.Namespace, le.config.EndpointsMeta.Name)
		close(stop)
	}, 0, stop)
}

// renew loops calling tryAcquireOrRenew and returns immediately when tryAcquireOrRenew fails.
func (le *LeaderElector) renew() {
	stop := make(chan struct{})
	util.Until(func() {
		err := wait.Poll(le.config.RetryPeriod, le.config.RenewDeadline, func() (bool, error) {
			return le.tryAcquireOrRenew(), nil
		})
		if err == nil {
			glog.V(4).Infof("succesfully renewed lease %v/%v", le.config.EndpointsMeta.Namespace, le.config.EndpointsMeta.Name)
			return
		}
		le.config.EventRecorder.Eventf(&api.Endpoints{ObjectMeta: le.config.EndpointsMeta}, api.EventTypeNormal, "%v stopped leading", le.config.Identity)
		glog.Infof("failed to renew lease %v/%v", le.config.EndpointsMeta.Namespace, le.config.EndpointsMeta.Name)
		close(stop)
	}, 0, stop)
}

// tryAcquireOrRenew tries to acquire a leader lease if it is not already acquired,
// else it tries to renew the lease if it has already been acquired. Returns true
// on success else returns false.
func (le *LeaderElector) tryAcquireOrRenew() bool {
	now := unversioned.Now()
	leaderElectionRecord := LeaderElectionRecord{
		HolderIdentity:       le.config.Identity,
		LeaseDurationSeconds: int(le.config.LeaseDuration / time.Second),
		RenewTime:            now,
		AcquireTime:          now,
	}

	e, err := le.config.Client.Endpoints(le.config.EndpointsMeta.Namespace).Get(le.config.EndpointsMeta.Name)
	if err != nil {
		if !errors.IsNotFound(err) {
			return false
		}

		leaderElectionRecordBytes, err := json.Marshal(leaderElectionRecord)
		if err != nil {
			return false
		}
		_, err = le.config.Client.Endpoints(le.config.EndpointsMeta.Namespace).Create(&api.Endpoints{
			ObjectMeta: api.ObjectMeta{
				Name:      le.config.EndpointsMeta.Name,
				Namespace: le.config.EndpointsMeta.Namespace,
				Annotations: map[string]string{
					LeaderElectionRecordAnnotationKey: string(leaderElectionRecordBytes),
				},
			},
		})
		if err != nil {
			glog.Errorf("error initially creating endpoints: %v", err)
			return false
		}
		le.observedRecord = leaderElectionRecord
		le.observedTime = time.Now()
		return true
	}

	if e.Annotations == nil {
		e.Annotations = make(map[string]string)
	}

	if oldLeaderElectionRecordBytes, found := e.Annotations[LeaderElectionRecordAnnotationKey]; found {
		var oldLeaderElectionRecord LeaderElectionRecord
		if err := json.Unmarshal([]byte(oldLeaderElectionRecordBytes), &oldLeaderElectionRecord); err != nil {
			glog.Errorf("error unmarshaling leader election record: %v", err)
			return false
		}
		if !reflect.DeepEqual(le.observedRecord, oldLeaderElectionRecord) {
			le.observedRecord = oldLeaderElectionRecord
			le.observedTime = time.Now()
		}
		if oldLeaderElectionRecord.HolderIdentity == le.config.Identity {
			leaderElectionRecord.AcquireTime = oldLeaderElectionRecord.AcquireTime
		}
		if le.observedTime.Add(le.config.LeaseDuration).After(now.Time) &&
			oldLeaderElectionRecord.HolderIdentity != le.config.Identity {
			glog.Infof("lock is held by %v and has not yet expired", oldLeaderElectionRecord.HolderIdentity)
			return false
		}
	}

	leaderElectionRecordBytes, err := json.Marshal(leaderElectionRecord)
	if err != nil {
		glog.Errorf("err marshaling leader election record: %v", err)
		return false
	}
	e.Annotations[LeaderElectionRecordAnnotationKey] = string(leaderElectionRecordBytes)

	_, err = le.config.Client.Endpoints(le.config.EndpointsMeta.Namespace).Update(e)
	if err != nil {
		glog.Errorf("err: %v", err)
		return false
	}
	le.observedRecord = leaderElectionRecord
	le.observedTime = time.Now()
	return true
}
<|endoftext|>


<commit_before>package classpath

import (
	"os"
	"path/filepath"
	"strings"
)

// :(linux/unix) or ;(windows)
const _pathListSeparator = string(os.PathListSeparator)

type CompoundClassPathEntry struct {
	entries []ClassPathEntry
}

func newCompoundClassPathEntry(pathList string) *CompoundClassPathEntry {
	compoundEntry := &CompoundClassPathEntry{}

	for _, path := range strings.Split(pathList, _pathListSeparator) {
		if absPath, err := filepath.Abs(path); err == nil {
			entry := parseClassPathEntry(absPath)
			compoundEntry.addEntry(entry)
		} else {
			// todo
		}
	}

	return compoundEntry
}

func (self *CompoundClassPathEntry) readClassData(className string) (ClassPathEntry, []byte, error) {
	for _, entry := range self.entries {
		entry, data, err := entry.readClassData(className)
		if err == nil {
			return entry, data, nil
		}
	}

	// todo
	return nil, nil, classNotFoundErr
}

func (self *CompoundClassPathEntry) addEntry(entry ClassPathEntry) {
	_len := len(self.entries)
	if _len == cap(self.entries) {
		newEntries := make([]ClassPathEntry, _len, _len+8)
		copy(newEntries, self.entries)
		self.entries = newEntries
	}

	self.entries = append(self.entries, entry)
}

func (self *CompoundClassPathEntry) String() string {
	strs := make([]string, len(self.entries))

	for i, entry := range self.entries {
		strs[i] = entry.String()
	}

	return strings.Join(strs, _pathListSeparator)
}
<commit_msg>reorder methods<commit_after>package classpath

import (
	"os"
	"path/filepath"
	"strings"
)

// :(linux/unix) or ;(windows)
const _pathListSeparator = string(os.PathListSeparator)

type CompoundClassPathEntry struct {
	entries []ClassPathEntry
}

func newCompoundClassPathEntry(pathList string) *CompoundClassPathEntry {
	compoundEntry := &CompoundClassPathEntry{}

	for _, path := range strings.Split(pathList, _pathListSeparator) {
		if absPath, err := filepath.Abs(path); err == nil {
			entry := parseClassPathEntry(absPath)
			compoundEntry.addEntry(entry)
		} else {
			// todo
		}
	}

	return compoundEntry
}

func (self *CompoundClassPathEntry) addEntry(entry ClassPathEntry) {
	_len := len(self.entries)
	if _len == cap(self.entries) {
		newEntries := make([]ClassPathEntry, _len, _len+8)
		copy(newEntries, self.entries)
		self.entries = newEntries
	}

	self.entries = append(self.entries, entry)
}

func (self *CompoundClassPathEntry) readClassData(className string) (ClassPathEntry, []byte, error) {
	for _, entry := range self.entries {
		entry, data, err := entry.readClassData(className)
		if err == nil {
			return entry, data, nil
		}
	}

	// todo
	return nil, nil, classNotFoundErr
}

func (self *CompoundClassPathEntry) String() string {
	strs := make([]string, len(self.entries))

	for i, entry := range self.entries {
		strs[i] = entry.String()
	}

	return strings.Join(strs, _pathListSeparator)
}
<|endoftext|>


<commit_before>/*
Copyright 2021 The Rook 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.
*/

package client

import (
	"encoding/json"
	"fmt"
	"strings"
	"syscall"

	"github.com/pkg/errors"
	cephv1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1"
	"github.com/rook/rook/pkg/clusterd"
	"github.com/rook/rook/pkg/util/exec"
)

type BootstrapPeerToken struct {
	Token string `json:"token"`
}

// RemoveFilesystemMirrorPeer add a mirror peer in the cephfs-mirror configuration
func RemoveFilesystemMirrorPeer(context *clusterd.Context, clusterInfo *ClusterInfo, peerUUID string) error {
	logger.Infof("removing cephfs-mirror peer %q", peerUUID)

	// Build command
	args := []string{"fs", "snapshot", "mirror", "peer_remove", peerUUID}
	cmd := NewCephCommand(context, clusterInfo, args)

	// Run command
	output, err := cmd.Run()
	if err != nil {
		return errors.Wrapf(err, "failed to remove cephfs-mirror peer for filesystem %q. %s", peerUUID, output)
	}

	logger.Infof("successfully removed cephfs-mirror peer %q", peerUUID)
	return nil
}

// EnableFilesystemSnapshotMirror enables filesystem snapshot mirroring
func EnableFilesystemSnapshotMirror(context *clusterd.Context, clusterInfo *ClusterInfo, filesystem string) error {
	logger.Infof("enabling ceph filesystem snapshot mirror for filesystem %q", filesystem)

	// Build command
	args := []string{"fs", "snapshot", "mirror", "enable", filesystem}
	cmd := NewCephCommand(context, clusterInfo, args)

	// Run command
	output, err := cmd.Run()
	if err != nil {
		return errors.Wrapf(err, "failed to enable ceph filesystem snapshot mirror for filesystem %q. %s", filesystem, output)
	}

	logger.Infof("successfully enabled ceph filesystem snapshot mirror for filesystem %q", filesystem)
	return nil
}

// DisableFilesystemSnapshotMirror enables filesystem snapshot mirroring
func DisableFilesystemSnapshotMirror(context *clusterd.Context, clusterInfo *ClusterInfo, filesystem string) error {
	logger.Infof("disabling ceph filesystem snapshot mirror for filesystem %q", filesystem)

	// Build command
	args := []string{"fs", "snapshot", "mirror", "disable", filesystem}
	cmd := NewCephCommand(context, clusterInfo, args)

	// Run command
	output, err := cmd.Run()
	if err != nil {
		if code, err := exec.ExtractExitCode(err); err == nil && code == int(syscall.ENOTSUP) {
			logger.Debug("filesystem mirroring is not enabled, nothing to disable")
			return nil
		}
		return errors.Wrapf(err, "failed to disable ceph filesystem snapshot mirror for filesystem %q. %s", filesystem, output)
	}

	logger.Infof("successfully disabled ceph filesystem snapshot mirror for filesystem %q", filesystem)
	return nil
}

func AddSnapshotSchedule(context *clusterd.Context, clusterInfo *ClusterInfo, path, interval, startTime, filesystem string) error {
	logger.Infof("adding snapshot schedule every %q to ceph filesystem %q on path %q", interval, filesystem, path)

	args := []string{"fs", "snap-schedule", "add", path, interval}
	if startTime != "" {
		args = append(args, startTime)
	}
	args = append(args, fmt.Sprintf("fs=%s", filesystem))
	cmd := NewCephCommand(context, clusterInfo, args)
	cmd.JsonOutput = false
	// Example command: "ceph fs snap-schedule add / 4d fs=myfs2"

	// CHANGE time for "2014-01-09T21:48:00" IF interval
	// Run command
	output, err := cmd.Run()
	if err != nil {
		if code, ok := exec.ExitStatus(err); ok && code != int(syscall.EEXIST) {
			return errors.Wrapf(err, "failed to add snapshot schedule every %q to ceph filesystem %q on path %q. %s", interval, filesystem, path, output)
		}
	}

	logger.Infof("successfully added snapshot schedule every %q to ceph filesystem %q on path %q", interval, filesystem, path)
	return nil
}

func AddSnapshotScheduleRetention(context *clusterd.Context, clusterInfo *ClusterInfo, path, duration, filesystem string) error {
	logger.Infof("adding snapshot schedule retention %s to ceph filesystem %q on path %q", duration, filesystem, path)

	// Example command: "ceph fs snap-schedule retention add / d 1 fs=myfs2"
	args := []string{"fs", "snap-schedule", "retention", "add", path, duration, fmt.Sprintf("fs=%s", filesystem)}
	cmd := NewCephCommand(context, clusterInfo, args)
	cmd.JsonOutput = false

	// Run command
	output, err := cmd.Run()
	if err != nil {
		if code, ok := exec.ExitStatus(err); ok && code == int(syscall.ENOENT) {
			logger.Warningf("snapshot schedule retention %s already exists for filesystem %q on path %q. %s", duration, filesystem, path, output)
		} else {
			return errors.Wrapf(err, "failed to add snapshot schedule retention %s to ceph filesystem %q on path %q. %s", duration, filesystem, path, output)
		}
	}

	logger.Infof("successfully added snapshot schedule retention %s to ceph filesystem %q on path %q", duration, filesystem, path)
	return nil
}

func GetSnapshotScheduleStatus(context *clusterd.Context, clusterInfo *ClusterInfo, filesystem string) ([]cephv1.FilesystemSnapshotSchedulesSpec, error) {
	logger.Infof("retrieving snapshot schedule status for ceph filesystem %q", filesystem)

	args := []string{"fs", "snap-schedule", "status", "/", "recursive=true", fmt.Sprintf("--fs=%s", filesystem)}
	cmd := NewCephCommand(context, clusterInfo, args)

	// Run command
	output, err := cmd.Run()
	if err != nil {
		return nil, errors.Wrapf(err, "failed to retrieve snapshot schedule status for ceph filesystem %q. %s", filesystem, output)
	}

	// Unmarshal JSON into Go struct
	var filesystemSnapshotSchedulesStatusSpec []cephv1.FilesystemSnapshotSchedulesSpec

	/* Replace new line since the command outputs a new line first and breaks the json parsing...
	[root@rook-ceph-operator-75c6d6bbfc-wqlnc /]# ceph --connect-timeout=15 --cluster=rook-ceph --conf=/var/lib/rook/rook-ceph/rook-ceph.config --name=client.admin --keyring=/var/lib/rook/rook-ceph/client.admin.keyring --format json fs snap-schedule status /

	[{"fs": "myfs", "subvol": null, "path": "/", "rel_path": "/", "schedule": "24h", "retention": {"h": 24}, "start": "2021-07-01T00:00:00", "created": "2021-07-01T12:19:12", "first": null, "last": null, "last_pruned": null, "created_count": 0, "pruned_count": 0, "active": true},{"fs": "myfs", "subvol": null, "path": "/", "rel_path": "/", "schedule": "25h", "retention": {"h": 24}, "start": "2021-07-01T00:00:00", "created": "2021-07-01T12:31:25", "first": null, "last": null, "last_pruned": null, "created_count": 0, "pruned_count": 0, "active": true}]
	*/
	if err := json.Unmarshal([]byte(strings.ReplaceAll(string(output), "\n", "")), &filesystemSnapshotSchedulesStatusSpec); err != nil {
		return nil, errors.Wrap(err, "failed to unmarshal filesystem mirror snapshot schedule status response")
	}

	logger.Infof("successfully retrieved snapshot schedule status for ceph filesystem %q", filesystem)
	return filesystemSnapshotSchedulesStatusSpec, nil
}

// ImportFSMirrorBootstrapPeer add a mirror peer in the cephfs-mirror configuration
func ImportFSMirrorBootstrapPeer(context *clusterd.Context, clusterInfo *ClusterInfo, fsName, token string) error {
	logger.Infof("importing cephfs bootstrap peer token for filesystem %q", fsName)

	// Build command
	args := []string{"fs", "snapshot", "mirror", "peer_bootstrap", "import", fsName, token}
	cmd := NewCephCommand(context, clusterInfo, args)

	// Run command
	output, err := cmd.Run()
	if err != nil {
		return errors.Wrapf(err, "failed to import cephfs-mirror peer token for filesystem %q. %s", fsName, output)
	}

	logger.Infof("successfully imported cephfs-mirror peer for filesystem %q", fsName)
	return nil
}

// CreateFSMirrorBootstrapPeer add a mirror peer in the cephfs-mirror configuration
func CreateFSMirrorBootstrapPeer(context *clusterd.Context, clusterInfo *ClusterInfo, fsName string) ([]byte, error) {
	logger.Infof("create cephfs-mirror bootstrap peer token for filesystem %q", fsName)

	// Build command
	args := []string{"fs", "snapshot", "mirror", "peer_bootstrap", "create", fsName, "client.mirror", clusterInfo.FSID}
	cmd := NewCephCommand(context, clusterInfo, args)

	// Run command
	output, err := cmd.Run()
	if err != nil {
		return nil, errors.Wrapf(err, "failed to create cephfs-mirror peer token for filesystem %q. %s", fsName, output)
	}

	// Unmarshal JSON into Go struct
	var bootstrapPeerToken BootstrapPeerToken
	if err := json.Unmarshal(output, &bootstrapPeerToken); err != nil {
		return nil, errors.Wrapf(err, "failed to unmarshal cephfs-mirror peer token create response. %s", output)
	}

	logger.Infof("successfully created cephfs-mirror bootstrap peer token for filesystem %q", fsName)
	return []byte(bootstrapPeerToken.Token), nil
}

// GetFSMirrorDaemonStatus returns the mirroring status of a given filesystem
func GetFSMirrorDaemonStatus(context *clusterd.Context, clusterInfo *ClusterInfo, fsName string) ([]cephv1.FilesystemMirroringInfo, error) {
	// Using Debug level since this is called in a recurrent go routine
	logger.Debugf("retrieving filesystem mirror status for filesystem %q", fsName)

	// Build command
	args := []string{"fs", "snapshot", "mirror", "daemon", "status", fsName}
	cmd := NewCephCommand(context, clusterInfo, args)

	// Run command
	output, err := cmd.Run()
	if err != nil {
		return nil, errors.Wrapf(err, "failed to retrieve filesystem mirror status for filesystem %q. %s", fsName, output)
	}

	// Unmarshal JSON into Go struct
	var filesystemMirroringInfo []cephv1.FilesystemMirroringInfo
	if err := json.Unmarshal([]byte(output), &filesystemMirroringInfo); err != nil {
		return nil, errors.Wrapf(err, "failed to unmarshal filesystem mirror status response. %q.", string(output))
	}

	logger.Debugf("successfully retrieved filesystem mirror status for filesystem %q", fsName)
	return filesystemMirroringInfo, nil
}
<commit_msg>cephfs-mirror: try to mitigate peer import error<commit_after>/*
Copyright 2021 The Rook 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.
*/

package client

import (
	"encoding/json"
	"fmt"
	"strings"
	"syscall"

	"github.com/pkg/errors"
	cephv1 "github.com/rook/rook/pkg/apis/ceph.rook.io/v1"
	"github.com/rook/rook/pkg/clusterd"
	"github.com/rook/rook/pkg/util/exec"
)

type BootstrapPeerToken struct {
	Token string `json:"token"`
}

// RemoveFilesystemMirrorPeer add a mirror peer in the cephfs-mirror configuration
func RemoveFilesystemMirrorPeer(context *clusterd.Context, clusterInfo *ClusterInfo, peerUUID string) error {
	logger.Infof("removing cephfs-mirror peer %q", peerUUID)

	// Build command
	args := []string{"fs", "snapshot", "mirror", "peer_remove", peerUUID}
	cmd := NewCephCommand(context, clusterInfo, args)

	// Run command
	output, err := cmd.Run()
	if err != nil {
		return errors.Wrapf(err, "failed to remove cephfs-mirror peer for filesystem %q. %s", peerUUID, output)
	}

	logger.Infof("successfully removed cephfs-mirror peer %q", peerUUID)
	return nil
}

// EnableFilesystemSnapshotMirror enables filesystem snapshot mirroring
func EnableFilesystemSnapshotMirror(context *clusterd.Context, clusterInfo *ClusterInfo, filesystem string) error {
	logger.Infof("enabling ceph filesystem snapshot mirror for filesystem %q", filesystem)

	// Build command
	args := []string{"fs", "snapshot", "mirror", "enable", filesystem}
	cmd := NewCephCommand(context, clusterInfo, args)

	// Run command
	output, err := cmd.Run()
	if err != nil {
		return errors.Wrapf(err, "failed to enable ceph filesystem snapshot mirror for filesystem %q. %s", filesystem, output)
	}

	logger.Infof("successfully enabled ceph filesystem snapshot mirror for filesystem %q", filesystem)
	return nil
}

// DisableFilesystemSnapshotMirror enables filesystem snapshot mirroring
func DisableFilesystemSnapshotMirror(context *clusterd.Context, clusterInfo *ClusterInfo, filesystem string) error {
	logger.Infof("disabling ceph filesystem snapshot mirror for filesystem %q", filesystem)

	// Build command
	args := []string{"fs", "snapshot", "mirror", "disable", filesystem}
	cmd := NewCephCommand(context, clusterInfo, args)

	// Run command
	output, err := cmd.Run()
	if err != nil {
		if code, err := exec.ExtractExitCode(err); err == nil && code == int(syscall.ENOTSUP) {
			logger.Debug("filesystem mirroring is not enabled, nothing to disable")
			return nil
		}
		return errors.Wrapf(err, "failed to disable ceph filesystem snapshot mirror for filesystem %q. %s", filesystem, output)
	}

	logger.Infof("successfully disabled ceph filesystem snapshot mirror for filesystem %q", filesystem)
	return nil
}

func AddSnapshotSchedule(context *clusterd.Context, clusterInfo *ClusterInfo, path, interval, startTime, filesystem string) error {
	logger.Infof("adding snapshot schedule every %q to ceph filesystem %q on path %q", interval, filesystem, path)

	args := []string{"fs", "snap-schedule", "add", path, interval}
	if startTime != "" {
		args = append(args, startTime)
	}
	args = append(args, fmt.Sprintf("fs=%s", filesystem))
	cmd := NewCephCommand(context, clusterInfo, args)
	cmd.JsonOutput = false
	// Example command: "ceph fs snap-schedule add / 4d fs=myfs2"

	// CHANGE time for "2014-01-09T21:48:00" IF interval
	// Run command
	output, err := cmd.Run()
	if err != nil {
		if code, ok := exec.ExitStatus(err); ok && code != int(syscall.EEXIST) {
			return errors.Wrapf(err, "failed to add snapshot schedule every %q to ceph filesystem %q on path %q. %s", interval, filesystem, path, output)
		}
	}

	logger.Infof("successfully added snapshot schedule every %q to ceph filesystem %q on path %q", interval, filesystem, path)
	return nil
}

func AddSnapshotScheduleRetention(context *clusterd.Context, clusterInfo *ClusterInfo, path, duration, filesystem string) error {
	logger.Infof("adding snapshot schedule retention %s to ceph filesystem %q on path %q", duration, filesystem, path)

	// Example command: "ceph fs snap-schedule retention add / d 1 fs=myfs2"
	args := []string{"fs", "snap-schedule", "retention", "add", path, duration, fmt.Sprintf("fs=%s", filesystem)}
	cmd := NewCephCommand(context, clusterInfo, args)
	cmd.JsonOutput = false

	// Run command
	output, err := cmd.Run()
	if err != nil {
		if code, ok := exec.ExitStatus(err); ok && code == int(syscall.ENOENT) {
			logger.Warningf("snapshot schedule retention %s already exists for filesystem %q on path %q. %s", duration, filesystem, path, output)
		} else {
			return errors.Wrapf(err, "failed to add snapshot schedule retention %s to ceph filesystem %q on path %q. %s", duration, filesystem, path, output)
		}
	}

	logger.Infof("successfully added snapshot schedule retention %s to ceph filesystem %q on path %q", duration, filesystem, path)
	return nil
}

func GetSnapshotScheduleStatus(context *clusterd.Context, clusterInfo *ClusterInfo, filesystem string) ([]cephv1.FilesystemSnapshotSchedulesSpec, error) {
	logger.Infof("retrieving snapshot schedule status for ceph filesystem %q", filesystem)

	args := []string{"fs", "snap-schedule", "status", "/", "recursive=true", fmt.Sprintf("--fs=%s", filesystem)}
	cmd := NewCephCommand(context, clusterInfo, args)

	// Run command
	output, err := cmd.Run()
	if err != nil {
		return nil, errors.Wrapf(err, "failed to retrieve snapshot schedule status for ceph filesystem %q. %s", filesystem, output)
	}

	// Unmarshal JSON into Go struct
	var filesystemSnapshotSchedulesStatusSpec []cephv1.FilesystemSnapshotSchedulesSpec

	/* Replace new line since the command outputs a new line first and breaks the json parsing...
	[root@rook-ceph-operator-75c6d6bbfc-wqlnc /]# ceph --connect-timeout=15 --cluster=rook-ceph --conf=/var/lib/rook/rook-ceph/rook-ceph.config --name=client.admin --keyring=/var/lib/rook/rook-ceph/client.admin.keyring --format json fs snap-schedule status /

	[{"fs": "myfs", "subvol": null, "path": "/", "rel_path": "/", "schedule": "24h", "retention": {"h": 24}, "start": "2021-07-01T00:00:00", "created": "2021-07-01T12:19:12", "first": null, "last": null, "last_pruned": null, "created_count": 0, "pruned_count": 0, "active": true},{"fs": "myfs", "subvol": null, "path": "/", "rel_path": "/", "schedule": "25h", "retention": {"h": 24}, "start": "2021-07-01T00:00:00", "created": "2021-07-01T12:31:25", "first": null, "last": null, "last_pruned": null, "created_count": 0, "pruned_count": 0, "active": true}]
	*/
	if err := json.Unmarshal([]byte(strings.ReplaceAll(string(output), "\n", "")), &filesystemSnapshotSchedulesStatusSpec); err != nil {
		return nil, errors.Wrap(err, "failed to unmarshal filesystem mirror snapshot schedule status response")
	}

	logger.Infof("successfully retrieved snapshot schedule status for ceph filesystem %q", filesystem)
	return filesystemSnapshotSchedulesStatusSpec, nil
}

// ImportFSMirrorBootstrapPeer add a mirror peer in the cephfs-mirror configuration
func ImportFSMirrorBootstrapPeer(context *clusterd.Context, clusterInfo *ClusterInfo, fsName, token string) error {
	logger.Infof("importing cephfs bootstrap peer token for filesystem %q", fsName)

	// Build command
	args := []string{"fs", "snapshot", "mirror", "peer_bootstrap", "import", fsName, strings.TrimSpace(token)}
	cmd := NewCephCommand(context, clusterInfo, args)
	cmd.JsonOutput = false

	// Run command
	output, err := cmd.Run()
	if err != nil {
		return errors.Wrapf(err, "failed to import cephfs-mirror peer token for filesystem %q. %s", fsName, output)
	}

	logger.Infof("successfully imported cephfs-mirror peer for filesystem %q", fsName)
	return nil
}

// CreateFSMirrorBootstrapPeer add a mirror peer in the cephfs-mirror configuration
func CreateFSMirrorBootstrapPeer(context *clusterd.Context, clusterInfo *ClusterInfo, fsName string) ([]byte, error) {
	logger.Infof("create cephfs-mirror bootstrap peer token for filesystem %q", fsName)

	// Build command
	args := []string{"fs", "snapshot", "mirror", "peer_bootstrap", "create", fsName, "client.mirror", clusterInfo.FSID}
	cmd := NewCephCommand(context, clusterInfo, args)

	// Run command
	output, err := cmd.Run()
	if err != nil {
		return nil, errors.Wrapf(err, "failed to create cephfs-mirror peer token for filesystem %q. %s", fsName, output)
	}

	// Unmarshal JSON into Go struct
	var bootstrapPeerToken BootstrapPeerToken
	if err := json.Unmarshal(output, &bootstrapPeerToken); err != nil {
		return nil, errors.Wrapf(err, "failed to unmarshal cephfs-mirror peer token create response. %s", output)
	}

	logger.Infof("successfully created cephfs-mirror bootstrap peer token for filesystem %q", fsName)
	return []byte(bootstrapPeerToken.Token), nil
}

// GetFSMirrorDaemonStatus returns the mirroring status of a given filesystem
func GetFSMirrorDaemonStatus(context *clusterd.Context, clusterInfo *ClusterInfo, fsName string) ([]cephv1.FilesystemMirroringInfo, error) {
	// Using Debug level since this is called in a recurrent go routine
	logger.Debugf("retrieving filesystem mirror status for filesystem %q", fsName)

	// Build command
	args := []string{"fs", "snapshot", "mirror", "daemon", "status", fsName}
	cmd := NewCephCommand(context, clusterInfo, args)

	// Run command
	output, err := cmd.Run()
	if err != nil {
		return nil, errors.Wrapf(err, "failed to retrieve filesystem mirror status for filesystem %q. %s", fsName, output)
	}

	// Unmarshal JSON into Go struct
	var filesystemMirroringInfo []cephv1.FilesystemMirroringInfo
	if err := json.Unmarshal([]byte(output), &filesystemMirroringInfo); err != nil {
		return nil, errors.Wrapf(err, "failed to unmarshal filesystem mirror status response. %q.", string(output))
	}

	logger.Debugf("successfully retrieved filesystem mirror status for filesystem %q", fsName)
	return filesystemMirroringInfo, nil
}
<|endoftext|>