desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Initialize a connection to the back-end OpenStack APIs. The expected url is http://192.168.2.12:8773/services/Cloud Args: parameters: A dictionary containing the \'credentials\' parameter. Returns: An instance of Boto EC2Connection.'
def open_connection(self, parameters):
credentials = parameters[self.PARAM_CREDENTIALS] region_str = self.DEFAULT_REGION access_key = str(credentials['EC2_ACCESS_KEY']) secret_key = str(credentials['EC2_SECRET_KEY']) ec2_url = str(credentials['EC2_URL']) result = urlparse(ec2_url) if ((result.port is None) or (result.hostname is ...
'Create a new InfrastructureManager instance. This constructor accepts an optional boolean parameter which decides whether the InfrastructureManager instance should operate in blocking mode or not. A blocking InfrastructureManager does not return until each requested run/terminate operation is complete. This mode is us...
def __init__(self, params=None, blocking=False):
self.blocking = blocking self.secret = utils.get_secret() self.agent_factory = InfrastructureAgentFactory() if (params is not None): store_factory = PersistentStoreFactory() store = store_factory.create_store(params) self.reservations = PersistentDictionary(store) else: ...
'Query the InfrastructureManager instance for details regarding a set of virtual machines spawned in the past. This method accepts a dictionary of parameters and a secret for authentication purposes. The dictionary of parameters must include a \'reservation_id\' parameter which is used to reference past virtual machine...
def describe_instances(self, parameters, secret):
(parameters, secret) = self.__validate_args(parameters, secret) if (self.secret != secret): return self.__generate_response(False, self.REASON_BAD_SECRET) for param in self.DESCRIBE_INSTANCES_REQUIRED_PARAMS: if (not utils.has_parameter(param, parameters)): return self.__generate...
'Start a new virtual machine deployment using the provided parameters. The input parameter set must include an \'infrastructure\' parameter which indicates the exact cloud environment to use. Value of this parameter will be used to instantiate a cloud environment specific agent which knows how to interact with the spec...
def run_instances(self, parameters, secret):
(parameters, secret) = self.__validate_args(parameters, secret) utils.log('Received a request to run instances.') if (self.secret != secret): utils.log('Incoming secret {0} does not match the current secret {1} - Rejecting request.'.format(secret, s...
'Terminate a group of virtual machines using the provided parameters. The input parameter map must contain an \'infrastructure\' parameter which will be used to instantiate a suitable cloud agent. Any additional environment specific parameters should also be available in the same map. If this InfrastructureManager inst...
def terminate_instances(self, parameters, secret):
(parameters, secret) = self.__validate_args(parameters, secret) if (self.secret != secret): return self.__generate_response(False, self.REASON_BAD_SECRET) for param in self.TERMINATE_INSTANCES_REQUIRED_PARAMS: if (not utils.has_parameter(param, parameters)): return self.__generat...
'Contacts the infrastructure named in \'parameters\' and tells it to attach a persistent disk to this machine. Args: parameters: A dict containing the credentials necessary to send requests to the underlying cloud infrastructure. disk_name: A str corresponding to the name of the persistent disk that should be attached ...
def attach_disk(self, parameters, disk_name, instance_id, secret):
(parameters, secret) = self.__validate_args(parameters, secret) if (self.secret != secret): return self.__generate_response(False, self.REASON_BAD_SECRET) infrastructure = parameters[self.PARAM_INFRASTRUCTURE] agent = self.agent_factory.create_agent(infrastructure) disk_location = agent.atta...
'Private method for starting a set of VMs Args: agent Infrastructure agent in charge of current operation num_vms No. of VMs to be spawned parameters A dictionary of parameters reservation_id Reservation ID of the current run request'
def __spawn_vms(self, agent, num_vms, parameters, reservation_id):
status_info = self.reservations.get(reservation_id) try: security_configured = agent.configure_instance_security(parameters) instance_info = agent.run_instances(num_vms, parameters, security_configured, public_ip_needed=False) ids = instance_info[0] public_ips = instance_info[1] ...
'Private method for stopping a set of VMs Args: agent Infrastructure agent in charge of current operation parameters A dictionary of parameters'
def __kill_vms(self, agent, parameters):
agent.terminate_instances(parameters)
'Generate an infrastructure manager service response Args: status A boolean value indicating the status msg A reason message (useful if this a failed operation) extra Any extra fields to be included in the response (Optional) Returns: A dictionary containing the operation response'
def __generate_response(self, status, msg, extra=None):
utils.log('Sending success = {0}, reason = {1}'.format(status, msg)) response = {'success': status, 'reason': msg} if (extra is not None): for (key, value) in extra.items(): response[key] = value return response
'Validate the arguments provided by user. Args: parameters A dictionary (or a JSON string) provided by the client secret Secret sent by the client Returns: Processed user arguments Raises TypeError If at least one user argument is not of the current type'
def __validate_args(self, parameters, secret):
if ((type(parameters) != type('')) and (type(parameters) != type({}))): raise TypeError('Invalid data type for parameters. Must be a JSON string or a dictionary.') elif (type(secret) != type('')): raise TypeError('Invalid data type for secret. M...
'Discovers CPU usage on this node. Args: secret: The secret of the deployment; used for authentication. Returns: A dictionary containing the idle, system and user percentages.'
def get_cpu_usage(self, secret):
if (self.secret != secret): return self.__generate_response(False, InfrastructureManager.REASON_BAD_SECRET) cpu_stats = psutil.cpu_times_percent(percpu=False) cpu_stats_dict = {JSONTags.CPU: {JSONTags.IDLE: cpu_stats.idle, JSONTags.SYSTEM: cpu_stats.system, JSONTags.USER: cpu_stats.user, JSONTags.CO...
'Discovers disk usage per mount point on this node. Args: secret: The secret of the deployment; used for authentication. Returns: A dictionary containing free bytes and bytes used per disk partition.'
def get_disk_usage(self, secret):
if (self.secret != secret): return self.__generate_response(False, InfrastructureManager.REASON_BAD_SECRET) inner_disk_stats_dict = [] for partition in psutil.disk_partitions(): if (partition.mountpoint not in MOUNTPOINT_WHITELIST): continue disk_stats = psutil.disk_usage...
'Discovers memory usage on this node. Args: secret: The secret of the deployment; used for authentication. Returns: A dictionary containing memory bytes available and used.'
def get_memory_usage(self, secret):
if (self.secret != secret): return self.__generate_response(False, InfrastructureManager.REASON_BAD_SECRET) mem_stats = psutil.virtual_memory() mem_stats_dict = {JSONTags.MEMORY: {JSONTags.TOTAL: mem_stats.total, JSONTags.AVAILABLE: mem_stats.available, JSONTags.USED: mem_stats.used}} logging.de...
'Retrieves Monit\'s summary on this node. Args: secret: The secret of the deployment; used for authentication. Returns: A dictionary containing Monit\'s summary as a string.'
def get_service_summary(self, secret):
if (self.secret != secret): return self.__generate_response(False, InfrastructureManager.REASON_BAD_SECRET) monit_stats = subprocess.check_output(['monit', 'summary']) monit_stats_dict = {} for line in monit_stats.split('\n'): tokens = line.split() if ('Process' in tokens): ...
'Discovers swap usage on this node. Args: secret: The secret of the deployment; used for authentication. Returns: A dictionary containing free bytes and bytes used for swap.'
def get_swap_usage(self, secret):
if (self.secret != secret): return self.__generate_response(False, InfrastructureManager.REASON_BAD_SECRET) swap_stats = psutil.swap_memory() swap_stats_dict = {JSONTags.SWAP: {JSONTags.FREE: swap_stats.free, JSONTags.USED: swap_stats.used}} logging.debug('Swap stats: {}'.format(swap_stats...
'Returns info from /proc/loadavg. See `man proc` for more details. Args: secret: The secret of the deployment; used for authentication. Returns: A dictionary containing average load for last 1, 5 and 15 minutes, and information about running and scheduled entities, and PID of the most recently added process.'
def get_loadavg(self, secret):
if (self.secret != secret): return self.__generate_response(False, InfrastructureManager.REASON_BAD_SECRET) with open('/proc/loadavg') as loadavg: loadavg = loadavg.read().split() kernel_entities = loadavg[3].split('/') loadavg_stat = {JSONTags.LOADAVG: {JSONTags.LAST_1_MIN: float(loadav...
'Generate a system manager service response Args: success: A boolean value indicating the success status. message: A str, the reason of failure. Returns: A dictionary containing the operation response.'
def __generate_response(self, success, message):
response = 'Sending success = {0}, reason = {1}'.format(success, message) if success: logging.debug(response) else: logging.warn(response) return {'success': success, 'reason': message}
'Create a new instance with an optional persistent backing store. If no backing store is provided, this instance will behave as a regular in-memory dictionary. If however a PersistentStore is provided as an argument, the created dictionary will write through all its updates to the specified store. Args: store An inst...
def __init__(self, store=None):
self.store = store if (store is not None): self.dictionary = store.get_all_entries() else: self.dictionary = {}
'Insert the specified key-value pair to the dictionary. If this instance of PersistentDictionary is backed by an instance of PersistentStore, the inserted entry will also be written to that store. Args: key Key of the entry value Value of the entry'
def put(self, key, value):
self.dictionary[key] = value if (self.store is not None): self.store.save_all_entries(self.dictionary)
'Retrieve the value of the specified key from the dictionary. Args: key Key of the entry Returns: Value of the entry if the key exists in the map Raises: KeyError If the specified key does not exist in the dictionary'
def get(self, key):
return self.dictionary[key]
'Checks whether the specified key exists in the dictionary. Args: key Key of the entry Returns: True if the key exists and False otherwise.'
def has_key(self, key):
return self.dictionary.has_key(key)
'Read all the dictionary entries from the persistent store and return as a dictionary. If there are no entries in the underlying store, returns an empty dictionary. Returns: A dictionary of key-value pairs (possibly empty)'
def get_all_entries(self):
raise NotImplementedError
'Save the contents of the given dictionary to the data store, thereby overwriting any previous content. Args: dict A dictionary of key-value pairs'
def save_all_entries(self, dictionary):
raise NotImplementedError
'Instantiate a new PersistentStore instance using the provided arguments. Arguments: parameters Any additional parameters required to create the PersistentStore instance. This map must at least contain PARAM_STORE_TYPE. Returns: A PersistentStore instance Raises: NameError If the type name provided is invalid'
def create_store(self, parameters):
store_type = parameters[self.PARAM_STORE_TYPE] if (store_type == 'file'): return FileSystemBasedPersistentStore(parameters) else: raise NameError('Unrecognized persistent store type')
'Create a new instance of the persistent store. Args: parameters A dictionary containing the PARAM_FILE_PATH entry'
def __init__(self, parameters):
self.file_path = parameters[self.PARAM_FILE_PATH] self.lock = Lock()
'See parent class documentation'
def get_all_entries(self):
self.lock.acquire() if os.path.exists(self.file_path): with open(self.file_path) as file_handle: dictionary = json.load(file_handle) self.lock.release() return dictionary else: self.lock.release() return {}
'See parent class documentation'
def save_all_entries(self, dictionary):
self.lock.acquire() with open(self.file_path, 'w') as file_handle: json.dump(dictionary, file_handle) self.lock.release()
'Creates a message service class. Args: name: Name of the class (ignored, but required by the metaclass protocol). bases: Base classes of the class being constructed. dictionary: The class dictionary of the class being constructed. dictionary[_DESCRIPTOR_KEY] must contain a ServiceDescriptor object describing this prot...
def __init__(cls, name, bases, dictionary):
if (GeneratedServiceType._DESCRIPTOR_KEY not in dictionary): return descriptor = dictionary[GeneratedServiceType._DESCRIPTOR_KEY] service_builder = _ServiceBuilder(descriptor) service_builder.BuildService(cls)
'Creates a message service stub class. Args: name: Name of the class (ignored, here). bases: Base classes of the class being constructed. dictionary: The class dictionary of the class being constructed. dictionary[_DESCRIPTOR_KEY] must contain a ServiceDescriptor object describing this protocol service type.'
def __init__(cls, name, bases, dictionary):
super(GeneratedServiceStubType, cls).__init__(name, bases, dictionary) if (GeneratedServiceStubType._DESCRIPTOR_KEY not in dictionary): return descriptor = dictionary[GeneratedServiceStubType._DESCRIPTOR_KEY] service_stub_builder = _ServiceStubBuilder(descriptor) service_stub_builder.BuildSe...
'Initializes an instance of the service class builder. Args: service_descriptor: ServiceDescriptor to use when constructing the service class.'
def __init__(self, service_descriptor):
self.descriptor = service_descriptor
'Constructs the service class. Args: cls: The class that will be constructed.'
def BuildService(self, cls):
def _WrapCallMethod(srvc, method_descriptor, rpc_controller, request, callback): return self._CallMethod(srvc, method_descriptor, rpc_controller, request, callback) self.cls = cls cls.CallMethod = _WrapCallMethod cls.GetDescriptor = staticmethod((lambda : self.descriptor)) cls.GetDescriptor....
'Calls the method described by a given method descriptor. Args: srvc: Instance of the service for which this method is called. method_descriptor: Descriptor that represent the method to call. rpc_controller: RPC controller to use for this method\'s execution. request: Request protocol message. callback: A callback to i...
def _CallMethod(self, srvc, method_descriptor, rpc_controller, request, callback):
if (method_descriptor.containing_service != self.descriptor): raise RuntimeError('CallMethod() given method descriptor for wrong service type.') method = getattr(srvc, method_descriptor.name) return method(rpc_controller, request, callback)
'Returns the class of the request protocol message. Args: method_descriptor: Descriptor of the method for which to return the request protocol message class. Returns: A class that represents the input protocol message of the specified method.'
def _GetRequestClass(self, method_descriptor):
if (method_descriptor.containing_service != self.descriptor): raise RuntimeError('GetRequestClass() given method descriptor for wrong service type.') return method_descriptor.input_type._concrete_class
'Returns the class of the response protocol message. Args: method_descriptor: Descriptor of the method for which to return the response protocol message class. Returns: A class that represents the output protocol message of the specified method.'
def _GetResponseClass(self, method_descriptor):
if (method_descriptor.containing_service != self.descriptor): raise RuntimeError('GetResponseClass() given method descriptor for wrong service type.') return method_descriptor.output_type._concrete_class
'Generates and returns a method that can be set for a service methods. Args: method: Descriptor of the service method for which a method is to be generated. Returns: A method that can be added to the service class.'
def _GenerateNonImplementedMethod(self, method):
return (lambda inst, rpc_controller, request, callback: self._NonImplementedMethod(method.name, rpc_controller, callback))
'The body of all methods in the generated service class. Args: method_name: Name of the method being executed. rpc_controller: RPC controller used to execute this method. callback: A callback which will be invoked when the method finishes.'
def _NonImplementedMethod(self, method_name, rpc_controller, callback):
rpc_controller.SetFailed(('Method %s not implemented.' % method_name)) callback(None)
'Initializes an instance of the service stub class builder. Args: service_descriptor: ServiceDescriptor to use when constructing the stub class.'
def __init__(self, service_descriptor):
self.descriptor = service_descriptor
'Constructs the stub class. Args: cls: The class that will be constructed.'
def BuildServiceStub(self, cls):
def _ServiceStubInit(stub, rpc_channel): stub.rpc_channel = rpc_channel self.cls = cls cls.__init__ = _ServiceStubInit for method in self.descriptor.methods: setattr(cls, method.name, self._GenerateStubMethod(method))
'The body of all service methods in the generated stub class. Args: stub: Stub instance. method_descriptor: Descriptor of the invoked method. rpc_controller: Rpc controller to execute the method. request: Request protocol message. callback: A callback to execute when the method finishes. Returns: Response message (in c...
def _StubMethod(self, stub, method_descriptor, rpc_controller, request, callback):
return stub.rpc_channel.CallMethod(method_descriptor, rpc_controller, request, method_descriptor.output_type._concrete_class, callback)
'Retrieves this service\'s descriptor.'
def GetDescriptor():
raise NotImplementedError
'Calls a method of the service specified by method_descriptor. If "done" is None then the call is blocking and the response message will be returned directly. Otherwise the call is asynchronous and "done" will later be called with the response value. In the blocking case, RpcException will be raised on error. Precondi...
def CallMethod(self, method_descriptor, rpc_controller, request, done):
raise NotImplementedError
'Returns the class of the request message for the specified method. CallMethod() requires that the request is of a particular subclass of Message. GetRequestClass() gets the default instance of this required type. Example: method = service.GetDescriptor().FindMethodByName("Foo") request = stub.GetRequestClass(method)()...
def GetRequestClass(self, method_descriptor):
raise NotImplementedError
'Returns the class of the response message for the specified method. This method isn\'t really needed, as the RpcChannel\'s CallMethod constructs the response protocol message. It\'s provided anyway in case it is useful for the caller to know the response type in advance.'
def GetResponseClass(self, method_descriptor):
raise NotImplementedError
'Resets the RpcController to its initial state. After the RpcController has been reset, it may be reused in a new call. Must not be called while an RPC is in progress.'
def Reset(self):
raise NotImplementedError
'Returns true if the call failed. After a call has finished, returns true if the call failed. The possible reasons for failure depend on the RPC implementation. Failed() must not be called before a call has finished. If Failed() returns true, the contents of the response message are undefined.'
def Failed(self):
raise NotImplementedError
'If Failed is true, returns a human-readable description of the error.'
def ErrorText(self):
raise NotImplementedError
'Initiate cancellation. Advises the RPC system that the caller desires that the RPC call be canceled. The RPC system may cancel it immediately, may wait awhile and then cancel it, or may not even cancel the call at all. If the call is canceled, the "done" callback will still be called and the RpcController will indic...
def StartCancel(self):
raise NotImplementedError
'Sets a failure reason. Causes Failed() to return true on the client side. "reason" will be incorporated into the message returned by ErrorText(). If you find you need to return machine-readable information about failures, you should incorporate it into your response protocol buffer and should NOT call SetFailed().'
def SetFailed(self, reason):
raise NotImplementedError
'Checks if the client cancelled the RPC. If true, indicates that the client canceled the RPC, so the server may as well give up on replying to it. The server should still call the final "done" callback.'
def IsCanceled(self):
raise NotImplementedError
'Sets a callback to invoke on cancel. Asks that the given callback be called when the RPC is canceled. The callback will always be called exactly once. If the RPC completes without being canceled, the callback will be called after completion. If the RPC has already been canceled when NotifyOnCancel() is called, the ...
def NotifyOnCancel(self, callback):
raise NotImplementedError
'Calls the method identified by the descriptor. Call the given method of the remote service. The signature of this procedure looks the same as Service.CallMethod(), but the requirements are less strict in one important way: the request object doesn\'t have to be of any specific class as long as its descriptor is meth...
def CallMethod(self, method_descriptor, rpc_controller, request, response_class, done):
raise NotImplementedError
'Initialize the descriptor given its options message and the name of the class of the options message. The name of the class is required in case the options message is None and has to be created.'
def __init__(self, options, options_class_name):
self._options = options self._options_class_name = options_class_name self.has_options = (options is not None)
'Sets the descriptor\'s options This function is used in generated proto2 files to update descriptor options. It must not be used outside proto2.'
def _SetOptions(self, options, options_class_name):
self._options = options self._options_class_name = options_class_name self.has_options = (options is not None)
'Retrieves descriptor options. This method returns the options set or creates the default options for the descriptor.'
def GetOptions(self):
if self._options: return self._options from google.net.proto2.proto import descriptor_pb2 try: options_class = getattr(descriptor_pb2, self._options_class_name) except AttributeError: raise RuntimeError(('Unknown options class name %s!' % self._options_class_name)) ...
'Constructor. Args: options: Protocol message options or None to use default message options. options_class_name: (str) The class name of the above options. name: (str) Name of this protocol message type. full_name: (str) Fully-qualified name of this protocol message type, which will include protocol "package" name and...
def __init__(self, options, options_class_name, name, full_name, file, containing_type, serialized_start=None, serialized_end=None):
super(_NestedDescriptorBase, self).__init__(options, options_class_name) self.name = name self.full_name = full_name self.file = file self.containing_type = containing_type self._serialized_start = serialized_start self._serialized_end = serialized_end
'Returns the root if this is a nested type, or itself if its the root.'
def GetTopLevelContainingType(self):
desc = self while (desc.containing_type is not None): desc = desc.containing_type return desc
'Copies this to the matching proto in descriptor_pb2. Args: proto: An empty proto instance from descriptor_pb2. Raises: Error: If self couldnt be serialized, due to to few constructor arguments.'
def CopyToProto(self, proto):
if ((self.file is not None) and (self._serialized_start is not None) and (self._serialized_end is not None)): proto.ParseFromString(self.file.serialized_pb[self._serialized_start:self._serialized_end]) else: raise Error('Descriptor does not contain serialization.')
'Arguments to __init__() are as described in the description of Descriptor fields above. Note that filename is an obsolete argument, that is not used anymore. Please use file.name to access this as an attribute.'
def __init__(self, name, full_name, filename, containing_type, fields, nested_types, enum_types, extensions, options=None, is_extendable=True, extension_ranges=None, file=None, serialized_start=None, serialized_end=None):
super(Descriptor, self).__init__(options, 'MessageOptions', name, full_name, file, containing_type, serialized_start=serialized_start, serialized_end=serialized_start) self.fields = fields for field in self.fields: field.containing_type = self self.fields_by_number = dict(((f.number, f) for f in...
'Returns the string name of an enum value. This is just a small helper method to simplify a common operation. Args: enum: string name of the Enum. value: int, value of the enum. Returns: string name of the enum value. Raises: KeyError if either the Enum doesn\'t exist or the value is not a valid value for the enum.'
def EnumValueName(self, enum, value):
return self.enum_types_by_name[enum].values_by_number[value].name
'Copies this to a descriptor_pb2.DescriptorProto. Args: proto: An empty descriptor_pb2.DescriptorProto.'
def CopyToProto(self, proto):
super(Descriptor, self).CopyToProto(proto)
'The arguments are as described in the description of FieldDescriptor attributes above. Note that containing_type may be None, and may be set later if necessary (to deal with circular references between message types, for example). Likewise for extension_scope.'
def __init__(self, name, full_name, index, number, type, cpp_type, label, default_value, message_type, enum_type, containing_type, is_extension, extension_scope, options=None, has_default_value=True):
super(FieldDescriptor, self).__init__(options, 'FieldOptions') self.name = name self.full_name = full_name self.index = index self.number = number self.type = type self.cpp_type = cpp_type self.label = label self.has_default_value = has_default_value self.default_value = default_...
'Converts from a Python proto type to a C++ Proto Type. The Python ProtocolBuffer classes specify both the \'Python\' datatype and the \'C++\' datatype - and they\'re not the same. This helper method should translate from one to another. Args: proto_type: the Python proto type (descriptor.FieldDescriptor.TYPE_*) Return...
@staticmethod def ProtoTypeToCppProtoType(proto_type):
try: return FieldDescriptor._PYTHON_TO_CPP_PROTO_TYPE_MAP[proto_type] except KeyError: raise TypeTransformationError(('Unknown proto_type: %s' % proto_type))
'Arguments are as described in the attribute description above. Note that filename is an obsolete argument, that is not used anymore. Please use file.name to access this as an attribute.'
def __init__(self, name, full_name, filename, values, containing_type=None, options=None, file=None, serialized_start=None, serialized_end=None):
super(EnumDescriptor, self).__init__(options, 'EnumOptions', name, full_name, file, containing_type, serialized_start=serialized_start, serialized_end=serialized_start) self.values = values for value in self.values: value.type = self self.values_by_name = dict(((v.name, v) for v in values)) ...
'Copies this to a descriptor_pb2.EnumDescriptorProto. Args: proto: An empty descriptor_pb2.EnumDescriptorProto.'
def CopyToProto(self, proto):
super(EnumDescriptor, self).CopyToProto(proto)
'Arguments are as described in the attribute description above.'
def __init__(self, name, index, number, type=None, options=None):
super(EnumValueDescriptor, self).__init__(options, 'EnumValueOptions') self.name = name self.index = index self.number = number self.type = type
'Searches for the specified method, and returns its descriptor.'
def FindMethodByName(self, name):
for method in self.methods: if (name == method.name): return method return None
'Copies this to a descriptor_pb2.ServiceDescriptorProto. Args: proto: An empty descriptor_pb2.ServiceDescriptorProto.'
def CopyToProto(self, proto):
super(ServiceDescriptor, self).CopyToProto(proto)
'The arguments are as described in the description of MethodDescriptor attributes above. Note that containing_service may be None, and may be set later if necessary.'
def __init__(self, name, full_name, index, containing_service, input_type, output_type, options=None):
super(MethodDescriptor, self).__init__(options, 'MethodOptions') self.name = name self.full_name = full_name self.index = index self.containing_service = containing_service self.input_type = input_type self.output_type = output_type
'Constructor.'
def __init__(self, name, package, options=None, serialized_pb=None, dependencies=None):
super(FileDescriptor, self).__init__(options, 'FileOptions') self.message_types_by_name = {} self.name = name self.package = package self.serialized_pb = serialized_pb self.enum_types_by_name = {} self.extensions_by_name = {} self.dependencies = (dependencies or []) if ((api_implemen...
'Copies this to a descriptor_pb2.FileDescriptorProto. Args: proto: An empty descriptor_pb2.FileDescriptorProto.'
def CopyToProto(self, proto):
proto.ParseFromString(self.serialized_pb)
'Recursively compares two messages by value and structure.'
def __eq__(self, other_msg):
raise NotImplementedError
'Outputs a human-readable representation of the message.'
def __str__(self):
raise NotImplementedError
'Outputs a human-readable representation of the message.'
def __unicode__(self):
raise NotImplementedError
'Merges the contents of the specified message into current message. This method merges the contents of the specified message into the current message. Singular fields that are set in the specified message overwrite the corresponding fields in the current message. Repeated fields are appended. Singular sub-messages and ...
def MergeFrom(self, other_msg):
raise NotImplementedError
'Copies the content of the specified message into the current message. The method clears the current message and then merges the specified message using MergeFrom. Args: other_msg: Message to copy into the current one.'
def CopyFrom(self, other_msg):
if (self is other_msg): return self.Clear() self.MergeFrom(other_msg)
'Clears all data that was set in the message.'
def Clear(self):
raise NotImplementedError
'Mark this as present in the parent. This normally happens automatically when you assign a field of a sub-message, but sometimes you want to make the sub-message present while keeping it empty. If you find yourself using this, you may want to reconsider your design.'
def SetInParent(self):
raise NotImplementedError
'Checks if the message is initialized. Returns: The method returns True if the message is initialized (i.e. all of its required fields are set).'
def IsInitialized(self):
raise NotImplementedError
'Merges serialized protocol buffer data into this message. When we find a field in |serialized| that is already present in this message: - If it\'s a "repeated" field, we append to the end of our list. - Else, if it\'s a scalar, we overwrite our field. - Else, (it\'s a nonrepeated composite), we recursively merge into ...
def MergeFromString(self, serialized):
raise NotImplementedError
'Like MergeFromString(), except we clear the object first.'
def ParseFromString(self, serialized):
self.Clear() self.MergeFromString(serialized)
'Serializes the protocol message to a binary string. Returns: A binary string representation of the message if all of the required fields in the message are set (i.e. the message is initialized). Raises: message.EncodeError if the message isn\'t initialized.'
def SerializeToString(self):
raise NotImplementedError
'Serializes the protocol message to a binary string. This method is similar to SerializeToString but doesn\'t check if the message is initialized. Returns: A string representation of the partial message.'
def SerializePartialToString(self):
raise NotImplementedError
'Returns a list of (FieldDescriptor, value) tuples for all fields in the message which are not empty. A singular field is non-empty if HasField() would return true, and a repeated field is non-empty if it contains at least one element. The fields are ordered by field number'
def ListFields(self):
raise NotImplementedError
'Checks if a certain field is set for the message. Note if the field_name is not defined in the message descriptor, ValueError will be raised.'
def HasField(self, field_name):
raise NotImplementedError
'Returns the serialized size of this message. Recursively calls ByteSize() on all contained messages.'
def ByteSize(self):
raise NotImplementedError
'Internal method used by the protocol message implementation. Clients should not call this directly. Sets a listener that this message will call on certain state transitions. The purpose of this method is to register back-edges from children to parents at runtime, for the purpose of setting "has" bits and byte-size-dir...
def _SetListener(self, message_listener):
raise NotImplementedError
'Support the pickle protocol.'
def __getstate__(self):
return dict(serialized=self.SerializePartialToString())
'Support the pickle protocol.'
def __setstate__(self, state):
self.__init__() self.ParseFromString(state['serialized'])
'Custom allocation for runtime-generated class types. We override __new__ because this is apparently the only place where we can meaningfully set __slots__ on the class we\'re creating(?). (The interplay between metaclasses and slots is not very well-documented). Args: name: Name of the class (ignored, but required by ...
def __new__(cls, name, bases, dictionary):
descriptor = dictionary[GeneratedProtocolMessageType._DESCRIPTOR_KEY] bases = _NewMessage(bases, descriptor, dictionary) superclass = super(GeneratedProtocolMessageType, cls) new_class = superclass.__new__(cls, name, bases, dictionary) setattr(descriptor, '_concrete_class', new_class) return new...
'Here we perform the majority of our work on the class. We add enum getters, an __init__ method, implementations of all Message methods, and properties for all fields in the protocol type. Args: name: Name of the class (ignored, but required by the metaclass protocol). bases: Base classes of the class we\'re constructi...
def __init__(cls, name, bases, dictionary):
descriptor = dictionary[GeneratedProtocolMessageType._DESCRIPTOR_KEY] _InitMessage(descriptor, cls) superclass = super(GeneratedProtocolMessageType, cls) superclass.__init__(name, bases, dictionary)
'Checks the end of the text was reached. Returns: True iff the end was reached.'
def AtEnd(self):
return (not self.token)
'Tries to consume a given piece of text. Args: token: Text to consume. Returns: True iff the text was consumed.'
def TryConsume(self, token):
if (self.token == token): self.NextToken() return True return False
'Consumes a piece of text. Args: token: Text to consume. Raises: ParseError: If the text couldn\'t be consumed.'
def Consume(self, token):
if (not self.TryConsume(token)): raise self._ParseError(('Expected "%s".' % token))
'Consumes protocol message field identifier. Returns: Identifier string. Raises: ParseError: If an identifier couldn\'t be consumed.'
def ConsumeIdentifier(self):
result = self.token if (not self._IDENTIFIER.match(result)): raise self._ParseError('Expected identifier.') self.NextToken() return result
'Consumes a signed 32bit integer number. Returns: The integer parsed. Raises: ParseError: If a signed 32bit integer couldn\'t be consumed.'
def ConsumeInt32(self):
try: result = ParseInteger(self.token, is_signed=True, is_long=False) except ValueError as e: raise self._ParseError(str(e)) self.NextToken() return result
'Consumes an unsigned 32bit integer number. Returns: The integer parsed. Raises: ParseError: If an unsigned 32bit integer couldn\'t be consumed.'
def ConsumeUint32(self):
try: result = ParseInteger(self.token, is_signed=False, is_long=False) except ValueError as e: raise self._ParseError(str(e)) self.NextToken() return result
'Consumes a signed 64bit integer number. Returns: The integer parsed. Raises: ParseError: If a signed 64bit integer couldn\'t be consumed.'
def ConsumeInt64(self):
try: result = ParseInteger(self.token, is_signed=True, is_long=True) except ValueError as e: raise self._ParseError(str(e)) self.NextToken() return result
'Consumes an unsigned 64bit integer number. Returns: The integer parsed. Raises: ParseError: If an unsigned 64bit integer couldn\'t be consumed.'
def ConsumeUint64(self):
try: result = ParseInteger(self.token, is_signed=False, is_long=True) except ValueError as e: raise self._ParseError(str(e)) self.NextToken() return result
'Consumes an floating point number. Returns: The number parsed. Raises: ParseError: If a floating point number couldn\'t be consumed.'
def ConsumeFloat(self):
try: result = ParseFloat(self.token) except ValueError as e: raise self._ParseError(str(e)) self.NextToken() return result
'Consumes a boolean value. Returns: The bool parsed. Raises: ParseError: If a boolean value couldn\'t be consumed.'
def ConsumeBool(self):
try: result = ParseBool(self.token) except ValueError as e: raise self._ParseError(str(e)) self.NextToken() return result