1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
|
// Copyright (c) 2020, Sylabs Inc. All rights reserved.
// This software is licensed under a 3-clause BSD license. Please consult the
// LICENSE.md file distributed with the sources of this project regarding your
// rights to use or distribute this software.
package callback
import (
"fmt"
"unsafe"
pluginapi "github.com/sylabs/singularity/v4/pkg/plugin"
)
// pluginCallback contains hook callbacks function registered
// by loaded plugins.
var pluginCallbacks = make(map[string][]pluginapi.Callback)
// sameType compares if the two interfaces have the same type.
func sameType(a interface{}, b interface{}) bool {
ptrA := unsafe.Pointer(&a)
ptrB := unsafe.Pointer(&b)
return *(*unsafe.Pointer)(ptrA) == *(*unsafe.Pointer)(ptrB)
}
// Loaded returns the loaded plugin callbacks of callback
// type passed in argument.
func Loaded(callbackType pluginapi.Callback) ([]pluginapi.Callback, error) {
callbacks := pluginCallbacks[Name(callbackType)]
// we ensure the plugin callback correspond to the registered callback
for _, callback := range callbacks {
if !sameType(callbackType, callback) {
return nil, fmt.Errorf("plugin callback has type '%T' instead of '%T'", callback, callbackType)
}
}
return callbacks, nil
}
// Load loads a plugin callback.
func Load(callback pluginapi.Callback) {
name := Name(callback)
if pluginCallbacks[name] == nil {
pluginCallbacks[name] = make([]pluginapi.Callback, 0)
}
pluginCallbacks[name] = append(pluginCallbacks[name], callback)
}
// Names returns a list of unique callback name passed in argument.
func Names(callbacks []pluginapi.Callback) []string {
var s []string
for _, c := range callbacks {
hookName := Name(c)
// get rid of duplicated hook name
found := false
for _, name := range s {
if name == hookName {
found = true
break
}
}
if !found {
s = append(s, hookName)
}
}
return s
}
// Name returns the callback name.
func Name(callback pluginapi.Callback) string {
return fmt.Sprintf("%T", callback)
}
|