How to use err method of main Package

Best Syzkaller code snippet using main.err

configmaps.go

Source:configmaps.go Github

copy

Full Screen

...7)8// ParseConfigMap parses ConfigMap into ConfigParams.9func ParseConfigMap(cfgm *v1.ConfigMap, nginxPlus bool, hasAppProtect bool) *ConfigParams {10 cfgParams := NewDefaultConfigParams(nginxPlus)11 if serverTokens, exists, err := GetMapKeyAsBool(cfgm.Data, "server-tokens", cfgm); exists {12 if err != nil {13 if nginxPlus {14 cfgParams.ServerTokens = cfgm.Data["server-tokens"]15 } else {16 glog.Error(err)17 }18 } else {19 cfgParams.ServerTokens = "off"20 if serverTokens {21 cfgParams.ServerTokens = "on"22 }23 }24 }25 if lbMethod, exists := cfgm.Data["lb-method"]; exists {26 if nginxPlus {27 if parsedMethod, err := ParseLBMethodForPlus(lbMethod); err != nil {28 glog.Errorf("Configmap %s/%s: Invalid value for the lb-method key: got %q: %v", cfgm.GetNamespace(), cfgm.GetName(), lbMethod, err)29 } else {30 cfgParams.LBMethod = parsedMethod31 }32 } else {33 if parsedMethod, err := ParseLBMethod(lbMethod); err != nil {34 glog.Errorf("Configmap %s/%s: Invalid value for the lb-method key: got %q: %v", cfgm.GetNamespace(), cfgm.GetName(), lbMethod, err)35 } else {36 cfgParams.LBMethod = parsedMethod37 }38 }39 }40 if proxyConnectTimeout, exists := cfgm.Data["proxy-connect-timeout"]; exists {41 cfgParams.ProxyConnectTimeout = proxyConnectTimeout42 }43 if proxyReadTimeout, exists := cfgm.Data["proxy-read-timeout"]; exists {44 cfgParams.ProxyReadTimeout = proxyReadTimeout45 }46 if proxySendTimeout, exists := cfgm.Data["proxy-send-timeout"]; exists {47 cfgParams.ProxySendTimeout = proxySendTimeout48 }49 if proxyHideHeaders, exists, err := GetMapKeyAsStringSlice(cfgm.Data, "proxy-hide-headers", cfgm, ","); exists {50 if err != nil {51 glog.Error(err)52 } else {53 cfgParams.ProxyHideHeaders = proxyHideHeaders54 }55 }56 if proxyPassHeaders, exists, err := GetMapKeyAsStringSlice(cfgm.Data, "proxy-pass-headers", cfgm, ","); exists {57 if err != nil {58 glog.Error(err)59 } else {60 cfgParams.ProxyPassHeaders = proxyPassHeaders61 }62 }63 if clientMaxBodySize, exists := cfgm.Data["client-max-body-size"]; exists {64 cfgParams.ClientMaxBodySize = clientMaxBodySize65 }66 if serverNamesHashBucketSize, exists := cfgm.Data["server-names-hash-bucket-size"]; exists {67 cfgParams.MainServerNamesHashBucketSize = serverNamesHashBucketSize68 }69 if serverNamesHashMaxSize, exists := cfgm.Data["server-names-hash-max-size"]; exists {70 cfgParams.MainServerNamesHashMaxSize = serverNamesHashMaxSize71 }72 if HTTP2, exists, err := GetMapKeyAsBool(cfgm.Data, "http2", cfgm); exists {73 if err != nil {74 glog.Error(err)75 } else {76 cfgParams.HTTP2 = HTTP277 }78 }79 if redirectToHTTPS, exists, err := GetMapKeyAsBool(cfgm.Data, "redirect-to-https", cfgm); exists {80 if err != nil {81 glog.Error(err)82 } else {83 cfgParams.RedirectToHTTPS = redirectToHTTPS84 }85 }86 if sslRedirect, exists, err := GetMapKeyAsBool(cfgm.Data, "ssl-redirect", cfgm); exists {87 if err != nil {88 glog.Error(err)89 } else {90 cfgParams.SSLRedirect = sslRedirect91 }92 }93 if hsts, exists, err := GetMapKeyAsBool(cfgm.Data, "hsts", cfgm); exists {94 if err != nil {95 glog.Error(err)96 } else {97 parsingErrors := false98 hstsMaxAge, existsMA, err := GetMapKeyAsInt64(cfgm.Data, "hsts-max-age", cfgm)99 if existsMA && err != nil {100 glog.Error(err)101 parsingErrors = true102 }103 hstsIncludeSubdomains, existsIS, err := GetMapKeyAsBool(cfgm.Data, "hsts-include-subdomains", cfgm)104 if existsIS && err != nil {105 glog.Error(err)106 parsingErrors = true107 }108 hstsBehindProxy, existsBP, err := GetMapKeyAsBool(cfgm.Data, "hsts-behind-proxy", cfgm)109 if existsBP && err != nil {110 glog.Error(err)111 parsingErrors = true112 }113 if parsingErrors {114 glog.Errorf("Configmap %s/%s: There are configuration issues with hsts annotations, skipping options for all hsts settings", cfgm.GetNamespace(), cfgm.GetName())115 } else {116 cfgParams.HSTS = hsts117 if existsMA {118 cfgParams.HSTSMaxAge = hstsMaxAge119 }120 if existsIS {121 cfgParams.HSTSIncludeSubdomains = hstsIncludeSubdomains122 }123 if existsBP {124 cfgParams.HSTSBehindProxy = hstsBehindProxy125 }126 }127 }128 }129 if proxyProtocol, exists, err := GetMapKeyAsBool(cfgm.Data, "proxy-protocol", cfgm); exists {130 if err != nil {131 glog.Error(err)132 } else {133 cfgParams.ProxyProtocol = proxyProtocol134 }135 }136 if realIPHeader, exists := cfgm.Data["real-ip-header"]; exists {137 cfgParams.RealIPHeader = realIPHeader138 }139 if setRealIPFrom, exists, err := GetMapKeyAsStringSlice(cfgm.Data, "set-real-ip-from", cfgm, ","); exists {140 if err != nil {141 glog.Error(err)142 } else {143 cfgParams.SetRealIPFrom = setRealIPFrom144 }145 }146 if realIPRecursive, exists, err := GetMapKeyAsBool(cfgm.Data, "real-ip-recursive", cfgm); exists {147 if err != nil {148 glog.Error(err)149 } else {150 cfgParams.RealIPRecursive = realIPRecursive151 }152 }153 if sslProtocols, exists := cfgm.Data["ssl-protocols"]; exists {154 cfgParams.MainServerSSLProtocols = sslProtocols155 }156 if sslPreferServerCiphers, exists, err := GetMapKeyAsBool(cfgm.Data, "ssl-prefer-server-ciphers", cfgm); exists {157 if err != nil {158 glog.Error(err)159 } else {160 cfgParams.MainServerSSLPreferServerCiphers = sslPreferServerCiphers161 }162 }163 if sslCiphers, exists := cfgm.Data["ssl-ciphers"]; exists {164 cfgParams.MainServerSSLCiphers = strings.Trim(sslCiphers, "\n")165 }166 if sslDHParamFile, exists := cfgm.Data["ssl-dhparam-file"]; exists {167 sslDHParamFile = strings.Trim(sslDHParamFile, "\n")168 cfgParams.MainServerSSLDHParamFileContent = &sslDHParamFile169 }170 if errorLogLevel, exists := cfgm.Data["error-log-level"]; exists {171 cfgParams.MainErrorLogLevel = errorLogLevel172 }173 if accessLogOff, exists, err := GetMapKeyAsBool(cfgm.Data, "access-log-off", cfgm); exists {174 if err != nil {175 glog.Error(err)176 } else {177 cfgParams.MainAccessLogOff = accessLogOff178 }179 }180 if logFormat, exists, err := GetMapKeyAsStringSlice(cfgm.Data, "log-format", cfgm, "\n"); exists {181 if err != nil {182 glog.Error(err)183 } else {184 cfgParams.MainLogFormat = logFormat185 }186 }187 if logFormatEscaping, exists := cfgm.Data["log-format-escaping"]; exists {188 logFormatEscaping = strings.TrimSpace(logFormatEscaping)189 if logFormatEscaping != "" {190 cfgParams.MainLogFormatEscaping = logFormatEscaping191 }192 }193 if streamLogFormat, exists, err := GetMapKeyAsStringSlice(cfgm.Data, "stream-log-format", cfgm, "\n"); exists {194 if err != nil {195 glog.Error(err)196 } else {197 cfgParams.MainStreamLogFormat = streamLogFormat198 }199 }200 if streamLogFormatEscaping, exists := cfgm.Data["stream-log-format-escaping"]; exists {201 streamLogFormatEscaping = strings.TrimSpace(streamLogFormatEscaping)202 if streamLogFormatEscaping != "" {203 cfgParams.MainStreamLogFormatEscaping = streamLogFormatEscaping204 }205 }206 if defaultServerAccessLogOff, exists, err := GetMapKeyAsBool(cfgm.Data, "default-server-access-log-off", cfgm); exists {207 if err != nil {208 glog.Error(err)209 } else {210 cfgParams.DefaultServerAccessLogOff = defaultServerAccessLogOff211 }212 }213 if defaultServerReturn, exists := cfgm.Data["default-server-return"]; exists {214 cfgParams.DefaultServerReturn = defaultServerReturn215 }216 if proxyBuffering, exists, err := GetMapKeyAsBool(cfgm.Data, "proxy-buffering", cfgm); exists {217 if err != nil {218 glog.Error(err)219 } else {220 cfgParams.ProxyBuffering = proxyBuffering221 }222 }223 if proxyBuffers, exists := cfgm.Data["proxy-buffers"]; exists {224 cfgParams.ProxyBuffers = proxyBuffers225 }226 if proxyBufferSize, exists := cfgm.Data["proxy-buffer-size"]; exists {227 cfgParams.ProxyBufferSize = proxyBufferSize228 }229 if proxyMaxTempFileSize, exists := cfgm.Data["proxy-max-temp-file-size"]; exists {230 cfgParams.ProxyMaxTempFileSize = proxyMaxTempFileSize231 }232 if mainMainSnippets, exists, err := GetMapKeyAsStringSlice(cfgm.Data, "main-snippets", cfgm, "\n"); exists {233 if err != nil {234 glog.Error(err)235 } else {236 cfgParams.MainMainSnippets = mainMainSnippets237 }238 }239 if mainHTTPSnippets, exists, err := GetMapKeyAsStringSlice(cfgm.Data, "http-snippets", cfgm, "\n"); exists {240 if err != nil {241 glog.Error(err)242 } else {243 cfgParams.MainHTTPSnippets = mainHTTPSnippets244 }245 }246 if locationSnippets, exists, err := GetMapKeyAsStringSlice(cfgm.Data, "location-snippets", cfgm, "\n"); exists {247 if err != nil {248 glog.Error(err)249 } else {250 cfgParams.LocationSnippets = locationSnippets251 }252 }253 if serverSnippets, exists, err := GetMapKeyAsStringSlice(cfgm.Data, "server-snippets", cfgm, "\n"); exists {254 if err != nil {255 glog.Error(err)256 } else {257 cfgParams.ServerSnippets = serverSnippets258 }259 }260 if _, exists, err := GetMapKeyAsInt(cfgm.Data, "worker-processes", cfgm); exists {261 if err != nil && cfgm.Data["worker-processes"] != "auto" {262 glog.Errorf("Configmap %s/%s: Invalid value for worker-processes key: must be an integer or the string 'auto', got %q", cfgm.GetNamespace(), cfgm.GetName(), cfgm.Data["worker-processes"])263 } else {264 cfgParams.MainWorkerProcesses = cfgm.Data["worker-processes"]265 }266 }267 if workerCPUAffinity, exists := cfgm.Data["worker-cpu-affinity"]; exists {268 cfgParams.MainWorkerCPUAffinity = workerCPUAffinity269 }270 if workerShutdownTimeout, exists := cfgm.Data["worker-shutdown-timeout"]; exists {271 cfgParams.MainWorkerShutdownTimeout = workerShutdownTimeout272 }273 if workerConnections, exists := cfgm.Data["worker-connections"]; exists {274 cfgParams.MainWorkerConnections = workerConnections275 }276 if workerRlimitNofile, exists := cfgm.Data["worker-rlimit-nofile"]; exists {277 cfgParams.MainWorkerRlimitNofile = workerRlimitNofile278 }279 if keepalive, exists, err := GetMapKeyAsInt(cfgm.Data, "keepalive", cfgm); exists {280 if err != nil {281 glog.Error(err)282 } else {283 cfgParams.Keepalive = keepalive284 }285 }286 if maxFails, exists, err := GetMapKeyAsInt(cfgm.Data, "max-fails", cfgm); exists {287 if err != nil {288 glog.Error(err)289 } else {290 cfgParams.MaxFails = maxFails291 }292 }293 if upstreamZoneSize, exists := cfgm.Data["upstream-zone-size"]; exists {294 cfgParams.UpstreamZoneSize = upstreamZoneSize295 }296 if failTimeout, exists := cfgm.Data["fail-timeout"]; exists {297 cfgParams.FailTimeout = failTimeout298 }299 if mainTemplate, exists := cfgm.Data["main-template"]; exists {300 cfgParams.MainTemplate = &mainTemplate301 }302 if ingressTemplate, exists := cfgm.Data["ingress-template"]; exists {303 cfgParams.IngressTemplate = &ingressTemplate304 }305 if virtualServerTemplate, exists := cfgm.Data["virtualserver-template"]; exists {306 cfgParams.VirtualServerTemplate = &virtualServerTemplate307 }308 if mainStreamSnippets, exists, err := GetMapKeyAsStringSlice(cfgm.Data, "stream-snippets", cfgm, "\n"); exists {309 if err != nil {310 glog.Error(err)311 } else {312 cfgParams.MainStreamSnippets = mainStreamSnippets313 }314 }315 if resolverAddresses, exists, err := GetMapKeyAsStringSlice(cfgm.Data, "resolver-addresses", cfgm, ","); exists {316 if err != nil {317 glog.Error(err)318 } else {319 if nginxPlus {320 cfgParams.ResolverAddresses = resolverAddresses321 } else {322 glog.Warning("ConfigMap key 'resolver-addresses' requires NGINX Plus")323 }324 }325 }326 if resolverIpv6, exists, err := GetMapKeyAsBool(cfgm.Data, "resolver-ipv6", cfgm); exists {327 if err != nil {328 glog.Error(err)329 } else {330 if nginxPlus {331 cfgParams.ResolverIPV6 = resolverIpv6332 } else {333 glog.Warning("ConfigMap key 'resolver-ipv6' requires NGINX Plus")334 }335 }336 }337 if resolverValid, exists := cfgm.Data["resolver-valid"]; exists {338 if nginxPlus {339 cfgParams.ResolverValid = resolverValid340 } else {341 glog.Warning("ConfigMap key 'resolver-valid' requires NGINX Plus")342 }343 }344 if resolverTimeout, exists := cfgm.Data["resolver-timeout"]; exists {345 if nginxPlus {346 cfgParams.ResolverTimeout = resolverTimeout347 } else {348 glog.Warning("ConfigMap key 'resolver-timeout' requires NGINX Plus")349 }350 }351 if keepaliveTimeout, exists := cfgm.Data["keepalive-timeout"]; exists {352 cfgParams.MainKeepaliveTimeout = keepaliveTimeout353 }354 if keepaliveRequests, exists, err := GetMapKeyAsInt64(cfgm.Data, "keepalive-requests", cfgm); exists {355 if err != nil {356 glog.Error(err)357 } else {358 cfgParams.MainKeepaliveRequests = keepaliveRequests359 }360 }361 if varHashBucketSize, exists, err := GetMapKeyAsUint64(cfgm.Data, "variables-hash-bucket-size", cfgm, true); exists {362 if err != nil {363 glog.Error(err)364 } else {365 cfgParams.VariablesHashBucketSize = varHashBucketSize366 }367 }368 if varHashMaxSize, exists, err := GetMapKeyAsUint64(cfgm.Data, "variables-hash-max-size", cfgm, false); exists {369 if err != nil {370 glog.Error(err)371 } else {372 cfgParams.VariablesHashMaxSize = varHashMaxSize373 }374 }375 if openTracingTracer, exists := cfgm.Data["opentracing-tracer"]; exists {376 cfgParams.MainOpenTracingTracer = openTracingTracer377 }378 if openTracingTracerConfig, exists := cfgm.Data["opentracing-tracer-config"]; exists {379 cfgParams.MainOpenTracingTracerConfig = openTracingTracerConfig380 }381 if cfgParams.MainOpenTracingTracer != "" || cfgParams.MainOpenTracingTracerConfig != "" {382 cfgParams.MainOpenTracingLoadModule = true383 }384 if openTracing, exists, err := GetMapKeyAsBool(cfgm.Data, "opentracing", cfgm); exists {385 if err != nil {386 glog.Error(err)387 } else {388 if cfgParams.MainOpenTracingLoadModule {389 cfgParams.MainOpenTracingEnabled = openTracing390 } else {391 glog.Error("ConfigMap Key 'opentracing' requires both 'opentracing-tracer' and 'opentracing-tracer-config' Keys configured, Opentracing will be disabled")392 }393 }394 }395 if hasAppProtect {396 if appProtectFailureModeAction, exists := cfgm.Data["app-protect-failure-mode-action"]; exists {397 if appProtectFailureModeAction == "pass" || appProtectFailureModeAction == "drop" {398 cfgParams.MainAppProtectFailureModeAction = appProtectFailureModeAction399 } else {400 glog.Error("ConfigMap Key 'app-protect-failure-mode-action' must have value 'pass' or 'drop'. Ignoring.")...

