github.com/choria-io/go-choria@v0.28.1-0.20240416190746-b3bf9c7d5a45/lifecycle/upgraded.go (about)

     1  // Copyright (c) 2023, R.I. Pienaar and the Choria Project contributors
     2  //
     3  // SPDX-License-Identifier: Apache-2.0
     4  
     5  package lifecycle
     6  
     7  import (
     8  	"encoding/json"
     9  	"fmt"
    10  )
    11  
    12  type UpgradedEvent struct {
    13  	basicEvent
    14  	Version    string `json:"version"`
    15  	NewVersion string `json:"new_version"`
    16  }
    17  
    18  func init() {
    19  	eventTypes["upgraded"] = Upgraded
    20  
    21  	eventJSONParsers[Upgraded] = func(j []byte) (Event, error) {
    22  		return newUpgradeEventFromJSON(j)
    23  	}
    24  
    25  	eventFactories[Upgraded] = func(opts ...Option) Event {
    26  		return newUpgradeEvent(opts...)
    27  	}
    28  }
    29  
    30  func newUpgradeEvent(opts ...Option) *UpgradedEvent {
    31  	event := &UpgradedEvent{basicEvent: newBasicEvent("upgraded")}
    32  
    33  	for _, o := range opts {
    34  		o(event)
    35  	}
    36  
    37  	return event
    38  }
    39  
    40  func newUpgradeEventFromJSON(j []byte) (*UpgradedEvent, error) {
    41  	event := newUpgradeEvent()
    42  
    43  	err := json.Unmarshal(j, event)
    44  	if err != nil {
    45  		return nil, err
    46  	}
    47  
    48  	switch event.EventProtocol {
    49  	case "io.choria.lifecycle.v1.upgraded":
    50  	case "choria:lifecycle:upgraded:1":
    51  		event.EventProtocol = "io.choria.lifecycle.v1.upgraded"
    52  	default:
    53  		return nil, fmt.Errorf("invalid protocol '%s'", event.EventProtocol)
    54  	}
    55  
    56  	return event, nil
    57  }
    58  
    59  // String is text suitable to display on the console etc
    60  func (e *UpgradedEvent) String() string {
    61  	return fmt.Sprintf("[upgraded] %s: %s version %s to %s", e.Ident, e.Component(), e.Version, e.NewVersion)
    62  }
    63  
    64  // SetVersion sets the version for the event
    65  func (e *UpgradedEvent) SetVersion(v string) {
    66  	e.Version = v
    67  }
    68  
    69  // SetNewVersion sets the version for the event
    70  func (e *UpgradedEvent) SetNewVersion(v string) {
    71  	e.NewVersion = v
    72  }