Skip to content

Default Kernel

penvm.kernels.default.client

Client-side interface to access the "default" kernel operations.

See penvm.kernels.default.server.

KernelClient

Bases: _KernelClient

Additional kernel ops.

Source code in penvm/src/kernels/penvm/kernels/default/client.py
 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
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
class KernelClient(_KernelClient):
    """Additional kernel ops."""

    name = "default"

    def __init__(self, session):
        super().__init__(session)

    def file_copyto(self, lpath, rpath, blksize=1024):
        """Copy local file to remote."""
        lpp = Path(lpath)
        if not lpp.exists():
            # TODO: what to do?
            return

        try:
            with open(lpath, "rb") as f:
                count = 0
                start = 0
                while True:
                    req = Request("file-put")
                    req.payload["path"] = rpath
                    req.payload["start"] = start
                    data = req.payload["data"] = f.read(blksize)
                    self.session.put_request(req)

                    self.session.put_request(Request("omq-pop"))
                    if data == b"":
                        break
                    start + len(data)
                    count += 1

            for i in range(count):
                resp = self.imq.pop()
                if resp.payload.get("-status") == "error":
                    raise Exception(f"expected {count} responses got error on {i}")
        except Exception as e:
            # TODO: what to do here?
            self.logger.debug("failed ({e})")

    def file_copyfrom(self, rpath, lpath, blksize=1024):
        """Copy remote file to local."""
        pass

    def file_get_block(self, filename, start=None, size=None):
        """See [penvm.kernels.default.server.FileGetBlock][]."""
        d = {
            "path": filename,
        }
        if start != None:
            d["start"] = start
        if size != None:
            d["size"] = size
        return self.session.newput_request("file-get-block", d)

    def file_get_status(self, path):
        """See [penvm.kernels.default.server.FileGetStatus][]."""
        d = {
            "path": path,
        }
        return self.session.newput_request("file-get-status", d)

    def file_list(self, path, pattern=None, sort=None, split=None):
        """See [penvm.kernels.default.server.FileList][]."""
        d = {
            "path": path,
        }
        if pattern != None:
            d["pattern"] = pattern
        if sort != None:
            d["sort"] = sort
        if split != None:
            d["split"] = split
        return self.session.newput_request("file-list", d)

    def file_put_block(self, path, data, start=None, size=None, truncate=None):
        """See [penvm.kernels.default.server.FilePutBlock][]."""
        d = {
            "path": path,
            "data": data,
        }
        if start != None:
            d["start"] = start
        if size != None:
            d["size"] = size
        if truncate != None:
            d["truncate"] = truncate
        return self.session.newput_request("file-put-block", d)

    def file_set_status(self, path, uid=None, gid=None, user=None, group=None, mode=None):
        """See [penvm.kernels.default.server.FileSetStatus][]."""
        d = {
            "path": path,
            "uid": uid,
            "gid": gid,
            "user": user,
            "group": group,
            "mode": mode,
        }
        return self.session.newput_request("file-set-status", d)

    def run_exec(
        self,
        path,
        args,
        capture_output=False,
        text=True,
        env=None,
        cwd=None,
        path_key=None,
    ):
        """See [penvm.kernels.default.server.RunExec][]."""
        d = {
            "args": [str(arg) for arg in args],
            "capture-output": capture_output,
            "text": text,
        }
        if path != None:
            d["path"] = path
        elif path_key != None:
            d["path-key"] = path_key
        if env != None:
            d["env"] = env
        if cwd != None:
            d["cwd"] = cwd
        return self.session.newput_request("run-exec", d)

    def run_exec_stream(
        self,
        path,
        args,
        capture_output=False,
        text=True,
        env=None,
        wd=None,
        path_key=None,
    ):
        """See [penvm.kernels.default.server.RunExecStream][]."""
        d = {
            "args": [str(arg) for arg in args],
            "capture-output": capture_output,
            "text": text,
        }
        if path != None:
            d["path"] = path
        elif path_key != None:
            d["path-key"] = path_key
        if env != None:
            d["env"] = env
        if wd != None:
            d["wd"] = wd
        return self.session.newput_request("run-exec-stream", d)

    def run_python(self, code, args=None, kwargs=None, _globals=None, _locals=None):
        """See [penvm.kernels.default.server.RunPython][]."""
        _locals = copy.deepcopy(_locals) if _locals != None else {}
        _locals["__penvm__"] = True
        d = {
            "code": code,
        }
        if args != None:
            d["args"] = args
        if kwargs != None:
            d["kwargs"] = kwargs
        if _locals != None:
            d["locals"] = _locals
        if _globals != None:
            d["globals"] = _globals
        return self.session.newput_request("run-python", d)

    def run_python_function(self, code, fnname, args=None, kwargs=None):
        """See [penvm.kernels.default.server.RunPythonFunction][]."""
        d = {
            "args": args,
            "code": code,
            "fn-name": fnname,
            "kwargs": kwargs,
        }
        return self.session.newput_request("run-python-function", d)

    def store_drop(self, name):
        """See [penvm.kernels.default.server.StoreDrop][]."""
        d = {
            "name": name,
        }
        return self.session.newput_request("store-drop", d)

    def store_get(self, name):
        """See [penvm.kernels.default.server.StoreGet][]."""
        d = {
            "name": name,
        }
        return self.session.newput_request("store-get", d)

    def store_get_state(self):
        """See [penvm.kernels.default.server.StoreGetState][]."""
        return self.session.newput_request("store-get-state")

    def store_list(self, pattern=None):
        """See [penvm.kernels.default.server.StoreList][]."""
        d = {}
        if pattern:
            d["pattern"] = pattern
        return self.session.newput_request("store-list", d)

    def store_pop(self, name):
        """See [penvm.kernels.default.server.StorePop][]."""
        d = {
            "name": name,
        }
        return self.session.newput_request("store-pop", d)

    def store_put(self, name, data):
        """See [penvm.kernels.default.server.StorePut][]."""
        d = {
            "name": name,
            "data": data,
        }
        return self.session.newput_request("store-put", d)

file_copyfrom(rpath, lpath, blksize=1024)

Copy remote file to local.

Source code in penvm/src/kernels/penvm/kernels/default/client.py
75
76
77
def file_copyfrom(self, rpath, lpath, blksize=1024):
    """Copy remote file to local."""
    pass

file_copyto(lpath, rpath, blksize=1024)

Copy local file to remote.