Full Screen

Full Screen

pns.go

Source:pns.go Github

copy

Full Screen

...14 log "github.com/sirupsen/logrus"15 corev1 "k8s.io/api/core/v1"16 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"17 "k8s.io/client-go/kubernetes"18 "github.com/argoproj/argo/errors"19 "github.com/argoproj/argo/util/archive"20 "github.com/argoproj/argo/workflow/common"21 execcommon "github.com/argoproj/argo/workflow/executor/common"22)23type PNSExecutor struct {24 clientset *kubernetes.Clientset25 podName string26 namespace string27 // ctrIDToPid maps a containerID to a process ID28 ctrIDToPid map[string]int29 // pidToCtrID maps a process ID to a container ID30 pidToCtrID map[int]string31 // pidFileHandles holds file handles to all root containers32 pidFileHandles map[int]*fileInfo33 // thisPID is the pid of this process34 thisPID int35 // mainPID holds the main container's pid36 mainPID int37 // mainFS holds a file descriptor to the main filesystem, allowing the executor to access the38 // filesystem after the main process exited39 mainFS *os.File40 // rootFS holds a file descriptor to the root filesystem, allowing the executor to exit out of a chroot41 rootFS *os.File42 // debug enables additional debugging43 debug bool44 // hasOutputs indicates if the template has outputs. determines if we need to45 hasOutputs bool46}47type fileInfo struct {48 file os.File49 info os.FileInfo50}51func NewPNSExecutor(clientset *kubernetes.Clientset, podName, namespace string, hasOutputs bool) (*PNSExecutor, error) {52 thisPID := os.Getpid()53 log.Infof("Creating PNS executor (namespace: %s, pod: %s, pid: %d, hasOutputs: %v)", namespace, podName, thisPID, hasOutputs)54 if thisPID == 1 {55 return nil, errors.New(errors.CodeBadRequest, "process namespace sharing is not enabled on pod")56 }57 return &PNSExecutor{58 clientset: clientset,59 podName: podName,60 namespace: namespace,61 ctrIDToPid: make(map[string]int),62 pidToCtrID: make(map[int]string),63 pidFileHandles: make(map[int]*fileInfo),64 thisPID: thisPID,65 debug: log.GetLevel() == log.DebugLevel,66 hasOutputs: hasOutputs,67 }, nil68}69func (p *PNSExecutor) GetFileContents(containerID string, sourcePath string) (string, error) {70 err := p.enterChroot()71 if err != nil {72 return "", err73 }74 defer func() { _ = p.exitChroot() }()75 out, err := ioutil.ReadFile(sourcePath)76 if err != nil {77 return "", err78 }79 return string(out), nil80}81// enterChroot enters chroot of the main container82func (p *PNSExecutor) enterChroot() error {83 if p.mainFS == nil {84 return errors.InternalErrorf("could not chroot into main for artifact collection: container may have exited too quickly")85 }86 if err := p.mainFS.Chdir(); err != nil {87 return errors.InternalWrapErrorf(err, "failed to chdir to main filesystem: %v", err)88 }89 err := syscall.Chroot(".")90 if err != nil {91 return errors.InternalWrapErrorf(err, "failed to chroot to main filesystem: %v", err)92 }93 return nil94}95// exitChroot exits chroot96func (p *PNSExecutor) exitChroot() error {97 if err := p.rootFS.Chdir(); err != nil {98 return errors.InternalWrapError(err)99 }100 err := syscall.Chroot(".")101 if err != nil {102 return errors.InternalWrapError(err)103 }104 return nil105}106// CopyFile copies a source file in a container to a local path107func (p *PNSExecutor) CopyFile(containerID string, sourcePath string, destPath string, compressionLevel int) (err error) {108 destFile, err := os.Create(destPath)109 if err != nil {110 return err111 }112 defer func() {113 // exit chroot and close the file. preserve the original error114 deferErr := p.exitChroot()115 if err == nil && deferErr != nil {116 err = errors.InternalWrapError(deferErr)117 }118 deferErr = destFile.Close()119 if err == nil && deferErr != nil {120 err = errors.InternalWrapError(deferErr)121 }122 }()123 w := bufio.NewWriter(destFile)124 err = p.enterChroot()125 if err != nil {126 return err127 }128 err = archive.TarGzToWriter(sourcePath, compressionLevel, w)129 return err130}131func (p *PNSExecutor) WaitInit() error {132 if !p.hasOutputs {133 return nil134 }135 go p.pollRootProcesses(time.Minute)136 // Secure a filehandle on our own root. This is because we will chroot back and forth from137 // the main container's filesystem, to our own.138 rootFS, err := os.Open("/")139 if err != nil {140 return errors.InternalWrapError(err)141 }142 p.rootFS = rootFS143 return nil144}145// Wait for the container to complete146func (p *PNSExecutor) Wait(containerID string) error {147 mainPID, err := p.getContainerPID(containerID)148 if err != nil {149 if !p.hasOutputs {150 log.Warnf("Ignoring wait failure: %v. Process assumed to have completed", err)151 return nil152 }153 return err154 }155 log.Infof("Main pid identified as %d", mainPID)156 p.mainPID = mainPID157 for pid, f := range p.pidFileHandles {158 if pid == p.mainPID {159 log.Info("Successfully secured file handle on main container root filesystem")160 p.mainFS = &f.file161 } else {162 log.Infof("Closing root filehandle for non-main pid %d", pid)163 _ = f.file.Close()164 }165 }166 if p.mainFS == nil {167 log.Warn("Failed to secure file handle on main container's root filesystem. Output artifacts from base image layer will fail")168 }169 // wait for pid to complete170 log.Infof("Waiting for main pid %d to complete", mainPID)171 err = executil.WaitPID(mainPID)172 if err != nil {173 return err174 }175 log.Infof("Main pid %d completed", mainPID)176 return nil177}178// pollRootProcesses will poll /proc for root pids (pids without parents) in a tight loop, for the179// purpose of securing an open file handle against /proc/<pid>/root as soon as possible.180// It opens file handles on all root pids because at this point, we do not yet know which pid is the181// "main" container.182// Polling is necessary because it is not possible to use something like fsnotify against procfs.183func (p *PNSExecutor) pollRootProcesses(timeout time.Duration) {184 log.Warnf("Polling root processes (%v)", timeout)185 deadline := time.Now().Add(timeout)186 for {187 p.updateCtrIDMap()188 if p.mainFS != nil {189 log.Info("Stopped root processes polling due to successful securing of main root fs")190 break191 }192 if time.Now().After(deadline) {193 log.Warnf("Polling root processes timed out (%v)", timeout)194 break195 }196 time.Sleep(50 * time.Millisecond)197 }198}199func (p *PNSExecutor) GetOutputStream(containerID string, combinedOutput bool) (io.ReadCloser, error) {200 if !combinedOutput {201 log.Warn("non combined output unsupported")202 }203 opts := corev1.PodLogOptions{204 Container: common.MainContainerName,205 Follow: true,206 }207 return p.clientset.CoreV1().Pods(p.namespace).GetLogs(p.podName, &opts).Stream()208}209func (p *PNSExecutor) GetExitCode(containerID string) (string, error) {210 log.Infof("Getting exit code of %s", containerID)211 _, containerStatus, err := p.GetContainerStatus(containerID)212 if err != nil {213 return "", fmt.Errorf("could not get container status: %s", err)214 }215 if containerStatus.State.Terminated != nil {216 return fmt.Sprint(containerStatus.State.Terminated.ExitCode), nil217 }218 return "", nil219}220// Kill a list of containerIDs first with a SIGTERM then with a SIGKILL after a grace period221func (p *PNSExecutor) Kill(containerIDs []string) error {222 var asyncErr error223 wg := sync.WaitGroup{}224 for _, cid := range containerIDs {225 wg.Add(1)226 go func(containerID string) {227 err := p.killContainer(containerID)228 if err != nil && asyncErr != nil {229 asyncErr = err230 }231 wg.Done()232 }(cid)233 }234 wg.Wait()235 return asyncErr236}237func (p *PNSExecutor) killContainer(containerID string) error {238 pid, err := p.getContainerPID(containerID)239 if err != nil {240 log.Warnf("Ignoring kill container failure of %s: %v. Process assumed to have completed", containerID, err)241 return nil242 }243 // On Unix systems, FindProcess always succeeds and returns a Process244 // for the given pid, regardless of whether the process exists.245 proc, _ := os.FindProcess(pid)246 log.Infof("Sending SIGTERM to pid %d", pid)247 err = proc.Signal(syscall.SIGTERM)248 if err != nil {249 log.Warnf("Failed to SIGTERM pid %d: %v", pid, err)250 }251 waitPIDOpts := executil.WaitPIDOpts{Timeout: execcommon.KillGracePeriod * time.Second}252 err = executil.WaitPID(pid, waitPIDOpts)253 if err == nil {254 log.Infof("PID %d completed", pid)255 return nil256 }257 if err != executil.ErrWaitPIDTimeout {258 return err259 }260 log.Warnf("Timed out (%v) waiting for pid %d to complete after SIGTERM. Issing SIGKILL", waitPIDOpts.Timeout, pid)261 time.Sleep(30 * time.Minute)262 err = proc.Signal(syscall.SIGKILL)263 if err != nil {264 log.Warnf("Failed to SIGKILL pid %d: %v", pid, err)265 }266 return err267}268// getContainerPID returns the pid associated with the container id. Returns error if it was unable269// to be determined because no running root processes exist with that container ID270func (p *PNSExecutor) getContainerPID(containerID string) (int, error) {271 pid, ok := p.ctrIDToPid[containerID]272 if ok {273 return pid, nil274 }275 p.updateCtrIDMap()276 pid, ok = p.ctrIDToPid[containerID]277 if !ok {278 return -1, errors.InternalErrorf("Failed to determine pid for containerID %s: container may have exited too quickly", containerID)279 }280 return pid, nil281}282// updateCtrIDMap updates the mapping between container IDs to PIDs283func (p *PNSExecutor) updateCtrIDMap() {284 allProcs, err := gops.Processes()285 if err != nil {286 log.Warnf("Failed to list processes: %v", err)287 return288 }289 for _, proc := range allProcs {290 pid := proc.Pid()291 if pid == 1 || pid == p.thisPID || proc.PPid() != 0 {292 // ignore the pause container, our own pid, and non-root processes293 continue294 }295 // Useful code for debugging:296 if p.debug {297 if data, err := ioutil.ReadFile(fmt.Sprintf("/proc/%d/root", pid) + "/etc/os-release"); err == nil {298 log.Infof("pid %d: %s", pid, string(data))299 _, _ = parseContainerID(pid)300 }301 }302 if p.hasOutputs && p.mainFS == nil {303 rootPath := fmt.Sprintf("/proc/%d/root", pid)304 currInfo, err := os.Stat(rootPath)305 if err != nil {306 log.Warnf("Failed to stat %s: %v", rootPath, err)307 continue308 }309 log.Infof("pid %d: %v", pid, currInfo)310 prevInfo := p.pidFileHandles[pid]311 // Secure the root filehandle of the process. NOTE if the file changed, it means that312 // the main container may have switched (e.g. gone from busybox to the user's container)313 if prevInfo == nil || !os.SameFile(prevInfo.info, currInfo) {314 fs, err := os.Open(rootPath)315 if err != nil {316 log.Warnf("Failed to open %s: %v", rootPath, err)317 continue318 }319 log.Infof("Secured filehandle on %s", rootPath)320 p.pidFileHandles[pid] = &fileInfo{321 info: currInfo,322 file: *fs,323 }324 if prevInfo != nil {325 _ = prevInfo.file.Close()326 }327 }328 }329 // Update maps of pids to container ids330 if _, ok := p.pidToCtrID[pid]; !ok {331 containerID, err := parseContainerID(pid)332 if err != nil {333 log.Warnf("Failed to identify containerID for process %d", pid)334 continue335 }336 log.Infof("containerID %s mapped to pid %d", containerID, pid)337 p.ctrIDToPid[containerID] = pid338 p.pidToCtrID[pid] = containerID339 }340 }341}342func (p *PNSExecutor) GetContainerStatus(containerID string) (*corev1.Pod, *corev1.ContainerStatus, error) {343 pod, err := p.clientset.CoreV1().Pods(p.namespace).Get(p.podName, metav1.GetOptions{})344 if err != nil {345 return nil, nil, fmt.Errorf("could not get pod: %s", err)346 }347 for _, containerStatus := range pod.Status.ContainerStatuses {348 if execcommon.GetContainerID(&containerStatus) != containerID {349 continue350 }351 return pod, &containerStatus, nil352 }353 return nil, nil, errors.New(errors.CodeNotFound, fmt.Sprintf("containerID %q is not found in the pod %s", containerID, p.podName))354}355// parseContainerID parses the containerID of a pid356func parseContainerID(pid int) (string, error) {357 cgroupPath := fmt.Sprintf("/proc/%d/cgroup", pid)358 cgroupFile, err := os.OpenFile(cgroupPath, os.O_RDONLY, os.ModePerm)359 if err != nil {360 return "", errors.InternalWrapError(err)361 }362 defer func() { _ = cgroupFile.Close() }()363 sc := bufio.NewScanner(cgroupFile)364 for sc.Scan() {365 // See https://www.systutorials.com/docs/linux/man/5-proc/ for /proc/XX/cgroup format. e.g.:366 // 5:cpuacct,cpu,cpuset:/daemons367 line := sc.Text()368 log.Debugf("pid %d: %s", pid, line)369 parts := strings.Split(line, "/")370 if len(parts) > 1 {371 if containerID := parts[len(parts)-1]; containerID != "" {372 // need to check for empty string because the line may look like: 5:rdma:/373 // for crio we need to get rid of "crio-" prefix and ".scope" suffix374 // e.g. crio-7a92a067289f6197148912be1c15f20f0330c7f3c541473d3b9c4043ca137b42.scope375 containerID := strings.TrimSuffix(strings.TrimPrefix(containerID, "crio-"), ".scope")376 return containerID, nil377 }378 }379 }380 return "", errors.InternalErrorf("Failed to parse container ID from %s", cgroupPath)381}...

