Repository navigation
Workflow Fundamentals
Previous Chapter: Introduction
- Introduction
- Scripts and jobs
- One-shot and loop scripts
- Job tags: the coordination medium
- Workflow identity: name and flow id
- Owned jobs
- Resuming and acquiring
- Consume-once tags
- Target project and own project
Every component of a shub-workflow workflow — a crawl manager, a consumer, a delivery script, a monitor — is a
script: a Python program built on the base classes of
shub_workflow/script.py,
deployed with your Scrapy project and run as a ScrapyCloud job. This chapter introduces the few concepts all of
them share: how a script runs, how jobs are identified and related to each other through tags, and how a
script that stops for any reason can continue its work when it is started again.
These concepts are the foundation of everything that follows. The crawl managers and graph managers of the next chapters are built on them, and they are also what makes possible the architecture described later in this tutorial, where many independent scripts cooperate without any central coordinator.
For the complete reference of the base classes, see Appendix B: Script Classes and Appendix C: Workflow Manager.
A spider job runs a spider; a script job runs a script deployed with the project. On ScrapyCloud a script job
is identified by its script name in the form py:<script>.py, in the same place where a spider job shows its
spider name. In order to be deployable, the script must be registered in the scripts list of the project
setup.py:
from setuptools import setup, find_packages
setup(
name="myproject",
version="1.0",
packages=find_packages(),
scripts=["scripts/myscript.py"],
entry_points={"scrapy": ["settings = myproject.settings"]},
)A minimal script subclasses BaseScript and implements run():
import logging
from shub_workflow.script import BaseScript
LOGGER = logging.getLogger(__name__)
class MyScript(BaseScript):
@property
def description(self):
return "Schedule the spider mysite.com once."
def add_argparser_options(self):
super().add_argparser_options()
self.argparser.add_argument("--section", default="news")
def run(self):
jobkey = self.schedule_spider("mysite.com", units=1, section=self.args.section)
LOGGER.info(f"Scheduled {jobkey}")
if __name__ == "__main__":
from shub_workflow.utils import get_kumo_loglevel
logging.basicConfig(format="%(asctime)s %(name)s [%(levelname)s]: %(message)s", level=get_kumo_loglevel())
MyScript().run()The __main__ block is the same boilerplate in every shub-workflow script. BaseScript already provides the
command line parsing, the ScrapyCloud client, scheduling of spiders and scripts (schedule_spider(),
schedule_script()), job queries (get_jobs()), a Scrapy stats collector (self.stats) that is uploaded to the
job stats, and a filesystem helper (self.fshelper) for S3, GCS and local files.
The same script can run in ScrapyCloud (scheduled manually, by a periodic job or by another script) or in your local environment. Locally you run it as any Python program:
$ python scripts/myscript.py --section=sports
A BaseScript performs its work in run() and finishes. Many workflow components, however, must keep working
for a long time: check the status of the jobs they scheduled, read new inputs as they appear, etc. For them there
is BaseLoopScript, which provides run() and calls instead your workflow_loop() method repeatedly:
from shub_workflow.script import BaseLoopScript
class MyLoopScript(BaseLoopScript):
loop_mode = 120 # seconds between loops. 0 (default) runs a single loop
max_running_time = 0 # if > 0, close the script after this number of seconds (plus a random jitter)
def on_start(self):
... # one time setup
def workflow_loop(self) -> bool:
... # one cycle of work
return True # True: continue looping. False: stop now
def on_close(self):
... # one time teardownBoth attributes can be overridden by the command line options --loop-mode and --max-running-time. The
script finishes when workflow_loop() returns False, when it reaches its maximal running time, or when it is
not in loop mode. The maximal running time effectively used is max_running_time plus a random extra time of up
to max_running_time_jitter (default 0.05, i.e. 5%) of it. Its stats are uploaded periodically while it runs, and when it closes.
Crawl managers, graph managers and issuers are all loop scripts.
ScrapyCloud lets you attach tags to every job, and query jobs by them: has_tag selects the jobs that have
a tag, lacks_tag the ones that don't. shub-workflow relies heavily on this feature. Tags are the only state
that ScrapyCloud keeps attached to each job and that any script, running anywhere, can query. So they are the
natural medium for relating jobs to each other, and for recording what has already been done with a job.
Many tags have a KEY=value form. BaseScript provides methods for handling them:
| Method | Purpose |
|---|---|
get_job_tags(jobkey=None) |
tags of the given job (or of the script's own job). |
get_keyvalue_job_tag(key, tags) |
the value of the key=value tag in the given tag list, if any. |
add_job_tags(jobkey=None, tags=...) |
add tags to the given job (or to the script's own job). |
remove_job_tags(tags, jobkey) |
remove tags from a job. |
get_jobs(state=..., has_tag=..., lacks_tag=..., ...) |
iterate over project jobs, with pagination handled for you. |
for jobdict in self.get_jobs(spider="mysite.com", state=["finished"], has_tag=["SECTION=news"], meta=["tags"]):
section = self.get_keyvalue_job_tag("SECTION", jobdict["tags"])When has_tag receives several values, ScrapyCloud returns the jobs that have any of them, not only the jobs
that have all of them. So if you need the jobs that have all the tags, filter server side by the most selective
one, and check the others in Python:
for jobdict in self.get_jobs(spider="mysite.com", state=["finished"], has_tag=["SECTION=news"], meta=["tags"]):
if "LANG=en" in jobdict["tags"]:
...You can add your own tags to the jobs a script schedules, either with the tags parameter of the scheduling
methods, the children_tags class attribute, or the --children-tag command line option.
shub-workflow adds a few tags of its own, which identify the workflow a job belongs to:
| Tag | Meaning |
|---|---|
NAME=<name> |
the name of a script within a workflow. Set via the name class attribute (or a command line argument, in workflow managers). |
FLOW_ID=<id> |
identifies one instance of a workflow. Every job scheduled within that instance carries the same flow id. |
PARENT_NAME=<name> |
added to every job a named script schedules: the name of its parent. |
A flow id is either given (--flow-id), inherited from the script's own job tags (because its parent scheduled
it with them), or, for scripts that require it, autogenerated. Workflow managers require a flow id
(flow_id_required = True), so a manager started without one generates a new one: that is, starting a manager
starts a new instance of its workflow. Once the script has a flow id, all the jobs it schedules inherit it:
graph manager NAME=delivery_flow FLOW_ID=af31...
│
├──► crawl manager NAME=crawl FLOW_ID=af31... PARENT_NAME=delivery_flow
│ │
│ ├──► spider job FLOW_ID=af31... PARENT_NAME=crawl
│ └──► spider job FLOW_ID=af31... PARENT_NAME=crawl
│
└──► deliver script FLOW_ID=af31... PARENT_NAME=delivery_flow
So any component can find all the jobs of its own workflow instance, and only them, even when many instances of
the same workflow run at the same time in the same project. Additional tags that must be transmitted along the
whole workflow can be registered with append_flow_tag().
A workflow manager (the base of the crawl managers and the graph manager) owns the jobs it schedules: the
ones tagged with its flow id and with its name as PARENT_NAME. get_owned_jobs() returns exactly those. This is
how a manager keeps track of its children, and how it enforces its maximal number of simultaneously running jobs
(--max-running-jobs, default default_max_jobs = 1000).
A script may stop for many reasons: it is cancelled, it reaches its maximal running time, it fails, its ScrapyCloud unit dies. When a workflow manager starts again, it must not schedule a second time the jobs its previous instance already scheduled, nor exceed its maximal number of running jobs because the children of the previous instance are still running. There are two mechanisms for that, and they are easy to confuse:
-
Resume. If a manager starts with a flow id that was not autogenerated, and finds a previous finished job
with the same name and flow id, it continues that one: it inherits its
key=valuetags and acquires its owned jobs, both running and finished. In practice this happens when you clone a stopped manager job (cloning conserves its tags, so itsFLOW_IDtoo) or pass--flow-idexplicitly. A default resume is enough for most managers; the hooksresume_running_job_hook()andresume_finished_job_hook()let you rebuild any additional state. -
Acquire. A manager that is scheduled automatically — by a periodic job, or by another script — always
starts a new workflow instance, with a new flow id, so it never resumes. Set
acquire_all_jobs = Trueon it: it then adopts the running children of any previous instance by theirPARENT_NAMEalone, whatever their flow id, and counts them against its running jobs limit. Pair it withdont_acquire_finished_jobs = True, unless you really need them, as the finished children of all previous instances can be many.
from shub_workflow.crawl import GeneratorCrawlManager
class CrawlManager(GeneratorCrawlManager):
name = "crawl"
loop_mode = 120
spider = "mysite.com"
# scheduled by a periodic job: adopt the children of previous instances
acquire_all_jobs = True
dont_acquire_finished_jobs = TrueAcquiring by name has a consequence: two instances of the same manager class that run against different targets
would adopt each other's children. In that case override get_owned_jobs() to narrow the match (e.g. by the
target spider). See The owned-jobs model
for the details.
Note that neither mechanism prevents two instances of the same manager from running at the same time: that is the responsibility of whoever schedules them. ScrapyCloud itself refuses to schedule a job identical (same script and same arguments) to one that is already pending or running.
Scripts that process the output of other jobs (like the issuers we will see later) need to know which jobs they already processed. The simplest and most robust way is a tag: select the jobs that lack the tag, process them, and add the tag to each one once it is completely processed.
from shub_workflow.script import BaseScript
class StatsCollector(BaseScript):
CHECKED_TAG = "STATS_CHECKED=True"
def run(self):
for jobdict in self.get_jobs(spider="mysite.com", state=["finished"], lacks_tag=[self.CHECKED_TAG]):
... # read the job stats, save them somewhere
self.add_job_tags(jobdict["key"], tags=[self.CHECKED_TAG])Such a script holds no state of its own. It can be stopped at any moment and started again, by hand or by a
periodic job, and it will continue with the jobs it didn't finish processing. A job whose processing was
interrupted before being tagged is just processed again, so the processing must tolerate that (at-least-once
semantics). This pattern — the state lives in the storage, here the job tags, and not in the script — is the
basis of the self-resuming components described later in this tutorial. The issuer classes implement it out of
the box with their CONSUMED_TAG.
A script works with two project ids: the one where it runs (its own project), and the one where it schedules
and queries jobs (its target project, self.project_id). They are the same by default, but a script running
in one project can operate on another one via --project-id (a numeric id or a scrapinghub.yml entry name).
When the script runs outside ScrapyCloud the target project is taken from --project-id, then from the
PROJECT_ID environment variable, then from the default entry of the project scrapinghub.yml.
Next Chapter: Crawl Managers
Foundations
Building blocks
Designing workflows at scale
- Managing Hubstorage Crawl Frontiers
- Independent Agents and Role Separation
- Feeding Spiders
- Closing the Loop
- The Post-Crawl Data Chain
- Keeping It Running
- Reference Architectures
Operating workflows