Source code in penvm/src/kernels/penvm/kernels/default/client.py
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
def file_copyto(self, lpath, rpath, blksize=1024):
    """Copy local file to remote."""
    lpp = Path(lpath)
    if not lpp.exists():
        # TODO: what to do?
        return

    try:
        with open(lpath, "rb") as f:
            count = 0
            start = 0
            while True:
                req = Request("file-put")
                req.payload["path"] = rpath
                req.payload["start"] = start
                data = req.payload["data"] = f.read(blksize)
                self.session.put_request(req)

                self.session.put_request(Request("omq-pop"))
                if data == b"":
                    break
                start + len(data)
                count += 1

        for i in range(count):
            resp = self.imq.pop()
            if resp.payload.get("-status") == "error":
                raise Exception(f"expected {count} responses got error on {i}")
    except Exception as e:
        # TODO: what to do here?
        self.logger.debug("failed ({e})")

file_get_block(filename, start=None, size=None)

See penvm.kernels.default.server.FileGetBlock.

Source code in penvm/src/kernels/penvm/kernels/default/client.py
79
80
81
82
83
84
85
86
87
88
def file_get_block(self, filename, start=None, size=None):
    """See [penvm.kernels.default.server.FileGetBlock][]."""
    d = {
        "path": filename,
    }
    if start != None:
        d["start"] = start
    if size != None:
        d["size"] = size
    return self.session.newput_request("file-get-block", d)

file_get_status(path)

See penvm.kernels.default.server.FileGetStatus.

Source code in penvm/src/kernels/penvm/kernels/default/client.py
90
91
92
93
94
95
def file_get_status(self, path):
    """See [penvm.kernels.default.server.FileGetStatus][]."""
    d = {
        "path": path,
    }
    return self.session.newput_request("file-get-status", d)

file_list(path, pattern=None, sort=None, split=None)

See penvm.kernels.default.server.FileList.

Source code in penvm/src/kernels/penvm/kernels/default/client.py
 97
 98
 99
100
101
102
103
104
105
106
107
108
def file_list(self, path, pattern=None, sort=None, split=None):
    """See [penvm.kernels.default.server.FileList][]."""
    d = {
        "path": path,
    }
    if pattern != None:
        d["pattern"] = pattern
    if sort != None:
        d["sort"] = sort
    if split != None:
        d["split"] = split
    return self.session.newput_request("file-list", d)

file_put_block(path, data, start=None, size=None, truncate=None)

See penvm.kernels.default.server.FilePutBlock.

Source code in penvm/src/kernels/penvm/kernels/default/client.py
110
111
112
113
114
115
116
117
118
119
120
121
122
def file_put_block(self, path, data, start=None, size=None, truncate=None):
    """See [penvm.kernels.default.server.FilePutBlock][]."""
    d = {
        "path": path,
        "data": data,
    }
    if start != None:
        d["start"] = start
    if size != None:
        d["size"] = size
    if truncate != None:
        d["truncate"] = truncate
    return self.session.newput_request("file-put-block", d)

file_set_status(path, uid=None, gid=None, user=None, group=None, mode=None)

See penvm.kernels.default.server.FileSetStatus.

Source code in penvm/src/kernels/penvm/kernels/default/client.py
124
125
126
127
128
129
130
131
132
133
134
def file_set_status(self, path, uid=None, gid=None, user=None, group=None, mode=None):
    """See [penvm.kernels.default.server.FileSetStatus][]."""
    d = {
        "path": path,
        "uid": uid,
        "gid": gid,
        "user": user,
        "group": group,
        "mode": mode,
    }
    return self.session.newput_request("file-set-status", d)

run_exec(path, args, capture_output=False, text=True, env=None, cwd=None, path_key=None)

See penvm.kernels.default.server.RunExec.

Source code in penvm/src/kernels/penvm/kernels/default/client.py
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
def run_exec(
    self,
    path,
    args,
    capture_output=False,
    text=True,
    env=None,
    cwd=None,
    path_key=None,
):
    """See [penvm.kernels.default.server.RunExec][]."""
    d = {
        "args": [str(arg) for arg in args],
        "capture-output": capture_output,
        "text": text,
    }
    if path != None:
        d["path"] = path
    elif path_key != None:
        d["path-key"] = path_key
    if env != None:
        d["env"] = env
    if cwd != None:
        d["cwd"] = cwd
    return self.session.newput_request("run-exec", d)

run_exec_stream(path, args, capture_output=False, text=True, env=None, wd=None, path_key=None)

See penvm.kernels.default.server.RunExecStream.

Source code in penvm/src/kernels/penvm/kernels/default/client.py
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
def run_exec_stream(
    self,
    path,
    args,
    capture_output=False,
    text=True,
    env=None,
    wd=None,
    path_key=None,
):
    """See [penvm.kernels.default.server.RunExecStream][]."""
    d = {
        "args": [str(arg) for arg in args],
        "capture-output": capture_output,
        "text": text,
    }
    if path != None:
        d["path"] = path
    elif path_key != None:
        d["path-key"] = path_key
    if env != None:
        d["env"] = env
    if wd != None:
        d["wd"] = wd
    return self.session.newput_request("run-exec-stream", d)

run_python(code, args=None, kwargs=None, _globals=None, _locals=None)

See penvm.kernels.default.server.RunPython.

Source code in penvm/src/kernels/penvm/kernels/default/client.py
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
def run_python(self, code, args=None, kwargs=None, _globals=None, _locals=None):
    """See [penvm.kernels.default.server.RunPython][]."""
    _locals = copy.deepcopy(_locals) if _locals != None else {}
    _locals["__penvm__"] = True
    d = {
        "code": code,
    }
    if args != None:
        d["args"] = args
    if kwargs != None:
        d["kwargs"] = kwargs
    if _locals != None:
        d["locals"] = _locals
    if _globals != None:
        d["globals"] = _globals
    return self.session.newput_request("run-python", d)

run_python_function(code, fnname, args=None, kwargs=None)

See penvm.kernels.default.server.RunPythonFunction.

Source code in penvm/src/kernels/penvm/kernels/default/client.py
205
206
207
208
209
210
211
212
213
def run_python_function(self, code, fnname, args=None, kwargs=None):
    """See [penvm.kernels.default.server.RunPythonFunction][]."""
    d = {
        "args": args,
        "code": code,
        "fn-name": fnname,
        "kwargs": kwargs,
    }
    return self.session.newput_request("run-python-function", d)

store_drop(name)

