OLD | NEW |
(Empty) | |
| 1 // Copyright 2015 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 /* |
| 6 Package cipd implements client side of Chrome Infra Package Deployer. |
| 7 |
| 8 TODO: write more. |
| 9 |
| 10 Binary package file format (in free form representation): |
| 11 <binary package> := <zipped data> |
| 12 <zipped data> := DeterministicZip(<all input files> + <manifest json>) |
| 13 <manifest json> := File{ |
| 14 name: ".cipdpkg/manifest.json", |
| 15 data: JSON({ |
| 16 "FormatVersion": "1", |
| 17 "PackageName": <name of the package> |
| 18 }), |
| 19 } |
| 20 DeterministicZip = zip archive with deterministic ordering of files and stripp
ed timestamps |
| 21 |
| 22 Main package data (<zipped data> above) is deterministic, meaning its content |
| 23 depends only on inputs used to built it (byte to byte): contents and names of |
| 24 all files added to the package (plus 'executable' file mode bit) and a package |
| 25 name (and all other data in the manifest). |
| 26 |
| 27 Binary package data MUST NOT depend on a timestamp, hostname of machine that |
| 28 built it, revision of the source code it was built from, etc. All that |
| 29 information will be distributed as a separate metadata packet associated with |
| 30 the package when it gets uploaded to the server. |
| 31 |
| 32 TODO: expand more when there's server-side package data model (labels |
| 33 and stuff). |
| 34 */ |
| 35 package cipd |
| 36 |
| 37 import ( |
| 38 "bufio" |
| 39 "errors" |
| 40 "fmt" |
| 41 "io" |
| 42 "io/ioutil" |
| 43 "net/http" |
| 44 "os" |
| 45 "path/filepath" |
| 46 "strings" |
| 47 "time" |
| 48 |
| 49 "infra/libs/build" |
| 50 "infra/libs/logging" |
| 51 |
| 52 "infra/tools/cipd/common" |
| 53 "infra/tools/cipd/local" |
| 54 ) |
| 55 |
| 56 // PackageACLChangeAction defines a flavor of PackageACLChange. |
| 57 type PackageACLChangeAction string |
| 58 |
| 59 const ( |
| 60 // GrantRole is used in PackageACLChange to request a role to be granted
. |
| 61 GrantRole PackageACLChangeAction = "GRANT" |
| 62 // RevokeRole is used in PackageACLChange to request a role to be revoke
d. |
| 63 RevokeRole PackageACLChangeAction = "REVOKE" |
| 64 |
| 65 // CASFinalizationTimeout is how long to wait for CAS service to finaliz
e the upload. |
| 66 CASFinalizationTimeout = 1 * time.Minute |
| 67 // TagAttachTimeout is how long to wait for instance to be processed whe
n attaching tags. |
| 68 TagAttachTimeout = 1 * time.Minute |
| 69 |
| 70 // UserAgent is HTTP user agent string for CIPD client. |
| 71 UserAgent = "cipd 1.0" |
| 72 |
| 73 // ProdServiceURL is URL of a backend to connect to if client is build w
ith +release tag. |
| 74 ProdServiceURL = "https://chrome-infra-packages.appspot.com" |
| 75 // TestingServiceURL is URL of a backend to connect to if client is buil
d without +release tag. |
| 76 TestingServiceURL = "https://chrome-infra-packages-dev.appspot.com" |
| 77 ) |
| 78 |
| 79 var ( |
| 80 // ErrFinalizationTimeout is returned if CAS service can not finalize up
load fast enough. |
| 81 ErrFinalizationTimeout = errors.New("Timeout while waiting for CAS servi
ce to finalize the upload") |
| 82 // ErrBadUpload is returned when a package file is uploaded, but servers
asks us to upload it again. |
| 83 ErrBadUpload = errors.New("Package file is uploaded, but servers asks us
to upload it again") |
| 84 // ErrBadUploadSession is returned by UploadToCAS if provided UploadSess
ion is not valid. |
| 85 ErrBadUploadSession = errors.New("UploadURL must be set if UploadSession
ID is used") |
| 86 // ErrUploadSessionDied is returned by UploadToCAS if upload session sud
denly disappeared. |
| 87 ErrUploadSessionDied = errors.New("Upload session is unexpectedly missin
g") |
| 88 // ErrNoUploadSessionID is returned by UploadToCAS if server didn't prov
ide upload session ID. |
| 89 ErrNoUploadSessionID = errors.New("Server didn't provide upload session
ID") |
| 90 // ErrAttachTagsTimeout is returned when service refuses to accept tags
for a long time. |
| 91 ErrAttachTagsTimeout = errors.New("Timeout while attaching tags") |
| 92 // ErrDownloadError is returned by FetchInstance on download errors. |
| 93 ErrDownloadError = errors.New("Failed to download the package file after
multiple attempts") |
| 94 // ErrUploadError is returned by RegisterInstance and UploadToCAS on upl
oad errors. |
| 95 ErrUploadError = errors.New("Failed to upload the package file after mul
tiple attempts") |
| 96 // ErrAccessDenined is returned by calls talking to backend on 401 or 40
3 HTTP errors. |
| 97 ErrAccessDenined = errors.New("Access denied (not authenticated or not e
nough permissions)") |
| 98 // ErrBackendInaccessible is returned by calls talking to backed if it d
oesn't response. |
| 99 ErrBackendInaccessible = errors.New("Request to the backend failed after
multiple attempts") |
| 100 // ErrEnsurePackagesFailed is returned by EnsurePackages if something is
not right. |
| 101 ErrEnsurePackagesFailed = errors.New("Failed to update packages, see the
log") |
| 102 ) |
| 103 |
| 104 // HTTPClientFactory lazily creates http.Client to use for making requests. |
| 105 type HTTPClientFactory func() (*http.Client, error) |
| 106 |
| 107 // Client provides high-level CIPD client interface. |
| 108 type Client struct { |
| 109 // ServiceURL is root URL of the backend service. |
| 110 ServiceURL string |
| 111 // Log is a logger to use for logs, default is logging.DefaultLogger. |
| 112 Log logging.Logger |
| 113 // AuthenticatedClientFactory lazily creates http.Client to use for maki
ng RPC requests. |
| 114 AuthenticatedClientFactory HTTPClientFactory |
| 115 // AnonymousClientFactory lazily creates http.Client to use for making r
equests to storage. |
| 116 AnonymousClientFactory HTTPClientFactory |
| 117 // UserAgent is put into User-Agent HTTP header with each request. |
| 118 UserAgent string |
| 119 |
| 120 // clock provides current time and ability to sleep. |
| 121 clock clock |
| 122 // remote knows how to call backend REST API. |
| 123 remote remote |
| 124 // storage knows how to upload and download raw binaries using signed UR
Ls. |
| 125 storage storage |
| 126 |
| 127 // authClient is a lazily created http.Client to use for authenticated r
equests. |
| 128 authClient *http.Client |
| 129 // anonClient is a lazily created http.Client to use for anonymous reque
sts. |
| 130 anonClient *http.Client |
| 131 } |
| 132 |
| 133 // PackageACL is per package path per role access control list that is a part of |
| 134 // larger overall ACL: ACL for package "a/b/c" is a union of PackageACLs for "a" |
| 135 // "a/b" and "a/b/c". |
| 136 type PackageACL struct { |
| 137 // PackagePath is a package subpath this ACL is defined for. |
| 138 PackagePath string |
| 139 // Role is a role that listed users have, e.g. 'READER', 'WRITER', ... |
| 140 Role string |
| 141 // Principals list users and groups granted the role. |
| 142 Principals []string |
| 143 // ModifiedBy specifies who modified the list the last time. |
| 144 ModifiedBy string |
| 145 // ModifiedTs is a timestamp when the list was modified the last time. |
| 146 ModifiedTs time.Time |
| 147 } |
| 148 |
| 149 // PackageACLChange is a mutation to some package ACL. |
| 150 type PackageACLChange struct { |
| 151 // Action defines what action to perform: GrantRole or RevokeRole. |
| 152 Action PackageACLChangeAction |
| 153 // Role to grant or revoke to a user or group. |
| 154 Role string |
| 155 // Principal is a user or a group to grant or revoke a role for. |
| 156 Principal string |
| 157 } |
| 158 |
| 159 // UploadSession describes open CAS upload session. |
| 160 type UploadSession struct { |
| 161 // ID identifies upload session in the backend. |
| 162 ID string |
| 163 // URL is where to upload the data to. |
| 164 URL string |
| 165 } |
| 166 |
| 167 // NewClient initializes default CIPD client object. Its fields can be further |
| 168 // tweaked after this call. |
| 169 func NewClient() *Client { |
| 170 c := &Client{ |
| 171 ServiceURL: ProdServiceURL, |
| 172 Log: logging.DefaultLogger, |
| 173 AuthenticatedClientFactory: func() (*http.Client, error) { retur
n http.DefaultClient, nil }, |
| 174 AnonymousClientFactory: func() (*http.Client, error) { retur
n http.DefaultClient, nil }, |
| 175 UserAgent: UserAgent, |
| 176 clock: &clockImpl{}, |
| 177 } |
| 178 if !build.ReleaseBuild { |
| 179 c.ServiceURL = TestingServiceURL |
| 180 c.UserAgent += " testing" |
| 181 } |
| 182 c.remote = &remoteImpl{c} |
| 183 c.storage = &storageImpl{c, uploadChunkSize} |
| 184 return c |
| 185 } |
| 186 |
| 187 // doAuthenticatedHTTPRequest is used by remote implementation to make HTTP call
s. |
| 188 func (client *Client) doAuthenticatedHTTPRequest(req *http.Request) (*http.Respo
nse, error) { |
| 189 if client.authClient == nil { |
| 190 var err error |
| 191 client.authClient, err = client.AuthenticatedClientFactory() |
| 192 if err != nil { |
| 193 return nil, err |
| 194 } |
| 195 } |
| 196 return client.authClient.Do(req) |
| 197 } |
| 198 |
| 199 // doAnonymousHTTPRequest is used by storage implementation to make HTTP calls. |
| 200 func (client *Client) doAnonymousHTTPRequest(req *http.Request) (*http.Response,
error) { |
| 201 if client.anonClient == nil { |
| 202 var err error |
| 203 client.anonClient, err = client.AnonymousClientFactory() |
| 204 if err != nil { |
| 205 return nil, err |
| 206 } |
| 207 } |
| 208 return client.anonClient.Do(req) |
| 209 } |
| 210 |
| 211 // FetchACL returns a list of PackageACL objects (parent paths first) that |
| 212 // together define the access control list for the given package subpath. |
| 213 func (client *Client) FetchACL(packagePath string) ([]PackageACL, error) { |
| 214 return client.remote.fetchACL(packagePath) |
| 215 } |
| 216 |
| 217 // ModifyACL applies a set of PackageACLChanges to a package path. |
| 218 func (client *Client) ModifyACL(packagePath string, changes []PackageACLChange)
error { |
| 219 return client.remote.modifyACL(packagePath, changes) |
| 220 } |
| 221 |
| 222 // UploadToCAS uploads package data blob to Content Addressed Store if it is not |
| 223 // there already. The data is addressed by SHA1 hash (also known as package's |
| 224 // InstanceID). It can be used as a standalone function (if 'session' is nil) |
| 225 // or as a part of more high level upload process (in that case upload session |
| 226 // can be opened elsewhere and its properties passed here via 'session' |
| 227 // argument). Returns nil on successful upload. |
| 228 func (client *Client) UploadToCAS(sha1 string, data io.ReadSeeker, session *Uplo
adSession) error { |
| 229 // Open new upload session if an existing is not provided. |
| 230 var err error |
| 231 if session == nil { |
| 232 client.Log.Infof("cipd: uploading %s: initiating", sha1) |
| 233 session, err = client.remote.initiateUpload(sha1) |
| 234 if err != nil { |
| 235 client.Log.Warningf("cipd: can't upload %s - %s", sha1,
err) |
| 236 return err |
| 237 } |
| 238 if session == nil { |
| 239 client.Log.Infof("cipd: %s is already uploaded", sha1) |
| 240 return nil |
| 241 } |
| 242 } else { |
| 243 if session.ID == "" || session.URL == "" { |
| 244 return ErrBadUploadSession |
| 245 } |
| 246 } |
| 247 |
| 248 // Upload the file to CAS storage. |
| 249 err = client.storage.upload(session.URL, data) |
| 250 if err != nil { |
| 251 return err |
| 252 } |
| 253 |
| 254 // Finalize the upload, wait until server verifies and publishes the fil
e. |
| 255 started := client.clock.now() |
| 256 delay := time.Second |
| 257 for { |
| 258 published, err := client.remote.finalizeUpload(session.ID) |
| 259 if err != nil { |
| 260 client.Log.Warningf("cipd: upload of %s failed: %s", sha
1, err) |
| 261 return err |
| 262 } |
| 263 if published { |
| 264 client.Log.Infof("cipd: successfully uploaded %s", sha1) |
| 265 return nil |
| 266 } |
| 267 if client.clock.now().Sub(started) > CASFinalizationTimeout { |
| 268 client.Log.Warningf("cipd: upload of %s failed: timeout"
, sha1) |
| 269 return ErrFinalizationTimeout |
| 270 } |
| 271 client.Log.Infof("cipd: uploading - verifying") |
| 272 client.clock.sleep(delay) |
| 273 if delay < 4*time.Second { |
| 274 delay += 500 * time.Millisecond |
| 275 } |
| 276 } |
| 277 } |
| 278 |
| 279 // RegisterInstance makes the package instance available for clients by |
| 280 // uploading it to the storage and registering it in the package repository. |
| 281 // 'instance' is a package instance to register. |
| 282 func (client *Client) RegisterInstance(instance local.PackageInstance) error { |
| 283 // Attempt to register. |
| 284 client.Log.Infof("cipd: registering %s", instance.Pin()) |
| 285 result, err := client.remote.registerInstance(instance.Pin()) |
| 286 if err != nil { |
| 287 return err |
| 288 } |
| 289 |
| 290 // Asked to upload the package file to CAS first? |
| 291 if result.uploadSession != nil { |
| 292 err = client.UploadToCAS(instance.Pin().InstanceID, instance.Dat
aReader(), result.uploadSession) |
| 293 if err != nil { |
| 294 return err |
| 295 } |
| 296 // Try again, now that file is uploaded. |
| 297 client.Log.Infof("cipd: registering %s", instance.Pin()) |
| 298 result, err = client.remote.registerInstance(instance.Pin()) |
| 299 if err != nil { |
| 300 return err |
| 301 } |
| 302 if result.uploadSession != nil { |
| 303 return ErrBadUpload |
| 304 } |
| 305 } |
| 306 |
| 307 if result.alreadyRegistered { |
| 308 client.Log.Infof( |
| 309 "cipd: instance %s is already registered by %s on %s", |
| 310 instance.Pin(), result.registeredBy, result.registeredTs
) |
| 311 } else { |
| 312 client.Log.Infof("cipd: instance %s was successfully registered"
, instance.Pin()) |
| 313 } |
| 314 |
| 315 return nil |
| 316 } |
| 317 |
| 318 // AttachTagsWhenReady attaches tags to an instance retrying on "not yet process
ed" responses. |
| 319 func (client *Client) AttachTagsWhenReady(pin common.Pin, tags []string) error { |
| 320 err := common.ValidatePin(pin) |
| 321 if err != nil { |
| 322 return err |
| 323 } |
| 324 if len(tags) == 0 { |
| 325 return nil |
| 326 } |
| 327 for _, tag := range tags { |
| 328 client.Log.Infof("cipd: attaching tag %s", tag) |
| 329 } |
| 330 deadline := client.clock.now().Add(TagAttachTimeout) |
| 331 for client.clock.now().Before(deadline) { |
| 332 err = client.remote.attachTags(pin, tags) |
| 333 if err == nil { |
| 334 client.Log.Infof("cipd: all tags attached") |
| 335 return nil |
| 336 } |
| 337 if _, ok := err.(*pendingProcessingError); ok { |
| 338 client.Log.Warningf("cipd: package instance is not ready
yet - %s", err) |
| 339 client.clock.sleep(5 * time.Second) |
| 340 } else { |
| 341 client.Log.Errorf("cipd: failed to attach tags - %s", er
r) |
| 342 return err |
| 343 } |
| 344 } |
| 345 client.Log.Errorf("cipd: failed to attach tags - deadline exceeded") |
| 346 return ErrAttachTagsTimeout |
| 347 } |
| 348 |
| 349 // FetchInstance downloads package instance file from the repository. |
| 350 func (client *Client) FetchInstance(pin common.Pin, output io.WriteSeeker) error
{ |
| 351 err := common.ValidatePin(pin) |
| 352 if err != nil { |
| 353 return err |
| 354 } |
| 355 client.Log.Infof("cipd: resolving fetch URL for %s", pin) |
| 356 fetchInfo, err := client.remote.fetchInstance(pin) |
| 357 if err == nil { |
| 358 err = client.storage.download(fetchInfo.fetchURL, output) |
| 359 } |
| 360 if err != nil { |
| 361 client.Log.Errorf("cipd: failed to fetch %s - %s", pin, err) |
| 362 return err |
| 363 } |
| 364 client.Log.Infof("cipd: successfully fetched %s", pin) |
| 365 return nil |
| 366 } |
| 367 |
| 368 // FetchAndDeployInstance fetches the package instance and deploys it into |
| 369 // a site root. It doesn't check whether the instance is already deployed. |
| 370 func (client *Client) FetchAndDeployInstance(root string, pin common.Pin) error
{ |
| 371 err := common.ValidatePin(pin) |
| 372 if err != nil { |
| 373 return err |
| 374 } |
| 375 |
| 376 // Use temp file for storing package file. Delete it when done. |
| 377 var instance local.PackageInstance |
| 378 tempPath := filepath.Join(root, local.SiteServiceDir, "tmp") |
| 379 err = os.MkdirAll(tempPath, 0777) |
| 380 if err != nil { |
| 381 return err |
| 382 } |
| 383 f, err := ioutil.TempFile(tempPath, pin.InstanceID) |
| 384 if err != nil { |
| 385 return err |
| 386 } |
| 387 defer func() { |
| 388 // Instance takes ownership of the file, no need to close it sep
arately. |
| 389 if instance == nil { |
| 390 f.Close() |
| 391 } |
| 392 os.Remove(f.Name()) |
| 393 }() |
| 394 |
| 395 // Fetch the package data to the provided storage. |
| 396 err = client.FetchInstance(pin, f) |
| 397 if err != nil { |
| 398 return err |
| 399 } |
| 400 |
| 401 // Open the instance, verify the instance ID. |
| 402 instance, err = local.OpenInstance(f, pin.InstanceID) |
| 403 if err != nil { |
| 404 return err |
| 405 } |
| 406 defer instance.Close() |
| 407 |
| 408 // Deploy it. 'defer' will take care of removing the temp file if needed
. |
| 409 _, err = local.DeployInstance(root, instance) |
| 410 return err |
| 411 } |
| 412 |
| 413 // ProcessEnsureFile parses text file that describes what should be installed |
| 414 // by EnsurePackages function. It is a text file where each line has a form: |
| 415 // <package name> <desired version>. Whitespaces are ignored. Lines that start |
| 416 // with '#' are ignored. Version can be specified as instance ID, tag or ref. |
| 417 // Will resolve tags and refs to concrete instance IDs. |
| 418 func (client *Client) ProcessEnsureFile(r io.Reader) ([]common.Pin, error) { |
| 419 // TODO(vadimsh): Resolve tags to instance IDs. |
| 420 |
| 421 lineNo := 0 |
| 422 makeError := func(msg string) error { |
| 423 return fmt.Errorf("Failed to parse desired state (line %d): %s",
lineNo, msg) |
| 424 } |
| 425 |
| 426 out := []common.Pin{} |
| 427 scanner := bufio.NewScanner(r) |
| 428 for scanner.Scan() { |
| 429 lineNo++ |
| 430 |
| 431 // Split each line into words, ignore white space. |
| 432 tokens := []string{} |
| 433 for _, chunk := range strings.Split(scanner.Text(), " ") { |
| 434 chunk = strings.TrimSpace(chunk) |
| 435 if chunk != "" { |
| 436 tokens = append(tokens, chunk) |
| 437 } |
| 438 } |
| 439 |
| 440 // Skip empty lines or lines starting with '#'. |
| 441 if len(tokens) == 0 || tokens[0][0] == '#' { |
| 442 continue |
| 443 } |
| 444 |
| 445 // Each line has a format "<package name> <version>". |
| 446 if len(tokens) != 2 { |
| 447 return nil, makeError("expecting '<package name> <versio
n>' line") |
| 448 } |
| 449 err := common.ValidatePackageName(tokens[0]) |
| 450 if err != nil { |
| 451 return nil, makeError(err.Error()) |
| 452 } |
| 453 err = common.ValidateInstanceID(tokens[1]) |
| 454 if err != nil { |
| 455 return nil, makeError(err.Error()) |
| 456 } |
| 457 |
| 458 // Good enough. |
| 459 out = append(out, common.Pin{PackageName: tokens[0], InstanceID:
tokens[1]}) |
| 460 } |
| 461 |
| 462 return out, nil |
| 463 } |
| 464 |
| 465 // EnsurePackages is high-level interface for installation, removal and updates |
| 466 // of packages inside some installation site root. Given a description of |
| 467 // what packages (and versions) should be installed it will do all necessary |
| 468 // actions to bring the state of the site root to the desired one. |
| 469 func (client *Client) EnsurePackages(root string, pins []common.Pin) error { |
| 470 // Make sure a package is specified only once. |
| 471 seen := make(map[string]bool, len(pins)) |
| 472 for _, p := range pins { |
| 473 if seen[p.PackageName] { |
| 474 return fmt.Errorf("Package %s is specified twice", p.Pac
kageName) |
| 475 } |
| 476 seen[p.PackageName] = true |
| 477 } |
| 478 |
| 479 // Ensure site root is a directory (or missing). |
| 480 root, err := filepath.Abs(filepath.Clean(root)) |
| 481 if err != nil { |
| 482 return err |
| 483 } |
| 484 stat, err := os.Stat(root) |
| 485 if err == nil && !stat.IsDir() { |
| 486 return fmt.Errorf("Path %s is not a directory", root) |
| 487 } |
| 488 if err != nil && !os.IsNotExist(err) { |
| 489 return err |
| 490 } |
| 491 rootExists := (err == nil) |
| 492 |
| 493 // Enumerate existing packages (only if root already exists). |
| 494 existing := []common.Pin{} |
| 495 if rootExists { |
| 496 existing, err = local.FindDeployed(root) |
| 497 if err != nil { |
| 498 client.Log.Errorf("Failed to enumerate installed package
s - %s", err) |
| 499 return err |
| 500 } |
| 501 } |
| 502 |
| 503 // Figure out what needs to be updated and deleted, log it. |
| 504 toDeploy, toDelete := buildActionPlan(pins, existing) |
| 505 if len(toDeploy) == 0 && len(toDelete) == 0 { |
| 506 client.Log.Infof("Everything is up-to-date.") |
| 507 return nil |
| 508 } |
| 509 if len(toDeploy) != 0 { |
| 510 client.Log.Infof("Packages to be installed:") |
| 511 for _, pin := range toDeploy { |
| 512 client.Log.Infof(" %s", pin) |
| 513 } |
| 514 } |
| 515 if len(toDelete) != 0 { |
| 516 client.Log.Infof("Packages to be removed:") |
| 517 for _, pin := range toDelete { |
| 518 client.Log.Infof(" %s", pin) |
| 519 } |
| 520 } |
| 521 |
| 522 // Create the site root directory before installing anything there. |
| 523 if len(toDeploy) != 0 && !rootExists { |
| 524 err = os.MkdirAll(root, 0777) |
| 525 if err != nil { |
| 526 return err |
| 527 } |
| 528 } |
| 529 |
| 530 // Remove all unneeded stuff. |
| 531 fail := false |
| 532 for _, pin := range toDelete { |
| 533 err = local.RemoveDeployed(root, pin.PackageName) |
| 534 if err != nil { |
| 535 client.Log.Errorf("Failed to remove %s - %s", pin.Packag
eName, err) |
| 536 fail = true |
| 537 } |
| 538 } |
| 539 |
| 540 // Install all new stuff. |
| 541 for _, pin := range toDeploy { |
| 542 err = client.FetchAndDeployInstance(root, pin) |
| 543 if err != nil { |
| 544 client.Log.Errorf("Failed to install %s - %s", pin, err) |
| 545 fail = true |
| 546 } |
| 547 } |
| 548 |
| 549 if !fail { |
| 550 client.Log.Infof("All changes applied.") |
| 551 return nil |
| 552 } |
| 553 return ErrEnsurePackagesFailed |
| 554 } |
| 555 |
| 556 //////////////////////////////////////////////////////////////////////////////// |
| 557 // Private structs and interfaces. |
| 558 |
| 559 type clock interface { |
| 560 now() time.Time |
| 561 sleep(time.Duration) |
| 562 } |
| 563 |
| 564 type remote interface { |
| 565 fetchACL(packagePath string) ([]PackageACL, error) |
| 566 modifyACL(packagePath string, changes []PackageACLChange) error |
| 567 |
| 568 initiateUpload(sha1 string) (*UploadSession, error) |
| 569 finalizeUpload(sessionID string) (bool, error) |
| 570 registerInstance(pin common.Pin) (*registerInstanceResponse, error) |
| 571 |
| 572 attachTags(pin common.Pin, tags []string) error |
| 573 fetchInstance(pin common.Pin) (*fetchInstanceResponse, error) |
| 574 } |
| 575 |
| 576 type storage interface { |
| 577 upload(url string, data io.ReadSeeker) error |
| 578 download(url string, output io.WriteSeeker) error |
| 579 } |
| 580 |
| 581 type registerInstanceResponse struct { |
| 582 uploadSession *UploadSession |
| 583 alreadyRegistered bool |
| 584 registeredBy string |
| 585 registeredTs time.Time |
| 586 } |
| 587 |
| 588 type fetchInstanceResponse struct { |
| 589 fetchURL string |
| 590 registeredBy string |
| 591 registeredTs time.Time |
| 592 } |
| 593 |
| 594 // Private stuff. |
| 595 |
| 596 type clockImpl struct{} |
| 597 |
| 598 func (c *clockImpl) now() time.Time { return time.Now() } |
| 599 func (c *clockImpl) sleep(d time.Duration) { time.Sleep(d) } |
| 600 |
| 601 // buildActionPlan is used by EnsurePackages to figure out what to install or re
move. |
| 602 func buildActionPlan(desired, existing []common.Pin) (toDeploy, toDelete []commo
n.Pin) { |
| 603 // Figure out what needs to be installed or updated. |
| 604 existingMap := buildInstanceIDMap(existing) |
| 605 for _, d := range desired { |
| 606 if existingMap[d.PackageName] != d.InstanceID { |
| 607 toDeploy = append(toDeploy, d) |
| 608 } |
| 609 } |
| 610 |
| 611 // Figure out what needs to be removed. |
| 612 desiredMap := buildInstanceIDMap(desired) |
| 613 for _, e := range existing { |
| 614 if desiredMap[e.PackageName] == "" { |
| 615 toDelete = append(toDelete, e) |
| 616 } |
| 617 } |
| 618 |
| 619 return |
| 620 } |
| 621 |
| 622 // buildInstanceIDMap builds mapping {package name -> instance ID}. |
| 623 func buildInstanceIDMap(pins []common.Pin) map[string]string { |
| 624 out := map[string]string{} |
| 625 for _, p := range pins { |
| 626 out[p.PackageName] = p.InstanceID |
| 627 } |
| 628 return out |
| 629 } |
OLD | NEW |