-
Notifications
You must be signed in to change notification settings - Fork 51
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat(libooniengine): add support for running tasks #1112
Open
DecFox
wants to merge
12
commits into
ooni:master
Choose a base branch
from
DecFox:c-api-newsession
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
ca3f41c
feat: expose NewSession in the C API
7dd9f5d
feat: introduce geolocate
468b313
refactor: dry out code to only include running tasks
95469ed
changes from code review
542c4e3
feat: add mock task for integration testing
719109a
feat: separate Go and C code
c73486f
feat: introduce TaskAPI.GetResult()
000abe5
refactor: remove redundant comments
9b904d8
changes from code review
d0a225a
x
62ca51b
refactor: handle non-positive timeout explicitly
e38a274
feat: introduce custom handle
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,90 @@ | ||
package main | ||
|
||
// | ||
// Handle mimics cgo.Handle but uses a intptr | ||
// | ||
|
||
//#include <stdlib.h> | ||
// | ||
//#include "engine.h" | ||
import "C" | ||
|
||
import ( | ||
"errors" | ||
"log" | ||
"sync" | ||
|
||
"github.com/ooni/probe-cli/v3/internal/motor" | ||
) | ||
|
||
var ( | ||
handler Handler | ||
|
||
// errHandleMisuse indicates that an invalid handle was misused | ||
errHandleMisuse = errors.New("misuse of a invalid handle") | ||
|
||
// errHandleSpaceExceeded | ||
errHandleSpaceExceeded = errors.New("ran out of handle space") | ||
) | ||
|
||
func init() { | ||
handler = Handler{ | ||
handles: make(map[Handle]interface{}), | ||
} | ||
} | ||
|
||
type Handle C.intptr_t | ||
|
||
// Handler handles the entirety of handle operations. | ||
type Handler struct { | ||
handles map[Handle]interface{} | ||
handleIdx Handle | ||
mu sync.Mutex | ||
} | ||
|
||
// newHandle returns a handle for a given value | ||
// if we run out of handle space, a zero handle is returned. | ||
func (h *Handler) newHandle(v any) (Handle, error) { | ||
h.mu.Lock() | ||
defer h.mu.Unlock() | ||
ptr := C.intptr_t(h.handleIdx) | ||
newId := ptr + 1 | ||
if newId < 0 { | ||
return Handle(0), errHandleSpaceExceeded | ||
} | ||
h.handleIdx = Handle(newId) | ||
h.handles[h.handleIdx] = v | ||
return h.handleIdx, nil | ||
} | ||
|
||
// delete invalidates a handle | ||
func (h *Handler) delete(hd Handle) { | ||
h.mu.Lock() | ||
defer h.mu.Unlock() | ||
delete(h.handles, hd) | ||
} | ||
|
||
// value returns the associated go value for a valid handle | ||
func (h *Handler) value(hd Handle) (any, error) { | ||
v, ok := h.handles[hd] | ||
if !ok { | ||
return nil, errHandleMisuse | ||
} | ||
return v, nil | ||
} | ||
|
||
// getTaskHandle checks if the task handle is valid and returns the corresponding TaskAPI. | ||
func (h *Handler) getTaskHandle(task C.OONITask) (tp motor.TaskAPI) { | ||
hd := Handle(task) | ||
val, err := h.value(hd) | ||
if err != nil { | ||
log.Printf("getTaskHandle: %s", err.Error()) | ||
return | ||
} | ||
tp, ok := val.(motor.TaskAPI) | ||
if !ok { | ||
log.Printf("getTaskHandle: invalid type assertion") | ||
return | ||
} | ||
return | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,136 @@ | ||
package main | ||
|
||
// | ||
// C API | ||
// | ||
|
||
//#include <stdlib.h> | ||
// | ||
//#include "engine.h" | ||
import "C" | ||
|
||
import ( | ||
"encoding/json" | ||
"log" | ||
"time" | ||
"unsafe" | ||
|
||
"github.com/ooni/probe-cli/v3/internal/motor" | ||
"github.com/ooni/probe-cli/v3/internal/version" | ||
) | ||
|
||
const ( | ||
// invalidTaskHandle represents the invalid task handle. | ||
invalidTaskHandle = 0 | ||
) | ||
|
||
// parse converts a JSON request string to the concrete Go type. | ||
func parse(req *C.char) (*motor.Request, error) { | ||
out := &motor.Request{} | ||
if err := json.Unmarshal([]byte(C.GoString(req)), &out); err != nil { | ||
return nil, err | ||
} | ||
return out, nil | ||
} | ||
|
||
// serialize serializes a OONI response to a JSON string accessible to C code. | ||
func serialize(resp *motor.Response) *C.char { | ||
if resp == nil { | ||
return nil | ||
} | ||
out, err := json.Marshal(resp) | ||
if err != nil { | ||
log.Printf("serializeMessage: cannot serialize message: %s", err.Error()) | ||
return nil | ||
} | ||
return C.CString(string(out)) | ||
} | ||
|
||
//export OONIEngineVersion | ||
func OONIEngineVersion() *C.char { | ||
return C.CString(version.Version) | ||
} | ||
|
||
//export OONIEngineFreeMemory | ||
func OONIEngineFreeMemory(ptr *C.void) { | ||
C.free(unsafe.Pointer(ptr)) | ||
} | ||
|
||
//export OONIEngineCall | ||
func OONIEngineCall(req *C.char) C.OONITask { | ||
r, err := parse(req) | ||
if err != nil { | ||
log.Printf("OONIEngineCall: %s", err.Error()) | ||
return invalidTaskHandle | ||
} | ||
tp := motor.StartTask(r) | ||
if tp == nil { | ||
log.Printf("OONITaskStart: startTask returned NULL") | ||
return invalidTaskHandle | ||
} | ||
handle, err := handler.newHandle(tp) | ||
if err != nil { | ||
log.Printf("OONITaskStart: %s", err.Error()) | ||
return invalidTaskHandle | ||
} | ||
return C.OONITask(handle) | ||
} | ||
|
||
//export OONIEngineWaitForNextEvent | ||
func OONIEngineWaitForNextEvent(task C.OONITask, timeout C.int32_t) *C.char { | ||
tp := handler.getTaskHandle(task) | ||
if tp == nil { | ||
return nil | ||
} | ||
var ev *motor.Response | ||
if timeout <= 0 { | ||
ev = tp.WaitForNextEvent(time.Duration(timeout)) | ||
} else { | ||
ev = tp.WaitForNextEvent(time.Duration(timeout) * time.Millisecond) | ||
} | ||
return serialize(ev) | ||
} | ||
|
||
//export OONIEngineTaskGetResult | ||
func OONIEngineTaskGetResult(task C.OONITask) *C.char { | ||
tp := handler.getTaskHandle(task) | ||
if tp == nil { | ||
return nil | ||
} | ||
result := tp.Result() | ||
return serialize(result) | ||
} | ||
|
||
//export OONIEngineTaskIsDone | ||
func OONIEngineTaskIsDone(task C.OONITask) (out C.uint8_t) { | ||
tp := handler.getTaskHandle(task) | ||
if tp == nil { | ||
return | ||
} | ||
if !tp.IsDone() { | ||
out++ | ||
} | ||
return | ||
} | ||
|
||
//export OONIEngineInterruptTask | ||
func OONIEngineInterruptTask(task C.OONITask) { | ||
tp := handler.getTaskHandle(task) | ||
if tp == nil { | ||
return | ||
} | ||
tp.Interrupt() | ||
} | ||
|
||
//export OONIEngineFreeTask | ||
func OONIEngineFreeTask(task C.OONITask) { | ||
tp := handler.getTaskHandle(task) | ||
if tp != nil { | ||
tp.Interrupt() | ||
} | ||
handler.delete(Handle(task)) | ||
} | ||
|
||
func main() { | ||
// do nothing | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
package motor | ||
|
||
// | ||
// Emitter | ||
// | ||
|
||
// taskChanEmitter implements taskMaybeEmitter. | ||
type taskChanEmitter struct { | ||
// out is the channel where we emit events. | ||
out chan *Response | ||
} | ||
|
||
var _ taskMaybeEmitter = &taskChanEmitter{} | ||
|
||
// maybeEmitEvent implements taskMaybeEmitter.maybeEmitEvent. | ||
func (e *taskChanEmitter) maybeEmitEvent(resp *Response) { | ||
select { | ||
case e.out <- resp: | ||
default: // buffer full, discard this event | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think
parse
should also handle the case wherereq
isnil
.