blob: 9bf840d8dd13de1af0f7f2151920816c240c817a [file] [log] [blame]
khenaidoobf6e7bb2018-08-14 22:27:29 -04001/*
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 Barbarie4a2564d2018-07-26 11:02:58 -040016package model
17
18import (
19 "bytes"
20 "crypto/md5"
21 "encoding/json"
22 "fmt"
23 "github.com/golang/protobuf/proto"
Stephane Barbarie8c48b5c2018-10-02 09:45:17 -040024 "github.com/opencord/voltha-go/common/log"
Stephane Barbarie4a2564d2018-07-26 11:02:58 -040025 "reflect"
26)
27
28type DataRevision struct {
29 Data interface{}
30 Hash string
31}
32
33func NewDataRevision(data interface{}) *DataRevision {
34 cdr := &DataRevision{}
35 cdr.Data = data
36 cdr.Hash = cdr.hashData(data)
37
38 return cdr
39}
40
41func (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 Barbarie8c48b5c2018-10-02 09:45:17 -040046 log.Errorf("problem to marshal protobuf data --> err: %s", err.Error())
Stephane Barbarie4a2564d2018-07-26 11:02:58 -040047 } 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 Barbarie8c48b5c2018-10-02 09:45:17 -040054 log.Errorf("problem to marshal data --> err: %s", err.Error())
Stephane Barbarie4a2564d2018-07-26 11:02:58 -040055 } 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}