// createCodePipelineTriggerPackage handles marshaling the template, zipping
// the config files in the package, and the
544848
func createCodePipelineTriggerPackage(cfTemplateJSON []byte, ctx *workflowContext) (string, error) {
	tmpFile, err := system.TemporaryFile(ScratchDirectory, ctx.userdata.codePipelineTrigger)
	if err != nil {
		return "", errors.Wrapf(err, "Failed to create temporary file for CodePipeline")
	}

	ctx.logger.WithFields(logrus.Fields{
		"PipelineName": tmpFile.Name(),
	}).Info("Creating pipeline archive")

	templateArchive := zip.NewWriter(tmpFile)
	ctx.logger.WithFields(logrus.Fields{
		"Path": tmpFile.Name(),
	}).Info("Creating CodePipeline archive")

	// File info for the binary executable
	zipEntryName := "cloudformation.json"
	bytesWriter, bytesWriterErr := templateArchive.Create(zipEntryName)
	if bytesWriterErr != nil {
		return "", bytesWriterErr
	}

	bytesReader := bytes.NewReader(cfTemplateJSON)
	written, writtenErr := io.Copy(bytesWriter, bytesReader)
	if nil != writtenErr {
		return "", writtenErr
	}
	ctx.logger.WithFields(logrus.Fields{
		"WrittenBytes": written,
		"ZipName":      zipEntryName,
	}).Debug("Archiving file")

	// If there is a codePipelineEnvironments defined, then we'll need to get all the
	// maps, marshal them to JSON, then add the JSON to the ZIP archive.
	if nil != codePipelineEnvironments {
		for eachEnvironment, eachMap := range codePipelineEnvironments {
			codePipelineParameters := map[string]interface{}{
				"Parameters": eachMap,
			}
			environmentJSON, environmentJSONErr := json.Marshal(codePipelineParameters)
			if nil != environmentJSONErr {
				ctx.logger.Error("Failed to Marshal CodePipeline environment: " + eachEnvironment)
				return "", environmentJSONErr
			}
			var envVarName = fmt.Sprintf("%s.json", eachEnvironment)

			// File info for the binary executable
			binaryWriter, binaryWriterErr := templateArchive.Create(envVarName)
			if binaryWriterErr != nil {
				return "", binaryWriterErr
			}
			_, writeErr := binaryWriter.Write(environmentJSON)
			if writeErr != nil {
				return "", writeErr
			}
		}
	}
	archiveCloseErr := templateArchive.Close()
	if nil != archiveCloseErr {
		return "", archiveCloseErr
	}
	tempfileCloseErr := tmpFile.Close()
	if nil != tempfileCloseErr {
		return "", tempfileCloseErr
	}
	// Leave it here...
	ctx.logger.WithFields(logrus.Fields{
		"File": filepath.Base(tmpFile.Name()),
	}).Info("Created CodePipeline archive")
	// The key is the name + the pipeline name
	return tmpFile.Name(), nil
}
660557
func marshalTriggersList(t []*internal.Trigger) []byte {
	if len(t) == 0 {
		return nil
	}
	blob, err := proto.Marshal(&internal.TriggerList{Triggers: t})
	if err != nil {
		panic(err)
	}
	return blob
}
1180768
func (s *Resolver) SetPipelineConfig(v *PipelineConfig) *Resolver {
	s.PipelineConfig = v
	return s
}
1135933
func (o *EgressACLTemplate) CreateEgressACLEntryTemplate(child *EgressACLEntryTemplate) *bambou.Error {

	return bambou.CurrentSession().CreateChild(o, child)
}
165377
func (t *Template) GetAllAWSCodePipelinePipelineResources() map[string]*resources.AWSCodePipelinePipeline {
	results := map[string]*resources.AWSCodePipelinePipeline{}
	for name, untyped := range t.Resources {
		switch resource := untyped.(type) {
		case *resources.AWSCodePipelinePipeline:
			results[name] = resource
		}
	}
	return results
}
941268
func NewRouteAppenderAggregator(ctx context.Context, chainBuilder chainBuilder, conf static.Configuration, entryPointName string, currentConfiguration *safe.Safe) *RouteAppenderAggregator {
	aggregator := &RouteAppenderAggregator{}

	if conf.Providers != nil && conf.Providers.Rest != nil {
		aggregator.AddAppender(conf.Providers.Rest)
	}

	if conf.API != nil && conf.API.EntryPoint == entryPointName {
		chain := chainBuilder.BuildChain(ctx, conf.API.Middlewares)
		aggregator.AddAppender(&WithMiddleware{
			appender: api.Handler{
				EntryPoint:            conf.API.EntryPoint,
				Dashboard:             conf.API.Dashboard,
				Statistics:            conf.API.Statistics,
				DashboardAssets:       conf.API.DashboardAssets,
				CurrentConfigurations: currentConfiguration,
				Debug:                 conf.Global.Debug,
			},
			routerMiddlewares: chain,
		})

	}

	if conf.Ping != nil && conf.Ping.EntryPoint == entryPointName {
		chain := chainBuilder.BuildChain(ctx, conf.Ping.Middlewares)
		aggregator.AddAppender(&WithMiddleware{
			appender:          conf.Ping,
			routerMiddlewares: chain,
		})
	}

	if conf.Metrics != nil && conf.Metrics.Prometheus != nil && conf.Metrics.Prometheus.EntryPoint == entryPointName {
		chain := chainBuilder.BuildChain(ctx, conf.Metrics.Prometheus.Middlewares)
		aggregator.AddAppender(&WithMiddleware{
			appender:          metrics.PrometheusHandler{},
			routerMiddlewares: chain,
		})
	}

	return aggregator
}
402644
func CodeGenModel(modelFile io.Reader, outFile io.Writer, optFns ...func(*CodeGenOptions)) error {
	var opts CodeGenOptions
	opts.Set(optFns...)

	resolver, err := DecodeModel(modelFile, func(d *DecodeModelOptions) {
		*d = opts.DecodeModelOptions
	})
	if err != nil {
		return err
	}

	v := struct {
		Resolver
		CodeGenOptions
	}{
		Resolver:       resolver,
		CodeGenOptions: opts,
	}

	tmpl := template.Must(template.New("tmpl").Funcs(funcMap).Parse(v3Tmpl))
	if err := tmpl.ExecuteTemplate(outFile, "defaults", v); err != nil {
		return fmt.Errorf("failed to execute template, %v", err)
	}

	return nil
}
781739
func (a *api) CompileServiceTemplate(config CompileTemplateConfig) (*template.ServiceTemplate, error) {
	st, err := template.BuildFromPath(config.Dir)
	if err != nil {
		return nil, err
	}

	var mapImageNames func(*servicedefinition.ServiceDefinition)
	mapImageNames = func(svc *servicedefinition.ServiceDefinition) {
		if imageID, found := config.Map[svc.ImageID]; found {
			svc.ImageID = imageID
		}
		for i := range svc.Services {
			mapImageNames(&svc.Services[i])
		}
	}
	for idx := range st.Services {
		mapImageNames(&st.Services[idx])
	}
	return st, nil
}
302228
func (p *PackageProvider) getCodePackageFromLegacyPP(name, version string) ([]byte, error) {
	codePackage, err := p.LegacyPP.GetChaincodeCodePackage(name, version)
	if err != nil {
		return nil, errors.Wrap(err, "error loading code package from ChaincodeDeploymentSpec")
	}
	return codePackage, nil
}
513246
func NewDeploymentConfigPipeline(g osgraph.Graph, dcNode *appsgraph.DeploymentConfigNode) (DeploymentConfigPipeline, IntSet) {
	covered := IntSet{}
	covered.Insert(dcNode.ID())

	dcPipeline := DeploymentConfigPipeline{}
	dcPipeline.DeploymentConfig = dcNode

	// for everything that can trigger a deployment, create an image pipeline and add it to the list
	for _, istNode := range g.PredecessorNodesByEdgeKind(dcNode, appsedges.TriggersDeploymentEdgeKind) {
		imagePipeline, covers := NewImagePipelineFromImageTagLocation(g, istNode, istNode.(ImageTagLocation))

		covered.Insert(covers.List()...)
		dcPipeline.Images = append(dcPipeline.Images, imagePipeline)
	}

	// for image that we use, create an image pipeline and add it to the list
	for _, tagNode := range g.PredecessorNodesByEdgeKind(dcNode, appsedges.UsedInDeploymentEdgeKind) {
		imagePipeline, covers := NewImagePipelineFromImageTagLocation(g, tagNode, tagNode.(ImageTagLocation))

		covered.Insert(covers.List()...)
		dcPipeline.Images = append(dcPipeline.Images, imagePipeline)
	}

	dcPipeline.ActiveDeployment, dcPipeline.InactiveDeployments = appsedges.RelevantDeployments(g, dcNode)
	for _, rc := range dcPipeline.InactiveDeployments {
		_, covers := NewReplicationController(g, rc)
		covered.Insert(covers.List()...)
	}

	if dcPipeline.ActiveDeployment != nil {
		_, covers := NewReplicationController(g, dcPipeline.ActiveDeployment)
		covered.Insert(covers.List()...)
	}

	return dcPipeline, covered
}
624034
func (mr *MockEnforcerMockRecorder) EnableDatapathPacketTracing(contextID, direction, interval interface{}) *gomock.Call {
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EnableDatapathPacketTracing", reflect.TypeOf((*MockEnforcer)(nil).EnableDatapathPacketTracing), contextID, direction, interval)
}
228241
func NewControlPacketWithHeader(fh FixedHeader) (cp ControlPacket) {
	switch fh.MessageType {
	case Connect:
		cp = &ConnectPacket{FixedHeader: fh, uuid: uuid.NewUUID()}
	case Connack:
		cp = &ConnackPacket{FixedHeader: fh, uuid: uuid.NewUUID()}
	case Disconnect:
		cp = &DisconnectPacket{FixedHeader: fh, uuid: uuid.NewUUID()}
	case Publish:
		cp = &PublishPacket{FixedHeader: fh, uuid: uuid.NewUUID()}
	case Puback:
		cp = &PubackPacket{FixedHeader: fh, uuid: uuid.NewUUID()}
	case Pubrec:
		cp = &PubrecPacket{FixedHeader: fh, uuid: uuid.NewUUID()}
	case Pubrel:
		cp = &PubrelPacket{FixedHeader: fh, uuid: uuid.NewUUID()}
	case Pubcomp:
		cp = &PubcompPacket{FixedHeader: fh, uuid: uuid.NewUUID()}
	case Subscribe:
		cp = &SubscribePacket{FixedHeader: fh, uuid: uuid.NewUUID()}
	case Suback:
		cp = &SubackPacket{FixedHeader: fh, uuid: uuid.NewUUID()}
	case Unsubscribe:
		cp = &UnsubscribePacket{FixedHeader: fh, uuid: uuid.NewUUID()}
	case Unsuback:
		cp = &UnsubackPacket{FixedHeader: fh, uuid: uuid.NewUUID()}
	case Pingreq:
		cp = &PingreqPacket{FixedHeader: fh, uuid: uuid.NewUUID()}
	case Pingresp:
		cp = &PingrespPacket{FixedHeader: fh, uuid: uuid.NewUUID()}
	default:
		return nil
	}
	return cp
}
841742
func (m *MockEC2) CreateLaunchTemplate(request *ec2.CreateLaunchTemplateInput) (*ec2.CreateLaunchTemplateOutput, error) {
	m.mutex.Lock()
	defer m.mutex.Unlock()

	if m.LaunchTemplates == nil {
		m.LaunchTemplates = make(map[string]*ec2.ResponseLaunchTemplateData)
	}
	if m.LaunchTemplates[aws.StringValue(request.LaunchTemplateName)] != nil {
		return nil, fmt.Errorf("duplicate LaunchTemplateName %s", aws.StringValue(request.LaunchTemplateName))
	}
	resp := &ec2.ResponseLaunchTemplateData{
		DisableApiTermination: request.LaunchTemplateData.DisableApiTermination,
		EbsOptimized:          request.LaunchTemplateData.EbsOptimized,
		ImageId:               request.LaunchTemplateData.ImageId,
		InstanceType:          request.LaunchTemplateData.InstanceType,
		KeyName:               request.LaunchTemplateData.KeyName,
		SecurityGroupIds:      request.LaunchTemplateData.SecurityGroupIds,
		SecurityGroups:        request.LaunchTemplateData.SecurityGroups,
		UserData:              request.LaunchTemplateData.UserData,
	}
	m.LaunchTemplates[aws.StringValue(request.LaunchTemplateName)] = resp

	// @GOD DAMN AWS request vs response .. fu@@@@@ .. so much typing!!#@#@#

	if request.LaunchTemplateData.Monitoring != nil {
		resp.Monitoring = &ec2.LaunchTemplatesMonitoring{Enabled: request.LaunchTemplateData.Monitoring.Enabled}
	}
	if request.LaunchTemplateData.CpuOptions != nil {
		resp.CpuOptions = &ec2.LaunchTemplateCpuOptions{
			CoreCount:      request.LaunchTemplateData.CpuOptions.CoreCount,
			ThreadsPerCore: request.LaunchTemplateData.CpuOptions.ThreadsPerCore,
		}
	}
	if len(request.LaunchTemplateData.BlockDeviceMappings) > 0 {
		for _, x := range request.LaunchTemplateData.BlockDeviceMappings {
			resp.BlockDeviceMappings = append(resp.BlockDeviceMappings, &ec2.LaunchTemplateBlockDeviceMapping{
				DeviceName: x.DeviceName,
				Ebs: &ec2.LaunchTemplateEbsBlockDevice{
					DeleteOnTermination: x.Ebs.DeleteOnTermination,
					Encrypted:           x.Ebs.Encrypted,
					Iops:                x.Ebs.Iops,
					KmsKeyId:            x.Ebs.KmsKeyId,
					SnapshotId:          x.Ebs.SnapshotId,
					VolumeSize:          x.Ebs.VolumeSize,
					VolumeType:          x.Ebs.VolumeType,
				},
				NoDevice:    x.NoDevice,
				VirtualName: x.VirtualName,
			})
		}
	}
	if request.LaunchTemplateData.CreditSpecification != nil {
		resp.CreditSpecification = &ec2.CreditSpecification{CpuCredits: request.LaunchTemplateData.CreditSpecification.CpuCredits}
	}
	if request.LaunchTemplateData.IamInstanceProfile != nil {
		resp.IamInstanceProfile = &ec2.LaunchTemplateIamInstanceProfileSpecification{
			Arn:  request.LaunchTemplateData.IamInstanceProfile.Arn,
			Name: request.LaunchTemplateData.IamInstanceProfile.Name,
		}
	}
	if request.LaunchTemplateData.InstanceMarketOptions != nil {
		resp.InstanceMarketOptions = &ec2.LaunchTemplateInstanceMarketOptions{
			MarketType: request.LaunchTemplateData.InstanceMarketOptions.MarketType,
			SpotOptions: &ec2.LaunchTemplateSpotMarketOptions{
				BlockDurationMinutes:         request.LaunchTemplateData.InstanceMarketOptions.SpotOptions.BlockDurationMinutes,
				InstanceInterruptionBehavior: request.LaunchTemplateData.InstanceMarketOptions.SpotOptions.InstanceInterruptionBehavior,
				MaxPrice:                     request.LaunchTemplateData.InstanceMarketOptions.SpotOptions.MaxPrice,
				SpotInstanceType:             request.LaunchTemplateData.InstanceMarketOptions.SpotOptions.SpotInstanceType,
				ValidUntil:                   request.LaunchTemplateData.InstanceMarketOptions.SpotOptions.ValidUntil,
			},
		}
	}
	if len(request.LaunchTemplateData.NetworkInterfaces) > 0 {
		for _, x := range request.LaunchTemplateData.NetworkInterfaces {
			resp.NetworkInterfaces = append(resp.NetworkInterfaces, &ec2.LaunchTemplateInstanceNetworkInterfaceSpecification{
				AssociatePublicIpAddress:       x.AssociatePublicIpAddress,
				DeleteOnTermination:            x.DeleteOnTermination,
				Description:                    x.Description,
				DeviceIndex:                    x.DeviceIndex,
				Groups:                         x.Groups,
				Ipv6AddressCount:               x.Ipv6AddressCount,
				NetworkInterfaceId:             x.NetworkInterfaceId,
				PrivateIpAddress:               x.PrivateIpAddress,
				PrivateIpAddresses:             x.PrivateIpAddresses,
				SecondaryPrivateIpAddressCount: x.SecondaryPrivateIpAddressCount,
				SubnetId:                       x.SubnetId,
			})
		}
	}

	return &ec2.CreateLaunchTemplateOutput{}, nil
}
1105592
func buildTriggerConfigs(configured []interface{}) []*codedeploy.TriggerConfig {
	configs := make([]*codedeploy.TriggerConfig, 0, len(configured))
	for _, raw := range configured {
		var config codedeploy.TriggerConfig
		m := raw.(map[string]interface{})

		config.TriggerEvents = expandStringSet(m["trigger_events"].(*schema.Set))
		config.TriggerName = aws.String(m["trigger_name"].(string))
		config.TriggerTargetArn = aws.String(m["trigger_target_arn"].(string))

		configs = append(configs, &config)
	}
	return configs
}
1338802
func NewControlPacket(packetType byte) (cp ControlPacket) {
	switch packetType {
	case Connect:
		cp = &ConnectPacket{FixedHeader: &FixedHeader{MessageType: Connect}}
	case Connack:
		cp = &ConnackPacket{FixedHeader: &FixedHeader{MessageType: Connack}}
	case Disconnect:
		cp = &DisconnectPacket{FixedHeader: &FixedHeader{MessageType: Disconnect}}
	case Publish:
		cp = &PublishPacket{FixedHeader: &FixedHeader{MessageType: Publish}}
	case Puback:
		cp = &PubackPacket{FixedHeader: &FixedHeader{MessageType: Puback}}
	case Pubrec:
		cp = &PubrecPacket{FixedHeader: &FixedHeader{MessageType: Pubrec}}
	case Pubrel:
		cp = &PubrelPacket{FixedHeader: &FixedHeader{MessageType: Pubrel, Qos: 1}}
	case Pubcomp:
		cp = &PubcompPacket{FixedHeader: &FixedHeader{MessageType: Pubcomp}}
	case Subscribe:
		cp = &SubscribePacket{FixedHeader: &FixedHeader{MessageType: Subscribe, Qos: 1}}
	case Suback:
		cp = &SubackPacket{FixedHeader: &FixedHeader{MessageType: Suback}}
	case Unsubscribe:
		cp = &UnsubscribePacket{FixedHeader: &FixedHeader{MessageType: Unsubscribe, Qos: 1}}
	case Unsuback:
		cp = &UnsubackPacket{FixedHeader: &FixedHeader{MessageType: Unsuback}}
	case Pingreq:
		cp = &PingreqPacket{FixedHeader: &FixedHeader{MessageType: Pingreq}}
	case Pingresp:
		cp = &PingrespPacket{FixedHeader: &FixedHeader{MessageType: Pingresp}}
	default:
		return nil
	}
	return cp
}
985383
func NewDeploymentConfigTriggers(config *appsv1.DeploymentConfig) *TriggerDefinition {
	t := &TriggerDefinition{}
	for _, trigger := range config.Spec.Triggers {
		switch trigger.Type {
		case appsv1.DeploymentTriggerOnConfigChange:
			t.ConfigChange = true
		case appsv1.DeploymentTriggerOnImageChange:
			t.ImageChange = append(t.ImageChange, ImageChangeTrigger{
				Auto:      trigger.ImageChangeParams.Automatic,
				Names:     trigger.ImageChangeParams.ContainerNames,
				From:      trigger.ImageChangeParams.From.Name,
				Namespace: defaultNamespace(trigger.ImageChangeParams.From.Namespace, config.Namespace),
			})
		}
	}
	return t
}
853973
func (c *AppConfig) buildPipelines(components app.ComponentReferences, environment app.Environment, buildEnvironment app.Environment) (app.PipelineGroup, error) {
	pipelines := app.PipelineGroup{}

	buildArgs, err := utilenv.ParseBuildArg(c.BuildArgs, c.In)
	if err != nil {
		return nil, err
	}

	var DockerStrategyOptions *buildv1.DockerStrategyOptions
	if len(c.BuildArgs) > 0 {
		DockerStrategyOptions = &buildv1.DockerStrategyOptions{
			BuildArgs: buildArgs,
		}
	}

	numDockerBuilds := 0

	pipelineBuilder := app.NewPipelineBuilder(c.Name, buildEnvironment, DockerStrategyOptions, c.OutputDocker).To(c.To)
	for _, group := range components.Group() {
		klog.V(4).Infof("found group: %v", group)
		common := app.PipelineGroup{}
		for _, ref := range group {
			refInput := ref.Input()
			from := refInput.String()
			var pipeline *app.Pipeline

			switch {
			case refInput.ExpectToBuild:
				klog.V(4).Infof("will add %q secrets into a build for a source build of %q", strings.Join(c.Secrets, ","), refInput.Uses)
				if err := refInput.Uses.AddBuildSecrets(c.Secrets); err != nil {
					return nil, fmt.Errorf("unable to add build secrets %q: %v", strings.Join(c.Secrets, ","), err)
				}

				klog.V(4).Infof("will add %q configMaps into a build for a source build of %q", strings.Join(c.ConfigMaps, ","), refInput.Uses)
				if err = refInput.Uses.AddBuildConfigMaps(c.ConfigMaps); err != nil {
					return nil, fmt.Errorf("unable to add build configMaps %q: %v", strings.Join(c.Secrets, ","), err)
				}

				if refInput.Uses.GetStrategy() == newapp.StrategyDocker {
					numDockerBuilds++
				}

				var (
					image *app.ImageRef
					err   error
				)
				if refInput.ResolvedMatch != nil {
					inputImage, err := app.InputImageFromMatch(refInput.ResolvedMatch)
					if err != nil {
						return nil, fmt.Errorf("can't build %q: %v", from, err)
					}
					if !inputImage.AsImageStream && from != "scratch" && (refInput.Uses == nil || refInput.Uses.GetStrategy() != newapp.StrategyPipeline) {
						msg := "Could not find an image stream match for %q. Make sure that a Docker image with that tag is available on the node for the build to succeed."
						klog.Warningf(msg, from)
					}
					image = inputImage
				}

				klog.V(4).Infof("will use %q as the base image for a source build of %q", ref, refInput.Uses)
				if pipeline, err = pipelineBuilder.NewBuildPipeline(from, image, refInput.Uses, c.BinaryBuild); err != nil {
					return nil, fmt.Errorf("can't build %q: %v", refInput.Uses, err)
				}
			default:
				inputImage, err := app.InputImageFromMatch(refInput.ResolvedMatch)
				if err != nil {
					return nil, fmt.Errorf("can't include %q: %v", from, err)
				}
				if !inputImage.AsImageStream {
					msg := "Could not find an image stream match for %q. Make sure that a Docker image with that tag is available on the node for the deployment to succeed."
					klog.Warningf(msg, from)
				}

				klog.V(4).Infof("will include %q", ref)
				if pipeline, err = pipelineBuilder.NewImagePipeline(from, inputImage); err != nil {
					return nil, fmt.Errorf("can't include %q: %v", refInput, err)
				}
			}
			if c.Deploy {
				if err := pipeline.NeedsDeployment(environment, c.Labels, c.AsTestDeployment); err != nil {
					return nil, fmt.Errorf("can't set up a deployment for %q: %v", refInput, err)
				}
			}
			if c.NoOutput {
				pipeline.Build.Output = nil
			}
			if refInput.Uses != nil && refInput.Uses.GetStrategy() == newapp.StrategyPipeline {
				pipeline.Build.Output = nil
				pipeline.Deployment = nil
				pipeline.Image = nil
				pipeline.InputImage = nil
			}
			common = append(common, pipeline)
			if err := common.Reduce(); err != nil {
				return nil, fmt.Errorf("can't create a pipeline from %s: %v", common, err)
			}
			describeBuildPipelineWithImage(c.Out, ref, pipeline, c.OriginNamespace)
		}
		pipelines = append(pipelines, common...)
	}

	if len(c.BuildArgs) > 0 {
		if numDockerBuilds == 0 {
			return nil, fmt.Errorf("Cannot use '--build-arg' without a Docker build")
		}
		if numDockerBuilds > 1 {
			fmt.Fprintf(c.ErrOut, "--> WARNING: Applying --build-arg to multiple Docker builds.\n")
		}
	}

	return pipelines, nil
}