@@ -785,6 +785,59 @@ func TestAgent_Lifecycle(t *testing.T) {
785
785
require .Equal (t , want , got )
786
786
}
787
787
})
788
+
789
+ t .Run ("ShutdownScriptOnce" , func (t * testing.T ) {
790
+ t .Parallel ()
791
+
792
+ expected := "this-is-shutdown"
793
+ client := & client {
794
+ t : t ,
795
+ agentID : uuid .New (),
796
+ metadata : codersdk.WorkspaceAgentMetadata {
797
+ DERPMap : tailnettest .RunDERPAndSTUN (t ),
798
+ StartupScript : "echo 1" ,
799
+ ShutdownScript : "echo " + expected ,
800
+ },
801
+ statsChan : make (chan * codersdk.AgentStats ),
802
+ coordinator : tailnet .NewCoordinator (),
803
+ }
804
+
805
+ fs := afero .NewMemMapFs ()
806
+ agent := agent .New (agent.Options {
807
+ Client : client ,
808
+ Logger : slogtest .Make (t , nil ).Leveled (slog .LevelInfo ),
809
+ Filesystem : fs ,
810
+ })
811
+
812
+ // agent.Close() loads the shutdown script from the agent metadata.
813
+ // The metadata is populated just before execution of the startup script, so it's mandatory to wait
814
+ // until the startup starts.
815
+ require .Eventually (t , func () bool {
816
+ outputPath := filepath .Join (os .TempDir (), "coder-startup-script.log" )
817
+ content , err := afero .ReadFile (fs , outputPath )
818
+ if err != nil {
819
+ t .Logf ("read file %q: %s" , outputPath , err )
820
+ return false
821
+ }
822
+ return len (content ) > 0 // something is in the startup log file
823
+ }, testutil .WaitShort , testutil .IntervalMedium )
824
+
825
+ err := agent .Close ()
826
+ require .NoError (t , err , "agent should be closed successfully" )
827
+
828
+ outputPath := filepath .Join (os .TempDir (), "coder-shutdown-script.log" )
829
+ logFirstRead , err := afero .ReadFile (fs , outputPath )
830
+ require .NoError (t , err , "log file should be present" )
831
+ require .Equal (t , expected , string (bytes .TrimSpace (logFirstRead )))
832
+
833
+ // Make sure that script can't be executed twice.
834
+ err = agent .Close ()
835
+ require .NoError (t , err , "don't need to close the agent twice, no effect" )
836
+
837
+ logSecondRead , err := afero .ReadFile (fs , outputPath )
838
+ require .NoError (t , err , "log file should be present" )
839
+ require .Equal (t , string (bytes .TrimSpace (logFirstRead )), string (bytes .TrimSpace (logSecondRead )))
840
+ })
788
841
}
789
842
790
843
func TestAgent_Startup (t * testing.T ) {
0 commit comments