<commit_before>package service_test

import (
	"fmt"
	"strings"
	"time"

	"github.com/pborman/uuid"
	"github.com/pivotal-cf/cf-redis-smoke-tests/redis"
	"github.com/pivotal-cf/cf-redis-smoke-tests/service/reporter"

	"github.com/pivotal-cf-experimental/cf-test-helpers/services"
	smokeTestCF "github.com/pivotal-cf/cf-redis-smoke-tests/cf"

	. "github.com/onsi/ginkgo"
)

var _ = Describe("Redis Service", func() {
	var (
		testCF = smokeTestCF.CF{
			ShortTimeout: time.Minute * 3,
			LongTimeout:  time.Minute * 15,
			RetryBackoff: redisConfig.Retry.Backoff(),
			MaxRetries:   redisConfig.Retry.MaxRetries(),
		}

		retryInterval = time.Second

		appPath             = "../assets/cf-redis-example-app"
		serviceInstanceName string
		appName             string
		planName            string

		context services.Context
	)

	BeforeSuite(func() {
		context = services.NewContext(cfTestConfig, "redis-test")

		createQuotaArgs := []string{
			"-m", "10G",
			"-r", "1000",
			"-s", "100",
			"--allow-paid-service-plans",
		}

		regularContext := context.RegularUserContext()

		beforeSuiteSteps := []*reporter.Step{
			reporter.NewStep(
				"Connect to CloudFoundry",
				testCF.API(cfTestConfig.ApiEndpoint, cfTestConfig.SkipSSLValidation),
			),
			reporter.NewStep(
				"Log in as admin",
				testCF.Auth(cfTestConfig.AdminUser, cfTestConfig.AdminPassword),
			),
			reporter.NewStep(
				"Create 'redis-smoke-tests' quota",
				testCF.CreateQuota("redis-smoke-test-quota", createQuotaArgs...),
			),
			reporter.NewStep(
				fmt.Sprintf("Create '%s' org", cfTestConfig.OrgName),
				testCF.CreateOrg(cfTestConfig.OrgName, "redis-smoke-test-quota"),
			),
			reporter.NewStep(
				fmt.Sprintf("Enable service access for '%s' org", cfTestConfig.OrgName),
				testCF.EnableServiceAccess(cfTestConfig.OrgName, redisConfig.ServiceName),
			),
			reporter.NewStep(
				fmt.Sprintf("Target '%s' org", cfTestConfig.OrgName),
				testCF.TargetOrg(cfTestConfig.OrgName),
			),
			reporter.NewStep(
				fmt.Sprintf("Create '%s' space", cfTestConfig.SpaceName),
				testCF.CreateSpace(cfTestConfig.SpaceName),
			),
			reporter.NewStep(
				fmt.Sprintf("Create user '%s'", regularContext.Username),
				testCF.CreateUser(regularContext.Username, cfTestConfig.ConfigurableTestPassword),
			),
			reporter.NewStep(
				fmt.Sprintf(
					"Assign user '%s' to 'SpaceManager' role for '%s'",
					regularContext.Username,
					cfTestConfig.SpaceName,
				),
				testCF.SetSpaceRole(regularContext.Username, regularContext.Org, cfTestConfig.SpaceName, "SpaceManager"),
			),
			reporter.NewStep(
				fmt.Sprintf(
					"Assign user '%s' to 'SpaceDeveloper' role for '%s'",
					regularContext.Username,
					cfTestConfig.SpaceName,
				),
				testCF.SetSpaceRole(regularContext.Username, regularContext.Org, cfTestConfig.SpaceName, "SpaceDeveloper"),
			),
			reporter.NewStep(
				fmt.Sprintf(
					"Assign user '%s' to 'SpaceAuditor' role for '%s'",
					regularContext.Username,
					cfTestConfig.SpaceName,
				),
				testCF.SetSpaceRole(regularContext.Username, regularContext.Org, cfTestConfig.SpaceName, "SpaceAuditor"),
			),
			reporter.NewStep(
				"Log out",
				testCF.Logout(),
			),
		}

		smokeTestReporter.RegisterBeforeSuiteSteps(beforeSuiteSteps)

		for _, task := range beforeSuiteSteps {
			task.Perform()
		}
	})

	BeforeEach(func() {
		regularContext := context.RegularUserContext()
		appName = randomName()
		serviceInstanceName = randomName()

		pushArgs := []string{
			"-m", "256M",
			"-p", appPath,
			"-s", "cflinuxfs2",
			"-no-start",
		}

		specSteps := []*reporter.Step{
			reporter.NewStep(
				fmt.Sprintf("Log in as %s", regularContext.Username),
				testCF.Auth(regularContext.Username, regularContext.Password),
			),
			reporter.NewStep(
				fmt.Sprintf("Target '%s' org and '%s' space", cfTestConfig.OrgName, cfTestConfig.SpaceName),
				testCF.TargetOrgAndSpace(cfTestConfig.OrgName, cfTestConfig.SpaceName),
			),
			reporter.NewStep(
				"Push the redis sample app to Cloud Foundry",
				testCF.Push(appName, pushArgs...),
			),
		}

		smokeTestReporter.ClearSpecSteps()
		smokeTestReporter.RegisterSpecSteps(specSteps)

		for _, task := range specSteps {
			task.Perform()
		}
	})

	AfterEach(func() {
		specSteps := []*reporter.Step{
			reporter.NewStep(
				fmt.Sprintf("Unbind the %q plan instance", planName),
				testCF.UnbindService(appName, serviceInstanceName),
			),
			reporter.NewStep(
				fmt.Sprintf("Delete the %q plan instance", planName),
				testCF.DeleteService(serviceInstanceName),
			),
			reporter.NewStep(
				fmt.Sprintf("Ensure service instance for plan %q has been deleted", planName),
				testCF.EnsureServiceInstanceGone(serviceInstanceName),
			),
			reporter.NewStep(
				"Delete the app",
				testCF.Delete(appName),
			),
			reporter.NewStep(
				"Log out",
				testCF.Logout(),
			),
			reporter.NewStep(
				"Log in as admin",
				testCF.Auth(cfTestConfig.AdminUser, cfTestConfig.AdminPassword),
			),
			reporter.NewStep(
				"Delete security group 'redis-smoke-tests-sg'",
				testCF.DeleteSecurityGroup("redis-smoke-tests-sg"),
			),
			reporter.NewStep(
				"Log out",
				testCF.Logout(),
			),
		}

		smokeTestReporter.RegisterSpecSteps(specSteps)

		for _, task := range specSteps {
			task.Perform()
		}
	})

	AfterSuite(func() {
		regularContext := context.RegularUserContext()

		afterSuiteSteps := []*reporter.Step{
			reporter.NewStep(
				"Connect to CloudFoundry",
				testCF.API(cfTestConfig.ApiEndpoint, cfTestConfig.SkipSSLValidation),
			),
			reporter.NewStep(
				"Log in as admin",
				testCF.Auth(cfTestConfig.AdminUser, cfTestConfig.AdminPassword),
			),
			reporter.NewStep(
				fmt.Sprintf("Target '%s' org and '%s' space", cfTestConfig.OrgName, cfTestConfig.SpaceName),
				testCF.TargetOrgAndSpace(cfTestConfig.OrgName, cfTestConfig.SpaceName),
			),
			reporter.NewStep(
				"Ensure no service-instances left",
				testCF.EnsureAllServiceInstancesGone(),
			),
			reporter.NewStep(
				fmt.Sprintf("Delete user '%s'", regularContext.Username),
				testCF.DeleteUser(regularContext.Username),
			),
			reporter.NewStep(
				"Log out",
				testCF.Logout(),
			),
		}

		smokeTestReporter.RegisterAfterSuiteSteps(afterSuiteSteps)

		for _, task := range afterSuiteSteps {
			task.Perform()
		}
	})

	AssertLifeCycleBehavior := func(planName string) {
		It(strings.ToUpper(planName)+": create, bind to, write to, read from, unbind, and destroy a service instance", func() {
			regularContext := context.RegularUserContext()

			var skip bool

			uri := fmt.Sprintf("https://%s.%s", appName, cfTestConfig.AppsDomain)
			app := redis.NewApp(uri, testCF.ShortTimeout, retryInterval)

			serviceCreateStep := reporter.NewStep(
				fmt.Sprintf("Create a '%s' plan instance of Redis\n    Please refer to http://docs.pivotal.io/redis/smoke-tests.html for more help on diagnosing this issue", planName),
				testCF.CreateService(redisConfig.ServiceName, planName, serviceInstanceName, &skip),
			)

			smokeTestReporter.RegisterSpecSteps([]*reporter.Step{serviceCreateStep})

			specSteps := []*reporter.Step{
				reporter.NewStep(
					fmt.Sprintf("Bind the redis sample app to the '%s' plan instance of Redis", planName),
					testCF.BindService(appName, serviceInstanceName),
				),
				reporter.NewStep(
					"Log in as admin",
					testCF.Auth(cfTestConfig.AdminUser, cfTestConfig.AdminPassword),
				),
				reporter.NewStep(
					fmt.Sprintf("Target '%s' org and '%s' space", cfTestConfig.OrgName, cfTestConfig.SpaceName),
					testCF.TargetOrgAndSpace(cfTestConfig.OrgName, cfTestConfig.SpaceName),
				),
				reporter.NewStep(
					"Create and bind security group for running smoke tests",
					testCF.CreateAndBindSecurityGroup("redis-smoke-tests-sg", appName, cfTestConfig.OrgName, cfTestConfig.SpaceName),
				),
				reporter.NewStep(
					fmt.Sprintf("Log in as %s", regularContext.Username),
					testCF.Auth(regularContext.Username, regularContext.Password),
				),
				reporter.NewStep(
					fmt.Sprintf("Target '%s' org and '%s' space", cfTestConfig.OrgName, cfTestConfig.SpaceName),
					testCF.TargetOrgAndSpace(cfTestConfig.OrgName, cfTestConfig.SpaceName),
				),
				reporter.NewStep(
					"Set the service name of the bound instance as an environment variable for the app",
					testCF.SetEnv(appName, "service_name", serviceInstanceName),
				),
				reporter.NewStep(
					"Start the app",
					testCF.Start(appName),
				),
				reporter.NewStep(
					"Verify that the app is responding",
					app.IsRunning(),
				),
				reporter.NewStep(
					"Write a key/value pair to Redis",
					app.Write("mykey", "myvalue"),
				),
				reporter.NewStep(
					"Read the key/value pair back",
					app.ReadAssert("mykey", "myvalue"),
				),
			}

			smokeTestReporter.RegisterSpecSteps(specSteps)

			serviceCreateStep.Perform()
			serviceCreateStep.Description = fmt.Sprintf("Create a '%s' plan instance of Redis", planName)

			if skip {
				serviceCreateStep.Result = "SKIPPED"
			} else {
				for _, task := range specSteps {
					task.Perform()
				}
			}
		})
	}

	Context("for each plan", func() {
		for _, planName = range redisConfig.PlanNames {
			AssertLifeCycleBehavior(planName)
		}
	})
})

func randomName() string {
	return uuid.NewRandom().String()
}
<commit_msg>Do not setenv for service instance name<commit_after>package service_test

import (
	"fmt"
	"strings"
	"time"

	"github.com/pborman/uuid"
	"github.com/pivotal-cf/cf-redis-smoke-tests/redis"
	"github.com/pivotal-cf/cf-redis-smoke-tests/service/reporter"

	"github.com/pivotal-cf-experimental/cf-test-helpers/services"
	smokeTestCF "github.com/pivotal-cf/cf-redis-smoke-tests/cf"

	. "github.com/onsi/ginkgo"
)

