-
-
Notifications
You must be signed in to change notification settings - Fork 28
/
operator.py
1806 lines (1448 loc) · 60 KB
/
operator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
""" btrixjob operator (working for metacontroller) """
import asyncio
import traceback
import os
from pprint import pprint
from typing import Optional, DefaultDict, TYPE_CHECKING
from collections import defaultdict
import json
from uuid import UUID
from fastapi import HTTPException
import yaml
import humanize
from pydantic import BaseModel, Field
from kubernetes.utils import parse_quantity
from redis import asyncio as exceptions
from .utils import (
from_k8s_date,
to_k8s_date,
dt_now,
)
from .k8sapi import K8sAPI
from .models import (
NON_RUNNING_STATES,
RUNNING_STATES,
RUNNING_AND_STARTING_ONLY,
RUNNING_AND_STARTING_STATES,
SUCCESSFUL_STATES,
CrawlFile,
CrawlCompleteIn,
StorageRef,
)
if TYPE_CHECKING:
from .crawlconfigs import CrawlConfigOps
from .crawls import CrawlOps
from .orgs import OrgOps
from .colls import CollectionOps
from .storages import StorageOps
from .webhooks import EventWebhookOps
from .users import UserManager
from .background_jobs import BackgroundJobOps
from redis.asyncio.client import Redis
else:
CrawlConfigOps = CrawlOps = OrgOps = CollectionOps = Redis = object
StorageOps = EventWebhookOps = UserManager = BackgroundJobOps = object
CMAP = "ConfigMap.v1"
PVC = "PersistentVolumeClaim.v1"
POD = "Pod.v1"
BTRIX_API = "btrix.cloud/v1"
CJS = f"CrawlJob.{BTRIX_API}"
METRICS_API = "metrics.k8s.io/v1beta1"
METRICS = f"PodMetrics.{METRICS_API}"
DEFAULT_TTL = 30
REDIS_TTL = 60
# time in seconds before a crawl is deemed 'waiting' instead of 'starting'
STARTING_TIME_SECS = 60
# how often to update execution time seconds
EXEC_TIME_UPDATE_SECS = 60
# ============================================================================
class MCBaseRequest(BaseModel):
"""base metacontroller model, used for customize hook"""
parent: dict
controller: dict
# ============================================================================
class MCSyncData(MCBaseRequest):
"""sync / finalize metacontroller model"""
children: dict
related: dict
finalizing: bool = False
# ============================================================================
class MCDecoratorSyncData(BaseModel):
"""sync for decoratorcontroller model"""
object: dict
controller: dict
attachments: dict
related: dict
finalizing: bool = False
# ============================================================================
class CrawlSpec(BaseModel):
"""spec from k8s CrawlJob object"""
id: str
cid: UUID
oid: UUID
scale: int = 1
storage: StorageRef
started: str
crawler_channel: str
stopping: bool = False
scheduled: bool = False
timeout: int = 0
max_crawl_size: int = 0
# ============================================================================
class PodResourcePercentage(BaseModel):
"""Resource usage percentage ratios"""
memory: float = 0
cpu: float = 0
storage: float = 0
# ============================================================================
class PodResources(BaseModel):
"""Pod Resources"""
memory: int = 0
cpu: float = 0
storage: int = 0
def __init__(self, *a, **kw):
if "memory" in kw:
kw["memory"] = int(parse_quantity(kw["memory"]))
if "cpu" in kw:
kw["cpu"] = float(parse_quantity(kw["cpu"]))
if "storage" in kw:
kw["storage"] = int(parse_quantity(kw["storage"]))
super().__init__(*a, **kw)
# ============================================================================
class PodInfo(BaseModel):
"""Aggregate pod status info held in CrawlJob"""
exitTime: Optional[str] = None
exitCode: Optional[int] = None
isNewExit: Optional[bool] = Field(default=None, exclude=True)
reason: Optional[str] = None
allocated: PodResources = PodResources()
used: PodResources = PodResources()
newCpu: Optional[int] = None
newMemory: Optional[int] = None
def dict(self, *a, **kw):
res = super().dict(*a, **kw)
percent = {
"memory": self.get_percent_memory(),
"cpu": self.get_percent_cpu(),
"storage": self.get_percent_storage(),
}
res["percent"] = percent
return res
def get_percent_memory(self) -> float:
"""compute percent memory used"""
return (
float(self.used.memory) / float(self.allocated.memory)
if self.allocated.memory
else 0
)
def get_percent_cpu(self) -> float:
"""compute percent cpu used"""
return (
float(self.used.cpu) / float(self.allocated.cpu)
if self.allocated.cpu
else 0
)
def get_percent_storage(self) -> float:
"""compute percent storage used"""
return (
float(self.used.storage) / float(self.allocated.storage)
if self.allocated.storage
else 0
)
def should_restart_pod(self):
"""return true if pod should be restarted"""
if self.newMemory and self.newMemory != self.allocated.memory:
return True
if self.newCpu and self.newCpu != self.allocated.cpu:
return True
return False
# ============================================================================
class CrawlStatus(BaseModel):
"""status from k8s CrawlJob object"""
state: str = "starting"
pagesFound: int = 0
pagesDone: int = 0
size: int = 0
# human readable size string
sizeHuman: str = ""
scale: int = 1
filesAdded: int = 0
filesAddedSize: int = 0
finished: Optional[str] = None
stopping: bool = False
stopReason: Optional[str] = None
initRedis: bool = False
crawlerImage: Optional[str] = None
lastActiveTime: str = ""
podStatus: Optional[DefaultDict[str, PodInfo]] = defaultdict(
lambda: PodInfo() # pylint: disable=unnecessary-lambda
)
# placeholder for pydantic 2.0 -- will require this version
# podStatus: Optional[
# DefaultDict[str, Annotated[PodInfo, Field(default_factory=PodInfo)]]
# ]
restartTime: Optional[str]
canceled: bool = False
# updated on pod exits and at regular interval
# Crawl Execution Time -- time all crawler pods have been running
# used to track resource usage and enforce execution minutes limit
crawlExecTime: int = 0
# Elapsed Exec Time -- time crawl has been running in at least one pod
# used for crawl timeouts
elapsedCrawlTime: int = 0
# last exec time update
lastUpdatedTime: str = ""
# any pods exited
anyCrawlPodNewExit: Optional[bool] = Field(default=False, exclude=True)
# don't include in status, use by metacontroller
resync_after: Optional[int] = Field(default=None, exclude=True)
# ============================================================================
# pylint: disable=too-many-statements, too-many-public-methods, too-many-branches, too-many-nested-blocks
# pylint: disable=too-many-instance-attributes, too-many-locals, too-many-lines, too-many-arguments
class BtrixOperator(K8sAPI):
"""BtrixOperator Handler"""
crawl_config_ops: CrawlConfigOps
crawl_ops: CrawlOps
orgs_ops: OrgOps
coll_ops: CollectionOps
storage_ops: StorageOps
event_webhook_ops: EventWebhookOps
background_job_ops: BackgroundJobOps
user_ops: UserManager
def __init__(
self,
crawl_config_ops,
crawl_ops,
org_ops,
coll_ops,
storage_ops,
event_webhook_ops,
background_job_ops,
):
super().__init__()
self.crawl_config_ops = crawl_config_ops
self.crawl_ops = crawl_ops
self.org_ops = org_ops
self.coll_ops = coll_ops
self.storage_ops = storage_ops
self.background_job_ops = background_job_ops
self.event_webhook_ops = event_webhook_ops
self.user_ops = crawl_config_ops.user_manager
self.config_file = "/config/config.yaml"
self.done_key = "crawls-done"
self.fast_retry_secs = int(os.environ.get("FAST_RETRY_SECS") or 0)
self.log_failed_crawl_lines = int(os.environ.get("LOG_FAILED_CRAWL_LINES") or 0)
with open(self.config_file, encoding="utf-8") as fh_config:
self.shared_params = yaml.safe_load(fh_config)
self._has_pod_metrics = False
self.compute_crawler_resources()
self.compute_profile_resources()
# to avoid background tasks being garbage collected
# see: https://stackoverflow.com/a/74059981
self.bg_tasks = set()
def compute_crawler_resources(self):
"""compute memory / cpu resources for crawlers"""
# pylint: disable=invalid-name
p = self.shared_params
num = max(int(p["crawler_browser_instances"]) - 1, 0)
if not p.get("crawler_cpu"):
base = parse_quantity(p["crawler_cpu_base"])
extra = parse_quantity(p["crawler_extra_cpu_per_browser"])
# cpu is a floating value of cpu cores
p["crawler_cpu"] = float(base + num * extra)
print(f"cpu = {base} + {num} * {extra} = {p['crawler_cpu']}")
else:
print(f"cpu = {p['crawler_cpu']}")
if not p.get("crawler_memory"):
base = parse_quantity(p["crawler_memory_base"])
extra = parse_quantity(p["crawler_extra_memory_per_browser"])
# memory is always an int
p["crawler_memory"] = int(base + num * extra)
print(f"memory = {base} + {num} * {extra} = {p['crawler_memory']}")
else:
print(f"memory = {p['crawler_memory']}")
def compute_profile_resources(self):
"""compute memory /cpu resources for a single profile browser"""
p = self.shared_params
# if no profile specific options provided, default to crawler base for one browser
profile_cpu = parse_quantity(
p.get("profile_browser_cpu") or p["crawler_cpu_base"]
)
profile_memory = parse_quantity(
p.get("profile_browser_memory") or p["crawler_memory_base"]
)
p["profile_cpu"] = profile_cpu
p["profile_memory"] = profile_memory
print("profile browser resources")
print(f"cpu = {profile_cpu}")
print(f"memory = {profile_memory}")
async def async_init(self):
"""perform any async init here"""
self._has_pod_metrics = await self.is_pod_metrics_available()
print("Pod Metrics Available:", self._has_pod_metrics)
async def sync_profile_browsers(self, data: MCSyncData):
"""sync profile browsers"""
spec = data.parent.get("spec", {})
expire_time = from_k8s_date(spec.get("expireTime"))
browserid = spec.get("id")
if dt_now() >= expire_time:
self.run_task(self.delete_profile_browser(browserid))
return {"status": {}, "children": []}
params = {}
params.update(self.shared_params)
params["id"] = browserid
params["userid"] = spec.get("userid", "")
oid = spec.get("oid")
storage = StorageRef(spec.get("storageName"))
storage_path = storage.get_storage_extra_path(oid)
storage_secret = storage.get_storage_secret_name(oid)
params["storage_path"] = storage_path
params["storage_secret"] = storage_secret
params["profile_filename"] = spec.get("profileFilename", "")
params["crawler_image"] = spec["crawlerImage"]
params["url"] = spec.get("startUrl", "about:blank")
params["vnc_password"] = spec.get("vncPassword")
children = self.load_from_yaml("profilebrowser.yaml", params)
return {"status": {}, "children": children}
# pylint: disable=too-many-return-statements, invalid-name
async def sync_crawls(self, data: MCSyncData):
"""sync crawls"""
status = CrawlStatus(**data.parent.get("status", {}))
spec = data.parent.get("spec", {})
crawl_id = spec["id"]
cid = spec["cid"]
oid = spec["oid"]
redis_url = self.get_redis_url(crawl_id)
params = {}
params.update(self.shared_params)
params["id"] = crawl_id
params["cid"] = cid
params["userid"] = spec.get("userid", "")
pods = data.children[POD]
# if finalizing, crawl is being deleted
if data.finalizing:
if not status.finished:
# if can't cancel, already finished
if not await self.cancel_crawl(
crawl_id, UUID(cid), UUID(oid), status, data.children[POD]
):
# instead of fetching the state (that was already set)
# return exception to ignore this request, keep previous
# finished state
raise HTTPException(status_code=400, detail="out_of_sync_status")
return await self.finalize_response(
crawl_id,
UUID(oid),
status,
spec,
data.children,
params,
)
# just in case, finished but not deleted, can only get here if
# do_crawl_finished_tasks() doesn't reach the end or taking too long
if status.finished:
print(
f"warn crawl {crawl_id} finished but not deleted, post-finish taking too long?"
)
self.run_task(self.delete_crawl_job(crawl_id))
return await self.finalize_response(
crawl_id,
UUID(oid),
status,
spec,
data.children,
params,
)
try:
configmap = data.related[CMAP][f"crawl-config-{cid}"]["data"]
# pylint: disable=bare-except, broad-except
except:
# fail crawl if config somehow missing, shouldn't generally happen
await self.fail_crawl(crawl_id, UUID(cid), UUID(oid), status, pods)
return self._empty_response(status)
crawl = CrawlSpec(
id=crawl_id,
cid=cid,
oid=oid,
storage=StorageRef(spec["storageName"]),
crawler_channel=spec.get("crawlerChannel"),
scale=spec.get("scale", 1),
started=data.parent["metadata"]["creationTimestamp"],
stopping=spec.get("stopping", False),
timeout=spec.get("timeout") or 0,
max_crawl_size=int(spec.get("maxCrawlSize") or 0),
scheduled=spec.get("manual") != "1",
)
# shouldn't get here, crawl should already be finalizing when canceled
# just in case, handle canceled-but-not-finalizing here
if status.state == "canceled":
await self.delete_crawl_job(crawl.id)
return {"status": status.dict(exclude_none=True), "children": []}
# first, check storage quota, and fail immediately if quota reached
if status.state in ("starting", "skipped_quota_reached"):
# only check on very first run, before any pods/pvcs created
# for now, allow if crawl has already started (pods/pvcs created)
if (
not pods
and not data.children[PVC]
and await self.org_ops.storage_quota_reached(crawl.oid)
):
await self.mark_finished(
crawl.id, crawl.cid, crawl.oid, status, "skipped_quota_reached"
)
return self._empty_response(status)
if status.state in ("starting", "waiting_org_limit"):
if not await self.can_start_new(crawl, data, status):
return self._empty_response(status)
await self.set_state(
"starting", status, crawl.id, allowed_from=["waiting_org_limit"]
)
if len(pods):
for pod_name, pod in pods.items():
self.sync_resources(status, pod_name, pod, data.children)
status = await self.sync_crawl_state(
redis_url,
crawl,
status,
pods,
data.related.get(METRICS, {}),
)
# auto sizing handled here
self.handle_auto_size(crawl.id, status.podStatus)
if status.finished:
return await self.finalize_response(
crawl_id,
UUID(oid),
status,
spec,
data.children,
params,
)
await self.increment_pod_exec_time(
pods, status, crawl.id, crawl.oid, EXEC_TIME_UPDATE_SECS
)
else:
status.scale = crawl.scale
now = dt_now()
await self.crawl_ops.inc_crawl_exec_time(crawl_id, 0, now)
status.lastUpdatedTime = to_k8s_date(now)
children = self._load_redis(params, status, data.children)
storage_path = crawl.storage.get_storage_extra_path(oid)
storage_secret = crawl.storage.get_storage_secret_name(oid)
params["storage_path"] = storage_path
params["storage_secret"] = storage_secret
params["profile_filename"] = configmap["PROFILE_FILENAME"]
# only resolve if not already set
# not automatically updating image for existing crawls
if not status.crawlerImage:
status.crawlerImage = self.crawl_config_ops.get_channel_crawler_image(
crawl.crawler_channel
)
params["crawler_image"] = status.crawlerImage
params["storage_filename"] = configmap["STORE_FILENAME"]
params["restart_time"] = spec.get("restartTime")
params["warc_prefix"] = spec.get("warcPrefix")
params["redis_url"] = redis_url
if spec.get("restartTime") != status.restartTime:
# pylint: disable=invalid-name
status.restartTime = spec.get("restartTime")
status.resync_after = self.fast_retry_secs
params["force_restart"] = True
else:
params["force_restart"] = False
for i in range(0, status.scale):
children.extend(self._load_crawler(params, i, status, data.children))
return {
"status": status.dict(exclude_none=True),
"children": children,
"resyncAfterSeconds": status.resync_after,
}
def _load_redis(self, params, status, children):
name = f"redis-{params['id']}"
has_pod = name in children[POD]
pod_info = status.podStatus[name]
params["name"] = name
params["cpu"] = pod_info.newCpu or params.get("redis_cpu")
params["memory"] = pod_info.newMemory or params.get("redis_memory")
restart = pod_info.should_restart_pod() and has_pod
if restart:
print(f"Restart {name}")
params["init_redis"] = status.initRedis and not restart
return self.load_from_yaml("redis.yaml", params)
def _load_crawler(self, params, i, status, children):
name = f"crawl-{params['id']}-{i}"
has_pod = name in children[POD]
pod_info = status.podStatus[name]
params["name"] = name
params["cpu"] = pod_info.newCpu or params.get("crawler_cpu")
params["memory"] = pod_info.newMemory or params.get("crawler_memory")
params["do_restart"] = (
pod_info.should_restart_pod() or params.get("force_restart")
) and has_pod
if params.get("do_restart"):
print(f"Restart {name}")
params["priorityClassName"] = f"crawl-instance-{i}"
return self.load_from_yaml("crawler.yaml", params)
# pylint: disable=too-many-arguments
async def _resolve_scale(
self,
crawl_id: str,
desired_scale: int,
redis: Redis,
status: CrawlStatus,
pods: dict[str, dict],
):
"""Resolve scale
If desired_scale >= actual scale, just set (also limit by number of pages
found).
If desired scale < actual scale, attempt to shut down each crawl instance
via redis setting. If contiguous instances shutdown (successful exit), lower
scale and clean up previous scale state.
"""
# actual scale (minus redis pod)
actual_scale = len(pods)
if pods.get(f"redis-{crawl_id}"):
actual_scale -= 1
# ensure at least enough pages for the scale
if status.pagesFound and status.pagesFound < desired_scale:
desired_scale = status.pagesFound
# if desired_scale same or scaled up, return desired_scale
if desired_scale >= actual_scale:
return desired_scale
new_scale = actual_scale
for i in range(actual_scale - 1, desired_scale - 1, -1):
name = f"crawl-{crawl_id}-{i}"
pod = pods.get(name)
if pod:
print(f"Attempting scaling down of pod {i}")
await redis.hset(f"{crawl_id}:stopone", name, "1")
# check if this pod can be scaled down
if new_scale == i + 1:
# if status key doesn't exist, this pod never actually ran, so just scale down
if not await redis.hexists(f"{crawl_id}:status", name):
new_scale = i
print(f"Scaled down pod index {i + 1} -> {i}, no previous pod")
elif pod and pod["status"].get("phase") == "Succeeded":
new_scale = i
print(f"Scaled down pod index {i + 1} -> {i}, pod completed")
if new_scale < actual_scale:
for i in range(new_scale, actual_scale):
name = f"crawl-{crawl_id}-{i}"
await redis.hdel(f"{crawl_id}:stopone", name)
await redis.hdel(f"{crawl_id}:status", name)
return new_scale
def sync_resources(self, status, name, pod, children):
"""set crawljob status from current resources"""
resources = status.podStatus[name].allocated
src = pod["spec"]["containers"][0]["resources"]["requests"]
resources.memory = int(parse_quantity(src.get("memory")))
resources.cpu = float(parse_quantity(src.get("cpu")))
pvc = children[PVC].get(name)
if pvc:
src = pvc["spec"]["resources"]["requests"]
resources.storage = int(parse_quantity(src.get("storage")))
async def set_state(self, state, status, crawl_id, allowed_from, **kwargs):
"""set status state and update db, if changed
if allowed_from passed in, can only transition from allowed_from state,
otherwise get current state from db and return
the following state transitions are supported:
from starting to org concurrent crawl limit and back:
- starting -> waiting_org_capacity -> starting
from starting to running:
- starting -> running
from running to complete or complete[:stopReason]:
- running -> complete[:stopReason]
- running -> complete
from starting or running to waiting for capacity (pods pending) and back:
- starting -> waiting_capacity
- running -> waiting_capacity
- waiting_capacity -> running
from any state to canceled or failed:
- not complete[:stopReason] -> canceled
- not complete[:stopReason] -> failed
"""
if not allowed_from or status.state in allowed_from:
res = await self.crawl_ops.update_crawl_state_if_allowed(
crawl_id, state=state, allowed_from=allowed_from, **kwargs
)
if res:
print(f"Setting state: {status.state} -> {state}, {crawl_id}")
status.state = state
return True
# get actual crawl state
actual_state, finished = await self.crawl_ops.get_crawl_state(crawl_id)
if actual_state:
status.state = actual_state
if finished:
status.finished = to_k8s_date(finished)
if actual_state != state:
print(f"state mismatch, actual state {actual_state}, requested {state}")
if not actual_state and state == "canceled":
return True
if status.state != state:
print(
f"Not setting state: {status.state} -> {state}, {crawl_id} not allowed"
)
return False
def load_from_yaml(self, filename, params):
"""load and parse k8s template from yaml file"""
return list(
yaml.safe_load_all(self.templates.env.get_template(filename).render(params))
)
def get_related(self, data: MCBaseRequest):
"""return objects related to crawl pods"""
spec = data.parent.get("spec", {})
cid = spec["cid"]
crawl_id = spec["id"]
oid = spec.get("oid")
related_resources = [
{
"apiVersion": "v1",
"resource": "configmaps",
"labelSelector": {"matchLabels": {"btrix.crawlconfig": cid}},
},
{
"apiVersion": BTRIX_API,
"resource": "crawljobs",
"labelSelector": {"matchLabels": {"btrix.org": oid}},
},
]
if self._has_pod_metrics:
related_resources.append(
{
"apiVersion": METRICS_API,
"resource": "pods",
"labelSelector": {"matchLabels": {"crawl": crawl_id}},
}
)
return {"relatedResources": related_resources}
async def can_start_new(self, crawl: CrawlSpec, data: MCSyncData, status):
"""return true if crawl can start, otherwise set crawl to 'queued' state
until more crawls for org finish"""
max_crawls = await self.org_ops.get_max_concurrent_crawls(crawl.oid)
if not max_crawls:
return True
if len(data.related[CJS]) <= max_crawls:
return True
name = data.parent.get("metadata", {}).get("name")
# def metadata_key(val):
# return val.get("metadata").get("creationTimestamp")
# all_crawljobs = sorted(data.related[CJS].values(), key=metadata_key)
# print(list(data.related[CJS].keys()))
i = 0
for crawl_sorted in data.related[CJS].values():
if crawl_sorted.get("status", {}).get("state") in NON_RUNNING_STATES:
continue
# print(i, crawl_sorted.get("metadata").get("name"))
if crawl_sorted.get("metadata").get("name") == name:
# print("found: ", name, "index", i)
if i < max_crawls:
return True
break
i += 1
await self.set_state(
"waiting_org_limit", status, crawl.id, allowed_from=["starting"]
)
return False
async def cancel_crawl(
self,
crawl_id: str,
cid: UUID,
oid: UUID,
status: CrawlStatus,
pods: dict,
) -> bool:
"""Mark crawl as canceled"""
if not await self.mark_finished(crawl_id, cid, oid, status, "canceled"):
return False
await self.mark_for_cancelation(crawl_id)
if not status.canceled:
for name, pod in pods.items():
pstatus = pod["status"]
role = pod["metadata"]["labels"]["role"]
if role != "crawler":
continue
if "containerStatuses" not in pstatus:
continue
cstatus = pstatus["containerStatuses"][0]
self.handle_terminated_pod(
name, role, status, cstatus["state"].get("terminated")
)
status.canceled = True
return status.canceled
async def fail_crawl(
self,
crawl_id: str,
cid: UUID,
oid: UUID,
status: CrawlStatus,
pods: dict,
stats=None,
) -> bool:
"""Mark crawl as failed, log crawl state and print crawl logs, if possible"""
prev_state = status.state
if not await self.mark_finished(
crawl_id, cid, oid, status, "failed", stats=stats
):
return False
if not self.log_failed_crawl_lines or prev_state == "failed":
return True
pod_names = list(pods.keys())
for name in pod_names:
print(f"============== POD STATUS: {name} ==============")
pprint(pods[name]["status"])
self.run_task(self.print_pod_logs(pod_names, self.log_failed_crawl_lines))
return True
def _empty_response(self, status):
"""done response for removing crawl"""
return {
"status": status.dict(exclude_none=True),
"children": [],
}
async def finalize_response(
self,
crawl_id: str,
oid: UUID,
status: CrawlStatus,
spec: dict,
children: dict,
params: dict,
):
"""ensure crawl id ready for deletion"""
redis_pod = f"redis-{crawl_id}"
new_children = []
finalized = False
pods = children[POD]
if redis_pod in pods:
# if has other pods, keep redis pod until they are removed
if len(pods) > 1:
new_children = self._load_redis(params, status, children)
await self.increment_pod_exec_time(pods, status, crawl_id, oid)
# keep pvs until pods are removed
if new_children:
new_children.extend(list(children[PVC].values()))
if not children[POD] and not children[PVC]:
# keep parent until ttl expired, if any
if status.finished:
ttl = spec.get("ttlSecondsAfterFinished", DEFAULT_TTL)
finished = from_k8s_date(status.finished)
if (dt_now() - finished).total_seconds() > ttl > 0:
print("CrawlJob expired, deleting: " + crawl_id)
finalized = True
else:
finalized = True
return {
"status": status.dict(exclude_none=True),
"children": new_children,
"finalized": finalized,
}
async def _get_redis(self, redis_url: str) -> Optional[Redis]:
"""init redis, ensure connectivity"""
redis = None
try:
redis = await self.get_redis_client(redis_url)
# test connection
await redis.ping()
return redis
# pylint: disable=bare-except
except:
if redis:
await redis.close()
return None
async def sync_crawl_state(
self,
redis_url: str,
crawl: CrawlSpec,
status: CrawlStatus,
pods: dict[str, dict],
metrics: Optional[dict],
):
"""sync crawl state for running crawl"""
# check if at least one crawler pod started running
crawler_running, redis_running, done = self.sync_pod_status(pods, status)
redis = None
try:
if redis_running:
redis = await self._get_redis(redis_url)
await self.add_used_stats(crawl.id, status.podStatus, redis, metrics)
# skip if no newly exited pods
if status.anyCrawlPodNewExit:
await self.log_crashes(crawl.id, status.podStatus, redis)
if not crawler_running or not redis:
# if either crawler is not running or redis is inaccessible
if self.should_mark_waiting(status.state, crawl.started):
# mark as waiting (if already running)
await self.set_state(
"waiting_capacity",
status,
crawl.id,
allowed_from=RUNNING_AND_STARTING_ONLY,
)
if not crawler_running and redis:
# if crawler running, but no redis, stop redis instance until crawler
# is running
if status.lastActiveTime and (
(
dt_now() - from_k8s_date(status.lastActiveTime)
).total_seconds()
> REDIS_TTL
):
print(
f"Pausing redis, no running crawler pods for >{REDIS_TTL} secs"
)
status.initRedis = False
elif crawler_running and not redis:
# if crawler is running, but no redis, init redis
status.initRedis = True
status.lastActiveTime = to_k8s_date(dt_now())
# if no crawler / no redis, resync after N seconds
status.resync_after = self.fast_retry_secs
return status
# set state to running (if not already)