Processing Config#
Now that our application has its config stored in the ConfigState
struct, we can use it to perform the application logic. While in the case of greeter
the app logic is trivial, in real-world applications it might be more complex.
func (a *App) Start(ctx context.Context) {
go a.receiveConfigNotifications(ctx)
for {
select {
case <-a.configReceivedCh:
a.logger.Info().Msg("Received full config")
a.processConfig(ctx)
a.updateState(ctx)
case <-ctx.Done():
a.stop()
return
}
}
}
Greeter' core app logic is to calculate the greeting message that consists of a name and the last-booted time of SR Linux system.
func (a *App) processConfig(ctx context.Context) {
if a.configState.Name == "" {
a.logger.Info().Msg("No name configured, deleting state")
a.configState = &ConfigState{}
return
}
uptime, err := a.getUptime(ctx)
if err != nil {
a.logger.Info().Msgf("failed to get uptime: %v", err)
return
}
a.configState.Greeting = "👋 Hi " + a.configState.Name +
", SR Linux was last booted at " + uptime
}
The processConfig
function first checks if the name
field is not an empty string. If it is an empty, it means the config name was either deleted or not configured at all. In this case we set the ConfigState
struct to an empty value which should result in the empty state in the SR Linux data store.
If name
is set we proceed with calculating the greeting message. Remember that we need to retrieve the last-booted
time value from the SR Linux system. We do this by calling the getUptime
function.
func (a *App) getUptime(ctx context.Context) (string, error) {
a.logger.Info().Msg("Fetching SR Linux uptime value")
// create a GetRequest
getReq, err := api.NewGetRequest(
api.Path("/system/information/last-booted"),
api.Encoding("proto"))
if err != nil {
return "", err
}
getResp, err := a.gNMITarget.Get(ctx, getReq)
if err != nil {
return "", err
}
a.logger.Info().Msgf("GetResponse: %+v", getResp)
return getResp.Notification[0].Update[0].GetVal().GetStringVal(), nil
}
Earlier on, we created the gNMI Target and now it is time to use it. We use the gNMI Get request to retrieve the /system/information/last-booted
value from the SR Linux. The Get
function returns a gNMI Get Response from which we extract the last-booted
value as string.
Now that we have the name
value retrieved from the configuration notification and last-booted
value fetched via gNMI, we can compose the greeting message:
a.configState.Greeting = "👋 Hi " + a.configState.Name +
", SR Linux was last booted at " + uptime
With our ConfigState
struct populated with the name
and greeting
values we have only one step left: to update the state datastore with them.