var _ = Describe("Redis Service", func() {
	var (
		testCF = smokeTestCF.CF{
			ShortTimeout: time.Minute * 3,
			LongTimeout:  time.Minute * 15,
			RetryBackoff: redisConfig.Retry.Backoff(),
			MaxRetries:   redisConfig.Retry.MaxRetries(),
		}

		retryInterval = time.Second

		appPath             = "../assets/cf-redis-example-app"
		serviceInstanceName string
		appName             string
		planName            string

		context services.Context
	)

	BeforeSuite(func() {
		context = services.NewContext(cfTestConfig, "redis-test")

		createQuotaArgs := []string{
			"-m", "10G",
			"-r", "1000",
			"-s", "100",
			"--allow-paid-service-plans",
		}

		regularContext := context.RegularUserContext()

		beforeSuiteSteps := []*reporter.Step{
			reporter.NewStep(
				"Connect to CloudFoundry",
				testCF.API(cfTestConfig.ApiEndpoint, cfTestConfig.SkipSSLValidation),
			),
			reporter.NewStep(
				"Log in as admin",
				testCF.Auth(cfTestConfig.AdminUser, cfTestConfig.AdminPassword),
			),
			reporter.NewStep(
				"Create 'redis-smoke-tests' quota",
				testCF.CreateQuota("redis-smoke-test-quota", createQuotaArgs...),
			),
			reporter.NewStep(
				fmt.Sprintf("Create '%s' org", cfTestConfig.OrgName),
				testCF.CreateOrg(cfTestConfig.OrgName, "redis-smoke-test-quota"),
			),
			reporter.NewStep(
				fmt.Sprintf("Enable service access for '%s' org", cfTestConfig.OrgName),
				testCF.EnableServiceAccess(cfTestConfig.OrgName, redisConfig.ServiceName),
			),
			reporter.NewStep(
				fmt.Sprintf("Target '%s' org", cfTestConfig.OrgName),
				testCF.TargetOrg(cfTestConfig.OrgName),
			),
			reporter.NewStep(
				fmt.Sprintf("Create '%s' space", cfTestConfig.SpaceName),
				testCF.CreateSpace(cfTestConfig.SpaceName),
			),
			reporter.NewStep(
				fmt.Sprintf("Create user '%s'", regularContext.Username),
				testCF.CreateUser(regularContext.Username, cfTestConfig.ConfigurableTestPassword),
			),
			reporter.NewStep(
				fmt.Sprintf(
					"Assign user '%s' to 'SpaceManager' role for '%s'",
					regularContext.Username,
					cfTestConfig.SpaceName,
				),
				testCF.SetSpaceRole(regularContext.Username, regularContext.Org, cfTestConfig.SpaceName, "SpaceManager"),
			),
			reporter.NewStep(
				fmt.Sprintf(
					"Assign user '%s' to 'SpaceDeveloper' role for '%s'",
					regularContext.Username,
					cfTestConfig.SpaceName,
				),
				testCF.SetSpaceRole(regularContext.Username, regularContext.Org, cfTestConfig.SpaceName, "SpaceDeveloper"),
			),
			reporter.NewStep(
				fmt.Sprintf(
					"Assign user '%s' to 'SpaceAuditor' role for '%s'",
					regularContext.Username,
					cfTestConfig.SpaceName,
				),
				testCF.SetSpaceRole(regularContext.Username, regularContext.Org, cfTestConfig.SpaceName, "SpaceAuditor"),
			),
			reporter.NewStep(
				"Log out",
				testCF.Logout(),
			),
		}

		smokeTestReporter.RegisterBeforeSuiteSteps(beforeSuiteSteps)

		for _, task := range beforeSuiteSteps {
			task.Perform()
		}
	})

	BeforeEach(func() {
		regularContext := context.RegularUserContext()
		appName = randomName()
		serviceInstanceName = randomName()

		pushArgs := []string{
			"-m", "256M",
			"-p", appPath,
			"-s", "cflinuxfs2",
			"-no-start",
		}

		specSteps := []*reporter.Step{
			reporter.NewStep(
				fmt.Sprintf("Log in as %s", regularContext.Username),
				testCF.Auth(regularContext.Username, regularContext.Password),
			),
			reporter.NewStep(
				fmt.Sprintf("Target '%s' org and '%s' space", cfTestConfig.OrgName, cfTestConfig.SpaceName),
				testCF.TargetOrgAndSpace(cfTestConfig.OrgName, cfTestConfig.SpaceName),
			),
			reporter.NewStep(
				"Push the redis sample app to Cloud Foundry",
				testCF.Push(appName, pushArgs...),
			),
		}

		smokeTestReporter.ClearSpecSteps()
		smokeTestReporter.RegisterSpecSteps(specSteps)

		for _, task := range specSteps {
			task.Perform()
		}
	})

	AfterEach(func() {
		specSteps := []*reporter.Step{
			reporter.NewStep(
				fmt.Sprintf("Unbind the %q plan instance", planName),
				testCF.UnbindService(appName, serviceInstanceName),
			),
			reporter.NewStep(
				fmt.Sprintf("Delete the %q plan instance", planName),
				testCF.DeleteService(serviceInstanceName),
			),
			reporter.NewStep(
				fmt.Sprintf("Ensure service instance for plan %q has been deleted", planName),
				testCF.EnsureServiceInstanceGone(serviceInstanceName),
			),
			reporter.NewStep(
				"Delete the app",
				testCF.Delete(appName),
			),
			reporter.NewStep(
				"Log out",
				testCF.Logout(),
			),
			reporter.NewStep(
				"Log in as admin",
				testCF.Auth(cfTestConfig.AdminUser, cfTestConfig.AdminPassword),
			),
			reporter.NewStep(
				"Delete security group 'redis-smoke-tests-sg'",
				testCF.DeleteSecurityGroup("redis-smoke-tests-sg"),
			),
			reporter.NewStep(
				"Log out",
				testCF.Logout(),
			),
		}

		smokeTestReporter.RegisterSpecSteps(specSteps)

		for _, task := range specSteps {
			task.Perform()
		}
	})

	AfterSuite(func() {
		regularContext := context.RegularUserContext()

		afterSuiteSteps := []*reporter.Step{
			reporter.NewStep(
				"Connect to CloudFoundry",
				testCF.API(cfTestConfig.ApiEndpoint, cfTestConfig.SkipSSLValidation),
			),
			reporter.NewStep(
				"Log in as admin",
				testCF.Auth(cfTestConfig.AdminUser, cfTestConfig.AdminPassword),
			),
			reporter.NewStep(
				fmt.Sprintf("Target '%s' org and '%s' space", cfTestConfig.OrgName, cfTestConfig.SpaceName),
				testCF.TargetOrgAndSpace(cfTestConfig.OrgName, cfTestConfig.SpaceName),
			),
			reporter.NewStep(
				"Ensure no service-instances left",
				testCF.EnsureAllServiceInstancesGone(),
			),
			reporter.NewStep(
				fmt.Sprintf("Delete user '%s'", regularContext.Username),
				testCF.DeleteUser(regularContext.Username),
			),
			reporter.NewStep(
				"Log out",
				testCF.Logout(),
			),
		}

		smokeTestReporter.RegisterAfterSuiteSteps(afterSuiteSteps)

		for _, task := range afterSuiteSteps {
			task.Perform()
		}
	})

	AssertLifeCycleBehavior := func(planName string) {
		It(strings.ToUpper(planName)+": create, bind to, write to, read from, unbind, and destroy a service instance", func() {
			regularContext := context.RegularUserContext()

			var skip bool

			uri := fmt.Sprintf("https://%s.%s", appName, cfTestConfig.AppsDomain)
			app := redis.NewApp(uri, testCF.ShortTimeout, retryInterval)

			serviceCreateStep := reporter.NewStep(
				fmt.Sprintf("Create a '%s' plan instance of Redis\n    Please refer to http://docs.pivotal.io/redis/smoke-tests.html for more help on diagnosing this issue", planName),
				testCF.CreateService(redisConfig.ServiceName, planName, serviceInstanceName, &skip),
			)

			smokeTestReporter.RegisterSpecSteps([]*reporter.Step{serviceCreateStep})

			specSteps := []*reporter.Step{
				reporter.NewStep(
					fmt.Sprintf("Bind the redis sample app to the '%s' plan instance of Redis", planName),
					testCF.BindService(appName, serviceInstanceName),
				),
				reporter.NewStep(
					"Log in as admin",
					testCF.Auth(cfTestConfig.AdminUser, cfTestConfig.AdminPassword),
				),
				reporter.NewStep(
					fmt.Sprintf("Target '%s' org and '%s' space", cfTestConfig.OrgName, cfTestConfig.SpaceName),
					testCF.TargetOrgAndSpace(cfTestConfig.OrgName, cfTestConfig.SpaceName),
				),
				reporter.NewStep(
					"Create and bind security group for running smoke tests",
					testCF.CreateAndBindSecurityGroup("redis-smoke-tests-sg", appName, cfTestConfig.OrgName, cfTestConfig.SpaceName),
				),
				reporter.NewStep(
					fmt.Sprintf("Log in as %s", regularContext.Username),
					testCF.Auth(regularContext.Username, regularContext.Password),
				),
				reporter.NewStep(
					fmt.Sprintf("Target '%s' org and '%s' space", cfTestConfig.OrgName, cfTestConfig.SpaceName),
					testCF.TargetOrgAndSpace(cfTestConfig.OrgName, cfTestConfig.SpaceName),
				),
				reporter.NewStep(
					"Start the app",
					testCF.Start(appName),
				),
				reporter.NewStep(
					"Verify that the app is responding",
					app.IsRunning(),
				),
				reporter.NewStep(
					"Write a key/value pair to Redis",
					app.Write("mykey", "myvalue"),
				),
				reporter.NewStep(
					"Read the key/value pair back",
					app.ReadAssert("mykey", "myvalue"),
				),
			}

			smokeTestReporter.RegisterSpecSteps(specSteps)

			serviceCreateStep.Perform()
			serviceCreateStep.Description = fmt.Sprintf("Create a '%s' plan instance of Redis", planName)

			if skip {
				serviceCreateStep.Result = "SKIPPED"
			} else {
				for _, task := range specSteps {
					task.Perform()
				}
			}
		})
	}

	Context("for each plan", func() {
		for _, planName = range redisConfig.PlanNames {
			AssertLifeCycleBehavior(planName)
		}
	})
})

func randomName() string {
	return uuid.NewRandom().String()
}
<|endoftext|>


