2019-02-09 12:30:49 +00:00
package manager
import (
Toward better context handling (#1835)
* Use the request context
The code uses context.Background() in a flow where there is a
http.Request. Use the requests context instead.
* Use a true context in the plugin example
Let AddTag/RemoveTag take a context and use that context throughout
the example.
* Avoid the use of context.Background
Prefer context.TODO over context.Background deep in the call chain.
This marks the site as something which we need to context-handle
later, and also makes it clear to the reader that the context is
sort-of temporary in the code base.
While here, be consistent in handling the `act` variable in each
branch of the if .. { .. } .. check.
* Prefer context.TODO over context.Background
For the different scraping operations here, there is a context
higher up the call chain, which we ought to use. Mark the call-sites
as TODO for now, so we can come back later on a sweep of which parts
can be context-lifted.
* Thread context upwards
Initialization requires context for transactions. Thread the context
upward the call chain.
At the intialization call, add a context.TODO since we can't break this
yet. The singleton assumption prevents us from pulling it up into main for
now.
* make tasks context-aware
Change the task interface to understand contexts.
Pass the context down in some of the branches where it is needed.
* Make QueryStashBoxScene context-aware
This call naturally sits inside the request-context. Use it.
* Introduce a context in the JS plugin code
This allows us to use a context for HTTP calls inside the system.
Mark the context with a TODO at top level for now.
* Nitpick error formatting
Use %v rather than %s for error interfaces.
Do not begin an error strong with a capital letter.
* Avoid the use of http.Get in FFMPEG download chain
Since http.Get has no context, it isn't possible to break out or have
policy induced. The call will block until the GET completes. Rewrite
to use a http Request and provide a context.
Thread the context through the call chain for now. provide
context.TODO() at the top level of the initialization chain.
* Make getRemoteCDPWSAddress aware of contexts
Eliminate a call to http.Get and replace it with a context-aware
variant.
Push the context upwards in the call chain, but plug it before the
scraper interface so we don't have to rewrite said interface yet.
Plugged with context.TODO()
* Scraper: make the getImage function context-aware
Use a context, and pass it upwards. Plug it with context.TODO()
up the chain before the rewrite gets too much out of hand for now.
Minor tweaks along the way, remove a call to context.Background()
deep in the call chain.
* Make NOTIFY request context-aware
The call sits inside a Request-handler. So it's natural to use the
requests context as the context for the outgoing HTTP request.
* Use a context in the url scraper code
We are sitting in code which has a context, so utilize it for the
request as well.
* Use a context when checking versions
When we check the version of stash on Github, use a context. Thread
the context up to the initialization routine of the HTTP/GraphQL
server and plug it with a context.TODO() for now.
This paves the way for providing a context to the HTTP server code in a
future patch.
* Make utils func ReadImage context-aware
In almost all of the cases, there is a context in the call chain which
is a natural use. This is true for all the GraphQL mutations.
The exception is in task_stash_box_tag, so plug that task with
context.TODO() for now.
* Make stash-box get context-aware
Thread a context through the call chain until we hit the Client API.
Plug it with context.TODO() there for now.
* Enable the noctx linter
The code is now free of any uncontexted HTTP request. This means we
pass the noctx linter, and we can enable it in the code base.
2021-10-14 04:32:41 +00:00
"context"
2021-04-11 23:31:33 +00:00
"errors"
"fmt"
"os"
"path/filepath"
2021-05-16 07:21:11 +00:00
"runtime/pprof"
2022-03-17 00:33:59 +00:00
"strings"
2019-08-23 05:27:00 +00:00
"sync"
2021-04-22 03:51:51 +00:00
"time"
2019-08-23 05:27:00 +00:00
2022-03-17 00:33:59 +00:00
"github.com/stashapp/stash/internal/desktop"
"github.com/stashapp/stash/internal/dlna"
"github.com/stashapp/stash/internal/log"
"github.com/stashapp/stash/internal/manager/config"
2021-04-11 23:31:33 +00:00
"github.com/stashapp/stash/pkg/database"
2019-02-14 23:42:52 +00:00
"github.com/stashapp/stash/pkg/ffmpeg"
2022-03-17 00:33:59 +00:00
"github.com/stashapp/stash/pkg/fsutil"
2021-05-24 04:24:18 +00:00
"github.com/stashapp/stash/pkg/job"
2019-02-14 23:42:52 +00:00
"github.com/stashapp/stash/pkg/logger"
2021-01-18 01:23:20 +00:00
"github.com/stashapp/stash/pkg/models"
2022-03-17 00:33:59 +00:00
"github.com/stashapp/stash/pkg/models/paths"
2020-08-08 02:05:35 +00:00
"github.com/stashapp/stash/pkg/plugin"
2020-07-21 04:06:25 +00:00
"github.com/stashapp/stash/pkg/scraper"
2021-06-11 07:24:58 +00:00
"github.com/stashapp/stash/pkg/session"
2021-01-18 01:23:20 +00:00
"github.com/stashapp/stash/pkg/sqlite"
2019-02-14 23:42:52 +00:00
"github.com/stashapp/stash/pkg/utils"
2022-03-17 00:33:59 +00:00
"github.com/stashapp/stash/ui"
2019-02-09 12:30:49 +00:00
)
2022-05-04 00:37:32 +00:00
type Manager struct {
2021-04-11 23:31:33 +00:00
Config * config . Instance
2022-03-17 00:33:59 +00:00
Logger * log . Logger
2021-04-11 23:31:33 +00:00
2021-05-24 04:24:18 +00:00
Paths * paths . Paths
2019-03-23 14:56:59 +00:00
2022-04-18 00:50:10 +00:00
FFMPEG ffmpeg . FFMpeg
2021-10-14 23:39:48 +00:00
FFProbe ffmpeg . FFProbe
2020-07-21 04:06:25 +00:00
2022-04-18 00:50:10 +00:00
ReadLockManager * fsutil . ReadLockManager
2021-06-11 07:24:58 +00:00
SessionStore * session . Store
2021-05-24 04:24:18 +00:00
JobManager * job . Manager
2020-08-08 02:05:35 +00:00
PluginCache * plugin . Cache
2020-07-21 04:06:25 +00:00
ScraperCache * scraper . Cache
2020-09-15 07:28:53 +00:00
DownloadStore * DownloadStore
2021-01-18 01:23:20 +00:00
2021-05-20 06:58:43 +00:00
DLNAService * dlna . Service
2021-01-18 01:23:20 +00:00
TxnManager models . TransactionManager
2021-05-24 04:24:18 +00:00
scanSubs * subscriptionManager
2019-02-09 12:30:49 +00:00
}
2022-05-04 00:37:32 +00:00
var instance * Manager
2019-02-09 12:30:49 +00:00
var once sync . Once
2022-05-04 00:37:32 +00:00
func GetInstance ( ) * Manager {
if _ , err := Initialize ( ) ; err != nil {
panic ( err )
}
2019-02-09 12:30:49 +00:00
return instance
}
2022-05-04 00:37:32 +00:00
func Initialize ( ) ( * Manager , error ) {
var err error
2019-02-09 12:30:49 +00:00
once . Do ( func ( ) {
2022-05-04 00:37:32 +00:00
err = initialize ( )
} )
2021-05-13 12:15:21 +00:00
2022-05-04 00:37:32 +00:00
return instance , err
}
2020-09-15 07:28:53 +00:00
2022-05-04 00:37:32 +00:00
func initialize ( ) error {
ctx := context . TODO ( )
cfg , err := config . Initialize ( )
2019-02-11 06:39:21 +00:00
2022-05-04 00:37:32 +00:00
if err != nil {
return fmt . Errorf ( "initializing configuration: %w" , err )
}
2021-05-24 04:24:18 +00:00
2022-05-04 00:37:32 +00:00
l := initLog ( )
initProfiling ( cfg . GetCPUProfilePath ( ) )
2019-02-11 10:49:39 +00:00
2022-05-04 00:37:32 +00:00
instance = & Manager {
Config : cfg ,
Logger : l ,
ReadLockManager : fsutil . NewReadLockManager ( ) ,
DownloadStore : NewDownloadStore ( ) ,
PluginCache : plugin . NewCache ( cfg ) ,
2022-03-17 00:33:59 +00:00
2022-05-04 00:37:32 +00:00
TxnManager : sqlite . NewTransactionManager ( ) ,
2021-05-20 06:58:43 +00:00
2022-05-04 00:37:32 +00:00
scanSubs : & subscriptionManager { } ,
}
2021-04-11 23:31:33 +00:00
2022-05-04 00:37:32 +00:00
instance . JobManager = initJobManager ( )
2021-04-11 23:31:33 +00:00
2022-05-04 00:37:32 +00:00
sceneServer := SceneServer {
TXNManager : instance . TxnManager ,
}
instance . DLNAService = dlna . NewService ( instance . TxnManager , instance . Config , & sceneServer )
2021-10-04 07:16:01 +00:00
2022-05-04 00:37:32 +00:00
if ! cfg . IsNewSystem ( ) {
logger . Infof ( "using config file: %s" , cfg . GetConfigFile ( ) )
2021-06-11 07:24:58 +00:00
2022-05-04 00:37:32 +00:00
if err == nil {
err = cfg . Validate ( )
}
2021-06-11 07:24:58 +00:00
2022-05-04 00:37:32 +00:00
if err != nil {
return fmt . Errorf ( "error initializing configuration: %w" , err )
} else if err := instance . PostInit ( ctx ) ; err != nil {
return err
2021-02-02 09:32:37 +00:00
}
2020-09-15 07:28:53 +00:00
2022-05-04 00:37:32 +00:00
initSecurity ( cfg )
} else {
cfgFile := cfg . GetConfigFile ( )
if cfgFile != "" {
cfgFile += " "
2021-09-23 07:15:50 +00:00
}
2021-05-20 06:58:43 +00:00
2022-05-04 00:37:32 +00:00
// create temporary session store - this will be re-initialised
// after config is complete
instance . SessionStore = session . NewStore ( cfg )
logger . Warnf ( "config file %snot found. Assuming new system..." , cfgFile )
}
if err = initFFMPEG ( ctx ) ; err != nil {
logger . Warnf ( "could not initialize FFMPEG subsystem: %v" , err )
}
// if DLNA is enabled, start it now
if instance . Config . GetDLNADefaultEnabled ( ) {
if err := instance . DLNAService . Start ( nil ) ; err != nil {
logger . Warnf ( "could not start DLNA service: %v" , err )
2021-05-20 06:58:43 +00:00
}
2022-05-04 00:37:32 +00:00
}
2019-02-09 12:30:49 +00:00
2022-05-04 00:37:32 +00:00
return nil
2019-02-09 12:30:49 +00:00
}
2022-03-17 00:33:59 +00:00
func initJobManager ( ) * job . Manager {
ret := job . NewManager ( )
// desktop notifications
ctx := context . Background ( )
c := ret . Subscribe ( context . Background ( ) )
go func ( ) {
for {
select {
case j := <- c . RemovedJob :
if instance . Config . GetNotificationsEnabled ( ) {
cleanDesc := strings . TrimRight ( j . Description , "." )
2022-04-25 06:21:21 +00:00
if j . StartTime == nil {
// Task was never started
return
}
timeElapsed := j . EndTime . Sub ( * j . StartTime )
2022-03-17 00:33:59 +00:00
desktop . SendNotification ( "Task Finished" , "Task \"" + cleanDesc + "\" is finished in " + formatDuration ( timeElapsed ) + "." )
}
case <- ctx . Done ( ) :
return
}
}
} ( )
return ret
}
func formatDuration ( t time . Duration ) string {
return fmt . Sprintf ( "%02.f:%02.f:%02.f" , t . Hours ( ) , t . Minutes ( ) , t . Seconds ( ) )
}
2021-10-04 07:16:01 +00:00
func initSecurity ( cfg * config . Instance ) {
if err := session . CheckExternalAccessTripwire ( cfg ) ; err != nil {
session . LogExternalAccessError ( * err )
}
}
2021-05-16 07:21:11 +00:00
func initProfiling ( cpuProfilePath string ) {
if cpuProfilePath == "" {
return
}
f , err := os . Create ( cpuProfilePath )
if err != nil {
logger . Fatalf ( "unable to create cpu profile file: %s" , err . Error ( ) )
}
logger . Infof ( "profiling to %s" , cpuProfilePath )
// StopCPUProfile is defer called in main
2021-09-23 07:15:50 +00:00
if err = pprof . StartCPUProfile ( f ) ; err != nil {
logger . Warnf ( "could not start CPU profiling: %v" , err )
}
2021-05-16 07:21:11 +00:00
}
Hoist context, enable errchkjson (#2488)
* Make the script scraper context-aware
Connect the context to the command execution. This means command
execution can be aborted if the context is canceled. The context is
usually bound to user-interaction, i.e., a scraper operation issued
by the user. Hence, it seems correct to abort a command if the user
aborts.
* Enable errchkjson
Some json marshal calls are *safe* in that they can never fail. This is
conditional on the types of the the data being encoded. errchkjson finds
those calls which are unsafe, and also not checked for errors.
Add logging warnings to the place where unsafe encodings might happen.
This can help uncover usage bugs early in stash if they are tripped,
making debugging easier.
While here, keep the checker enabled in the linter to capture future
uses of json marshalling.
* Pass the context for zip file scanning.
* Pass the context in scanning
* Pass context, replace context.TODO()
Where applicable, pass the context down toward the lower functions in
the call stack. Replace uses of context.TODO() with the passed context.
This makes the code more context-aware, and you can rely on aborting
contexts to clean up subsystems to a far greater extent now.
I've left the cases where there is a context in a struct. My gut feeling
is that they have solutions that are nice, but they require more deep
thinking to unveil how to handle it.
* Remove context from task-structs
As a rule, contexts are better passed explicitly to functions than they
are passed implicitly via structs. In the case of tasks, we already
have a valid context in scope when creating the struct, so remove ctx
from the struct and use the scoped context instead.
With this change it is clear that the scanning functions are under a
context, and the task-starting caller has jurisdiction over the context
and its lifetime. A reader of the code don't have to figure out where
the context are coming from anymore.
While here, connect context.TODO() to the newly scoped context in most
of the scan code.
* Remove context from autotag struct too
* Make more context-passing explicit
In all of these cases, there is an applicable context which is close
in the call-tree. Hook up to this context.
* Simplify context passing in manager
The managers context handling generally wants to use an outer context
if applicable. However, the code doesn't pass it explicitly, but stores
it in a struct. Pull out the context from the struct and use it to
explicitly pass it.
At a later point in time, we probably want to handle this by handing
over the job to a different (program-lifetime) context for background
jobs, but this will do for a start.
2022-04-15 01:34:53 +00:00
func initFFMPEG ( ctx context . Context ) error {
2021-05-17 23:14:25 +00:00
// only do this if we have a config file set
if instance . Config . GetConfigFile ( ) != "" {
// use same directory as config path
configDirectory := instance . Config . GetConfigPath ( )
paths := [ ] string {
configDirectory ,
paths . GetStashHomeDirectory ( ) ,
}
ffmpegPath , ffprobePath := ffmpeg . GetPaths ( paths )
if ffmpegPath == "" || ffprobePath == "" {
logger . Infof ( "couldn't find FFMPEG, attempting to download it" )
Toward better context handling (#1835)
* Use the request context
The code uses context.Background() in a flow where there is a
http.Request. Use the requests context instead.
* Use a true context in the plugin example
Let AddTag/RemoveTag take a context and use that context throughout
the example.
* Avoid the use of context.Background
Prefer context.TODO over context.Background deep in the call chain.
This marks the site as something which we need to context-handle
later, and also makes it clear to the reader that the context is
sort-of temporary in the code base.
While here, be consistent in handling the `act` variable in each
branch of the if .. { .. } .. check.
* Prefer context.TODO over context.Background
For the different scraping operations here, there is a context
higher up the call chain, which we ought to use. Mark the call-sites
as TODO for now, so we can come back later on a sweep of which parts
can be context-lifted.
* Thread context upwards
Initialization requires context for transactions. Thread the context
upward the call chain.
At the intialization call, add a context.TODO since we can't break this
yet. The singleton assumption prevents us from pulling it up into main for
now.
* make tasks context-aware
Change the task interface to understand contexts.
Pass the context down in some of the branches where it is needed.
* Make QueryStashBoxScene context-aware
This call naturally sits inside the request-context. Use it.
* Introduce a context in the JS plugin code
This allows us to use a context for HTTP calls inside the system.
Mark the context with a TODO at top level for now.
* Nitpick error formatting
Use %v rather than %s for error interfaces.
Do not begin an error strong with a capital letter.
* Avoid the use of http.Get in FFMPEG download chain
Since http.Get has no context, it isn't possible to break out or have
policy induced. The call will block until the GET completes. Rewrite
to use a http Request and provide a context.
Thread the context through the call chain for now. provide
context.TODO() at the top level of the initialization chain.
* Make getRemoteCDPWSAddress aware of contexts
Eliminate a call to http.Get and replace it with a context-aware
variant.
Push the context upwards in the call chain, but plug it before the
scraper interface so we don't have to rewrite said interface yet.
Plugged with context.TODO()
* Scraper: make the getImage function context-aware
Use a context, and pass it upwards. Plug it with context.TODO()
up the chain before the rewrite gets too much out of hand for now.
Minor tweaks along the way, remove a call to context.Background()
deep in the call chain.
* Make NOTIFY request context-aware
The call sits inside a Request-handler. So it's natural to use the
requests context as the context for the outgoing HTTP request.
* Use a context in the url scraper code
We are sitting in code which has a context, so utilize it for the
request as well.
* Use a context when checking versions
When we check the version of stash on Github, use a context. Thread
the context up to the initialization routine of the HTTP/GraphQL
server and plug it with a context.TODO() for now.
This paves the way for providing a context to the HTTP server code in a
future patch.
* Make utils func ReadImage context-aware
In almost all of the cases, there is a context in the call chain which
is a natural use. This is true for all the GraphQL mutations.
The exception is in task_stash_box_tag, so plug that task with
context.TODO() for now.
* Make stash-box get context-aware
Thread a context through the call chain until we hit the Client API.
Plug it with context.TODO() there for now.
* Enable the noctx linter
The code is now free of any uncontexted HTTP request. This means we
pass the noctx linter, and we can enable it in the code base.
2021-10-14 04:32:41 +00:00
if err := ffmpeg . Download ( ctx , configDirectory ) ; err != nil {
2021-05-17 23:14:25 +00:00
msg := ` Unable to locate / automatically download FFMPEG
Check the readme for download links .
The FFMPEG and FFProbe binaries should be placed in % s
The error was : % s
`
logger . Errorf ( msg , configDirectory , err )
return err
} else {
// After download get new paths for ffmpeg and ffprobe
ffmpegPath , ffprobePath = ffmpeg . GetPaths ( paths )
}
2019-02-09 12:30:49 +00:00
}
2021-05-17 23:14:25 +00:00
2022-04-18 00:50:10 +00:00
instance . FFMPEG = ffmpeg . FFMpeg ( ffmpegPath )
2021-10-14 23:39:48 +00:00
instance . FFProbe = ffmpeg . FFProbe ( ffprobePath )
2019-02-09 12:30:49 +00:00
}
2019-02-11 07:35:53 +00:00
2021-05-17 23:14:25 +00:00
return nil
2019-02-11 10:49:39 +00:00
}
2022-03-17 00:33:59 +00:00
func initLog ( ) * log . Logger {
2021-04-11 23:31:33 +00:00
config := config . GetInstance ( )
2022-03-17 00:33:59 +00:00
l := log . NewLogger ( )
l . Init ( config . GetLogFile ( ) , config . GetLogOut ( ) , config . GetLogLevel ( ) )
logger . Logger = l
return l
2019-10-25 00:13:44 +00:00
}
2021-04-11 23:31:33 +00:00
// PostInit initialises the paths, caches and txnManager after the initial
// configuration has been set. Should only be called if the configuration
// is valid.
2022-05-04 00:37:32 +00:00
func ( s * Manager ) PostInit ( ctx context . Context ) error {
2021-09-23 07:15:50 +00:00
if err := s . Config . SetInitialConfig ( ) ; err != nil {
logger . Warnf ( "could not set initial configuration: %v" , err )
}
2021-05-03 21:42:33 +00:00
2021-04-11 23:31:33 +00:00
s . Paths = paths . NewPaths ( s . Config . GetGeneratedPath ( ) )
s . RefreshConfig ( )
2021-06-11 07:24:58 +00:00
s . SessionStore = session . NewStore ( s . Config )
s . PluginCache . RegisterSessionStore ( s . SessionStore )
2021-04-11 23:31:33 +00:00
2021-06-03 01:00:17 +00:00
if err := s . PluginCache . LoadPlugins ( ) ; err != nil {
logger . Errorf ( "Error reading plugin configs: %s" , err . Error ( ) )
}
s . ScraperCache = instance . initScraperCache ( )
2022-03-17 00:33:59 +00:00
writeStashIcon ( )
2021-06-03 01:00:17 +00:00
2021-04-11 23:31:33 +00:00
// clear the downloads and tmp directories
// #1021 - only clear these directories if the generated folder is non-empty
if s . Config . GetGeneratedPath ( ) != "" {
2021-04-22 03:51:51 +00:00
const deleteTimeout = 1 * time . Second
utils . Timeout ( func ( ) {
2022-03-17 00:33:59 +00:00
if err := fsutil . EmptyDir ( instance . Paths . Generated . Downloads ) ; err != nil {
2021-09-23 07:15:50 +00:00
logger . Warnf ( "could not empty Downloads directory: %v" , err )
}
2022-03-17 00:33:59 +00:00
if err := fsutil . EmptyDir ( instance . Paths . Generated . Tmp ) ; err != nil {
2021-09-23 07:15:50 +00:00
logger . Warnf ( "could not empty Tmp directory: %v" , err )
}
2021-04-22 03:51:51 +00:00
} , deleteTimeout , func ( done chan struct { } ) {
logger . Info ( "Please wait. Deleting temporary files..." ) // print
<- done // and wait for deletion
logger . Info ( "Temporary files deleted." )
} )
2021-04-11 23:31:33 +00:00
}
if err := database . Initialize ( s . Config . GetDatabasePath ( ) ) ; err != nil {
return err
}
if database . Ready ( ) == nil {
Toward better context handling (#1835)
* Use the request context
The code uses context.Background() in a flow where there is a
http.Request. Use the requests context instead.
* Use a true context in the plugin example
Let AddTag/RemoveTag take a context and use that context throughout
the example.
* Avoid the use of context.Background
Prefer context.TODO over context.Background deep in the call chain.
This marks the site as something which we need to context-handle
later, and also makes it clear to the reader that the context is
sort-of temporary in the code base.
While here, be consistent in handling the `act` variable in each
branch of the if .. { .. } .. check.
* Prefer context.TODO over context.Background
For the different scraping operations here, there is a context
higher up the call chain, which we ought to use. Mark the call-sites
as TODO for now, so we can come back later on a sweep of which parts
can be context-lifted.
* Thread context upwards
Initialization requires context for transactions. Thread the context
upward the call chain.
At the intialization call, add a context.TODO since we can't break this
yet. The singleton assumption prevents us from pulling it up into main for
now.
* make tasks context-aware
Change the task interface to understand contexts.
Pass the context down in some of the branches where it is needed.
* Make QueryStashBoxScene context-aware
This call naturally sits inside the request-context. Use it.
* Introduce a context in the JS plugin code
This allows us to use a context for HTTP calls inside the system.
Mark the context with a TODO at top level for now.
* Nitpick error formatting
Use %v rather than %s for error interfaces.
Do not begin an error strong with a capital letter.
* Avoid the use of http.Get in FFMPEG download chain
Since http.Get has no context, it isn't possible to break out or have
policy induced. The call will block until the GET completes. Rewrite
to use a http Request and provide a context.
Thread the context through the call chain for now. provide
context.TODO() at the top level of the initialization chain.
* Make getRemoteCDPWSAddress aware of contexts
Eliminate a call to http.Get and replace it with a context-aware
variant.
Push the context upwards in the call chain, but plug it before the
scraper interface so we don't have to rewrite said interface yet.
Plugged with context.TODO()
* Scraper: make the getImage function context-aware
Use a context, and pass it upwards. Plug it with context.TODO()
up the chain before the rewrite gets too much out of hand for now.
Minor tweaks along the way, remove a call to context.Background()
deep in the call chain.
* Make NOTIFY request context-aware
The call sits inside a Request-handler. So it's natural to use the
requests context as the context for the outgoing HTTP request.
* Use a context in the url scraper code
We are sitting in code which has a context, so utilize it for the
request as well.
* Use a context when checking versions
When we check the version of stash on Github, use a context. Thread
the context up to the initialization routine of the HTTP/GraphQL
server and plug it with a context.TODO() for now.
This paves the way for providing a context to the HTTP server code in a
future patch.
* Make utils func ReadImage context-aware
In almost all of the cases, there is a context in the call chain which
is a natural use. This is true for all the GraphQL mutations.
The exception is in task_stash_box_tag, so plug that task with
context.TODO() for now.
* Make stash-box get context-aware
Thread a context through the call chain until we hit the Client API.
Plug it with context.TODO() there for now.
* Enable the noctx linter
The code is now free of any uncontexted HTTP request. This means we
pass the noctx linter, and we can enable it in the code base.
2021-10-14 04:32:41 +00:00
s . PostMigrate ( ctx )
2021-04-11 23:31:33 +00:00
}
return nil
}
2022-03-17 00:33:59 +00:00
func writeStashIcon ( ) {
p := FaviconProvider {
2022-04-05 04:58:08 +00:00
UIBox : ui . UIBox ,
2022-03-17 00:33:59 +00:00
}
iconPath := filepath . Join ( instance . Config . GetConfigPath ( ) , "icon.png" )
2022-09-06 05:12:59 +00:00
err := os . WriteFile ( iconPath , p . GetFaviconPng ( ) , 0644 )
2022-03-17 00:33:59 +00:00
if err != nil {
logger . Errorf ( "Couldn't write icon file: %s" , err . Error ( ) )
}
}
2020-08-04 00:42:40 +00:00
// initScraperCache initializes a new scraper cache and returns it.
2022-05-04 00:37:32 +00:00
func ( s * Manager ) initScraperCache ( ) * scraper . Cache {
2021-04-11 23:31:33 +00:00
ret , err := scraper . NewCache ( config . GetInstance ( ) , s . TxnManager )
2020-07-21 04:06:25 +00:00
if err != nil {
logger . Errorf ( "Error reading scraper configs: %s" , err . Error ( ) )
}
return ret
}
2022-05-04 00:37:32 +00:00
func ( s * Manager ) RefreshConfig ( ) {
2021-04-11 23:31:33 +00:00
s . Paths = paths . NewPaths ( s . Config . GetGeneratedPath ( ) )
config := s . Config
if config . Validate ( ) == nil {
2022-03-17 00:33:59 +00:00
if err := fsutil . EnsureDir ( s . Paths . Generated . Screenshots ) ; err != nil {
2021-09-23 07:15:50 +00:00
logger . Warnf ( "could not create directory for Screenshots: %v" , err )
}
2022-03-17 00:33:59 +00:00
if err := fsutil . EnsureDir ( s . Paths . Generated . Vtt ) ; err != nil {
2021-09-23 07:15:50 +00:00
logger . Warnf ( "could not create directory for VTT: %v" , err )
}
2022-03-17 00:33:59 +00:00
if err := fsutil . EnsureDir ( s . Paths . Generated . Markers ) ; err != nil {
2021-09-23 07:15:50 +00:00
logger . Warnf ( "could not create directory for Markers: %v" , err )
}
2022-03-17 00:33:59 +00:00
if err := fsutil . EnsureDir ( s . Paths . Generated . Transcodes ) ; err != nil {
2021-09-23 07:15:50 +00:00
logger . Warnf ( "could not create directory for Transcodes: %v" , err )
}
2022-03-17 00:33:59 +00:00
if err := fsutil . EnsureDir ( s . Paths . Generated . Downloads ) ; err != nil {
2021-09-23 07:15:50 +00:00
logger . Warnf ( "could not create directory for Downloads: %v" , err )
}
2022-03-17 00:33:59 +00:00
if err := fsutil . EnsureDir ( s . Paths . Generated . InteractiveHeatmap ) ; err != nil {
2021-12-13 02:41:07 +00:00
logger . Warnf ( "could not create directory for Interactive Heatmaps: %v" , err )
}
2019-02-11 10:49:39 +00:00
}
}
2020-08-04 00:42:40 +00:00
// RefreshScraperCache refreshes the scraper cache. Call this when scraper
// configuration changes.
2022-05-04 00:37:32 +00:00
func ( s * Manager ) RefreshScraperCache ( ) {
2021-01-18 01:23:20 +00:00
s . ScraperCache = s . initScraperCache ( )
2020-08-04 00:42:40 +00:00
}
2021-04-11 23:31:33 +00:00
func setSetupDefaults ( input * models . SetupInput ) {
if input . ConfigLocation == "" {
2022-03-17 00:33:59 +00:00
input . ConfigLocation = filepath . Join ( fsutil . GetHomeDirectory ( ) , ".stash" , "config.yml" )
2021-04-11 23:31:33 +00:00
}
configDir := filepath . Dir ( input . ConfigLocation )
if input . GeneratedLocation == "" {
input . GeneratedLocation = filepath . Join ( configDir , "generated" )
}
if input . DatabaseFile == "" {
input . DatabaseFile = filepath . Join ( configDir , "stash-go.sqlite" )
}
}
2022-05-04 00:37:32 +00:00
func ( s * Manager ) Setup ( ctx context . Context , input models . SetupInput ) error {
2021-04-11 23:31:33 +00:00
setSetupDefaults ( & input )
2021-11-07 23:14:11 +00:00
c := s . Config
2021-04-11 23:31:33 +00:00
2021-08-10 04:58:14 +00:00
// create the config directory if it does not exist
2021-11-07 23:14:11 +00:00
// don't do anything if config is already set in the environment
if ! config . FileEnvSet ( ) {
configDir := filepath . Dir ( input . ConfigLocation )
2022-03-17 00:33:59 +00:00
if exists , _ := fsutil . DirExists ( configDir ) ; ! exists {
2021-11-07 23:14:11 +00:00
if err := os . Mkdir ( configDir , 0755 ) ; err != nil {
return fmt . Errorf ( "error creating config directory: %v" , err )
}
2021-08-10 04:58:14 +00:00
}
2021-11-07 23:14:11 +00:00
2022-03-17 00:33:59 +00:00
if err := fsutil . Touch ( input . ConfigLocation ) ; err != nil {
2021-11-07 23:14:11 +00:00
return fmt . Errorf ( "error creating config file: %v" , err )
}
s . Config . SetConfigFile ( input . ConfigLocation )
2021-08-10 04:58:14 +00:00
}
2021-04-11 23:31:33 +00:00
// create the generated directory if it does not exist
2021-11-07 23:14:11 +00:00
if ! c . HasOverride ( config . Generated ) {
2022-03-17 00:33:59 +00:00
if exists , _ := fsutil . DirExists ( input . GeneratedLocation ) ; ! exists {
2021-11-07 23:14:11 +00:00
if err := os . Mkdir ( input . GeneratedLocation , 0755 ) ; err != nil {
return fmt . Errorf ( "error creating generated directory: %v" , err )
}
2021-04-11 23:31:33 +00:00
}
2021-11-07 23:14:11 +00:00
s . Config . Set ( config . Generated , input . GeneratedLocation )
2021-04-11 23:31:33 +00:00
}
// set the configuration
2021-11-07 23:14:11 +00:00
if ! c . HasOverride ( config . Database ) {
s . Config . Set ( config . Database , input . DatabaseFile )
}
2021-04-11 23:31:33 +00:00
s . Config . Set ( config . Stash , input . Stashes )
if err := s . Config . Write ( ) ; err != nil {
Errorlint sweep + minor linter tweaks (#1796)
* Replace error assertions with Go 1.13 style
Use `errors.As(..)` over type assertions. This enables better use of
wrapped errors in the future, and lets us pass some errorlint checks
in the process.
The rewrite is entirely mechanical, and uses a standard idiom for
doing so.
* Use Go 1.13's errors.Is(..)
Rather than directly checking for error equality, use errors.Is(..).
This protects against error wrapping issues in the future.
Even though something like sql.ErrNoRows doesn't need the wrapping, do
so anyway, for the sake of consistency throughout the code base.
The change almost lets us pass the `errorlint` Go checker except for
a missing case in `js.go` which is to be handled separately; it isn't
mechanical, like these changes are.
* Remove goconst
goconst isn't a useful linter in many cases, because it's false positive
rate is high. It's 100% for the current code base.
* Avoid direct comparison of errors in recover()
Assert that we are catching an error from recover(). If we are,
check that the error caught matches errStop.
* Enable the "errorlint" checker
Configure the checker to avoid checking for errorf wraps. These are
often false positives since the suggestion is to blanket wrap errors
with %w, and that exposes the underlying API which you might not want
to do.
The other warnings are good however, and with the current patch stack,
the code base passes all these checks as well.
* Configure rowserrcheck
The project uses sqlx. Configure rowserrcheck to include said package.
* Mechanically rewrite a large set of errors
Mechanically search for errors that look like
fmt.Errorf("...%s", err.Error())
and rewrite those into
fmt.Errorf("...%v", err)
The `fmt` package is error-aware and knows how to call err.Error()
itself.
The rationale is that this is more idiomatic Go; it paves the
way for using error wrapping later with %w in some sites.
This patch only addresses the entirely mechanical rewriting caught by
a project-side search/replace. There are more individual sites not
addressed by this patch.
2021-10-12 03:03:08 +00:00
return fmt . Errorf ( "error writing configuration file: %v" , err )
2021-04-11 23:31:33 +00:00
}
// initialise the database
Toward better context handling (#1835)
* Use the request context
The code uses context.Background() in a flow where there is a
http.Request. Use the requests context instead.
* Use a true context in the plugin example
Let AddTag/RemoveTag take a context and use that context throughout
the example.
* Avoid the use of context.Background
Prefer context.TODO over context.Background deep in the call chain.
This marks the site as something which we need to context-handle
later, and also makes it clear to the reader that the context is
sort-of temporary in the code base.
While here, be consistent in handling the `act` variable in each
branch of the if .. { .. } .. check.
* Prefer context.TODO over context.Background
For the different scraping operations here, there is a context
higher up the call chain, which we ought to use. Mark the call-sites
as TODO for now, so we can come back later on a sweep of which parts
can be context-lifted.
* Thread context upwards
Initialization requires context for transactions. Thread the context
upward the call chain.
At the intialization call, add a context.TODO since we can't break this
yet. The singleton assumption prevents us from pulling it up into main for
now.
* make tasks context-aware
Change the task interface to understand contexts.
Pass the context down in some of the branches where it is needed.
* Make QueryStashBoxScene context-aware
This call naturally sits inside the request-context. Use it.
* Introduce a context in the JS plugin code
This allows us to use a context for HTTP calls inside the system.
Mark the context with a TODO at top level for now.
* Nitpick error formatting
Use %v rather than %s for error interfaces.
Do not begin an error strong with a capital letter.
* Avoid the use of http.Get in FFMPEG download chain
Since http.Get has no context, it isn't possible to break out or have
policy induced. The call will block until the GET completes. Rewrite
to use a http Request and provide a context.
Thread the context through the call chain for now. provide
context.TODO() at the top level of the initialization chain.
* Make getRemoteCDPWSAddress aware of contexts
Eliminate a call to http.Get and replace it with a context-aware
variant.
Push the context upwards in the call chain, but plug it before the
scraper interface so we don't have to rewrite said interface yet.
Plugged with context.TODO()
* Scraper: make the getImage function context-aware
Use a context, and pass it upwards. Plug it with context.TODO()
up the chain before the rewrite gets too much out of hand for now.
Minor tweaks along the way, remove a call to context.Background()
deep in the call chain.
* Make NOTIFY request context-aware
The call sits inside a Request-handler. So it's natural to use the
requests context as the context for the outgoing HTTP request.
* Use a context in the url scraper code
We are sitting in code which has a context, so utilize it for the
request as well.
* Use a context when checking versions
When we check the version of stash on Github, use a context. Thread
the context up to the initialization routine of the HTTP/GraphQL
server and plug it with a context.TODO() for now.
This paves the way for providing a context to the HTTP server code in a
future patch.
* Make utils func ReadImage context-aware
In almost all of the cases, there is a context in the call chain which
is a natural use. This is true for all the GraphQL mutations.
The exception is in task_stash_box_tag, so plug that task with
context.TODO() for now.
* Make stash-box get context-aware
Thread a context through the call chain until we hit the Client API.
Plug it with context.TODO() there for now.
* Enable the noctx linter
The code is now free of any uncontexted HTTP request. This means we
pass the noctx linter, and we can enable it in the code base.
2021-10-14 04:32:41 +00:00
if err := s . PostInit ( ctx ) ; err != nil {
Errorlint sweep + minor linter tweaks (#1796)
* Replace error assertions with Go 1.13 style
Use `errors.As(..)` over type assertions. This enables better use of
wrapped errors in the future, and lets us pass some errorlint checks
in the process.
The rewrite is entirely mechanical, and uses a standard idiom for
doing so.
* Use Go 1.13's errors.Is(..)
Rather than directly checking for error equality, use errors.Is(..).
This protects against error wrapping issues in the future.
Even though something like sql.ErrNoRows doesn't need the wrapping, do
so anyway, for the sake of consistency throughout the code base.
The change almost lets us pass the `errorlint` Go checker except for
a missing case in `js.go` which is to be handled separately; it isn't
mechanical, like these changes are.
* Remove goconst
goconst isn't a useful linter in many cases, because it's false positive
rate is high. It's 100% for the current code base.
* Avoid direct comparison of errors in recover()
Assert that we are catching an error from recover(). If we are,
check that the error caught matches errStop.
* Enable the "errorlint" checker
Configure the checker to avoid checking for errorf wraps. These are
often false positives since the suggestion is to blanket wrap errors
with %w, and that exposes the underlying API which you might not want
to do.
The other warnings are good however, and with the current patch stack,
the code base passes all these checks as well.
* Configure rowserrcheck
The project uses sqlx. Configure rowserrcheck to include said package.
* Mechanically rewrite a large set of errors
Mechanically search for errors that look like
fmt.Errorf("...%s", err.Error())
and rewrite those into
fmt.Errorf("...%v", err)
The `fmt` package is error-aware and knows how to call err.Error()
itself.
The rationale is that this is more idiomatic Go; it paves the
way for using error wrapping later with %w in some sites.
This patch only addresses the entirely mechanical rewriting caught by
a project-side search/replace. There are more individual sites not
addressed by this patch.
2021-10-12 03:03:08 +00:00
return fmt . Errorf ( "error initializing the database: %v" , err )
2021-04-11 23:31:33 +00:00
}
2021-05-13 12:15:21 +00:00
s . Config . FinalizeSetup ( )
Hoist context, enable errchkjson (#2488)
* Make the script scraper context-aware
Connect the context to the command execution. This means command
execution can be aborted if the context is canceled. The context is
usually bound to user-interaction, i.e., a scraper operation issued
by the user. Hence, it seems correct to abort a command if the user
aborts.
* Enable errchkjson
Some json marshal calls are *safe* in that they can never fail. This is
conditional on the types of the the data being encoded. errchkjson finds
those calls which are unsafe, and also not checked for errors.
Add logging warnings to the place where unsafe encodings might happen.
This can help uncover usage bugs early in stash if they are tripped,
making debugging easier.
While here, keep the checker enabled in the linter to capture future
uses of json marshalling.
* Pass the context for zip file scanning.
* Pass the context in scanning
* Pass context, replace context.TODO()
Where applicable, pass the context down toward the lower functions in
the call stack. Replace uses of context.TODO() with the passed context.
This makes the code more context-aware, and you can rely on aborting
contexts to clean up subsystems to a far greater extent now.
I've left the cases where there is a context in a struct. My gut feeling
is that they have solutions that are nice, but they require more deep
thinking to unveil how to handle it.
* Remove context from task-structs
As a rule, contexts are better passed explicitly to functions than they
are passed implicitly via structs. In the case of tasks, we already
have a valid context in scope when creating the struct, so remove ctx
from the struct and use the scoped context instead.
With this change it is clear that the scanning functions are under a
context, and the task-starting caller has jurisdiction over the context
and its lifetime. A reader of the code don't have to figure out where
the context are coming from anymore.
While here, connect context.TODO() to the newly scoped context in most
of the scan code.
* Remove context from autotag struct too
* Make more context-passing explicit
In all of these cases, there is an applicable context which is close
in the call-tree. Hook up to this context.
* Simplify context passing in manager
The managers context handling generally wants to use an outer context
if applicable. However, the code doesn't pass it explicitly, but stores
it in a struct. Pull out the context from the struct and use it to
explicitly pass it.
At a later point in time, we probably want to handle this by handing
over the job to a different (program-lifetime) context for background
jobs, but this will do for a start.
2022-04-15 01:34:53 +00:00
if err := initFFMPEG ( ctx ) ; err != nil {
2021-09-23 07:15:50 +00:00
return fmt . Errorf ( "error initializing FFMPEG subsystem: %v" , err )
}
2021-05-17 23:14:25 +00:00
return nil
}
2022-05-04 00:37:32 +00:00
func ( s * Manager ) validateFFMPEG ( ) error {
2021-10-14 23:39:48 +00:00
if s . FFMPEG == "" || s . FFProbe == "" {
2021-05-17 23:14:25 +00:00
return errors . New ( "missing ffmpeg and/or ffprobe" )
}
2021-04-11 23:31:33 +00:00
return nil
}
2022-05-04 00:37:32 +00:00
func ( s * Manager ) Migrate ( ctx context . Context , input models . MigrateInput ) error {
2021-04-11 23:31:33 +00:00
// always backup so that we can roll back to the previous version if
// migration fails
backupPath := input . BackupPath
if backupPath == "" {
backupPath = database . DatabaseBackupPath ( )
}
// perform database backup
if err := database . Backup ( database . DB , backupPath ) ; err != nil {
return fmt . Errorf ( "error backing up database: %s" , err )
}
if err := database . RunMigrations ( ) ; err != nil {
errStr := fmt . Sprintf ( "error performing migration: %s" , err )
// roll back to the backed up version
restoreErr := database . RestoreFromBackup ( backupPath )
if restoreErr != nil {
errStr = fmt . Sprintf ( "ERROR: unable to restore database from backup after migration failure: %s\n%s" , restoreErr . Error ( ) , errStr )
} else {
errStr = "An error occurred migrating the database to the latest schema version. The backup database file was automatically renamed to restore the database.\n" + errStr
}
return errors . New ( errStr )
}
// perform post-migration operations
Toward better context handling (#1835)
* Use the request context
The code uses context.Background() in a flow where there is a
http.Request. Use the requests context instead.
* Use a true context in the plugin example
Let AddTag/RemoveTag take a context and use that context throughout
the example.
* Avoid the use of context.Background
Prefer context.TODO over context.Background deep in the call chain.
This marks the site as something which we need to context-handle
later, and also makes it clear to the reader that the context is
sort-of temporary in the code base.
While here, be consistent in handling the `act` variable in each
branch of the if .. { .. } .. check.
* Prefer context.TODO over context.Background
For the different scraping operations here, there is a context
higher up the call chain, which we ought to use. Mark the call-sites
as TODO for now, so we can come back later on a sweep of which parts
can be context-lifted.
* Thread context upwards
Initialization requires context for transactions. Thread the context
upward the call chain.
At the intialization call, add a context.TODO since we can't break this
yet. The singleton assumption prevents us from pulling it up into main for
now.
* make tasks context-aware
Change the task interface to understand contexts.
Pass the context down in some of the branches where it is needed.
* Make QueryStashBoxScene context-aware
This call naturally sits inside the request-context. Use it.
* Introduce a context in the JS plugin code
This allows us to use a context for HTTP calls inside the system.
Mark the context with a TODO at top level for now.
* Nitpick error formatting
Use %v rather than %s for error interfaces.
Do not begin an error strong with a capital letter.
* Avoid the use of http.Get in FFMPEG download chain
Since http.Get has no context, it isn't possible to break out or have
policy induced. The call will block until the GET completes. Rewrite
to use a http Request and provide a context.
Thread the context through the call chain for now. provide
context.TODO() at the top level of the initialization chain.
* Make getRemoteCDPWSAddress aware of contexts
Eliminate a call to http.Get and replace it with a context-aware
variant.
Push the context upwards in the call chain, but plug it before the
scraper interface so we don't have to rewrite said interface yet.
Plugged with context.TODO()
* Scraper: make the getImage function context-aware
Use a context, and pass it upwards. Plug it with context.TODO()
up the chain before the rewrite gets too much out of hand for now.
Minor tweaks along the way, remove a call to context.Background()
deep in the call chain.
* Make NOTIFY request context-aware
The call sits inside a Request-handler. So it's natural to use the
requests context as the context for the outgoing HTTP request.
* Use a context in the url scraper code
We are sitting in code which has a context, so utilize it for the
request as well.
* Use a context when checking versions
When we check the version of stash on Github, use a context. Thread
the context up to the initialization routine of the HTTP/GraphQL
server and plug it with a context.TODO() for now.
This paves the way for providing a context to the HTTP server code in a
future patch.
* Make utils func ReadImage context-aware
In almost all of the cases, there is a context in the call chain which
is a natural use. This is true for all the GraphQL mutations.
The exception is in task_stash_box_tag, so plug that task with
context.TODO() for now.
* Make stash-box get context-aware
Thread a context through the call chain until we hit the Client API.
Plug it with context.TODO() there for now.
* Enable the noctx linter
The code is now free of any uncontexted HTTP request. This means we
pass the noctx linter, and we can enable it in the code base.
2021-10-14 04:32:41 +00:00
s . PostMigrate ( ctx )
2021-04-11 23:31:33 +00:00
// if no backup path was provided, then delete the created backup
if input . BackupPath == "" {
if err := os . Remove ( backupPath ) ; err != nil {
logger . Warnf ( "error removing unwanted database backup (%s): %s" , backupPath , err . Error ( ) )
}
}
return nil
}
2022-05-04 00:37:32 +00:00
func ( s * Manager ) GetSystemStatus ( ) * models . SystemStatus {
2021-04-11 23:31:33 +00:00
status := models . SystemStatusEnumOk
dbSchema := int ( database . Version ( ) )
dbPath := database . DatabasePath ( )
appSchema := int ( database . AppSchemaVersion ( ) )
2021-05-13 12:15:21 +00:00
configFile := s . Config . GetConfigFile ( )
2021-04-11 23:31:33 +00:00
2021-05-13 12:15:21 +00:00
if s . Config . IsNewSystem ( ) {
2021-04-11 23:31:33 +00:00
status = models . SystemStatusEnumSetup
} else if dbSchema < appSchema {
status = models . SystemStatusEnumNeedsMigration
}
return & models . SystemStatus {
DatabaseSchema : & dbSchema ,
DatabasePath : & dbPath ,
AppSchema : appSchema ,
Status : status ,
2021-05-13 12:15:21 +00:00
ConfigPath : & configFile ,
2021-04-11 23:31:33 +00:00
}
}
2021-09-07 04:28:40 +00:00
// Shutdown gracefully stops the manager
2022-05-04 00:37:32 +00:00
func ( s * Manager ) Shutdown ( code int ) {
2022-04-05 04:58:08 +00:00
// stop any profiling at exit
pprof . StopCPUProfile ( )
2021-09-07 04:28:40 +00:00
// TODO: Each part of the manager needs to gracefully stop at some point
// for now, we just close the database.
2022-02-03 00:20:34 +00:00
err := database . Close ( )
if err != nil {
logger . Errorf ( "Error closing database: %s" , err )
if code == 0 {
os . Exit ( 1 )
}
}
2022-04-05 04:58:08 +00:00
2022-02-03 00:20:34 +00:00
os . Exit ( code )
2021-09-07 04:28:40 +00:00
}