Matteo Scandolo | d2044a4 | 2017-08-07 16:08:28 -0700 | [diff] [blame] | 1 | # Copyright 2017-present Open Networking Foundation |
| 2 | # |
| 3 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | # you may not use this file except in compliance with the License. |
| 5 | # You may obtain a copy of the License at |
| 6 | # |
| 7 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | # |
| 9 | # Unless required by applicable law or agreed to in writing, software |
| 10 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | # See the License for the specific language governing permissions and |
| 13 | # limitations under the License. |
| 14 | |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 15 | from __future__ import print_function |
| 16 | import os |
| 17 | import sys |
| 18 | import threading |
| 19 | import time |
| 20 | import imp |
Andy Bavier | 04ee191 | 2019-01-30 14:17:16 -0700 | [diff] [blame] | 21 | import traceback |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 22 | from xosconfig import Config |
| 23 | from multistructlog import create_logger |
Matteo Scandolo | d2044a4 | 2017-08-07 16:08:28 -0700 | [diff] [blame] | 24 | |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 25 | """ |
| 26 | Django-like ORM layer for gRPC |
| 27 | |
| 28 | Usage: |
| 29 | api = ORMStub(stub) |
| 30 | |
| 31 | api.Slices.all() ... list all slices |
| 32 | |
| 33 | someSlice = api.Slices.get(id=1) ... get slice #1 |
| 34 | |
| 35 | someSlice.site ... automatically resolves site_id into a site object |
| 36 | someSlice.instances ... automatically resolves instances_ids into instance objects |
| 37 | someSlice.save() ... saves the slice object |
| 38 | """ |
| 39 | |
| 40 | """ |
| 41 | import grpc_client, orm |
| 42 | c=grpc_client.SecureClient("xos-core.cord.lab", username="padmin@vicci.org", password="letmein") |
Scott Baker | a1eae7a | 2017-06-06 09:20:15 -0700 | [diff] [blame] | 43 | u=c.xos_orm.User.objects.get(id=1) |
| 44 | """ |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 45 | |
Matteo Scandolo | e3d2f26 | 2018-06-05 17:45:39 -0700 | [diff] [blame] | 46 | |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 47 | log = create_logger(Config().get("logging")) |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 48 | |
Scott Baker | 22796cc | 2017-02-23 16:53:34 -0800 | [diff] [blame] | 49 | convenience_wrappers = {} |
| 50 | |
Andy Bavier | 04ee191 | 2019-01-30 14:17:16 -0700 | [diff] [blame] | 51 | # Find the topmost synchronizer-specific function in the call stack |
| 52 | def get_synchronizer_function(): |
| 53 | result = None |
| 54 | for file,line,func,stmt in traceback.extract_stack(): |
| 55 | if file.startswith("/opt/xos/synchronizers"): |
| 56 | if not result: |
| 57 | result = "%s:%s()" % (file,func) |
| 58 | if not file.startswith("/opt/xos/synchronizers/new_base"): |
| 59 | result = "%s:%s()" % (file,func) |
| 60 | break |
| 61 | return result |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 62 | |
Scott Baker | d0f1dc1 | 2018-04-23 12:05:32 -0700 | [diff] [blame] | 63 | class ORMGenericContentNotFoundException(Exception): |
| 64 | pass |
| 65 | |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 66 | |
Scott Baker | d0f1dc1 | 2018-04-23 12:05:32 -0700 | [diff] [blame] | 67 | class ORMGenericObjectNotFoundException(Exception): |
| 68 | pass |
| 69 | |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 70 | |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 71 | class ORMWrapper(object): |
| 72 | """ Wraps a protobuf object to provide ORM features """ |
| 73 | |
| 74 | def __init__(self, wrapped_class, stub, is_new=False): |
| 75 | super(ORMWrapper, self).__setattr__("_wrapped_class", wrapped_class) |
| 76 | super(ORMWrapper, self).__setattr__("stub", stub) |
| 77 | super(ORMWrapper, self).__setattr__("cache", {}) |
| 78 | super(ORMWrapper, self).__setattr__("reverse_cache", {}) |
Sapan Bhatia | 71f5768 | 2017-08-23 20:09:08 -0400 | [diff] [blame] | 79 | super(ORMWrapper, self).__setattr__("synchronizer_step", None) |
Sapan Bhatia | 2b307f7 | 2017-11-02 11:39:17 -0400 | [diff] [blame] | 80 | super(ORMWrapper, self).__setattr__("dependent", None) |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 81 | super(ORMWrapper, self).__setattr__("is_new", is_new) |
Scott Baker | c4156c3 | 2017-12-08 10:58:21 -0800 | [diff] [blame] | 82 | super(ORMWrapper, self).__setattr__("post_save_fixups", []) |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 83 | fkmap = self.gen_fkmap() |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 84 | super(ORMWrapper, self).__setattr__("_fkmap", fkmap) |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 85 | reverse_fkmap = self.gen_reverse_fkmap() |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 86 | super(ORMWrapper, self).__setattr__("_reverse_fkmap", reverse_fkmap) |
Scott Baker | 5b7fba0 | 2018-10-17 08:46:46 -0700 | [diff] [blame] | 87 | super(ORMWrapper, self).__setattr__("_initial", self._dict) |
| 88 | |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 89 | def fields_differ(self, f1, f2): |
| 90 | return f1 != f2 |
Scott Baker | 5b7fba0 | 2018-10-17 08:46:46 -0700 | [diff] [blame] | 91 | |
| 92 | @property |
| 93 | def _dict(self): |
| 94 | """ Return a dictionary of {fieldname: fieldvalue} for the object. |
| 95 | |
| 96 | This differs for the xos-core implementation of XOSBase. For new object, XOSBase will include field names |
| 97 | that are set to default values. ORM ignores fields that are set to default values. |
| 98 | """ |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 99 | d = {} |
Scott Baker | 5b7fba0 | 2018-10-17 08:46:46 -0700 | [diff] [blame] | 100 | for (fieldDesc, val) in self._wrapped_class.ListFields(): |
| 101 | name = fieldDesc.name |
| 102 | d[name] = val |
| 103 | return d |
| 104 | |
| 105 | @property |
| 106 | def diff(self): |
| 107 | d1 = self._initial |
| 108 | d2 = self._dict |
| 109 | all_field_names = self._wrapped_class.DESCRIPTOR.fields_by_name.keys() |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 110 | diffs = [] |
Scott Baker | 5b7fba0 | 2018-10-17 08:46:46 -0700 | [diff] [blame] | 111 | for k in all_field_names: |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 112 | if d1.get(k, None) != d2.get(k, None): |
| 113 | diffs.append((k, (d1.get(k, None), d2.get(k, None)))) |
Scott Baker | 5b7fba0 | 2018-10-17 08:46:46 -0700 | [diff] [blame] | 114 | |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 115 | # diffs = [(k, (v, d2[k])) for k, v in d1.items() if self.fields_differ(v,d2[k])] |
Scott Baker | 5b7fba0 | 2018-10-17 08:46:46 -0700 | [diff] [blame] | 116 | return dict(diffs) |
| 117 | |
| 118 | @property |
| 119 | def has_changed(self): |
| 120 | return bool(self.diff) |
| 121 | |
| 122 | @property |
| 123 | def changed_fields(self): |
| 124 | """ Return the list of changed fields. |
| 125 | |
| 126 | This differs for the xos-core implementation of XOSBase. For new object, XOSBase will include field names |
| 127 | that are set to default values. |
| 128 | """ |
| 129 | if self.is_new: |
| 130 | return self._dict.keys() |
| 131 | return self.diff.keys() |
| 132 | |
| 133 | def has_field_changed(self, field_name): |
| 134 | return field_name in self.diff.keys() |
| 135 | |
| 136 | def get_field_diff(self, field_name): |
| 137 | return self.diff.get(field_name, None) |
| 138 | |
| 139 | def recompute_initial(self): |
| 140 | self._initial = self._dict |
| 141 | |
| 142 | def save_changed_fields(self, always_update_timestamp=False): |
| 143 | if self.has_changed: |
| 144 | update_fields = self.changed_fields |
| 145 | if always_update_timestamp and "updated" not in update_fields: |
| 146 | update_fields.append("updated") |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 147 | self.save( |
| 148 | update_fields=sorted(update_fields), |
| 149 | always_update_timestamp=always_update_timestamp, |
| 150 | ) |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 151 | |
Scott Baker | d78f647 | 2017-03-14 17:30:14 -0700 | [diff] [blame] | 152 | def create_attr(self, name, value=None): |
| 153 | """ setattr(self, ...) will fail for attributes that don't exist in the |
| 154 | wrapped grpc class. This is by design. However, if someone really |
| 155 | does want to attach a new attribute to this class, then they can |
| 156 | call create_attr() |
| 157 | """ |
| 158 | super(ORMWrapper, self).__setattr__(name, value) |
| 159 | |
Scott Baker | 03a163f | 2017-05-17 09:21:47 -0700 | [diff] [blame] | 160 | def get_generic_foreignkeys(self): |
| 161 | """ this is a placeholder until generic foreign key support is added |
| 162 | to xproto. |
| 163 | """ |
| 164 | return [] |
| 165 | |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 166 | def gen_fkmap(self): |
| 167 | fkmap = {} |
| 168 | |
Scott Baker | aa556b0 | 2017-03-07 16:07:34 -0800 | [diff] [blame] | 169 | all_field_names = self._wrapped_class.DESCRIPTOR.fields_by_name.keys() |
| 170 | |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 171 | for (name, field) in self._wrapped_class.DESCRIPTOR.fields_by_name.items(): |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 172 | if name.endswith("_id"): |
| 173 | foreignKey = field.GetOptions().Extensions._FindExtensionByName( |
| 174 | "xos.foreignKey" |
| 175 | ) |
| 176 | fk = field.GetOptions().Extensions[foreignKey] |
| 177 | if fk and fk.modelName: |
| 178 | fkdict = { |
| 179 | "src_fieldName": name, |
| 180 | "modelName": fk.modelName, |
| 181 | "kind": "fk", |
| 182 | } |
| 183 | if fk.reverseFieldName: |
| 184 | fkdict["reverse_fieldName"] = fk.reverseFieldName |
| 185 | fkmap[name[:-3]] = fkdict |
| 186 | else: |
| 187 | # If there's a corresponding _type_id field, then see if this |
| 188 | # is a generic foreign key. |
| 189 | type_name = name[:-3] + "_type_id" |
| 190 | if type_name in all_field_names: |
| 191 | fkmap[name[:-3]] = { |
| 192 | "src_fieldName": name, |
| 193 | "ct_fieldName": type_name, |
| 194 | "kind": "generic_fk", |
| 195 | } |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 196 | |
Scott Baker | 03a163f | 2017-05-17 09:21:47 -0700 | [diff] [blame] | 197 | for gfk in self.get_generic_foreignkeys(): |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 198 | fkmap[gfk["name"]] = { |
| 199 | "src_fieldName": gfk["id"], |
| 200 | "ct_fieldName": gfk["content_type"], |
| 201 | "kind": "generic_fk", |
| 202 | } |
Scott Baker | 03a163f | 2017-05-17 09:21:47 -0700 | [diff] [blame] | 203 | |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 204 | return fkmap |
| 205 | |
| 206 | def gen_reverse_fkmap(self): |
| 207 | reverse_fkmap = {} |
| 208 | |
| 209 | for (name, field) in self._wrapped_class.DESCRIPTOR.fields_by_name.items(): |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 210 | if name.endswith("_ids"): |
| 211 | reverseForeignKey = field.GetOptions().Extensions._FindExtensionByName( |
| 212 | "xos.reverseForeignKey" |
| 213 | ) |
| 214 | fk = field.GetOptions().Extensions[reverseForeignKey] |
| 215 | if fk and fk.modelName: |
| 216 | reverse_fkmap[name[:-4]] = { |
| 217 | "src_fieldName": name, |
| 218 | "modelName": fk.modelName, |
| 219 | "writeable": False, |
| 220 | } |
| 221 | else: |
| 222 | manyToManyForeignKey = field.GetOptions().Extensions._FindExtensionByName( |
| 223 | "xos.manyToManyForeignKey" |
| 224 | ) |
| 225 | fk = field.GetOptions().Extensions[manyToManyForeignKey] |
| 226 | if fk and fk.modelName: |
| 227 | reverse_fkmap[name[:-4]] = { |
| 228 | "src_fieldName": name, |
| 229 | "modelName": fk.modelName, |
| 230 | "writeable": True, |
| 231 | } |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 232 | |
| 233 | return reverse_fkmap |
| 234 | |
| 235 | def fk_resolve(self, name): |
| 236 | if name in self.cache: |
Scott Baker | c4156c3 | 2017-12-08 10:58:21 -0800 | [diff] [blame] | 237 | return self.cache[name] |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 238 | |
| 239 | fk_entry = self._fkmap[name] |
Scott Baker | aa556b0 | 2017-03-07 16:07:34 -0800 | [diff] [blame] | 240 | fk_kind = fk_entry["kind"] |
| 241 | fk_id = getattr(self, fk_entry["src_fieldName"]) |
| 242 | |
| 243 | if not fk_id: |
| 244 | return None |
| 245 | |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 246 | if fk_kind == "fk": |
| 247 | id = self.stub.make_ID(id=fk_id) |
Scott Baker | aa556b0 | 2017-03-07 16:07:34 -0800 | [diff] [blame] | 248 | dest_model = self.stub.invoke("Get%s" % fk_entry["modelName"], id) |
| 249 | |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 250 | elif fk_kind == "generic_fk": |
| 251 | dest_model = self.stub.genericForeignKeyResolve( |
| 252 | getattr(self, fk_entry["ct_fieldName"]), fk_id |
| 253 | )._wrapped_class |
Scott Baker | aa556b0 | 2017-03-07 16:07:34 -0800 | [diff] [blame] | 254 | |
| 255 | else: |
| 256 | raise Exception("unknown fk_kind") |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 257 | |
Scott Baker | c4156c3 | 2017-12-08 10:58:21 -0800 | [diff] [blame] | 258 | dest_model = make_ORMWrapper(dest_model, self.stub) |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 259 | self.cache[name] = dest_model |
| 260 | |
Scott Baker | c4156c3 | 2017-12-08 10:58:21 -0800 | [diff] [blame] | 261 | return dest_model |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 262 | |
| 263 | def reverse_fk_resolve(self, name): |
| 264 | if name not in self.reverse_cache: |
| 265 | fk_entry = self._reverse_fkmap[name] |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 266 | self.reverse_cache[name] = ORMLocalObjectManager( |
| 267 | self.stub, |
| 268 | fk_entry["modelName"], |
| 269 | getattr(self, fk_entry["src_fieldName"]), |
| 270 | fk_entry["writeable"], |
| 271 | ) |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 272 | |
Scott Baker | 7ab456b | 2019-01-08 14:58:13 -0800 | [diff] [blame] | 273 | return self.reverse_cache[name] |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 274 | |
Scott Baker | e72e761 | 2017-02-20 10:07:09 -0800 | [diff] [blame] | 275 | def fk_set(self, name, model): |
| 276 | fk_entry = self._fkmap[name] |
Scott Baker | aa556b0 | 2017-03-07 16:07:34 -0800 | [diff] [blame] | 277 | fk_kind = fk_entry["kind"] |
Scott Baker | a1eae7a | 2017-06-06 09:20:15 -0700 | [diff] [blame] | 278 | if model: |
| 279 | id = model.id |
| 280 | else: |
| 281 | id = 0 |
Scott Baker | e72e761 | 2017-02-20 10:07:09 -0800 | [diff] [blame] | 282 | setattr(self._wrapped_class, fk_entry["src_fieldName"], id) |
| 283 | |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 284 | if fk_kind == "generic_fk": |
| 285 | setattr( |
| 286 | self._wrapped_class, |
| 287 | fk_entry["ct_fieldName"], |
| 288 | model.self_content_type_id, |
| 289 | ) |
Scott Baker | aa556b0 | 2017-03-07 16:07:34 -0800 | [diff] [blame] | 290 | |
Scott Baker | c4156c3 | 2017-12-08 10:58:21 -0800 | [diff] [blame] | 291 | if name in self.cache: |
| 292 | old_model = self.cache[name] |
| 293 | if fk_entry.get("reverse_fieldName"): |
| 294 | # Note this fk change so that we can update the destination model after we save. |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 295 | self.post_save_fixups.append( |
| 296 | { |
| 297 | "src_fieldName": fk_entry["src_fieldName"], |
| 298 | "dest_id": id, |
| 299 | "dest_model": old_model, |
| 300 | "remove": True, |
| 301 | "reverse_fieldName": fk_entry.get("reverse_fieldName"), |
| 302 | } |
| 303 | ) |
Scott Baker | c4156c3 | 2017-12-08 10:58:21 -0800 | [diff] [blame] | 304 | del self.cache[name] |
Scott Baker | e72e761 | 2017-02-20 10:07:09 -0800 | [diff] [blame] | 305 | |
Scott Baker | c4156c3 | 2017-12-08 10:58:21 -0800 | [diff] [blame] | 306 | if model: |
| 307 | self.cache[name] = model |
| 308 | if fk_entry.get("reverse_fieldName"): |
| 309 | # Note this fk change so that we can update the destination model after we save. |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 310 | self.post_save_fixups.append( |
| 311 | { |
| 312 | "src_fieldName": fk_entry["src_fieldName"], |
| 313 | "dest_id": id, |
| 314 | "dest_model": model, |
| 315 | "remove": False, |
| 316 | "reverse_fieldName": fk_entry.get("reverse_fieldName"), |
| 317 | } |
| 318 | ) |
Scott Baker | c4156c3 | 2017-12-08 10:58:21 -0800 | [diff] [blame] | 319 | elif name in self.cache: |
| 320 | del self.cache[name] |
Scott Baker | e72e761 | 2017-02-20 10:07:09 -0800 | [diff] [blame] | 321 | |
Scott Baker | c4156c3 | 2017-12-08 10:58:21 -0800 | [diff] [blame] | 322 | def do_post_save_fixups(self): |
| 323 | # Perform post-save foreign key fixups. |
| 324 | # Fixup the models that we've set a foreign key to so that their in-memory representation has the correct |
| 325 | # reverse foreign key back to us. We can only do this after a save, because self.id isn't known until |
| 326 | # after save. |
| 327 | # See unit test test_foreign_key_set_without_invalidate |
| 328 | for fixup in self.post_save_fixups: |
| 329 | model = fixup["dest_model"] |
| 330 | reverse_fieldName_ids = fixup["reverse_fieldName"] + "_ids" |
| 331 | if not hasattr(model, reverse_fieldName_ids): |
| 332 | continue |
| 333 | if fixup["remove"]: |
| 334 | reverse_ids = getattr(model, reverse_fieldName_ids) |
| 335 | if self.id in reverse_ids: |
| 336 | reverse_ids.remove(self.id) |
| 337 | else: |
| 338 | reverse_ids = getattr(model, reverse_fieldName_ids) |
| 339 | if self.id not in reverse_ids: |
| 340 | reverse_ids.append(self.id) |
| 341 | model.invalidate_cache(fixup["reverse_fieldName"]) |
| 342 | self.post_save_fixups = [] |
Scott Baker | e72e761 | 2017-02-20 10:07:09 -0800 | [diff] [blame] | 343 | |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 344 | def __getattr__(self, name, *args, **kwargs): |
| 345 | # note: getattr is only called for attributes that do not exist in |
| 346 | # self.__dict__ |
| 347 | |
Scott Baker | 186372f | 2017-02-23 13:49:36 -0800 | [diff] [blame] | 348 | # pk is a synonym for id |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 349 | if name == "pk": |
Scott Baker | 186372f | 2017-02-23 13:49:36 -0800 | [diff] [blame] | 350 | name = "id" |
| 351 | |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 352 | if name in self._fkmap.keys(): |
| 353 | return self.fk_resolve(name) |
| 354 | |
| 355 | if name in self._reverse_fkmap.keys(): |
| 356 | return self.reverse_fk_resolve(name) |
| 357 | |
Scott Baker | 37cf9e2 | 2018-08-20 14:39:33 -0700 | [diff] [blame] | 358 | try: |
| 359 | # When sending a reply, XOS will leave the field unset if it is None in the data model. If |
| 360 | # HasField(<fieldname>)==False for an existing object, then the caller can infer that field was set to |
| 361 | # None. |
| 362 | if (not self.is_new) and (not self._wrapped_class.HasField(name)): |
| 363 | return None |
| 364 | except ValueError: |
| 365 | # ValueError is thrown if the field does not exist. We will handle that case in the getattr() below. |
| 366 | pass |
| 367 | |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 368 | return getattr(self._wrapped_class, name, *args, **kwargs) |
| 369 | |
| 370 | def __setattr__(self, name, value): |
Scott Baker | e72e761 | 2017-02-20 10:07:09 -0800 | [diff] [blame] | 371 | if name in self._fkmap.keys(): |
| 372 | self.fk_set(name, value) |
| 373 | elif name in self.__dict__: |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 374 | super(ORMWrapper, self).__setattr__(name, value) |
Scott Baker | 37cf9e2 | 2018-08-20 14:39:33 -0700 | [diff] [blame] | 375 | elif value is None: |
| 376 | # When handling requests, XOS interprets gRPC HasField(<fieldname>)==False to indicate that the caller |
| 377 | # has not set the field and wants it to continue to use its existing (or default) value. That leaves us |
| 378 | # with no easy way to support setting a field to None. |
| 379 | raise ValueError("Setting a non-foreignkey field to None is not supported") |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 380 | else: |
| 381 | setattr(self._wrapped_class, name, value) |
| 382 | |
| 383 | def __repr__(self): |
Scott Baker | d194097 | 2017-05-01 15:45:32 -0700 | [diff] [blame] | 384 | class_name = self._wrapped_class.__class__.__name__ |
| 385 | id = getattr(self._wrapped_class, "id", "noid") |
| 386 | name = getattr(self._wrapped_class, "name", None) |
| 387 | if name: |
| 388 | return "<%s: %s>" % (class_name, name) |
| 389 | else: |
| 390 | return "<%s: id-%s>" % (class_name, id) |
| 391 | |
| 392 | def __str__(self): |
| 393 | class_name = self._wrapped_class.__class__.__name__ |
| 394 | id = getattr(self._wrapped_class, "id", "noid") |
| 395 | name = getattr(self._wrapped_class, "name", None) |
| 396 | if name: |
| 397 | return name |
| 398 | else: |
| 399 | return "%s-%s" % (class_name, id) |
| 400 | |
| 401 | def dumpstr(self): |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 402 | return self._wrapped_class.__repr__() |
| 403 | |
Scott Baker | d194097 | 2017-05-01 15:45:32 -0700 | [diff] [blame] | 404 | def dump(self): |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 405 | print(self.dumpstr()) |
Scott Baker | d194097 | 2017-05-01 15:45:32 -0700 | [diff] [blame] | 406 | |
Scott Baker | e72e761 | 2017-02-20 10:07:09 -0800 | [diff] [blame] | 407 | def invalidate_cache(self, name=None): |
| 408 | if name: |
| 409 | if name in self.cache: |
| 410 | del self.cache[name] |
| 411 | if name in self.reverse_cache: |
| 412 | del self.reverse_cache[name] |
Scott Baker | e72e761 | 2017-02-20 10:07:09 -0800 | [diff] [blame] | 413 | else: |
| 414 | self.cache.clear() |
| 415 | self.reverse_cache.clear() |
Scott Baker | e72e761 | 2017-02-20 10:07:09 -0800 | [diff] [blame] | 416 | |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 417 | def save( |
| 418 | self, |
| 419 | update_fields=None, |
| 420 | always_update_timestamp=False, |
| 421 | is_sync_save=False, |
| 422 | is_policy_save=False, |
| 423 | ): |
Andy Bavier | 04ee191 | 2019-01-30 14:17:16 -0700 | [diff] [blame] | 424 | classname = self._wrapped_class.__class__.__name__ |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 425 | if self.is_new: |
Andy Bavier | 04ee191 | 2019-01-30 14:17:16 -0700 | [diff] [blame] | 426 | log.debug("save(): is new", classname=classname, syncstep=get_synchronizer_function()) |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 427 | new_class = self.stub.invoke( |
Andy Bavier | 04ee191 | 2019-01-30 14:17:16 -0700 | [diff] [blame] | 428 | "Create%s" % classname, self._wrapped_class |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 429 | ) |
| 430 | self._wrapped_class = new_class |
| 431 | self.is_new = False |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 432 | else: |
Andy Bavier | 04ee191 | 2019-01-30 14:17:16 -0700 | [diff] [blame] | 433 | if self.has_changed: |
| 434 | log.debug("save(): updated", classname=classname, changed_fields=self.changed_fields, syncstep=get_synchronizer_function()) |
| 435 | else: |
| 436 | log.debug("save(): no changes", classname=classname, syncstep=get_synchronizer_function()) |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 437 | metadata = [] |
| 438 | if update_fields: |
| 439 | metadata.append(("update_fields", ",".join(update_fields))) |
| 440 | if always_update_timestamp: |
| 441 | metadata.append(("always_update_timestamp", "1")) |
| 442 | if is_policy_save: |
| 443 | metadata.append(("is_policy_save", "1")) |
| 444 | if is_sync_save: |
| 445 | metadata.append(("is_sync_save", "1")) |
| 446 | self.stub.invoke( |
Andy Bavier | 04ee191 | 2019-01-30 14:17:16 -0700 | [diff] [blame] | 447 | "Update%s" % classname, |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 448 | self._wrapped_class, |
| 449 | metadata=metadata, |
| 450 | ) |
Scott Baker | c4156c3 | 2017-12-08 10:58:21 -0800 | [diff] [blame] | 451 | self.do_post_save_fixups() |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 452 | |
Scott Baker | 5b7fba0 | 2018-10-17 08:46:46 -0700 | [diff] [blame] | 453 | # Now that object has saved, reset our initial state for diff calculation |
| 454 | self.recompute_initial() |
| 455 | |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 456 | def delete(self): |
| 457 | id = self.stub.make_ID(id=self._wrapped_class.id) |
| 458 | self.stub.invoke("Delete%s" % self._wrapped_class.__class__.__name__, id) |
| 459 | |
Scott Baker | 22796cc | 2017-02-23 16:53:34 -0800 | [diff] [blame] | 460 | def tologdict(self): |
| 461 | try: |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 462 | d = {"model_name": self._wrapped_class.__class__.__name__, "pk": self.pk} |
| 463 | except BaseException: |
Scott Baker | 22796cc | 2017-02-23 16:53:34 -0800 | [diff] [blame] | 464 | d = {} |
| 465 | |
| 466 | return d |
| 467 | |
Scott Baker | bb81e15 | 2017-03-02 15:28:36 -0800 | [diff] [blame] | 468 | @property |
Scott Baker | ff104cc | 2017-08-14 15:24:41 -0700 | [diff] [blame] | 469 | def leaf_model(self): |
| 470 | # Easy case - this model is already the leaf |
| 471 | if self.leaf_model_name == self._wrapped_class.__class__.__name__: |
| 472 | return self |
| 473 | |
| 474 | # This model is not the leaf, so use the stub to fetch the leaf model |
| 475 | return getattr(self.stub, self.leaf_model_name).objects.get(id=self.id) |
| 476 | |
| 477 | @property |
Scott Baker | d2543ed | 2017-03-07 21:46:48 -0800 | [diff] [blame] | 478 | def model_name(self): |
| 479 | return self._wrapped_class.__class__.__name__ |
| 480 | |
| 481 | @property |
Scott Baker | bb81e15 | 2017-03-02 15:28:36 -0800 | [diff] [blame] | 482 | def ansible_tag(self): |
| 483 | return "%s_%s" % (self._wrapped_class.__class__.__name__, self.id) |
| 484 | |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 485 | |
Scott Baker | b05393b | 2017-03-01 14:59:55 -0800 | [diff] [blame] | 486 | class ORMQuerySet(list): |
| 487 | """ Makes lists look like django querysets """ |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 488 | |
Scott Baker | b05393b | 2017-03-01 14:59:55 -0800 | [diff] [blame] | 489 | def first(self): |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 490 | if len(self) > 0: |
Scott Baker | b05393b | 2017-03-01 14:59:55 -0800 | [diff] [blame] | 491 | return self[0] |
| 492 | else: |
| 493 | return None |
| 494 | |
Scott Baker | 8c7267d | 2017-03-14 19:34:13 -0700 | [diff] [blame] | 495 | def exists(self): |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 496 | return len(self) > 0 |
| 497 | |
Scott Baker | 8c7267d | 2017-03-14 19:34:13 -0700 | [diff] [blame] | 498 | |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 499 | class ORMLocalObjectManager(object): |
| 500 | """ Manages a local list of objects """ |
| 501 | |
Scott Baker | c59f1bc | 2017-12-04 16:55:05 -0800 | [diff] [blame] | 502 | def __init__(self, stub, modelName, idList, writeable): |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 503 | self._stub = stub |
| 504 | self._modelName = modelName |
| 505 | self._idList = idList |
Scott Baker | c59f1bc | 2017-12-04 16:55:05 -0800 | [diff] [blame] | 506 | self._writeable = writeable |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 507 | self._cache = None |
| 508 | |
| 509 | def resolve_queryset(self): |
| 510 | if self._cache is not None: |
| 511 | return self._cache |
| 512 | |
| 513 | models = [] |
| 514 | for id in self._idList: |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 515 | models.append( |
| 516 | self._stub.invoke("Get%s" % self._modelName, self._stub.make_ID(id=id)) |
| 517 | ) |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 518 | |
| 519 | self._cache = models |
| 520 | |
| 521 | return models |
| 522 | |
| 523 | def all(self): |
| 524 | models = self.resolve_queryset() |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 525 | return [make_ORMWrapper(x, self._stub) for x in models] |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 526 | |
Scott Baker | 8c7267d | 2017-03-14 19:34:13 -0700 | [diff] [blame] | 527 | def exists(self): |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 528 | return len(self._idList) > 0 |
Scott Baker | 8c7267d | 2017-03-14 19:34:13 -0700 | [diff] [blame] | 529 | |
Scott Baker | a1eae7a | 2017-06-06 09:20:15 -0700 | [diff] [blame] | 530 | def count(self): |
| 531 | return len(self._idList) |
| 532 | |
Scott Baker | 8c7267d | 2017-03-14 19:34:13 -0700 | [diff] [blame] | 533 | def first(self): |
| 534 | if self._idList: |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 535 | model = make_ORMWrapper( |
| 536 | self._stub.invoke( |
| 537 | "Get%s" % self._modelName, self._stub.make_ID(id=self._idList[0]) |
| 538 | ), |
| 539 | self._stub, |
| 540 | ) |
Scott Baker | 8c7267d | 2017-03-14 19:34:13 -0700 | [diff] [blame] | 541 | return model |
| 542 | else: |
| 543 | return None |
| 544 | |
Scott Baker | c59f1bc | 2017-12-04 16:55:05 -0800 | [diff] [blame] | 545 | def add(self, model): |
| 546 | if not self._writeable: |
| 547 | raise Exception("Only ManyToMany lists are writeable") |
| 548 | |
| 549 | if isinstance(model, int): |
| 550 | id = model |
| 551 | else: |
| 552 | if not model.id: |
| 553 | raise Exception("Model %s has no id" % model) |
| 554 | id = model.id |
| 555 | |
| 556 | self._idList.append(id) |
| 557 | |
| 558 | def remove(self, model): |
| 559 | if not self._writeable: |
| 560 | raise Exception("Only ManyToMany lists are writeable") |
| 561 | |
| 562 | if isinstance(model, int): |
| 563 | id = model |
| 564 | else: |
| 565 | if not model.id: |
| 566 | raise Exception("Model %s has no id" % model) |
| 567 | id = model.id |
| 568 | |
| 569 | self._idList.remove(id) |
| 570 | |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 571 | |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 572 | class ORMObjectManager(object): |
| 573 | """ Manages a remote list of objects """ |
| 574 | |
Scott Baker | ac2f2b5 | 2017-02-21 14:53:23 -0800 | [diff] [blame] | 575 | # constants better agree with common.proto |
Scott Baker | ea1f4d0 | 2018-12-17 10:21:50 -0800 | [diff] [blame] | 576 | DEFAULT = 0 |
| 577 | ALL = 1 |
Scott Baker | bae9d84 | 2017-03-21 10:44:10 -0700 | [diff] [blame] | 578 | SYNCHRONIZER_DIRTY_OBJECTS = 2 |
| 579 | SYNCHRONIZER_DELETED_OBJECTS = 3 |
| 580 | SYNCHRONIZER_DIRTY_POLICIES = 4 |
| 581 | SYNCHRONIZER_DELETED_POLICIES = 5 |
Scott Baker | ac2f2b5 | 2017-02-21 14:53:23 -0800 | [diff] [blame] | 582 | |
Scott Baker | ea1f4d0 | 2018-12-17 10:21:50 -0800 | [diff] [blame] | 583 | def __init__(self, stub, modelName, packageName, kind=0): |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 584 | self._stub = stub |
| 585 | self._modelName = modelName |
| 586 | self._packageName = packageName |
Scott Baker | ea1f4d0 | 2018-12-17 10:21:50 -0800 | [diff] [blame] | 587 | self._kind = kind |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 588 | |
| 589 | def wrap_single(self, obj): |
Scott Baker | 22796cc | 2017-02-23 16:53:34 -0800 | [diff] [blame] | 590 | return make_ORMWrapper(obj, self._stub) |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 591 | |
| 592 | def wrap_list(self, obj): |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 593 | result = [] |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 594 | for item in obj.items: |
Scott Baker | 22796cc | 2017-02-23 16:53:34 -0800 | [diff] [blame] | 595 | result.append(make_ORMWrapper(item, self._stub)) |
Scott Baker | b05393b | 2017-03-01 14:59:55 -0800 | [diff] [blame] | 596 | return ORMQuerySet(result) |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 597 | |
| 598 | def all(self): |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 599 | if self._kind == self.DEFAULT: |
| 600 | return self.wrap_list( |
| 601 | self._stub.invoke("List%s" % self._modelName, self._stub.make_empty()) |
| 602 | ) |
Scott Baker | ea1f4d0 | 2018-12-17 10:21:50 -0800 | [diff] [blame] | 603 | else: |
| 604 | return self.filter() |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 605 | |
Scott Baker | 22796cc | 2017-02-23 16:53:34 -0800 | [diff] [blame] | 606 | def first(self): |
Scott Baker | ea1f4d0 | 2018-12-17 10:21:50 -0800 | [diff] [blame] | 607 | objs = self.all() |
Scott Baker | 22796cc | 2017-02-23 16:53:34 -0800 | [diff] [blame] | 608 | if not objs: |
| 609 | return None |
| 610 | return objs[0] |
| 611 | |
Scott Baker | ac2f2b5 | 2017-02-21 14:53:23 -0800 | [diff] [blame] | 612 | def filter(self, **kwargs): |
| 613 | q = self._stub.make_Query() |
Scott Baker | ea1f4d0 | 2018-12-17 10:21:50 -0800 | [diff] [blame] | 614 | q.kind = self._kind |
Scott Baker | ac2f2b5 | 2017-02-21 14:53:23 -0800 | [diff] [blame] | 615 | |
| 616 | for (name, val) in kwargs.items(): |
| 617 | el = q.elements.add() |
| 618 | |
| 619 | if name.endswith("__gt"): |
| 620 | name = name[:-4] |
| 621 | el.operator = el.GREATER_THAN |
| 622 | elif name.endswith("__gte"): |
| 623 | name = name[:-5] |
| 624 | el.operator = el.GREATER_THAN_OR_EQUAL |
| 625 | elif name.endswith("__lt"): |
| 626 | name = name[:-4] |
| 627 | el.operator = el.LESS_THAN |
| 628 | elif name.endswith("__lte"): |
| 629 | name = name[:-5] |
| 630 | el.operator = el.LESS_THAN_OR_EQUAL |
Scott Baker | e1607b8 | 2018-09-20 14:10:59 -0700 | [diff] [blame] | 631 | elif name.endswith("__iexact"): |
| 632 | name = name[:-8] |
| 633 | el.operator = el.IEXACT |
Scott Baker | ac2f2b5 | 2017-02-21 14:53:23 -0800 | [diff] [blame] | 634 | else: |
| 635 | el.operator = el.EQUAL |
| 636 | |
| 637 | el.name = name |
| 638 | if isinstance(val, int): |
| 639 | el.iValue = val |
| 640 | else: |
| 641 | el.sValue = val |
| 642 | |
| 643 | return self.wrap_list(self._stub.invoke("Filter%s" % self._modelName, q)) |
| 644 | |
| 645 | def filter_special(self, kind): |
| 646 | q = self._stub.make_Query() |
| 647 | q.kind = kind |
| 648 | return self.wrap_list(self._stub.invoke("Filter%s" % self._modelName, q)) |
| 649 | |
Scott Baker | 22796cc | 2017-02-23 16:53:34 -0800 | [diff] [blame] | 650 | def get(self, **kwargs): |
| 651 | if kwargs.keys() == ["id"]: |
| 652 | # the fast and easy case, look it up by id |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 653 | return self.wrap_single( |
| 654 | self._stub.invoke( |
| 655 | "Get%s" % self._modelName, self._stub.make_ID(id=kwargs["id"]) |
| 656 | ) |
| 657 | ) |
Scott Baker | 22796cc | 2017-02-23 16:53:34 -0800 | [diff] [blame] | 658 | else: |
| 659 | # the slightly more difficult case, filter and return the first item |
| 660 | objs = self.filter(**kwargs) |
| 661 | return objs[0] |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 662 | |
| 663 | def new(self, **kwargs): |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 664 | if self._kind != ORMObjectManager.DEFAULT: |
| 665 | raise Exception( |
| 666 | "Creating objects is only supported by the DEFAULT object manager" |
| 667 | ) |
Scott Baker | ea1f4d0 | 2018-12-17 10:21:50 -0800 | [diff] [blame] | 668 | |
Scott Baker | aa556b0 | 2017-03-07 16:07:34 -0800 | [diff] [blame] | 669 | cls = self._stub.all_grpc_classes[self._modelName] |
Scott Baker | fe42a6f | 2017-03-18 09:11:31 -0700 | [diff] [blame] | 670 | o = make_ORMWrapper(cls(), self._stub, is_new=True) |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 671 | for (k, v) in kwargs.items(): |
Scott Baker | fe42a6f | 2017-03-18 09:11:31 -0700 | [diff] [blame] | 672 | setattr(o, k, v) |
Scott Baker | 5b7fba0 | 2018-10-17 08:46:46 -0700 | [diff] [blame] | 673 | o.recompute_initial() |
Scott Baker | fe42a6f | 2017-03-18 09:11:31 -0700 | [diff] [blame] | 674 | return o |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 675 | |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 676 | |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 677 | class ORMModelClass(object): |
| 678 | def __init__(self, stub, model_name, package_name): |
Scott Baker | 22796cc | 2017-02-23 16:53:34 -0800 | [diff] [blame] | 679 | self.model_name = model_name |
Scott Baker | aa556b0 | 2017-03-07 16:07:34 -0800 | [diff] [blame] | 680 | self._stub = stub |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 681 | self.objects = ORMObjectManager(stub, model_name, package_name) |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 682 | self.deleted_objects = ORMObjectManager( |
| 683 | stub, |
| 684 | model_name, |
| 685 | package_name, |
| 686 | ORMObjectManager.SYNCHRONIZER_DELETED_OBJECTS, |
| 687 | ) |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 688 | |
Scott Baker | bb81e15 | 2017-03-02 15:28:36 -0800 | [diff] [blame] | 689 | @property |
Scott Baker | 22796cc | 2017-02-23 16:53:34 -0800 | [diff] [blame] | 690 | def __name__(self): |
| 691 | return self.model_name |
| 692 | |
Scott Baker | aa556b0 | 2017-03-07 16:07:34 -0800 | [diff] [blame] | 693 | @property |
| 694 | def content_type_id(self): |
| 695 | return self._stub.reverse_content_type_map[self.model_name] |
| 696 | |
Scott Baker | 8a6d91f | 2017-03-22 11:23:11 -0700 | [diff] [blame] | 697 | def __call__(self, *args, **kwargs): |
| 698 | return self.objects.new(*args, **kwargs) |
| 699 | |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 700 | |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 701 | class ORMStub(object): |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 702 | def __init__( |
| 703 | self, |
| 704 | stub, |
| 705 | protos, |
| 706 | package_name, |
| 707 | invoker=None, |
| 708 | caller_kind="grpcapi", |
| 709 | empty=None, |
| 710 | enable_backoff=True, |
| 711 | restart_on_disconnect=False, |
| 712 | ): |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 713 | self.grpc_stub = stub |
Scott Baker | b96ba43 | 2018-02-26 09:53:48 -0800 | [diff] [blame] | 714 | self.protos = protos |
| 715 | self.common_protos = protos.common__pb2 |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 716 | self.all_model_names = [] |
Scott Baker | aa556b0 | 2017-03-07 16:07:34 -0800 | [diff] [blame] | 717 | self.all_grpc_classes = {} |
| 718 | self.content_type_map = {} |
| 719 | self.reverse_content_type_map = {} |
Scott Baker | ef8d85d | 2017-02-21 16:44:28 -0800 | [diff] [blame] | 720 | self.invoker = invoker |
Scott Baker | 22796cc | 2017-02-23 16:53:34 -0800 | [diff] [blame] | 721 | self.caller_kind = caller_kind |
Scott Baker | 500f8c7 | 2017-05-19 09:41:50 -0700 | [diff] [blame] | 722 | self.enable_backoff = enable_backoff |
Scott Baker | b06e3e0 | 2017-12-12 11:05:53 -0800 | [diff] [blame] | 723 | self.restart_on_disconnect = restart_on_disconnect |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 724 | |
Scott Baker | f0ee0dc | 2017-05-15 10:10:05 -0700 | [diff] [blame] | 725 | if not empty: |
Scott Baker | b96ba43 | 2018-02-26 09:53:48 -0800 | [diff] [blame] | 726 | empty = self.protos.google_dot_protobuf_dot_empty__pb2.Empty |
Scott Baker | f0ee0dc | 2017-05-15 10:10:05 -0700 | [diff] [blame] | 727 | self._empty = empty |
| 728 | |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 729 | for name in dir(stub): |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 730 | if name.startswith("Get"): |
| 731 | model_name = name[3:] |
| 732 | setattr(self, model_name, ORMModelClass(self, model_name, package_name)) |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 733 | |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 734 | self.all_model_names.append(model_name) |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 735 | |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 736 | grpc_class = getattr(self.protos, model_name) |
| 737 | self.all_grpc_classes[model_name] = grpc_class |
Scott Baker | aa556b0 | 2017-03-07 16:07:34 -0800 | [diff] [blame] | 738 | |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 739 | ct = grpc_class.DESCRIPTOR.GetOptions().Extensions._FindExtensionByName( |
| 740 | "xos.contentTypeId" |
| 741 | ) |
| 742 | if ct: |
| 743 | ct = grpc_class.DESCRIPTOR.GetOptions().Extensions[ct] |
| 744 | if ct: |
| 745 | self.content_type_map[ct] = model_name |
| 746 | self.reverse_content_type_map[model_name] = ct |
Scott Baker | aa556b0 | 2017-03-07 16:07:34 -0800 | [diff] [blame] | 747 | |
| 748 | def genericForeignKeyResolve(self, content_type_id, id): |
Scott Baker | d0f1dc1 | 2018-04-23 12:05:32 -0700 | [diff] [blame] | 749 | if content_type_id.endswith("_decl"): |
| 750 | content_type_id = content_type_id[:-5] |
| 751 | |
| 752 | if content_type_id not in self.content_type_map: |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 753 | raise ORMGenericContentNotFoundException( |
| 754 | "Content_type %s not found in self.content_type_map" % content_type_id |
| 755 | ) |
Scott Baker | d0f1dc1 | 2018-04-23 12:05:32 -0700 | [diff] [blame] | 756 | |
Scott Baker | aa556b0 | 2017-03-07 16:07:34 -0800 | [diff] [blame] | 757 | model_name = self.content_type_map[content_type_id] |
Scott Baker | d0f1dc1 | 2018-04-23 12:05:32 -0700 | [diff] [blame] | 758 | |
Scott Baker | aa556b0 | 2017-03-07 16:07:34 -0800 | [diff] [blame] | 759 | model = getattr(self, model_name) |
Scott Baker | d0f1dc1 | 2018-04-23 12:05:32 -0700 | [diff] [blame] | 760 | objs = model.objects.filter(id=id) |
| 761 | if not objs: |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 762 | raise ORMGenericObjectNotFoundException( |
| 763 | "Object %s of model %s was not found" % (id, model_name) |
| 764 | ) |
Scott Baker | d0f1dc1 | 2018-04-23 12:05:32 -0700 | [diff] [blame] | 765 | |
Scott Baker | aa556b0 | 2017-03-07 16:07:34 -0800 | [diff] [blame] | 766 | return model.objects.get(id=id) |
| 767 | |
Scott Baker | 22796cc | 2017-02-23 16:53:34 -0800 | [diff] [blame] | 768 | def add_default_metadata(self, metadata): |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 769 | default_metadata = [("caller_kind", self.caller_kind)] |
Scott Baker | 22796cc | 2017-02-23 16:53:34 -0800 | [diff] [blame] | 770 | |
Scott Baker | d824671 | 2018-07-12 18:08:31 -0700 | [diff] [blame] | 771 | # introspect to see if we're running from a synchronizer thread |
| 772 | if getattr(threading.current_thread(), "is_sync_thread", False): |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 773 | default_metadata.append(("is_sync_save", "1")) |
Scott Baker | d824671 | 2018-07-12 18:08:31 -0700 | [diff] [blame] | 774 | |
| 775 | # introspect to see if we're running from a model_policy thread |
| 776 | if getattr(threading.current_thread(), "is_policy_thread", False): |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 777 | default_metadata.append(("is_policy_save", "1")) |
Scott Baker | d824671 | 2018-07-12 18:08:31 -0700 | [diff] [blame] | 778 | |
Scott Baker | 22796cc | 2017-02-23 16:53:34 -0800 | [diff] [blame] | 779 | # build up a list of metadata keys we already have |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 780 | md_keys = [x[0] for x in metadata] |
Scott Baker | 22796cc | 2017-02-23 16:53:34 -0800 | [diff] [blame] | 781 | |
| 782 | # add any defaults that we don't already have |
| 783 | for md in default_metadata: |
| 784 | if md[0] not in md_keys: |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 785 | metadata.append((md[0], md[1])) |
Scott Baker | 22796cc | 2017-02-23 16:53:34 -0800 | [diff] [blame] | 786 | |
Scott Baker | 57c7482 | 2017-02-23 11:13:04 -0800 | [diff] [blame] | 787 | def invoke(self, name, request, metadata=[]): |
Scott Baker | 22796cc | 2017-02-23 16:53:34 -0800 | [diff] [blame] | 788 | self.add_default_metadata(metadata) |
| 789 | |
Scott Baker | ef8d85d | 2017-02-21 16:44:28 -0800 | [diff] [blame] | 790 | if self.invoker: |
| 791 | # Hook in place to call Chameleon's invoke method, as soon as we |
| 792 | # have rewritten the synchronizer to use reactor. |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 793 | return self.invoker.invoke( |
| 794 | self.grpc_stub.__class__, name, request, metadata={} |
| 795 | ).result[0] |
Scott Baker | 500f8c7 | 2017-05-19 09:41:50 -0700 | [diff] [blame] | 796 | elif self.enable_backoff: |
Scott Baker | ef8d85d | 2017-02-21 16:44:28 -0800 | [diff] [blame] | 797 | # Our own retry mechanism. This works fine if there is a temporary |
| 798 | # failure in connectivity, but does not re-download gRPC schema. |
Scott Baker | 500f8c7 | 2017-05-19 09:41:50 -0700 | [diff] [blame] | 799 | import grpc |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 800 | |
Scott Baker | b06e3e0 | 2017-12-12 11:05:53 -0800 | [diff] [blame] | 801 | backoff = [0.5, 1, 2, 4, 8] |
Scott Baker | ef8d85d | 2017-02-21 16:44:28 -0800 | [diff] [blame] | 802 | while True: |
Scott Baker | ef8d85d | 2017-02-21 16:44:28 -0800 | [diff] [blame] | 803 | try: |
| 804 | method = getattr(self.grpc_stub, name) |
Scott Baker | 57c7482 | 2017-02-23 11:13:04 -0800 | [diff] [blame] | 805 | return method(request, metadata=metadata) |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 806 | except grpc._channel._Rendezvous as e: |
Scott Baker | ef8d85d | 2017-02-21 16:44:28 -0800 | [diff] [blame] | 807 | code = e.code() |
| 808 | if code == grpc.StatusCode.UNAVAILABLE: |
Scott Baker | b06e3e0 | 2017-12-12 11:05:53 -0800 | [diff] [blame] | 809 | if self.restart_on_disconnect: |
| 810 | # This is a blunt technique... We lost connectivity to the core, and we don't know that |
| 811 | # the core is still serving up the same models it was when we established connectivity, |
| 812 | # so restart the synchronizer. |
| 813 | # TODO: Hash check on the core models to tell if something changed would be better. |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 814 | os.execv(sys.executable, ["python"] + sys.argv) |
Scott Baker | ef8d85d | 2017-02-21 16:44:28 -0800 | [diff] [blame] | 815 | if not backoff: |
| 816 | raise Exception("No more retries on %s" % name) |
| 817 | time.sleep(backoff.pop(0)) |
| 818 | else: |
| 819 | raise |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 820 | except BaseException: |
Scott Baker | ef8d85d | 2017-02-21 16:44:28 -0800 | [diff] [blame] | 821 | raise |
Scott Baker | 500f8c7 | 2017-05-19 09:41:50 -0700 | [diff] [blame] | 822 | else: |
| 823 | method = getattr(self.grpc_stub, name) |
| 824 | return method(request, metadata=metadata) |
| 825 | |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 826 | def make_ID(self, id): |
Scott Baker | b96ba43 | 2018-02-26 09:53:48 -0800 | [diff] [blame] | 827 | return getattr(self.common_protos, "ID")(id=id) |
Scott Baker | f0ee0dc | 2017-05-15 10:10:05 -0700 | [diff] [blame] | 828 | |
| 829 | def make_empty(self): |
| 830 | return self._empty() |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 831 | |
Scott Baker | ac2f2b5 | 2017-02-21 14:53:23 -0800 | [diff] [blame] | 832 | def make_Query(self): |
Scott Baker | b96ba43 | 2018-02-26 09:53:48 -0800 | [diff] [blame] | 833 | return getattr(self.common_protos, "Query")() |
Scott Baker | ac2f2b5 | 2017-02-21 14:53:23 -0800 | [diff] [blame] | 834 | |
Scott Baker | f6145a2 | 2017-03-29 14:50:25 -0700 | [diff] [blame] | 835 | def listObjects(self): |
| 836 | return self.all_model_names |
| 837 | |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 838 | |
Scott Baker | 22796cc | 2017-02-23 16:53:34 -0800 | [diff] [blame] | 839 | def register_convenience_wrapper(class_name, wrapper): |
| 840 | global convenience_wrappers |
Scott Baker | 96b995a | 2017-02-15 16:21:12 -0800 | [diff] [blame] | 841 | |
Scott Baker | 22796cc | 2017-02-23 16:53:34 -0800 | [diff] [blame] | 842 | convenience_wrappers[class_name] = wrapper |
| 843 | |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 844 | |
Scott Baker | 22796cc | 2017-02-23 16:53:34 -0800 | [diff] [blame] | 845 | def make_ORMWrapper(wrapped_class, *args, **kwargs): |
Scott Baker | 2f314d5 | 2018-08-24 08:31:19 -0700 | [diff] [blame] | 846 | cls = None |
| 847 | |
| 848 | if (not cls) and wrapped_class.__class__.__name__ in convenience_wrappers: |
Scott Baker | 22796cc | 2017-02-23 16:53:34 -0800 | [diff] [blame] | 849 | cls = convenience_wrappers[wrapped_class.__class__.__name__] |
Scott Baker | 2f314d5 | 2018-08-24 08:31:19 -0700 | [diff] [blame] | 850 | |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 851 | if not cls: |
Scott Baker | 2f314d5 | 2018-08-24 08:31:19 -0700 | [diff] [blame] | 852 | # Search the list of class names for this model to see if we have any applicable wrappers. The list is always |
| 853 | # sorted from most specific to least specific, so the first one we find will automatically be the most relevant |
| 854 | # one. If we don't find any, then default to ORMWrapper |
| 855 | |
| 856 | # Note: Only works on objects that have been fetched from the server, not objects that are created on the |
| 857 | # client. This is because wrapped_class.class_names is filled in by the server. |
| 858 | |
| 859 | # TODO(smbaker): Ought to be able to make this work with newly created objects after they are saved. |
| 860 | |
| 861 | for name in wrapped_class.class_names.split(","): |
| 862 | if name in convenience_wrappers: |
| 863 | cls = convenience_wrappers[name] |
| 864 | |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 865 | if not cls: |
Scott Baker | 22796cc | 2017-02-23 16:53:34 -0800 | [diff] [blame] | 866 | cls = ORMWrapper |
| 867 | |
| 868 | return cls(wrapped_class, *args, **kwargs) |
| 869 | |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 870 | |
Matteo Scandolo | 10a2f3c | 2018-04-20 16:59:38 +0200 | [diff] [blame] | 871 | def import_convenience_methods(): |
| 872 | |
| 873 | log.info("Loading convenience methods") |
| 874 | |
| 875 | cwd = os.path.abspath(os.path.dirname(os.path.realpath(__file__))) |
| 876 | api_convenience_dir = os.path.join(cwd, "convenience") |
| 877 | for file in os.listdir(api_convenience_dir): |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 878 | if file.endswith(".py") and "test" not in file: |
Matteo Scandolo | 10a2f3c | 2018-04-20 16:59:38 +0200 | [diff] [blame] | 879 | pathname = os.path.join(api_convenience_dir, file) |
| 880 | try: |
| 881 | log.debug("Loading: %s" % file) |
| 882 | imp.load_source(file[:-3], pathname) |
Zack Williams | 045b63d | 2019-01-22 16:30:57 -0700 | [diff] [blame] | 883 | except Exception: |
| 884 | log.exception( |
| 885 | "Cannot import api convenience method for: %s, %s" |
| 886 | % (file[:-3], pathname) |
| 887 | ) |