See penvm.kernels.default.server.StoreDrop.

Source code in penvm/src/kernels/penvm/kernels/default/client.py
215
216
217
218
219
220
def store_drop(self, name):
    """See [penvm.kernels.default.server.StoreDrop][]."""
    d = {
        "name": name,
    }
    return self.session.newput_request("store-drop", d)

store_get(name)

See penvm.kernels.default.server.StoreGet.

Source code in penvm/src/kernels/penvm/kernels/default/client.py
222
223
224
225
226
227
def store_get(self, name):
    """See [penvm.kernels.default.server.StoreGet][]."""
    d = {
        "name": name,
    }
    return self.session.newput_request("store-get", d)

store_get_state()

See penvm.kernels.default.server.StoreGetState.

Source code in penvm/src/kernels/penvm/kernels/default/client.py
229
230
231
def store_get_state(self):
    """See [penvm.kernels.default.server.StoreGetState][]."""
    return self.session.newput_request("store-get-state")

store_list(pattern=None)

See penvm.kernels.default.server.StoreList.

Source code in penvm/src/kernels/penvm/kernels/default/client.py
233
234
235
236
237
238
def store_list(self, pattern=None):
    """See [penvm.kernels.default.server.StoreList][]."""
    d = {}
    if pattern:
        d["pattern"] = pattern
    return self.session.newput_request("store-list", d)

store_pop(name)

See penvm.kernels.default.server.StorePop.

Source code in penvm/src/kernels/penvm/kernels/default/client.py
240
241
242
243
244
245
def store_pop(self, name):
    """See [penvm.kernels.default.server.StorePop][]."""
    d = {
        "name": name,
    }
    return self.session.newput_request("store-pop", d)

store_put(name, data)

See penvm.kernels.default.server.StorePut.

Source code in penvm/src/kernels/penvm/kernels/default/client.py
247
248
249
250
251
252
253
def store_put(self, name, data):
    """See [penvm.kernels.default.server.StorePut][]."""
    d = {
        "name": name,
        "data": data,
    }
    return self.session.newput_request("store-put", d)

penvm.kernels.default.server

Server-side "default" kernel operations.

The default operations providing the necessary functionality for many/most use cases including support for: filesystem, kv store, and binary and python code execution.

For an explanation of the Request and Response sections see penvm.kernels.core.server.

FileGetBlock

Bases: Op

Read data (block) from a file object.

Request:

Name Type Description
path str

File path.

size int

Size (in bytes) to read. Defaults to 1024.

start int

Offset from file start. Defaults to 0.

OkResponse:

Name Type Description
data bytes

Bytes (up to size) from file block.

size int

Size (in bytes) read.

start int

Offset from file start.

ErrorResponse:

Name Type Description
-

Error message.

Source code in penvm/src/kernels/penvm/kernels/default/server.py
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
class FileGetBlock(Op):
    """Read data (block) from a file object.

    Attributes: Request:
        path (str): File path.
        size (int): Size (in bytes) to read. Defaults to 1024.
        start (int): Offset from file start. Defaults to 0.

    Attributes: OkResponse:
        data (bytes): Bytes (up to `size`) from file block.
        size (int): Size (in bytes) read.
        start (int): Offset from file start.

    Attributes: ErrorResponse:
        -: Error message.
    """

    def run(self, ctxt, req):
        try:
            payload = req.payload
            path = payload.get("path")
            size = payload.get("size", 1024)
            start = payload.get("start", 0)

            if not path:
                return ErrorResponse(
                    "path not provided",
                    refmsg=req,
                )

            pp = Path(path)
            if not pp.exists():
                return ErrorResponse(
                    f"path ({path}) not found",
                    refmsg=req,
                )

            try:
                f = pp.open("rb")
                f.seek(start)
                return OkResponse(
                    payload=Payload(
                        {"data": f.read(size), "size": size, "start": start},
                    ),
                    refmsg=req,
                )
            except Exception as e:
                return ErrorResponse(
                    f"{e}",
                    refmsg=req,
                )
        except Exception as e:
            self.logger.error(f"{e}")

FileGetStatus

Bases: Op

Get file status (os.stat()).

Request:

Name Type Description
path str

File path to stat.

OkResponse:

Name Type Description
mode int

File mode.

ino int

Inode.

dev int

Device identifier.

nlink int

Number of hard links.

uid int

User id of file owner.

gid int

Group id of file owner.

size int

File size (in bytes).

atime int

Most recent access time (in seconds).

mtime int

Most recent content modication time (in seconds).

ctime int

Most recent metadata change time (in seconds).

ErrorResponse:

Name Type Description
-

Error message.

Source code in penvm/src/kernels/penvm/kernels/default/server.py
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
class FileGetStatus(Op):
    """Get file status (`os.stat()`).

    Attributes: Request:
        path (str): File path to stat.

    Attributes: OkResponse:
        mode (int): File mode.
        ino (int): Inode.
        dev (int): Device identifier.
        nlink (int): Number of hard links.
        uid (int): User id of file owner.
        gid (int): Group id of file owner.
        size (int): File size (in bytes).
        atime (int): Most recent access time (in seconds).
        mtime (int): Most recent content modication time (in seconds).
        ctime (int): Most recent metadata change time (in seconds).

    Attributes: ErrorResponse:
        -: Error message.
    """

    def run(self, ctxt, req):
        try:
            path = req.payload.get("path")
            if path != None:
                return ErrorResponse("path not provided")

            if not os.path.exists(path):
                return ErrorResponse("path not found")

            st = os.stat(path)
            return OkResponse(
                payload={
                    "mode": st.st_mode,
                    "ino": st.st_ino,
                    "dev": st.st_dev,
                    "nlink": st.st_nlink,
                    "uid": st.st_uid,
                    "gid": st.st_gid,
                    "size": st.st_size,
                    "atime": st.st_atime,
                    "mtime": st.st_mtime,
                    "ctime": st.st_ctime,
                },
                refmsg=req,
            )
        except Exception as e:
            self.logger.error(f"{e}")

FileList

Bases: Op

List filenames/dirnames at filesystem path.

Request:

Name Type Description
path str

Directory path.

filter str

Filename filter. Defaults to no filter.

sort bool

Sort names. Defaults to False.

Response:

Name Type Description
names list of str

List of directory entries.

ErrorResponse:

Name Type Description
-

Error message.

