Skip to contentSkip to conversation

golang/xenlight: Don't try to marshall zero-length arrays in fromC

PATCH Superseded George Dunlap 5 participants 32 messages Jan 17, 2020 – Feb 4, 2020

v3 of 4 Superseded Latest is v4 →

lore
Share & tools
lore
#0 lore raw

PATCH v3 1/8 golang/xenlight: Don't try to marshall zero-length arrays in fromC

The current fromC array code will do the "magic" casting and martialling even when num_foo variable is 0. Go crashes when doing the cast.

Only do array marshalling if the number of elements is non-zero; otherwise, leave the target pointer empty (nil for Go slices, NULL for C arrays).

---
v2:
- Remove toC part of this, which has been folded into Nick's patch series.

CC Nick Rosbrook <[email protected]>
---
 tools/golang/xenlight/gengotypes.py  |   5 +-
 tools/golang/xenlight/helpers.gen.go | 452 +++++++++++++++------------
 2 files changed, 261 insertions(+), 196 deletions(-)
tools/golang/xenlight/gengotypes.py +3 -2
index 27edf66241..ad2c573da9 100644
@@ -419,7 +419,8 @@ def xenlight_golang_array_from_C(ty = None):
     clenvar    = ty.type.lenvar.name
     golenvar   = xenlight_golang_fmt_name(clenvar,exported=False)
 
-    s += '{} := int(xc.{})\n'.format(golenvar, clenvar)
+    s += 'x.{} = nil\n'.format(goname)
+    s += 'if {} := int(xc.{}); {} > 0 {{\n'.format(golenvar, clenvar, golenvar)
     s += '{} := '.format(cslice)
     s +='(*[1<<28]C.{})(unsafe.Pointer(xc.{}))[:{}:{}]\n'.format(ctypename, cname,
                                                                 golenvar, golenvar)
@@ -433,7 +434,7 @@ def xenlight_golang_array_from_C(ty = None):
         s += 'if err := x.{}[i].fromC(&v); err != nil {{\n'.format(goname)
         s += 'return err }\n'
 
-    s += '}\n'
+    s += '}\n}\n'
 
     return s
 
tools/golang/xenlight/helpers.gen.go +258 -194

581 lines not on this page · raw message

Signature · 7 lines
2.24.1


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel
#1 lore raw

PATCH v3 2/8 go/xenlight: Fix CpuidPoliclyList conversion

Empty Go strings should be converted to nil libxl_cpuid_policy_list; otherwise libxl_cpuid_parse_config gets confused.

Also, libxl_cpuid_policy_list returns a weird error, not a "normal" libxl error; if it returns one of these non-standard errors, convert it to ErrorInval.

Finally, make the fromC() method take a pointer, and set the value of CpuidPolicyList such that it will generate a valid CpuidPolicyList in response.

---
v2:
- Port over toC() function signature change
- Have fromC set the string to ""

CC Nick Rosbrook <[email protected]>
---
 tools/golang/xenlight/xenlight.go | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)
tools/golang/xenlight/xenlight.go +8 -2
index b1587b964f..1299981713 100644
@@ -306,9 +306,14 @@ func (el *EvLink) toC(cel *C.libxl_ev_link) (err error) { return }
 // empty when it is returned from libxl.
 type CpuidPolicyList string
 
-func (cpl CpuidPolicyList) fromC(ccpl *C.libxl_cpuid_policy_list) error { return nil }
+func (cpl *CpuidPolicyList) fromC(ccpl *C.libxl_cpuid_policy_list) error { *cpl = ""; return nil }
 
 func (cpl CpuidPolicyList) toC(ccpl *C.libxl_cpuid_policy_list) error {
+	if cpl == "" {
+		*ccpl = nil
+		return nil
+	}
+
 	s := C.CString(string(cpl))
 	defer C.free(unsafe.Pointer(s))
 
@@ -316,7 +321,8 @@ func (cpl CpuidPolicyList) toC(ccpl *C.libxl_cpuid_policy_list) error {
 	if ret != 0 {
 		C.libxl_cpuid_dispose(ccpl)
 
-		return Error(-ret)
+		// libxl_cpuid_parse_config doesn't return a normal libxl error.
+		return ErrorInval
 	}
 
 	return nil
Signature · 7 lines
2.24.1


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel
Reviewed-by on v3 2/8
#2 lore raw

Re: [Xen-devel] [PATCH v3 2/8] go/xenlight: Fix CpuidPoliclyList conversion

Quoted 7 lines

Empty Go strings should be converted to nil libxl_cpuid_policy_list; otherwise libxl_cpuid_parse_config gets confused.

Also, libxl_cpuid_policy_list returns a weird error, not a "normal" libxl error; if it returns one of these non-standard errors, convert it to ErrorInval.

Quoted 5 lines

Finally, make the fromC() method take a pointer, and set the value of CpuidPolicyList such that it will generate a valid CpuidPolicyList in response.

_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel

#3 lore raw

PATCH v3 3/8 go/xenlight: More informative error messages

In reply to George Dunlap

If an error is encountered deep in a complicated data structure, it's often difficult to tell where the error actually is. Make the error message from the generated toC() and fromC() structures more informative by tagging which field being converted encountered the error. This will have the effect of giving a "stack trace" of the failure inside a nested data structure.

NB that my version of python insists on reordering a couple of switch statements for some reason; In other patches I've reverted those changes, but in this case it's more difficult because they interact with actual code changes. I'll leave this here for now, as we're going to remove helpers.gen.go from being tracked by git at some point in the near future anyway.

---
v2:
- Keep error messages lower case
- Actually implement .toC changes

CC Nick Rosbrook <[email protected]>
---
 tools/golang/xenlight/gengotypes.py  |  10 +-
 tools/golang/xenlight/helpers.gen.go | 530 +++++++++++++--------------
 2 files changed, 270 insertions(+), 270 deletions(-)
tools/golang/xenlight/gengotypes.py +5 -5
index ad2c573da9..17b0ca00bd 100644
@@ -314,7 +314,7 @@ def xenlight_golang_convert_from_C(ty = None, outer_name = None, cvarname = None
         # If the type is not castable, we need to call its fromC
         # function.
         s += 'if err := x.{}.fromC(&{}.{});'.format(goname,cvarname,cname)
-        s += 'err != nil {\n return err \n}\n'
+        s += 'err != nil {{\nreturn fmt.Errorf("converting field {}: %v", err) \n}}\n'.format(goname)
 
     elif gotypename == 'string':
         # Use the cgo helper for converting C strings.
@@ -389,7 +389,7 @@ def xenlight_golang_union_from_C(ty = None, union_name = '', struct_name = ''):
 
         s += 'var {} {}\n'.format(goname, gotype)
         s += 'if err := {}.fromC(xc);'.format(goname)
-        s += 'err != nil {\n return err \n}\n'
+        s += 'err != nil {{\n return fmt.Errorf("converting field {}: %v", err) \n}}\n'.format(goname)
 
         field_name = xenlight_golang_fmt_name('{}_union'.format(keyname))
         s += 'x.{} = {}\n'.format(field_name, goname)
@@ -432,7 +432,7 @@ def xenlight_golang_array_from_C(ty = None):
         s += 'x.{}[i] = {}(v)\n'.format(goname, gotypename)
     else:
         s += 'if err := x.{}[i].fromC(&v); err != nil {{\n'.format(goname)
-        s += 'return err }\n'
+        s += 'return fmt.Errorf("converting field {}: %v", err) }}\n'.format(goname)
 
     s += '}\n}\n'
 
@@ -513,7 +513,7 @@ def xenlight_golang_convert_to_C(ty = None, outer_name = None,
     if not is_castable:
         s += 'if err := {}.{}.toC(&{}.{}); err != nil {{\n'.format(govarname,goname,
                                                                    cvarname,cname)
-        s += 'return err\n}\n'
+        s += 'return fmt.Errorf("converting field {}: %v", err) \n}}\n'.format(goname)
 
     elif gotypename == 'string':
         # Use the cgo helper for converting C strings.
@@ -615,7 +615,7 @@ def xenlight_golang_array_to_C(ty = None):
                                                                          golenvar,golenvar)
     s += 'for i,v := range x.{} {{\n'.format(goname)
     s += 'if err := v.toC(&c{}[i]); err != nil {{\n'.format(goname)
-    s += 'return err\n'
+    s += 'return fmt.Errorf("converting field {}: %v", err) \n'.format(goname)
     s += '}\n}\n}\n'
 
     return s
tools/golang/xenlight/helpers.gen.go +265 -265

1,638 lines not on this page · raw message

Signature · 7 lines
2.24.1


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel
Reviewed-by on v3 3/8
#4 lore raw

Re: [Xen-devel] [PATCH v3 3/8] go/xenlight: More informative error messages

Quoted 7 lines

If an error is encountered deep in a complicated data structure, it's often difficult to tell where the error actually is. Make the error message from the generated toC() and fromC() structures more informative by tagging which field being converted encountered the error. This will have the effect of giving a "stack trace" of the failure inside a nested data structure.

Quoted 8 lines

NB that my version of python insists on reordering a couple of switch statements for some reason; In other patches I've reverted those changes, but in this case it's more difficult because they interact with actual code changes. I'll leave this here for now, as we're going to remove helpers.gen.go from being tracked by git at some point in the near future anyway.

_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel

#5 lore raw

PATCH v3 4/8 golang/xenlight: Errors are negative

In reply to George Dunlap

Commit 871e51d2d4 changed the sign on the xenlight error types (making the values negative, same as the C-generated constants), but failed to flip the sign in the Error() string function. The result is that ErrorNonspecific.String() prints "libxl error: 1" rather than the human-readable error message.

Get rid of the whole issue by making libxlErrors a map, and mapping actual error values to string, falling back to printing the actual value of the Error type if it's not present.

---
v2:
- Convert libxlErrors to a map.

CC Nick Rosbrook <[email protected]>
---
 tools/golang/xenlight/xenlight.go | 62 +++++++++++++++----------------
 1 file changed, 30 insertions(+), 32 deletions(-)
tools/golang/xenlight/xenlight.go +30 -32
index 1299981713..aa1e63a61a 100644
@@ -36,42 +36,40 @@ import (
 	"unsafe"
 )
 
-var libxlErrors = [...]string{
-	-ErrorNonspecific:                  "Non-specific error",
-	-ErrorVersion:                      "Wrong version",
-	-ErrorFail:                         "Failed",
-	-ErrorNi:                           "Not Implemented",
-	-ErrorNomem:                        "No memory",
-	-ErrorInval:                        "Invalid argument",
-	-ErrorBadfail:                      "Bad Fail",
-	-ErrorGuestTimedout:                "Guest timed out",
-	-ErrorTimedout:                     "Timed out",
-	-ErrorNoparavirt:                   "No Paravirtualization",
-	-ErrorNotReady:                     "Not ready",
-	-ErrorOseventRegFail:               "OS event registration failed",
-	-ErrorBufferfull:                   "Buffer full",
-	-ErrorUnknownChild:                 "Unknown child",
-	-ErrorLockFail:                     "Lock failed",
-	-ErrorJsonConfigEmpty:              "JSON config empty",
-	-ErrorDeviceExists:                 "Device exists",
-	-ErrorCheckpointDevopsDoesNotMatch: "Checkpoint devops does not match",
-	-ErrorCheckpointDeviceNotSupported: "Checkpoint device not supported",
-	-ErrorVnumaConfigInvalid:           "VNUMA config invalid",
-	-ErrorDomainNotfound:               "Domain not found",
-	-ErrorAborted:                      "Aborted",
-	-ErrorNotfound:                     "Not found",
-	-ErrorDomainDestroyed:              "Domain destroyed",
-	-ErrorFeatureRemoved:               "Feature removed",
+var libxlErrors = map[Error]string{
+	ErrorNonspecific:                  "Non-specific error",
+	ErrorVersion:                      "Wrong version",
+	ErrorFail:                         "Failed",
+	ErrorNi:                           "Not Implemented",
+	ErrorNomem:                        "No memory",
+	ErrorInval:                        "Invalid argument",
+	ErrorBadfail:                      "Bad Fail",
+	ErrorGuestTimedout:                "Guest timed out",
+	ErrorTimedout:                     "Timed out",
+	ErrorNoparavirt:                   "No Paravirtualization",
+	ErrorNotReady:                     "Not ready",
+	ErrorOseventRegFail:               "OS event registration failed",
+	ErrorBufferfull:                   "Buffer full",
+	ErrorUnknownChild:                 "Unknown child",
+	ErrorLockFail:                     "Lock failed",
+	ErrorJsonConfigEmpty:              "JSON config empty",
+	ErrorDeviceExists:                 "Device exists",
+	ErrorCheckpointDevopsDoesNotMatch: "Checkpoint devops does not match",
+	ErrorCheckpointDeviceNotSupported: "Checkpoint device not supported",
+	ErrorVnumaConfigInvalid:           "VNUMA config invalid",
+	ErrorDomainNotfound:               "Domain not found",
+	ErrorAborted:                      "Aborted",
+	ErrorNotfound:                     "Not found",
+	ErrorDomainDestroyed:              "Domain destroyed",
+	ErrorFeatureRemoved:               "Feature removed",
 }
 
 func (e Error) Error() string {
-	if 0 < int(e) && int(e) < len(libxlErrors) {
-		s := libxlErrors[e]
-		if s != "" {
-			return s
-		}
+	if s, ok := libxlErrors[e]; ok {
+		return s
 	}
-	return fmt.Sprintf("libxl error: %d", -e)
+
+	return fmt.Sprintf("libxl error: %d", e)
 }
 
 // Context represents a libxl_ctx.
Signature · 7 lines
2.24.1


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel
Reviewed-by on v3 4/8
#6 lore raw

Re: [Xen-devel] [PATCH v3 4/8] golang/xenlight: Errors are negative

Quoted 11 lines

Commit 871e51d2d4 changed the sign on the xenlight error types (making the values negative, same as the C-generated constants), but failed to flip the sign in the Error() string function. The result is that ErrorNonspecific.String() prints "libxl error: 1" rather than the human-readable error message.

Get rid of the whole issue by making libxlErrors a map, and mapping actual error values to string, falling back to printing the actual value of the Error type if it's not present.

_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel

#7 lore raw

PATCH v3 5/8 golang/xenlight: Default loglevel to DEBUG until we get everything working

In reply to George Dunlap

---

The other option would be to expose the XTL logging levels and let the caller set them somehow.

CC Nick Rosbrook <[email protected]>
---
 tools/golang/xenlight/xenlight.go | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
tools/golang/xenlight/xenlight.go +1 -1
index aa1e63a61a..0e71f6ca7d 100644
@@ -82,7 +82,7 @@ type Context struct {
 func NewContext() (*Context, error) {
 	var ctx Context
 
-	ctx.logger = C.xtl_createlogger_stdiostream(C.stderr, C.XTL_ERROR, 0)
+	ctx.logger = C.xtl_createlogger_stdiostream(C.stderr, C.XTL_DEBUG, 0)
 
 	ret := C.libxl_ctx_alloc(&ctx.ctx, C.LIBXL_VERSION, 0,
 		(*C.xentoollog_logger)(unsafe.Pointer(ctx.logger)))
Signature · 7 lines
2.24.1


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel
#8 lore raw

Re: [Xen-devel] [PATCH v3 5/8] golang/xenlight: Default loglevel to DEBUG until we get everything working

Quoted 2 lines

The other option would be to expose the XTL logging levels and let the caller set them somehow.

I think this is fine for now.

For the future, I like using the "functional option" pattern for this sort of thing. That way, if a user wanted to set a non-default log level, they could do:

ctx, err := xenlight.NewContext(xenlight.WithLogLevel(lvl))

but if they do not need to specify any options, it's still just:

ctx, err := xenlight.NewContext()

-NR

_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel

#9 lore raw

Re: [Xen-devel] [PATCH v3 5/8] golang/xenlight: Default loglevel to DEBUG until we get everything working

Quoted 12 lines · Nick Rosbrook
Quoted 3 lines

The other option would be to expose the XTL logging levels and let the caller set them somehow.

I think this is fine for now.

For the future, I like using the "functional option" pattern for this sort of thing. That way, if a user wanted to set a non-default log level, they could do:

Quoted 5 lines

ctx, err := xenlight.NewContext(xenlight.WithLogLevel(lvl))

but if they do not need to specify any options, it's still just:

ctx, err := xenlight.NewContext()

You know, I somehow remembered the “use a function to set options” pattern (and have a mock-up for that in the “NewType()” patch later), but didn’t notice that such function were variadic. That’s a lot nicer.

But really, we need a way to actually create a logger properly. Apparently one thing libvirt does is to create a logger to a file for each guest. That’s something our package users might want to do at some point.

-George
_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel

#10 lore raw

Re: [Xen-devel] [PATCH v3 5/8] golang/xenlight: Default loglevel to DEBUG until we get everything working

Quoted 1 line

But really, we need a way to actually create a logger properly. Apparently one thing libvirt does is to create a logger to a file for each guest. That’s something our package users might want to do at some point.

Yes, I think package users will want logging to be pretty flexible. I think we can cover most of those cases with Context options, or maybe we make a Logger type that provides an abstraction for XTL.

-NR

_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel

#11 lore raw

PATCH v3 6/8 golang/xenlight: Don't leak memory on context open failure

In reply to George Dunlap

If libxl_ctx_alloc() returns an error, we need to destroy the logger that we made.

Restructure the Close() method such that it checks for each resource to be freed and then frees it. This allows Close() to be come idempotent, as well as to be a useful clean-up to a partially-created context.

---
CC: Nick Rosbrook <[email protected]>

---
 tools/golang/xenlight/xenlight.go | 30 +++++++++++++++++++++---------
 1 file changed, 21 insertions(+), 9 deletions(-)
tools/golang/xenlight/xenlight.go +21 -9
index 0e71f6ca7d..662b266250 100644
@@ -79,28 +79,40 @@ type Context struct {
 }
 
 // NewContext returns a new Context.
-func NewContext() (*Context, error) {
-	var ctx Context
+func NewContext() (ctx *Context, err error) {
+	ctx = &Context{}
+
+	defer func() {
+		if err != nil {
+			ctx.Close()
+			ctx = nil
+		}
+	}()
 
 	ctx.logger = C.xtl_createlogger_stdiostream(C.stderr, C.XTL_DEBUG, 0)
 
 	ret := C.libxl_ctx_alloc(&ctx.ctx, C.LIBXL_VERSION, 0,
 		(*C.xentoollog_logger)(unsafe.Pointer(ctx.logger)))
 	if ret != 0 {
-		return nil, Error(ret)
+		return ctx, Error(ret)
 	}
 
-	return &ctx, nil
+	return ctx, nil
 }
 
 // Close closes the Context.
 func (ctx *Context) Close() error {
-	ret := C.libxl_ctx_free(ctx.ctx)
-	ctx.ctx = nil
-	C.xtl_logger_destroy((*C.xentoollog_logger)(unsafe.Pointer(ctx.logger)))
+	if ctx.ctx != nil {
+		ret := C.libxl_ctx_free(ctx.ctx)
+		if ret != 0 {
+			return Error(ret)
+		}
+		ctx.ctx = nil
+	}
 
-	if ret != 0 {
-		return Error(ret)
+	if ctx.logger != nil {
+		C.xtl_logger_destroy((*C.xentoollog_logger)(unsafe.Pointer(ctx.logger)))
+		ctx.logger = nil
 	}
 
 	return nil
Signature · 7 lines
2.24.1


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel
Reviewed-by on v3 6/8
#12 lore raw

Re: [Xen-devel] [PATCH v3 6/8] golang/xenlight: Don't leak memory on context open failure

Quoted 9 lines

If libxl_ctx_alloc() returns an error, we need to destroy the logger that we made.

Restructure the Close() method such that it checks for each resource to be freed and then frees it. This allows Close() to be come idempotent, as well as to be a useful clean-up to a partially-created context.

_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel

#13 lore raw

PATCH v3 7/8 golang/xenlight: Notify xenlight of SIGCHLD

In reply to George Dunlap

libxl forks external processes and waits for them to complete; it therefore needs to be notified when children exit.

In absence of instructions to the contrary, libxl sets up its own SIGCHLD handlers.

Golang always unmasks and handles SIGCHLD itself. libxl thankfully notices this and throws an assert() rather than clobbering SIGCHLD handlers.

Tell libxl that we'll be responsible for getting SIGCHLD notifications to it. Arrange for a channel in the context to receive notifications on SIGCHLD, and set up a goroutine that will pass these on to libxl.

NB that every libxl context needs a notification; so multiple contexts will each spin up their own goroutine when opening a context, and shut it down on close.

libxl also wants to hold on to a const pointer to xenlight_childproc_hooks rather than do a copy; so make a global structure in C space and initialize it once on library creation.

While here, add a few comments to make the context set-up a bit easier to follow.

---
v2:
- Fix unsafe libxl_childproc_hooks pointer behavior
- Close down the SIGCHLD handler first, and make sure it's exited before closing the context
- Explicitly decide to have a separate goroutine per ctx

NB that due to a bug in libxl, this will hang without Ian's "[PATCH v2 00/10] libxl: event: Fix hang for some applications" series.

CC Nick Rosbrook <[email protected]>
CC Ian Jackson <[email protected]>
---
 tools/golang/xenlight/xenlight.go | 72 ++++++++++++++++++++++++++++++-
 1 file changed, 70 insertions(+), 2 deletions(-)
tools/golang/xenlight/xenlight.go +70 -2
index 662b266250..c462e4bb42 100644
@@ -20,6 +20,8 @@ package xenlight
 #cgo LDFLAGS: -lxenlight -lyajl -lxentoollog
 #include <stdlib.h>
 #include <libxl.h>
+
+libxl_childproc_hooks xenlight_childproc_hooks;
 */
 import "C"
 
@@ -33,6 +35,9 @@ import "C"
 
 import (
 	"fmt"
+	"os"
+	"os/signal"
+	"syscall"
 	"unsafe"
 )
 
@@ -72,10 +77,49 @@ func (e Error) Error() string {
 	return fmt.Sprintf("libxl error: %d", e)
 }
 
+func init() {
+	// libxl for some reason wants to:
+	// 1. Retain a copy to this pointer as long as the context is open, and
+	// 2. Not free it when it's done
+	//
+	// Rather than alloc and free multiple copies, just keep a single
+	// static copy in the C space (since C code isn't allowed to retain pointers
+	// to go code), and initialize it once.
+	C.xenlight_childproc_hooks.chldowner = C.libxl_sigchld_owner_mainloop
+}
+
 // Context represents a libxl_ctx.
 type Context struct {
-	ctx    *C.libxl_ctx
-	logger *C.xentoollog_logger_stdiostream
+	ctx         *C.libxl_ctx
+	logger      *C.xentoollog_logger_stdiostream
+	sigchld     chan os.Signal
+	sigchldDone chan bool
+}
+
+// Golang always unmasks SIGCHLD, and internally has ways of
+// distributing SIGCHLD to multiple recipients.  libxl has provision
+// for this model: just tell it when a SIGCHLD happened, and it will
+// look after its own processes.
+//
+// This should "play nicely" with other users of SIGCHLD as long as
+// they don't reap libxl's processes.
+//
+// Every context needs to be notified on each SIGCHLD; so spin up a
+// new goroutine for each context.  If there are a large number of contexts,
+// this means each context will be woken up looking through its own list of children.
+//
+// The alternate would be to register a fork callback, such that the
+// xenlight package can make a single list of all children, and only
+// notify the specific libxl context(s) that have children woken.  But
+// it's not clear to me this will be much more work than having the
+// xenlight go library do the same thing; doing it in separate go
+// threads has the potential to do it in parallel.  Leave that as an
+// optimization for later if it turns out to be a bottleneck.
+func sigchldHandler(ctx *Context) {
+	for _ = range ctx.sigchld {
+		go C.libxl_childproc_sigchld_occurred(ctx.ctx)
+	}
+	close(ctx.sigchldDone)
 }
 
 // NewContext returns a new Context.
@@ -89,19 +133,43 @@ func NewContext() (ctx *Context, err error) {
 		}
 	}()
 
+	// Create a logger
 	ctx.logger = C.xtl_createlogger_stdiostream(C.stderr, C.XTL_DEBUG, 0)
 
+	// Allocate a context
 	ret := C.libxl_ctx_alloc(&ctx.ctx, C.LIBXL_VERSION, 0,
 		(*C.xentoollog_logger)(unsafe.Pointer(ctx.logger)))
 	if ret != 0 {
 		return ctx, Error(ret)
 	}
 
+	// Tell libxl that we'll be dealing with SIGCHLD...
+	C.libxl_childproc_setmode(ctx.ctx, &C.xenlight_childproc_hooks, nil)
+
+	// ...and arrange to keep that promise.
+	ctx.sigchld = make(chan os.Signal, 2)
+	ctx.sigchldDone = make(chan bool, 1)
+	signal.Notify(ctx.sigchld, syscall.SIGCHLD)
+
+	go sigchldHandler(ctx)
+
 	return ctx, nil
 }
 
 // Close closes the Context.
 func (ctx *Context) Close() error {
+	// Tell our SIGCHLD notifier to shut down, and wait for it to exit
+	// before we free the context.
+	if ctx.sigchld == nil {
+		signal.Stop(ctx.sigchld)
+		close(ctx.sigchld)
+
+		<-ctx.sigchldDone
+
+		ctx.sigchld = nil
+		ctx.sigchldDone = nil
+	}
+
 	if ctx.ctx != nil {
 		ret := C.libxl_ctx_free(ctx.ctx)
 		if ret != 0 {
Signature · 7 lines
2.24.1


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel
Reviewed-by on v3 7/8
#14 lore raw

Re: [Xen-devel] [PATCH v3 7/8] golang/xenlight: Notify xenlight of SIGCHLD

George Dunlap writes ("[PATCH v3 7/8] golang/xenlight: Notify xenlight of SIGCHLD"):

Quoted 18 lines

libxl forks external processes and waits for them to complete; it therefore needs to be notified when children exit.

In absence of instructions to the contrary, libxl sets up its own SIGCHLD handlers.

Golang always unmasks and handles SIGCHLD itself. libxl thankfully notices this and throws an assert() rather than clobbering SIGCHLD handlers.

Tell libxl that we'll be responsible for getting SIGCHLD notifications to it. Arrange for a channel in the context to receive notifications on SIGCHLD, and set up a goroutine that will pass these on to libxl.

NB that every libxl context needs a notification; so multiple contexts will each spin up their own goroutine when opening a context, and shut it down on close.

Quoted 6 lines

libxl also wants to hold on to a const pointer to xenlight_childproc_hooks rather than do a copy; so make a global structure in C space and initialize it once on library creation.

While here, add a few comments to make the context set-up a bit easier to follow.

For what it's worth,

However, I don't think I understand golang (and particularly the threading model etc.) well enough for that to mean I'm confident that this correct.

tools/golang/xenlight/xenlight.go func (e Error) Error() string { · line 83

Quoted 4 lines
tools/golang/xenlight/xenlight.go +4 -0
+func init() {
+	// libxl for some reason wants to:
+	// 1. Retain a copy to this pointer as long as the context is open, and
+	// 2. Not free it when it's done

I found this comment a bit rude. This is not an unusual approach for a pointer in a C API.

In Rust this would be called an `immutable borrow': the ctx borrows the contents of the pointer, promises not to modify it (and the caller ought to promise not to modify it either); but the caller retains ownership so when the ctx is done the borrow ends.

Normally in C the struct would be `static const', so there is no need to allocate it or free it.

I think that ...

tools/golang/xenlight/xenlight.go func (e Error) Error() string { · line 88

Quoted 4 lines
tools/golang/xenlight/xenlight.go +4 -0
+	// Rather than alloc and free multiple copies, just keep a single
+	// static copy in the C space (since C code isn't allowed to retain pointers
+	// to go code), and initialize it once.
+	C.xenlight_childproc_hooks.chldowner = C.libxl_sigchld_owner_mainloop

... this is what this is doing ?

tools/golang/xenlight/xenlight.go func (e Error) Error() string { · line 105

Quoted 2 lines
tools/golang/xenlight/xenlight.go +2 -0
+// This should "play nicely" with other users of SIGCHLD as long as
+// they don't reap libxl's processes.

I assume that nothing in golang will do this. If something calls a non-process-specific variant of wait* then you would need to somehow capture the results and feed them to libxl_childproc_exited.

tools/golang/xenlight/xenlight.go func (e Error) Error() string { · line 117

Quoted 7 lines
tools/golang/xenlight/xenlight.go +7 -0
+// The alternate would be to register a fork callback, such that the
+// xenlight package can make a single list of all children, and only
+// notify the specific libxl context(s) that have children woken.  But
+// it's not clear to me this will be much more work than having the
+// xenlight go library do the same thing; doing it in separate go
+// threads has the potential to do it in parallel.  Leave that as an
+// optimization for later if it turns out to be a bottleneck.

I think this is fine.

Thanks,
Ian.

_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel

#15 lore raw

Re: [Xen-devel] [PATCH v3 7/8] golang/xenlight: Notify xenlight of SIGCHLD

Quoted 26 lines · Ian Jackson

George Dunlap writes ("[PATCH v3 7/8] golang/xenlight: Notify xenlight of SIGCHLD"):

Quoted 18 lines

libxl forks external processes and waits for them to complete; it therefore needs to be notified when children exit.

In absence of instructions to the contrary, libxl sets up its own SIGCHLD handlers.

Golang always unmasks and handles SIGCHLD itself. libxl thankfully notices this and throws an assert() rather than clobbering SIGCHLD handlers.

Tell libxl that we'll be responsible for getting SIGCHLD notifications to it. Arrange for a channel in the context to receive notifications on SIGCHLD, and set up a goroutine that will pass these on to libxl.

NB that every libxl context needs a notification; so multiple contexts will each spin up their own goroutine when opening a context, and shut it down on close.

Quoted 6 lines

libxl also wants to hold on to a const pointer to xenlight_childproc_hooks rather than do a copy; so make a global structure in C space and initialize it once on library creation.

While here, add a few comments to make the context set-up a bit easier to follow.

Quoted 7 lines

For what it's worth,

However, I don't think I understand golang (and particularly the threading model etc.) well enough for that to mean I'm confident that this correct.

Thanks -- I mainly just wanted to give you the opportunity to spot any obvious things I was doing wrong wrt libxl. (For instance, an earlier version of this patch had me destroying the libxl context before shutting down the sigchld helper, which is obviously wrong.)

Quoted 11 lines

tools/golang/xenlight/xenlight.go func (e Error) Error() string { · line 83

Quoted 4 lines
tools/golang/xenlight/xenlight.go +4 -0
+func init() {
+	// libxl for some reason wants to:
+	// 1. Retain a copy to this pointer as long as the context is open, and
+	// 2. Not free it when it's done

I found this comment a bit rude. This is not an unusual approach for a pointer in a C API.>
In Rust this would be called an `immutable borrow': the ctx borrows the contents of the pointer, promises not to modify it (and the caller ought to promise not to modify it either); but the caller retains ownership so when the ctx is done the borrow ends.

I'm sorry to be rude; I've deleted the comment. But none of what you said is obvious from the documentation; on the contrary:

---
...is equivalent to &{ libxl_sigchld_owner_libxl, 0, 0 }
---

...seems to imply that you can pass it a pointer to the stack. And, from an interface perspective, that seems obviously better to me -- rather than make the caller promise not to change the contents (to who-knows-what result if they forget), it's much easier to just take a local copy and update it with locks next time the function is called.

I was slightly more annoyed because Go's rule about C functions not retaining pointers to Go memory meant I had to do some un-Golike things to make this work; but that's nothing to do with libxl.

Quoted 11 lines

Normally in C the struct would be `static const', so there is no need to allocate it or free it.

I think that ...

tools/golang/xenlight/xenlight.go func (e Error) Error() string { · line 88

Quoted 4 lines
tools/golang/xenlight/xenlight.go +4 -0
+	// Rather than alloc and free multiple copies, just keep a single
+	// static copy in the C space (since C code isn't allowed to retain pointers
+	// to go code), and initialize it once.
+	C.xenlight_childproc_hooks.chldowner = C.libxl_sigchld_owner_mainloop

... this is what this is doing ?

In fact, there's a global C variable declared here:

---
#include <libxl.h>
+
+libxl_childproc_hooks xenlight_childproc_hooks;
*/
import "C"
---

...and the line above just initialized it. But on reflection I've decided to do this:

---
/*

#cgo LDFLAGS: -lxenlight -lyajl -lxentoollog
#include <stdlib.h>
#include <libxl.h>

static const libxl_childproc_hooks childproc_hooks = { .chldowner = libxl_sigchld_owner_mainloop };

void xenlight_set_chldproc(libxl_ctx *ctx) {
	libxl_childproc_setmode(ctx, &childproc_hooks, NULL);
}

*/
import "C"
---

That declares childproc_hooks as static const in the C space; and then defines a C function which takes a libxl_ctx* and calls libxl_childproc_setmode appropriately. That way childproc_hooks can enjoy the safety of static const.

Quoted 9 lines

tools/golang/xenlight/xenlight.go func (e Error) Error() string { · line 117

Quoted 7 lines
tools/golang/xenlight/xenlight.go +7 -0
+// The alternate would be to register a fork callback, such that the
+// xenlight package can make a single list of all children, and only
+// notify the specific libxl context(s) that have children woken.  But
+// it's not clear to me this will be much more work than having the
+// xenlight go library do the same thing; doing it in separate go
+// threads has the potential to do it in parallel.  Leave that as an
+// optimization for later if it turns out to be a bottleneck.

I think this is fine.

Thanks.

-George

_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel

#16 lore raw

PATCH 1/1 libxl: event: Document lifetime API for libxl_childproc_setmode

There is already an identical comment for
libxl_osevent_register_hooks.

libxl_childproc_setmode's hooks parameter has the same property and this should be documented.

Reported-by; George Dunlap <[email protected]>

---
 tools/libxl/libxl_event.h | 2 ++
 1 file changed, 2 insertions(+)
tools/libxl/libxl_event.h +2 -0
index d1517f7456..8d0aa6417e 100644
@@ -548,6 +548,8 @@ typedef struct {
  * May not be called when libxl might have any child processes, or the
  * behaviour is undefined.  So it is best to call this at
  * initialisation.
+ *
+ * The value *hooks is not copied and must outlast the libxl_ctx.
  */
 void libxl_childproc_setmode(libxl_ctx *ctx, const libxl_childproc_hooks *hooks,
                              void *user);
Signature · 7 lines
2.11.0


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel
Acked-by on v1 1/1
#17 lore raw

Re: [Xen-devel] [PATCH] libxl: event: Document lifetime API for libxl_childproc_setmode

Quoted 8 lines · Ian Jackson

There is already an identical comment for
libxl_osevent_register_hooks.

libxl_childproc_setmode's hooks parameter has the same property and this should be documented.

Reported-by; George Dunlap <[email protected]>

_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel

#18 lore raw

Re: [Xen-devel] [PATCH v3 7/8] golang/xenlight: Notify xenlight of SIGCHLD

In reply to George Dunlap

tools/golang/xenlight/xenlight.go func (e Error) Error() string { · line 96

Quoted 8 lines

// Context represents a libxl_ctx.
type Context struct {

tools/golang/xenlight/xenlight.go +4 -2
-       ctx    *C.libxl_ctx
-       logger *C.xentoollog_logger_stdiostream
+       ctx         *C.libxl_ctx
+       logger      *C.xentoollog_logger_stdiostream
+       sigchld     chan os.Signal
+       sigchldDone chan bool

It's preferred to use chan struct{} for this pattern; it makes it clear that the data sent over the channel has no meaning, and is only intended to be used for synchronization.

tools/golang/xenlight/xenlight.go func NewContext() (ctx *Context, err error) { · line 154

Quoted 6 lines
tools/golang/xenlight/xenlight.go +6 -0
+       // ...and arrange to keep that promise.
+       ctx.sigchld = make(chan os.Signal, 2)
+       ctx.sigchldDone = make(chan bool, 1)
+       signal.Notify(ctx.sigchld, syscall.SIGCHLD)
+
+       go sigchldHandler(ctx)

It could be useful to add a comment here that explains the lifetime of this goroutine, i.e. it returns when the context is Close()'d.

tools/golang/xenlight/xenlight.go func NewContext() (ctx *Context, err error) { · line 163

Quoted 5 lines

// Close closes the Context.
func (ctx *Context) Close() error {

tools/golang/xenlight/xenlight.go +3 -0
+       // Tell our SIGCHLD notifier to shut down, and wait for it to exit
+       // before we free the context.
+       if ctx.sigchld == nil {

Shouldn't this be if ctx.sigchld != nil?

-NR

_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel

#19 lore raw

Re: [Xen-devel] [PATCH v3 7/8] golang/xenlight: Notify xenlight of SIGCHLD

Quoted 9 lines · Nick Rosbrook

tools/golang/xenlight/xenlight.go func (e Error) Error() string { · line 96

Quoted 8 lines

// Context represents a libxl_ctx.
type Context struct {

tools/golang/xenlight/xenlight.go +4 -2
-       ctx    *C.libxl_ctx
-       logger *C.xentoollog_logger_stdiostream
+       ctx         *C.libxl_ctx
+       logger      *C.xentoollog_logger_stdiostream
+       sigchld     chan os.Signal
+       sigchldDone chan bool
Quoted 3 lines

It's preferred to use chan struct{} for this pattern; it makes it clear that the data sent over the channel has no meaning, and is only intended to be used for synchronization.

OK. I think it looks ugly, but there's certainly a signalling value to having it really be empty.

Quoted 10 lines

tools/golang/xenlight/xenlight.go func NewContext() (ctx *Context, err error) { · line 154

Quoted 7 lines
tools/golang/xenlight/xenlight.go +6 -0
+       // ...and arrange to keep that promise.
+       ctx.sigchld = make(chan os.Signal, 2)
+       ctx.sigchldDone = make(chan bool, 1)
+       signal.Notify(ctx.sigchld, syscall.SIGCHLD)
+
+       go sigchldHandler(ctx)

It could be useful to add a comment here that explains the lifetime of this goroutine, i.e. it returns when the context is Close()'d.

Ack.

Quoted 7 lines

tools/golang/xenlight/xenlight.go func NewContext() (ctx *Context, err error) { · line 163

Quoted 5 lines

// Close closes the Context.
func (ctx *Context) Close() error {

tools/golang/xenlight/xenlight.go +3 -0
+       // Tell our SIGCHLD notifier to shut down, and wait for it to exit
+       // before we free the context.
+       if ctx.sigchld == nil {

Shouldn't this be if ctx.sigchld != nil?

Er, yes, indeed it should. This has gone through too many iterations...

-George

_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel

#20 lore raw

PATCH v3 8/8 RFC: Sketch constructors, DomainCreateNew

In reply to George Dunlap

This is a sketch of functionality suitable for creating a basic domain, with a disk and a vif. DomainConfig, DeviceDisk, and DeviceNic types are all created using constructor functions, which initialize them with libxl's defaults.

DomainCreateNew takes the config and calls without any updates.

Obviously some of these will need to be changed it we switch to passing references to .toC() rather than passing back by value.

The main purpose of this is to allow testing of creating a hard-coded domain.

Creating a domain would look like this:

	// type = "pv"
	dconf, err := xl.NewDomainConfig(xl.DomainTypePv)
	if err != nil {
		fmt.Printf("NewDomainConfig: %v\n", err)
		return
	}
	dconf.CInfo.Type = xl.DomainTypePv
	// name = "c6-01"
	dconf.CInfo.Name = "c6-01"
	// vcpus=4
	dconf.BInfo.MaxVcpus = 4
	// memory = "2048"
	dconf.BInfo.MaxMemkb = 2048 * 1024
	dconf.BInfo.TargetMemkb = 2048 * 1024
	// on_crash = 'destroy'
	dconf.OnCrash = xl.ActionOnShutdownDestroy
	// bootloader = "pygrub"
	dconf.BInfo.Bootloader = "pygrub"
	// disk = [ 'vdev=hda,format=raw,target=/images/c6-01.raw']
	{
		disk, err := xl.NewDeviceDisk()
		if err != nil {
			fmt.Printf("NewDeviceDisk: %v\n", err)
			return
		}
		disk.Vdev = "hda"
		//disk.DiskBackend = xl.DiskBackendPhy
		disk.Format = xl.DiskFormatRaw
		disk.Readwrite = 1
		disk.PdevPath = "/images/c6-01.raw"
		dconf.Disks = append(dconf.Disks, *disk)
	}
	// vif = [ 'mac=5a:5b:d6:f1:d6:b4' ]
	{
		vif, err := xl.NewDeviceNic()
		if err != nil {
			fmt.Printf("NewDeviceNic: %v\n", err)
			return
		}
		vif.Mac = xl.Mac{ 0x5a, 0x5b, 0xd6, 0x31, 0xd6, 0xb4 }
		dconf.Nics = append(dconf.Nics, *vif)
	}
	// serial='pty' # HVM only

	did, err := ctx.DomainCreateNew(dconf)

	if err != nil {
		fmt.Printf("Creating domain: %v\n", err)
		return
	}

	fmt.Printf("Domain %s(%d) created successfully", dconf.CInfo.Name, did)

---
CC: Nick Rosbrook <[email protected]>

---
 tools/golang/xenlight/xenlight.go | 66 +++++++++++++++++++++++++++++++
 1 file changed, 66 insertions(+)
tools/golang/xenlight/xenlight.go +66 -0
index c462e4bb42..5a21a2b9b8 100644
@@ -1113,3 +1113,69 @@ func (Ctx *Context) PrimaryConsoleGetTty(domid uint32) (path string, err error)
 	path = C.GoString(cpath)
 	return
 }
+
+func NewDomainConfig(t DomainType) (*DomainConfig, error) {
+	var cconfig C.libxl_domain_config
+
+	C.libxl_domain_config_init(&cconfig)
+	C.libxl_domain_build_info_init_type(&cconfig.b_info, C.libxl_domain_type(t))
+
+	gconfig := &DomainConfig{}
+	err := gconfig.fromC(&cconfig)
+	if err != nil {
+		return nil, err
+	}
+
+	return gconfig, nil
+}
+
+func NewDeviceDisk() (*DeviceDisk, error) {
+	var ctype C.libxl_device_disk
+
+	C.libxl_device_disk_init(&ctype)
+
+	gtype := &DeviceDisk{}
+	err := gtype.fromC(&ctype)
+
+	if err != nil {
+		return nil, err
+	}
+
+	return gtype, nil
+}
+
+func NewDeviceNic() (*DeviceNic, error) {
+	var ctype C.libxl_device_nic
+
+	C.libxl_device_nic_init(&ctype)
+
+	gtype := &DeviceNic{}
+	err := gtype.fromC(&ctype)
+
+	if err != nil {
+		return nil, err
+	}
+
+	return gtype, nil
+}
+
+// int libxl_domain_create_new(libxl_ctx *ctx, libxl_domain_config *d_config,
+//                             uint32_t *domid,
+//                             const libxl_asyncop_how *ao_how,
+//                             const libxl_asyncprogress_how *aop_console_how)
+func (Ctx *Context) DomainCreateNew(config *DomainConfig) (Domid, error) {
+	var cdomid C.uint32_t
+	var cconfig C.libxl_domain_config
+	err := config.toC(&cconfig)
+	if err != nil {
+		return Domid(0), fmt.Errorf("converting domain config to C: %v", err)
+	}
+	defer C.libxl_domain_config_dispose(&cconfig)
+
+	ret := C.libxl_domain_create_new(Ctx.ctx, &cconfig, &cdomid, nil, nil)
+	if ret != 0 {
+		return Domid(0), Error(ret)
+	}
+
+	return Domid(cdomid), nil
+}
Signature · 7 lines
2.24.1


_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel
#21 lore raw

Re: [Xen-devel] [PATCH v3 8/8] RFC: Sketch constructors, DomainCreateNew

Quoted 140 lines · George Dunlap

This is a sketch of functionality suitable for creating a basic domain, with a disk and a vif. DomainConfig, DeviceDisk, and DeviceNic types are all created using constructor functions, which initialize them with libxl's defaults.

DomainCreateNew takes the config and calls without any updates.

Obviously some of these will need to be changed it we switch to passing references to .toC() rather than passing back by value.

The main purpose of this is to allow testing of creating a hard-coded domain.

Creating a domain would look like this:

	// type = "pv"
	dconf, err := xl.NewDomainConfig(xl.DomainTypePv)
	if err != nil {
		fmt.Printf("NewDomainConfig: %v\n", err)
		return
	}
	dconf.CInfo.Type = xl.DomainTypePv
	// name = "c6-01"
	dconf.CInfo.Name = "c6-01"
	// vcpus=4
	dconf.BInfo.MaxVcpus = 4
	// memory = "2048"
	dconf.BInfo.MaxMemkb = 2048 * 1024
	dconf.BInfo.TargetMemkb = 2048 * 1024
	// on_crash = 'destroy'
	dconf.OnCrash = xl.ActionOnShutdownDestroy
	// bootloader = "pygrub"
	dconf.BInfo.Bootloader = "pygrub"
	// disk = [ 'vdev=hda,format=raw,target=/images/c6-01.raw']
	{
		disk, err := xl.NewDeviceDisk()
		if err != nil {
			fmt.Printf("NewDeviceDisk: %v\n", err)
			return
		}
		disk.Vdev = "hda"
		//disk.DiskBackend = xl.DiskBackendPhy
		disk.Format = xl.DiskFormatRaw
		disk.Readwrite = 1
		disk.PdevPath = "/images/c6-01.raw"
		dconf.Disks = append(dconf.Disks, *disk)
	}
	// vif = [ 'mac=5a:5b:d6:f1:d6:b4' ]
	{
		vif, err := xl.NewDeviceNic()
		if err != nil {
			fmt.Printf("NewDeviceNic: %v\n", err)
			return
		}
		vif.Mac = xl.Mac{ 0x5a, 0x5b, 0xd6, 0x31, 0xd6, 0xb4 }
		dconf.Nics = append(dconf.Nics, *vif)
	}
	// serial='pty' # HVM only

	did, err := ctx.DomainCreateNew(dconf)

	if err != nil {
		fmt.Printf("Creating domain: %v\n", err)
		return
	}

	fmt.Printf("Domain %s(%d) created successfully", dconf.CInfo.Name, did)

---
CC: Nick Rosbrook <[email protected]>

---
 tools/golang/xenlight/xenlight.go | 66 +++++++++++++++++++++++++++++++
 1 file changed, 66 insertions(+)
tools/golang/xenlight/xenlight.go +56 -0
index c462e4bb42..5a21a2b9b8 100644
@@ -1113,3 +1113,69 @@ func (Ctx *Context) PrimaryConsoleGetTty(domid uint32) (path string, err error)
 	path = C.GoString(cpath)
 	return
 }
+
+func NewDomainConfig(t DomainType) (*DomainConfig, error) {
+	var cconfig C.libxl_domain_config
+
+	C.libxl_domain_config_init(&cconfig)
+	C.libxl_domain_build_info_init_type(&cconfig.b_info, C.libxl_domain_type(t))
+
+	gconfig := &DomainConfig{}
+	err := gconfig.fromC(&cconfig)
+	if err != nil {
+		return nil, err
+	}
+
+	return gconfig, nil
+}
+
+func NewDeviceDisk() (*DeviceDisk, error) {
+	var ctype C.libxl_device_disk
+
+	C.libxl_device_disk_init(&ctype)
+
+	gtype := &DeviceDisk{}
+	err := gtype.fromC(&ctype)
+
+	if err != nil {
+		return nil, err
+	}
+
+	return gtype, nil
+}
+
+func NewDeviceNic() (*DeviceNic, error) {
+	var ctype C.libxl_device_nic
+
+	C.libxl_device_nic_init(&ctype)
+
+	gtype := &DeviceNic{}
+	err := gtype.fromC(&ctype)
+
+	if err != nil {
+		return nil, err
+	}
+
+	return gtype, nil
+}
+
+// int libxl_domain_create_new(libxl_ctx *ctx, libxl_domain_config *d_config,
+//                             uint32_t *domid,
+//                             const libxl_asyncop_how *ao_how,
+//                             const libxl_asyncprogress_how *aop_console_how)
+func (Ctx *Context) DomainCreateNew(config *DomainConfig) (Domid, error) {
+	var cdomid C.uint32_t
+	var cconfig C.libxl_domain_config
+	err := config.toC(&cconfig)
+	if err != nil {
+		return Domid(0), fmt.Errorf("converting domain config to C: %v", err)

tools/golang/xenlight/xenlight.go func (Ctx *Context) PrimaryConsoleGetTty(domid uint32) (path string, err error) · line 1181

Quoted 10 lines
tools/golang/xenlight/xenlight.go +10 -0
+	}
+	defer C.libxl_domain_config_dispose(&cconfig)
+
+	ret := C.libxl_domain_create_new(Ctx.ctx, &cconfig, &cdomid, nil, nil)
+	if ret != 0 {
+		return Domid(0), Error(ret)
+	}
+
+	return Domid(cdomid), nil
+}

An alternate way to do this would be something like this:

---
func NewDomainConfig(t DomainType, populate func(*DomainConfig))

*DomainConfig {
	var ctype C.libxl_domain_config

	C.libxl_domain_config_init(&ctype)
	C.libxl_domain_build_info_init_type(&ctype.b_info, C.libxl_domain_type(t))

	gtype := &DomainConfig{}
	err := gtype.fromC(&ctype)
	if err != nil {
		panic("internal error: Can't convert empty DomainConfig")
	}

	if populate != nil {
		populate(gtype)
	}

	return gtype
}
func NewDeviceDisk(populate func(*DeviceDisk)) *DeviceDisk {
	var ctype C.libxl_device_disk

	C.libxl_device_disk_init(&ctype)

	gtype := &DeviceDisk{}
	err := gtype.fromC(&ctype)

	if err != nil {
		panic("internal error: Can't convert empty DeviceDisk")
	}

	if populate != nil {
		populate(gtype)
	}

	return gtype
}
func NewDeviceNic(populate func(*DeviceNic)) *DeviceNic {
	var ctype C.libxl_device_nic

	C.libxl_device_nic_init(&ctype)

	gtype := &DeviceNic{}
	err := gtype.fromC(&ctype)

	if err != nil {
		panic("internal error: Can't convert empty DeviceNic")
	}

	if populate != nil {
		populate(gtype)
	}

	return gtype
}

---

And then code to populate a domain config might look like this:

	dconf := xl.NewDomainConfig(xl.DomainTypePv, func(dconf *xl.DomainConfig) {
		dconf.CInfo.Type = xl.DomainTypePv
		// name = "c6-01"
		dconf.CInfo.Name = "c6-01"
		// vcpus=4
		dconf.BInfo.MaxVcpus = 4
		// memory = "2048"
		dconf.BInfo.MaxMemkb = 2048 * 1024
		dconf.BInfo.TargetMemkb = 2048 * 1024
		// on_crash = 'destroy'
		dconf.OnCrash = xl.ActionOnShutdownDestroy
		// bootloader = "pygrub"
		dconf.BInfo.Bootloader = "pygrub"
	})

	dconf.Disks = []xl.DeviceDisk{*xl.NewDeviceDisk(func(disk *xl.DeviceDisk) {
		disk.Vdev = "hda"
		//disk.DiskBackend = xl.DiskBackendPhy
		disk.Format = xl.DiskFormatRaw
		disk.Readwrite = 1
		disk.PdevPath = "/images/c6-01.raw"
		dconf.Disks = append(dconf.Disks, *disk)
	})}

	dconf.Nics = []xl.DeviceNic{*xl.NewDeviceNic(func(vif *xl.DeviceNic) {
		vif.Mac = xl.Mac{0x5a, 0x5b, 0xd6, 0x31, 0xd6, 0xb4}
	})}

_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel

#22 lore raw

Re: [Xen-devel] [PATCH v3 8/8] RFC: Sketch constructors, DomainCreateNew

In reply to George Dunlap
Quoted 5 lines · George Dunlap

This is a sketch of functionality suitable for creating a basic domain, with a disk and a vif. DomainConfig, DeviceDisk, and DeviceNic types are all created using constructor functions, which initialize them with libxl's defaults.

Quoted 7 lines

DomainCreateNew takes the config and calls without any updates.

Obviously some of these will need to be changed it we switch to passing references to .toC() rather than passing back by value.

The main purpose of this is to allow testing of creating a hard-coded domain.

BTW, just in case anyone decides to try this -- this will create a domain in the "paused" state, and it does not create a "reaper" for it when the domain shuts down. You have to manually xl unpause the domain for it to run, and then xl destroy the domain after it shuts down.

The first is just an implementation detail; the second requires adding the ability to receive events, which will be the next "level" of libxl event handling support.

-George

_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel

#23 lore raw

Re: [Xen-devel] [PATCH v3 8/8] RFC: Sketch constructors, DomainCreateNew

In reply to George Dunlap

Sorry for the late reply on this one.

Quoted 4 lines
tools/golang/xenlight/xenlight.go +4 -0
+func NewDomainConfig(t DomainType) (*DomainConfig, error) {
+       var cconfig C.libxl_domain_config
+
+       C.libxl_domain_config_init(&cconfig)

tools/golang/xenlight/xenlight.go func (Ctx *Context) PrimaryConsoleGetTty(domid uint32) (path string, err error) · line 1130

Quoted 10 lines
tools/golang/xenlight/xenlight.go +10 -0
+       C.libxl_domain_build_info_init_type(&cconfig.b_info, C.libxl_domain_type(t))
+
+       gconfig := &DomainConfig{}
+       err := gconfig.fromC(&cconfig)
+       if err != nil {
+               return nil, err
+       }
+
+       return gconfig, nil
+}

I think this is sufficient for the "New" functions; simple is probably better here. I appreciate the idea of the populate func approach you mentioned in another email, but I think in practice people will want to leverage encoding/json or otherwise to unmarshal some data into a DomainConfig etc. Or, we would hopefully be able to unmarshal an xl.cfg. All that is to say, I think the approach you have shown here gives us and package users the most flexibility.

Do you have any thoughts on supporting unmarshaling json, xl.cfg, etc.?

If we stick with this outline for constructors, they will be easy to generate. I'm happy to work on that, unless you were already planning on it.

Thanks,
-NR

_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel

#24 lore raw

Re: [Xen-devel] [PATCH v3 8/8] RFC: Sketch constructors, DomainCreateNew

Quoted 17 lines · Nick Rosbrook

Sorry for the late reply on this one.

Quoted 4 lines
tools/golang/xenlight/xenlight.go +4 -0
+func NewDomainConfig(t DomainType) (*DomainConfig, error) {
+       var cconfig C.libxl_domain_config
+
+       C.libxl_domain_config_init(&cconfig)

tools/golang/xenlight/xenlight.go func (Ctx *Context) PrimaryConsoleGetTty(domid uint32) (path string, err error) · line 1130

Quoted 10 lines
tools/golang/xenlight/xenlight.go +10 -0
+       C.libxl_domain_build_info_init_type(&cconfig.b_info, C.libxl_domain_type(t))
+
+       gconfig := &DomainConfig{}
+       err := gconfig.fromC(&cconfig)
+       if err != nil {
+               return nil, err
+       }
+
+       return gconfig, nil
+}
Quoted 7 lines

I think this is sufficient for the "New" functions; simple is probably better here. I appreciate the idea of the populate func approach you mentioned in another email, but I think in practice people will want to leverage encoding/json or otherwise to unmarshal some data into a DomainConfig etc. Or, we would hopefully be able to unmarshal an xl.cfg. All that is to say, I think the approach you have shown here gives us and package users the most flexibility.

I think marshaling and unmarshalling should be fine, *as long as* the structure being unmarshalled actually went through the libxl_<type>_init() function first.

In fact, I was kicking around the idea of adding a non-exported field to all the generated structs -- maybe "bool initalized" -- and having the .fromC() methods set this to 'true', and the .toC() methods return an error if it wasn't set. But then we'd need to write custom JSON marshallers to handle these.

I'm not personally very interested in parsing xl.cfg files, but libxl has library functions to do that, so it should be something very easy to add if you want. (Although in fact, it looks like a lot of the code to actually interpret the results of the parsing is in xl; we might want to see about moving some of that functionality into libxlu.)

Quoted 3 lines

If we stick with this outline for constructors, they will be easy to generate. I'm happy to work on that, unless you were already planning on it.

I'm afraid my 1 day a week of coding is going to have to be diverted to something else for a month or so; so please go ahead if you have the time.

As far as further steps -- do you have a clear idea what kind of functionality you'd like to see possible by the time of the feature freeze (probably in May)? Do you have plans to use these bindings yourself, and if so, how?

For my part, I want to start and reap guests. The latter will require adding event callback functionality which will require more thought (and perhaps expose more libxl issues). But I don't yet have a clear target beyond that.

Re function calls -- do we want to just manually duplicate them as needed, or try to get some sort of IDL support?

Other work items include:

* modifying configure to detect the availability of go and enable the bindings if it's available

* Enabling go build testing in the gitlab CI loop

* Making go get work, which might involve having code to push post-generated code to a repo and tagging as appropriate

-George

_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel

#25 lore raw

Re: [Xen-devel] [PATCH v3 8/8] RFC: Sketch constructors, DomainCreateNew

Quoted 9 lines

I think marshaling and unmarshalling should be fine, *as long as* the structure being unmarshalled actually went through the libxl_<type>_init() function first.

In fact, I was kicking around the idea of adding a non-exported field to all the generated structs -- maybe "bool initalized" -- and having the .fromC() methods set this to 'true', and the .toC() methods return an error if it wasn't set. But then we'd need to write custom JSON marshallers to handle these.

I *think* to guarantee that libxl_<type>_init() has been called when unmarshaling, we would need to generate UnmarshalJSON functions to implement json.Unmarshaler. E.g.,:

func (dd *DeviceDisk) UnmarshalJSON(data []byte) error {
        if dd == nil { // Or maybe this is the 'initialized' check you mentioned
                dd, err := NewDeviceDisk()
                if err != nil {
                        return err
                }
        }

        return json.Unmarshal(data, dd)
}

AFAICT, this would be required for someone to unmarshal a complete domain configuration in one go.

Quoted 5 lines

I'm not personally very interested in parsing xl.cfg files, but libxl has library functions to do that, so it should be something very easy to add if you want. (Although in fact, it looks like a lot of the code to actually interpret the results of the parsing is in xl; we might want to see about moving some of that functionality into libxlu.)

Okay, noted.

Quoted 6 lines
Quoted 3 lines

If we stick with this outline for constructors, they will be easy to generate. I'm happy to work on that, unless you were already planning on it.

I'm afraid my 1 day a week of coding is going to have to be diverted to something else for a month or so; so please go ahead if you have the time.

Okay, I think I can manage this fairly easily.

Quoted 9 lines

As far as further steps -- do you have a clear idea what kind of functionality you'd like to see possible by the time of the feature freeze (probably in May)? Do you have plans to use these bindings yourself, and if so, how?

For my part, I want to start and reap guests. The latter will require adding event callback functionality which will require more thought (and perhaps expose more libxl issues). But I don't yet have a clear target beyond that.

Yes, I plan on using these bindings in redctl (our Redfield toolstack) [1], to replace our os/exec calls to xl. To fully make that transition, we would need domain start/stop, PCI and network attach/detach, as well as some utilities (most of which are either implemented, or would be easy to do). But, making that transition is relatively low on the priority list right now, so I can't commit to a timeline unfortunately.

Quoted 2 lines

Re function calls -- do we want to just manually duplicate them as needed, or try to get some sort of IDL support?

I think it will make more sense to manually duplicate them as needed. That way, we can be more particular about function signatures etc. to ensure they are idiomatic Go. Also, I am of the opinion that a minimal API is a better place to start. Which brings me to another question and potential work item:

Do we want to re-evaluate what is currently implemented in the API? Do you have plans to use everything that is currently there? If not, it might be nice to trim off things we don't need right now.

Quoted 9 lines

Other work items include:

* modifying configure to detect the availability of go and enable the bindings if it's available

* Enabling go build testing in the gitlab CI loop

* Making go get work, which might involve having code to push post-generated code to a repo and tagging as appropriate

I was going to ask about this. You had a vanity URL in place at one point, right? Did go get ever work with that? In any case, pushing to another repo might be desirable.

Thanks,
-NR

[1] https://gitlab.com/redfield/redctl

_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel

#26 lore raw

Re: [Xen-devel] [PATCH v3 8/8] RFC: Sketch constructors, DomainCreateNew

Quoted 6 lines

I *think* to guarantee that libxl_<type>_init() has been called when unmarshaling, we would need to generate UnmarshalJSON functions to implement json.Unmarshaler. E.g.,:

func (dd *DeviceDisk) UnmarshalJSON(data []byte) error {
        if dd == nil { // Or maybe this is the 'initialized' check you mentioned

Err, I mean if dd == (DeviceDisk{}). We want to check if the value that dd points to is the DeviceDisk zero value.

-NR

_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel

#27 lore raw

Re: [Xen-devel] [PATCH v3 8/8] RFC: Sketch constructors, DomainCreateNew

In reply to Nick Rosbrook
Quoted 25 lines · Nick Rosbrook
Quoted 9 lines

I think marshaling and unmarshalling should be fine, *as long as* the structure being unmarshalled actually went through the libxl_<type>_init() function first.

In fact, I was kicking around the idea of adding a non-exported field to all the generated structs -- maybe "bool initalized" -- and having the .fromC() methods set this to 'true', and the .toC() methods return an error if it wasn't set. But then we'd need to write custom JSON marshallers to handle these.

I *think* to guarantee that libxl_<type>_init() has been called when unmarshaling, we would need to generate UnmarshalJSON functions to implement json.Unmarshaler. E.g.,:

func (dd *DeviceDisk) UnmarshalJSON(data []byte) error {
        if dd == nil { // Or maybe this is the 'initialized' check you mentioned
                dd, err := NewDeviceDisk()
                if err != nil {
                        return err
                }
        }

        return json.Unmarshal(data, dd)
}
Quoted 2 lines

AFAICT, this would be required for someone to unmarshal a complete domain configuration in one go.

So the above will fix an issue like this:

Scenario A
1. Make a structure from version V by calling NewType()
2. Fill in what you want
3. Marshal it into json
4. Marshal it out of json into a structure from version V+1, with new fields

With code as above, the new elements of structure V+1 will be initialized by the NewType() in the UnmarshalJSON() method.

But the problem I'm worried about is this:

Scenario B
1. Make an empty, uninitialized structure, without calling NewType()
2. Fill in some fields
3. Marshal it into json
4. Marshal it out of json (with the same version)

In the case above, step 3 encodes all the known fields with *golang*'s zero values, rather than libxl's default values, and so step 4 will clobber any defaults written by NewType() with golang zero values again.

Of course, something like scenario A might happen without the marshal / unmarshal, which is why I thought having a private 'initialized' flag might be helpful. But then what you'd want to solve B by having the unmarshaller read the initialized flag and add it to the json / read it from the json (since the json package itself can't do it).

(Naturally people can directly modify the json to have the 'initialized' flag set, but if you get to that level of messing around, you get to keep all the pieces if it breaks.)

Quoted 10 lines
Quoted 9 lines

As far as further steps -- do you have a clear idea what kind of functionality you'd like to see possible by the time of the feature freeze (probably in May)? Do you have plans to use these bindings yourself, and if so, how?

For my part, I want to start and reap guests. The latter will require adding event callback functionality which will require more thought (and perhaps expose more libxl issues). But I don't yet have a clear target beyond that.

Quoted 7 lines

Yes, I plan on using these bindings in redctl (our Redfield toolstack) [1], to replace our os/exec calls to xl. To fully make that transition, we would need domain start/stop, PCI and network attach/detach, as well as some utilities (most of which are either implemented, or would be easy to do). But, making that transition is relatively low on the priority list right now, so I can't commit to a timeline unfortunately.

Sure, nor I; but having a goal always helps, even if it's only best-effort.

Looking at redctl, it seems like actually a pretty full-featured toolstack -- that seems like a nice complete target to aim at. :-)

Quoted 9 lines
Quoted 2 lines

Re function calls -- do we want to just manually duplicate them as needed, or try to get some sort of IDL support?

I think it will make more sense to manually duplicate them as needed. That way, we can be more particular about function signatures etc. to ensure they are idiomatic Go. Also, I am of the opinion that a minimal API is a better place to start. Which brings me to another question and potential work item:

Quoted 3 lines

Do we want to re-evaluate what is currently implemented in the API? Do you have plans to use everything that is currently there? If not, it might be nice to trim off things we don't need right now.

I think we should make sure that things actually work. The very original golang bindings I wrote to be able to control cpupools, so I think those functions should stay. But I'm not sure if anyone's ever used ConsoleGetTty. Like xl.cfg parsing, it's the sort of thing that *somebody* will probably want eventually; so I'm inclined to say it would be less cost to just test it and make sure it works than to remove it and re-add it when someone decides they need it.

Did you have anything in particular in mind?

I was sort of thinking what we might do is leave xenlight as mostly just a plain wrapper around the libxl C functions, as close to what might be generated as possible; and then have another package that would do something more useful. For instance, having 'Vm' struct, which could be Start()ed, shut down, and so on; and which would keep track of if/when the domain died, &c.

Quoted 5 lines
Quoted 5 lines

Other work items include:

* modifying configure to detect the availability of go and enable the bindings if it's available

Quoted 8 lines
Quoted 4 lines

* Enabling go build testing in the gitlab CI loop

* Making go get work, which might involve having code to push post-generated code to a repo and tagging as appropriate

I was going to ask about this. You had a vanity URL in place at one point, right? Did go get ever work with that? In any case, pushing to another repo might be desirable.

We never actually had a URL in place, no. I had simply chosen the URL based on what would be a good combination of easy to type/remember and easy to set up effectively. (This was after having an informal chat with Ian Jackson, who tends to do most of this sort of technical admin thing.) We'd probably want to go back and figure out what kind of "interface" is possible, how to do versioning &c, and then work backwards from that to get a workflow from the various Xen branches into that.

BTW do you guys have a solution to the "install new tools then reboot" issue? I guess if you have a daemon then it will retain the old version of the library until after you reboot?

-George

_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel

#28 lore raw

Re: [Xen-devel] [PATCH v3 8/8] RFC: Sketch constructors, DomainCreateNew

Quoted 11 lines

But the problem I'm worried about is this:

Scenario B
1. Make an empty, uninitialized structure, without calling NewType()
2. Fill in some fields
3. Marshal it into json
4. Marshal it out of json (with the same version)

In the case above, step 3 encodes all the known fields with *golang*'s zero values, rather than libxl's default values, and so step 4 will clobber any defaults written by NewType() with golang zero values again.

One way to solve this would be add struct tags to generated types that tell JSON to omit zero values when marshaling. I.e., json:",omitempty". Then, only fields that were actually set will be marshaled. And, for Unmarshal to overwrite a field set by NewType(), it would have to be *explicitly* set by a user. But, that does mean if a field is set, and happens to be a Go zero value, it will not be shown in the JSON. That could be a problem itself.

Quoted 18 lines
Quoted 10 lines
Quoted 9 lines

As far as further steps -- do you have a clear idea what kind of functionality you'd like to see possible by the time of the feature freeze (probably in May)? Do you have plans to use these bindings yourself, and if so, how?

For my part, I want to start and reap guests. The latter will require adding event callback functionality which will require more thought (and perhaps expose more libxl issues). But I don't yet have a clear target beyond that.

Quoted 7 lines

Yes, I plan on using these bindings in redctl (our Redfield toolstack) [1], to replace our os/exec calls to xl. To fully make that transition, we would need domain start/stop, PCI and network attach/detach, as well as some utilities (most of which are either implemented, or would be easy to do). But, making that transition is relatively low on the priority list right now, so I can't commit to a timeline unfortunately.

Quoted 4 lines

Sure, nor I; but having a goal always helps, even if it's only best-effort.

Looking at redctl, it seems like actually a pretty full-featured toolstack -- that seems like a nice complete target to aim at. :-)

Sounds like a plan to me. :)

Quoted 9 lines

I think we should make sure that things actually work. The very original golang bindings I wrote to be able to control cpupools, so I think those functions should stay. But I'm not sure if anyone's ever used ConsoleGetTty. Like xl.cfg parsing, it's the sort of thing that *somebody* will probably want eventually; so I'm inclined to say it would be less cost to just test it and make sure it works than to remove it and re-add it when someone decides they need it.

Did you have anything in particular in mind?

Okay, that's good to know. I don't have anything particular in mind, I just wanted to pose the question. Since I wasn't around when you first wrote the bindings, I wasn't aware of the motivations.

Quoted 6 lines

I was sort of thinking what we might do is leave xenlight as mostly just a plain wrapper around the libxl C functions, as close to what might be generated as possible; and then have another package that would do something more useful. For instance, having 'Vm' struct, which could be Start()ed, shut down, and so on; and which would keep track of if/when the domain died, &c.

That's a good point, it might be nice to create an API that is more "Go-like" and not as tied to libxl semantically speaking.

Quoted 11 lines
Quoted 3 lines

I was going to ask about this. You had a vanity URL in place at one point, right? Did go get ever work with that? In any case, pushing to another repo might be desirable.

We never actually had a URL in place, no. I had simply chosen the URL based on what would be a good combination of easy to type/remember and easy to set up effectively. (This was after having an informal chat with Ian Jackson, who tends to do most of this sort of technical admin thing.) We'd probably want to go back and figure out what kind of "interface" is possible, how to do versioning &c, and then work backwards from that to get a workflow from the various Xen branches into that.

What do you mean by "figure out what kind of interface is possible"? For versioning, I think it would be nice to adopt Go modules and follow their semantic versioning recommendations. Have you considered that route, or any others?

Quoted 3 lines

BTW do you guys have a solution to the "install new tools then reboot" issue? I guess if you have a daemon then it will retain the old version of the library until after you reboot?

At the moment, we don't have a solution to that problem as we're simply calling xl via os/exec. But yes, when we integrate xenlight into redctl the daemon will retain the old version until reboot.

Thanks,
-NR

_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel

#29 lore raw
In reply to George Dunlap
Quoted 8 lines · George Dunlap

The current fromC array code will do the "magic" casting and martialling even when num_foo variable is 0. Go crashes when doing the cast.

Only do array marshalling if the number of elements is non-zero; otherwise, leave the target pointer empty (nil for Go slices, NULL for C arrays).

Quoted 5 lines

---
v2:
- Remove toC part of this, which has been folded into Nick's patch series.

Er, obviously the subject line should say "v2", for the whole series. :-/

-George

_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel

#30 lore raw
In reply to George Dunlap

Sorry I didn't catch this the first time around, but:

Quoted 6 lines
tools/golang/xenlight/helpers.gen.go +0 -0
index b9a7e828a0..889807d928 100644
@@ -623,12 +623,14 @@ func (x *SchedParams) toC(xc *C.libxl_sched_params) (err error) {
 

tools/golang/xenlight/helpers.gen.go func (x *SchedParams) toC(xc *C.libxl_sched_params) (err error) { · line 627

Quoted 10 lines
tools/golang/xenlight/helpers.gen.go +2 -6
 func (x *VcpuSchedParams) fromC(xc *C.libxl_vcpu_sched_params) error {
        x.Sched = Scheduler(xc.sched)
-       numVcpus := int(xc.num_vcpus)
-       cVcpus := (*[1 << 28]C.libxl_sched_params)(unsafe.Pointer(xc.vcpus))[:numVcpus:numVcpus]
-       x.Vcpus = make([]SchedParams, numVcpus)
-       for i, v := range cVcpus {
-               if err := x.Vcpus[i].fromC(&v); err != nil {
-                       return err
+       x.Vcpus = nil
+       if numVcpus := int(xc.num_vcpus); numVcpus > 0 {

Since numX is now scoped to this if block, we could probably just use n or similar and then drop golenvar from xenlight_golang_array_fromC. It would remove some pretty ugly variable names from the generated code :)

-NR

_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel

#31 lore raw
Quoted 8 lines · Nick Rosbrook

Sorry I didn't catch this the first time around, but:

Quoted 6 lines
tools/golang/xenlight/helpers.gen.go +0 -0
index b9a7e828a0..889807d928 100644
@@ -623,12 +623,14 @@ func (x *SchedParams) toC(xc *C.libxl_sched_params) (err error) {
 
Quoted 16 lines

tools/golang/xenlight/helpers.gen.go func (x *SchedParams) toC(xc *C.libxl_sched_params) (err error) { · line 627

Quoted 10 lines
tools/golang/xenlight/helpers.gen.go +2 -6
 func (x *VcpuSchedParams) fromC(xc *C.libxl_vcpu_sched_params) error {
        x.Sched = Scheduler(xc.sched)
-       numVcpus := int(xc.num_vcpus)
-       cVcpus := (*[1 << 28]C.libxl_sched_params)(unsafe.Pointer(xc.vcpus))[:numVcpus:numVcpus]
-       x.Vcpus = make([]SchedParams, numVcpus)
-       for i, v := range cVcpus {
-               if err := x.Vcpus[i].fromC(&v); err != nil {
-                       return err
+       x.Vcpus = nil
+       if numVcpus := int(xc.num_vcpus); numVcpus > 0 {

Since numX is now scoped to this if block, we could probably just use n or similar and then drop golenvar from xenlight_golang_array_fromC. It would remove some pretty ugly variable names from the generated code :)

Yes, that looks good.

-George

_______________________________________________
Xen-devel mailing list
[email protected]
https://lists.xenproject.org/mailman/listinfo/xen-devel