1"""
2BitBake 'remotedata' module
3
4Provides support for using a datastore from the bitbake client
5"""
6
7# Copyright (C) 2016  Intel Corporation
8#
9# SPDX-License-Identifier: GPL-2.0-only
10#
11
12import bb.data
13
14class RemoteDatastores:
15    """Used on the server side to manage references to server-side datastores"""
16    def __init__(self, cooker):
17        self.cooker = cooker
18        self.datastores = {}
19        self.locked = []
20        self.datastores[0] = self.cooker.data
21        self.nextindex = 1
22
23    def __len__(self):
24        return len(self.datastores)
25
26    def __getitem__(self, key):
27        # Cooker could have changed its datastore from under us
28        self.datastores[0] = self.cooker.data
29        return self.datastores[key]
30
31    def items(self):
32        return self.datastores.items()
33
34    def store(self, d, locked=False):
35        """
36        Put a datastore into the collection. If locked=True then the datastore
37        is understood to be managed externally and cannot be released by calling
38        release().
39        """
40        idx = self.nextindex
41        self.datastores[idx] = d
42        if locked:
43            self.locked.append(idx)
44        self.nextindex += 1
45        return idx
46
47    def check_store(self, d, locked=False):
48        """
49        Put a datastore into the collection if it's not already in there;
50        in either case return the index
51        """
52        for key, val in self.datastores.items():
53            if val is d:
54                idx = key
55                break
56        else:
57            idx = self.store(d, locked)
58        return idx
59
60    def release(self, idx):
61        """Discard a datastore in the collection"""
62        if idx in self.locked:
63            raise Exception('Tried to release locked datastore %d' % idx)
64        del self.datastores[idx]
65
66