Source code in penvm/src/kernels/penvm/kernels/default/server.py
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
class FileList(Op):
    """List filenames/dirnames at filesystem path.

    Attributes: Request:
        path (str): Directory path.
        filter (str): Filename filter. Defaults to no filter.
        sort (bool): Sort names. Defaults to False.

    Attributes: Response:
        names (list of str): List of directory entries.

    Attributes: ErrorResponse:
        -: Error message.
    """

    def run(self, ctxt, req):
        try:
            payload = req.payload
            path = payload.get("path")
            pattern = payload.get("pattern")
            sort = payload.get("sort", False)
            split = payload.get("split", False)

            if not path:
                return ErrorResponse(
                    "path not provided",
                    refmsg=req,
                )

            try:
                if split:
                    if os.path.isdir(path):
                        for root, dirnames, filenames in os.walk(path):
                            break
                    else:
                        root, dirnames, filenames = None, [], [path]

                    if pattern:
                        dirnames = fnmatch.filter(dirnames, pattern)
                        filenames = fnmatch.filter(filenames, pattern)
                    if sort:
                        dirnames.sort()
                        filenames.sort()

                    return OkResponse(
                        payload=Payload(
                            {
                                "dirnames": dirnames,
                                "filenames": filenames,
                            }
                        ),
                        refmsg=req,
                    )
                else:
                    if os.path.isdir(path):
                        names = os.listdir(path)
                    elif os.path.isfile(path):
                        names = [os.path.basename(path)]

                    if pattern:
                        names = fnmatch.filter(names, pattern)
                    if sort:
                        names.sort()

                    return OkResponse(
                        payload=Payload({"names": names}),
                        refmsg=req,
                    )
            except Exception as e:
                return ErrorResponse(
                    f"{e}",
                    refmsg=req,
                )
        except Exception as e:
            self.logger.error(f"{e}")

FilePutBlock

Bases: Op

Write data (block) to a file object.

Request:

Name Type Description
data bytes

Data to store.

path str

File path.

size int

Size (in bytes) of data.

start int

Offset from file start. Defaults to 0.

truncate bool

Flag to indicate truncation of file. Defaults to False.

OkResponse:

Name Type Description
-

Empty.

ErrorResponse:

Name Type Description
-

Error message.

Source code in penvm/src/kernels/penvm/kernels/default/server.py
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
class FilePutBlock(Op):
    """Write data (block) to a file object.

    Attributes: Request:
        data (bytes): Data to store.
        path (str): File path.
        size (int): Size (in bytes) of data.
        start (int): Offset from file start. Defaults to 0.
        truncate (bool): Flag to indicate truncation of file. Defaults
            to False.

    Attributes: OkResponse:
        -: Empty.

    Attributes: ErrorResponse:
        -: Error message.
    """

    def run(self, ctxt, req):
        try:
            payload = req.payload
            data = payload.get("data")
            path = payload.get("path")
            size = payload.get("size", len(data))
            start = payload.get("start", 0)
            truncate = payload.get("truncate", False)

            if not path:
                return ErrorResponse(
                    "path not provided",
                    refmsg=req,
                )
            if not data:
                return ErrorResponse(
                    "data not provided",
                    refmsg=req,
                )

            pp = Path(path)
            if not pp.parent.is_dir():
                return ErrorResponse(
                    f"parent path ({pp.parent.isabsolute()}) does not exist",
                    refmsg=req,
                )

            try:
                with pp.open("wb+") as f:
                    if truncate:
                        # TODO: support truncateat?
                        f.truncate()
                    f.seek(start)
                    if size != None:
                        f.write(data[:size])
                    else:
                        f.write(data)
                    f.close()
                return OkResponse(
                    refmsg=req,
                )
            except Exception as e:
                return ErrorResponse(
                    f"{e}",
                    refmsg=req,
                )
        except Exception as e:
            self.logger.error(f"{e}")

FileSetStatus

Bases: Op

Set file status settings.

Request:

Name Type Description
path str

File object path.

uid int

User id of file owner.

user str

User name of file owner.

gid int

Group id of file owner.

group int

Group name of file owner.

mode int

File mode.

Response:

Name Type Description
-

None.

Source code in penvm/src/kernels/penvm/kernels/default/server.py
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
class FileSetStatus(Op):
    """Set file status settings.

    Attributes: Request:
        path (str): File object path.
        uid (int): User id of file owner.
        user (str): User name of file owner.
        gid (int): Group id of file owner.
        group (int): Group name of file owner.
        mode (int): File mode.

    Attributes: Response:
        -: None.
    """

    def run(self, ctxt, req):
        try:
            payload = req.payload
            path = payload.get("path")
            uid = payload.get("uid")
            user = payload.get("user")
            gid = payload.get("gid")
            group = payload.get("group")
            mode = payload.get("mode")

            if path == None:
                return

            if not os.path.exists(path):
                return

            if user and pwd:
                pw = pwd.getpwnam(user)
                if pw:
                    uid = pw.pw_uid
            if group and grp:
                gr = grp.getgrnam(group)
                if gr:
                    gid = gr.gr_gid

            if uid == None:
                uid = -1
            if gid == None:
                gid = -1

            try:
                if mode != None:
                    os.chmod(path, mode)
            except:
                pass

            try:
                if uid != -1 and gid != -1:
                    os.chown(path, uid, gid)
            except:
                pass
        except Exception as e:
            self.logger.error(f"{e}")

RunExec

Bases: Op

Run a locally available executable via a path with arguments.

Request:

Name Type Description
args list of string

Arguments. Defaults to empty list.

capture_output bool

Capture stdout/stderr. Defaults to True.

env dict|list of strings

Dictionary or list of strings for the environment.

path str

Path of executable. See also path-key.

path-key str

Name of item in file kvstore. See also path.

text bool

Treat output as "text". Otherwise, "binary".

cwd str

Working directory to run under. Defaults to "/".

OkResponse:

Name Type Description
returncode int

Exit/return code

stderr str

stderr output

stdout str

stdout output

Source code in penvm/src/kernels/penvm/kernels/default/server.py
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
class RunExec(Op):
    """Run a locally available executable via a path with arguments.

    Attributes: Request:
        args (list of string): Arguments. Defaults to empty list.
        capture_output (bool): Capture stdout/stderr. Defaults to
            True.
        env (dict|list of strings): Dictionary or list of strings for
            the environment.
        path (str): Path of executable. See also `path-key`.
        path-key (str): Name of item in file kvstore. See also `path`.
        text (bool): Treat output as "text". Otherwise, "binary".
        cwd (str): Working directory to run under. Defaults to "/".

    Attributes: OkResponse:
        returncode (int): Exit/return code
        stderr (str): stderr output
        stdout (str): stdout output
    """

    def run(self, ctxt, req):
        """Run operation."""
        try:
            self.logger.debug("run")

            payload = req.payload

            args = list(payload.get("args", []))
            capture_output = payload.get("capture-output", True)
            env = payload.get("env", None)
            path = payload.get("path")
            path_key = payload.get("path-key")
            text = payload.get("text", False)
            cwd = payload.get("cwd", "/")

            self.logger.debug(f"path {path} path-key {path_key}")
            if path == None:
                path = ctxt.machine.fkvstore.get_path(path_key)
                # TODO: make it executable in a different call?
                os.chmod(path, 0o700)

            if None in [path]:
                return ErrorResponse(
                    "path not provided",
                    refmsg=req,
                )
            elif not os.path.exists(path):
                _path = shutil.which(path)
                if _path == None:
                    return ErrorResponse(
                        f"file ({path}) not found",
                        refmsg=req,
                    )
                path = _path

            kwargs = {
                "capture_output": capture_output,
                "cwd": cwd,
                "text": text,
            }
            if env:
                kwargs["env"] = env

            cp = subprocess.run(
                [path] + args,
                **kwargs,
            )
            return OkResponse(
                payload=Payload(
                    {
                        "stdout": cp.stdout,
                        "stderr": cp.stderr,
                        "returncode": cp.returncode,
                    }
                ),
                refmsg=req,
            )
        except Exception as e:
            return ErrorResponse(
                f"{e}",
                refmsg=req,
            )

run(ctxt, req)

Run operation.

Source code in penvm/src/kernels/penvm/kernels/default/server.py
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
def run(self, ctxt, req):
    """Run operation."""
    try:
        self.logger.debug("run")

        payload = req.payload

        args = list(payload.get("args", []))
        capture_output = payload.get("capture-output", True)
        env = payload.get("env", None)
        path = payload.get("path")
        path_key = payload.get("path-key")
        text = payload.get("text", False)
        cwd = payload.get("cwd", "/")

        self.logger.debug(f"path {path} path-key {path_key}")
        if path == None:
            path = ctxt.machine.fkvstore.get_path(path_key)
            # TODO: make it executable in a different call?
            os.chmod(path, 0o700)

        if None in [path]:
            return ErrorResponse(
                "path not provided",
                refmsg=req,
            )
        elif not os.path.exists(path):
            _path = shutil.which(path)
            if _path == None:
                return ErrorResponse(
                    f"file ({path}) not found",
                    refmsg=req,
                )
            path = _path

        kwargs = {
            "capture_output": capture_output,
            "cwd": cwd,
            "text": text,
        }
        if env:
            kwargs["env"] = env

        cp = subprocess.run(
            [path] + args,
            **kwargs,
        )
        return OkResponse(
            payload=Payload(
                {
                    "stdout": cp.stdout,
                    "stderr": cp.stderr,
                    "returncode": cp.returncode,
                }
            ),
            refmsg=req,
        )
    except Exception as e:
        return ErrorResponse(
            f"{e}",
            refmsg=req,
        )

RunExecStream

Bases: Op

Run a locally available executable via a path with arguments with streaming capability.

Whereas RunExec runs the executable, waits for it to complete, then collects and returns the stdout, stderr, and returncode, RunExecStream streams partial results over the lifetime of the operation. As such, an undetermined number of responses are collected and returned. When the operation completes, a final message will contain a returncode != None. The requester must perform queue management (e.g., session-pop-omq at the server, and consume the messages at the client side).

Note

stdin is not supported.

Request:

Name Type Description
args list of string

Arguments. Defaults to empty list.

capture_output bool

Capture stdout/stderr. Defaults to True.

env bool

(dict|list of strings): Dictionary or list of strings for the environment.

path str

Path of executable. See also path-key.

path-key str

Name of item in file kvstore. See also path.

text bool

Treat output as "text". Otherwise, "binary".

cwd str

Working directory to run under. Defaults to "/".

OkResponse:

Name Type Description
returncode int | None

Exit/return code. Last response sends returncode != None.

stderr str

stderr output.

stdout str

stdout output.

Source code in penvm/src/kernels/penvm/kernels/default/server.py
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
class RunExecStream(Op):
    """Run a locally available executable via a path with arguments
    with streaming capability.

    Whereas `RunExec` runs the executable, waits for it to complete,
    then collects and returns the `stdout`, `stderr`, and
    `returncode`, `RunExecStream` streams partial results over the
    lifetime of the operation. As such, an undetermined number of
    responses are collected and returned. When the operation
    completes, a final message will contain a `returncode` != `None`.
    The requester must perform queue management (e.g.,
    `session-pop-omq` at the server, and consume the messages at the
    client side).

    Note:
        `stdin` is not supported.

    Attributes: Request:
        args (list of string): Arguments. Defaults to empty list.
        capture_output (bool): Capture stdout/stderr. Defaults to
            True.
        env: (dict|list of strings): Dictionary or list of strings for
            the environment.
        path (str): Path of executable. See also `path-key`.
        path-key (str): Name of item in file kvstore. See also `path`.
        text (bool): Treat output as "text". Otherwise, "binary".
        cwd (str): Working directory to run under. Defaults to "/".

    Attributes: OkResponse:
        returncode (int|None): Exit/return code. Last response sends
            `returncode` != `None`.
        stderr (str): `stderr` output.
        stdout (str): `stdout` output.
    """

    def run(self, ctxt, req):
        """Run operation."""
        try:
            self.logger.debug("run")

            payload = req.payload

            args = list(payload.get("args", []))
            capture_output = payload.get("capture-output", True)
            env = payload.get("env", None)
            path = payload.get("path")
            path_key = payload.get("path-key")
            text = payload.get("text", False)
            cwd = payload.get("cwd", "/")

            self.logger.debug(f"path {path} path-key {path_key}")
            if path == None:
                path = ctxt.machine.fkvstore.get_path(path_key)
                # TODO: make it executable in a different call?
                os.chmod(path, 0o700)

            if None in [path]:
                return ErrorResponse(
                    "path not provided",
                    refmsg=req,
                )
            elif not os.path.exists(path):
                return ErrorResponse(
                    f"file ({path}) not found",
                    refmsg=req,
                )
            else:
                kwargs = {
                    "cwd": cwd,
                    "text": text,
                }
                if capture_output:
                    kwargs["stdout"] = subprocess.PIPE
                    kwargs["stderr"] = subprocess.PIPE
                if env:
                    kwargs["env"] = env

                if 0:
                    # no buffering, allows short reads
                    kwargs["bufsize"] = 0
                if 1:
                    # line buffered
                    kwargs["bufsize"] = 1

                try:
                    sp = subprocess.Popen(
                        [path] + args,
                        **kwargs,
                    )

                    POLLIN = select.POLLIN
                    POLLOUT = select.POLLOUT
                    POLLHEN = select.POLLHUP | select.POLLERR | select.POLLNVAL

                    stdout_fd = sp.stdout.fileno()
                    stderr_fd = sp.stderr.fileno()

                    poll = select.poll()
                    poll.register(stdout_fd, select.POLLIN)
                    poll.register(stderr_fd, select.POLLIN)

                    self.logger.debug(f"{sp.stdout=} {sp.stdout.line_buffering=} {sp.stderr=}")
                    sp.stdout.reconfigure(line_buffering=True)
                    sp.stderr.reconfigure(line_buffering=True)

                    self.logger.debug(f"starting ...")

                    nfds = 2
                    while nfds:
                        populated = False
                        resp = OkResponse(
                            refmsg=req,
                        )
                        for fd, event in poll.poll():
                            self.logger.debug(f"{fd=} {event=}")
                            if event & POLLIN:
                                if fd == stdout_fd:
                                    populated = True
                                    resp.payload["stdout"] = sp.stdout.read(128)
                                else:
                                    # assume stderr
                                    populated = True
                                    resp.payload["stderr"] = sp.stderr.read(128)
                            if event & POLLHEN:
                                poll.unregister(fd)
                                nfds -= 1
                        if populated:
                            ctxt.session.omq.put(resp)

                    sp.wait()
                    self.logger.debug(f"final")
                    resp = OkResponse(
                        refmsg=req,
                    )
                    resp.payload["returncode"] = sp.returncode
                    return resp
                except Exception as e:
                    # TODO: cleanup? kill?
                    sp.kill()
                    raise
        except Exception as e:
            self.logger.error(f"{e}")
            return ErrorResponse(
                f"{e}",
                refmsg=req,
            )

