-
Notifications
You must be signed in to change notification settings - Fork 112
/
pebble.py
1227 lines (1019 loc) · 42.7 KB
/
pebble.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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
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
307
308
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
367
368
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
451
452
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
599
600
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
676
677
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
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
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
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
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
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
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
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2021 Canonical Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Client for the Pebble API (HTTP over Unix socket).
For a command-line interface for local testing, see test/pebble_cli.py.
"""
import binascii
import cgi
import datetime
import email.parser
import enum
import http.client
import io
import json
import os
import re
import socket
import sys
import time
import typing
import urllib.error
import urllib.parse
import urllib.request
from ops._private import yaml
_not_provided = object()
class _UnixSocketConnection(http.client.HTTPConnection):
"""Implementation of HTTPConnection that connects to a named Unix socket."""
def __init__(self, host, timeout=_not_provided, socket_path=None):
if timeout is _not_provided:
super().__init__(host)
else:
super().__init__(host, timeout=timeout)
self.socket_path = socket_path
def connect(self):
"""Override connect to use Unix socket (instead of TCP socket)."""
if not hasattr(socket, 'AF_UNIX'):
raise NotImplementedError('Unix sockets not supported on {}'.format(sys.platform))
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sock.connect(self.socket_path)
if self.timeout is not _not_provided:
self.sock.settimeout(self.timeout)
class _UnixSocketHandler(urllib.request.AbstractHTTPHandler):
"""Implementation of HTTPHandler that uses a named Unix socket."""
def __init__(self, socket_path):
super().__init__()
self.socket_path = socket_path
def http_open(self, req):
"""Override http_open to use a Unix socket connection (instead of TCP)."""
return self.do_open(_UnixSocketConnection, req, socket_path=self.socket_path)
# Matches yyyy-mm-ddTHH:MM:SS(.sss)ZZZ
_TIMESTAMP_RE = re.compile(
r'(\d{4})-(\d{2})-(\d{2})[Tt](\d{2}):(\d{2}):(\d{2})(\.\d+)?(.*)')
# Matches [-+]HH:MM
_TIMEOFFSET_RE = re.compile(r'([-+])(\d{2}):(\d{2})')
def _parse_timestamp(s):
"""Parse timestamp from Go-encoded JSON.
This parses RFC3339 timestamps (which are a subset of ISO8601 timestamps)
that Go's encoding/json package produces for time.Time values.
Unfortunately we can't use datetime.fromisoformat(), as that does not
support more than 6 digits for the fractional second, nor the 'Z' for UTC.
Also, it was only introduced in Python 3.7.
"""
match = _TIMESTAMP_RE.match(s)
if not match:
raise ValueError('invalid timestamp {!r}'.format(s))
y, m, d, hh, mm, ss, sfrac, zone = match.groups()
if zone in ('Z', 'z'):
tz = datetime.timezone.utc
else:
match = _TIMEOFFSET_RE.match(zone)
if not match:
raise ValueError('invalid timestamp {!r}'.format(s))
sign, zh, zm = match.groups()
tz_delta = datetime.timedelta(hours=int(zh), minutes=int(zm))
tz = datetime.timezone(tz_delta if sign == '+' else -tz_delta)
microsecond = round(float(sfrac or '0') * 1000000)
return datetime.datetime(int(y), int(m), int(d), int(hh), int(mm), int(ss),
microsecond=microsecond, tzinfo=tz)
def _json_loads(s: typing.Union[str, bytes]) -> typing.Dict:
"""Like json.loads(), but handle str or bytes.
This is needed because an HTTP response's read() method returns bytes on
Python 3.5, and json.load doesn't handle bytes.
"""
if isinstance(s, bytes):
s = s.decode('utf-8')
return json.loads(s)
class Error(Exception):
"""Base class of most errors raised by the Pebble client."""
def __repr__(self):
return '<{}.{} {}>'.format(type(self).__module__, type(self).__name__, self.args)
def name(self):
"""Return a string representation of the model plus class."""
return '<{}.{}>'.format(type(self).__module__, type(self).__name__)
def message(self):
"""Return the message passed as an argument."""
return self.args[0]
class TimeoutError(TimeoutError, Error):
"""Raised when a polling timeout occurs."""
class ConnectionError(Error):
"""Raised when the Pebble client can't connect to the socket."""
class ProtocolError(Error):
"""Raised when there's a higher-level protocol error talking to Pebble."""
class PathError(Error):
"""Raised when there's an error with a specific path."""
def __init__(self, kind: str, message: str):
"""This shouldn't be instantiated directly."""
self.kind = kind
self.message = message
def __str__(self):
return '{} - {}'.format(self.kind, self.message)
def __repr__(self):
return 'PathError({!r}, {!r})'.format(self.kind, self.message)
class APIError(Error):
"""Raised when an HTTP API error occurs talking to the Pebble server."""
def __init__(self, body: typing.Dict, code: int, status: str, message: str):
"""This shouldn't be instantiated directly."""
super().__init__(message) # Makes str(e) return message
self.body = body
self.code = code
self.status = status
self.message = message
def __repr__(self):
return 'APIError({!r}, {!r}, {!r}, {!r})'.format(
self.body, self.code, self.status, self.message)
class ChangeError(Error):
"""Raised by actions when a change is ready but has an error.
For example, this happens when you attempt to start an already-started
service:
cannot perform the following tasks:
- Start service "test" (service "test" was previously started)
"""
def __init__(self, err: str, change: 'Change'):
"""This shouldn't be instantiated directly."""
super().__init__(err) # Makes str(e) return err
self.err = err
self.change = change
def __repr__(self):
return 'ChangeError({!r}, {!r})'.format(self.err, self.change)
class WarningState(enum.Enum):
"""Enum of states for get_warnings() select parameter."""
ALL = 'all'
PENDING = 'pending'
class ChangeState(enum.Enum):
"""Enum of states for get_changes() select parameter."""
ALL = 'all'
IN_PROGRESS = 'in-progress'
READY = 'ready'
class SystemInfo:
"""System information object."""
def __init__(self, version: str):
self.version = version
@classmethod
def from_dict(cls, d: typing.Dict) -> 'SystemInfo':
"""Create new SystemInfo object from dict parsed from JSON."""
return cls(version=d['version'])
def __repr__(self):
return 'SystemInfo(version={self.version!r})'.format(self=self)
class Warning:
"""Warning object."""
def __init__(
self,
message: str,
first_added: datetime.datetime,
last_added: datetime.datetime,
last_shown: typing.Optional[datetime.datetime],
expire_after: str,
repeat_after: str,
):
self.message = message
self.first_added = first_added
self.last_added = last_added
self.last_shown = last_shown
self.expire_after = expire_after
self.repeat_after = repeat_after
@classmethod
def from_dict(cls, d: typing.Dict) -> 'Warning':
"""Create new Warning object from dict parsed from JSON."""
return cls(
message=d['message'],
first_added=_parse_timestamp(d['first-added']),
last_added=_parse_timestamp(d['last-added']),
last_shown=_parse_timestamp(d['last-shown']) if d.get('last-shown') else None,
expire_after=d['expire-after'],
repeat_after=d['repeat-after'],
)
def __repr__(self):
return ('Warning('
'message={self.message!r}, '
'first_added={self.first_added!r}, '
'last_added={self.last_added!r}, '
'last_shown={self.last_shown!r}, '
'expire_after={self.expire_after!r}, '
'repeat_after={self.repeat_after!r})'
).format(self=self)
class TaskProgress:
"""Task progress object."""
def __init__(
self,
label: str,
done: int,
total: int,
):
self.label = label
self.done = done
self.total = total
@classmethod
def from_dict(cls, d: typing.Dict) -> 'TaskProgress':
"""Create new TaskProgress object from dict parsed from JSON."""
return cls(
label=d['label'],
done=d['done'],
total=d['total'],
)
def __repr__(self):
return ('TaskProgress('
'label={self.label!r}, '
'done={self.done!r}, '
'total={self.total!r})'
).format(self=self)
class TaskID(str):
"""Task ID (a more strongly-typed string)."""
def __repr__(self):
return 'TaskID({!r})'.format(str(self))
class Task:
"""Task object."""
def __init__(
self,
id: TaskID,
kind: str,
summary: str,
status: str,
log: typing.List[str],
progress: TaskProgress,
spawn_time: datetime.datetime,
ready_time: typing.Optional[datetime.datetime],
):
self.id = id
self.kind = kind
self.summary = summary
self.status = status
self.log = log
self.progress = progress
self.spawn_time = spawn_time
self.ready_time = ready_time
@classmethod
def from_dict(cls, d: typing.Dict) -> 'Task':
"""Create new Task object from dict parsed from JSON."""
return cls(
id=TaskID(d['id']),
kind=d['kind'],
summary=d['summary'],
status=d['status'],
log=d.get('log') or [],
progress=TaskProgress.from_dict(d['progress']),
spawn_time=_parse_timestamp(d['spawn-time']),
ready_time=_parse_timestamp(d['ready-time']) if d.get('ready-time') else None,
)
def __repr__(self):
return ('Task('
'id={self.id!r}, '
'kind={self.kind!r}, '
'summary={self.summary!r}, '
'status={self.status!r}, '
'log={self.log!r}, '
'progress={self.progress!r}, '
'spawn_time={self.spawn_time!r}, '
'ready_time={self.ready_time!r})'
).format(self=self)
class ChangeID(str):
"""Change ID (a more strongly-typed string)."""
def __repr__(self):
return 'ChangeID({!r})'.format(str(self))
class Change:
"""Change object."""
def __init__(
self,
id: ChangeID,
kind: str,
summary: str,
status: str,
tasks: typing.List[Task],
ready: bool,
err: typing.Optional[str],
spawn_time: datetime.datetime,
ready_time: typing.Optional[datetime.datetime],
):
self.id = id
self.kind = kind
self.summary = summary
self.status = status
self.tasks = tasks
self.ready = ready
self.err = err
self.spawn_time = spawn_time
self.ready_time = ready_time
@classmethod
def from_dict(cls, d: typing.Dict) -> 'Change':
"""Create new Change object from dict parsed from JSON."""
return cls(
id=ChangeID(d['id']),
kind=d['kind'],
summary=d['summary'],
status=d['status'],
tasks=[Task.from_dict(t) for t in d.get('tasks') or []],
ready=d['ready'],
err=d.get('err'),
spawn_time=_parse_timestamp(d['spawn-time']),
ready_time=_parse_timestamp(d['ready-time']) if d.get('ready-time') else None,
)
def __repr__(self):
return ('Change('
'id={self.id!r}, '
'kind={self.kind!r}, '
'summary={self.summary!r}, '
'status={self.status!r}, '
'tasks={self.tasks!r}, '
'ready={self.ready!r}, '
'err={self.err!r}, '
'spawn_time={self.spawn_time!r}, '
'ready_time={self.ready_time!r})'
).format(self=self)
class Plan:
"""Represents the effective Pebble configuration."""
def __init__(self, raw: str):
d = yaml.safe_load(raw) or {}
self._raw = raw
self._services = {name: Service(name, service)
for name, service in d.get('services', {}).items()}
@property
def services(self):
"""This plan's services mapping (maps service name to Service).
This property is currently read-only.
"""
return self._services
def to_dict(self) -> typing.Dict[str, typing.Any]:
"""Convert this plan to its dict representation."""
as_dicts = {name: service.to_dict() for name, service in self._services.items()}
if not as_dicts:
return {}
return {
'services': as_dicts,
}
def to_yaml(self) -> str:
"""Return this plan's YAML representation."""
return yaml.safe_dump(self.to_dict())
__str__ = to_yaml
class Layer:
"""Represents a Pebble configuration layer.
The format of this is not documented, but is captured in code here:
https://github.com/canonical/pebble/blob/master/internal/plan/plan.go
Attributes:
summary: A summary of the purpose of this layer
description: A long form description of this layer
services: A mapping of name: :class:`Service` defined by this layer
"""
# This is how you do type annotations, but it is not supported by Python 3.5
# summary: str
# description: str
# services: typing.Mapping[str, 'Service']
def __init__(self, raw: typing.Union[str, typing.Dict] = None):
if isinstance(raw, str):
d = yaml.safe_load(raw) or {}
else:
d = raw or {}
self.summary = d.get('summary', '')
self.description = d.get('description', '')
self.services = {name: Service(name, service)
for name, service in d.get('services', {}).items()}
def to_yaml(self) -> str:
"""Convert this layer to its YAML representation."""
return yaml.safe_dump(self.to_dict())
def to_dict(self) -> typing.Dict[str, typing.Any]:
"""Convert this layer to its dict representation."""
fields = [
('summary', self.summary),
('description', self.description),
('services', {name: service.to_dict() for name, service in self.services.items()})
]
return {name: value for name, value in fields if value}
def __repr__(self) -> str:
return 'Layer({!r})'.format(self.to_dict())
__str__ = to_yaml
class Service:
"""Represents a service description in a Pebble configuration layer."""
def __init__(self, name: str, raw: typing.Dict = None):
self.name = name
raw = raw or {}
self.summary = raw.get('summary', '')
self.description = raw.get('description', '')
self.startup = raw.get('startup', '')
self.override = raw.get('override', '')
self.command = raw.get('command', '')
self.after = list(raw.get('after', []))
self.before = list(raw.get('before', []))
self.requires = list(raw.get('requires', []))
self.environment = dict(raw.get('environment', {}))
self.user = raw.get('user', '')
self.user_id = raw.get('user-id')
self.group = raw.get('group', '')
self.group_id = raw.get('group-id')
def to_dict(self) -> typing.Dict:
"""Convert this service object to its dict representation."""
fields = [
('summary', self.summary),
('description', self.description),
('startup', self.startup),
('override', self.override),
('command', self.command),
('after', self.after),
('before', self.before),
('requires', self.requires),
('environment', self.environment),
('user', self.user),
('user-id', self.user_id),
('group', self.group),
('group-id', self.group_id),
]
return {name: value for name, value in fields if value}
def __repr__(self) -> str:
return 'Service({!r})'.format(self.to_dict())
def __eq__(self, other: typing.Union[typing.Dict, 'Service']) -> bool:
"""Compare this service description to another."""
if isinstance(other, dict):
return self.to_dict() == other
elif isinstance(other, Service):
return self.to_dict() == other.to_dict()
else:
raise ValueError(
"Cannot compare pebble.Service to {}".format(type(other))
)
class ServiceStartup(enum.Enum):
"""Enum of service startup options."""
ENABLED = 'enabled'
DISABLED = 'disabled'
class ServiceStatus(enum.Enum):
"""Enum of service statuses."""
ACTIVE = 'active'
INACTIVE = 'inactive'
ERROR = 'error'
class ServiceInfo:
"""Service status information."""
def __init__(
self,
name: str,
startup: typing.Union[ServiceStartup, str],
current: typing.Union[ServiceStatus, str],
):
self.name = name
self.startup = startup
self.current = current
def is_running(self) -> bool:
"""Return True if this service is running (in the active state)."""
return self.current == ServiceStatus.ACTIVE
@classmethod
def from_dict(cls, d: typing.Dict) -> 'ServiceInfo':
"""Create new ServiceInfo object from dict parsed from JSON."""
try:
startup = ServiceStartup(d['startup'])
except ValueError:
startup = d['startup']
try:
current = ServiceStatus(d['current'])
except ValueError:
current = d['current']
return cls(
name=d['name'],
startup=startup,
current=current,
)
def __repr__(self):
return ('ServiceInfo('
'name={self.name!r}, '
'startup={self.startup}, '
'current={self.current})'
).format(self=self)
class FileType(enum.Enum):
"""Enum of file types."""
FILE = 'file'
DIRECTORY = 'directory'
SYMLINK = 'symlink'
SOCKET = 'socket'
NAMED_PIPE = 'named-pipe'
DEVICE = 'device'
UNKNOWN = 'unknown'
class FileInfo:
"""Stat-like information about a single file."""
def __init__(
self,
path: str,
name: str,
type: typing.Union['FileType', str],
size: typing.Optional[int],
permissions: int,
last_modified: datetime.datetime,
user_id: typing.Optional[int],
user: typing.Optional[str],
group_id: typing.Optional[int],
group: typing.Optional[str],
):
self.path = path
self.name = name
self.type = type
self.size = size
self.permissions = permissions
self.last_modified = last_modified
self.user_id = user_id
self.user = user
self.group_id = group_id
self.group = group
@classmethod
def from_dict(cls, d: typing.Dict) -> 'FileInfo':
"""Create new FileInfo object from dict parsed from JSON."""
try:
file_type = FileType(d['type'])
except ValueError:
file_type = d['type']
return cls(
path=d['path'],
name=d['name'],
type=file_type,
size=d.get('size'),
permissions=int(d['permissions'], 8),
last_modified=_parse_timestamp(d['last-modified']),
user_id=d.get('user-id'),
user=d.get('user'),
group_id=d.get('group-id'),
group=d.get('group'),
)
def __repr__(self):
return ('FileInfo('
'path={self.path!r}, '
'name={self.name!r}, '
'type={self.type}, '
'size={self.size}, '
'permissions=0o{self.permissions:o}, '
'last_modified={self.last_modified!r}, '
'user_id={self.user_id}, '
'user={self.user!r}, '
'group_id={self.group_id}, '
'group={self.group!r})'
).format(self=self)
class Client:
"""Pebble API client."""
def __init__(self, socket_path=None, opener=None, base_url='http://localhost', timeout=5.0):
"""Initialize a client instance.
Defaults to using a Unix socket at socket_path (which must be specified
unless a custom opener is provided).
"""
if opener is None:
if socket_path is None:
raise ValueError('no socket path provided')
opener = self._get_default_opener(socket_path)
self.opener = opener
self.base_url = base_url
self.timeout = timeout
@classmethod
def _get_default_opener(cls, socket_path):
"""Build the default opener to use for requests (HTTP over Unix socket)."""
opener = urllib.request.OpenerDirector()
opener.add_handler(_UnixSocketHandler(socket_path))
opener.add_handler(urllib.request.HTTPDefaultErrorHandler())
opener.add_handler(urllib.request.HTTPRedirectHandler())
opener.add_handler(urllib.request.HTTPErrorProcessor())
return opener
def _request(
self, method: str, path: str, query: typing.Dict = None, body: typing.Dict = None,
) -> typing.Dict:
"""Make a JSON request to the Pebble server with the given HTTP method and path.
If query dict is provided, it is encoded and appended as a query string
to the URL. If body dict is provided, it is serialied as JSON and used
as the HTTP body (with Content-Type: "application/json"). The resulting
body is decoded from JSON.
"""
headers = {'Accept': 'application/json'}
data = None
if body is not None:
data = json.dumps(body).encode('utf-8')
headers['Content-Type'] = 'application/json'
response = self._request_raw(method, path, query, headers, data)
self._ensure_content_type(response.headers, 'application/json')
return _json_loads(response.read())
@staticmethod
def _ensure_content_type(headers, expected):
"""Parse Content-Type header from headers and ensure it's equal to expected.
Return a dict of any options in the header, e.g., {'boundary': ...}.
"""
ctype, options = cgi.parse_header(headers.get('Content-Type', ''))
if ctype != expected:
raise ProtocolError('expected Content-Type {!r}, got {!r}'.format(expected, ctype))
return options
def _request_raw(
self, method: str, path: str, query: typing.Dict = None, headers: typing.Dict = None,
data: bytes = None,
) -> http.client.HTTPResponse:
"""Make a request to the Pebble server; return the raw HTTPResponse object."""
url = self.base_url + path
if query:
url = url + '?' + urllib.parse.urlencode(query)
if headers is None:
headers = {}
request = urllib.request.Request(url, method=method, data=data, headers=headers)
try:
response = self.opener.open(request, timeout=self.timeout)
except urllib.error.HTTPError as e:
code = e.code
status = e.reason
try:
body = _json_loads(e.read())
message = body['result']['message']
except (IOError, ValueError, KeyError) as e2:
# Will only happen on read error or if Pebble sends invalid JSON.
body = {}
message = '{} - {}'.format(type(e2).__name__, e2)
raise APIError(body, code, status, message)
except urllib.error.URLError as e:
raise ConnectionError(e.reason)
return response
def get_system_info(self) -> SystemInfo:
"""Get system info."""
resp = self._request('GET', '/v1/system-info')
return SystemInfo.from_dict(resp['result'])
def get_warnings(self, select: WarningState = WarningState.PENDING) -> typing.List[Warning]:
"""Get list of warnings in given state (pending or all)."""
query = {'select': select.value}
resp = self._request('GET', '/v1/warnings', query)
return [Warning.from_dict(w) for w in resp['result']]
def ack_warnings(self, timestamp: datetime.datetime) -> int:
"""Acknowledge warnings up to given timestamp, return number acknowledged."""
body = {'action': 'okay', 'timestamp': timestamp.isoformat()}
resp = self._request('POST', '/v1/warnings', body=body)
return resp['result']
def get_changes(
self, select: ChangeState = ChangeState.IN_PROGRESS, service: str = None,
) -> typing.List[Change]:
"""Get list of changes in given state, filter by service name if given."""
query = {'select': select.value}
if service is not None:
query['for'] = service
resp = self._request('GET', '/v1/changes', query)
return [Change.from_dict(c) for c in resp['result']]
def get_change(self, change_id: ChangeID) -> Change:
"""Get single change by ID."""
resp = self._request('GET', '/v1/changes/{}'.format(change_id))
return Change.from_dict(resp['result'])
def abort_change(self, change_id: ChangeID) -> Change:
"""Abort change with given ID."""
body = {'action': 'abort'}
resp = self._request('POST', '/v1/changes/{}'.format(change_id), body=body)
return Change.from_dict(resp['result'])
def autostart_services(self, timeout: float = 30.0, delay: float = 0.1) -> ChangeID:
"""Start the startup-enabled services and wait (poll) for them to be started.
Raises ChangeError if one or more of the services didn't start. If
timeout is 0, submit the action but don't wait; just return the change
ID immediately.
"""
return self._services_action('autostart', [], timeout, delay)
def start_services(
self, services: typing.List[str], timeout: float = 30.0, delay: float = 0.1,
) -> ChangeID:
"""Start services by name and wait (poll) for them to be started.
Raises ChangeError if one or more of the services didn't start. If
timeout is 0, submit the action but don't wait; just return the change
ID immediately.
"""
return self._services_action('start', services, timeout, delay)
def stop_services(
self, services: typing.List[str], timeout: float = 30.0, delay: float = 0.1,
) -> ChangeID:
"""Stop services by name and wait (poll) for them to be started.
Raises ChangeError if one or more of the services didn't stop. If
timeout is 0, submit the action but don't wait; just return the change
ID immediately.
"""
return self._services_action('stop', services, timeout, delay)
def _services_action(
self, action: str, services: typing.Iterable[str], timeout: float, delay: float,
) -> ChangeID:
if not isinstance(services, (list, tuple)):
raise TypeError('services must be a list of str, not {}'.format(
type(services).__name__))
for s in services:
if not isinstance(s, str):
raise TypeError('service names must be str, not {}'.format(type(s).__name__))
body = {'action': action, 'services': services}
resp = self._request('POST', '/v1/services', body=body)
change_id = ChangeID(resp['change'])
if timeout:
change = self.wait_change(change_id, timeout=timeout, delay=delay)
if change.err:
raise ChangeError(change.err, change)
return change_id
def wait_change(
self, change_id: ChangeID, timeout: float = 30.0, delay: float = 0.1,
) -> Change:
"""Wait for the given change to be ready.
If the Pebble server supports the /v1/changes/{id}/wait API endpoint,
use that to avoid polling, otherwise poll /v1/changes/{id} every delay
seconds.
Args:
change_id: Change ID of change to wait for.
timeout: Maximum time in seconds to wait for the change to be
ready. May be None, in which case wait_change never times out.
delay: If polling, this is the delay in seconds between attempts.
Returns:
The Change object being waited on.
Raises:
TimeoutError: If the maximum timeout is reached.
"""
try:
return self._wait_change_using_wait(change_id, timeout)
except NotImplementedError:
# Pebble server doesn't support wait endpoint, fall back to polling
return self._wait_change_using_polling(change_id, timeout, delay)
def _wait_change_using_wait(self, change_id, timeout):
"""Wait for a change to be ready using the wait-change API."""
deadline = time.time() + timeout if timeout is not None else None
# Hit the wait endpoint every Client.timeout-1 seconds to avoid long
# requests (the -1 is to ensure it wakes up before the socket timeout)
while True:
this_timeout = max(self.timeout - 1, 1) # minimum of 1 second
if timeout is not None:
time_remaining = deadline - time.time()
if time_remaining <= 0:
break
# Wait the lesser of the time remaining and Client.timeout-1
this_timeout = min(time_remaining, this_timeout)
try:
return self._wait_change(change_id, this_timeout)
except TimeoutError:
# Catch timeout from wait endpoint and loop to check deadline
pass
raise TimeoutError('timed out waiting for change {} ({} seconds)'.format(
change_id, timeout))
def _wait_change(self, change_id: ChangeID, timeout: float = None) -> Change:
"""Call the wait-change API endpoint directly."""
query = {}
if timeout is not None:
query['timeout'] = '{:.3f}s'.format(timeout)
try:
resp = self._request('GET', '/v1/changes/{}/wait'.format(change_id), query)
except APIError as e:
if e.code == 404:
raise NotImplementedError('server does not implement wait-change endpoint')
if e.code == 504:
raise TimeoutError('timed out waiting for change {} ({} seconds)'.format(
change_id, timeout))
raise
return Change.from_dict(resp['result'])
def _wait_change_using_polling(self, change_id, timeout, delay):
"""Wait for a change to be ready by polling the get-change API."""
deadline = time.time() + timeout if timeout is not None else None
while timeout is None or time.time() < deadline:
change = self.get_change(change_id)
if change.ready:
return change
time.sleep(delay)
raise TimeoutError('timed out waiting for change {} ({} seconds)'.format(
change_id, timeout))
def add_layer(
self, label: str, layer: typing.Union[str, dict, Layer], *, combine: bool = False):
"""Dynamically add a new layer onto the Pebble configuration layers.
If combine is False (the default), append the new layer as the top
layer with the given label. If combine is True and the label already
exists, the two layers are combined into a single one considering the
layer override rules; if the layer doesn't exist, it is added as usual.
"""
if not isinstance(label, str):
raise TypeError('label must be a str, not {}'.format(type(label).__name__))
if isinstance(layer, str):
layer_yaml = layer
elif isinstance(layer, dict):
layer_yaml = Layer(layer).to_yaml()
elif isinstance(layer, Layer):
layer_yaml = layer.to_yaml()
else:
raise TypeError('layer must be str, dict, or pebble.Layer, not {}'.format(
type(layer).__name__))
body = {
'action': 'add',
'combine': combine,
'label': label,
'format': 'yaml',
'layer': layer_yaml,
}
self._request('POST', '/v1/layers', body=body)
def get_plan(self) -> Plan:
"""Get the Pebble plan (currently contains only combined services)."""
resp = self._request('GET', '/v1/plan', {'format': 'yaml'})
return Plan(resp['result'])
def get_services(self, names: typing.List[str] = None) -> typing.List[ServiceInfo]:
"""Get the service status for the configured services.
If names is specified, only fetch the service status for the services
named.
"""
query = None
if names is not None:
query = {'names': ','.join(names)}
resp = self._request('GET', '/v1/services', query)
return [ServiceInfo.from_dict(info) for info in resp['result']]
def pull(self, path: str, *, encoding: str = 'utf-8') -> typing.Union[typing.BinaryIO,
typing.TextIO]:
"""Read a file's content from the remote system.
Args: