github.com/google/cloudprober@v0.11.3/probes/probeutils/probeutils.go (about)

     1  // Copyright 2017-2019 The Cloudprober Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  /*
    16  Package probeutils implements utilities that are shared across multiple probe
    17  types.
    18  */
    19  package probeutils
    20  
    21  import (
    22  	"bytes"
    23  	"fmt"
    24  )
    25  
    26  // PatternPayload builds a payload that can be verified using VerifyPayloadPattern.
    27  // It repeats the pattern to fill the payload []byte slice. Last remaining
    28  // bytes (len(payload) mod patternSize) are left unpopulated (hence set to 0
    29  // bytes).
    30  func PatternPayload(payload, pattern []byte) {
    31  	patternSize := len(pattern)
    32  	for i := 0; i < len(payload); i += patternSize {
    33  		copy(payload[i:], pattern)
    34  	}
    35  }
    36  
    37  // VerifyPayloadPattern verifies the payload built using PatternPayload.
    38  func VerifyPayloadPattern(payload, pattern []byte) error {
    39  	patternSize := len(pattern)
    40  	nReplica := len(payload) / patternSize
    41  
    42  	for i := 0; i < nReplica; i++ {
    43  		bN := payload[0:patternSize]    // Next pattern sized bytes
    44  		payload = payload[patternSize:] // Shift payload for next iteration
    45  
    46  		if !bytes.Equal(bN, pattern) {
    47  			return fmt.Errorf("bytes are not in the expected format. payload[%d-Replica]=%v, pattern=%v", i, bN, pattern)
    48  		}
    49  	}
    50  
    51  	if !bytes.Equal(payload, pattern[:len(payload)]) {
    52  		return fmt.Errorf("last %d bytes are not in the expected format. payload=%v, expected=%v", len(payload), payload, pattern[:len(payload)])
    53  	}
    54  
    55  	return nil
    56  }