khenaidoo | bf6e7bb | 2018-08-14 22:27:29 -0400 | [diff] [blame] | 1 | /* |
| 2 | * Copyright 2018-present Open Networking Foundation |
| 3 | |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
Stephane Barbarie | 4a2564d | 2018-07-26 11:02:58 -0400 | [diff] [blame] | 16 | package model |
| 17 | |
| 18 | import ( |
| 19 | "bytes" |
| 20 | "crypto/md5" |
| 21 | "encoding/json" |
| 22 | "fmt" |
| 23 | "github.com/golang/protobuf/proto" |
Stephane Barbarie | 8c48b5c | 2018-10-02 09:45:17 -0400 | [diff] [blame] | 24 | "github.com/opencord/voltha-go/common/log" |
Stephane Barbarie | 4a2564d | 2018-07-26 11:02:58 -0400 | [diff] [blame] | 25 | "reflect" |
| 26 | ) |
| 27 | |
| 28 | type DataRevision struct { |
| 29 | Data interface{} |
| 30 | Hash string |
| 31 | } |
| 32 | |
| 33 | func NewDataRevision(data interface{}) *DataRevision { |
| 34 | cdr := &DataRevision{} |
| 35 | cdr.Data = data |
| 36 | cdr.Hash = cdr.hashData(data) |
| 37 | |
| 38 | return cdr |
| 39 | } |
| 40 | |
| 41 | func (cr *DataRevision) hashData(data interface{}) string { |
| 42 | var buffer bytes.Buffer |
| 43 | |
| 44 | if IsProtoMessage(data) { |
| 45 | if pbdata, err := proto.Marshal(data.(proto.Message)); err != nil { |
Stephane Barbarie | 8c48b5c | 2018-10-02 09:45:17 -0400 | [diff] [blame] | 46 | log.Errorf("problem to marshal protobuf data --> err: %s", err.Error()) |
Stephane Barbarie | 4a2564d | 2018-07-26 11:02:58 -0400 | [diff] [blame] | 47 | } else { |
| 48 | buffer.Write(pbdata) |
| 49 | } |
| 50 | |
| 51 | } else if reflect.ValueOf(data).IsValid() { |
| 52 | dataObj := reflect.New(reflect.TypeOf(data).Elem()) |
| 53 | if json, err := json.Marshal(dataObj.Interface()); err != nil { |
Stephane Barbarie | 8c48b5c | 2018-10-02 09:45:17 -0400 | [diff] [blame] | 54 | log.Errorf("problem to marshal data --> err: %s", err.Error()) |
Stephane Barbarie | 4a2564d | 2018-07-26 11:02:58 -0400 | [diff] [blame] | 55 | } else { |
| 56 | buffer.Write(json) |
| 57 | } |
| 58 | } else { |
| 59 | dataObj := reflect.New(reflect.TypeOf(data).Elem()) |
| 60 | buffer.Write(dataObj.Bytes()) |
| 61 | } |
| 62 | |
| 63 | return fmt.Sprintf("%x", md5.Sum(buffer.Bytes()))[:12] |
| 64 | } |