run(ctxt, req)

Run operation.

Source code in penvm/src/kernels/penvm/kernels/default/server.py
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
def run(self, ctxt, req):
    """Run operation."""
    try:
        self.logger.debug("run")

        payload = req.payload

        args = list(payload.get("args", []))
        capture_output = payload.get("capture-output", True)
        env = payload.get("env", None)
        path = payload.get("path")
        path_key = payload.get("path-key")
        text = payload.get("text", False)
        cwd = payload.get("cwd", "/")

        self.logger.debug(f"path {path} path-key {path_key}")
        if path == None:
            path = ctxt.machine.fkvstore.get_path(path_key)
            # TODO: make it executable in a different call?
            os.chmod(path, 0o700)

        if None in [path]:
            return ErrorResponse(
                "path not provided",
                refmsg=req,
            )
        elif not os.path.exists(path):
            return ErrorResponse(
                f"file ({path}) not found",
                refmsg=req,
            )
        else:
            kwargs = {
                "cwd": cwd,
                "text": text,
            }
            if capture_output:
                kwargs["stdout"] = subprocess.PIPE
                kwargs["stderr"] = subprocess.PIPE
            if env:
                kwargs["env"] = env

            if 0:
                # no buffering, allows short reads
                kwargs["bufsize"] = 0
            if 1:
                # line buffered
                kwargs["bufsize"] = 1

            try:
                sp = subprocess.Popen(
                    [path] + args,
                    **kwargs,
                )

                POLLIN = select.POLLIN
                POLLOUT = select.POLLOUT
                POLLHEN = select.POLLHUP | select.POLLERR | select.POLLNVAL

                stdout_fd = sp.stdout.fileno()
                stderr_fd = sp.stderr.fileno()

                poll = select.poll()
                poll.register(stdout_fd, select.POLLIN)
                poll.register(stderr_fd, select.POLLIN)

                self.logger.debug(f"{sp.stdout=} {sp.stdout.line_buffering=} {sp.stderr=}")
                sp.stdout.reconfigure(line_buffering=True)
                sp.stderr.reconfigure(line_buffering=True)

                self.logger.debug(f"starting ...")

                nfds = 2
                while nfds:
                    populated = False
                    resp = OkResponse(
                        refmsg=req,
                    )
                    for fd, event in poll.poll():
                        self.logger.debug(f"{fd=} {event=}")
                        if event & POLLIN:
                            if fd == stdout_fd:
                                populated = True
                                resp.payload["stdout"] = sp.stdout.read(128)
                            else:
                                # assume stderr
                                populated = True
                                resp.payload["stderr"] = sp.stderr.read(128)
                        if event & POLLHEN:
                            poll.unregister(fd)
                            nfds -= 1
                    if populated:
                        ctxt.session.omq.put(resp)

                sp.wait()
                self.logger.debug(f"final")
                resp = OkResponse(
                    refmsg=req,
                )
                resp.payload["returncode"] = sp.returncode
                return resp
            except Exception as e:
                # TODO: cleanup? kill?
                sp.kill()
                raise
    except Exception as e:
        self.logger.error(f"{e}")
        return ErrorResponse(
            f"{e}",
            refmsg=req,
        )

RunPython

Bases: Op

Run python code snippet with typed args and typed kwargs.

The code is executed in a thread of the machine.

Danger

Running in the machine process can cause problems.

See penvm.kernels.default.server.RunExec.

Request:

Name Type Description
args typed list

Arguments.

code str

Code snippet.

globals typed dict

Dictionary of "globals" to use. Defaults to current "globals".

kwargs typed dict

Keyword arguments.

locals typed dict

Dictionary of "locals" to use. Defaults to empty dict.

path-key str

Path of code snippet in file kvstore. See also code.

Response:

Name Type Description
return-value typed value

Taken from returnvalue in locals.