Full Screen

Full Screen

Go_files.go

Source:Go_files.go Github

copy

Full Screen

...7 "os"8)910func main() { 11 f, err := os.Create("test.txt")12 if err != nil {13 fmt.Println(err)14 return15 }16 l, err := f.WriteString("Hello World")17 if err != nil {18 fmt.Println(err)19 f.Close()20 return21 }22 fmt.Println(l, "bytes written successfully")23 err = f.Close()24 if err != nil {25 fmt.Println(err)26 return27 }28}2930$go run main.go3111 bytes written successfully3233// 2. example3435package main36 37import (38 "log"39 "os"40)41 42func main() {43 emptyFile, err := os.Create("empty.txt")44 if err != nil {45 log.Fatal(err)46 }47 log.Println(emptyFile)48 emptyFile.Close()49}5051$go run main.go522020/11/17 06:54:29 &{0xc42009c060}5354// 3. example5556package main57import (58 "log"59 "os"60)61 62func main() {63 _, err := os.Stat("test")64 65 if os.IsNotExist(err) {66 errDir := os.MkdirAll("test", 0755)67 if errDir != nil {68 log.Fatal(err)69 }70 71 }72}7374$go run main.go7576// 4. example7778package main79 80import (81 "log"82 "os"83)84 85func main() {86 oldName := "test.txt"87 newName := "testing.txt"88 err := os.Rename(oldName, newName)89 if err != nil {90 log.Fatal(err)91 }92}9394$go run main.go952020/11/17 06:55:09 rename test.txt testing.txt: no such file or directory96exit status 1979899// 5.example100101package main102 103import (104 "io"105 "log"106 "os"107)108 109func main() {110 111 sourceFile, err := os.Open("/var/www/html/src/test.txt")112 if err != nil {113 log.Fatal(err)114 }115 defer sourceFile.Close()116 117 // Create new file118 newFile, err := os.Create("/var/www/html/test.txt")119 if err != nil {120 log.Fatal(err)121 }122 defer newFile.Close()123 124 bytesCopied, err := io.Copy(newFile, sourceFile)125 if err != nil {126 log.Fatal(err)127 }128 log.Printf("Copied %d bytes.", bytesCopied)129}130131 $go run main.go1322020/11/17 06:55:58 open /src/test.txt: no such file or directory133exit status 1134135// 6.example136137package main138 139import (140 "fmt"141 "log"142 "os"143)144 145func main() {146 fileStat, err := os.Stat("test.txt")147 148 if err != nil {149 log.Fatal(err)150 }151 152 fmt.Println("File Name:", fileStat.Name()) 153 fmt.Println("Size:", fileStat.Size()) 154 fmt.Println("Permissions:", fileStat.Mode()) 155 fmt.Println("Last Modified:", fileStat.ModTime()) 156 fmt.Println("Is Directory: ", fileStat.IsDir()) 157}158159$go run main.go1602020/11/17 06:57:46 stat test.txt: no such file or directory161exit status 1162163// 7.example 164165package main166 167import (168 "log"169 "os"170)171 172func main() {173 err := os.Remove("/var/www/html/test.txt")174 if err != nil {175 log.Fatal(err)176 }177}178179$go run main.go1802020/11/17 06:58:39 remove /test.txt: no such file or directory181exit status 1182183// 8.example184185package main186 187import (188 "bufio"189 "fmt"190 "io/ioutil"191 "os"192 "strings"193)194 195func main() {196 filename := "test.txt"197 198 filebuffer, err := ioutil.ReadFile(filename)199 if err != nil {200 fmt.Println(err)201 os.Exit(1)202 }203 inputdata := string(filebuffer)204 data := bufio.NewScanner(strings.NewReader(inputdata))205 data.Split(bufio.ScanRunes)206 207 for data.Scan() {208 fmt.Print(data.Text())209 }210}211$go run main.go212open test.txt: no such file or directory213exit status 1214215// 9.example216217package main218 219import (220 "log"221 "os"222)223 224func main() {225 err := os.Truncate("test.txt", 100)226 227 if err != nil {228 log.Fatal(err)229 }230}231232$go run main.go2332020/11/17 06:59:53 truncate test.txt: no such file or directory234exit status 1235236// 10.example237238package main239 240import (241 "log"242 "os"243 "time"244)245 246func main() {247 // Test File existence.248 _, err := os.Stat("test.txt")249 if err != nil {250 if os.IsNotExist(err) {251 log.Fatal("File does not exist.")252 }253 }254 log.Println("File exist.")255 256 257 err = os.Chmod("test.txt", 0777)258 if err != nil {259 log.Println(err)260 }261 262 263 err = os.Chown("test.txt", os.Getuid(), os.Getgid())264 if err != nil {265 log.Println(err)266 }267 268 269 addOneDayFromNow := time.Now().Add(24 * time.Hour)270 lastAccessTime := addOneDayFromNow271 lastModifyTime := addOneDayFromNow272 err = os.Chtimes("test.txt", lastAccessTime, lastModifyTime)273 if err != nil {274 log.Println(err)275 }276}277278$go run main.go2792020/11/17 07:01:08 File does not exist.280exit status 1281282283 ...

