How to use init method of run Package

Best Venom code snippet using run.init

run.go

Source:run.go Github

copy

Full Screen

...44 "max-rate", 0, "Maximum frequency of operations (reads/writes). If 0, no limit.")45var maxOps = runFlags.Uint64("max-ops", 0, "Maximum number of operations to run")46var duration = runFlags.Duration("duration", 0,47 "The duration to run (in addition to --ramp). If 0, run forever.")48var doInit = runFlags.Bool("init", false, "Automatically run init. DEPRECATED: Use workload init instead.")49var ramp = runFlags.Duration("ramp", 0*time.Second, "The duration over which to ramp up load.")50var initFlags = pflag.NewFlagSet(`init`, pflag.ContinueOnError)51var drop = initFlags.Bool("drop", false, "Drop the existing database, if it exists")52var sharedFlags = pflag.NewFlagSet(`shared`, pflag.ContinueOnError)53var pprofport = sharedFlags.Int("pprofport", 33333, "Port for pprof endpoint.")54var dataLoader = sharedFlags.String("data-loader", `INSERT`,55 "How to load initial table data. Options are INSERT and IMPORT")56var initConns = sharedFlags.Int("init-conns", 16,57 "The number of connections to use during INSERT init")58var displayEvery = runFlags.Duration("display-every", time.Second, "How much time between every one-line activity reports.")59var displayFormat = runFlags.String("display-format", "simple", "Output display format (simple, incremental-json)")60var prometheusPort = sharedFlags.Int(61 "prometheus-port",62 2112,63 "Port to expose prometheus metrics if the workload has a prometheus gatherer set.",64)65var histograms = runFlags.String(66 "histograms", "",67 "File to write per-op incremental and cumulative histogram data.")68var histogramsMaxLatency = runFlags.Duration(69 "histograms-max-latency", 100*time.Second,70 "Expected maximum latency of running a query")71var securityFlags = pflag.NewFlagSet(`security`, pflag.ContinueOnError)72var secure = securityFlags.Bool("secure", false,73 "Run in secure mode (sslmode=require). "+74 "Running in secure mode expects the relevant certs to have been created for the user in the certs/ directory."+75 "For example when using root, certs/client.root.crt certs/client.root.key should exist.")76var user = securityFlags.String("user", "root", "Specify a user to run the workload as")77var password = securityFlags.String("password", "", "Optionally specify a password for the user")78func init() {79 _ = sharedFlags.MarkHidden("pprofport")80 AddSubCmd(func(userFacing bool) *cobra.Command {81 var initCmd = SetCmdDefaults(&cobra.Command{82 Use: `init`,83 Short: `set up tables for a workload`,84 })85 for _, meta := range workload.Registered() {86 gen := meta.New()87 var genFlags *pflag.FlagSet88 if f, ok := gen.(workload.Flagser); ok {89 genFlags = f.Flags().FlagSet90 }91 genInitCmd := SetCmdDefaults(&cobra.Command{92 Use: meta.Name + " [pgurl...]",93 Short: meta.Description,94 Long: meta.Description + meta.Details,95 Args: cobra.ArbitraryArgs,96 })97 genInitCmd.Flags().AddFlagSet(initFlags)98 genInitCmd.Flags().AddFlagSet(sharedFlags)99 genInitCmd.Flags().AddFlagSet(genFlags)100 genInitCmd.Flags().AddFlagSet(securityFlags)101 genInitCmd.Run = CmdHelper(gen, runInit)102 if userFacing && !meta.PublicFacing {103 genInitCmd.Hidden = true104 }105 initCmd.AddCommand(genInitCmd)106 }107 return initCmd108 })109 AddSubCmd(func(userFacing bool) *cobra.Command {110 var runCmd = SetCmdDefaults(&cobra.Command{111 Use: `run`,112 Short: `run a workload's operations against a cluster`,113 })114 for _, meta := range workload.Registered() {115 gen := meta.New()116 if _, ok := gen.(workload.Opser); !ok {117 // If Opser is not implemented, this would just fail at runtime,118 // so omit it.119 continue120 }121 var genFlags *pflag.FlagSet122 if f, ok := gen.(workload.Flagser); ok {123 genFlags = f.Flags().FlagSet124 }125 genRunCmd := SetCmdDefaults(&cobra.Command{126 Use: meta.Name + " [pgurl...]",127 Short: meta.Description,128 Long: meta.Description + meta.Details,129 Args: cobra.ArbitraryArgs,130 })131 genRunCmd.Flags().AddFlagSet(runFlags)132 genRunCmd.Flags().AddFlagSet(sharedFlags)133 genRunCmd.Flags().AddFlagSet(genFlags)134 genRunCmd.Flags().AddFlagSet(securityFlags)135 initFlags.VisitAll(func(initFlag *pflag.Flag) {136 // Every init flag is a valid run flag that implies the --init option.137 f := *initFlag138 f.Usage += ` (implies --init)`139 genRunCmd.Flags().AddFlag(&f)140 })141 genRunCmd.Run = CmdHelper(gen, runRun)142 if userFacing && !meta.PublicFacing {143 genRunCmd.Hidden = true144 }145 runCmd.AddCommand(genRunCmd)146 }147 return runCmd148 })149}150// CmdHelper handles common workload command logic, such as error handling and151// ensuring the database name in the connection string (if provided) matches the152// expected one.153func CmdHelper(154 gen workload.Generator, fn func(gen workload.Generator, urls []string, dbName string) error,155) func(*cobra.Command, []string) {156 return HandleErrs(func(cmd *cobra.Command, args []string) error {157 // Apply the logging configuration if none was set already.158 if active, _ := log.IsActive(); !active {159 cfg := logconfig.DefaultStderrConfig()160 if err := cfg.Validate(nil /* no default log directory */); err != nil {161 return err162 }163 if _, err := log.ApplyConfig(cfg); err != nil {164 return err165 }166 }167 if h, ok := gen.(workload.Hookser); ok {168 if h.Hooks().Validate != nil {169 if err := h.Hooks().Validate(); err != nil {170 return errors.Wrapf(err, "could not validate")171 }172 }173 }174 // HACK: Steal the dbOverride out of flags. This should go away175 // once more of run.go moves inside workload.176 var dbOverride string177 if dbFlag := cmd.Flag(`db`); dbFlag != nil {178 dbOverride = dbFlag.Value.String()179 }180 urls := args181 if len(urls) == 0 {182 crdbDefaultURL := fmt.Sprintf(`postgres://%s@localhost:26257?sslmode=disable`, *user)183 if *secure {184 if *password != "" {185 crdbDefaultURL = fmt.Sprintf(186 `postgres://%s:%s@localhost:26257?sslmode=require&sslrootcert=certs/ca.crt`,187 *user, *password)188 } else {189 crdbDefaultURL = fmt.Sprintf(190 // This URL expects the certs to have been created by the user.191 `postgres://%s@localhost:26257?sslcert=certs/client.%s.crt&sslkey=certs/client.%s.key&sslrootcert=certs/ca.crt&sslmode=require`,192 *user, *user, *user)193 }194 }195 urls = []string{crdbDefaultURL}196 }197 dbName, err := workload.SanitizeUrls(gen, dbOverride, urls)198 if err != nil {199 return err200 }201 return fn(gen, urls, dbName)202 })203}204// SetCmdDefaults ensures that the provided Cobra command will properly report205// an error if the user specifies an invalid subcommand. It is safe to call on206// any Cobra command.207//208// This is a wontfix bug in Cobra: https://github.com/spf13/cobra/pull/329209func SetCmdDefaults(cmd *cobra.Command) *cobra.Command {210 if cmd.Run == nil && cmd.RunE == nil {211 cmd.Run = func(cmd *cobra.Command, args []string) {212 _ = cmd.Usage()213 }214 }215 if cmd.Args == nil {216 cmd.Args = cobra.NoArgs217 }218 return cmd219}220// numOps keeps a global count of successful operations.221var numOps uint64222// workerRun is an infinite loop in which the worker continuously attempts to223// read / write blocks of random data into a table in cockroach DB. The function224// returns only when the provided context is canceled.225func workerRun(226 ctx context.Context,227 errCh chan<- error,228 wg *sync.WaitGroup,229 limiter *rate.Limiter,230 workFn func(context.Context) error,231) {232 if wg != nil {233 defer wg.Done()234 }235 for {236 if ctx.Err() != nil {237 return238 }239 // Limit how quickly the load generator sends requests based on --max-rate.240 if limiter != nil {241 if err := limiter.Wait(ctx); err != nil {242 return243 }244 }245 if err := workFn(ctx); err != nil {246 if ctx.Err() != nil && (errors.Is(err, ctx.Err()) || errors.Is(err, driver.ErrBadConn)) {247 // lib/pq may return either the `context canceled` error or a248 // `bad connection` error when performing an operation with a context249 // that has been canceled. See https://github.com/lib/pq/pull/1000250 return251 }252 errCh <- err253 continue254 }255 v := atomic.AddUint64(&numOps, 1)256 if *maxOps > 0 && v >= *maxOps {257 return258 }259 }260}261func runInit(gen workload.Generator, urls []string, dbName string) error {262 ctx := context.Background()263 initDB, err := gosql.Open(`cockroach`, strings.Join(urls, ` `))264 if err != nil {265 return err266 }267 startPProfEndPoint(ctx)268 return runInitImpl(ctx, gen, initDB, dbName)269}270func runInitImpl(271 ctx context.Context, gen workload.Generator, initDB *gosql.DB, dbName string,272) error {273 if *drop {274 if _, err := initDB.ExecContext(ctx, `DROP DATABASE IF EXISTS `+dbName); err != nil {275 return err276 }277 }278 if _, err := initDB.ExecContext(ctx, `CREATE DATABASE IF NOT EXISTS `+dbName); err != nil {279 return err280 }281 var l workload.InitialDataLoader282 switch strings.ToLower(*dataLoader) {283 case `insert`, `inserts`:284 l = workloadsql.InsertsDataLoader{285 Concurrency: *initConns,286 }287 case `import`, `imports`:288 l = workload.ImportDataLoader289 default:290 return errors.Errorf(`unknown data loader: %s`, *dataLoader)291 }292 _, err := workloadsql.Setup(ctx, initDB, gen, l)293 return err294}295func startPProfEndPoint(ctx context.Context) {296 b := envutil.EnvOrDefaultInt64("COCKROACH_BLOCK_PROFILE_RATE",297 10000000 /* 1 sample per 10 milliseconds spent blocking */)298 m := envutil.EnvOrDefaultInt("COCKROACH_MUTEX_PROFILE_RATE",299 1000 /* 1 sample per 1000 mutex contention events */)300 runtime.SetBlockProfileRate(int(b))301 runtime.SetMutexProfileFraction(m)302 go func() {303 err := http.ListenAndServe(":"+strconv.Itoa(*pprofport), nil)304 if err != nil {305 log.Errorf(ctx, "%v", err)306 }307 }()308}309func runRun(gen workload.Generator, urls []string, dbName string) error {310 ctx := context.Background()311 var formatter outputFormat312 switch *displayFormat {313 case "simple":314 formatter = &textFormatter{}315 case "incremental-json":316 formatter = &jsonFormatter{w: os.Stdout}317 default:318 return errors.Errorf("unknown display format: %s", *displayFormat)319 }320 startPProfEndPoint(ctx)321 initDB, err := gosql.Open(`cockroach`, strings.Join(urls, ` `))322 if err != nil {323 return err324 }325 if *doInit || *drop {326 log.Info(ctx, `DEPRECATION: `+327 `the --init flag on "workload run" will no longer be supported after 19.2`)328 for {329 err = runInitImpl(ctx, gen, initDB, dbName)330 if err == nil {331 break332 }333 if !*tolerateErrors {334 return err335 }336 log.Infof(ctx, "retrying after error during init: %v", err)337 }338 }339 var limiter *rate.Limiter340 if *maxRate > 0 {341 // Create a limiter using maxRate specified on the command line and342 // with allowed burst of 1 at the maximum allowed rate.343 limiter = rate.NewLimiter(rate.Limit(*maxRate), 1)344 }345 o, ok := gen.(workload.Opser)346 if !ok {347 return errors.Errorf(`no operations defined for %s`, gen.Meta().Name)348 }349 reg := histogram.NewRegistry(350 *histogramsMaxLatency,351 gen.Meta().Name,352 )353 // Expose the prometheus gatherer.354 go func() {355 if err := http.ListenAndServe(356 fmt.Sprintf(":%d", *prometheusPort),357 promhttp.HandlerFor(reg.Gatherer(), promhttp.HandlerOpts{}),358 ); err != nil {359 log.Errorf(context.Background(), "error serving prometheus: %v", err)360 }361 }()362 var ops workload.QueryLoad363 prepareStart := timeutil.Now()364 log.Infof(ctx, "creating load generator...")365 const prepareTimeout = 60 * time.Minute366 prepareCtx, cancel := context.WithTimeout(ctx, prepareTimeout)367 defer cancel()368 if prepareErr := func(ctx context.Context) error {369 retry := retry.StartWithCtx(ctx, retry.Options{})370 var err error371 for retry.Next() {372 if err != nil {373 log.Warningf(ctx, "retrying after error while creating load: %v", err)374 }375 ops, err = o.Ops(ctx, urls, reg)376 if err == nil {377 return nil378 }379 err = errors.Wrapf(err, "failed to initialize the load generator")380 if !*tolerateErrors {381 return err382 }383 }384 if ctx.Err() != nil {385 // Don't retry endlessly. Note that this retry loop is not under the386 // control of --duration, so we're avoiding retrying endlessly.387 log.Errorf(ctx, "Attempt to create load generator failed. "+388 "It's been more than %s since we started trying to create the load generator "+389 "so we're giving up. Last failure: %s", prepareTimeout, err)390 }391 return err392 }(prepareCtx); prepareErr != nil {393 return prepareErr...

Full Screen

Full Screen

run_as_non_root_test.go

Source:run_as_non_root_test.go Github

copy

Full Screen

...75 name: "pod run as non root false, container security context unset",76 objs: containerNonRoot(&falseVar, nil),77 expected: diagnostic(),78 },79 // init container tests80 {81 name: "pod security context and init container security context unset",82 objs: initContainerSecurityContextNil(),83 expected: diagnostic(),84 },85 {86 name: "pod security context unset, init container with run as non root set to true",87 objs: initContainerNonRoot(nil, &trueVar),88 expected: nil,89 },90 {91 name: "pod security context unset, init container with run as non root set to false",92 objs: initContainerNonRoot(nil, &falseVar),93 expected: diagnostic(),94 },95 {96 name: "pod run as non root true, init container run as non root true",97 objs: initContainerNonRoot(&trueVar, &trueVar),98 expected: nil,99 },100 {101 name: "pod run as non root true, init container run as non root false",102 objs: initContainerNonRoot(&trueVar, &falseVar),103 expected: nil,104 },105 {106 name: "pod run as non root false, init container run as non root true",107 objs: initContainerNonRoot(&falseVar, &trueVar),108 expected: nil,109 },110 {111 name: "pod run as non root false, init container run as non root false",112 objs: initContainerNonRoot(&falseVar, &falseVar),113 expected: diagnostic(),114 },115 {116 name: "pod run as non root true, init container security context unset",117 objs: initContainerNonRoot(&trueVar, nil),118 expected: nil,119 },120 {121 name: "pod run as non root false, init container security context unset",122 objs: initContainerNonRoot(&falseVar, nil),123 expected: diagnostic(),124 },125 }126 for _, test := range tests {127 t.Run(test.name, func(t *testing.T) {128 d, _, err := nonRootUserCheck.Run(test.objs)129 assert.NoError(t, err)130 assert.ElementsMatch(t, test.expected, d)131 })132 }133}134func diagnostic() []check.Diagnostic {135 pod := initPod().Pods.Items[0]136 d := []check.Diagnostic{137 {138 Severity: check.Warning,139 Message: "Container `bar` can run as root user. Please ensure that the image is from a trusted source.",140 Kind: check.Pod,141 Object: &pod.ObjectMeta,142 Owners: pod.ObjectMeta.GetOwnerReferences(),143 },144 }145 return d146}...

Full Screen

Full Screen

pipe.go

Source:pipe.go Github

copy

Full Screen

...44 opt := &RunOpt{}45 for i := range opts {46 opts[i](opt)47 }48 initCtx := opt.InitContext49 if initCtx == nil {50 initCtx = NewContext()51 }52 handlerMw := NewHandlerMiddleware(handler)53 if p.globalOrchestrator != nil {54 p.mws = p.globalOrchestrator(p.mws)55 }56 if p.mwOrchestrator != nil {57 p.mws = p.mwOrchestrator(p.mws)58 }59 for i, mw := range p.mws {60 if i < len(p.mws)-1 {61 mw.SetNext(p.mws[i+1])62 continue63 }64 mw.SetNext(handlerMw)65 }66 if len(p.mws) == 0 {67 err := handlerMw.Handle(initCtx)68 return initCtx, err69 }70 err := p.mws[0].Handle(initCtx)71 return initCtx.Output(), err72}...

Full Screen

Full Screen

init

Using AI Code Generation

copy

Full Screen

1func main() {2 run.Init()3}4func main() {5 run.Init()6}7func main() {8 run.Init()9}10func main() {11 run.Init()12}13func main() {14 run.Init()15}16func main() {17 run.Init()18}19func main() {20 run.Init()21}22func main() {23 run.Init()24}25func main() {26 run.Init()27}28func main() {29 run.Init()30}31func main() {32 run.Init()33}34func main() {35 run.Init()36}37func main() {38 run.Init()39}40func main() {41 run.Init()42}43func main() {44 run.Init()45}46func main() {47 run.Init()48}49func main() {50 run.Init()51}52func main() {53 run.Init()54}55func main() {56 run.Init()57}58func main() {

Full Screen

Full Screen

init

Using AI Code Generation

copy

Full Screen

1import "fmt"2func main() {3 fmt.Println("hello world")4}5import "fmt"6func init() {7 fmt.Println("init 2")8}9import "fmt"10func init() {11 fmt.Println("init 3")12}13import "fmt"14func init() {15 fmt.Println("init 4")16}

Full Screen

Full Screen

init

Using AI Code Generation

copy

Full Screen

1import "fmt"2func init() { 3 fmt.Println("init method of run class") 4}5func main() {6 fmt.Println("main method of run class")7}

Full Screen

Full Screen

init

Using AI Code Generation

copy

Full Screen

1func main() {2 run.Init()3 run.Run()4}5func main() {6 run.Run()7}8func main() {9 run.Run()10}11import (12var (13func init() {14}15func Init() {16 fmt.Println("init")17}18func Run() {19 fmt.Println("run")20}

Full Screen

Full Screen

init

Using AI Code Generation

copy

Full Screen

1func main() {2 run.Init()3 run.Run()4}5import (6func Run() {7 fmt.Println("Running")8}9import (10func Init() {11 fmt.Println("Initializing")12}

Full Screen

Full Screen

init

Using AI Code Generation

copy

Full Screen

1import (2func init() {3 fmt.Println("init method is called")4}5func main() {6 fmt.Println("main method is called")7 if runtime.GOOS == "windows" {8 } else {9 }10 err := cmd.Start()11 if err != nil {12 log.Fatal(err)13 }14}

Full Screen

Full Screen

init

Using AI Code Generation

copy

Full Screen

1func main() {2 run.Run()3}4import (5func Run() {6 if runtime.GOOS == "windows" {7 } else if runtime.GOOS == "linux" {8 } else {9 fmt.Println("Unsupported platform!")10 os.Exit(1)11 }12 cmd.Start()13}

Full Screen

Full Screen

init

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello, World!")4 fmt.Println(os.Args[1])5}6import (7func main() {8 fmt.Println("Hello, World!")9 fmt.Println(os.Args[1])10}11import (12func main() {13 fmt.Println("Hello, World!")14 fmt.Println(os.Args[1])15}16import (17func main() {18 fmt.Println("Hello, World!")19 fmt.Println(os.Args[1])20}21import (22func main() {23 fmt.Println("Hello, World!")24 fmt.Println(os.Args[1])25}26import (27func main() {28 fmt.Println("Hello, World!")29 fmt.Println(os.Args[1])30}31import (32func main() {33 fmt.Println("Hello, World!")34 fmt.Println(os.Args[1])35}36import (37func main() {38 fmt.Println("Hello, World!")39 fmt.Println(os.Args[1])40}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful