• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2020 The Chromium Authors
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4"""Class for managing multiple SkiaGoldSessions."""
5
6import json
7import tempfile
8from typing import Dict, Optional, Type, Union
9
10from skia_gold_common import output_managerless_skia_gold_session
11from skia_gold_common import skia_gold_properties
12from skia_gold_common import skia_gold_session
13
14KeysInputType = Union[dict, str]
15# {
16#   instance: {
17#     corpus: {
18#       keys_string: SkiaGoldSession,
19#     },
20#   },
21# }
22SessionMapType = Dict[str, Dict[str, Dict[str,
23                                          skia_gold_session.SkiaGoldSession]]]
24
25
26class SkiaGoldSessionManager():
27  def __init__(self, working_dir: str,
28               gold_properties: skia_gold_properties.SkiaGoldProperties):
29    """Class to manage one or more skia_gold_session.SkiaGoldSessions.
30
31    A separate session is required for each instance/corpus/keys_file
32    combination, so this class will lazily create them as necessary.
33
34    The base implementation is usable on its own, but is meant to be overridden
35    as necessary.
36
37    Args:
38      working_dir: The working directory under which each individual
39          SkiaGoldSessions' working directory will be created.
40      gold_properties: A SkiaGoldProperties instance that will be used to create
41          any SkiaGoldSessions.
42    """
43    self._working_dir = working_dir
44    self._gold_properties = gold_properties
45    self._sessions: SessionMapType = {}
46
47  def GetSkiaGoldSession(
48      self,
49      keys_input: KeysInputType,
50      corpus: Optional[str] = None,
51      instance: Optional[str] = None,
52      bucket: Optional[str] = None) -> skia_gold_session.SkiaGoldSession:
53    """Gets a SkiaGoldSession for the given arguments.
54
55    Lazily creates one if necessary.
56
57    Args:
58      keys_input: A way of retrieving various comparison config data such as
59          corpus and debug information like the hardware/software configuration
60          the image was produced on. Can be either a dict or a filepath to a
61          file containing JSON to read.
62      corpus: A string containing the corpus the session is for. If None, the
63          corpus will be determined using available information.
64      instance: The name of the Skia Gold instance to interact with. If None,
65          will use whatever default the subclass sets.
66      bucket: Overrides the formulaic Google Storage bucket name generated by
67          goldctl
68    """
69    instance = instance or self._GetDefaultInstance()
70    keys_dict = _GetKeysAsDict(keys_input)
71    keys_string = json.dumps(keys_dict, sort_keys=True)
72    if corpus is None:
73      corpus = keys_dict.get('source_type', instance)
74    # Use the string representation of the keys JSON as a proxy for a hash since
75    # dicts themselves are not hashable.
76    session = self._sessions.setdefault(instance,
77                                        {}).setdefault(corpus, {}).setdefault(
78                                            keys_string, None)
79    if not session:
80      working_dir = tempfile.mkdtemp(dir=self._working_dir)
81      keys_file = _GetKeysAsJson(keys_input, working_dir)
82      session = self.GetSessionClass()(working_dir, self._gold_properties,
83                                       keys_file, corpus, instance, bucket)
84      self._sessions[instance][corpus][keys_string] = session
85    return session
86
87  @staticmethod
88  def _GetDefaultInstance() -> str:
89    """Gets the default Skia Gold instance.
90
91    Returns:
92      A string containing the default instance.
93    """
94    return 'chrome'
95
96  @staticmethod
97  def GetSessionClass() -> Type[skia_gold_session.SkiaGoldSession]:
98    """Gets the SkiaGoldSession class to use for session creation.
99
100    Returns:
101      A reference to a SkiaGoldSession class.
102    """
103    return output_managerless_skia_gold_session.OutputManagerlessSkiaGoldSession
104
105
106def _GetKeysAsDict(keys_input: KeysInputType) -> dict:
107  """Converts |keys_input| into a dictionary.
108
109  Args:
110    keys_input: A dictionary or a string pointing to a JSON file. The contents
111        of either should be Skia Gold config data.
112
113  Returns:
114    A dictionary containing the Skia Gold config data.
115  """
116  if isinstance(keys_input, dict):
117    return keys_input
118  assert isinstance(keys_input, str)
119  with open(keys_input) as f:
120    return json.load(f)
121
122
123def _GetKeysAsJson(keys_input: KeysInputType, session_work_dir: str) -> str:
124  """Converts |keys_input| into a JSON file on disk.
125
126  Args:
127    keys_input: A dictionary or a string pointing to a JSON file. The contents
128        of either should be Skia Gold config data.
129    session_work_dir: The working directory under which each individual
130        SkiaGoldSessions' working directory will be created.
131
132  Returns:
133    A string containing a filepath to a JSON file with containing |keys_input|'s
134    data.
135  """
136  if isinstance(keys_input, str):
137    return keys_input
138  assert isinstance(keys_input, dict)
139  keys_file = tempfile.NamedTemporaryFile(suffix='.json',
140                                          dir=session_work_dir,
141                                          delete=False).name
142  with open(keys_file, 'w') as f:
143    json.dump(keys_input, f)
144  return keys_file
145