Full Screen

Full Screen

err

Using AI Code Generation

copy

Full Screen

1import (2func (e ErrNegativeSqrt) Error() string {3 return fmt.Sprintf("cannot Sqrt negative number: %g", float64(e))4}5func Sqrt(x float64) (float64, error) {6 if x < 0 {7 return 0, ErrNegativeSqrt(x)8 }9 for i := 0; i < 10; i++ {10 z -= (z*z - x) / (2 * z)11 }12}13func main() {14 fmt.Println(Sqrt(2))15 fmt.Println(Sqrt(-2))16}17import (18func (e ErrNegativeSqrt) Error() string {19 return fmt.Sprintf("cannot Sqrt negative number: %g", float64(e))20}21func Sqrt(x float64) (float64, error) {22 if x < 0 {23 return 0, ErrNegativeSqrt(x)24 }25 for i := 0; i < 10; i++ {26 z -= (z*z - x) / (2 * z)27 }28}29func main() {30 fmt.Println(Sqrt(2))31 fmt.Println(Sqrt(-2))32}33import (34func (e ErrNegativeSqrt) Error() string {35 return fmt.Sprintf("cannot Sqrt negative number: %g", float64(e))36}37func Sqrt(x float64) (float64, error) {38 if x < 0 {39 return 0, ErrNegativeSqrt(x)40 }

Full Screen

Full Screen

err

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if len(os.Args) != 3 {4 fmt.Println("Usage: ", os.Args[0], "integer1 integer2")5 os.Exit(1)6 }7 value1, err1 := strconv.Atoi(os.Args[1])8 if err1 != nil {9 fmt.Println("First argument is not an integer")10 os.Exit(1)11 }12 value2, err2 := strconv.Atoi(os.Args[2])13 if err2 != nil {14 fmt.Println("Second argument is not an integer")15 os.Exit(1)16 }17 fmt.Println(value1, "+", value2, "=", value1+value2)18}19import (20func main() {21 if len(os.Args) != 3 {22 fmt.Println("Usage: ", os.Args[0], "integer1 integer2")23 os.Exit(1)24 }25 value1, err := strconv.Atoi(os.Args[1])26 if err != nil {27 fmt.Println("First argument is not an integer")28 os.Exit(1)29 }30 value2, err := strconv.Atoi(os.Args[2])31 if err != nil {32 fmt.Println("Second argument is not an integer")33 os.Exit(1)34 }35 fmt.Println(value1, "+", value2, "=", value1+value2)36}37import (38func main() {39 if len(os.Args) != 3 {40 fmt.Println("Usage: ", os.Args[0], "integer1 integer2")41 os.Exit(1)42 }43 value1, err := strconv.Atoi(os.Args[1])44 value2, err := strconv.Atoi(os.Args[2])45 if err != nil {46 fmt.Println("First argument is not an integer")47 os.Exit(1)48 }49 fmt.Println(value1, "+", value2, "=", value1+value2)50}51import (

Full Screen

Full Screen

err

Using AI Code Generation

copy

Full Screen

1import (2func main() {3}4import (5func main() {6}7import (8func main() {9}10import (11func main() {

Full Screen

Full Screen

err

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello, playground")4 _, err := fmt.Println("Hello, playground")5 if err != nil {6 log.Fatal(err)7 }8}9import (10func main() {11 fmt.Println("Hello, playground")12 _, err := fmt.Println("Hello, playground")13 if err != nil {14 log.Fatal(err)15 }16}17runtime.throw(0x4f7c00, 0x16)18runtime.sysMap(0xc820000000, 0x100000, 0x0, 0x7f3f1a1b9d38)19runtime.(*mheap).sysAlloc(0x7f3f1a1b9d38, 0x100000, 0x0)20runtime.(*mheap).grow(0x7f3f1a1b9d38, 0x8, 0x0)21runtime.(*mheap).allocSpanLocked(0x7f3f1a1b9d38, 0x1, 0x7f3f1a1b9d48)22runtime.(*mheap).alloc_m(0x7f3f1a1b9d38, 0x1, 0x15, 0x0)23runtime.(*mheap).alloc.func1()24runtime.systemstack(0x7f3f1a1b9d38)

Full Screen

Full Screen

err

Using AI Code Generation

copy

Full Screen

1import "fmt"2func main() {3 fmt.Println("Hello, playground")4}5import "testing"6func TestHello(t *testing.T) {7 t.Error("Hello")8}9import "fmt"10func main() {11 fmt.Println("Hello, playground")12}13import "testing"14func TestHello(t *testing.T) {15 t.Fatal("Hello")16}17import "fmt"18func main() {19 fmt.Println("Hello, playground")20}21import "testing"22func TestHello(t *testing.T) {23 t.Skip("Hello")24}25import "fmt"26func main() {27 fmt.Println("Hello, playground")28}29import "testing"30func TestHello(t *testing.T) {31 t.Log("Hello")32}33import "fmt"34func main() {35 fmt.Println("Hello, playground")36}37import "testing"38func TestHello(t *testing.T) {39 t.Logf("Hello")40}41import "fmt"42func main() {43 fmt.Println("Hello, playground")44}45import "testing"46func TestHello(t *testing.T) {47 t.Logf("Hello")48}49import "fmt"50func main() {51 fmt.Println("Hello, playground")52}53import "testing"54func TestHello(t *testing.T) {55 t.Logf("Hello")56}57import "fmt"58func main() {59 fmt.Println("Hello, playground")60}

Full Screen

Full Screen

err

Using AI Code Generation

copy

Full Screen

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

Full Screen

Full Screen

err

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello, playground")4 path1.Err()5}6import (7func Err() {8 fmt.Println("Hello, playground")9}10You should use relative import path instead of absolute path:11import (12func main() {13 fmt.Println("Hello, playground")14 path1.Err()15}16import (17func Err() {18 fmt.Println("Hello, playground")19}

Full Screen

Full Screen

err

Using AI Code Generation

copy

Full Screen

1import "fmt"2func main() {3 fmt.Println("Hello, playground")4 err := fmt.Errorf("Error")5 fmt.Println(err)6}7import "fmt"8func main() {9 fmt.Println("Hello, playground")10 err := fmt.Errorf("Error")11 fmt.Println(err)12}13import "fmt"14func main() {15 fmt.Println("Hello, playground")16 err := fmt.Errorf("Error")17 fmt.Println(err)18}19import "fmt"20func main() {21 fmt.Println("Hello, playground")22 err := fmt.Errorf("Error")23 fmt.Println(err)24}25import "fmt"26func main() {27 fmt.Println("Hello, playground")28 err := fmt.Errorf("Error")29 fmt.Println(err)30}31import "fmt"32func main() {33 fmt.Println("Hello, playground")34 err := fmt.Errorf("Error")35 fmt.Println(err)36}

Full Screen

Full Screen

err

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 fmt.Println(err)5 }6 fmt.Println(f.Name(), "opened successfully")7}8import (9func main() {10 if err != nil {11 fmt.Println(err)12 }13 fmt.Println(f.Name(), "opened successfully")14}15import (16func main() {17 if err != nil {18 fmt.Println(err)19 }20 fmt.Println(f.Name(), "opened successfully")21}22import (23func main() {24 if err != nil {25 fmt.Println(err)26 }27 fmt.Println(f.Name(), "opened successfully")28}29import (30func main() {31 if err != nil {32 fmt.Println(err)33 }34 fmt.Println(f.Name(), "opened successfully")35}36import (37func main() {

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.

Run Syzkaller automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful