func writeFile()

in google_guest_agent/sshca/sshca.go [58:110]


func writeFile(ctx context.Context, evType string, data interface{}, evData *events.EventData) bool {
	// There was some error on the pipe watcher, just ignore it.
	if evData.Error != nil {
		logger.Debugf("Not handling ssh trusted ca cert event, we got an error: %+v", evData.Error)
		return true
	}

	// Make sure we close the pipe after we've done writing to it.
	pipeData, ok := evData.Data.(*sshtrustedca.PipeData)
	if !ok {
		logger.Errorf("Received invalid event data (%+v), ignoring this event and un-subscribing %s", evData.Data, evType)
		return false
	}

	defer func() {
		if err := pipeData.File.Close(); err != nil {
			logger.Errorf("Failed to close pipe: %+v", err)
		}
		pipeData.Finished()
	}()

	certificate, err := mdsClient.GetKey(ctx, "oslogin/certificates", nil)
	if err != nil {
		logger.Errorf("Failed to get certificate from metadata server: %+v", err)
		return true
	}

	// Keep a copy of the returned certificate for error fallback caching.
	var certs Certificates
	var outData []string

	if err := json.Unmarshal([]byte(certificate), &certs); err != nil {
		logger.Errorf("Failed to unmarshal certificate json: %+v", err)
		return true
	}

	for _, curr := range certs.Certs {
		outData = append(outData, curr.PublicKey)
	}

	outStr := strings.Join(outData, "\n")
	n, err := pipeData.File.WriteString(outStr)
	if err != nil {
		logger.Errorf("Failed to write certificate to the write end of the pipe: %+v", err)
		return true
	}

	if n != len(outStr) {
		logger.Errorf("Wrote the wrong ammout of data, wrote %d bytes instead of %d bytes", n, len(certificate))
	}

	return true
}