<commit_before>/*
 *
 * k6 - a next-generation load testing tool
 * Copyright (C) 2019 Load Impact
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

package executor

import (
	"context"
	"sync"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	null "gopkg.in/guregu/null.v3"

	"github.com/loadimpact/k6/lib"
	"github.com/loadimpact/k6/lib/types"
)

func getTestPerVUIterationsConfig() PerVUIterationsConfig {
	return PerVUIterationsConfig{
		VUs:         null.IntFrom(10),
		Iterations:  null.IntFrom(100),
		MaxDuration: types.NullDurationFrom(5 * time.Second),
	}
}

func TestPerVUIterations(t *testing.T) {
	t.Parallel()
	var result sync.Map
	es := lib.NewExecutionState(lib.Options{}, 10, 50)
	var ctx, cancel, executor, _ = setupExecutor(
		t, getTestPerVUIterationsConfig(), es,
		simpleRunner(func(ctx context.Context) error {
			state := lib.GetState(ctx)
			currIter, _ := result.LoadOrStore(state.Vu, uint64(0))
			result.Store(state.Vu, currIter.(uint64)+1)
			return nil
		}),
	)
	defer cancel()
	err := executor.Run(ctx, nil)
	require.NoError(t, err)

	var totalIters uint64
	result.Range(func(key, value interface{}) bool {
		vuIters := value.(uint64)
		assert.Equal(t, uint64(100), vuIters)
		totalIters += vuIters
		return true
	})
	assert.Equal(t, uint64(1000), totalIters)
}
<commit_msg>Add PerVUIterations executor work splitting test<commit_after>/*
 *
 * k6 - a next-generation load testing tool
 * Copyright (C) 2019 Load Impact
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

package executor

import (
	"context"
	"sync"
	"sync/atomic"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	null "gopkg.in/guregu/null.v3"

	"github.com/loadimpact/k6/lib"
	"github.com/loadimpact/k6/lib/types"
)

func getTestPerVUIterationsConfig() PerVUIterationsConfig {
	return PerVUIterationsConfig{
		VUs:         null.IntFrom(10),
		Iterations:  null.IntFrom(100),
		MaxDuration: types.NullDurationFrom(3 * time.Second),
	}
}

// Baseline test
func TestPerVUIterationsRun(t *testing.T) {
	t.Parallel()
	var result sync.Map
	es := lib.NewExecutionState(lib.Options{}, 10, 50)
	var ctx, cancel, executor, _ = setupExecutor(
		t, getTestPerVUIterationsConfig(), es,
		simpleRunner(func(ctx context.Context) error {
			state := lib.GetState(ctx)
			currIter, _ := result.LoadOrStore(state.Vu, uint64(0))
			result.Store(state.Vu, currIter.(uint64)+1)
			return nil
		}),
	)
	defer cancel()
	err := executor.Run(ctx, nil)
	require.NoError(t, err)

	var totalIters uint64
	result.Range(func(key, value interface{}) bool {
		vuIters := value.(uint64)
		assert.Equal(t, uint64(100), vuIters)
		totalIters += vuIters
		return true
	})
	assert.Equal(t, uint64(1000), totalIters)
}

// Test that when one VU "slows down", others will *not* pick up the workload.
// This is the reverse behavior of the SharedIterations executor.
func TestPerVUIterationsRunVariableVU(t *testing.T) {
	t.Parallel()
	var (
		result   sync.Map
		slowVUID int64
	)
	es := lib.NewExecutionState(lib.Options{}, 10, 50)
	var ctx, cancel, executor, _ = setupExecutor(
		t, getTestPerVUIterationsConfig(), es,
		simpleRunner(func(ctx context.Context) error {
			state := lib.GetState(ctx)
			// Pick one VU randomly and always slow it down.
			sid := atomic.LoadInt64(&slowVUID)
			if sid == int64(0) {
				atomic.StoreInt64(&slowVUID, state.Vu)
			}
			if sid == state.Vu {
				time.Sleep(200 * time.Millisecond)
			}
			currIter, _ := result.LoadOrStore(state.Vu, uint64(0))
			result.Store(state.Vu, currIter.(uint64)+1)
			return nil
		}),
	)
	defer cancel()
	err := executor.Run(ctx, nil)
	require.NoError(t, err)

	val, ok := result.Load(slowVUID)
	assert.True(t, ok)

	var totalIters uint64
	result.Range(func(key, value interface{}) bool {
		vuIters := value.(uint64)
		if key != slowVUID {
			assert.Equal(t, uint64(100), vuIters)
		}
		totalIters += vuIters
		return true
	})

	// The slow VU should complete 16 iterations given these timings,
	// while the rest should equally complete their assigned 100 iterations.
	assert.Equal(t, uint64(16), val)
	assert.Equal(t, uint64(916), totalIters)
}
<|endoftext|>


<commit_before>package radicals

import "testing"

var (
	numRadicals    = 252
	numKanji       = 6355
	radkfileParser = RadkfileParser{}
	kradfileParser = KradfileParser{}
)

func TestRadkfileParser(t *testing.T) {
	got, err := ParseRadkfile("radkfile.utf8")
	if err != nil {
		t.Fatalf("ParseRadkfile: %v", err)
	}
	if len(got.Radicals) != numRadicals {
		t.Fatalf("ParseRadkfile length incorrect: got %d, want %d", len(got.Radicals), numRadicals)
	}
	radkfileParser = got
}

func TestKradfileParser(t *testing.T) {
	got, err := ParseKradfile("kradfile.utf8")
	if err != nil {
		t.Fatalf("ParseKradfile: %v", err)
	}
	if len(got.Kanji) != numKanji {
		t.Fatalf("ParseKradfile length incorrect: got %d, want %d", len(got.Kanji), numKanji)
	}
	kradfileParser = got
}
<commit_msg>start on radicals to kanji test<commit_after>package radicals

import (
	"strings"
	"testing"
)

var (
	numRadicals = 252
	numKanji    = 6355
)

func TestRadkfileParser(t *testing.T) {
	got, err := ParseRadkfile("radkfile.utf8")
	if err != nil {
		t.Fatalf("ParseRadkfile: %v", err)
	}
	if len(got.Radicals) != numRadicals {
		t.Fatalf("ParseRadkfile length incorrect: got %d, want %d", len(got.Radicals), numRadicals)
	}
}

func TestKradfileParser(t *testing.T) {
	got, err := ParseKradfile("kradfile.utf8")
	if err != nil {
		t.Fatalf("ParseKradfile: %v", err)
	}
	if len(got.Kanji) != numKanji {
		t.Fatalf("ParseKradfile length incorrect: got %d, want %d", len(got.Kanji), numKanji)
	}
}

var radicalToKanjiTests = []struct {
	radical string
	kanji   []string
}{
	{"入_2", strings.Split("久込入兩兪叺圦懣杁柩滿疚瞞窩糴裲蹣輛陝魎鳰", "")},
	{"マ_2", strings.Split("桶擬疑凝柔序痛通樋矛勇湧涌予預踊豫舒俑墅慂懋抒揉矜礙糅蛹蹂踴鞣", "")},
}

func sliceEqual(s1, s2 []string) bool {
	if len(s1) != len(s2) {
		return false
	}
	for i, x := range s1 {
		if s2[i] != x {
			return false
		}
	}
	return true
}

func TestRadicalsToKanji(t *testing.T) {
	r, err := ParseRadkfile("radkfile.utf8")
	if err != nil {
		t.Fatalf("ParseRadkfile: %v", err)
	}
	for _, tt := range radicalToKanjiTests {
		if got := r.Radicals[tt.radical]; !sliceEqual(got, tt.kanji) {
			t.Errorf("TestRadicalsToKanji: got %v, want %v", got, tt.kanji)
		}
	}
}
<|endoftext|>


<commit_before>// +build acceptance

package v2

import (
	"os"
	"testing"

	"github.com/rackspace/gophercloud/rackspace/identity/v2/tokens"
	th "github.com/rackspace/gophercloud/testhelper"
)

func TestTokenAuth(t *testing.T) {
	authedClient := createClient(t, true)
	token := authedClient.TokenID

	tenantID := os.Getenv("RS_TENANT_ID")
	if tenantID == "" {
		t.Skip("You must set RS_TENANT_ID environment variable to run this test")
	}

	authOpts := tokens.AuthOptions{}
	authOpts.TenantID = tenantID
	authOpts.TokenID = token

	_, err := tokens.Create(authedClient, authOpts).ExtractToken()
	th.AssertNoErr(t, err)
}
<commit_msg>remove rackspace acceptance test<commit_after><|endoftext|>


<commit_before>// Copyright 2019 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0

package builtinpluginconsts

const (
	nameReferenceFieldSpecs = `
nameReference:
- kind: Deployment
  fieldSpecs:
  - path: spec/scaleTargetRef/name
    kind: HorizontalPodAutoscaler

- kind: ReplicationController
  fieldSpecs:
  - path: spec/scaleTargetRef/name
    kind: HorizontalPodAutoscaler

- kind: ReplicaSet
  fieldSpecs:
  - path: spec/scaleTargetRef/name
    kind: HorizontalPodAutoscaler

- kind: StatefulSet
  fieldSpecs:
  - path: spec/scaleTargetRef/name
    kind: HorizontalPodAutoscaler

- kind: ConfigMap
  version: v1
  fieldSpecs:
  - path: spec/volumes/configMap/name
    version: v1
    kind: Pod
  - path: spec/containers/env/valueFrom/configMapKeyRef/name
    version: v1
    kind: Pod
  - path: spec/initContainers/env/valueFrom/configMapKeyRef/name
    version: v1
    kind: Pod
  - path: spec/containers/envFrom/configMapRef/name
    version: v1
    kind: Pod
  - path: spec/initContainers/envFrom/configMapRef/name
    version: v1
    kind: Pod
  - path: spec/volumes/projected/sources/configMap/name
    version: v1
    kind: Pod
  - path: spec/template/spec/volumes/configMap/name
    kind: Deployment
  - path: spec/template/spec/containers/env/valueFrom/configMapKeyRef/name
    kind: Deployment
  - path: spec/template/spec/initContainers/env/valueFrom/configMapKeyRef/name
    kind: Deployment
  - path: spec/template/spec/containers/envFrom/configMapRef/name
    kind: Deployment
  - path: spec/template/spec/initContainers/envFrom/configMapRef/name
    kind: Deployment
  - path: spec/template/spec/volumes/projected/sources/configMap/name
    kind: Deployment
  - path: spec/template/spec/volumes/configMap/name
    kind: ReplicaSet
  - path: spec/template/spec/containers/env/valueFrom/configMapKeyRef/name
    kind: ReplicaSet
  - path: spec/template/spec/initContainers/env/valueFrom/configMapKeyRef/name
    kind: ReplicaSet
  - path: spec/template/spec/containers/envFrom/configMapRef/name
    kind: ReplicaSet
  - path: spec/template/spec/initContainers/envFrom/configMapRef/name
    kind: ReplicaSet
  - path: spec/template/spec/volumes/projected/sources/configMap/name
    kind: ReplicaSet
  - path: spec/template/spec/volumes/configMap/name
    kind: DaemonSet
  - path: spec/template/spec/containers/env/valueFrom/configMapKeyRef/name
    kind: DaemonSet
  - path: spec/template/spec/initContainers/env/valueFrom/configMapKeyRef/name
    kind: DaemonSet
  - path: spec/template/spec/containers/envFrom/configMapRef/name
    kind: DaemonSet
  - path: spec/template/spec/initContainers/envFrom/configMapRef/name
    kind: DaemonSet
  - path: spec/template/spec/volumes/projected/sources/configMap/name
    kind: DaemonSet
  - path: spec/template/spec/volumes/configMap/name
    kind: StatefulSet
  - path: spec/template/spec/containers/env/valueFrom/configMapKeyRef/name
    kind: StatefulSet
  - path: spec/template/spec/initContainers/env/valueFrom/configMapKeyRef/name
    kind: StatefulSet
  - path: spec/template/spec/containers/envFrom/configMapRef/name
    kind: StatefulSet
  - path: spec/template/spec/initContainers/envFrom/configMapRef/name
    kind: StatefulSet
  - path: spec/template/spec/volumes/projected/sources/configMap/name
    kind: StatefulSet
  - path: spec/template/spec/volumes/configMap/name
    kind: Job
  - path: spec/template/spec/containers/env/valueFrom/configMapKeyRef/name
    kind: Job
  - path: spec/template/spec/initContainers/env/valueFrom/configMapKeyRef/name
    kind: Job
  - path: spec/template/spec/containers/envFrom/configMapRef/name
    kind: Job
  - path: spec/template/spec/initContainers/envFrom/configMapRef/name
    kind: Job
  - path: spec/template/spec/volumes/projected/sources/configMap/name
    kind: Job
  - path: spec/jobTemplate/spec/template/spec/volumes/configMap/name
    kind: CronJob
  - path: spec/jobTemplate/spec/template/spec/volumes/projected/sources/configMap/name
    kind: CronJob
  - path: spec/jobTemplate/spec/template/spec/containers/env/valueFrom/configMapKeyRef/name
    kind: CronJob
  - path: spec/jobTemplate/spec/template/spec/initContainers/env/valueFrom/configMapKeyRef/name
    kind: CronJob
  - path: spec/jobTemplate/spec/template/spec/containers/envFrom/configMapRef/name
    kind: CronJob
  - path: spec/jobTemplate/spec/template/spec/initContainers/envFrom/configMapRef/name
    kind: CronJob
  - path: spec/configSource/configMap
    kind: Node

- kind: Secret
  version: v1
  fieldSpecs:
  - path: spec/volumes/secret/secretName
    version: v1
    kind: Pod
  - path: spec/containers/env/valueFrom/secretKeyRef/name
    version: v1
    kind: Pod
  - path: spec/initContainers/env/valueFrom/secretKeyRef/name
    version: v1
    kind: Pod
  - path: spec/containers/envFrom/secretRef/name
    version: v1
    kind: Pod
  - path: spec/initContainers/envFrom/secretRef/name
    version: v1
    kind: Pod
  - path: spec/imagePullSecrets/name
    version: v1
    kind: Pod
  - path: spec/volumes/projected/sources/secret/name
    version: v1
    kind: Pod
  - path: spec/template/spec/volumes/secret/secretName
    kind: Deployment
  - path: spec/template/spec/containers/env/valueFrom/secretKeyRef/name
    kind: Deployment
  - path: spec/template/spec/initContainers/env/valueFrom/secretKeyRef/name
    kind: Deployment
  - path: spec/template/spec/containers/envFrom/secretRef/name
    kind: Deployment
  - path: spec/template/spec/initContainers/envFrom/secretRef/name
    kind: Deployment
  - path: spec/template/spec/imagePullSecrets/name
    kind: Deployment
  - path: spec/template/spec/volumes/projected/sources/secret/name
    kind: Deployment
  - path: spec/template/spec/volumes/secret/secretName
    kind: ReplicaSet
  - path: spec/template/spec/containers/env/valueFrom/secretKeyRef/name
    kind: ReplicaSet
  - path: spec/template/spec/initContainers/env/valueFrom/secretKeyRef/name
    kind: ReplicaSet
  - path: spec/template/spec/containers/envFrom/secretRef/name
    kind: ReplicaSet
  - path: spec/template/spec/initContainers/envFrom/secretRef/name
    kind: ReplicaSet
  - path: spec/template/spec/imagePullSecrets/name
    kind: ReplicaSet
  - path: spec/template/spec/volumes/projected/sources/secret/name
    kind: ReplicaSet
  - path: spec/template/spec/volumes/secret/secretName
    kind: DaemonSet
  - path: spec/template/spec/containers/env/valueFrom/secretKeyRef/name
    kind: DaemonSet
  - path: spec/template/spec/initContainers/env/valueFrom/secretKeyRef/name
    kind: DaemonSet
  - path: spec/template/spec/containers/envFrom/secretRef/name
    kind: DaemonSet
  - path: spec/template/spec/initContainers/envFrom/secretRef/name
    kind: DaemonSet
  - path: spec/template/spec/imagePullSecrets/name
    kind: DaemonSet
  - path: spec/template/spec/volumes/projected/sources/secret/name
    kind: DaemonSet
  - path: spec/template/spec/volumes/secret/secretName
    kind: StatefulSet
  - path: spec/template/spec/containers/env/valueFrom/secretKeyRef/name
    kind: StatefulSet
  - path: spec/template/spec/initContainers/env/valueFrom/secretKeyRef/name
    kind: StatefulSet
  - path: spec/template/spec/containers/envFrom/secretRef/name
    kind: StatefulSet
  - path: spec/template/spec/initContainers/envFrom/secretRef/name
    kind: StatefulSet
  - path: spec/template/spec/imagePullSecrets/name
    kind: StatefulSet
  - path: spec/template/spec/volumes/projected/sources/secret/name
    kind: StatefulSet
  - path: spec/template/spec/volumes/secret/secretName
    kind: Job
  - path: spec/template/spec/containers/env/valueFrom/secretKeyRef/name
    kind: Job
  - path: spec/template/spec/initContainers/env/valueFrom/secretKeyRef/name
    kind: Job
  - path: spec/template/spec/containers/envFrom/secretRef/name
    kind: Job
  - path: spec/template/spec/initContainers/envFrom/secretRef/name
    kind: Job
  - path: spec/template/spec/imagePullSecrets/name
    kind: Job
  - path: spec/template/spec/volumes/projected/sources/secret/name
    kind: Job
  - path: spec/jobTemplate/spec/template/spec/volumes/secret/secretName
    kind: CronJob
  - path: spec/jobTemplate/spec/template/spec/volumes/projected/sources/secret/name
    kind: CronJob
  - path: spec/jobTemplate/spec/template/spec/containers/env/valueFrom/secretKeyRef/name
    kind: CronJob
  - path: spec/jobTemplate/spec/template/spec/initContainers/env/valueFrom/secretKeyRef/name
    kind: CronJob
  - path: spec/jobTemplate/spec/template/spec/containers/envFrom/secretRef/name
    kind: CronJob
  - path: spec/jobTemplate/spec/template/spec/initContainers/envFrom/secretRef/name
    kind: CronJob
  - path: spec/jobTemplate/spec/template/spec/imagePullSecrets/name
    kind: CronJob
  - path: spec/tls/secretName
    kind: Ingress
  - path: metadata/annotations/ingress.kubernetes.io\/auth-secret
    kind: Ingress
  - path: metadata/annotations/nginx.ingress.kubernetes.io\/auth-secret
    kind: Ingress
  - path: metadata/annotations/nginx.ingress.kubernetes.io\/auth-tls-secret
    kind: Ingress
  - path: imagePullSecrets/name
    kind: ServiceAccount
  - path: parameters/secretName
    kind: StorageClass
  - path: parameters/adminSecretName
    kind: StorageClass
  - path: parameters/userSecretName
    kind: StorageClass
  - path: parameters/secretRef
    kind: StorageClass
  - path: rules/resourceNames
    kind: Role
  - path: rules/resourceNames
    kind: ClusterRole
  - path: spec/template/spec/containers/env/valueFrom/secretKeyRef/name
    kind: Service
    group: serving.knative.dev

- kind: Service
  version: v1
  fieldSpecs:
  - path: spec/serviceName
    kind: StatefulSet
    group: apps
  - path: spec/rules/http/paths/backend/serviceName
    kind: Ingress
  - path: spec/backend/serviceName
    kind: Ingress
  - path: spec/service/name
    kind: APIService
    group: apiregistration.k8s.io
  - path: webhooks/clientConfig/service
    kind: ValidatingWebhookConfiguration
    group: admissionregistration.k8s.io
  - path: webhooks/clientConfig/service
    kind: MutatingWebhookConfiguration
    group: admissionregistration.k8s.io

- kind: Role
  group: rbac.authorization.k8s.io
  fieldSpecs:
  - path: roleRef/name
    kind: RoleBinding
    group: rbac.authorization.k8s.io

- kind: ClusterRole
  group: rbac.authorization.k8s.io
  fieldSpecs:
  - path: roleRef/name
    kind: RoleBinding
    group: rbac.authorization.k8s.io
  - path: roleRef/name
    kind: ClusterRoleBinding
    group: rbac.authorization.k8s.io

- kind: ServiceAccount
  version: v1
  fieldSpecs:
  - path: subjects
    kind: RoleBinding
    group: rbac.authorization.k8s.io
  - path: subjects
    kind: ClusterRoleBinding
    group: rbac.authorization.k8s.io
  - path: spec/serviceAccountName
    kind: Pod
  - path: spec/template/spec/serviceAccountName
    kind: StatefulSet
  - path: spec/template/spec/serviceAccountName
    kind: Deployment
  - path: spec/template/spec/serviceAccountName
    kind: ReplicationController
  - path: spec/jobTemplate/spec/template/spec/serviceAccountName
    kind: CronJob
  - path: spec/template/spec/serviceAccountName
    kind: Job
  - path: spec/template/spec/serviceAccountName
    kind: DaemonSet

- kind: PersistentVolumeClaim
  version: v1
  fieldSpecs:
  - path: spec/volumes/persistentVolumeClaim/claimName
    kind: Pod
  - path: spec/template/spec/volumes/persistentVolumeClaim/claimName
    kind: StatefulSet
  - path: spec/template/spec/volumes/persistentVolumeClaim/claimName
    kind: Deployment
  - path: spec/template/spec/volumes/persistentVolumeClaim/claimName
    kind: ReplicationController
  - path: spec/jobTemplate/spec/template/spec/volumes/persistentVolumeClaim/claimName
    kind: CronJob
  - path: spec/template/spec/volumes/persistentVolumeClaim/claimName
    kind: Job
  - path: spec/template/spec/volumes/persistentVolumeClaim/claimName
    kind: DaemonSet

- kind: PersistentVolume
  version: v1
  fieldSpecs:
  - path: spec/volumeName
    kind: PersistentVolumeClaim
  - path: rules/resourceNames
    kind: ClusterRole

- kind: StorageClass
  version: v1
  group: storage.k8s.io
  fieldSpecs:
  - path: spec/storageClassName
    kind: PersistentVolume
  - path: spec/storageClassName
    kind: PersistentVolumeClaim
  - path: spec/volumeClaimTemplates/spec/storageClassName
    kind: StatefulSet

- kind: PriorityClass
  version: v1
  group: scheduling.k8s.io
  fieldSpecs:
  - path: spec/priorityClassName
    kind: Pod
  - path: spec/template/spec/priorityClassName
    kind: StatefulSet
  - path: spec/template/spec/priorityClassName
    kind: Deployment
  - path: spec/template/spec/priorityClassName
    kind: ReplicationController
  - path: spec/jobTemplate/spec/template/spec/priorityClassName
    kind: CronJob
  - path: spec/template/spec/priorityClassName
    kind: Job
  - path: spec/template/spec/priorityClassName
    kind: DaemonSet
`
)
<commit_msg>Add knative API version<commit_after>// Copyright 2019 The Kubernetes Authors.
// SPDX-License-Identifier: Apache-2.0

package builtinpluginconsts

const (
	nameReferenceFieldSpecs = `
nameReference:
- kind: Deployment
  fieldSpecs:
  - path: spec/scaleTargetRef/name
    kind: HorizontalPodAutoscaler

- kind: ReplicationController
  fieldSpecs:
  - path: spec/scaleTargetRef/name
    kind: HorizontalPodAutoscaler

- kind: ReplicaSet
  fieldSpecs:
  - path: spec/scaleTargetRef/name
    kind: HorizontalPodAutoscaler

- kind: StatefulSet
  fieldSpecs:
  - path: spec/scaleTargetRef/name
    kind: HorizontalPodAutoscaler

- kind: ConfigMap
  version: v1
  fieldSpecs:
  - path: spec/volumes/configMap/name
    version: v1
    kind: Pod
  - path: spec/containers/env/valueFrom/configMapKeyRef/name
    version: v1
    kind: Pod
  - path: spec/initContainers/env/valueFrom/configMapKeyRef/name
    version: v1
    kind: Pod
  - path: spec/containers/envFrom/configMapRef/name
    version: v1
    kind: Pod
  - path: spec/initContainers/envFrom/configMapRef/name
    version: v1
    kind: Pod
  - path: spec/volumes/projected/sources/configMap/name
    version: v1
    kind: Pod
  - path: spec/template/spec/volumes/configMap/name
    kind: Deployment
  - path: spec/template/spec/containers/env/valueFrom/configMapKeyRef/name
    kind: Deployment
  - path: spec/template/spec/initContainers/env/valueFrom/configMapKeyRef/name
    kind: Deployment
  - path: spec/template/spec/containers/envFrom/configMapRef/name
    kind: Deployment
  - path: spec/template/spec/initContainers/envFrom/configMapRef/name
    kind: Deployment
  - path: spec/template/spec/volumes/projected/sources/configMap/name
    kind: Deployment
  - path: spec/template/spec/volumes/configMap/name
    kind: ReplicaSet
  - path: spec/template/spec/containers/env/valueFrom/configMapKeyRef/name
    kind: ReplicaSet
  - path: spec/template/spec/initContainers/env/valueFrom/configMapKeyRef/name
    kind: ReplicaSet
  - path: spec/template/spec/containers/envFrom/configMapRef/name
    kind: ReplicaSet
  - path: spec/template/spec/initContainers/envFrom/configMapRef/name
    kind: ReplicaSet
  - path: spec/template/spec/volumes/projected/sources/configMap/name
    kind: ReplicaSet
  - path: spec/template/spec/volumes/configMap/name
    kind: DaemonSet
  - path: spec/template/spec/containers/env/valueFrom/configMapKeyRef/name
    kind: DaemonSet
  - path: spec/template/spec/initContainers/env/valueFrom/configMapKeyRef/name
    kind: DaemonSet
  - path: spec/template/spec/containers/envFrom/configMapRef/name
    kind: DaemonSet
  - path: spec/template/spec/initContainers/envFrom/configMapRef/name
    kind: DaemonSet
  - path: spec/template/spec/volumes/projected/sources/configMap/name
    kind: DaemonSet
  - path: spec/template/spec/volumes/configMap/name
    kind: StatefulSet
  - path: spec/template/spec/containers/env/valueFrom/configMapKeyRef/name
    kind: StatefulSet
  - path: spec/template/spec/initContainers/env/valueFrom/configMapKeyRef/name
    kind: StatefulSet
  - path: spec/template/spec/containers/envFrom/configMapRef/name
    kind: StatefulSet
  - path: spec/template/spec/initContainers/envFrom/configMapRef/name
    kind: StatefulSet
  - path: spec/template/spec/volumes/projected/sources/configMap/name
    kind: StatefulSet
  - path: spec/template/spec/volumes/configMap/name
    kind: Job
  - path: spec/template/spec/containers/env/valueFrom/configMapKeyRef/name
    kind: Job
  - path: spec/template/spec/initContainers/env/valueFrom/configMapKeyRef/name
    kind: Job
  - path: spec/template/spec/containers/envFrom/configMapRef/name
    kind: Job
  - path: spec/template/spec/initContainers/envFrom/configMapRef/name
    kind: Job
  - path: spec/template/spec/volumes/projected/sources/configMap/name
    kind: Job
  - path: spec/jobTemplate/spec/template/spec/volumes/configMap/name
    kind: CronJob
  - path: spec/jobTemplate/spec/template/spec/volumes/projected/sources/configMap/name
    kind: CronJob
  - path: spec/jobTemplate/spec/template/spec/containers/env/valueFrom/configMapKeyRef/name
    kind: CronJob
  - path: spec/jobTemplate/spec/template/spec/initContainers/env/valueFrom/configMapKeyRef/name
    kind: CronJob
  - path: spec/jobTemplate/spec/template/spec/containers/envFrom/configMapRef/name
    kind: CronJob
  - path: spec/jobTemplate/spec/template/spec/initContainers/envFrom/configMapRef/name
    kind: CronJob
  - path: spec/configSource/configMap
    kind: Node

- kind: Secret
  version: v1
  fieldSpecs:
  - path: spec/volumes/secret/secretName
    version: v1
    kind: Pod
  - path: spec/containers/env/valueFrom/secretKeyRef/name
    version: v1
    kind: Pod
  - path: spec/initContainers/env/valueFrom/secretKeyRef/name
    version: v1
    kind: Pod
  - path: spec/containers/envFrom/secretRef/name
    version: v1
    kind: Pod
  - path: spec/initContainers/envFrom/secretRef/name
    version: v1
    kind: Pod
  - path: spec/imagePullSecrets/name
    version: v1
    kind: Pod
  - path: spec/volumes/projected/sources/secret/name
    version: v1
    kind: Pod
  - path: spec/template/spec/volumes/secret/secretName
    kind: Deployment
  - path: spec/template/spec/containers/env/valueFrom/secretKeyRef/name
    kind: Deployment
  - path: spec/template/spec/initContainers/env/valueFrom/secretKeyRef/name
    kind: Deployment
  - path: spec/template/spec/containers/envFrom/secretRef/name
    kind: Deployment
  - path: spec/template/spec/initContainers/envFrom/secretRef/name
    kind: Deployment
  - path: spec/template/spec/imagePullSecrets/name
    kind: Deployment
  - path: spec/template/spec/volumes/projected/sources/secret/name
    kind: Deployment
  - path: spec/template/spec/volumes/secret/secretName
    kind: ReplicaSet
  - path: spec/template/spec/containers/env/valueFrom/secretKeyRef/name
    kind: ReplicaSet
  - path: spec/template/spec/initContainers/env/valueFrom/secretKeyRef/name
    kind: ReplicaSet
  - path: spec/template/spec/containers/envFrom/secretRef/name
    kind: ReplicaSet
  - path: spec/template/spec/initContainers/envFrom/secretRef/name
    kind: ReplicaSet
  - path: spec/template/spec/imagePullSecrets/name
    kind: ReplicaSet
  - path: spec/template/spec/volumes/projected/sources/secret/name
    kind: ReplicaSet
  - path: spec/template/spec/volumes/secret/secretName
    kind: DaemonSet
  - path: spec/template/spec/containers/env/valueFrom/secretKeyRef/name
    kind: DaemonSet
  - path: spec/template/spec/initContainers/env/valueFrom/secretKeyRef/name
    kind: DaemonSet
  - path: spec/template/spec/containers/envFrom/secretRef/name
    kind: DaemonSet
  - path: spec/template/spec/initContainers/envFrom/secretRef/name
    kind: DaemonSet
  - path: spec/template/spec/imagePullSecrets/name
    kind: DaemonSet
  - path: spec/template/spec/volumes/projected/sources/secret/name
    kind: DaemonSet
  - path: spec/template/spec/volumes/secret/secretName
    kind: StatefulSet
  - path: spec/template/spec/containers/env/valueFrom/secretKeyRef/name
    kind: StatefulSet
  - path: spec/template/spec/initContainers/env/valueFrom/secretKeyRef/name
    kind: StatefulSet
  - path: spec/template/spec/containers/envFrom/secretRef/name
    kind: StatefulSet
  - path: spec/template/spec/initContainers/envFrom/secretRef/name
    kind: StatefulSet
  - path: spec/template/spec/imagePullSecrets/name
    kind: StatefulSet
  - path: spec/template/spec/volumes/projected/sources/secret/name
    kind: StatefulSet
  - path: spec/template/spec/volumes/secret/secretName
    kind: Job
  - path: spec/template/spec/containers/env/valueFrom/secretKeyRef/name
    kind: Job
  - path: spec/template/spec/initContainers/env/valueFrom/secretKeyRef/name
    kind: Job
  - path: spec/template/spec/containers/envFrom/secretRef/name
    kind: Job
  - path: spec/template/spec/initContainers/envFrom/secretRef/name
    kind: Job
  - path: spec/template/spec/imagePullSecrets/name
    kind: Job
  - path: spec/template/spec/volumes/projected/sources/secret/name
    kind: Job
  - path: spec/jobTemplate/spec/template/spec/volumes/secret/secretName
    kind: CronJob
  - path: spec/jobTemplate/spec/template/spec/volumes/projected/sources/secret/name
    kind: CronJob
  - path: spec/jobTemplate/spec/template/spec/containers/env/valueFrom/secretKeyRef/name
    kind: CronJob
  - path: spec/jobTemplate/spec/template/spec/initContainers/env/valueFrom/secretKeyRef/name
    kind: CronJob
  - path: spec/jobTemplate/spec/template/spec/containers/envFrom/secretRef/name
    kind: CronJob
  - path: spec/jobTemplate/spec/template/spec/initContainers/envFrom/secretRef/name
    kind: CronJob
  - path: spec/jobTemplate/spec/template/spec/imagePullSecrets/name
    kind: CronJob
  - path: spec/tls/secretName
    kind: Ingress
  - path: metadata/annotations/ingress.kubernetes.io\/auth-secret
    kind: Ingress
  - path: metadata/annotations/nginx.ingress.kubernetes.io\/auth-secret
    kind: Ingress
  - path: metadata/annotations/nginx.ingress.kubernetes.io\/auth-tls-secret
    kind: Ingress
  - path: imagePullSecrets/name
    kind: ServiceAccount
  - path: parameters/secretName
    kind: StorageClass
  - path: parameters/adminSecretName
    kind: StorageClass
  - path: parameters/userSecretName
    kind: StorageClass
  - path: parameters/secretRef
    kind: StorageClass
  - path: rules/resourceNames
    kind: Role
  - path: rules/resourceNames
    kind: ClusterRole
  - path: spec/template/spec/containers/env/valueFrom/secretKeyRef/name
    kind: Service
    group: serving.knative.dev
    version: v1

- kind: Service
  version: v1
  fieldSpecs:
  - path: spec/serviceName
    kind: StatefulSet
    group: apps
  - path: spec/rules/http/paths/backend/serviceName
    kind: Ingress
  - path: spec/backend/serviceName
    kind: Ingress
  - path: spec/service/name
    kind: APIService
    group: apiregistration.k8s.io
  - path: webhooks/clientConfig/service
    kind: ValidatingWebhookConfiguration
    group: admissionregistration.k8s.io
  - path: webhooks/clientConfig/service
    kind: MutatingWebhookConfiguration
    group: admissionregistration.k8s.io

- kind: Role
  group: rbac.authorization.k8s.io
  fieldSpecs:
  - path: roleRef/name
    kind: RoleBinding
    group: rbac.authorization.k8s.io

- kind: ClusterRole
  group: rbac.authorization.k8s.io
  fieldSpecs:
  - path: roleRef/name
    kind: RoleBinding
    group: rbac.authorization.k8s.io
  - path: roleRef/name
    kind: ClusterRoleBinding
    group: rbac.authorization.k8s.io

- kind: ServiceAccount
  version: v1
  fieldSpecs:
  - path: subjects
    kind: RoleBinding
    group: rbac.authorization.k8s.io
  - path: subjects
    kind: ClusterRoleBinding
    group: rbac.authorization.k8s.io
  - path: spec/serviceAccountName
    kind: Pod
  - path: spec/template/spec/serviceAccountName
    kind: StatefulSet
  - path: spec/template/spec/serviceAccountName
    kind: Deployment
  - path: spec/template/spec/serviceAccountName
    kind: ReplicationController
  - path: spec/jobTemplate/spec/template/spec/serviceAccountName
    kind: CronJob
  - path: spec/template/spec/serviceAccountName
    kind: Job
  - path: spec/template/spec/serviceAccountName
    kind: DaemonSet

- kind: PersistentVolumeClaim
  version: v1
  fieldSpecs:
  - path: spec/volumes/persistentVolumeClaim/claimName
    kind: Pod
  - path: spec/template/spec/volumes/persistentVolumeClaim/claimName
    kind: StatefulSet
  - path: spec/template/spec/volumes/persistentVolumeClaim/claimName
    kind: Deployment
  - path: spec/template/spec/volumes/persistentVolumeClaim/claimName
    kind: ReplicationController
  - path: spec/jobTemplate/spec/template/spec/volumes/persistentVolumeClaim/claimName
    kind: CronJob
  - path: spec/template/spec/volumes/persistentVolumeClaim/claimName
    kind: Job
  - path: spec/template/spec/volumes/persistentVolumeClaim/claimName
    kind: DaemonSet

- kind: PersistentVolume
  version: v1
  fieldSpecs:
  - path: spec/volumeName
    kind: PersistentVolumeClaim
  - path: rules/resourceNames
    kind: ClusterRole

- kind: StorageClass
  version: v1
  group: storage.k8s.io
  fieldSpecs:
  - path: spec/storageClassName
    kind: PersistentVolume
  - path: spec/storageClassName
    kind: PersistentVolumeClaim
  - path: spec/volumeClaimTemplates/spec/storageClassName
    kind: StatefulSet

- kind: PriorityClass
  version: v1
  group: scheduling.k8s.io
  fieldSpecs:
  - path: spec/priorityClassName
    kind: Pod
  - path: spec/template/spec/priorityClassName
    kind: StatefulSet
  - path: spec/template/spec/priorityClassName
    kind: Deployment
  - path: spec/template/spec/priorityClassName
    kind: ReplicationController
  - path: spec/jobTemplate/spec/template/spec/priorityClassName
    kind: CronJob
  - path: spec/template/spec/priorityClassName
    kind: Job
  - path: spec/template/spec/priorityClassName
    kind: DaemonSet
`
)
<|endoftext|>


<commit_before>package client_test

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/go-test/deep"
	"github.com/square/spincycle/job-runner/client"
	"github.com/square/spincycle/proto"
)

func TestStartRequest(t *testing.T) {
	// Unsuccessful response status code.
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusBadRequest)
	}))
	c := client.NewJRClient(&http.Client{}, ts.URL)

	err := c.StartRequest(3)
	if err == nil {
		t.Errorf("expected an error but did not get one")
	}
	ts.Close()

	// Successful response status code.
	var path string
	var method string
	ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		path = r.URL.Path
		method = r.Method
		w.WriteHeader(http.StatusOK)
	}))
	c = client.NewJRClient(&http.Client{}, ts.URL)

	err = c.StartRequest(3)
	if err != nil {
		t.Errorf("err = %s, expected nil", err)
	}
	ts.Close()

	expectedPath := "/api/v1/job-chains/3/start"
	if path != expectedPath {
		t.Errorf("url path = %s, expected %s", path, expectedPath)
	}

	if method != "PUT" {
		t.Errorf("request method = %s, expected POST", method)
	}
}

func TestStopRequest(t *testing.T) {
	// Unsuccessful response status code.
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusBadRequest)
	}))
	c := client.NewJRClient(&http.Client{}, ts.URL)

	err := c.StopRequest(3)
	if err == nil {
		t.Errorf("expected an error but did not get one")
	}
	ts.Close()

	// Successful response status code.
	var path string
	var method string
	ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		path = r.URL.Path
		method = r.Method
		w.WriteHeader(http.StatusOK)
	}))
	c = client.NewJRClient(&http.Client{}, ts.URL)

	err = c.StopRequest(3)
	if err != nil {
		t.Errorf("err = %s, expected nil", err)
	}
	ts.Close()

	expectedPath := "/api/v1/job-chains/3/stop"
	if path != expectedPath {
		t.Errorf("url path = %s, expected %s", path, expectedPath)
	}

	if method != "PUT" {
		t.Errorf("request method = %s, expected POST", method)
	}
}

func TestRequestStatus(t *testing.T) {
	// Unsuccessful response status code.
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusBadRequest)
	}))
	c := client.NewJRClient(&http.Client{}, ts.URL)

	_, err := c.RequestStatus(3)
	if err == nil {
		t.Errorf("expected an error but did not get one")
	}
	ts.Close()

	// Successful response status code, but bad payload.
	ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		fmt.Fprintln(w, "baD{json")
	}))
	c = client.NewJRClient(&http.Client{}, ts.URL)

	_, err = c.RequestStatus(3)
	if err == nil {
		t.Errorf("expected an error but did not get one")
	}
	ts.Close()

	// Successful response status code.
	var path string
	var method string
	ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		path = r.URL.Path
		method = r.Method
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		fmt.Fprintln(w, "{\"requestId\":3,\"jobStatuses\":[{\"name\":\"job1\",\"status\":\"job is running...\",\"state\":5}]}")
	}))
	c = client.NewJRClient(&http.Client{}, ts.URL)

	status, err := c.RequestStatus(3)
	if err != nil {
		t.Errorf("err = %s, expected nil", err)
	}
	ts.Close()

	expectedPath := "/api/v1/job-chains/3/status"
	if path != expectedPath {
		t.Errorf("url path = %s, expected %s", path, expectedPath)
	}

	if method != "GET" {
		t.Errorf("request method = %s, expected POST", method)
	}

	expectedStatus := &proto.JobChainStatus{
		JobStatuses: proto.JobStatuses{
			proto.JobStatus{
				Name:   "job1",
				Status: "job is running...",
				State:  5,
			},
		},
		RequestId: 3,
	}
	if diff := deep.Equal(status, expectedStatus); diff != nil {
		t.Error(diff)
	}
}

func TestNewJobChain(t *testing.T) {
	// Make a job chain.
	jc := proto.JobChain{
		RequestId: 3,
		Jobs: map[string]proto.Job{
			"job1": proto.Job{
				Name:  "job1",
				Type:  "type1",
				Bytes: []byte{1, 2, 3, 4, 5},
				State: 3,
			},
		},
		AdjacencyList: map[string][]string{
			"job1": []string{},
		},
		State: 4,
	}

	// Unsuccessful response status code.
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusBadRequest)
	}))
	c := client.NewJRClient(&http.Client{}, ts.URL)

	err := c.NewJobChain(jc)
	if err == nil {
		t.Errorf("expected an error but did not get one")
	}
	ts.Close()

	// Successful response status code.
	var path string
	var method string
	var payload proto.JobChain
	ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		path = r.URL.Path
		method = r.Method

		// Get the request payload.
		body, err := ioutil.ReadAll(r.Body)
		if err != nil {
			t.Fatal(err)
		}
		err = json.Unmarshal(body, &payload)
		if err != nil {
			t.Fatal(err)
		}

		w.WriteHeader(http.StatusOK)
	}))
	c = client.NewJRClient(&http.Client{}, ts.URL)

	err = c.NewJobChain(jc)
	if err != nil {
		t.Errorf("err = %s, expected nil", err)
	}
	ts.Close()

	expectedPath := "/api/v1/job-chains"
	if path != expectedPath {
		t.Errorf("url path = %s, expected %s", path, expectedPath)
	}

	if method != "POST" {
		t.Errorf("request method = %s, expected POST", method)
	}

	if diff := deep.Equal(payload, jc); diff != nil {
		t.Error(diff)
	}
}
<commit_msg>gofmt -s fix<commit_after>package client_test

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/go-test/deep"
	"github.com/square/spincycle/job-runner/client"
	"github.com/square/spincycle/proto"
)

func TestStartRequest(t *testing.T) {
	// Unsuccessful response status code.
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusBadRequest)
	}))
	c := client.NewJRClient(&http.Client{}, ts.URL)

	err := c.StartRequest(3)
	if err == nil {
		t.Errorf("expected an error but did not get one")
	}
	ts.Close()

	// Successful response status code.
	var path string
	var method string
	ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		path = r.URL.Path
		method = r.Method
		w.WriteHeader(http.StatusOK)
	}))
	c = client.NewJRClient(&http.Client{}, ts.URL)

	err = c.StartRequest(3)
	if err != nil {
		t.Errorf("err = %s, expected nil", err)
	}
	ts.Close()

	expectedPath := "/api/v1/job-chains/3/start"
	if path != expectedPath {
		t.Errorf("url path = %s, expected %s", path, expectedPath)
	}

	if method != "PUT" {
		t.Errorf("request method = %s, expected POST", method)
	}
}

func TestStopRequest(t *testing.T) {
	// Unsuccessful response status code.
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusBadRequest)
	}))
	c := client.NewJRClient(&http.Client{}, ts.URL)

	err := c.StopRequest(3)
	if err == nil {
		t.Errorf("expected an error but did not get one")
	}
	ts.Close()

	// Successful response status code.
	var path string
	var method string
	ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		path = r.URL.Path
		method = r.Method
		w.WriteHeader(http.StatusOK)
	}))
	c = client.NewJRClient(&http.Client{}, ts.URL)

	err = c.StopRequest(3)
	if err != nil {
		t.Errorf("err = %s, expected nil", err)
	}
	ts.Close()

	expectedPath := "/api/v1/job-chains/3/stop"
	if path != expectedPath {
		t.Errorf("url path = %s, expected %s", path, expectedPath)
	}

	if method != "PUT" {
		t.Errorf("request method = %s, expected POST", method)
	}
}

func TestRequestStatus(t *testing.T) {
	// Unsuccessful response status code.
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusBadRequest)
	}))
	c := client.NewJRClient(&http.Client{}, ts.URL)

	_, err := c.RequestStatus(3)
	if err == nil {
		t.Errorf("expected an error but did not get one")
	}
	ts.Close()

	// Successful response status code, but bad payload.
	ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		fmt.Fprintln(w, "baD{json")
	}))
	c = client.NewJRClient(&http.Client{}, ts.URL)

	_, err = c.RequestStatus(3)
	if err == nil {
		t.Errorf("expected an error but did not get one")
	}
	ts.Close()

	// Successful response status code.
	var path string
	var method string
	ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		path = r.URL.Path
		method = r.Method
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		fmt.Fprintln(w, "{\"requestId\":3,\"jobStatuses\":[{\"name\":\"job1\",\"status\":\"job is running...\",\"state\":5}]}")
	}))
	c = client.NewJRClient(&http.Client{}, ts.URL)

	status, err := c.RequestStatus(3)
	if err != nil {
		t.Errorf("err = %s, expected nil", err)
	}
	ts.Close()

	expectedPath := "/api/v1/job-chains/3/status"
	if path != expectedPath {
		t.Errorf("url path = %s, expected %s", path, expectedPath)
	}

	if method != "GET" {
		t.Errorf("request method = %s, expected POST", method)
	}

	expectedStatus := &proto.JobChainStatus{
		JobStatuses: proto.JobStatuses{
			proto.JobStatus{
				Name:   "job1",
				Status: "job is running...",
				State:  5,
			},
		},
		RequestId: 3,
	}
	if diff := deep.Equal(status, expectedStatus); diff != nil {
		t.Error(diff)
	}
}

func TestNewJobChain(t *testing.T) {
	// Make a job chain.
	jc := proto.JobChain{
		RequestId: 3,
		Jobs: map[string]proto.Job{
			"job1": {
				Name:  "job1",
				Type:  "type1",
				Bytes: []byte{1, 2, 3, 4, 5},
				State: 3,
			},
		},
		AdjacencyList: map[string][]string{
			"job1": {},
		},
		State: 4,
	}

	// Unsuccessful response status code.
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusBadRequest)
	}))
	c := client.NewJRClient(&http.Client{}, ts.URL)

	err := c.NewJobChain(jc)
	if err == nil {
		t.Errorf("expected an error but did not get one")
	}
	ts.Close()

	// Successful response status code.
	var path string
	var method string
	var payload proto.JobChain
	ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		path = r.URL.Path
		method = r.Method

		// Get the request payload.
		body, err := ioutil.ReadAll(r.Body)
		if err != nil {
			t.Fatal(err)
		}
		err = json.Unmarshal(body, &payload)
		if err != nil {
			t.Fatal(err)
		}

		w.WriteHeader(http.StatusOK)
	}))
	c = client.NewJRClient(&http.Client{}, ts.URL)

	err = c.NewJobChain(jc)
	if err != nil {
		t.Errorf("err = %s, expected nil", err)
	}
	ts.Close()

	expectedPath := "/api/v1/job-chains"
	if path != expectedPath {
		t.Errorf("url path = %s, expected %s", path, expectedPath)
	}

	if method != "POST" {
		t.Errorf("request method = %s, expected POST", method)
	}

	if diff := deep.Equal(payload, jc); diff != nil {
		t.Error(diff)
	}
}
<|endoftext|>


<commit_before>package model

import (
	"time"
	"github.com/thanhpk/sutu.shop/ecom/common/auth"
)

type ProductType struct {
	Id string
	Name string
	Description string
	NumverOfView int32
	NumberOfLove int32
	Price int32
	BrandId string
	Category Category
}

type IProductTypeRepository interface {
	Create(*ProductType) string
	Count(search string) string
	List(keyword string, n int32, p int32) []ProductType
	Update(*ProductType) string
	Read(id string) *ProductType
}

type Brand struct {
	Id string
	Name string
	Description string
	LogoImage string
	CoverImage string
}

type IBrandRepository interface {
	Create(*Brand) string
	Count(search string) string
	List(keyword string, n int32, p int32) []Brand
	Update(*Brand) string
	Read(id string) *Brand
}

type VarianceType struct {
	Id string
	Name string
}

type IVarianceTypeRepository interface {
	Create(*VarianceType) string
	Count(search string) string
	List(keyword string, n int32, p int32) []VarianceType
	Update(*VarianceType) string
	Read(id string) *VarianceType
}

type Variance struct {
	Id string
	VarianceId string
	Value string
}

type Product struct {
	Id string
	TypeId string
	Name string
	Price int32
	SalePrice int32
	Description string
	Images []string
	Variances []Variance
}

type IProductRepository interface {
	Create(*Product) string
	Count(search string) string
	List(keyword string, n int32, p int32) []Product
	Update(*Product) string
	Read(id string) *Product
}

const ORDER_PLACED = 0
const ORDER_CONFIRMED = 1
const ORDER_SHIPPING = 2
const ORDER_SUCCESS = 3

type Item struct {
	Product Product
	Quantity int32
}

type Order struct {
	Id string
	Code string
	ShippingAddress Address
	UserIp string
	UserId string
	Status int
	Items []Item
	IsRead bool
	IsPaid bool
	CreateTime time.Time
	LastModifiedTime time.Time
}

type IOrderRepository interface {
	Create(*Order) string
	Count(keyword string) string
	List(keyword string, n int32, p int32) []Order
	Update(*Order) string
	Read(id string) *Order
	Match(code string) *Order
}

type Sale struct {
	Id string
	Name string
	Code string
	StartTime time.Time
	EndTime time.Time
	CoverImage string
	QuanlificationCode string
}

type ISaleRepository interface {
	Cerate(*Sale) string
	Count(keyword string) string
	List(keyword string, n int32, p int32) []Sale
	Update(*Sale) string
	Read(id string) *Sale
	Match(code string) *Sale
}

type Category struct {
	Id string

	Name string
	Path string
	Parent *Category
}

type ICategoryRepository interface {
	Cerate(*Category) string
	Count(keyword string) string
	List(keyword string, n int32, p int32) []Category
	Update(*Category) string
	Read(id string) *Category
	Match(code string) *Category
}

type Address struct {
	Id string
	Phone string
	Address string
}

type IAddressRepository interface {
	Cerate(*Address) string
	Count(keyword string) string
	List(keyword string, n int32, p int32) []Address
	Update(*Address) string
	Read(id string) *Address
	Match(code string) *Address
}

type Customer struct {
	Id string
	Name string
	Email string
	Phone string
	HashedPassword string
	Point int32
	IsAdmin bool
	Username string

	Addresses []Address
}

type Auth interface {
	Authenticate(id string, password string) bool
	CanAccess(user_id string, action string) bool
}

type ICustomerRepository interface {

	Create(*Customer) string
	Count(keyword string) int32
	List(keyword string, n int32, p int32) []Customer
	Update(*Customer) string
	Read(id string) *Customer

	MatchByUsername(string) *Customer
}

<commit_msg>fix product model<commit_after>package model

import (
	"time"
)

type ProductType struct {
	Id string
	Name string
	Description string
	NumverOfView int32
	NumberOfLove int32
	Price int32
	BrandId string
	CategoryId string
}

type IProductTypeMgt interface {

}

type ProductTypeMgt struct {

}

type IProductTypeRepository interface {
	Create(*ProductType) string
	Count(search string) string
	List(keyword string, n int32, p int32) []ProductType
	Update(*ProductType) string
	Read(id string) *ProductType
}

type Brand struct {
	Id string
	Name string
	Description string
	LogoImage string
	CoverImage string
}

type IBrandRepository interface {
	Create(*Brand) string
	Count(search string) string
	List(keyword string, n int32, p int32) []Brand
	Update(*Brand) string
	Read(id string) *Brand
}

type VarianceType struct {
	Id string
	Name string
}

type IVarianceTypeRepository interface {
	Create(*VarianceType) string
	Count(search string) string
	List(keyword string, n int32, p int32) []VarianceType
	Update(*VarianceType) string
	Read(id string) *VarianceType
}

type Variance struct {
	Id string
	VarianceTypeId string
	Value string
}

type Product struct {
	Id string
	Quantity int32
	TypeId string
	Name string
	Price int32
	SalePrice int32
	Description string
	Images []string
	Variances []Variance
}

type IProductRepository interface {
	Create(*Product) string
	Count(search string) string
	List(keyword string, n int32, p int32) []Product
	Update(*Product) string
	Read(id string) *Product
}

const ORDER_PLACED = 0
const ORDER_CONFIRMED = 1
const ORDER_SHIPPING = 2
const ORDER_SUCCESS = 3

type Item struct {
	ProductId string
	Quantity int32
}

type Order struct {
	Id string
	Code string
	ShippingAddressId string
	UserIp string
	UserId string
	Status int
	Items []Item
	IsRead bool
	IsPaid bool
	CreateTime time.Time
	LastModifiedTime time.Time
}

type IOrderRepository interface {
	Create(*Order) string
	Count(keyword string) string
	List(keyword string, n int32, p int32) []Order
	Update(*Order) string
	Read(id string) *Order
	Match(code string) *Order
}

type Sale struct {
	Id string
	Name string
	Code string
	StartTime time.Time
	EndTime time.Time
	CoverImage string
	QuanlificationCode string
}

type ISaleRepository interface {
	Cerate(*Sale) string
	Count(keyword string) string
	List(keyword string, n int32, p int32) []Sale
	Update(*Sale) string
	Read(id string) *Sale
	Match(code string) *Sale
}

type Category struct {
	Id string

	Name string
	Path string
	Parent *Category
}

type ICategoryRepository interface {
	Cerate(*Category) string
	Count(keyword string) string
	List(keyword string, n int32, p int32) []Category
	Update(*Category) string
	Read(id string) *Category
	Match(code string) *Category
}

type Address struct {
	Id string
	Phone string
	Address string
}

type IAddressRepository interface {
	Cerate(*Address) string
	Count(keyword string) string
	List(keyword string, n int32, p int32) []Address
	Update(*Address) string
	Read(id string) *Address
	Match(code string) *Address
}

type Customer struct {
	Id string
	Name string
	Email string
	Phone string
	HashedPassword string
	Point int32
	IsAdmin bool
	Username string

	Addresses []Address
}

type Auth interface {
	Authenticate(id string, password string) bool
	CanAccess(user_id string, action string) bool
}

type ICustomerRepository interface {

	Create(*Customer) string
	Count(keyword string) int32
	List(keyword string, n int32, p int32) []Customer
	Update(*Customer) string
	Read(id string) *Customer

	MatchByUsername(string) *Customer
}
<|endoftext|>


<commit_before>package tty

import (
	"os"
	"fmt"
	"bytes"
)

const (
	DA1_SIXEL = 4
	DA1_MAX = 64
)

type DeviceAttributes1 [DA1_MAX]bool

func GetDeviceAttributes1(file *os.File) (DeviceAttributes1, error) {
	var err error
	var termios_save Termios
	var da1 DeviceAttributes1

	termios_save, err = MakeRaw(file)
	if err != nil {
		return da1, err
	}
	defer SetTermios(file, termios_save)

	file.WriteString("\x1B[c")

	buf := make([]byte, 3)
	_, err = file.Read(buf)
	if err != nil {
		return da1, fmt.Errorf("cannot read DA1: %v", err)
	}
	if bytes.Compare(buf, []byte("\x1b[?")) != 0 {
		return da1, fmt.Errorf("invalid DA1 response")
	}

	var attr byte
LOOP:
	for {
		_, err = file.Read(buf[0:1])
		if err != nil {
			return da1, fmt.Errorf("cannot read DA1: %v", err)
		}
		switch {
		case buf[0] >= '0' && buf[0] <= '9':
			attr *= 10
			attr += buf[0] - '0'
		case buf[0] == ';' || buf[0] == 'c':
			if attr <= DA1_MAX {
				da1[attr] = true
			}
			if buf[0] == 'c' {
				break LOOP
			}
			attr = 0
		}
	}

	return da1, nil
}

<commit_msg>tty: Define all DA1 attribute values<commit_after>package tty

import (
	"os"
	"fmt"
	"bytes"
)

const (
	DA1_132_COLUMNS =				 1
	DA1_PRINTER_PORT =				 2
	DA1_SIXEL =					 4
	DA1_SELECTIVE_ERASE =				 6
	DA1_DRCS =					 7
	DA1_SOFT_CHARACTER_SET =			 7
	DA1_UDKS =					 8
	DA1_USER_DEFINED_KEYS =				 8
	DA1_NRCS =					 9
	DA1_NATIONAL_REPLACEMENT_CHARACTER_SETS =	 9
	DA1_SCS =					12
	DA1_YUGOSLAVIAN =				12
	DA1_TECHNICAL_CHARACTER_SET =			15
	DA1_WINDOWING_CAPABILITY =			18
	DA1_HORIZONTAL_SCROLLING =			21
	DA1_GREEK =					23
	DA1_TURKISH =					24
	DA1_ISO_LATIN2_CHARACTER_SET =			42
	DA1_PCTERM =					44
	DA1_SOFT_KEY_MAP =				45
	DA1_ASCII_EMULATION =				46
	DA1_MAX =					64
)

type DeviceAttributes1 [DA1_MAX]bool

func GetDeviceAttributes1(file *os.File) (DeviceAttributes1, error) {
	var err error
	var termios_save Termios
	var da1 DeviceAttributes1

	termios_save, err = MakeRaw(file)
	if err != nil {
		return da1, err
	}
	defer SetTermios(file, termios_save)

	file.WriteString("\x1B[c")

	buf := make([]byte, 3)
	_, err = file.Read(buf)
	if err != nil {
		return da1, fmt.Errorf("cannot read DA1: %v", err)
	}
	if bytes.Compare(buf, []byte("\x1b[?")) != 0 {
		return da1, fmt.Errorf("invalid DA1 response")
	}

	var attr byte
LOOP:
	for {
		_, err = file.Read(buf[0:1])
		if err != nil {
			return da1, fmt.Errorf("cannot read DA1: %v", err)
		}
		switch {
		case buf[0] >= '0' && buf[0] <= '9':
			attr *= 10
			attr += buf[0] - '0'
		case buf[0] == ';' || buf[0] == 'c':
			if attr <= DA1_MAX {
				da1[attr] = true
			}
			if buf[0] == 'c' {
				break LOOP
			}
			attr = 0
		}
	}

	return da1, nil
}

<|endoftext|>


<commit_before>package heroku

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

type Build struct {
	Id         string      `json:"id"`
	SourceBlob *SourceBlob `json:"source_blob"`
	Status     string      `json:"status"`
}

type SourceBlob struct {
	Checksum string `json:"checksum,omitempty"`
	Url      string `json:"url"`
	Version  string `json:"url"`
}

type buildCreateRequest struct {
	SourceBlob *SourceBlob `json:"source_blob"`
}

func (c *Client) BuildCreate(appId string, sourceBlob *SourceBlob) (*Build, *http.Response, error) {
	body, err := json.Marshal(&buildCreateRequest{
		SourceBlob: sourceBlob,
	})
	fmt.Printf("BuildCreate body: %v\n", string(body))
	if err != nil {
		return nil, nil, err
	}

	url := c.BaseUrl() + fmt.Sprintf("/apps/%v/builds", appId)
	resp, err := c.MakeRequest("POST", url, &body)
	if err != nil {
		return nil, resp, err
	}

	var build Build
	err = c.readResponseInto(resp, &build)
	if err != nil {
		return nil, resp, err
	}

	return &build, resp, nil
}

func (c *Client) BuildInfo(appId string, id string) (*Build, *http.Response, error) {
	url := c.BaseUrl() + fmt.Sprintf("/apps/%v/builds/%v", appId, id)
	resp, err := c.MakeRequest("GET", url, nil)
	if err != nil {
		return nil, resp, err
	}

	var build Build
	err = c.readResponseInto(resp, &build)
	if err != nil {
		return nil, resp, err
	}

	return &build, resp, nil
}

func (c *Client) readResponse(resp *http.Response) ([]byte, error) {
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	if resp.StatusCode >= 400 && c.Debug {
		fmt.Printf("[Heroku] Error: code=%v %v\n", resp.StatusCode, string(body))
	}

	return body, nil
}

func (c *Client) readResponseInto(resp *http.Response, val interface{}) error {
	body, err := c.readResponse(resp)
	if err != nil {
		return err
	}

	err = json.Unmarshal(body, val)
	if err != nil {
		return err
	}

	return nil
}
<commit_msg>Add some more logging; fix JSON key name<commit_after>package heroku

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

type Build struct {
	Id         string      `json:"id"`
	SourceBlob *SourceBlob `json:"source_blob"`
	Status     string      `json:"status"`
}

type SourceBlob struct {
	Checksum string `json:"checksum,omitempty"`
	Url      string `json:"url"`
	Version  string `json:"version"`
}

type buildCreateRequest struct {
	SourceBlob *SourceBlob `json:"source_blob"`
}

func (c *Client) BuildCreate(appId string, sourceBlob *SourceBlob) (*Build, *http.Response, error) {
	fmt.Printf("sourceBlob: %+v\n", sourceBlob)
	body, err := json.Marshal(&buildCreateRequest{
		SourceBlob: sourceBlob,
	})
	fmt.Printf("BuildCreate body: %v\n", string(body))
	if err != nil {
		return nil, nil, err
	}

	url := c.BaseUrl() + fmt.Sprintf("/apps/%v/builds", appId)
	resp, err := c.MakeRequest("POST", url, &body)
	if err != nil {
		return nil, resp, err
	}

	var build Build
	err = c.readResponseInto(resp, &build)
	if err != nil {
		return nil, resp, err
	}

	return &build, resp, nil
}

func (c *Client) BuildInfo(appId string, id string) (*Build, *http.Response, error) {
	url := c.BaseUrl() + fmt.Sprintf("/apps/%v/builds/%v", appId, id)
	resp, err := c.MakeRequest("GET", url, nil)
	if err != nil {
		return nil, resp, err
	}

	var build Build
	err = c.readResponseInto(resp, &build)
	if err != nil {
		return nil, resp, err
	}

	return &build, resp, nil
}

func (c *Client) readResponse(resp *http.Response) ([]byte, error) {
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	if resp.StatusCode >= 400 && c.Debug {
		fmt.Printf("[Heroku] Error: code=%v %v\n", resp.StatusCode, string(body))
	}

	return body, nil
}

func (c *Client) readResponseInto(resp *http.Response, val interface{}) error {
	body, err := c.readResponse(resp)
	if err != nil {
		return err
	}

	err = json.Unmarshal(body, val)
	if err != nil {
		return err
	}

	return nil
}
<|endoftext|>


<commit_before>package nessusProcessor

// PolicyViolationMatchCriteria holds what criteria should be checked when checking for a
// policy violation.
type PolicyViolationMatchCriteria struct {
	ExternallyAccessible             bool
	IgnoreViolationWithCriteriaMatch bool
	PreviousViolationCheck           bool
	CountIf                          string
	DescriptionRegexp                []string
	NotDescriptionRegexp             []string
	PluginID                         int
	Ports                            []int
	OrganizationIDs                  []int
	RegionIDs                        []int
}

// FalsePositiveMatchCriteria holds what criteria should be checked when
// checking for a false positive.
type FalsePositiveMatchCriteria struct {
	PluginID            int
	Port                int
	Protocol            string
	DescriptionRegexp   []string
	CheckIfIsNotDefined bool
	SQLSolarisCheck     bool
}
<commit_msg>Make ports a slice for consistency with policy violations<commit_after>package nessusProcessor

// PolicyViolationMatchCriteria holds what criteria should be checked when checking for a
// policy violation.
type PolicyViolationMatchCriteria struct {
	ExternallyAccessible             bool
	IgnoreViolationWithCriteriaMatch bool
	PreviousViolationCheck           bool
	CountIf                          string
	DescriptionRegexp                []string
	NotDescriptionRegexp             []string
	PluginID                         int
	Ports                            []int
	OrganizationIDs                  []int
	RegionIDs                        []int
}

// FalsePositiveMatchCriteria holds what criteria should be checked when
// checking for a false positive.
type FalsePositiveMatchCriteria struct {
	PluginID            int
	Ports               []int
	Protocol            string
	DescriptionRegexp   []string
	CheckIfIsNotDefined bool
	SQLSolarisCheck     bool
}
<|endoftext|>


<commit_before>package main

import (
	"crypto/tls"
	"flag"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"os"
	"strings"
	"sync"

	pb "github.com/creiht/formic/proto"

	"bazil.org/fuse"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
)

type server struct {
	fs *fs
	wg sync.WaitGroup
}

func newserver(fs *fs) *server {
	s := &server{
		fs: fs,
	}
	return s
}

func (s *server) serve() error {
	defer s.wg.Wait()

	for {
		req, err := s.fs.conn.ReadRequest()
		if err != nil {
			if err == io.EOF {
				break
			}
			return err
		}
		s.wg.Add(1)
		go func() {
			defer s.wg.Done()
			s.fs.handle(req)
		}()
	}
	return nil
}

func debuglog(msg interface{}) {
	fmt.Fprintf(os.Stderr, "%v\n", msg)
}

type rpc struct {
	conn *grpc.ClientConn
	api  pb.ApiClient
}

func newrpc(conn *grpc.ClientConn) *rpc {
	r := &rpc{
		conn: conn,
		api:  pb.NewApiClient(conn),
	}

	return r
}

type NullWriter int

func (NullWriter) Write([]byte) (int, error) { return 0, nil }

func main() {

	fusermountPath()
	flag.Usage = printUsage
	flag.Parse()
	clargs := getArgs(flag.Args())
	mountpoint := clargs["mountPoint"]
	serverAddr := clargs["host"]

	// crapy debug log handling :)
	if debug, ok := clargs["debug"]; ok {
		if debug == "false" {
			log.SetFlags(0)
			log.SetOutput(ioutil.Discard)
		}
	} else {
		log.SetFlags(0)
		log.SetOutput(ioutil.Discard)
	}

	// Setup grpc
	var opts []grpc.DialOption
	creds := credentials.NewTLS(&tls.Config{
		InsecureSkipVerify: true,
	})
	opts = append(opts, grpc.WithTransportCredentials(creds))
	conn, err := grpc.Dial(serverAddr, opts...)
	if err != nil {
		log.Fatalf("failed to dial: %v", err)
	}
	defer conn.Close()

	// Uncomment the following to diable logs
	//log.SetOutput(new(NullWriter))

	c, err := fuse.Mount(
		mountpoint,
		fuse.FSName("cfs"),
		fuse.Subtype("cfs"),
		fuse.LocalVolume(),
		fuse.VolumeName("CFS"),
		//fuse.AllowOther(),
		fuse.DefaultPermissions(),
	)
	if err != nil {
		log.Fatal(err)
	}
	defer c.Close()

	rpc := newrpc(conn)
	fs := newfs(c, rpc)
	srv := newserver(fs)

	if err := srv.serve(); err != nil {
		log.Fatal(err)
	}

	<-c.Ready
	if err := c.MountError; err != nil {
		log.Fatal(err)
	}
}

// getArgs is passed a command line and breaks it up into commands
// the valid format is <device> <mount point> -o [Options]
func getArgs(args []string) map[string]string {
	// Setup declarations
	var optList []string
	requiredOptions := []string{"host"}
	clargs := make(map[string]string)

	// Not the correct number of arguments or -help
	if len(args) != 4 {
		printUsage()
		os.Exit(0)
	}

	// Verify mountPoint exists
	if _, err := os.Stat(args[1]); os.IsNotExist(err) {
		printUsage()
		log.Fatalf("Mount point %s does not exist\n\n", args[1])
	}

	// process options -o
	if args[2] == "-o" || args[2] == "--o" {
		optList = strings.Split(args[3], ",")
		for _, item := range optList {
			if strings.Contains(item, "=") {
				value := strings.Split(item, "=")
				if value[0] == "" || value[1] == "" {
					printUsage()
					log.Fatalf("Invalid option %s, %s no value\n\n", value[0], value[1])
				} else {
					clargs[value[0]] = value[1]
				}
			} else {
				clargs[item] = ""
			}
		}
	} else {
		printUsage()
		log.Fatalf("Invalid option %v\n\n", args[2])
	}

	// Verify required options exist
	for _, v := range requiredOptions {
		_, ok := clargs[v]
		if !ok {
			printUsage()
			log.Fatalf("%s is a required option", v)
		}
	}

	// load in device and mountPoint
	clargs["cfsDevice"] = args[0]
	clargs["mountPoint"] = args[1]
	return clargs
}

func fusermountPath() {
	// Grab the current path
	currentPath := os.Getenv("PATH")
	if len(currentPath) == 0 {
		// using mount seem to not have a path
		// fusermount is in /bin
		os.Setenv("PATH", "/bin")
	}
}

// printUsage will display usage
func printUsage() {
	fmt.Println("Usage:")
	fmt.Println("\tcfs [file system] [mount point] -o [OPTIONS] -help")
	fmt.Println("\texample: mount -t cfs fsaas /mnt/cfsdrive -o host=localhost:8445")
	fmt.Println("\tMount Options: (separated by commas with no spaces)")
	fmt.Println("\t\tRequired:")
	fmt.Println("\t\t\thost\taddress of the formic server")
	fmt.Println("")
	fmt.Println("\thelp\tdisplay usage")
}
<commit_msg>First Pass at cfsmanage<commit_after>package main

import (
	"crypto/tls"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/url"
	"os"
	"strings"
	"sync"

	"golang.org/x/net/context"

	"github.com/codegangsta/cli"
	pb "github.com/creiht/formic/proto"
	mb "github.com/letterj/oohhc/proto/filesystem"

	"bazil.org/fuse"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
)

type server struct {
	fs *fs
	wg sync.WaitGroup
}

func newserver(fs *fs) *server {
	s := &server{
		fs: fs,
	}
	return s
}

func (s *server) serve() error {
	defer s.wg.Wait()

	for {
		req, err := s.fs.conn.ReadRequest()
		if err != nil {
			if err == io.EOF {
				break
			}
			return err
		}
		s.wg.Add(1)
		go func() {
			defer s.wg.Done()
			s.fs.handle(req)
		}()
	}
	return nil
}

func debuglog(msg interface{}) {
	fmt.Fprintf(os.Stderr, "%v\n", msg)
}

type rpc struct {
	conn *grpc.ClientConn
	api  pb.ApiClient
}

func newrpc(conn *grpc.ClientConn) *rpc {
	r := &rpc{
		conn: conn,
		api:  pb.NewApiClient(conn),
	}

	return r
}

// NullWriter ...
type NullWriter int

func (NullWriter) Write([]byte) (int, error) { return 0, nil }

func main() {

	// Process command line arguments
	var token string
	var acctNum string
	var fsNum string
	var serverAddr string

	app := cli.NewApp()
	app.Name = "cfs"
	app.Usage = "Client used to test filesysd"
	app.Version = "0.5.0"
	app.Flags = []cli.Flag{
		cli.StringFlag{
			Name:        "token, T",
			Value:       "",
			Usage:       "Access token",
			EnvVar:      "OOHHC_TOKEN_KEY",
			Destination: &token,
		},
		cli.StringFlag{
			Name:        "server, s",
			Value:       "api.ea.iad3.rackfs.com:8443",
			Usage:       "Address of the oohhc-acctd server",
			EnvVar:      "OOHHC_FILESYS_SERVER_ADDR",
			Destination: &serverAddr,
		},
	}
	app.Commands = []cli.Command{
		{
			Name:  "show",
			Usage: "Show a File Systems",
			Action: func(c *cli.Context) {
				if !c.Args().Present() {
					fmt.Println("Invalid syntax for show.")
					os.Exit(1)
				}
				if token == "" {
					fmt.Println("Token is required")
				}
				u, err := url.Parse(c.Args().Get(0))
				if err != nil {
					panic(err)
				}
				fmt.Println(u.Scheme)
				acctNum = u.Host
				fsNum = u.Path[1:]
				conn := setupWS(serverAddr)
				ws := mb.NewFileSystemAPIClient(conn)
				result, err := ws.ShowFS(context.Background(), &mb.ShowFSRequest{Acctnum: acctNum, FSid: fsNum, Token: token})
				if err != nil {
					log.Fatalf("Bad Request: %v", err)
					conn.Close()
					os.Exit(1)
				}
				conn.Close()
				log.Printf("Result: %s\n", result.Status)
				log.Printf("SHOW Results: %s", result.Payload)
			},
		},
		{
			Name:  "create",
			Usage: "Create a File Systems",
			Flags: []cli.Flag{
				cli.StringFlag{
					Name:  "name, N",
					Value: "",
					Usage: "Name of the file system",
				},
			},
			Action: func(c *cli.Context) {
				if !c.Args().Present() {
					fmt.Println("Invalid syntax for show.")
					os.Exit(1)
				}
				if token == "" {
					fmt.Println("Token is required")
				}
				u, err := url.Parse(c.Args().Get(0))
				if err != nil {
					fmt.Printf("Url parse error: %v", err)
					os.Exit(1)
				}
				fmt.Println(u.Scheme)
				acctNum = u.Host
				if u.Path != "" {
					fmt.Println("Invalid url scheme")
					os.Exit(1)
				}
				if c.String("name") == "" {
					fmt.Println("File system name is a required field.")
					os.Exit(1)
				}
				conn := setupWS(serverAddr)
				ws := mb.NewFileSystemAPIClient(conn)
				result, err := ws.CreateFS(context.Background(), &mb.CreateFSRequest{Acctnum: acctNum, FSName: c.String("name"), Token: token})
				if err != nil {
					log.Fatalf("Bad Request: %v", err)
					conn.Close()
					os.Exit(1)
				}
				conn.Close()
				log.Printf("Result: %s\n", result.Status)
				log.Printf("Create Results: %s", result.Payload)
			},
		},
		{
			Name:  "list",
			Usage: "List File Systems for an account",
			Action: func(c *cli.Context) {
				if !c.Args().Present() {
					fmt.Println("Invalid syntax for list.")
					os.Exit(1)
				}
				if token == "" {
					fmt.Println("Token is required")
				}
				u, err := url.Parse(c.Args().Get(0))
				if err != nil {
					fmt.Println("Invalid url scheme")
					os.Exit(1)
				}
				fmt.Println(u.Scheme)
				acctNum = u.Host
				if u.Path != "" {
					fmt.Println("Invaid url")
					os.Exit(1)
				}
				conn := setupWS(serverAddr)
				ws := mb.NewFileSystemAPIClient(conn)
				result, err := ws.ListFS(context.Background(), &mb.ListFSRequest{Acctnum: acctNum, Token: token})
				if err != nil {
					log.Fatalf("Bad Request: %v", err)
					conn.Close()
					os.Exit(1)
				}
				conn.Close()
				log.Printf("Result: %s\n", result.Status)
				log.Printf("LIST Results: %s", result.Payload)
			},
		},
		{
			Name:  "delete",
			Usage: "Delete a File Systems",
			Action: func(c *cli.Context) {
				if !c.Args().Present() {
					fmt.Println("Invalid syntax for delete.")
					os.Exit(1)
				}
				if token == "" {
					fmt.Println("Token is required")
				}
				u, err := url.Parse(c.Args().Get(0))
				if err != nil {
					fmt.Println("Invalid url scheme")
					os.Exit(1)
				}
				fmt.Println(u.Scheme)
				acctNum = u.Host
				fsNum = u.Path[1:]
				conn := setupWS(serverAddr)
				ws := mb.NewFileSystemAPIClient(conn)
				result, err := ws.DeleteFS(context.Background(), &mb.DeleteFSRequest{Acctnum: acctNum, FSid: fsNum, Token: token})
				if err != nil {
					log.Fatalf("Bad Request: %v", err)
					conn.Close()
					os.Exit(1)
				}
				conn.Close()
				log.Printf("Result: %s\n", result.Status)
				log.Printf("Delete Results: %s", result.Payload)
			},
		},
		{
			Name:  "update",
			Usage: "Update a File Systems",
			Flags: []cli.Flag{
				cli.StringFlag{
					Name:  "name, N",
					Value: "",
					Usage: "Name of the file system",
				},
				cli.StringFlag{
					Name:  "S, status",
					Value: "",
					Usage: "Status of the file system",
				},
			},
			Action: func(c *cli.Context) {
				if !c.Args().Present() {
					fmt.Println("Invalid syntax for delete.")
					os.Exit(1)
				}
				if token == "" {
					fmt.Println("Token is required")
				}
				u, err := url.Parse(c.Args().Get(0))
				if err != nil {
					fmt.Printf("Url Parse error: %v", err)
					os.Exit(1)
				}
				fmt.Println(u.Scheme)
				acctNum = u.Host
				fsNum = u.Path[1:]
				if c.String("name") != "" && !validAcctName(c.String("name")) {
					fmt.Printf("Invalid File System String: %q\n", c.String("name"))
					os.Exit(1)
				}
				fsMod := &mb.ModFS{
					Name:   c.String("name"),
					Status: c.String("status"),
				}
				conn := setupWS(serverAddr)
				ws := mb.NewFileSystemAPIClient(conn)
				result, err := ws.UpdateFS(context.Background(), &mb.UpdateFSRequest{Acctnum: acctNum, FSid: fsNum, Token: token, Filesys: fsMod})
				if err != nil {
					log.Fatalf("Bad Request: %v", err)
					conn.Close()
					os.Exit(1)
				}
				conn.Close()
				log.Printf("Result: %s\n", result.Status)
				log.Printf("Update Results: %s", result.Payload)
			},
		},
		{
			Name:  "grant",
			Usage: "Grant an Addr access to a File Systems",
			Flags: []cli.Flag{
				cli.StringFlag{
					Name:  "addr",
					Value: "",
					Usage: "Address to Grant",
				},
			},
			Action: func(c *cli.Context) {
				if !c.Args().Present() {
					fmt.Println("Invalid syntax for delete.")
					os.Exit(1)
				}
				if token == "" {
					fmt.Println("Token is required")
					os.Exit(1)
				}
				if c.String("addr") == "" {
					fmt.Println("addr is required")
					os.Exit(1)
				}
				u, err := url.Parse(c.Args().Get(0))
				if err != nil {
					fmt.Println("Invalid url scheme")
					os.Exit(1)
				}
				fmt.Println(u.Scheme)
				acctNum = u.Host
				fsNum = u.Path[1:]
				conn := setupWS(serverAddr)
				ws := mb.NewFileSystemAPIClient(conn)
				result, err := ws.GrantAddrFS(context.Background(), &mb.GrantAddrFSRequest{Acctnum: acctNum, FSid: fsNum, Token: token, Addr: c.String("addr")})
				if err != nil {
					log.Fatalf("Bad Request: %v", err)
					conn.Close()
					os.Exit(1)
				}
				conn.Close()
				log.Printf("Result: %s\n", result.Status)
			},
		},
		{
			Name:  "revoke",
			Usage: "Revoke an Addr's access to a File Systems",
			Flags: []cli.Flag{
				cli.StringFlag{
					Name:  "addr",
					Value: "",
					Usage: "Address to Revoke",
				},
			},
			Action: func(c *cli.Context) {
				if !c.Args().Present() {
					fmt.Println("Invalid syntax for revoke.")
					os.Exit(1)
				}
				if token == "" {
					fmt.Println("Token is required")
					os.Exit(1)
				}
				if c.String("addr") == "" {
					fmt.Println("addr is required")
					os.Exit(1)
				}
				u, err := url.Parse(c.Args().Get(0))
				if err != nil {
					fmt.Println("Invalid url scheme")
					os.Exit(1)
				}
				fmt.Println(u.Scheme)
				acctNum = u.Host
				fsNum = u.Path[1:]
				conn := setupWS(serverAddr)
				ws := mb.NewFileSystemAPIClient(conn)
				result, err := ws.RevokeAddrFS(context.Background(), &mb.RevokeAddrFSRequest{Acctnum: acctNum, FSid: fsNum, Token: token, Addr: c.String("addr")})
				if err != nil {
					log.Fatalf("Bad Request: %v", err)
					conn.Close()
					os.Exit(1)
				}
				conn.Close()
				log.Printf("Result: %s\n", result.Status)
			},
		},
		{
			Name:  "verify",
			Usage: "Verify an Addr has access to a file system",
			Flags: []cli.Flag{
				cli.StringFlag{
					Name:  "addr",
					Value: "",
					Usage: "Address to check",
				},
			},
			Action: func(c *cli.Context) {
				if !c.Args().Present() {
					fmt.Println("Invalid syntax for revoke.")
					os.Exit(1)
				}
				if c.String("addr") == "" {
					fmt.Println("addr is required")
					os.Exit(1)
				}
				u, err := url.Parse(c.Args().Get(0))
				if err != nil {
					fmt.Println("Invalid url scheme")
					os.Exit(1)
				}
				fmt.Println(u.Scheme)
				fsNum = u.Host
				conn := setupWS(serverAddr)
				ws := mb.NewFileSystemAPIClient(conn)
				result, err := ws.LookupAddrFS(context.Background(), &mb.LookupAddrFSRequest{FSid: fsNum, Addr: c.String("addr")})
				if err != nil {
					log.Fatalf("Bad Request: %v", err)
					conn.Close()
					os.Exit(1)
				}
				conn.Close()
				log.Printf("Result: %s\n", result.Status)
			},
		},
		{
			Name:  "mount",
			Usage: "mount a file system",
			Flags: []cli.Flag{
				cli.StringFlag{
					Name:  "o",
					Value: "",
					Usage: "mount options",
				},
			},
			Action: func(c *cli.Context) {
				if !c.Args().Present() {
					fmt.Println("Invalid syntax for revoke.")
					os.Exit(1)
				}
				if c.String("o") == "" {
					fmt.Println("options are required")
					os.Exit(1)
				}
				u, err := url.Parse(c.Args().Get(0))
				if err != nil {
					fmt.Println("Invalid url scheme")
					os.Exit(1)
				}
				fmt.Println(u.Scheme)
				fsNum = u.Host
				mountpoint := c.Args().Get(1)
				// check mountpoint exists
				if _, ferr := os.Stat(mountpoint); os.IsNotExist(ferr) {
					log.Printf("Mount point %s does not exist\n\n", mountpoint)
					os.Exit(1)
				}
				fusermountPath()
				if u.Scheme == "aio0" {
					serverAddr = "127.0.0.1:8443"
				}
				// process file system options
				clargs := getArgs(c.String("o"))

				// crapy debug log handling :)
				if debug, ok := clargs["debug"]; ok {
					if debug == "false" {
						log.SetFlags(0)
						log.SetOutput(ioutil.Discard)
					}
				} else {
					log.SetFlags(0)
					log.SetOutput(ioutil.Discard)
				}
				// Setup grpc
				var opts []grpc.DialOption
				creds := credentials.NewTLS(&tls.Config{
					InsecureSkipVerify: true,
				})
				opts = append(opts, grpc.WithTransportCredentials(creds))
				conn, err := grpc.Dial(serverAddr, opts...)
				if err != nil {
					log.Fatalf("failed to dial: %v", err)
				}
				defer conn.Close()
				// Work with fuse
				cfs, err := fuse.Mount(
					mountpoint,
					fuse.FSName("cfs"),
					fuse.Subtype("cfs"),
					fuse.LocalVolume(),
					fuse.VolumeName("CFS"),
					//fuse.AllowOther(),
					fuse.DefaultPermissions(),
				)
				if err != nil {
					log.Fatal(err)
				}
				defer cfs.Close()

				rpc := newrpc(conn)
				fs := newfs(cfs, rpc)
				srv := newserver(fs)

				if err := srv.serve(); err != nil {
					log.Fatal(err)
				}

				<-cfs.Ready
				if err := cfs.MountError; err != nil {
					log.Fatal(err)
				}
			},
		},
	}
	app.Run(os.Args)
}

// getArgs is passed a command line and breaks it up into commands
// the valid format is <device> <mount point> -o [Options]
func getArgs(args string) map[string]string {
	// Setup declarations
	var optList []string
	requiredOptions := []string{}
	clargs := make(map[string]string)

	// process options -o
	optList = strings.Split(args, ",")
	for _, item := range optList {
		if strings.Contains(item, "=") {
			value := strings.Split(item, "=")
			if value[0] == "" || value[1] == "" {
				log.Printf("Invalid option %s, %s no value\n\n", value[0], value[1])
				os.Exit(1)
			} else {
				clargs[value[0]] = value[1]
			}
		} else {
			clargs[item] = ""
		}
	}

	// Verify required options exist
	for _, v := range requiredOptions {
		_, ok := clargs[v]
		if !ok {
			log.Printf("%s is a required option", v)
			os.Exit(1)
		}
	}

	// load in device and mountPoint
	return clargs
}

func fusermountPath() {
	// Grab the current path
	currentPath := os.Getenv("PATH")
	if len(currentPath) == 0 {
		// using mount seem to not have a path
		// fusermount is in /bin
		os.Setenv("PATH", "/bin")
	}
}

// Validate the account string passed in from the command line
func validAcctName(a string) bool {
	//TODO: Determine what needs to be done to validate
	return true
}

// setupWS ...
func setupWS(svr string) *grpc.ClientConn {
	var opts []grpc.DialOption
	creds := credentials.NewTLS(&tls.Config{
		InsecureSkipVerify: true,
	})
	opts = append(opts, grpc.WithTransportCredentials(creds))
	conn, err := grpc.Dial(svr, opts...)
	if err != nil {
		log.Fatalf("failed to dial: %v", err)
	}
	return conn
}
<|endoftext|>


<commit_before>package clang

// #cgo LDFLAGS: -lclang
// #cgo linux CFLAGS: -I.
import "C"

//EOF
<commit_msg>Add the repository root to CFLAGS -I<commit_after>package clang

// #cgo LDFLAGS: -lclang
// #cgo CFLAGS: -I.
import "C"

//EOF
<|endoftext|>