Source code in penvm/src/kernels/penvm/kernels/default/server.py
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
class RunPython(Op):
    """Run python code snippet with typed args and typed kwargs.

    The code is executed in a thread of the `machine`.

    Danger:
        Running in the machine process can cause problems.

    See [penvm.kernels.default.server.RunExec][].

    Attributes: Request:
        args (typed list): Arguments.
        code (str): Code snippet.
        globals (typed dict): Dictionary of "globals" to use. Defaults
            to current "globals".
        kwargs (typed dict): Keyword arguments.
        locals (typed dict): Dictionary of "locals" to use. Defaults
            to empty dict.
        path-key (str): Path of code snippet in file kvstore. See also
            `code`.

    Attributes: Response:
        return-value (typed value): Taken from `returnvalue` in locals.
    """

    def run(self, ctxt, req):
        """Run operation."""
        try:
            self.logger.debug("run")
            payload = req.payload

            code = payload.get("code")
            path_key = payload.get("path-key")

            if code == None:
                code = ctxt.machine.fkvstore.get(path_key)

            # TODO: should args and kwargs be distinct or in one of locals or globals
            args = payload.get("args", [])
            _locals = payload.get("locals", {})
            _globals = payload.get("globals", None)
            kwargs = payload.get("kwargs", {})

            if None in [code]:
                return ErrorResponse(
                    "code not provided",
                    refmsg=req,
                )
            else:
                try:
                    co = compile(code, "<string>", "exec")
                except Exception as e:
                    self.logger.warning(f"EXCEPTION ({e})")
                    co = None

                if co == None:
                    return ErrorResponse(
                        "code does not compile",
                        refmsg=req,
                    )
                else:
                    try:
                        exec(code, _globals, _locals)
                        return OkResponse(
                            payload=Payload({"return-value": _locals.get("returnvalue")}),
                            refmsg=req,
                        )
                    except Exception as e:
                        self.logger.warning(f"EXCEPTION ({e})")
                        resp = ErrorResponse(
                            f"{e}",
                            refmsg=req,
                        )
        except Exception as e:
            self.logger.error(f"{e}")

run(ctxt, req)

Run operation.

Source code in penvm/src/kernels/penvm/kernels/default/server.py
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
def run(self, ctxt, req):
    """Run operation."""
    try:
        self.logger.debug("run")
        payload = req.payload

        code = payload.get("code")
        path_key = payload.get("path-key")

        if code == None:
            code = ctxt.machine.fkvstore.get(path_key)

        # TODO: should args and kwargs be distinct or in one of locals or globals
        args = payload.get("args", [])
        _locals = payload.get("locals", {})
        _globals = payload.get("globals", None)
        kwargs = payload.get("kwargs", {})

        if None in [code]:
            return ErrorResponse(
                "code not provided",
                refmsg=req,
            )
        else:
            try:
                co = compile(code, "<string>", "exec")
            except Exception as e:
                self.logger.warning(f"EXCEPTION ({e})")
                co = None

            if co == None:
                return ErrorResponse(
                    "code does not compile",
                    refmsg=req,
                )
            else:
                try:
                    exec(code, _globals, _locals)
                    return OkResponse(
                        payload=Payload({"return-value": _locals.get("returnvalue")}),
                        refmsg=req,
                    )
                except Exception as e:
                    self.logger.warning(f"EXCEPTION ({e})")
                    resp = ErrorResponse(
                        f"{e}",
                        refmsg=req,
                    )
    except Exception as e:
        self.logger.error(f"{e}")

RunPythonFunction

Bases: Op

Run function from python code snippet with typed args and typed kwargs.

The code is executed in a thread of the machine.

Danger

Running in the machine process can cause problems.

See penvm.kernels.default.server.RunExec.

Request:

Name Type Description
args typed list

Arguments.

code str

Code snippet.

code-key str

Code snippet in file kvstore. See also code.

globals typed dict

Dictionary of "globals" to use. Defaults to current "globals"

kwargs typed dict

Keyword arguments.

locals typed dict

Dictionary of "locals" to use. Defaults to empty dict

path-key str

Path of code snippet in file kvstore. See also code.

OkResponse:

Name Type Description
return-value typed

Return value from function call.

Source code in penvm/src/kernels/penvm/kernels/default/server.py
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
class RunPythonFunction(Op):
    """Run function from python code snippet with typed args and typed
    kwargs.

    The code is executed in a thread of the `machine`.

    Danger:
        Running in the machine process can cause problems.

    See [penvm.kernels.default.server.RunExec][].

    Attributes: Request:
        args (typed list): Arguments.
        code (str): Code snippet.
        code-key (str): Code snippet in file kvstore. See also `code`.
        globals (typed dict): Dictionary of "globals" to use. Defaults
            to current "globals"
        kwargs (typed dict): Keyword arguments.
        locals (typed dict): Dictionary of "locals" to use. Defaults
            to empty dict
        path-key (str): Path of code snippet in file kvstore. See also
            `code`.

    Attributes: OkResponse:
        return-value (typed): Return value from function call.
    """

    code_template = """\
fn = globals().get(fnname)
__penvm_returnvalue__ = fn(*args, **kwargs)
"""

    def run(self, ctxt, req):
        """Run operation."""
        try:
            self.logger.debug("run")
            payload = req.payload

            # TODO: tweak args and kwargs handling
            args = payload.get("args", [])
            code = payload.get("code")
            path_key = payload.get("path-key")
            if code == None:
                code = ctxt.machine.fkvstore.get(path_key)
            fnname = payload.get("fn-name")
            kwargs = payload.get("kwargs") or {}

            _globals = payload.get("globals", {})
            _locals = payload.get(
                "locals",
                {
                    "args": args,
                    "fnname": fnname,
                    "kwargs": kwargs,
                },
            )

            if code == None:
                return ErrorResponse(
                    "code not provided",
                    refmsg=req,
                )
            elif fnname == None:
                return ErrorResponse(
                    "fnname not provided",
                    refmsg=req,
                )
            else:
                try:
                    co = compile(code, "<string>", "exec")
                except Exception as e:
                    self.logger.warning(f"EXCEPTION ({e})")
                    co = None

                if co == None:
                    return ErrorResponse(
                        "code does not compile",
                        refmsg=req,
                    )
                else:
                    try:
                        # load provided code
                        exec(code, _globals)
                        # run fn
                        exec(self.code_template, _globals, _locals)
                        resp = OkResponse(
                            payload=Payload(
                                {"return-value": _locals.get("__penvm_returnvalue__")}
                            ),
                            refmsg=req,
                        )
                        return resp
                    except Exception as e:
                        self.logger.warning(f"EXCEPTION ({e})")
                        resp = ErrorResponse(
                            f"{e}",
                            refmsg=req,
                        )
        except Exception as e:
            self.logger.error(f"{e}")

run(ctxt, req)

Run operation.

