// StructuredGenerate outputs a clusterRoleBinding object using the configured fields.
768525
func (s ClusterRoleBindingGeneratorV1) StructuredGenerate() (runtime.Object, error) {
	if err := s.validate(); err != nil {
		return nil, err
	}
	clusterRoleBinding := &rbacv1beta1.ClusterRoleBinding{}
	clusterRoleBinding.Name = s.Name
	clusterRoleBinding.RoleRef = rbacv1beta1.RoleRef{
		APIGroup: rbacv1beta1.GroupName,
		Kind:     "ClusterRole",
		Name:     s.ClusterRole,
	}
	for _, user := range sets.NewString(s.Users...).List() {
		clusterRoleBinding.Subjects = append(clusterRoleBinding.Subjects, rbacv1beta1.Subject{
			Kind:     rbacv1beta1.UserKind,
			APIGroup: rbacv1beta1.GroupName,
			Name:     user,
		})
	}
	for _, group := range sets.NewString(s.Groups...).List() {
		clusterRoleBinding.Subjects = append(clusterRoleBinding.Subjects, rbacv1beta1.Subject{
			Kind:     rbacv1beta1.GroupKind,
			APIGroup: rbacv1beta1.GroupName,
			Name:     group,
		})
	}
	for _, sa := range sets.NewString(s.ServiceAccounts...).List() {
		tokens := strings.Split(sa, ":")
		if len(tokens) != 2 || tokens[0] == "" || tokens[1] == "" {
			return nil, fmt.Errorf("serviceaccount must be <namespace>:<name>")
		}
		clusterRoleBinding.Subjects = append(clusterRoleBinding.Subjects, rbacv1beta1.Subject{
			Kind:      rbacv1beta1.ServiceAccountKind,
			APIGroup:  "",
			Namespace: tokens[0],
			Name:      tokens[1],
		})
	}

	return clusterRoleBinding, nil
}
1265147
func (f *RelationalModelDefinition) IterateBuildSources(it BuildSourceIterator) error {

	for _, bs := range f.BuildSources {
		if err := it(bs); err != nil {
			return err
		}
	}
	return nil
}
844832
func (c *cluster) unprotectedGenerateResizeJob(nodeAction nodeAction) (*resizeJob, error) {
	c.logger.Printf("generateResizeJob: %v", nodeAction)

	j, err := c.unprotectedGenerateResizeJobByAction(nodeAction)
	if err != nil {
		return nil, errors.Wrap(err, "generating job")
	}
	c.logger.Printf("generated resizeJob: %d", j.ID)

	// Save job in jobs map for future reference.
	c.jobs[j.ID] = j

	// Set job as currentJob.
	if c.currentJob != nil {
		return nil, fmt.Errorf("there is currently a resize job running")
	}
	c.currentJob = j

	return j, nil
}
297579
func handleGenerate(s *rpcServer, cmd interface{}, closeChan <-chan struct{}) (interface{}, error) {
	// Respond with an error if there are no addresses to pay the
	// created blocks to.
	if len(cfg.miningAddrs) == 0 {
		return nil, &btcjson.RPCError{
			Code: btcjson.ErrRPCInternal.Code,
			Message: "No payment addresses specified " +
				"via --miningaddr",
		}
	}

	// Respond with an error if there's virtually 0 chance of mining a block
	// with the CPU.
	if !s.cfg.ChainParams.GenerateSupported {
		return nil, &btcjson.RPCError{
			Code: btcjson.ErrRPCDifficulty,
			Message: fmt.Sprintf("No support for `generate` on "+
				"the current network, %s, as it's unlikely to "+
				"be possible to mine a block with the CPU.",
				s.cfg.ChainParams.Net),
		}
	}

	c := cmd.(*btcjson.GenerateCmd)

	// Respond with an error if the client is requesting 0 blocks to be generated.
	if c.NumBlocks == 0 {
		return nil, &btcjson.RPCError{
			Code:    btcjson.ErrRPCInternal.Code,
			Message: "Please request a nonzero number of blocks to generate.",
		}
	}

	// Create a reply
	reply := make([]string, c.NumBlocks)

	blockHashes, err := s.cfg.CPUMiner.GenerateNBlocks(c.NumBlocks)
	if err != nil {
		return nil, &btcjson.RPCError{
			Code:    btcjson.ErrRPCInternal.Code,
			Message: err.Error(),
		}
	}

	// Mine the correct number of blocks, assigning the hex representation of the
	// hash of each one to its place in the reply.
	for i, hash := range blockHashes {
		reply[i] = hash.String()
	}

	return reply, nil
}
269699
func (c *unstructuredConverter) ToUnstructured(obj interface{}) (map[string]interface{}, error) {
	var u map[string]interface{}
	var err error
	if unstr, ok := obj.(Unstructured); ok {
		u = unstr.UnstructuredContent()
	} else {
		t := reflect.TypeOf(obj)
		value := reflect.ValueOf(obj)
		if t.Kind() != reflect.Ptr || value.IsNil() {
			return nil, fmt.Errorf("ToUnstructured requires a non-nil pointer to an object, got %v", t)
		}
		u = map[string]interface{}{}
		err = toUnstructured(value.Elem(), reflect.ValueOf(&u).Elem())
	}
	if c.mismatchDetection {
		newUnstr := map[string]interface{}{}
		newErr := toUnstructuredViaJSON(obj, &newUnstr)
		if (err != nil) != (newErr != nil) {
			klog.Fatalf("ToUnstructured unexpected error for %v: error: %v; newErr: %v", obj, err, newErr)
		}
		if err == nil && !c.comparison.DeepEqual(u, newUnstr) {
			klog.Fatalf("ToUnstructured mismatch\nobj1: %#v\nobj2: %#v", u, newUnstr)
		}
	}
	if err != nil {
		return nil, err
	}
	return u, nil
}
834442
func ecGenerate(ctx pkcs11helpers.PKCtx, session pkcs11.SessionHandle, label, curveStr string) (*ecdsa.PublicKey, error) {
	curve, present := stringToCurve[curveStr]
	if !present {
		return nil, fmt.Errorf("curve %q not supported", curveStr)
	}
	keyID := make([]byte, 4)
	_, err := rand.Read(keyID)
	if err != nil {
		return nil, err
	}
	log.Printf("Generating ECDSA key with curve %s and ID %x\n", curveStr, keyID)
	args := ecArgs(label, curve, keyID)
	pub, priv, err := ctx.GenerateKeyPair(session, args.mechanism, args.publicAttrs, args.privateAttrs)
	if err != nil {
		return nil, err
	}
	log.Println("Key generated")
	log.Println("Extracting public key")
	pk, err := ecPub(ctx, session, pub, curve)
	if err != nil {
		return nil, err
	}
	log.Println("Extracted public key")
	log.Println("Verifying public key")
	err = ecVerify(ctx, session, priv, pk)
	if err != nil {
		return nil, err
	}
	log.Println("Key verified")
	return pk, nil
}
376004
func (pb ProjectionBuilder) buildChildNodes() ([]exprNode, error) {
	childNodes := make([]exprNode, 0, len(pb.names))
	for _, name := range pb.names {
		operand, err := name.BuildOperand()
		if err != nil {
			return []exprNode{}, err
		}
		childNodes = append(childNodes, operand.exprNode)
	}

	return childNodes, nil
}
40742
func (vr *validateRun) validateGenerated(ctx context.Context, path string) (*validateResult, error) {
	// -config-set flag must not be used in this mode, config sets are defined
	// on Starlark level.
	if vr.configSet != "" {
		return nil, base.NewCLIError("-config-set can't be used when validating Starlark-based configs")
	}

	meta := vr.DefaultMeta()
	output, err := base.GenerateConfigs(ctx, path, &meta, &vr.Meta)
	if err != nil {
		return nil, err
	}

	result := &validateResult{}

	if meta.ConfigDir != "-" {
		// Find files that are present on disk, but no longer in the output.
		tracked, err := lucicfg.FindTrackedFiles(meta.ConfigDir, meta.TrackedFiles)
		if err != nil {
			return result, err
		}
		for _, f := range tracked {
			if _, present := output.Data[f]; !present {
				result.Stale = append(result.Stale, f)
			}
		}
		// Find files that are newer in the output or do not exist on disk.
		changed, _ := output.Compare(meta.ConfigDir)
		result.Stale = append(result.Stale, changed...)
	}

	if len(result.Stale) != 0 {
		return result, fmt.Errorf(
			"following files on disk are out-of-date: %s.\n"+
				"  Run `lucicfg generate %q` to update them",
			strings.Join(result.Stale, ", "), path)
	}

	// Validate via LUCI Config RPC. This silently skips configs not belonging to
	// any config sets.
	result.Validation, err = base.ValidateOutput(
		ctx,
		output,
		vr.ConfigService,
		meta.ConfigServiceHost,
		meta.FailOnWarnings)
	return result, err
}
266305
func (s *Scheme) unstructuredToTyped(in Unstructured) (Object, error) {
	// the type must be something we recognize
	gvks, _, err := s.ObjectKinds(in)
	if err != nil {
		return nil, err
	}
	typed, err := s.New(gvks[0])
	if err != nil {
		return nil, err
	}
	if err := DefaultUnstructuredConverter.FromUnstructured(in.UnstructuredContent(), typed); err != nil {
		return nil, fmt.Errorf("unable to convert unstructured object to %v: %v", gvks[0], err)
	}
	return typed, nil
}
1267683
func NewClusterRoleAggregation(clusterRoleInformer rbacinformers.ClusterRoleInformer, clusterRoleClient rbacclient.ClusterRolesGetter) *ClusterRoleAggregationController {
	c := &ClusterRoleAggregationController{
		clusterRoleClient:  clusterRoleClient,
		clusterRoleLister:  clusterRoleInformer.Lister(),
		clusterRolesSynced: clusterRoleInformer.Informer().HasSynced,

		queue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "ClusterRoleAggregator"),
	}
	c.syncHandler = c.syncClusterRole

	clusterRoleInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
		AddFunc: func(obj interface{}) {
			c.enqueue()
		},
		UpdateFunc: func(old, cur interface{}) {
			c.enqueue()
		},
		DeleteFunc: func(uncast interface{}) {
			c.enqueue()
		},
	})
	return c
}
948644
func (g *genConversion) generateFor(inType, outType *types.Type, sw *generator.SnippetWriter) {
	klog.V(5).Infof("generating %v -> %v", inType, outType)
	var f func(*types.Type, *types.Type, *generator.SnippetWriter)

	switch inType.Kind {
	case types.Builtin:
		f = g.doBuiltin
	case types.Map:
		f = g.doMap
	case types.Slice:
		f = g.doSlice
	case types.Struct:
		f = g.doStruct
	case types.Pointer:
		f = g.doPointer
	case types.Alias:
		f = g.doAlias
	default:
		f = g.doUnknown
	}

	f(inType, outType, sw)
}
462177
func (g *Generator) MustGenerate(length, numDigits, numSymbols int, noUpper, allowRepeat bool) string {
	res, err := g.Generate(length, numDigits, numSymbols, noUpper, allowRepeat)
	if err != nil {
		panic(err)
	}
	return res
}
1160474
func (g *Generator) genTypeEncoder(t reflect.Type, in string, tags fieldTags, indent int, assumeNonEmpty bool) error {
	ws := strings.Repeat("  ", indent)

	marshalerIface := reflect.TypeOf((*easyjson.Marshaler)(nil)).Elem()
	if reflect.PtrTo(t).Implements(marshalerIface) {
		fmt.Fprintln(g.out, ws+"("+in+").MarshalEasyJSON(out)")
		return nil
	}

	marshalerIface = reflect.TypeOf((*json.Marshaler)(nil)).Elem()
	if reflect.PtrTo(t).Implements(marshalerIface) {
		fmt.Fprintln(g.out, ws+"out.Raw( ("+in+").MarshalJSON() )")
		return nil
	}

	marshalerIface = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()
	if reflect.PtrTo(t).Implements(marshalerIface) {
		fmt.Fprintln(g.out, ws+"out.RawText( ("+in+").MarshalText() )")
		return nil
	}

	err := g.genTypeEncoderNoCheck(t, in, tags, indent, assumeNonEmpty)
	return err
}
710973
func DefaultGenerators(cmdName string) map[string]generate.Generator {
	var generator map[string]generate.Generator
	switch cmdName {
	case "expose":
		generator = map[string]generate.Generator{
			ServiceV1GeneratorName: ServiceGeneratorV1{},
			ServiceV2GeneratorName: ServiceGeneratorV2{},
		}
	case "service-clusterip":
		generator = map[string]generate.Generator{
			ServiceClusterIPGeneratorV1Name: ServiceClusterIPGeneratorV1{},
		}
	case "service-nodeport":
		generator = map[string]generate.Generator{
			ServiceNodePortGeneratorV1Name: ServiceNodePortGeneratorV1{},
		}
	case "service-loadbalancer":
		generator = map[string]generate.Generator{
			ServiceLoadBalancerGeneratorV1Name: ServiceLoadBalancerGeneratorV1{},
		}
	case "deployment":
		// Create Deployment has only StructuredGenerators and no
		// param-based Generators.
		// The StructuredGenerators are as follows (as of 2018-03-16):
		// DeploymentBasicV1Beta1GeneratorName -> DeploymentBasicGeneratorV1
		// DeploymentBasicAppsV1Beta1GeneratorName -> DeploymentBasicAppsGeneratorV1Beta1
		// DeploymentBasicAppsV1GeneratorName -> DeploymentBasicAppsGeneratorV1
		generator = map[string]generate.Generator{}
	case "run":
		generator = map[string]generate.Generator{
			RunV1GeneratorName:                 BasicReplicationController{},
			RunPodV1GeneratorName:              BasicPod{},
			DeploymentV1Beta1GeneratorName:     DeploymentV1Beta1{},
			DeploymentAppsV1Beta1GeneratorName: DeploymentAppsV1Beta1{},
			DeploymentAppsV1GeneratorName:      DeploymentAppsV1{},
			JobV1GeneratorName:                 JobV1{},
			CronJobV2Alpha1GeneratorName:       CronJobV2Alpha1{},
			CronJobV1Beta1GeneratorName:        CronJobV1Beta1{},
		}
	case "namespace":
		generator = map[string]generate.Generator{
			NamespaceV1GeneratorName: NamespaceGeneratorV1{},
		}
	case "quota":
		generator = map[string]generate.Generator{
			ResourceQuotaV1GeneratorName: ResourceQuotaGeneratorV1{},
		}
	case "secret":
		generator = map[string]generate.Generator{
			SecretV1GeneratorName: SecretGeneratorV1{},
		}
	case "secret-for-docker-registry":
		generator = map[string]generate.Generator{
			SecretForDockerRegistryV1GeneratorName: SecretForDockerRegistryGeneratorV1{},
		}
	case "secret-for-tls":
		generator = map[string]generate.Generator{
			SecretForTLSV1GeneratorName: SecretForTLSGeneratorV1{},
		}
	}

	return generator
}
38217
func (s SecretForTLSGeneratorV1) StructuredGenerate() (runtime.Object, error) {
	if err := s.validate(); err != nil {
		return nil, err
	}
	tlsCrt, err := readFile(s.Cert)
	if err != nil {
		return nil, err
	}
	tlsKey, err := readFile(s.Key)
	if err != nil {
		return nil, err
	}

	if _, err := tls.X509KeyPair(tlsCrt, tlsKey); err != nil {
		return nil, fmt.Errorf("failed to load key pair %v", err)
	}
	// TODO: Add more validation.
	// 1. If the certificate contains intermediates, it is a valid chain.
	// 2. Format etc.

	secret := &v1.Secret{}
	secret.Name = s.Name
	secret.Type = v1.SecretTypeTLS
	secret.Data = map[string][]byte{}
	secret.Data[v1.TLSCertKey] = []byte(tlsCrt)
	secret.Data[v1.TLSPrivateKeyKey] = []byte(tlsKey)
	if s.AppendHash {
		h, err := hash.SecretHash(secret)
		if err != nil {
			return nil, err
		}
		secret.Name = fmt.Sprintf("%s-%s", secret.Name, h)
	}
	return secret, nil
}
981448
func (c *clusterRoleBindings) Create(clusterRoleBinding *v1.ClusterRoleBinding) (result *v1.ClusterRoleBinding, err error) {
	result = &v1.ClusterRoleBinding{}
	err = c.client.Post().
		Resource("clusterrolebindings").
		Body(clusterRoleBinding).
		Do().
		Into(result)
	return
}
92915
func (a *APIDefinition) RandomGenerator() *RandomGenerator {
	if a.rand == nil {
		a.rand = NewRandomGenerator(a.Name)
	}
	return a.rand
}