@tsplc/build 0.4.3 → 0.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -15,7 +15,7 @@
15
15
  "url": "git+https://github.com/rip-technologies/tsplc.git",
16
16
  "directory": "packages/build"
17
17
  },
18
- "version": "0.4.3",
18
+ "version": "0.4.4",
19
19
  "type": "module",
20
20
  "exports": {
21
21
  ".": {
@@ -54,9 +54,9 @@
54
54
  },
55
55
  "dependencies": {
56
56
  "zod": "4.3.6",
57
- "@tsplc/config": "0.4.3",
58
- "@tsplc/typegen": "0.4.3",
59
- "@tsplc/iec": "0.4.3"
57
+ "@tsplc/config": "0.4.4",
58
+ "@tsplc/typegen": "0.4.4",
59
+ "@tsplc/iec": "0.4.4"
60
60
  },
61
61
  "bin": {
62
62
  "tsplc-build": "./dist/cli.js"
package/python/build.py CHANGED
@@ -737,9 +737,11 @@ def describe_devices(engine, tree, root):
737
737
 
738
738
 
739
739
  def open_template(engine, request, path, devices, caches, progress):
740
- """Opens the template as `path` with its controller and device tree, whose descriptions are in
741
- `devices`; from the cache in `caches` when it holds this tree's structure. Returns the project,
742
- the channels it pinned, and a newly generated tree to keep once the project works."""
740
+ """Opens the template as `path` with its controller, or the cache in `caches` when it holds this
741
+ request's device tree structure. Returns the project and a function that brings its device tree,
742
+ whose descriptions are in `devices`, up to the request's: generating it, which takes minutes, or
743
+ mapping the cached one. That function returns the channels the tree pinned and a newly generated
744
+ tree to keep once the project works. A controller operation checks the controller in between."""
743
745
  tree = request.get("deviceTree")
744
746
  cache = device_tree_cache(request, caches) if tree else None
745
747
  if cache and os.path.isfile(cache):
@@ -747,21 +749,23 @@ def open_template(engine, request, path, devices, caches, progress):
747
749
  describe_devices(engine, tree, devices)
748
750
  shutil.copyfile(cache, path)
749
751
  project = engine.projects.open(path, primary=True)
750
- return project, update_device_tree(engine, project, tree, progress), None
752
+ return project, lambda: (update_device_tree(engine, project, tree, progress), None)
751
753
  progress("Opening project")
752
754
  project = engine.projects.open(request["template"], primary=True)
753
755
  project.save_as(path)
754
756
  if request.get("controller"):
755
757
  apply_controller(project, request["controller"], progress)
756
758
  if not tree:
757
- return project, {}, None
758
- pinned = configure_device_tree(engine, project, tree, devices, progress)
759
- project.save()
760
- if not os.path.isdir(os.path.dirname(cache)):
761
- os.makedirs(os.path.dirname(cache))
762
- pending = cache + ".pending"
763
- shutil.copyfile(project.path, pending)
764
- return project, pinned, (pending, cache)
759
+ return project, lambda: ({}, None)
760
+ def generate():
761
+ pinned = configure_device_tree(engine, project, tree, devices, progress)
762
+ project.save()
763
+ if not os.path.isdir(os.path.dirname(cache)):
764
+ os.makedirs(os.path.dirname(cache))
765
+ pending = cache + ".pending"
766
+ shutil.copyfile(project.path, pending)
767
+ return pinned, (pending, cache)
768
+ return project, generate
765
769
 
766
770
 
767
771
  def open_project(engine, request, workspace, progress):
@@ -783,7 +787,8 @@ def open_project(engine, request, workspace, progress):
783
787
  previous = json.load(source)
784
788
  shutil.copyfile(last, path)
785
789
  return engine.projects.open(path, primary=True), previous, {}, None
786
- project, pinned, generated = open_template(engine, request, path, devices, caches, progress)
790
+ project, complete_tree = open_template(engine, request, path, devices, caches, progress)
791
+ pinned, generated = complete_tree()
787
792
  return project, None, pinned, generated
788
793
 
789
794
 
@@ -15,6 +15,13 @@ from System.Reflection import BindingFlags, TargetInvocationException
15
15
  # An application that was never compiled or downloaded reports this code and data ID.
16
16
  EMPTY_GUID = '00000000-0000-0000-0000-000000000000'
17
17
  GATEWAY_NAME = 'codesys-build'
18
+ # The worker answers CODESYS's prompts with their defaults (LogPrompts), and CODESYS writes each one
19
+ # to its output as this line, while the call that prompted raises only a generic error.
20
+ LOGGED_PROMPT = re.compile(r'Script Messages: (\{.*\})\s*$')
21
+ TERMINAL_ESCAPE = re.compile(r'\x1b\[[0-?]*[ -/]*[@-~]')
22
+ # What CODESYS answers when the controller's runtime rejects the application it is sent, as Control
23
+ # for Linux SL 4.22 does while a task of the old application it stopped can't be deleted.
24
+ RUNTIME_REFUSAL = 'Invalid result package'
18
25
 
19
26
 
20
27
  def download_required(message):
@@ -74,10 +81,77 @@ def failure_text(error):
74
81
  return ' '.join(str(cause if cause is not None else error).split())
75
82
 
76
83
 
84
+ def output_position(log):
85
+ """Where CODESYS's output ends now, so a later read finds only what it writes after."""
86
+ try:
87
+ return os.path.getsize(log)
88
+ except OSError:
89
+ return 0
90
+
91
+
92
+ def prompt_text(message):
93
+ """A prompt's statement, without the question it asked, such as whether to continue."""
94
+ paragraphs = [' '.join(paragraph.split()) for paragraph in re.split(r'(?:\r?\n){2,}', message)]
95
+ return ' '.join(paragraph for paragraph in paragraphs if paragraph and not paragraph.endswith('?'))
96
+
97
+
98
+ def logged_prompts(log, start):
99
+ """The prompts CODESYS answered by itself since `start` in its output."""
100
+ try:
101
+ with io.open(log, 'rb') as output:
102
+ output.seek(start)
103
+ text = output.read().decode('utf-8', 'replace')
104
+ except (IOError, OSError):
105
+ return []
106
+ prompts = []
107
+ for line in text.splitlines():
108
+ logged = LOGGED_PROMPT.search(TERMINAL_ESCAPE.sub('', line))
109
+ if not logged:
110
+ continue
111
+ try:
112
+ message = json.loads(logged.group(1))['message']
113
+ except (ValueError, KeyError, TypeError):
114
+ continue
115
+ if prompt_text(message):
116
+ prompts.append(prompt_text(message))
117
+ return prompts
118
+
119
+
120
+ def refusal(error, prompts):
121
+ """The failure of a transfer the controller refused, saying why from the prompts CODESYS
122
+ answered; None when it answered none."""
123
+ if not prompts:
124
+ return None
125
+ answered = '; '.join(prompts)
126
+ if any(RUNTIME_REFUSAL in prompt for prompt in prompts):
127
+ return RuntimeError(
128
+ u'The controller\'s runtime refused the application: CODESYS answered "{0}" ({1}). Its log would '
129
+ u'show why; a task of the old application may have failed to stop, after which the runtime '
130
+ u'accepts no application until it restarts. Restart it with `sudo systemctl restart '
131
+ u'codesyscontrol` on the controller before deploying again; the controller may stay stopped '
132
+ u'until then'.format(answered, failure_text(error)))
133
+ return RuntimeError(u'The controller refused the transfer: CODESYS answered "{0}" ({1})'.format(
134
+ answered, failure_text(error)))
135
+
136
+
137
+ def transfer(log, send):
138
+ """Runs `send`, a step that transfers to the controller, failing with the reason the controller
139
+ gave when it refused, which CODESYS writes to `log`, its output, rather than raising."""
140
+ start = output_position(log)
141
+ try:
142
+ return send()
143
+ except Exception as error:
144
+ refused = refusal(error, logged_prompts(log, start))
145
+ if refused is None:
146
+ raise
147
+ raise refused
148
+
149
+
77
150
  def preflight(engine, application, request, progress):
78
151
  """Logs in read-only before a download changes anything, so a gateway, controller or user it
79
- can't reach fails it in seconds, before the import, with the controller untouched. Returns the
80
- controller's identity and state of this application, None when it holds none of this name."""
152
+ can't reach fails it in seconds, before the device tree and the import, with the controller
153
+ untouched. Returns the controller's identity and state of this application, None when it holds
154
+ none of this name."""
81
155
  if request.get('initializeUser'):
82
156
  progress('Skipping the preflight login: this download creates the controller user')
83
157
  return None
@@ -250,7 +324,10 @@ def opened_ahead(request, prepared, progress):
250
324
 
251
325
 
252
326
  def open_operation_project(engine, request, prepared, progress):
253
- """Returns the project, the channels its tree pinned, and a newly generated tree to keep once the operation works."""
327
+ """Returns the project, with its controller, and a function that brings its device tree up to the
328
+ request's, which returns the channels the tree pinned and a newly generated tree to keep once the
329
+ operation works. Opening is quick; the tree, generated or mapped, is not, so it waits until the
330
+ operation has checked the controller."""
254
331
  project = opened_ahead(request, prepared, progress)
255
332
  if project is None:
256
333
  # Operations reuse the downloaded project, which has its controller and tree; a download without one starts from the template.
@@ -260,10 +337,10 @@ def open_operation_project(engine, request, prepared, progress):
260
337
  project = engine.projects.open(request['project'], primary=True)
261
338
  tree = request.get('deviceTree')
262
339
  # The downloaded tree has this tree's structure, but the channel mappings of the last download.
263
- return project, update_device_tree(engine, project, tree, progress) if tree else {}, None
340
+ return project, lambda: (update_device_tree(engine, project, tree, progress) if tree else {}, None)
264
341
 
265
342
 
266
- def restore_previous(engine, request, progress):
343
+ def restore_previous(engine, request, log, progress):
267
344
  """Downloads the last committed project again after a download failed mid-transfer, unless the
268
345
  controller still runs it. The project compiled and ran before, so this needs no import. Returns
269
346
  whether it downloaded, and the controller's identity and state afterwards."""
@@ -292,7 +369,7 @@ def restore_previous(engine, request, progress):
292
369
  return {'restored': False, 'controllerIds': expected, 'state': 'run'}
293
370
  enter_phase(request, u'transfer')
294
371
  progress('Downloading the previous application')
295
- online_app.login(engine.OnlineChangeOption.Never, False)
372
+ transfer(log, lambda: online_app.login(engine.OnlineChangeOption.Never, False))
296
373
  if controller_state(core) != 'run':
297
374
  online_app.start()
298
375
  progress('Saving the previous application as controller boot project')
@@ -348,10 +425,21 @@ def finish_online(request, finishing):
348
425
  return {}
349
426
 
350
427
 
351
- def run_online(engine, request, prepared=None, keep=None):
352
- """`prepared` is a project a warm worker opened ahead; an online change of that project uses it.
353
- A request to finish later replies once the controller runs the application, and hands `keep`
354
- the open project and its newly generated tree, for `finish_online` to save."""
428
+ def confirm_changing_login(core, progress):
429
+ """Logs in as the operation's user without read-only mode and out again, so a user who may only
430
+ look at the controller fails the operation before it builds anything. The core login, unlike the
431
+ scripting wrapper's, never creates or downloads an application."""
432
+ progress('Checking the controller user may change the application')
433
+ if not core.Login(True):
434
+ raise RuntimeError('The controller refused a login that may change the application, so it was not changed')
435
+ core.Logout()
436
+
437
+
438
+ def run_online(engine, request, log, prepared=None, keep=None):
439
+ """`log` is CODESYS's output, where it writes the prompts it answers. `prepared` is a project a
440
+ warm worker opened ahead; an online change of that project uses it. A request to finish later
441
+ replies once the controller runs the application, and hands `keep` the open project and its newly
442
+ generated tree, for `finish_online` to save."""
355
443
  progress = request_progress(request)
356
444
  progress('Starting; processor count {0}'.format(Environment.ProcessorCount))
357
445
  if request.get('finishLater') and keep is None:
@@ -359,15 +447,17 @@ def run_online(engine, request, prepared=None, keep=None):
359
447
  if request['operation'] == 'restore':
360
448
  if prepared is not None:
361
449
  prepared.close()
362
- return restore_previous(engine, request, progress)
450
+ return restore_previous(engine, request, log, progress)
363
451
  previous = request.get('baseline')
364
- project, pinned, generated = open_operation_project(engine, request, prepared, progress)
452
+ project, complete_tree = open_operation_project(engine, request, prepared, progress)
365
453
  application = project.active_application
366
454
  online_app = None
367
455
  online_device = None
368
456
  kept = []
369
457
  try:
370
- progress('Project opened; configuring controller connection')
458
+ # Everything up to the device tree is quick, so a controller the operation can't use fails it
459
+ # in seconds, with nothing changed on it.
460
+ progress('Project opened; checking the controller before changing anything')
371
461
  if application is None:
372
462
  raise RuntimeError('Project has no active Application')
373
463
  device, credentials = connect_controller(engine, application, request['online'], request.get('credentialsFile'))
@@ -402,6 +492,8 @@ def run_online(engine, request, prepared=None, keep=None):
402
492
  'state': state, 'values': {expression: online_app.read_value(expression) for expression in request.get('read', [])}}
403
493
  finally:
404
494
  core.Logout()
495
+ confirm_changing_login(core, progress)
496
+ pinned, generated = complete_tree()
405
497
  # Only what changed since the baseline is written; a template gets every object.
406
498
  import_source(engine, application, request, previous['objects'] if previous is not None else None, progress)
407
499
  # Match the normal build's source/template lifecycle. Saving the edited
@@ -431,7 +523,7 @@ def run_online(engine, request, prepared=None, keep=None):
431
523
  # From here the controller may hold neither application, so nothing may stop CODESYS.
432
524
  enter_phase(request, u'transfer')
433
525
  progress('Downloading application')
434
- online_app.login(engine.OnlineChangeOption.Never, False)
526
+ transfer(log, lambda: online_app.login(engine.OnlineChangeOption.Never, False))
435
527
  expected = controller_ids(core)
436
528
  if controller_state(core) != 'run':
437
529
  online_app.start()
@@ -455,7 +547,7 @@ def run_online(engine, request, prepared=None, keep=None):
455
547
  mode = loaded_type('_3S.CoDeSys.Core.Online.BootProjectTransferMode')
456
548
  enter_phase(request, u'transfer')
457
549
  progress('Applying online change')
458
- core.Download(True, Enum.Parse(mode, 'UseProjectSetting'))
550
+ transfer(log, lambda: core.Download(True, Enum.Parse(mode, 'UseProjectSetting')))
459
551
  # An online-change transfer does not itself replace the boot project.
460
552
  # The original online boot command saves the downloaded application;
461
553
  # Boot-only host preparation saves the accepted application separately
package/python/worker.py CHANGED
@@ -55,7 +55,8 @@ def run_controller_operation(engine, directory, loaded):
55
55
  if request["operation"] == "finish":
56
56
  result = finish_online(request, finishing)
57
57
  else:
58
- result = run_online(engine, request, prepared, lambda project, generated: loaded.update(finishing=(project, generated)))
58
+ result = run_online(engine, request, os.path.join(directory, "codesys.log"), prepared,
59
+ lambda project, generated: loaded.update(finishing=(project, generated)))
59
60
  write_json(engine, os.path.join(root, "result.json"), result)
60
61
 
61
62