khenaidoo | b920354 | 2018-09-17 22:56:37 -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 | */ |
| 16 | package core |
| 17 | |
| 18 | import ( |
| 19 | "crypto/rand" |
| 20 | "encoding/hex" |
khenaidoo | ca30132 | 2019-01-09 23:06:32 -0500 | [diff] [blame] | 21 | "errors" |
| 22 | "fmt" |
khenaidoo | b920354 | 2018-09-17 22:56:37 -0400 | [diff] [blame] | 23 | m "math/rand" |
khenaidoo | ca30132 | 2019-01-09 23:06:32 -0500 | [diff] [blame] | 24 | "strconv" |
khenaidoo | b920354 | 2018-09-17 22:56:37 -0400 | [diff] [blame] | 25 | ) |
| 26 | |
| 27 | func randomHex(n int) (string, error) { |
| 28 | bytes := make([]byte, n) |
| 29 | if _, err := rand.Read(bytes); err != nil { |
| 30 | return "", err |
| 31 | } |
| 32 | return hex.EncodeToString(bytes), nil |
| 33 | } |
| 34 | |
| 35 | // CreateDeviceId produces a device ID. DeviceId is 16 hex long - lower 12 hex is the device id. |
| 36 | // TODO: A cluster unique ID may be required |
| 37 | func CreateDeviceId() string { |
| 38 | val, _ := randomHex(12) |
| 39 | return val |
| 40 | } |
| 41 | |
| 42 | // CreateLogicalDeviceId is not used for now as the logical device ID is derived from the |
| 43 | // OLT MAC address |
| 44 | func CreateLogicalDeviceId() string { |
| 45 | // logical device id is 16 hex long - lower 12 hex is the logical device id. For now just generate the 12 hex |
| 46 | val, _ := randomHex(12) |
| 47 | return val |
| 48 | } |
| 49 | |
khenaidoo | 9a46896 | 2018-09-19 15:33:13 -0400 | [diff] [blame] | 50 | // CreateLogicalPortId produces a random port ID for a logical device. |
khenaidoo | b920354 | 2018-09-17 22:56:37 -0400 | [diff] [blame] | 51 | func CreateLogicalPortId() uint32 { |
| 52 | // A logical port is a uint32 |
| 53 | return m.Uint32() |
| 54 | } |
khenaidoo | ca30132 | 2019-01-09 23:06:32 -0500 | [diff] [blame] | 55 | |
| 56 | func CreateDataPathId(idInHexString string) (uint64, error) { |
| 57 | if idInHexString == "" { |
| 58 | return 0, errors.New("id-empty") |
| 59 | } |
| 60 | // First prepend 0x to the string |
| 61 | newId := fmt.Sprintf("0x%s", idInHexString) |
| 62 | if d, err := strconv.ParseUint(newId, 0, 64); err != nil { |
| 63 | return 0, err |
| 64 | } else { |
| 65 | return d, nil |
| 66 | } |
| 67 | } |