// ScheduleProfileLoop installs a profiling loop that pushes profile information
// to S3 for local consumption using a `profile` command that wraps
// pprof
187483
func ScheduleProfileLoop(s3BucketArchive interface{},
	snapshotInterval time.Duration,
	cpuProfileDuration time.Duration,
	profileNames ...string) {

	// When we're building, we want a template decorator that will be called
	// by `provision`. This decorator will be responsible for:
	// ensuring each function has IAM creds (if the role isn't a string)
	// to write to the profile location and also pushing the
	// Stack name info as reseved environment variables into the function
	// execution context so that the AWS lambda version of this function
	// can quickly lookup the StackName and instance information ...
	profileDecorator = func(stackName string, info *LambdaAWSInfo, S3Bucket string, logger *logrus.Logger) error {
		// If we have a role definition, ensure the function has rights to upload
		// to that bucket, with the limited ARN key
		logger.WithFields(logrus.Fields{
			"Function": info.lambdaFunctionName(),
		}).Info("Instrumenting function for profiling")

		// The bucket is either a literal or a gocf.StringExpr - which one?
		var bucketValue gocf.Stringable
		if s3BucketArchive != nil {
			bucketValue = spartaCF.DynamicValueToStringExpr(s3BucketArchive)
		} else {
			bucketValue = gocf.String(S3Bucket)
		}

		// 1. Add the env vars to the map
		if info.Options.Environment == nil {
			info.Options.Environment = make(map[string]*gocf.StringExpr)
		}
		info.Options.Environment[envVarStackName] = gocf.Ref("AWS::StackName").String()
		info.Options.Environment[envVarStackInstanceID] = gocf.Ref("AWS::StackId").String()
		info.Options.Environment[envVarProfileBucketName] = bucketValue.String()

		// Update the IAM role...
		if info.RoleDefinition != nil {
			arn := gocf.Join("",
				gocf.String("arn:aws:s3:::"),
				bucketValue,
				gocf.String("/"),
				gocf.String(profileSnapshotRootKeypath(stackName)),
				gocf.String("/*"))

			info.RoleDefinition.Privileges = append(info.RoleDefinition.Privileges, IAMRolePrivilege{
				Actions:  []string{"s3:PutObject"},
				Resource: arn.String(),
			})
		}
		return nil
	}
}
610754
func (cmd *BenchCommand) startProfiling(options *BenchOptions) {
	var err error

	// Start CPU profiling.
	if options.CPUProfile != "" {
		cpuprofile, err = os.Create(options.CPUProfile)
		if err != nil {
			fmt.Fprintf(cmd.Stderr, "bench: could not create cpu profile %q: %v\n", options.CPUProfile, err)
			os.Exit(1)
		}
		pprof.StartCPUProfile(cpuprofile)
	}

	// Start memory profiling.
	if options.MemProfile != "" {
		memprofile, err = os.Create(options.MemProfile)
		if err != nil {
			fmt.Fprintf(cmd.Stderr, "bench: could not create memory profile %q: %v\n", options.MemProfile, err)
			os.Exit(1)
		}
		runtime.MemProfileRate = 4096
	}

	// Start fatal profiling.
	if options.BlockProfile != "" {
		blockprofile, err = os.Create(options.BlockProfile)
		if err != nil {
			fmt.Fprintf(cmd.Stderr, "bench: could not create block profile %q: %v\n", options.BlockProfile, err)
			os.Exit(1)
		}
		runtime.SetBlockProfileRate(1)
	}
}
35677
func (e Endpoints) GetProfile(ctx context.Context, id string) (Profile, error) {
	request := getProfileRequest{ID: id}
	response, err := e.GetProfileEndpoint(ctx, request)
	if err != nil {
		return Profile{}, err
	}
	resp := response.(getProfileResponse)
	return resp.Profile, resp.Err
}
610986
func NewProfiler() (prof *Profiler, err error) {
	proc, err := joe.NewProc(procFile)
	if err != nil {
		return nil, err
	}
	prof = &Profiler{Procer: proc, Buffer: joe.NewBuffer()}
	err = prof.InitFrequency()
	if err != nil {
		return nil, err
	}
	return prof, nil
}
841570
func grabProfile(source, exec, buildid string, fetch plugin.Fetcher, sym plugin.Symbolizer, obj plugin.ObjTool, ui plugin.UI, f *flags) (*profile.Profile, error) {
	source, host, duration := adjustURL(source, *f.flagSeconds, ui)
	remote := host != ""

	if remote {
		ui.Print("Fetching profile from ", source)
		if duration != 0 {
			ui.Print("Please wait... (" + duration.String() + ")")
		}
	}

	now := time.Now()
	// Fetch profile from source.
	// Give 50% slack on the timeout.
	p, err := fetch(source, duration+duration/2, ui)
	if err != nil {
		return nil, err
	}

	// Update the time/duration if the profile source doesn't include it.
	// TODO(rsilvera): Remove this when we remove support for legacy profiles.
	if remote {
		if p.TimeNanos == 0 {
			p.TimeNanos = now.UnixNano()
		}
		if duration != 0 && p.DurationNanos == 0 {
			p.DurationNanos = int64(duration)
		}
	}

	// Replace executable/buildID with the options provided in the
	// command line. Assume the executable is the first Mapping entry.
	if exec != "" || buildid != "" {
		if len(p.Mapping) == 0 {
			// Create a fake mapping to hold the user option, and associate
			// all samples to it.
			m := &profile.Mapping{
				ID: 1,
			}
			for _, l := range p.Location {
				l.Mapping = m
			}
			p.Mapping = []*profile.Mapping{m}
		}
		if exec != "" {
			p.Mapping[0].File = exec
		}
		if buildid != "" {
			p.Mapping[0].BuildID = buildid
		}
	}

	if err := sym(*f.flagSymbolize, source, p, obj, ui); err != nil {
		return nil, err
	}

	// Save a copy of any remote profiles, unless the user is explicitly
	// saving it.
	if remote && !f.isFormat("proto") {
		prefix := "pprof."
		if len(p.Mapping) > 0 && p.Mapping[0].File != "" {
			prefix = prefix + filepath.Base(p.Mapping[0].File) + "."
		}
		if !strings.ContainsRune(host, os.PathSeparator) {
			prefix = prefix + host + "."
		}
		for _, s := range p.SampleType {
			prefix = prefix + s.Type + "."
		}

		dir := os.Getenv("PPROF_TMPDIR")
		tempFile, err := tempfile.New(dir, prefix, ".pb.gz")
		if err == nil {
			if err = p.Write(tempFile); err == nil {
				ui.PrintErr("Saved profile in ", tempFile.Name())
			}
		}
		if err != nil {
			ui.PrintErr("Could not save profile: ", err)
		}
	}

	if err := p.Demangle(obj.Demangle); err != nil {
		ui.PrintErr("Failed to demangle profile: ", err)
	}

	if err := p.CheckValid(); err != nil {
		return nil, fmt.Errorf("Grab %s: %v", source, err)
	}

	return p, nil
}
258230
func WithApparmorProfile(profile string) SpecOpts {
	return func(_ context.Context, _ Client, _ *containers.Container, s *Spec) error {
		setProcess(s)
		s.Process.ApparmorProfile = profile
		return nil
	}
}
71886
func (remote *RemoteDebugger) StopProfiler() (p Profile, err error) {
	res, err := remote.sendRawReplyRequest("Profiler.stop", nil)
	if err != nil {
		return p, err
	}
	var response map[string]json.RawMessage
	err = json.Unmarshal(res, &response)
	if err != nil {
		return p, err
	}
	err = json.Unmarshal(response["profile"], &p)
	return p, err
}
927126
func (e Endpoints) PostProfile(ctx context.Context, p Profile) error {
	request := postProfileRequest{Profile: p}
	response, err := e.PostProfileEndpoint(ctx, request)
	if err != nil {
		return err
	}
	resp := response.(postProfileResponse)
	return resp.Err
}
226853
func dataForPseudoProfiling() [][]types.Datum {
	var rows [][]types.Datum
	row := types.MakeDatums(
		0,                      // QUERY_ID
		0,                      // SEQ
		"",                     // STATE
		types.NewDecFromInt(0), // DURATION
		types.NewDecFromInt(0), // CPU_USER
		types.NewDecFromInt(0), // CPU_SYSTEM
		0,                      // CONTEXT_VOLUNTARY
		0,                      // CONTEXT_INVOLUNTARY
		0,                      // BLOCK_OPS_IN
		0,                      // BLOCK_OPS_OUT
		0,                      // MESSAGES_SENT
		0,                      // MESSAGES_RECEIVED
		0,                      // PAGE_FAULTS_MAJOR
		0,                      // PAGE_FAULTS_MINOR
		0,                      // SWAPS
		"",                     // SOURCE_FUNCTION
		"",                     // SOURCE_FILE
		0,                      // SOURCE_LINE
	)
	rows = append(rows, row)
	return rows
}
954086
func WithProfile(profile string) oci.SpecOpts {
	return func(_ context.Context, _ oci.Client, _ *containers.Container, s *specs.Spec) error {
		s.Linux.Seccomp = &specs.LinuxSeccomp{}
		f, err := ioutil.ReadFile(profile)
		if err != nil {
			return fmt.Errorf("cannot load seccomp profile %q: %v", profile, err)
		}
		if err := json.Unmarshal(f, s.Linux.Seccomp); err != nil {
			return fmt.Errorf("decoding seccomp profile failed %q: %v", profile, err)
		}
		return nil
	}
}
201599
func (c *Config) LoadProfile(profileDir string, proxyName string) error {
	profileDir = FullProfilePath(profileDir)
	// read the profile:
	cp, err := ProfileFromDir(profileDir, ProxyHost(proxyName))
	if err != nil {
		if trace.IsNotFound(err) {
			return nil
		}
		return trace.Wrap(err)
	}

	// DELETE IN: 3.1.0
	// The "proxy_host" field (and associated ports) have been deprecated and
	// replaced with "proxy_web_addr" and "proxy_ssh_addr".
	if cp.ProxyHost != "" {
		if cp.ProxyWebPort == 0 {
			cp.ProxyWebPort = defaults.HTTPListenPort
		}
		if cp.ProxySSHPort == 0 {
			cp.ProxySSHPort = defaults.SSHProxyListenPort
		}
		c.WebProxyAddr = net.JoinHostPort(cp.ProxyHost, strconv.Itoa(cp.ProxyWebPort))
		c.SSHProxyAddr = net.JoinHostPort(cp.ProxyHost, strconv.Itoa(cp.ProxySSHPort))
	}

	c.Username = cp.Username
	c.SiteName = cp.SiteName
	c.KubeProxyAddr = cp.KubeProxyAddr

	// UPDATE IN: 3.1.0
	// Remove the above DELETE IN block and below if statements and always set
	// WebProxyAddr and SSHProxyAddr. This needs to be done right now to support
	// backward compatibility with Teleport 2.0.
	if cp.WebProxyAddr != "" {
		c.WebProxyAddr = cp.WebProxyAddr
	}
	if cp.SSHProxyAddr != "" {
		c.SSHProxyAddr = cp.SSHProxyAddr
	}

	c.LocalForwardPorts, err = ParsePortForwardSpec(cp.ForwardedPorts)
	if err != nil {
		log.Warnf("Unable to parse port forwarding in user profile: %v.", err)
	}

	c.DynamicForwardedPorts, err = ParseDynamicPortForwardSpec(cp.DynamicForwardedPorts)
	if err != nil {
		log.Warnf("Unable to parse dynamic port forwarding in user profile: %v.", err)
	}

	return nil
}
152624
func IdentityFilterByProfileURL(profileURL string) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		return db.Where("profile_url = ?", profileURL).Limit(1)
	}
}
96586
func (c *ContivClient) NetprofilePost(obj *Netprofile) error {
	// build key and URL
	keyStr := obj.TenantName + ":" + obj.ProfileName
	url := c.baseURL + "/api/v1/netprofiles/" + keyStr + "/"

	// http post the object
	err := c.httpPost(url, obj)
	if err != nil {
		log.Debugf("Error creating netprofile %+v. Err: %v", obj, err)
		return err
	}

	return nil
}
420683
func startProfiler(profilerType, dirPath string) (minioProfiler, error) {
	var err error
	if dirPath == "" {
		dirPath, err = ioutil.TempDir("", "profile")
		if err != nil {
			return nil, err
		}
	}

	var profiler interface {
		Stop()
	}

	var profilerFileName string

	// Enable profiler and set the name of the file that pkg/pprof
	// library creates to store profiling data.
	switch profilerType {
	case "cpu":
		profiler = profile.Start(profile.CPUProfile, profile.NoShutdownHook, profile.ProfilePath(dirPath))
		profilerFileName = "cpu.pprof"
	case "mem":
		profiler = profile.Start(profile.MemProfile, profile.NoShutdownHook, profile.ProfilePath(dirPath))
		profilerFileName = "mem.pprof"
	case "block":
		profiler = profile.Start(profile.BlockProfile, profile.NoShutdownHook, profile.ProfilePath(dirPath))
		profilerFileName = "block.pprof"
	case "mutex":
		profiler = profile.Start(profile.MutexProfile, profile.NoShutdownHook, profile.ProfilePath(dirPath))
		profilerFileName = "mutex.pprof"
	case "trace":
		profiler = profile.Start(profile.TraceProfile, profile.NoShutdownHook, profile.ProfilePath(dirPath))
		profilerFileName = "trace.out"
	default:
		return nil, errors.New("profiler type unknown")
	}

	return &profilerWrapper{
		stopFn: profiler.Stop,
		pathFn: func() string {
			return filepath.Join(dirPath, profilerFileName)
		},
	}, nil
}
1274120
func WriteProfilesToFile(filename string, profiles []*Profile) error {
	out := io.Writer(os.Stdout)
	if filename != "-" {
		f, err := os.Create(filename)
		if err != nil {
			return err
		}
		defer f.Close()
		out = f
	}

	if err := WriteProfiles(out, profiles); err != nil {
		return err
	}

	return nil
}
1148056
func LoadProfile(path string) (result Profile, err error) {
	var contents []byte
	contents, err = ioutil.ReadFile(path)
	if err != nil {
		err = fmt.Errorf("failed to open file (%s) while loading token: %v", path, err)
		return
	}
	reader := utfbom.SkipOnly(bytes.NewReader(contents))

	dec := json.NewDecoder(reader)
	if err = dec.Decode(&result); err != nil {
		err = fmt.Errorf("failed to decode contents of file (%s) into a Profile representation: %v", path, err)
		return
	}

	return
}
866127
func StopCPUProfile() error {
	if !inCPUProfile {
		return errors.New("CPU profile hasn't been started!")
	}
	pprof.StopCPUProfile()
	inCPUProfile = false
	return nil
}