Source code in penvm/src/kernels/penvm/kernels/default/server.py
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
def run(self, ctxt, req):
    """Run operation."""
    try:
        self.logger.debug("run")
        payload = req.payload

        # TODO: tweak args and kwargs handling
        args = payload.get("args", [])
        code = payload.get("code")
        path_key = payload.get("path-key")
        if code == None:
            code = ctxt.machine.fkvstore.get(path_key)
        fnname = payload.get("fn-name")
        kwargs = payload.get("kwargs") or {}

        _globals = payload.get("globals", {})
        _locals = payload.get(
            "locals",
            {
                "args": args,
                "fnname": fnname,
                "kwargs": kwargs,
            },
        )

        if code == None:
            return ErrorResponse(
                "code not provided",
                refmsg=req,
            )
        elif fnname == None:
            return ErrorResponse(
                "fnname not provided",
                refmsg=req,
            )
        else:
            try:
                co = compile(code, "<string>", "exec")
            except Exception as e:
                self.logger.warning(f"EXCEPTION ({e})")
                co = None

            if co == None:
                return ErrorResponse(
                    "code does not compile",
                    refmsg=req,
                )
            else:
                try:
                    # load provided code
                    exec(code, _globals)
                    # run fn
                    exec(self.code_template, _globals, _locals)
                    resp = OkResponse(
                        payload=Payload(
                            {"return-value": _locals.get("__penvm_returnvalue__")}
                        ),
                        refmsg=req,
                    )
                    return resp
                except Exception as e:
                    self.logger.warning(f"EXCEPTION ({e})")
                    resp = ErrorResponse(
                        f"{e}",
                        refmsg=req,
                    )
    except Exception as e:
        self.logger.error(f"{e}")

StoreDrop

Bases: Op

Drop item from store.

Request:

Name Type Description
name

Item name.

TODO: should an reponse be sent?

Source code in penvm/src/kernels/penvm/kernels/default/server.py
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
class StoreDrop(Op):
    """Drop item from store.

    Attributes: Request:
        name: Item name.
    TODO: should an reponse be sent?
    """

    def run(self, ctxt, req):
        try:
            self.logger.debug("run")

            name = req.payload.get("name")
            if name != None:
                ctxt.machine.fkvstore.drop(name)
        except Exception as e:
            self.logger.error(f"{e}")

StoreGet

Bases: Op

Get item from store.

Request:

Name Type Description
name

Item name.

Response:

Name Type Description
data

Data as text or binary.

name

Item name.

Source code in penvm/src/kernels/penvm/kernels/default/server.py
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
class StoreGet(Op):
    """Get item from store.

    Attributes: Request:
        name: Item name.

    Attributes: Response:
        data: Data as text or binary.
        name: Item name.
    """

    def run(self, ctxt, req):
        try:
            self.logger.debug("run")

            name = req.payload.get("name")
            data = ctxt.machine.fkvstore.get(name)
            if data == None:
                return ErrorResponse(
                    f"name ({name}) not in store",
                    refmsg=req,
                )
            else:
                return OkResponse(
                    payload=Payload(
                        {
                            "name": name,
                            "data": data,
                        }
                    ),
                    refmsg=req,
                )
        except Exception as e:
            self.logger.error(f"{e}")
            return ErrorResponse(
                f"{e}",
                refmsg=req,
            )

StoreGetState

Bases: Op

Get store state.

Request:

Name Type Description

Unused.

OkResponse:

Name Type Description

Dictionary of state.

Source code in penvm/src/kernels/penvm/kernels/default/server.py
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
class StoreGetState(Op):
    """Get store state.

    Attributes: Request:
        : Unused.

    Attributes: OkResponse:
        : Dictionary of state.
    """

    def run(self, ctxt, req):
        try:
            self.logger.debug("run")
            return OkResponse(
                payload=Payload(ctxt.machine.fkvstore.state()),
                refmsg=req,
            )
        except Exception as e:
            self.logger.error(f"{e}")
            return ErrorResponse(
                "store not found",
                refmsg=req,
            )

StoreList

Bases: Op

Get item from store.

Request:

Name Type Description
-

Unused.

Response:

Name Type Description
names

Item name.

Source code in penvm/src/kernels/penvm/kernels/default/server.py
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
class StoreList(Op):
    """Get item from store.

    Attributes: Request:
        -: Unused.

    Attributes: Response:
        names: Item name.
    """

    def run(self, ctxt, req):
        try:
            self.logger.debug("run")

            fkvstore = ctxt.machine.fkvstore
            return OkResponse(
                payload=Payload({"names": list(fkvstore.keys())}),
                refmsg=req,
            )
        except Exception as e:
            self.logger.error(f"{e}")
            return ErrorResponse(
                f"{e}",
                refmsg=req,
            )

StorePop

Bases: Op

Get item from store and remove from store.

Request:

Name Type Description
name

Item name.

Response:

Name Type Description
data

Data as text or binary.

name

Item name.

Source code in penvm/src/kernels/penvm/kernels/default/server.py
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
class StorePop(Op):
    """Get item from store and remove from store.

    Attributes: Request:
        name: Item name.

    Attributes: Response:
        data: Data as text or binary.
        name: Item name.
    """

    def run(self, ctxt, req):
        try:
            self.logger.debug("run")

            name = req.payload.get("name")
            resp = StoreGet().run(ctxt, req)
            if name != None:
                ctxt.machine.fkvstore.drop(name)
            return resp
        except Exception as e:
            self.logger.error(f"{e}")

StorePut

Bases: Op

Put item into store.

Request:

Name Type Description
data

Data as text or binary.

name

Item name.

TODO: should an reponse be sent?

Source code in penvm/src/kernels/penvm/kernels/default/server.py
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
class StorePut(Op):
    """Put item into store.

    Attributes: Request:
        data: Data as text or binary.
        name: Item name.
    TODO: should an reponse be sent?
    """

    def run(self, ctxt, req):
        try:
            self.logger.debug("run")

            ftype = req.payload.get("type", "text")
            name = req.payload.get("name")
            data = req.payload.get("data")
            if None in [name, data]:
                # DROP!
                self.logger.debug(f"drop for bad 'name' or 'data'")
                return
            if data:
                self.logger.debug(f"putting {name=} {ftype=} {ctxt.machine.fkvstore.dirpath=} ...")
                ctxt.machine.fkvstore.put(name, data)
        except Exception as e:
            self.logger.error(f"{e}")
You are on penvm.dev